1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
19 //config: bool "ash (77 kb)"
21 //config: depends on !NOMMU
23 //config: The most complete and most pedantically correct shell included with
24 //config: busybox. This shell is actually a derivative of the Debian 'dash'
25 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
26 //config: (written by Kenneth Almquist) from NetBSD.
28 //config:# ash options
29 //config:# note: Don't remove !NOMMU part in the next line; it would break
30 //config:# menuconfig's indenting.
31 //config:if !NOMMU && (ASH || SH_IS_ASH || BASH_IS_ASH)
33 //config:config ASH_OPTIMIZE_FOR_SIZE
34 //config: bool "Optimize for size instead of speed"
36 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
38 //config:config ASH_INTERNAL_GLOB
39 //config: bool "Use internal glob() implementation"
40 //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
41 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
43 //config: Do not use glob() function from libc, use internal implementation.
44 //config: Use this if you are getting "glob.h: No such file or directory"
45 //config: or similar build errors.
46 //config: Note that as of now (2017-01), uclibc and musl glob() both have bugs
47 //config: which would break ash if you select N here.
49 //config:config ASH_BASH_COMPAT
50 //config: bool "bash-compatible extensions"
52 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
54 //config:config ASH_JOB_CONTROL
55 //config: bool "Job control"
57 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
59 //config:config ASH_ALIAS
60 //config: bool "Alias support"
62 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
64 //config:config ASH_RANDOM_SUPPORT
65 //config: bool "Pseudorandom generator and $RANDOM variable"
67 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
69 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
70 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
71 //config: You can reset the generator by using a specified start value.
72 //config: After "unset RANDOM" the generator will switch off and this
73 //config: variable will no longer have special treatment.
75 //config:config ASH_EXPAND_PRMT
76 //config: bool "Expand prompt string"
78 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
80 //config: $PS# may contain volatile content, such as backquote commands.
81 //config: This option recreates the prompt string from the environment
82 //config: variable each time it is displayed.
84 //config:config ASH_IDLE_TIMEOUT
85 //config: bool "Idle timeout variable $TMOUT"
87 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
89 //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
91 //config:config ASH_MAIL
92 //config: bool "Check for new mail in interactive shell"
94 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
96 //config: Enable "check for new mail" function:
97 //config: if set, $MAIL file and $MAILPATH list of files
98 //config: are checked for mtime changes, and "you have mail"
99 //config: message is printed if change is detected.
101 //config:config ASH_ECHO
102 //config: bool "echo builtin"
104 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
106 //config:config ASH_PRINTF
107 //config: bool "printf builtin"
109 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
111 //config:config ASH_TEST
112 //config: bool "test builtin"
114 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
116 //config:config ASH_HELP
117 //config: bool "help builtin"
119 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
121 //config:config ASH_GETOPTS
122 //config: bool "getopts builtin"
124 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
126 //config:config ASH_CMDCMD
127 //config: bool "command builtin"
129 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
131 //config: Enable support for the 'command' builtin, which allows
132 //config: you to run the specified command or builtin,
133 //config: even when there is a function with the same name.
135 //config:endif # ash options
137 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
138 // APPLET_ODDNAME:name main location suid_type help
139 //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
140 //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
142 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
143 //kbuild:lib-$(CONFIG_SH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
144 //kbuild:lib-$(CONFIG_BASH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
145 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
148 * DEBUG=1 to compile in debugging ('set -o debug' turns on)
149 * DEBUG=2 to compile in and turn on debugging.
150 * When debugging is on ("set -o debug" was executed, or DEBUG=2),
151 * debugging info is written to ./trace, quit signal generates core dump.
154 /* Tweak debug output verbosity here */
158 #define DEBUG_INTONOFF 0
162 #define JOBS ENABLE_ASH_JOB_CONTROL
166 #include <sys/times.h>
167 #include <sys/utsname.h> /* for setting $HOSTNAME */
168 #include "busybox.h" /* for applet_names */
170 /* So far, all bash compat is controlled by one config option */
171 /* Separate defines document which part of code implements what */
172 /* function keyword */
173 #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
174 #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
176 #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
177 #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
179 #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
180 #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
181 #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
182 #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
183 #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
184 #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
186 #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
187 #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
188 #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
189 #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
190 #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
191 #define BASH_XTRACEFD ENABLE_ASH_BASH_COMPAT
193 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
194 /* Bionic at least up to version 24 has no glob() */
195 # undef ENABLE_ASH_INTERNAL_GLOB
196 # define ENABLE_ASH_INTERNAL_GLOB 1
199 #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
200 # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
201 # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
202 # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
203 # error glob() should unbackslash them and match. uClibc does not unbackslash,
204 # error fails to match dirname, subsequently not expanding <pattern> in it.
206 // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
207 // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
210 #if !ENABLE_ASH_INTERNAL_GLOB
215 #include "shell_common.h"
216 #if ENABLE_FEATURE_SH_MATH
219 typedef long arith_t;
220 # define ARITH_FMT "%ld"
222 #if ENABLE_ASH_RANDOM_SUPPORT
225 # define CLEAR_RANDOM_T(rnd) ((void)0)
228 #include "NUM_APPLETS.h"
230 /* STANDALONE does not make sense, and won't compile */
231 # undef CONFIG_FEATURE_SH_STANDALONE
232 # undef ENABLE_FEATURE_SH_STANDALONE
233 # undef IF_FEATURE_SH_STANDALONE
234 # undef IF_NOT_FEATURE_SH_STANDALONE
235 # define ENABLE_FEATURE_SH_STANDALONE 0
236 # define IF_FEATURE_SH_STANDALONE(...)
237 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
241 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
245 # error "Do not even bother, ash will not run on NOMMU machine"
249 /* ============ Hash table sizes. Configurable. */
253 #define CMDTABLESIZE 31 /* should be prime */
256 /* ============ Shell options */
258 static const char *const optletters_optnames[] = {
282 #define optletters(n) optletters_optnames[n][0]
283 #define optnames(n) (optletters_optnames[n] + 1)
285 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
288 /* ============ Misc data */
290 #define msg_illnum "Illegal number: %s"
293 * We enclose jmp_buf in a structure so that we can declare pointers to
294 * jump locations. The global variable handler contains the location to
295 * jump to when an exception occurs, and the global variable exception_type
296 * contains a code identifying the exception. To implement nested
297 * exception handlers, the user should save the value of handler on entry
298 * to an inner scope, set handler to point to a jmploc structure for the
299 * inner scope, and restore handler on exit from the scope.
305 struct globals_misc {
306 uint8_t exitstatus; /* exit status of last command */
307 uint8_t back_exitstatus;/* exit status of backquoted command */
308 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
309 int rootpid; /* pid of main shell */
310 /* shell level: 0 for the main shell, 1 for its children, and so on */
312 #define rootshell (!shlvl)
313 char *minusc; /* argument to -c option */
315 char *curdir; // = nullstr; /* current working directory */
316 char *physdir; // = nullstr; /* physical working directory */
318 char *arg0; /* value of $0 */
320 struct jmploc *exception_handler;
322 volatile int suppress_int; /* counter */
323 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
324 volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
325 volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
326 smallint exception_type; /* kind of exception (0..5) */
328 #define EXINT 0 /* SIGINT received */
329 #define EXERROR 1 /* a generic error */
330 #define EXEXIT 4 /* exit the shell */
332 char nullstr[1]; /* zero length string */
335 #define eflag optlist[0]
336 #define fflag optlist[1]
337 #define Iflag optlist[2]
338 #define iflag optlist[3]
339 #define mflag optlist[4]
340 #define nflag optlist[5]
341 #define sflag optlist[6]
342 #define xflag optlist[7]
343 #define vflag optlist[8]
344 #define Cflag optlist[9]
345 #define aflag optlist[10]
346 #define bflag optlist[11]
347 #define uflag optlist[12]
348 #define viflag optlist[13]
350 # define pipefail optlist[14]
355 # define nolog optlist[14 + BASH_PIPEFAIL]
356 # define debug optlist[15 + BASH_PIPEFAIL]
359 /* trap handler commands */
361 * Sigmode records the current value of the signal handlers for the various
362 * modes. A value of zero means that the current handler is not known.
363 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
365 char sigmode[NSIG - 1];
366 #define S_DFL 1 /* default signal handling (SIG_DFL) */
367 #define S_CATCH 2 /* signal is caught */
368 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
369 #define S_HARD_IGN 4 /* signal is ignored permanently (it was SIG_IGN on entry to shell) */
371 /* indicates specified signal received */
372 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
373 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
375 char **trap_ptr; /* used only by "trap hack" */
377 /* Rarely referenced stuff */
378 #if ENABLE_ASH_RANDOM_SUPPORT
381 pid_t backgndpid; /* pid of last background process */
383 extern struct globals_misc *const ash_ptr_to_globals_misc;
384 #define G_misc (*ash_ptr_to_globals_misc)
385 #define exitstatus (G_misc.exitstatus )
386 #define back_exitstatus (G_misc.back_exitstatus )
387 #define job_warning (G_misc.job_warning)
388 #define rootpid (G_misc.rootpid )
389 #define shlvl (G_misc.shlvl )
390 #define minusc (G_misc.minusc )
391 #define curdir (G_misc.curdir )
392 #define physdir (G_misc.physdir )
393 #define arg0 (G_misc.arg0 )
394 #define exception_handler (G_misc.exception_handler)
395 #define exception_type (G_misc.exception_type )
396 #define suppress_int (G_misc.suppress_int )
397 #define pending_int (G_misc.pending_int )
398 #define got_sigchld (G_misc.got_sigchld )
399 #define pending_sig (G_misc.pending_sig )
400 #define nullstr (G_misc.nullstr )
401 #define optlist (G_misc.optlist )
402 #define sigmode (G_misc.sigmode )
403 #define gotsig (G_misc.gotsig )
404 #define may_have_traps (G_misc.may_have_traps )
405 #define trap (G_misc.trap )
406 #define trap_ptr (G_misc.trap_ptr )
407 #define random_gen (G_misc.random_gen )
408 #define backgndpid (G_misc.backgndpid )
409 #define INIT_G_misc() do { \
410 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
418 /* ============ DEBUG */
420 static void trace_printf(const char *fmt, ...);
421 static void trace_vprintf(const char *fmt, va_list va);
422 # define TRACE(param) trace_printf param
423 # define TRACEV(param) trace_vprintf param
424 # define close(fd) do { \
426 if (close(dfd) < 0) \
427 bb_error_msg("bug on %d: closing %d(0x%x)", \
428 __LINE__, dfd, dfd); \
431 # define TRACE(param)
432 # define TRACEV(param)
436 /* ============ Utility functions */
437 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
438 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
441 isdigit_str9(const char *str)
443 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
444 while (--maxlen && isdigit(*str))
446 return (*str == '\0');
450 var_end(const char *var)
459 /* ============ Interrupts / exceptions */
461 static void exitshell(void) NORETURN;
464 * These macros allow the user to suspend the handling of interrupt signals
465 * over a period of time. This is similar to SIGHOLD or to sigblock, but
466 * much more efficient and portable. (But hacking the kernel is so much
467 * more fun than worrying about efficiency and portability. :-))
470 # define INT_OFF do { \
471 TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
476 # define INT_OFF do { \
483 * Called to raise an exception. Since C doesn't include exceptions, we
484 * just do a longjmp to the exception handler. The type of exception is
485 * stored in the global variable "exception_type".
487 static void raise_exception(int) NORETURN;
489 raise_exception(int e)
492 if (exception_handler == NULL)
497 longjmp(exception_handler->loc, 1);
500 #define raise_exception(e) do { \
501 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
502 raise_exception(e); \
507 * Called when a SIGINT is received. (If the user specifies
508 * that SIGINT is to be trapped or ignored using the trap builtin, then
509 * this routine is not called.) Suppressint is nonzero when interrupts
510 * are held using the INT_OFF macro. (The test for iflag is just
511 * defensive programming.)
513 static void raise_interrupt(void) NORETURN;
515 raise_interrupt(void)
518 /* Signal is not automatically unmasked after it is raised,
519 * do it ourself - unmask all signals */
520 sigprocmask_allsigs(SIG_UNBLOCK);
521 /* pending_sig = 0; - now done in signal_handler() */
523 if (!(rootshell && iflag)) {
524 /* Kill ourself with SIGINT */
525 signal(SIGINT, SIG_DFL);
528 /* bash: ^C even on empty command line sets $? */
529 exitstatus = SIGINT + 128;
530 raise_exception(EXINT);
534 #define raise_interrupt() do { \
535 TRACE(("raising interrupt on line %d\n", __LINE__)); \
540 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
544 if (--suppress_int == 0 && pending_int) {
549 # define INT_ON do { \
550 TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
554 # define INT_ON int_on()
556 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
564 #define FORCE_INT_ON force_int_on()
566 #define SAVE_INT(v) ((v) = suppress_int)
568 #define RESTORE_INT(v) do { \
570 suppress_int = (v); \
571 if (suppress_int == 0 && pending_int) \
576 /* ============ Stdout/stderr output */
579 outstr(const char *p, FILE *file)
587 flush_stdout_stderr(void)
594 /* Was called outcslow(c,FILE*), but c was always '\n' */
596 newline_and_flush(FILE *dest)
604 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
606 out1fmt(const char *fmt, ...)
613 r = vprintf(fmt, ap);
619 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
621 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
628 ret = vsnprintf(outbuf, length, fmt, ap);
635 out1str(const char *p)
641 out2str(const char *p)
644 flush_stdout_stderr();
648 /* ============ Parser structures */
650 /* control characters in argument strings */
651 #define CTL_FIRST CTLESC
652 #define CTLESC ((unsigned char)'\201') /* escape next character */
653 #define CTLVAR ((unsigned char)'\202') /* variable defn */
654 #define CTLENDVAR ((unsigned char)'\203')
655 #define CTLBACKQ ((unsigned char)'\204')
656 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
657 #define CTLENDARI ((unsigned char)'\207')
658 #define CTLQUOTEMARK ((unsigned char)'\210')
659 #define CTL_LAST CTLQUOTEMARK
661 /* variable substitution byte (follows CTLVAR) */
662 #define VSTYPE 0x0f /* type of variable substitution */
663 #define VSNUL 0x10 /* colon--treat the empty string as unset */
665 /* values of VSTYPE field */
666 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
667 #define VSMINUS 0x2 /* ${var-text} */
668 #define VSPLUS 0x3 /* ${var+text} */
669 #define VSQUESTION 0x4 /* ${var?message} */
670 #define VSASSIGN 0x5 /* ${var=text} */
671 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
672 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
673 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
674 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
675 #define VSLENGTH 0xa /* ${#var} */
677 #define VSSUBSTR 0xc /* ${var:position:length} */
679 #if BASH_PATTERN_SUBST
680 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
681 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
684 static const char dolatstr[] ALIGN1 = {
685 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
687 #define DOLATSTRLEN 6
706 #if BASH_REDIR_OUTPUT
723 smallint type; /* Nxxxx */
726 union node *redirect;
731 smallint pipe_backgnd;
732 struct nodelist *cmdlist;
738 union node *redirect;
751 union node *elsepart;
778 struct nodelist *backquote;
781 /* nfile and ndup layout must match!
782 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
783 * that it is actually NTO2 (>&file), and change its type.
800 char *_unused_expfname;
819 struct nredir nredir;
820 struct nbinary nbinary;
824 struct nclist nclist;
833 * NODE_EOF is returned by parsecmd when it encounters an end of file.
834 * It must be distinct from NULL.
836 #define NODE_EOF ((union node *) -1L)
839 struct nodelist *next;
852 freefunc(struct funcnode *f)
854 if (f && --f->count < 0)
859 /* ============ Debugging output */
863 static FILE *tracefile;
866 trace_printf(const char *fmt, ...)
873 fprintf(tracefile, "%u ", (int) time(NULL));
875 fprintf(tracefile, "[%u] ", (int) getpid());
877 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
879 vfprintf(tracefile, fmt, va);
884 trace_vprintf(const char *fmt, va_list va)
888 vfprintf(tracefile, fmt, va);
889 fprintf(tracefile, "\n");
893 trace_puts(const char *s)
901 trace_puts_quoted(char *s)
908 putc('"', tracefile);
909 for (p = s; *p; p++) {
910 switch ((unsigned char)*p) {
911 case '\n': c = 'n'; goto backslash;
912 case '\t': c = 't'; goto backslash;
913 case '\r': c = 'r'; goto backslash;
914 case '\"': c = '\"'; goto backslash;
915 case '\\': c = '\\'; goto backslash;
916 case CTLESC: c = 'e'; goto backslash;
917 case CTLVAR: c = 'v'; goto backslash;
918 case CTLBACKQ: c = 'q'; goto backslash;
920 putc('\\', tracefile);
924 if (*p >= ' ' && *p <= '~')
927 putc('\\', tracefile);
928 putc((*p >> 6) & 03, tracefile);
929 putc((*p >> 3) & 07, tracefile);
930 putc(*p & 07, tracefile);
935 putc('"', tracefile);
939 trace_puts_args(char **ap)
946 trace_puts_quoted(*ap);
948 putc('\n', tracefile);
951 putc(' ', tracefile);
966 /* leave open because libedit might be using it */
969 strcpy(s, "./trace");
971 if (!freopen(s, "a", tracefile)) {
972 fprintf(stderr, "Can't re-open %s\n", s);
977 tracefile = fopen(s, "a");
978 if (tracefile == NULL) {
979 fprintf(stderr, "Can't open %s\n", s);
985 flags = fcntl(fileno(tracefile), F_GETFL);
987 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
989 setlinebuf(tracefile);
990 fputs("\nTracing started.\n", tracefile);
994 indent(int amount, char *pfx, FILE *fp)
998 for (i = 0; i < amount; i++) {
999 if (pfx && i == amount - 1)
1005 /* little circular references here... */
1006 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
1009 sharg(union node *arg, FILE *fp)
1012 struct nodelist *bqlist;
1013 unsigned char subtype;
1015 if (arg->type != NARG) {
1016 out1fmt("<node type %d>\n", arg->type);
1019 bqlist = arg->narg.backquote;
1020 for (p = arg->narg.text; *p; p++) {
1021 switch ((unsigned char)*p) {
1030 if (subtype == VSLENGTH)
1038 if (subtype & VSNUL)
1041 switch (subtype & VSTYPE) {
1067 case VSTRIMRIGHTMAX:
1074 out1fmt("<subtype %d>", subtype);
1083 shtree(bqlist->n, -1, NULL, fp);
1094 shcmd(union node *cmd, FILE *fp)
1102 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1108 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1112 switch (np->nfile.type) {
1113 case NTO: s = ">>"+1; dftfd = 1; break;
1114 case NCLOBBER: s = ">|"; dftfd = 1; break;
1115 case NAPPEND: s = ">>"; dftfd = 1; break;
1116 #if BASH_REDIR_OUTPUT
1119 case NTOFD: s = ">&"; dftfd = 1; break;
1120 case NFROM: s = "<"; break;
1121 case NFROMFD: s = "<&"; break;
1122 case NFROMTO: s = "<>"; break;
1123 default: s = "*error*"; break;
1125 if (np->nfile.fd != dftfd)
1126 fprintf(fp, "%d", np->nfile.fd);
1128 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1129 fprintf(fp, "%d", np->ndup.dupfd);
1131 sharg(np->nfile.fname, fp);
1138 shtree(union node *n, int ind, char *pfx, FILE *fp)
1140 struct nodelist *lp;
1146 indent(ind, pfx, fp);
1148 if (n == NODE_EOF) {
1163 shtree(n->nbinary.ch1, ind, NULL, fp);
1166 shtree(n->nbinary.ch2, ind, NULL, fp);
1174 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1175 shtree(lp->n, 0, NULL, fp);
1179 if (n->npipe.pipe_backgnd)
1185 fprintf(fp, "<node type %d>", n->type);
1193 showtree(union node *n)
1195 trace_puts("showtree called\n");
1196 shtree(n, 1, NULL, stderr);
1202 /* ============ Parser data */
1205 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1208 struct strlist *next;
1215 struct strpush *prev; /* preceding string on stack */
1217 int prev_left_in_line;
1218 #if ENABLE_ASH_ALIAS
1219 struct alias *ap; /* if push was associated with an alias */
1221 char *string; /* remember the string since it may change */
1223 /* Remember last two characters for pungetc. */
1226 /* Number of outstanding calls to pungetc. */
1231 struct parsefile *prev; /* preceding file on stack */
1232 int linno; /* current line */
1233 int pf_fd; /* file descriptor (or -1 if string) */
1234 int left_in_line; /* number of chars left in this line */
1235 int left_in_buffer; /* number of chars left in this buffer past the line */
1236 char *next_to_pgetc; /* next char in buffer */
1237 char *buf; /* input buffer */
1238 struct strpush *strpush; /* for pushing strings at this level */
1239 struct strpush basestrpush; /* so pushing one is fast */
1241 /* Remember last two characters for pungetc. */
1244 /* Number of outstanding calls to pungetc. */
1248 static struct parsefile basepf; /* top level input file */
1249 static struct parsefile *g_parsefile = &basepf; /* current input file */
1250 static int startlinno; /* line # where last token started */
1251 static char *commandname; /* currently executing command */
1254 /* ============ Message printing */
1257 ash_vmsg(const char *msg, va_list ap)
1259 fprintf(stderr, "%s: ", arg0);
1261 if (strcmp(arg0, commandname))
1262 fprintf(stderr, "%s: ", commandname);
1263 if (!iflag || g_parsefile->pf_fd > 0)
1264 fprintf(stderr, "line %d: ", startlinno);
1266 vfprintf(stderr, msg, ap);
1267 newline_and_flush(stderr);
1271 * Exverror is called to raise the error exception. If the second argument
1272 * is not NULL then error prints an error message using printf style
1273 * formatting. It then raises the error exception.
1275 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1277 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1281 TRACE(("ash_vmsg_and_raise(%d):", cond));
1284 TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
1289 flush_stdout_stderr();
1290 raise_exception(cond);
1294 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1296 ash_msg_and_raise_error(const char *msg, ...)
1303 ash_vmsg_and_raise(EXERROR, msg, ap);
1309 * Use '%m' to append error string on platforms that support it, '%s' and
1310 * strerror() on those that don't.
1312 * 'fmt' must be a string literal.
1314 #ifdef HAVE_PRINTF_PERCENTM
1315 #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": %m", ##__VA_ARGS__)
1317 #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": %s", ##__VA_ARGS__, strerror(errno))
1320 static void raise_error_syntax(const char *) NORETURN;
1322 raise_error_syntax(const char *msg)
1324 ash_msg_and_raise_error("syntax error: %s", msg);
1328 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1330 ash_msg_and_raise(int cond, const char *msg, ...)
1335 ash_vmsg_and_raise(cond, msg, ap);
1341 * error/warning routines for external builtins
1344 ash_msg(const char *fmt, ...)
1354 * Return a string describing an error. The returned string may be a
1355 * pointer to a static buffer that will be overwritten on the next call.
1356 * Action describes the operation that got the error.
1359 errmsg(int e, const char *em)
1361 if (e == ENOENT || e == ENOTDIR) {
1368 /* ============ Memory allocation */
1371 /* I consider these wrappers nearly useless:
1372 * ok, they return you to nearest exception handler, but
1373 * how much memory do you leak in the process, making
1374 * memory starvation worse?
1377 ckrealloc(void * p, size_t nbytes)
1379 p = realloc(p, nbytes);
1381 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1386 ckmalloc(size_t nbytes)
1388 return ckrealloc(NULL, nbytes);
1392 ckzalloc(size_t nbytes)
1394 return memset(ckmalloc(nbytes), 0, nbytes);
1398 ckstrdup(const char *s)
1400 char *p = strdup(s);
1402 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1406 /* Using bbox equivalents. They exit if out of memory */
1407 # define ckrealloc xrealloc
1408 # define ckmalloc xmalloc
1409 # define ckzalloc xzalloc
1410 # define ckstrdup xstrdup
1414 * It appears that grabstackstr() will barf with such alignments
1415 * because stalloc() will return a string allocated in a new stackblock.
1417 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1419 /* Most machines require the value returned from malloc to be aligned
1420 * in some way. The following macro will get this right
1421 * on many machines. */
1422 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1423 /* Minimum size of a block */
1424 MINSIZE = SHELL_ALIGN(504),
1427 struct stack_block {
1428 struct stack_block *prev;
1429 char space[MINSIZE];
1433 struct stack_block *stackp;
1439 struct globals_memstack {
1440 struct stack_block *g_stackp; // = &stackbase;
1441 char *g_stacknxt; // = stackbase.space;
1442 char *sstrend; // = stackbase.space + MINSIZE;
1443 size_t g_stacknleft; // = MINSIZE;
1444 struct stack_block stackbase;
1446 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1447 #define G_memstack (*ash_ptr_to_globals_memstack)
1448 #define g_stackp (G_memstack.g_stackp )
1449 #define g_stacknxt (G_memstack.g_stacknxt )
1450 #define sstrend (G_memstack.sstrend )
1451 #define g_stacknleft (G_memstack.g_stacknleft)
1452 #define stackbase (G_memstack.stackbase )
1453 #define INIT_G_memstack() do { \
1454 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1456 g_stackp = &stackbase; \
1457 g_stacknxt = stackbase.space; \
1458 g_stacknleft = MINSIZE; \
1459 sstrend = stackbase.space + MINSIZE; \
1463 #define stackblock() ((void *)g_stacknxt)
1464 #define stackblocksize() g_stacknleft
1467 * Parse trees for commands are allocated in lifo order, so we use a stack
1468 * to make this more efficient, and also to avoid all sorts of exception
1469 * handling code to handle interrupts in the middle of a parse.
1471 * The size 504 was chosen because the Ultrix malloc handles that size
1475 stalloc(size_t nbytes)
1480 aligned = SHELL_ALIGN(nbytes);
1481 if (aligned > g_stacknleft) {
1484 struct stack_block *sp;
1486 blocksize = aligned;
1487 if (blocksize < MINSIZE)
1488 blocksize = MINSIZE;
1489 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1490 if (len < blocksize)
1491 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1494 sp->prev = g_stackp;
1495 g_stacknxt = sp->space;
1496 g_stacknleft = blocksize;
1497 sstrend = g_stacknxt + blocksize;
1502 g_stacknxt += aligned;
1503 g_stacknleft -= aligned;
1508 stzalloc(size_t nbytes)
1510 return memset(stalloc(nbytes), 0, nbytes);
1517 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1518 write(STDERR_FILENO, "stunalloc\n", 10);
1522 g_stacknleft += g_stacknxt - (char *)p;
1527 * Like strdup but works with the ash stack.
1530 sstrdup(const char *p)
1532 size_t len = strlen(p) + 1;
1533 return memcpy(stalloc(len), p, len);
1537 grabstackblock(size_t len)
1543 pushstackmark(struct stackmark *mark, size_t len)
1545 mark->stackp = g_stackp;
1546 mark->stacknxt = g_stacknxt;
1547 mark->stacknleft = g_stacknleft;
1548 grabstackblock(len);
1552 setstackmark(struct stackmark *mark)
1554 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1558 popstackmark(struct stackmark *mark)
1560 struct stack_block *sp;
1566 while (g_stackp != mark->stackp) {
1568 g_stackp = sp->prev;
1571 g_stacknxt = mark->stacknxt;
1572 g_stacknleft = mark->stacknleft;
1573 sstrend = mark->stacknxt + mark->stacknleft;
1578 * When the parser reads in a string, it wants to stick the string on the
1579 * stack and only adjust the stack pointer when it knows how big the
1580 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1581 * of space on top of the stack and stackblocklen returns the length of
1582 * this block. Growstackblock will grow this space by at least one byte,
1583 * possibly moving it (like realloc). Grabstackblock actually allocates the
1584 * part of the block that has been used.
1587 growstackblock(void)
1591 newlen = g_stacknleft * 2;
1592 if (newlen < g_stacknleft)
1593 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1597 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1598 struct stack_block *sp;
1599 struct stack_block *prevstackp;
1604 prevstackp = sp->prev;
1605 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1606 sp = ckrealloc(sp, grosslen);
1607 sp->prev = prevstackp;
1609 g_stacknxt = sp->space;
1610 g_stacknleft = newlen;
1611 sstrend = sp->space + newlen;
1614 char *oldspace = g_stacknxt;
1615 size_t oldlen = g_stacknleft;
1616 char *p = stalloc(newlen);
1618 /* free the space we just allocated */
1619 g_stacknxt = memcpy(p, oldspace, oldlen);
1620 g_stacknleft += newlen;
1625 * The following routines are somewhat easier to use than the above.
1626 * The user declares a variable of type STACKSTR, which may be declared
1627 * to be a register. The macro STARTSTACKSTR initializes things. Then
1628 * the user uses the macro STPUTC to add characters to the string. In
1629 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1630 * grown as necessary. When the user is done, she can just leave the
1631 * string there and refer to it using stackblock(). Or she can allocate
1632 * the space for it using grabstackstr(). If it is necessary to allow
1633 * someone else to use the stack temporarily and then continue to grow
1634 * the string, the user should use grabstack to allocate the space, and
1635 * then call ungrabstr(p) to return to the previous mode of operation.
1637 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1638 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1639 * is space for at least one character.
1644 size_t len = stackblocksize();
1646 return (char *)stackblock() + len;
1650 * Called from CHECKSTRSPACE.
1653 makestrspace(size_t newlen, char *p)
1655 size_t len = p - g_stacknxt;
1661 size = stackblocksize();
1663 if (nleft >= newlen)
1667 return (char *)stackblock() + len;
1671 stack_nputstr(const char *s, size_t n, char *p)
1673 p = makestrspace(n, p);
1674 p = (char *)mempcpy(p, s, n);
1679 stack_putstr(const char *s, char *p)
1681 return stack_nputstr(s, strlen(s), p);
1685 _STPUTC(int c, char *p)
1693 #define STARTSTACKSTR(p) ((p) = stackblock())
1694 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1695 #define CHECKSTRSPACE(n, p) do { \
1698 size_t m = sstrend - q; \
1700 (p) = makestrspace(l, q); \
1702 #define USTPUTC(c, p) (*(p)++ = (c))
1703 #define STACKSTRNUL(p) do { \
1704 if ((p) == sstrend) \
1705 (p) = growstackstr(); \
1708 #define STUNPUTC(p) (--(p))
1709 #define STTOPC(p) ((p)[-1])
1710 #define STADJUST(amount, p) ((p) += (amount))
1712 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1713 #define ungrabstackstr(s, p) stunalloc(s)
1714 #define stackstrend() ((void *)sstrend)
1717 /* ============ String helpers */
1720 * prefix -- see if pfx is a prefix of string.
1723 prefix(const char *string, const char *pfx)
1726 if (*pfx++ != *string++)
1729 return (char *) string;
1733 * Check for a valid number. This should be elsewhere.
1736 is_number(const char *p)
1741 } while (*++p != '\0');
1746 * Convert a string of digits to an integer, printing an error message on
1750 number(const char *s)
1753 ash_msg_and_raise_error(msg_illnum, s);
1758 * Produce a single quoted string suitable as input to the shell.
1759 * The return string is allocated on the stack.
1762 single_quote(const char *s)
1772 len = strchrnul(s, '\'') - s;
1774 q = p = makestrspace(len + 3, p);
1777 q = (char *)mempcpy(q, s, len);
1786 do len++; while (*++s == '\'');
1788 q = p = makestrspace(len + 3, p);
1791 q = (char *)mempcpy(q, s - len, len);
1799 return stackblock();
1803 * Produce a possibly single quoted string suitable as input to the shell.
1804 * If quoting was done, the return string is allocated on the stack,
1805 * otherwise a pointer to the original string is returned.
1808 maybe_single_quote(const char *s)
1813 /* Assuming ACSII */
1814 /* quote ctrl_chars space !"#$%&'()* */
1818 if (*p >= ';' && *p <= '?')
1827 /* quote {|}~ DEL and high bytes */
1830 /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
1831 /* TODO: maybe avoid quoting % */
1837 return single_quote(s);
1841 /* ============ nextopt */
1843 static char **argptr; /* argument list for builtin commands */
1844 static char *optionarg; /* set by nextopt (like getopt) */
1845 static char *optptr; /* used by nextopt */
1848 * XXX - should get rid of. Have all builtins use getopt(3).
1849 * The library getopt must have the BSD extension static variable
1850 * "optreset", otherwise it can't be used within the shell safely.
1852 * Standard option processing (a la getopt) for builtin routines.
1853 * The only argument that is passed to nextopt is the option string;
1854 * the other arguments are unnecessary. It returns the character,
1855 * or '\0' on end of input.
1858 nextopt(const char *optstring)
1865 if (p == NULL || *p == '\0') {
1866 /* We ate entire "-param", take next one */
1872 if (*++p == '\0') /* just "-" ? */
1875 if (LONE_DASH(p)) /* "--" ? */
1877 /* p => next "-param" */
1879 /* p => some option char in the middle of a "-param" */
1881 for (q = optstring; *q != c;) {
1883 ash_msg_and_raise_error("illegal option -%c", c);
1891 ash_msg_and_raise_error("no arg for -%c option", c);
1901 /* ============ Shell variables */
1904 * The parsefile structure pointed to by the global variable parsefile
1905 * contains information about the current file being read.
1908 int nparam; /* # of positional parameters (without $0) */
1909 #if ENABLE_ASH_GETOPTS
1910 int optind; /* next parameter to be processed by getopts */
1911 int optoff; /* used by getopts */
1913 unsigned char malloced; /* if parameter list dynamically allocated */
1914 char **p; /* parameter list */
1918 * Free the list of positional parameters.
1921 freeparam(volatile struct shparam *param)
1923 if (param->malloced) {
1925 ap = ap1 = param->p;
1932 #if ENABLE_ASH_GETOPTS
1933 static void FAST_FUNC getoptsreset(const char *value);
1937 struct var *next; /* next entry in hash list */
1938 int flags; /* flags are defined above */
1939 const char *var_text; /* name=value */
1940 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1941 /* the variable gets set/unset */
1945 struct localvar *next; /* next local variable in list */
1946 struct var *vp; /* the variable that was made local */
1947 int flags; /* saved flags */
1948 const char *text; /* saved text */
1952 #define VEXPORT 0x01 /* variable is exported */
1953 #define VREADONLY 0x02 /* variable cannot be modified */
1954 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1955 #define VTEXTFIXED 0x08 /* text is statically allocated */
1956 #define VSTACK 0x10 /* text is allocated on the stack */
1957 #define VUNSET 0x20 /* the variable is not set */
1958 #define VNOFUNC 0x40 /* don't call the callback function */
1959 #define VNOSET 0x80 /* do not set variable - just readonly test */
1960 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1961 #if ENABLE_ASH_RANDOM_SUPPORT
1962 # define VDYNAMIC 0x200 /* dynamic variable */
1968 /* Need to be before varinit_data[] */
1969 #if ENABLE_LOCALE_SUPPORT
1970 static void FAST_FUNC
1971 change_lc_all(const char *value)
1973 if (value && *value != '\0')
1974 setlocale(LC_ALL, value);
1976 static void FAST_FUNC
1977 change_lc_ctype(const char *value)
1979 if (value && *value != '\0')
1980 setlocale(LC_CTYPE, value);
1984 static void chkmail(void);
1985 static void changemail(const char *var_value) FAST_FUNC;
1987 # define chkmail() ((void)0)
1989 static void changepath(const char *) FAST_FUNC;
1990 #if ENABLE_ASH_RANDOM_SUPPORT
1991 static void change_random(const char *) FAST_FUNC;
1994 static const struct {
1996 const char *var_text;
1997 void (*var_func)(const char *) FAST_FUNC;
1998 } varinit_data[] = {
2000 * Note: VEXPORT would not work correctly here for NOFORK applets:
2001 * some environment strings may be constant.
2003 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
2005 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
2006 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
2008 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
2009 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
2010 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
2011 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
2012 #if ENABLE_ASH_GETOPTS
2013 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
2015 #if ENABLE_ASH_RANDOM_SUPPORT
2016 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
2018 #if ENABLE_LOCALE_SUPPORT
2019 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
2020 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
2022 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
2023 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
2029 struct globals_var {
2030 struct shparam shellparam; /* $@ current positional parameters */
2031 struct redirtab *redirlist;
2032 int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
2033 struct var *vartab[VTABSIZE];
2034 struct var varinit[ARRAY_SIZE(varinit_data)];
2036 extern struct globals_var *const ash_ptr_to_globals_var;
2037 #define G_var (*ash_ptr_to_globals_var)
2038 #define shellparam (G_var.shellparam )
2039 //#define redirlist (G_var.redirlist )
2040 #define preverrout_fd (G_var.preverrout_fd)
2041 #define vartab (G_var.vartab )
2042 #define varinit (G_var.varinit )
2043 #define INIT_G_var() do { \
2045 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
2047 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
2048 varinit[i].flags = varinit_data[i].flags; \
2049 varinit[i].var_text = varinit_data[i].var_text; \
2050 varinit[i].var_func = varinit_data[i].var_func; \
2054 #define vifs varinit[0]
2056 # define vmail (&vifs)[1]
2057 # define vmpath (&vmail)[1]
2058 # define vpath (&vmpath)[1]
2060 # define vpath (&vifs)[1]
2062 #define vps1 (&vpath)[1]
2063 #define vps2 (&vps1)[1]
2064 #define vps4 (&vps2)[1]
2065 #if ENABLE_ASH_GETOPTS
2066 # define voptind (&vps4)[1]
2067 # if ENABLE_ASH_RANDOM_SUPPORT
2068 # define vrandom (&voptind)[1]
2071 # if ENABLE_ASH_RANDOM_SUPPORT
2072 # define vrandom (&vps4)[1]
2077 * The following macros access the values of the above variables.
2078 * They have to skip over the name. They return the null string
2079 * for unset variables.
2081 #define ifsval() (vifs.var_text + 4)
2082 #define ifsset() ((vifs.flags & VUNSET) == 0)
2084 # define mailval() (vmail.var_text + 5)
2085 # define mpathval() (vmpath.var_text + 9)
2086 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2088 #define pathval() (vpath.var_text + 5)
2089 #define ps1val() (vps1.var_text + 4)
2090 #define ps2val() (vps2.var_text + 4)
2091 #define ps4val() (vps4.var_text + 4)
2092 #if ENABLE_ASH_GETOPTS
2093 # define optindval() (voptind.var_text + 7)
2096 #if ENABLE_ASH_GETOPTS
2097 static void FAST_FUNC
2098 getoptsreset(const char *value)
2100 shellparam.optind = number(value) ?: 1;
2101 shellparam.optoff = -1;
2106 * Compares two strings up to the first = or '\0'. The first
2107 * string must be terminated by '='; the second may be terminated by
2108 * either '=' or '\0'.
2111 varcmp(const char *p, const char *q)
2115 while ((c = *p) == (d = *q)) {
2116 if (c == '\0' || c == '=')
2130 * Find the appropriate entry in the hash table from the name.
2132 static struct var **
2133 hashvar(const char *p)
2137 hashval = ((unsigned char) *p) << 4;
2138 while (*p && *p != '=')
2139 hashval += (unsigned char) *p++;
2140 return &vartab[hashval % VTABSIZE];
2144 vpcmp(const void *a, const void *b)
2146 return varcmp(*(const char **)a, *(const char **)b);
2150 * This routine initializes the builtin variables.
2160 * PS1 depends on uid
2162 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2163 vps1.var_text = "PS1=\\w \\$ ";
2166 vps1.var_text = "PS1=# ";
2169 end = vp + ARRAY_SIZE(varinit);
2171 vpp = hashvar(vp->var_text);
2174 } while (++vp < end);
2177 static struct var **
2178 findvar(struct var **vpp, const char *name)
2180 for (; *vpp; vpp = &(*vpp)->next) {
2181 if (varcmp((*vpp)->var_text, name) == 0) {
2189 * Find the value of a variable. Returns NULL if not set.
2191 static const char* FAST_FUNC
2192 lookupvar(const char *name)
2196 v = *findvar(hashvar(name), name);
2198 #if ENABLE_ASH_RANDOM_SUPPORT
2200 * Dynamic variables are implemented roughly the same way they are
2201 * in bash. Namely, they're "special" so long as they aren't unset.
2202 * As soon as they're unset, they're no longer dynamic, and dynamic
2203 * lookup will no longer happen at that point. -- PFM.
2205 if (v->flags & VDYNAMIC)
2208 if (!(v->flags & VUNSET))
2209 return var_end(v->var_text);
2214 #if ENABLE_UNICODE_SUPPORT
2216 reinit_unicode_for_ash(void)
2218 /* Unicode support should be activated even if LANG is set
2219 * _during_ shell execution, not only if it was set when
2220 * shell was started. Therefore, re-check LANG every time:
2222 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2223 || ENABLE_UNICODE_USING_LOCALE
2225 const char *s = lookupvar("LC_ALL");
2226 if (!s) s = lookupvar("LC_CTYPE");
2227 if (!s) s = lookupvar("LANG");
2232 # define reinit_unicode_for_ash() ((void)0)
2236 * Search the environment of a builtin command.
2238 static ALWAYS_INLINE const char *
2239 bltinlookup(const char *name)
2241 return lookupvar(name);
2245 * Same as setvar except that the variable and value are passed in
2246 * the first argument as name=value. Since the first argument will
2247 * be actually stored in the table, it should not be a string that
2249 * Called with interrupts off.
2252 setvareq(char *s, int flags)
2254 struct var *vp, **vpp;
2257 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2258 vpp = findvar(vpp, s);
2261 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2264 if (flags & VNOSAVE)
2268 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2274 if (vp->var_func && !(flags & VNOFUNC))
2275 vp->var_func(var_end(s));
2277 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2278 free((char*)vp->var_text);
2280 if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
2284 if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
2289 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2291 /* variable s is not found */
2294 if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
2296 vp = ckzalloc(sizeof(*vp));
2298 /*vp->func = NULL; - ckzalloc did it */
2301 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2311 * Set the value of a variable. The flags argument is ored with the
2312 * flags of the variable. If val is NULL, the variable is unset.
2315 setvar(const char *name, const char *val, int flags)
2324 q = endofname(name);
2325 p = strchrnul(q, '=');
2327 if (!namelen || p != q)
2328 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2333 vallen = strlen(val);
2337 nameeq = ckmalloc(namelen + vallen + 2);
2338 p = mempcpy(nameeq, name, namelen);
2341 p = mempcpy(p, val, vallen);
2344 vp = setvareq(nameeq, flags | VNOSAVE);
2350 static void FAST_FUNC
2351 setvar0(const char *name, const char *val)
2353 setvar(name, val, 0);
2357 * Unset the specified variable.
2360 unsetvar(const char *s)
2366 * Process a linked list of variable assignments.
2369 listsetvar(struct strlist *list_set_var, int flags)
2371 struct strlist *lp = list_set_var;
2377 setvareq(lp->text, flags);
2384 * Generate a list of variables satisfying the given conditions.
2387 listvars(int on, int off, char ***end)
2398 for (vp = *vpp; vp; vp = vp->next) {
2399 if ((vp->flags & mask) == on) {
2400 if (ep == stackstrend())
2401 ep = growstackstr();
2402 *ep++ = (char*)vp->var_text;
2405 } while (++vpp < vartab + VTABSIZE);
2406 if (ep == stackstrend())
2407 ep = growstackstr();
2411 return grabstackstr(ep);
2415 /* ============ Path search helper
2417 * The variable path (passed by reference) should be set to the start
2418 * of the path before the first call; path_advance will update
2419 * this value as it proceeds. Successive calls to path_advance will return
2420 * the possible path expansions in sequence. If an option (indicated by
2421 * a percent sign) appears in the path entry then the global variable
2422 * pathopt will be set to point to it; otherwise pathopt will be set to
2425 static const char *pathopt; /* set by path_advance */
2428 path_advance(const char **path, const char *name)
2438 for (p = start; *p && *p != ':' && *p != '%'; p++)
2440 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2441 while (stackblocksize() < len)
2445 q = mempcpy(q, start, p - start);
2452 while (*p && *p != ':')
2459 return stalloc(len);
2463 /* ============ Prompt */
2465 static smallint doprompt; /* if set, prompt the user */
2466 static smallint needprompt; /* true if interactive and at start of line */
2468 #if ENABLE_FEATURE_EDITING
2469 static line_input_t *line_input_state;
2470 static const char *cmdedit_prompt;
2472 putprompt(const char *s)
2474 if (ENABLE_ASH_EXPAND_PRMT) {
2475 free((char*)cmdedit_prompt);
2476 cmdedit_prompt = ckstrdup(s);
2483 putprompt(const char *s)
2489 /* expandstr() needs parsing machinery, so it is far away ahead... */
2490 static const char *expandstr(const char *ps, int syntax_type);
2491 /* Values for syntax param */
2492 #define BASESYNTAX 0 /* not in quotes */
2493 #define DQSYNTAX 1 /* in double quotes */
2494 #define SQSYNTAX 2 /* in single quotes */
2495 #define ARISYNTAX 3 /* in arithmetic */
2496 #if ENABLE_ASH_EXPAND_PRMT
2497 # define PSSYNTAX 4 /* prompt. never passed to SIT() */
2499 /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
2502 * called by editline -- any expansions to the prompt should be added here.
2505 setprompt_if(smallint do_set, int whichprompt)
2508 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2515 switch (whichprompt) {
2525 #if ENABLE_ASH_EXPAND_PRMT
2526 pushstackmark(&smark, stackblocksize());
2527 putprompt(expandstr(prompt, PSSYNTAX));
2528 popstackmark(&smark);
2535 /* ============ The cd and pwd commands */
2537 #define CD_PHYSICAL 1
2547 while ((i = nextopt("LP")) != '\0') {
2549 flags ^= CD_PHYSICAL;
2558 * Update curdir (the name of the current directory) in response to a
2562 updatepwd(const char *dir)
2569 cdcomppath = sstrdup(dir);
2572 if (curdir == nullstr)
2574 new = stack_putstr(curdir, new);
2576 new = makestrspace(strlen(dir) + 2, new);
2577 lim = (char *)stackblock() + 1;
2581 if (new > lim && *lim == '/')
2586 if (dir[1] == '/' && dir[2] != '/') {
2592 p = strtok(cdcomppath, "/");
2596 if (p[1] == '.' && p[2] == '\0') {
2608 new = stack_putstr(p, new);
2611 p = strtok(NULL, "/");
2616 return stackblock();
2620 * Find out what the current directory is. If we already know the current
2621 * directory, this routine returns immediately.
2626 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2627 return dir ? dir : nullstr;
2631 setpwd(const char *val, int setold)
2635 oldcur = dir = curdir;
2638 setvar("OLDPWD", oldcur, VEXPORT);
2641 if (physdir != nullstr) {
2642 if (physdir != oldcur)
2646 if (oldcur == val || !val) {
2652 dir = ckstrdup(val);
2653 if (oldcur != dir && oldcur != nullstr) {
2658 setvar("PWD", dir, VEXPORT);
2661 static void hashcd(void);
2664 * Actually do the chdir. We also call hashcd to let other routines
2665 * know that the current directory has changed.
2668 docd(const char *dest, int flags)
2670 const char *dir = NULL;
2673 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2676 if (!(flags & CD_PHYSICAL)) {
2677 dir = updatepwd(dest);
2691 static int FAST_FUNC
2692 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2704 dest = bltinlookup("HOME");
2705 else if (LONE_DASH(dest)) {
2706 dest = bltinlookup("OLDPWD");
2728 path = bltinlookup("CDPATH");
2731 p = path_advance(&path, dest);
2732 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2736 if (!docd(p, flags))
2747 ash_msg_and_raise_error("can't cd to %s", dest);
2750 if (flags & CD_PRINT)
2751 out1fmt("%s\n", curdir);
2755 static int FAST_FUNC
2756 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2759 const char *dir = curdir;
2763 if (physdir == nullstr)
2767 out1fmt("%s\n", dir);
2772 /* ============ ... */
2775 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2777 /* Syntax classes */
2778 #define CWORD 0 /* character is nothing special */
2779 #define CNL 1 /* newline character */
2780 #define CBACK 2 /* a backslash character */
2781 #define CSQUOTE 3 /* single quote */
2782 #define CDQUOTE 4 /* double quote */
2783 #define CENDQUOTE 5 /* a terminating quote */
2784 #define CBQUOTE 6 /* backwards single quote */
2785 #define CVAR 7 /* a dollar sign */
2786 #define CENDVAR 8 /* a '}' character */
2787 #define CLP 9 /* a left paren in arithmetic */
2788 #define CRP 10 /* a right paren in arithmetic */
2789 #define CENDFILE 11 /* end of file */
2790 #define CCTL 12 /* like CWORD, except it must be escaped */
2791 #define CSPCL 13 /* these terminate a word */
2792 #define CIGN 14 /* character should be ignored */
2795 #if ENABLE_ASH_ALIAS
2799 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2801 #if ENABLE_FEATURE_SH_MATH
2802 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2804 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2806 static const uint16_t S_I_T[] ALIGN2 = {
2807 #if ENABLE_ASH_ALIAS
2808 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2810 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2811 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2812 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2813 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2814 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2815 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2816 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2817 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2818 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2819 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2820 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2821 #if !USE_SIT_FUNCTION
2822 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2823 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2824 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2828 /* Constants below must match table above */
2830 #if ENABLE_ASH_ALIAS
2831 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2833 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2834 CNL_CNL_CNL_CNL , /* 2 */
2835 CWORD_CCTL_CCTL_CWORD , /* 3 */
2836 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2837 CVAR_CVAR_CWORD_CVAR , /* 5 */
2838 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2839 CSPCL_CWORD_CWORD_CLP , /* 7 */
2840 CSPCL_CWORD_CWORD_CRP , /* 8 */
2841 CBACK_CBACK_CCTL_CBACK , /* 9 */
2842 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2843 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2844 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2845 CWORD_CWORD_CWORD_CWORD , /* 13 */
2846 CCTL_CCTL_CCTL_CCTL , /* 14 */
2849 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2850 * caller must ensure proper cast on it if c is *char_ptr!
2852 #if USE_SIT_FUNCTION
2855 SIT(int c, int syntax)
2857 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2858 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2860 * This causes '/' to be prepended with CTLESC in dquoted string,
2861 * making "./file"* treated incorrectly because we feed
2862 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2863 * The "homegrown" glob implementation is okay with that,
2864 * but glibc one isn't. With '/' always treated as CWORD,
2867 # if ENABLE_ASH_ALIAS
2868 static const uint8_t syntax_index_table[] ALIGN1 = {
2869 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2870 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2871 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2875 static const uint8_t syntax_index_table[] ALIGN1 = {
2876 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2877 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2878 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2887 # if ENABLE_ASH_ALIAS
2893 /* Cast is purely for paranoia here,
2894 * just in case someone passed signed char to us */
2895 if ((unsigned char)c >= CTL_FIRST
2896 && (unsigned char)c <= CTL_LAST
2900 s = strchrnul(spec_symbls, c);
2903 indx = syntax_index_table[s - spec_symbls];
2905 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2908 #else /* !USE_SIT_FUNCTION */
2910 static const uint8_t syntax_index_table[] ALIGN1 = {
2911 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2912 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2922 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2923 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2945 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2946 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2947 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2949 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2951 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2952 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2953 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2954 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2955 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2957 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2958 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2959 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2960 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2972 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2973 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2974 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2975 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2976 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2977 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
3005 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
3006 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
3007 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
3008 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
3009 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
3010 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
3011 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
3012 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
3013 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
3014 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
3015 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
3016 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
3017 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
3018 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
3019 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
3020 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3021 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3022 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3023 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3024 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3025 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3026 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3027 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3028 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3029 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3030 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3031 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3032 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3033 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3034 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3035 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3036 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3037 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3038 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3039 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3040 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3041 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3043 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3044 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3045 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3046 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3047 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3048 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3049 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3050 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3120 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3121 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3122 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3123 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3124 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3125 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3126 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3127 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3128 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3129 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3130 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3131 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3132 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3133 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3134 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3135 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3136 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3137 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3138 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3139 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3140 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3141 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3142 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3143 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3144 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3145 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3146 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3147 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3148 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3149 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3150 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3151 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3152 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3153 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3154 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3155 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3156 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3157 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3158 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3159 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3160 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3161 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3162 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3163 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3164 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3165 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3166 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3167 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3168 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3169 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3170 # if ENABLE_ASH_ALIAS
3171 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3176 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3177 #else /* debug version, caught one signed char bug */
3178 # define SIT(c, syntax) \
3180 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3181 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3182 if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
3183 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3184 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3188 #endif /* !USE_SIT_FUNCTION */
3191 /* ============ Alias handling */
3193 #if ENABLE_ASH_ALIAS
3195 #define ALIASINUSE 1
3206 static struct alias **atab; // [ATABSIZE];
3207 #define INIT_G_alias() do { \
3208 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3212 static struct alias **
3213 __lookupalias(const char *name)
3215 unsigned int hashval;
3222 ch = (unsigned char)*p;
3226 ch = (unsigned char)*++p;
3228 app = &atab[hashval % ATABSIZE];
3230 for (; *app; app = &(*app)->next) {
3231 if (strcmp(name, (*app)->name) == 0) {
3239 static struct alias *
3240 lookupalias(const char *name, int check)
3242 struct alias *ap = *__lookupalias(name);
3244 if (check && ap && (ap->flag & ALIASINUSE))
3249 static struct alias *
3250 freealias(struct alias *ap)
3254 if (ap->flag & ALIASINUSE) {
3255 ap->flag |= ALIASDEAD;
3267 setalias(const char *name, const char *val)
3269 struct alias *ap, **app;
3271 app = __lookupalias(name);
3275 if (!(ap->flag & ALIASINUSE)) {
3278 ap->val = ckstrdup(val);
3279 ap->flag &= ~ALIASDEAD;
3282 ap = ckzalloc(sizeof(struct alias));
3283 ap->name = ckstrdup(name);
3284 ap->val = ckstrdup(val);
3285 /*ap->flag = 0; - ckzalloc did it */
3286 /*ap->next = NULL;*/
3293 unalias(const char *name)
3297 app = __lookupalias(name);
3301 *app = freealias(*app);
3312 struct alias *ap, **app;
3316 for (i = 0; i < ATABSIZE; i++) {
3318 for (ap = *app; ap; ap = *app) {
3319 *app = freealias(*app);
3329 printalias(const struct alias *ap)
3331 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3335 * TODO - sort output
3337 static int FAST_FUNC
3338 aliascmd(int argc UNUSED_PARAM, char **argv)
3347 for (i = 0; i < ATABSIZE; i++) {
3348 for (ap = atab[i]; ap; ap = ap->next) {
3354 while ((n = *++argv) != NULL) {
3355 v = strchr(n+1, '=');
3356 if (v == NULL) { /* n+1: funny ksh stuff */
3357 ap = *__lookupalias(n);
3359 fprintf(stderr, "%s: %s not found\n", "alias", n);
3372 static int FAST_FUNC
3373 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3377 while (nextopt("a") != '\0') {
3381 for (i = 0; *argptr; argptr++) {
3382 if (unalias(*argptr)) {
3383 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3391 #endif /* ASH_ALIAS */
3394 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3397 #define FORK_NOJOB 2
3399 /* mode flags for showjob(s) */
3400 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3401 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3402 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3403 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3406 * A job structure contains information about a job. A job is either a
3407 * single process or a set of processes contained in a pipeline. In the
3408 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3412 pid_t ps_pid; /* process id */
3413 int ps_status; /* last process status from wait() */
3414 char *ps_cmd; /* text of command being run */
3418 struct procstat ps0; /* status of process */
3419 struct procstat *ps; /* status or processes when more than one */
3421 int stopstatus; /* status of a stopped job */
3423 unsigned nprocs; /* number of processes */
3425 #define JOBRUNNING 0 /* at least one proc running */
3426 #define JOBSTOPPED 1 /* all procs are stopped */
3427 #define JOBDONE 2 /* all procs are completed */
3431 sigint: 1, /* job was killed by SIGINT */
3432 jobctl: 1, /* job running under job control */
3434 waited: 1, /* true if this entry has been waited for */
3435 used: 1, /* true if this entry is in used */
3436 changed: 1; /* true if status has changed */
3437 struct job *prev_job; /* previous job */
3440 static struct job *makejob(/*union node *,*/ int);
3441 static int forkshell(struct job *, union node *, int);
3442 static int waitforjob(struct job *);
3445 enum { doing_jobctl = 0 };
3446 #define setjobctl(on) do {} while (0)
3448 static smallint doing_jobctl; //references:8
3449 static void setjobctl(int);
3456 ignoresig(int signo)
3458 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3459 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3460 /* No, need to do it */
3461 signal(signo, SIG_IGN);
3463 sigmode[signo - 1] = S_HARD_IGN;
3467 * Only one usage site - in setsignal()
3470 signal_handler(int signo)
3472 if (signo == SIGCHLD) {
3478 gotsig[signo - 1] = 1;
3479 pending_sig = signo;
3481 if (signo == SIGINT && !trap[SIGINT]) {
3482 if (!suppress_int) {
3484 raise_interrupt(); /* does not return */
3491 * Set the signal handler for the specified signal. The routine figures
3492 * out what it should be set to.
3495 setsignal(int signo)
3498 char cur_act, new_act;
3499 struct sigaction act;
3503 if (t != NULL) { /* trap for this sig is set */
3505 if (t[0] == '\0') /* trap is "": ignore this sig */
3509 if (rootshell && new_act == S_DFL) {
3512 if (iflag || minusc || sflag == 0)
3521 * "In all cases, bash ignores SIGQUIT. Non-builtin
3522 * commands run by bash have signal handlers
3523 * set to the values inherited by the shell
3524 * from its parent". */
3540 /* if !rootshell, we reset SIGQUIT to DFL,
3541 * whereas we have to restore it to what shell got on entry.
3542 * This is handled by the fact that if signal was IGNored on entry,
3543 * then cur_act is S_HARD_IGN and we never change its sigaction
3547 if (signo == SIGCHLD)
3550 t = &sigmode[signo - 1];
3553 /* current setting is not yet known */
3554 if (sigaction(signo, NULL, &act)) {
3555 /* pretend it worked; maybe we should give a warning,
3556 * but other shells don't. We don't alter sigmode,
3557 * so we retry every time.
3558 * btw, in Linux it never fails. --vda */
3561 if (act.sa_handler == SIG_IGN) {
3562 cur_act = S_HARD_IGN;
3564 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3566 cur_act = S_IGN; /* don't hard ignore these */
3569 if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
3570 /* installing SIG_DFL over SIG_DFL is a no-op */
3571 /* saves one sigaction call in each "sh -c SCRIPT" invocation */
3576 if (cur_act == S_HARD_IGN || cur_act == new_act)
3581 act.sa_handler = SIG_DFL;
3584 act.sa_handler = signal_handler;
3587 act.sa_handler = SIG_IGN;
3590 /* flags and mask matter only if !DFL and !IGN, but we do it
3591 * for all cases for more deterministic behavior:
3593 act.sa_flags = 0; //TODO: why not SA_RESTART?
3594 sigfillset(&act.sa_mask);
3596 sigaction_set(signo, &act);
3599 /* mode flags for set_curjob */
3600 #define CUR_DELETE 2
3601 #define CUR_RUNNING 1
3602 #define CUR_STOPPED 0
3605 /* pgrp of shell on invocation */
3606 static int initialpgrp; //references:2
3607 static int ttyfd = -1; //5
3610 static struct job *jobtab; //5
3612 static unsigned njobs; //4
3614 static struct job *curjob; //lots
3615 /* number of presumed living untracked jobs */
3616 static int jobless; //4
3619 /* Bash has a feature: it restores termios after a successful wait for
3620 * a foreground job which had at least one stopped or sigkilled member.
3621 * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
3622 * properly restoring tty state. Should we do this too?
3623 * A reproducer: ^Z an interactive python:
3626 * Python 2.7.12 (...)
3628 * { python leaves tty in -icanon -echo state. We do survive that... }
3629 * [1]+ Stopped python
3630 * { ...however, next program (python #2) does not survive it well: }
3632 * Python 2.7.12 (...)
3633 * >>> Traceback (most recent call last):
3634 * { above, I typed "qwerty<CR>", but -echo state is still in effect }
3635 * File "<stdin>", line 1, in <module>
3636 * NameError: name 'qwerty' is not defined
3638 * The implementation below is modeled on bash code and seems to work.
3639 * However, I'm not sure we should do this. For one: what if I'd fg
3640 * the stopped python instead? It'll be confused by "restored" tty state.
3642 static struct termios shell_tty_info;
3646 if (rootshell && ttyfd >= 0)
3647 tcgetattr(ttyfd, &shell_tty_info);
3652 /* if (rootshell) - caller ensures this */
3654 tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
3657 job_signal_status(struct job *jp)
3661 struct procstat *ps = jp->ps;
3662 for (i = 0; i < jp->nprocs; i++) {
3663 status = ps[i].ps_status;
3664 if (WIFSIGNALED(status) || WIFSTOPPED(status))
3670 restore_tty_if_stopped_or_signaled(struct job *jp)
3672 //TODO: check what happens if we come from waitforjob() in expbackq()
3674 int s = job_signal_status(jp);
3675 if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
3680 # define get_tty_state() ((void)0)
3681 # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
3685 set_curjob(struct job *jp, unsigned mode)
3688 struct job **jpp, **curp;
3690 /* first remove from list */
3691 jpp = curp = &curjob;
3696 jpp = &jp1->prev_job;
3698 *jpp = jp1->prev_job;
3700 /* Then re-insert in correct position */
3708 /* job being deleted */
3711 /* newly created job or backgrounded job,
3712 * put after all stopped jobs.
3717 if (!jp1 || jp1->state != JOBSTOPPED)
3720 jpp = &jp1->prev_job;
3726 /* newly stopped job - becomes curjob */
3727 jp->prev_job = *jpp;
3735 jobno(const struct job *jp)
3737 return jp - jobtab + 1;
3742 * Convert a job name to a job structure.
3745 #define getjob(name, getctl) getjob(name)
3748 getjob(const char *name, int getctl)
3752 const char *err_msg = "%s: no such job";
3756 char *(*match)(const char *, const char *);
3771 if (c == '+' || c == '%') {
3773 err_msg = "No current job";
3779 err_msg = "No previous job";
3789 if (num > 0 && num <= njobs) {
3790 jp = jobtab + num - 1;
3805 if (match(jp->ps[0].ps_cmd, p)) {
3809 err_msg = "%s: ambiguous";
3819 err_msg = "job %s not created under job control";
3820 if (getctl && jp->jobctl == 0)
3825 ash_msg_and_raise_error(err_msg, name);
3829 * Mark a job structure as unused.
3832 freejob(struct job *jp)
3834 struct procstat *ps;
3838 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3839 if (ps->ps_cmd != nullstr)
3842 if (jp->ps != &jp->ps0)
3845 set_curjob(jp, CUR_DELETE);
3851 xtcsetpgrp(int fd, pid_t pgrp)
3853 if (tcsetpgrp(fd, pgrp))
3854 ash_msg_and_raise_perror("can't set tty process group");
3858 * Turn job control on and off.
3860 * Note: This code assumes that the third arg to ioctl is a character
3861 * pointer, which is true on Berkeley systems but not System V. Since
3862 * System V doesn't have job control yet, this isn't a problem now.
3864 * Called with interrupts off.
3872 if (on == doing_jobctl || rootshell == 0)
3876 ofd = fd = open(_PATH_TTY, O_RDWR);
3878 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3879 * That sometimes helps to acquire controlling tty.
3880 * Obviously, a workaround for bugs when someone
3881 * failed to provide a controlling tty to bash! :) */
3887 /* fd is a tty at this point */
3888 fd = fcntl(fd, F_DUPFD, 10);
3889 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
3892 goto out; /* F_DUPFD failed */
3893 close_on_exec_on(fd);
3894 while (1) { /* while we are in the background */
3895 pgrp = tcgetpgrp(fd);
3898 ash_msg("can't access tty; job control turned off");
3902 if (pgrp == getpgrp())
3913 xtcsetpgrp(fd, pgrp);
3915 /* turning job control off */
3918 /* was xtcsetpgrp, but this can make exiting ash
3919 * loop forever if pty is already deleted */
3920 tcsetpgrp(fd, pgrp);
3934 static int FAST_FUNC
3935 killcmd(int argc, char **argv)
3937 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3940 if (argv[i][0] == '%') {
3942 * "kill %N" - job kill
3943 * Converting to pgrp / pid kill
3949 jp = getjob(argv[i], 0);
3951 * In jobs started under job control, we signal
3952 * entire process group by kill -PGRP_ID.
3953 * This happens, f.e., in interactive shell.
3955 * Otherwise, we signal each child via
3956 * kill PID1 PID2 PID3.
3958 * sh -c 'sleep 1|sleep 1 & kill %1'
3959 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3960 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3962 n = jp->nprocs; /* can't be 0 (I hope) */
3965 dst = alloca(n * sizeof(int)*4);
3967 for (j = 0; j < n; j++) {
3968 struct procstat *ps = &jp->ps[j];
3969 /* Skip non-running and not-stopped members
3970 * (i.e. dead members) of the job
3972 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3975 * kill_main has matching code to expect
3976 * leading space. Needed to not confuse
3977 * negative pids with "kill -SIGNAL_NO" syntax
3979 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3983 } while (argv[++i]);
3985 return kill_main(argc, argv);
3989 showpipe(struct job *jp /*, FILE *out*/)
3991 struct procstat *ps;
3992 struct procstat *psend;
3994 psend = jp->ps + jp->nprocs;
3995 for (ps = jp->ps + 1; ps < psend; ps++)
3996 printf(" | %s", ps->ps_cmd);
3997 newline_and_flush(stdout);
3998 flush_stdout_stderr();
4003 restartjob(struct job *jp, int mode)
4005 struct procstat *ps;
4011 if (jp->state == JOBDONE)
4013 jp->state = JOBRUNNING;
4014 pgid = jp->ps[0].ps_pid;
4015 if (mode == FORK_FG) {
4017 xtcsetpgrp(ttyfd, pgid);
4019 killpg(pgid, SIGCONT);
4023 if (WIFSTOPPED(ps->ps_status)) {
4029 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
4034 static int FAST_FUNC
4035 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
4041 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
4045 jp = getjob(*argv, 1);
4046 if (mode == FORK_BG) {
4047 set_curjob(jp, CUR_RUNNING);
4048 printf("[%d] ", jobno(jp));
4050 out1str(jp->ps[0].ps_cmd);
4051 showpipe(jp /*, stdout*/);
4052 retval = restartjob(jp, mode);
4053 } while (*argv && *++argv);
4059 sprint_status48(char *s, int status, int sigonly)
4065 if (!WIFEXITED(status)) {
4067 if (WIFSTOPPED(status))
4068 st = WSTOPSIG(status);
4071 st = WTERMSIG(status);
4073 if (st == SIGINT || st == SIGPIPE)
4076 if (WIFSTOPPED(status))
4081 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
4082 col = fmtstr(s, 32, strsignal(st));
4083 if (WCOREDUMP(status)) {
4084 strcpy(s + col, " (core dumped)");
4085 col += sizeof(" (core dumped)")-1;
4087 } else if (!sigonly) {
4088 st = WEXITSTATUS(status);
4089 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
4096 wait_block_or_sig(int *status)
4103 /* Poll all children for changes in their state */
4105 /* if job control is active, accept stopped processes too */
4106 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
4108 break; /* Error (e.g. EINTR, ECHILD) or pid */
4110 /* Children exist, but none are ready. Sleep until interesting signal */
4113 sigprocmask(SIG_SETMASK, &mask, &mask);
4114 while (!got_sigchld && !pending_sig)
4116 sigprocmask(SIG_SETMASK, &mask, NULL);
4117 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
4118 while (!got_sigchld && !pending_sig)
4122 /* If it was SIGCHLD, poll children again */
4123 } while (got_sigchld);
4128 #define DOWAIT_NONBLOCK 0
4129 #define DOWAIT_BLOCK 1
4130 #define DOWAIT_BLOCK_OR_SIG 2
4133 dowait(int block, struct job *job)
4138 struct job *thisjob = NULL;
4140 TRACE(("dowait(0x%x) called\n", block));
4142 /* It's wrong to call waitpid() outside of INT_OFF region:
4143 * signal can arrive just after syscall return and handler can
4144 * longjmp away, losing stop/exit notification processing.
4145 * Thus, for "jobs" builtin, and for waiting for a fg job,
4146 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4148 * However, for "wait" builtin it is wrong to simply call waitpid()
4149 * in INT_OFF region: "wait" needs to wait for any running job
4150 * to change state, but should exit on any trap too.
4151 * In INT_OFF region, a signal just before syscall entry can set
4152 * pending_sig variables, but we can't check them, and we would
4153 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4155 * Because of this, we run inside INT_OFF, but use a special routine
4156 * which combines waitpid() and sigsuspend().
4157 * This is the reason why we need to have a handler for SIGCHLD:
4158 * SIG_DFL handler does not wake sigsuspend().
4161 if (block == DOWAIT_BLOCK_OR_SIG) {
4162 pid = wait_block_or_sig(&status);
4165 if (block == DOWAIT_NONBLOCK)
4166 wait_flags = WNOHANG;
4167 /* if job control is active, accept stopped processes too */
4169 wait_flags |= WUNTRACED;
4170 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4171 pid = waitpid(-1, &status, wait_flags);
4173 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4174 pid, status, errno, strerror(errno)));
4179 for (jp = curjob; jp; jp = jp->prev_job) {
4181 struct procstat *ps;
4182 struct procstat *psend;
4183 if (jp->state == JOBDONE)
4187 psend = ps + jp->nprocs;
4189 if (ps->ps_pid == pid) {
4190 TRACE(("Job %d: changing status of proc %d "
4191 "from 0x%x to 0x%x\n",
4192 jobno(jp), pid, ps->ps_status, status));
4193 ps->ps_status = status;
4196 if (ps->ps_status == -1)
4197 jobstate = JOBRUNNING;
4199 if (jobstate == JOBRUNNING)
4201 if (WIFSTOPPED(ps->ps_status)) {
4202 jp->stopstatus = ps->ps_status;
4203 jobstate = JOBSTOPPED;
4206 } while (++ps < psend);
4210 /* Found the job where one of its processes changed its state.
4211 * Is there at least one live and running process in this job? */
4212 if (jobstate != JOBRUNNING) {
4213 /* No. All live processes in the job are stopped
4214 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4216 thisjob->changed = 1;
4217 if (thisjob->state != jobstate) {
4218 TRACE(("Job %d: changing state from %d to %d\n",
4219 jobno(thisjob), thisjob->state, jobstate));
4220 thisjob->state = jobstate;
4222 if (jobstate == JOBSTOPPED)
4223 set_curjob(thisjob, CUR_STOPPED);
4229 /* The process wasn't found in job list */
4231 if (!WIFSTOPPED(status))
4237 if (thisjob && thisjob == job) {
4241 len = sprint_status48(s, status, 1);
4253 showjob(struct job *jp, int mode)
4255 struct procstat *ps;
4256 struct procstat *psend;
4259 char s[16 + 16 + 48];
4260 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4264 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4265 /* just output process (group) id of pipeline */
4266 fprintf(out, "%d\n", ps->ps_pid);
4270 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4275 else if (curjob && jp == curjob->prev_job)
4278 if (mode & SHOW_PIDS)
4279 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4281 psend = ps + jp->nprocs;
4283 if (jp->state == JOBRUNNING) {
4284 strcpy(s + col, "Running");
4285 col += sizeof("Running") - 1;
4287 int status = psend[-1].ps_status;
4288 if (jp->state == JOBSTOPPED)
4289 status = jp->stopstatus;
4290 col += sprint_status48(s + col, status, 0);
4292 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4294 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4295 * or prints several "PID | <cmdN>" lines,
4296 * depending on SHOW_PIDS bit.
4297 * We do not print status of individual processes
4298 * between PID and <cmdN>. bash does it, but not very well:
4299 * first line shows overall job status, not process status,
4300 * making it impossible to know 1st process status.
4304 /* for each process */
4307 if (mode & SHOW_PIDS)
4308 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4310 fprintf(out, "%s%*c%s%s",
4312 33 - col >= 0 ? 33 - col : 0, ' ',
4313 ps == jp->ps ? "" : "| ",
4316 } while (++ps != psend);
4317 newline_and_flush(out);
4321 if (jp->state == JOBDONE) {
4322 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4328 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4329 * statuses have changed since the last call to showjobs.
4336 TRACE(("showjobs(0x%x) called\n", mode));
4338 /* Handle all finished jobs */
4339 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4342 for (jp = curjob; jp; jp = jp->prev_job) {
4343 if (!(mode & SHOW_CHANGED) || jp->changed) {
4349 static int FAST_FUNC
4350 jobscmd(int argc UNUSED_PARAM, char **argv)
4355 while ((m = nextopt("lp")) != '\0') {
4359 mode |= SHOW_ONLY_PGID;
4365 showjob(getjob(*argv, 0), mode);
4375 /* Called only on finished or stopped jobs (no members are running) */
4377 getstatus(struct job *job)
4381 struct procstat *ps;
4383 /* Fetch last member's status */
4384 ps = job->ps + job->nprocs - 1;
4385 status = ps->ps_status;
4387 /* "set -o pipefail" mode: use last _nonzero_ status */
4388 while (status == 0 && --ps >= job->ps)
4389 status = ps->ps_status;
4392 retval = WEXITSTATUS(status);
4393 if (!WIFEXITED(status)) {
4395 retval = WSTOPSIG(status);
4396 if (!WIFSTOPPED(status))
4399 /* XXX: limits number of signals */
4400 retval = WTERMSIG(status);
4402 if (retval == SIGINT)
4408 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4409 jobno(job), job->nprocs, status, retval));
4413 static int FAST_FUNC
4414 waitcmd(int argc UNUSED_PARAM, char **argv)
4425 /* wait for all jobs */
4429 if (!jp) /* no running procs */
4431 if (jp->state == JOBRUNNING)
4437 * "When bash is waiting for an asynchronous command via
4438 * the wait builtin, the reception of a signal for which a trap
4439 * has been set will cause the wait builtin to return immediately
4440 * with an exit status greater than 128, immediately after which
4441 * the trap is executed."
4443 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4444 /* if child sends us a signal *and immediately exits*,
4445 * dowait() returns pid > 0. Check this case,
4446 * not "if (dowait() < 0)"!
4455 if (**argv != '%') {
4456 pid_t pid = number(*argv);
4461 if (job->ps[job->nprocs - 1].ps_pid == pid)
4463 job = job->prev_job;
4466 job = getjob(*argv, 0);
4468 /* loop until process terminated or stopped */
4469 while (job->state == JOBRUNNING) {
4470 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4475 retval = getstatus(job);
4482 retval = 128 + pending_sig;
4491 struct job *jp, *jq;
4493 len = njobs * sizeof(*jp);
4495 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4497 offset = (char *)jp - (char *)jq;
4499 /* Relocate pointers */
4502 jq = (struct job *)((char *)jq + l);
4506 #define joff(p) ((struct job *)((char *)(p) + l))
4507 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4508 if (joff(jp)->ps == &jq->ps0)
4509 jmove(joff(jp)->ps);
4510 if (joff(jp)->prev_job)
4511 jmove(joff(jp)->prev_job);
4521 jp = (struct job *)((char *)jp + len);
4525 } while (--jq >= jp);
4530 * Return a new job structure.
4531 * Called with interrupts off.
4534 makejob(/*union node *node,*/ int nprocs)
4539 for (i = njobs, jp = jobtab; ; jp++) {
4546 if (jp->state != JOBDONE || !jp->waited)
4555 memset(jp, 0, sizeof(*jp));
4557 /* jp->jobctl is a bitfield.
4558 * "jp->jobctl |= doing_jobctl" likely to give awful code */
4562 jp->prev_job = curjob;
4567 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4569 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4576 * Return a string identifying a command (to be printed by the
4579 static char *cmdnextc;
4582 cmdputs(const char *s)
4584 static const char vstype[VSTYPE + 1][3] = {
4585 "", "}", "-", "+", "?", "=",
4586 "%", "%%", "#", "##"
4587 IF_BASH_SUBSTR(, ":")
4588 IF_BASH_PATTERN_SUBST(, "/", "//")
4591 const char *p, *str;
4595 unsigned char subtype = 0;
4599 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4601 while ((c = *p++) != '\0') {
4609 if ((subtype & VSTYPE) == VSLENGTH)
4615 str = "\"}" + !(quoted & 1);
4622 #if ENABLE_FEATURE_SH_MATH
4637 if ((subtype & VSTYPE) != VSNORMAL)
4639 str = vstype[subtype & VSTYPE];
4640 if (subtype & VSNUL)
4649 /* These can only happen inside quotes */
4655 // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
4666 while ((c = *str++) != '\0') {
4669 } /* while *p++ not NUL */
4672 USTPUTC('"', nextc);
4678 /* cmdtxt() and cmdlist() call each other */
4679 static void cmdtxt(union node *n);
4682 cmdlist(union node *np, int sep)
4684 for (; np; np = np->narg.next) {
4688 if (sep && np->narg.next)
4694 cmdtxt(union node *n)
4697 struct nodelist *lp;
4708 lp = n->npipe.cmdlist;
4726 cmdtxt(n->nbinary.ch1);
4742 cmdtxt(n->nif.test);
4744 if (n->nif.elsepart) {
4745 cmdtxt(n->nif.ifpart);
4747 n = n->nif.elsepart;
4765 cmdtxt(n->nbinary.ch1);
4775 cmdputs(n->nfor.var);
4777 cmdlist(n->nfor.args, 1);
4782 cmdputs(n->narg.text);
4786 cmdlist(n->ncmd.args, 1);
4787 cmdlist(n->ncmd.redirect, 0);
4800 cmdputs(n->ncase.expr->narg.text);
4802 for (np = n->ncase.cases; np; np = np->nclist.next) {
4803 cmdtxt(np->nclist.pattern);
4805 cmdtxt(np->nclist.body);
4819 #if BASH_REDIR_OUTPUT
4834 cmdputs(utoa(n->nfile.fd));
4836 if (n->type == NTOFD || n->type == NFROMFD) {
4837 if (n->ndup.dupfd >= 0)
4838 cmdputs(utoa(n->ndup.dupfd));
4849 commandtext(union node *n)
4853 STARTSTACKSTR(cmdnextc);
4855 name = stackblock();
4856 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4857 return ckstrdup(name);
4862 * Fork off a subshell. If we are doing job control, give the subshell its
4863 * own process group. Jp is a job structure that the job is to be added to.
4864 * N is the command that will be evaluated by the child. Both jp and n may
4865 * be NULL. The mode parameter can be one of the following:
4866 * FORK_FG - Fork off a foreground process.
4867 * FORK_BG - Fork off a background process.
4868 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4869 * process group even if job control is on.
4871 * When job control is turned off, background processes have their standard
4872 * input redirected to /dev/null (except for the second and later processes
4875 * Called with interrupts off.
4878 * Clear traps on a fork.
4886 for (tp = trap; tp < &trap[NSIG]; tp++) {
4887 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4888 if (trap_ptr == trap)
4890 /* else: it "belongs" to trap_ptr vector, don't free */
4892 if ((tp - trap) != 0)
4893 setsignal(tp - trap);
4900 /* Lives far away from here, needed for forkchild */
4901 static void closescript(void);
4903 /* Called after fork(), in child */
4904 /* jp and n are NULL when called by openhere() for heredoc support */
4905 static NOINLINE void
4906 forkchild(struct job *jp, union node *n, int mode)
4910 TRACE(("Child shell %d\n", getpid()));
4914 /* man bash: "Non-builtin commands run by bash have signal handlers
4915 * set to the values inherited by the shell from its parent".
4916 * Do we do it correctly? */
4920 if (mode == FORK_NOJOB /* is it `xxx` ? */
4921 && n && n->type == NCMD /* is it single cmd? */
4922 /* && n->ncmd.args->type == NARG - always true? */
4923 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4924 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4925 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4927 TRACE(("Trap hack\n"));
4928 /* Awful hack for `trap` or $(trap).
4930 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4931 * contains an example where "trap" is executed in a subshell:
4933 * save_traps=$(trap)
4935 * eval "$save_traps"
4937 * Standard does not say that "trap" in subshell shall print
4938 * parent shell's traps. It only says that its output
4939 * must have suitable form, but then, in the above example
4940 * (which is not supposed to be normative), it implies that.
4942 * bash (and probably other shell) does implement it
4943 * (traps are reset to defaults, but "trap" still shows them),
4944 * but as a result, "trap" logic is hopelessly messed up:
4947 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4948 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4949 * # true | trap <--- trap is in subshell - no output (ditto)
4950 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4951 * trap -- 'echo Ho' SIGWINCH
4952 * # echo `(trap)` <--- in subshell in subshell - output
4953 * trap -- 'echo Ho' SIGWINCH
4954 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4955 * trap -- 'echo Ho' SIGWINCH
4957 * The rules when to forget and when to not forget traps
4958 * get really complex and nonsensical.
4960 * Our solution: ONLY bare $(trap) or `trap` is special.
4962 /* Save trap handler strings for trap builtin to print */
4963 trap_ptr = xmemdup(trap, sizeof(trap));
4964 /* Fall through into clearing traps */
4968 /* do job control only in root shell */
4970 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4973 if (jp->nprocs == 0)
4976 pgrp = jp->ps[0].ps_pid;
4977 /* this can fail because we are doing it in the parent also */
4979 if (mode == FORK_FG)
4980 xtcsetpgrp(ttyfd, pgrp);
4985 if (mode == FORK_BG) {
4986 /* man bash: "When job control is not in effect,
4987 * asynchronous commands ignore SIGINT and SIGQUIT" */
4990 if (jp->nprocs == 0) {
4992 if (open(bb_dev_null, O_RDONLY) != 0)
4993 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4997 if (iflag) { /* why if iflag only? */
5002 * "In all cases, bash ignores SIGQUIT. Non-builtin
5003 * commands run by bash have signal handlers
5004 * set to the values inherited by the shell
5006 * Take care of the second rule: */
5010 if (n && n->type == NCMD
5011 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
5013 TRACE(("Job hack\n"));
5014 /* "jobs": we do not want to clear job list for it,
5015 * instead we remove only _its_ own_ job from job list.
5016 * This makes "jobs .... | cat" more useful.
5022 for (jp = curjob; jp; jp = jp->prev_job)
5027 /* Called after fork(), in parent */
5029 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
5032 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
5034 TRACE(("In parent shell: child = %d\n", pid));
5036 /* jp is NULL when called by openhere() for heredoc support */
5037 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
5043 if (mode != FORK_NOJOB && jp->jobctl) {
5046 if (jp->nprocs == 0)
5049 pgrp = jp->ps[0].ps_pid;
5050 /* This can fail because we are doing it in the child also */
5054 if (mode == FORK_BG) {
5055 backgndpid = pid; /* set $! */
5056 set_curjob(jp, CUR_RUNNING);
5059 struct procstat *ps = &jp->ps[jp->nprocs++];
5062 ps->ps_cmd = nullstr;
5064 if (doing_jobctl && n)
5065 ps->ps_cmd = commandtext(n);
5070 /* jp and n are NULL when called by openhere() for heredoc support */
5072 forkshell(struct job *jp, union node *n, int mode)
5076 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
5079 TRACE(("Fork failed, errno=%d", errno));
5082 ash_msg_and_raise_error("can't fork");
5085 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
5086 forkchild(jp, n, mode);
5088 forkparent(jp, n, mode, pid);
5094 * Wait for job to finish.
5096 * Under job control we have the problem that while a child process
5097 * is running interrupts generated by the user are sent to the child
5098 * but not to the shell. This means that an infinite loop started by
5099 * an interactive user may be hard to kill. With job control turned off,
5100 * an interactive user may place an interactive program inside a loop.
5101 * If the interactive program catches interrupts, the user doesn't want
5102 * these interrupts to also abort the loop. The approach we take here
5103 * is to have the shell ignore interrupt signals while waiting for a
5104 * foreground process to terminate, and then send itself an interrupt
5105 * signal if the child process was terminated by an interrupt signal.
5106 * Unfortunately, some programs want to do a bit of cleanup and then
5107 * exit on interrupt; unless these processes terminate themselves by
5108 * sending a signal to themselves (instead of calling exit) they will
5109 * confuse this approach.
5111 * Called with interrupts off.
5114 waitforjob(struct job *jp)
5118 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
5121 while (jp->state == JOBRUNNING) {
5122 /* In non-interactive shells, we _can_ get
5123 * a keyboard signal here and be EINTRed,
5124 * but we just loop back, waiting for command to complete.
5127 * "If bash is waiting for a command to complete and receives
5128 * a signal for which a trap has been set, the trap
5129 * will not be executed until the command completes."
5131 * Reality is that even if trap is not set, bash
5132 * will not act on the signal until command completes.
5133 * Try this. sleep5intoff.c:
5134 * #include <signal.h>
5135 * #include <unistd.h>
5138 * sigemptyset(&set);
5139 * sigaddset(&set, SIGINT);
5140 * sigaddset(&set, SIGQUIT);
5141 * sigprocmask(SIG_BLOCK, &set, NULL);
5145 * $ bash -c './sleep5intoff; echo hi'
5146 * ^C^C^C^C <--- pressing ^C once a second
5148 * $ bash -c './sleep5intoff; echo hi'
5149 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5152 dowait(DOWAIT_BLOCK, jp);
5159 xtcsetpgrp(ttyfd, rootpid);
5160 restore_tty_if_stopped_or_signaled(jp);
5163 * This is truly gross.
5164 * If we're doing job control, then we did a TIOCSPGRP which
5165 * caused us (the shell) to no longer be in the controlling
5166 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5167 * intuit from the subprocess exit status whether a SIGINT
5168 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5170 if (jp->sigint) /* TODO: do the same with all signals */
5171 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5173 if (jp->state == JOBDONE)
5180 * return 1 if there are stopped jobs, otherwise 0
5192 if (jp && jp->state == JOBSTOPPED) {
5193 out2str("You have stopped jobs.\n");
5203 * Code for dealing with input/output redirection.
5208 #define EMPTY -2 /* marks an unused slot in redirtab */
5209 #define CLOSED -1 /* marks a slot of previously-closed fd */
5212 * Handle here documents. Normally we fork off a process to write the
5213 * data to a pipe. If the document is short, we can stuff the data in
5214 * the pipe without forking.
5216 /* openhere needs this forward reference */
5217 static void expandhere(union node *arg, int fd);
5219 openhere(union node *redir)
5225 ash_msg_and_raise_error("pipe call failed");
5226 if (redir->type == NHERE) {
5227 len = strlen(redir->nhere.doc->narg.text);
5228 if (len <= PIPE_BUF) {
5229 full_write(pip[1], redir->nhere.doc->narg.text, len);
5233 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5236 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5237 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5238 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5239 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5240 signal(SIGPIPE, SIG_DFL);
5241 if (redir->type == NHERE)
5242 full_write(pip[1], redir->nhere.doc->narg.text, len);
5244 expandhere(redir->nhere.doc, pip[1]);
5245 _exit(EXIT_SUCCESS);
5253 openredirect(union node *redir)
5259 switch (redir->nfile.type) {
5260 /* Can't happen, our single caller does this itself */
5266 return openhere(redir);
5269 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5270 * allocated space. Do it only when we know it is safe.
5272 fname = redir->nfile.expfname;
5274 switch (redir->nfile.type) {
5280 f = open(fname, O_RDONLY);
5285 f = open(fname, O_RDWR|O_CREAT, 0666);
5290 #if BASH_REDIR_OUTPUT
5293 /* Take care of noclobber mode. */
5295 if (stat(fname, &sb) < 0) {
5296 f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5299 } else if (!S_ISREG(sb.st_mode)) {
5300 f = open(fname, O_WRONLY, 0666);
5303 if (fstat(f, &sb) < 0 && S_ISREG(sb.st_mode)) {
5316 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5321 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5329 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5331 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5335 * Copy a file descriptor to be >= 10. Throws exception on error.
5343 newfd = fcntl(from, F_DUPFD, 10);
5344 err = newfd < 0 ? errno : 0;
5347 ash_msg_and_raise_perror("%d", from);
5349 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5355 dup2_or_raise(int from, int to)
5359 newfd = (from != to) ? dup2(from, to) : to;
5361 /* Happens when source fd is not open: try "echo >&99" */
5362 ash_msg_and_raise_perror("%d", from);
5367 fcntl_F_DUPFD(int fd, int avoid_fd)
5371 newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
5381 xdup_CLOEXEC_and_close(int fd, int avoid_fd)
5385 newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
5391 /* fd was not open? */
5394 ash_msg_and_raise_perror("%d", newfd);
5396 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5401 /* Struct def and variable are moved down to the first usage site */
5407 struct redirtab *next;
5409 struct squirrel two_fd[];
5411 #define redirlist (G_var.redirlist)
5414 add_squirrel_closed(struct redirtab *sq, int fd)
5421 for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5422 /* If we collide with an already moved fd... */
5423 if (fd == sq->two_fd[i].orig_fd) {
5425 * "echo 3>FILE 3>&- 3>FILE"
5426 * "echo 3>&- 3>FILE"
5427 * No need for last redirect to insert
5428 * another "need to close 3" indicator.
5430 TRACE(("redirect_fd %d: already moved or closed\n", fd));
5434 TRACE(("redirect_fd %d: previous fd was closed\n", fd));
5435 sq->two_fd[i].orig_fd = fd;
5436 sq->two_fd[i].moved_to = CLOSED;
5440 save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
5444 if (avoid_fd < 9) /* the important case here is that it can be -1 */
5449 /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
5450 ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
5451 TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
5452 return 1; /* "we closed fd" */
5455 /* Are we called from redirect(0)? E.g. redirect
5456 * in a forked child. No need to save fds,
5457 * we aren't going to use them anymore, ok to trash.
5462 /* If this one of script's fds? */
5464 struct parsefile *pf = g_parsefile;
5466 /* We skip fd == 0 case because of the following:
5467 * $ ash # running ash interactively
5469 * and in script.sh: "exec 9>&0".
5470 * Even though top-level pf_fd _is_ 0,
5471 * it's still ok to use it: "read" builtin uses it,
5472 * why should we cripple "exec" builtin?
5474 if (fd == pf->pf_fd) {
5475 pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
5476 return 1; /* "we closed fd" */
5482 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
5484 /* First: do we collide with some already moved fds? */
5485 for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5486 /* If we collide with an already moved fd... */
5487 if (fd == sq->two_fd[i].moved_to) {
5488 new_fd = fcntl_F_DUPFD(fd, avoid_fd);
5489 sq->two_fd[i].moved_to = new_fd;
5490 TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
5491 if (new_fd < 0) /* what? */
5493 return 0; /* "we did not close fd" */
5495 if (fd == sq->two_fd[i].orig_fd) {
5496 /* Example: echo Hello >/dev/null 1>&2 */
5497 TRACE(("redirect_fd %d: already moved\n", fd));
5498 return 0; /* "we did not close fd" */
5502 /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
5503 new_fd = fcntl_F_DUPFD(fd, avoid_fd);
5504 TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
5508 /* new_fd = CLOSED; - already is -1 */
5510 sq->two_fd[i].moved_to = new_fd;
5511 sq->two_fd[i].orig_fd = fd;
5513 /* if we move stderr, let "set -x" code know */
5514 if (fd == preverrout_fd)
5515 preverrout_fd = new_fd;
5517 return 0; /* "we did not close fd" */
5521 internally_opened_fd(int fd, struct redirtab *sq)
5528 /* If this one of script's fds? */
5530 struct parsefile *pf = g_parsefile;
5532 if (fd == pf->pf_fd)
5538 if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
5539 if (fd == sq->two_fd[i].moved_to)
5546 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5547 * old file descriptors are stashed away so that the redirection can be
5548 * undone by calling popredir.
5550 /* flags passed to redirect */
5551 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5553 redirect(union node *redir, int flags)
5555 struct redirtab *sv;
5562 if (flags & REDIR_PUSH)
5570 fd = redir->nfile.fd;
5571 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5572 //bb_error_msg("doing %d > %d", fd, newfd);
5573 newfd = redir->ndup.dupfd;
5576 newfd = openredirect(redir); /* always >= 0 */
5578 /* open() gave us precisely the fd we wanted.
5579 * This means that this fd was not busy
5580 * (not opened to anywhere).
5581 * Remember to close it on restore:
5583 add_squirrel_closed(sv, fd);
5592 /* if "N>FILE": move newfd to fd */
5593 /* if "N>&M": dup newfd to fd */
5594 /* if "N>&-": close fd (newfd is -1) */
5596 IF_BASH_REDIR_OUTPUT(redirect_more:)
5598 closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
5600 /* "N>&-" means "close me" */
5602 /* ^^^ optimization: saving may already
5603 * have closed it. If not... */
5607 /* if newfd is a script fd or saved fd, simulate EBADF */
5608 if (internally_opened_fd(newfd, sv)) {
5610 ash_msg_and_raise_perror("%d", newfd);
5612 dup2_or_raise(newfd, fd);
5613 if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
5615 #if BASH_REDIR_OUTPUT
5616 if (redir->nfile.type == NTO2 && fd == 1) {
5617 /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
5625 } while ((redir = redir->nfile.next) != NULL);
5628 //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
5629 #define REDIR_SAVEFD2 0
5630 // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
5631 // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
5632 // not only for calls with flags containing REDIR_SAVEFD2.
5633 // We do this unconditionally (see save_fd_on_redirect()).
5634 //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5635 // preverrout_fd = copied_fd2;
5639 redirectsafe(union node *redir, int flags)
5642 volatile int saveint;
5643 struct jmploc *volatile savehandler = exception_handler;
5644 struct jmploc jmploc;
5647 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5648 err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
5650 exception_handler = &jmploc;
5651 redirect(redir, flags);
5653 exception_handler = savehandler;
5654 if (err && exception_type != EXERROR)
5655 longjmp(exception_handler->loc, 1);
5656 RESTORE_INT(saveint);
5660 static struct redirtab*
5661 pushredir(union node *redir)
5663 struct redirtab *sv;
5672 #if BASH_REDIR_OUTPUT
5673 if (redir->nfile.type == NTO2)
5676 redir = redir->nfile.next;
5679 sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
5682 sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
5683 sv->next = redirlist;
5689 * Undo the effects of the last redirection.
5694 struct redirtab *rp;
5697 if (redirlist == NULL)
5701 for (i = 0; i < rp->pair_count; i++) {
5702 int fd = rp->two_fd[i].orig_fd;
5703 int copy = rp->two_fd[i].moved_to;
5704 if (copy == CLOSED) {
5709 if (copy != EMPTY) {
5712 dup2_or_raise(copy, fd);
5717 redirlist = rp->next;
5723 unwindredir(struct redirtab *stop)
5725 while (redirlist != stop)
5726 popredir(/*drop:*/ 0);
5730 /* ============ Routines to expand arguments to commands
5732 * We have to deal with backquotes, shell variables, and file metacharacters.
5735 #if ENABLE_FEATURE_SH_MATH
5737 ash_arith(const char *s)
5739 arith_state_t math_state;
5742 math_state.lookupvar = lookupvar;
5743 math_state.setvar = setvar0;
5744 //math_state.endofname = endofname;
5747 result = arith(&math_state, s);
5748 if (math_state.errmsg)
5749 ash_msg_and_raise_error(math_state.errmsg);
5759 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5760 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5761 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5762 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5763 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5764 * POSIX says for this case:
5765 * Pathname expansion shall not be performed on the word by a
5766 * non-interactive shell; an interactive shell may perform it, but shall
5767 * do so only when the expansion would result in one word.
5768 * Currently, our code complies to the above rule by never globbing
5769 * redirection filenames.
5770 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5771 * (this means that on a typical Linux distro, bash almost always
5772 * performs globbing, and thus diverges from what we do).
5774 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5775 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5776 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5777 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5778 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5782 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5783 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5784 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5785 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5786 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5788 /* Add CTLESC when necessary. */
5789 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT)
5790 /* Do not skip NUL characters. */
5791 #define QUOTES_KEEPNUL EXP_TILDE
5794 * Structure specifying which parts of the string should be searched
5795 * for IFS characters.
5798 struct ifsregion *next; /* next region in list */
5799 int begoff; /* offset of start of region */
5800 int endoff; /* offset of end of region */
5801 int nulonly; /* search for nul bytes only */
5805 struct strlist *list;
5806 struct strlist **lastp;
5809 /* output of current string */
5810 static char *expdest;
5811 /* list of back quote expressions */
5812 static struct nodelist *argbackq;
5813 /* first struct in list of ifs regions */
5814 static struct ifsregion ifsfirst;
5815 /* last struct in list */
5816 static struct ifsregion *ifslastp;
5817 /* holds expanded arg list */
5818 static struct arglist exparg;
5822 * cvtnum() is used even if math support is off (to prepare $? values and such).
5829 /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
5830 len = sizeof(arith_t) * 3;
5831 /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
5832 if (sizeof(arith_t) < 4) len += 2;
5834 expdest = makestrspace(len, expdest);
5835 len = fmtstr(expdest, len, ARITH_FMT, num);
5836 STADJUST(len, expdest);
5841 * Break the argument string into pieces based upon IFS and add the
5842 * strings to the argument list. The regions of the string to be
5843 * searched for IFS characters have been stored by recordregion.
5846 ifsbreakup(char *string, struct arglist *arglist)
5848 struct ifsregion *ifsp;
5853 const char *ifs, *realifs;
5858 if (ifslastp != NULL) {
5861 realifs = ifsset() ? ifsval() : defifs;
5864 p = string + ifsp->begoff;
5865 nulonly = ifsp->nulonly;
5866 ifs = nulonly ? nullstr : realifs;
5868 while (p < string + ifsp->endoff) {
5870 if ((unsigned char)*p == CTLESC)
5872 if (!strchr(ifs, *p)) {
5877 ifsspc = (strchr(defifs, *p) != NULL);
5878 /* Ignore IFS whitespace at start */
5879 if (q == start && ifsspc) {
5885 sp = stzalloc(sizeof(*sp));
5887 *arglist->lastp = sp;
5888 arglist->lastp = &sp->next;
5892 if (p >= string + ifsp->endoff) {
5896 if ((unsigned char)*p == CTLESC)
5898 if (strchr(ifs, *p) == NULL) {
5902 if (strchr(defifs, *p) == NULL) {
5917 } while (ifsp != NULL);
5926 sp = stzalloc(sizeof(*sp));
5928 *arglist->lastp = sp;
5929 arglist->lastp = &sp->next;
5935 struct ifsregion *p = ifsfirst.next;
5942 struct ifsregion *ifsp;
5947 ifsfirst.next = NULL;
5954 esclen(const char *start, const char *p)
5958 while (p > start && (unsigned char)*--p == CTLESC) {
5965 * Remove any CTLESC characters from a string.
5968 rmescapes(char *str, int flag)
5970 static const char qchars[] ALIGN1 = {
5971 IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
5975 unsigned protect_against_glob;
5977 IF_BASH_PATTERN_SUBST(unsigned slash = flag & RMESCAPE_SLASH;)
5979 p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash));
5985 if (flag & RMESCAPE_ALLOC) {
5986 size_t len = p - str;
5987 size_t fulllen = len + strlen(p) + 1;
5989 if (flag & RMESCAPE_GROW) {
5990 int strloc = str - (char *)stackblock();
5991 r = makestrspace(fulllen, expdest);
5992 /* p and str may be invalidated by makestrspace */
5993 str = (char *)stackblock() + strloc;
5995 } else if (flag & RMESCAPE_HEAP) {
5996 r = ckmalloc(fulllen);
5998 r = stalloc(fulllen);
6002 q = (char *)mempcpy(q, str, len);
6007 globbing = flag & RMESCAPE_GLOB;
6008 protect_against_glob = globbing;
6010 if ((unsigned char)*p == CTLQUOTEMARK) {
6011 // Note: both inquotes and protect_against_glob only affect whether
6012 // CTLESC,<ch> gets converted to <ch> or to \<ch>
6013 inquotes = ~inquotes;
6015 protect_against_glob = globbing;
6018 if ((unsigned char)*p == CTLESC) {
6022 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
6024 if (protect_against_glob) {
6026 * We used to trust glob() and fnmatch() to eat
6027 * superfluous escapes (\z where z has no
6028 * special meaning anyway). But this causes
6029 * bugs such as string of one greek letter rho
6030 * (unicode-encoded as two bytes "cf,81")
6031 * getting encoded as "cf,CTLESC,81"
6032 * and here, converted to "cf,\,81" -
6033 * which does not go well with some flavors
6034 * of fnmatch() in unicode locales
6035 * (for example, glibc <= 2.22).
6037 * Lets add "\" only on the chars which need it.
6038 * Testcases for less obvious chars are shown.
6043 || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
6044 || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
6045 || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
6046 || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
6047 /* Some libc support [^negate], that's why "^" also needs love */
6048 || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
6053 } else if (*p == '\\' && !inquotes) {
6054 /* naked back slash */
6055 protect_against_glob = 0;
6058 #if BASH_PATTERN_SUBST
6059 else if (*p == '/' && slash) {
6060 /* stop handling globbing and mark location of slash */
6061 globbing = slash = 0;
6065 protect_against_glob = globbing;
6070 if (flag & RMESCAPE_GROW) {
6072 STADJUST(q - r + 1, expdest);
6076 #define pmatch(a, b) !fnmatch((a), (b), 0)
6079 * Prepare a pattern for a expmeta (internal glob(3)) call.
6081 * Returns an stalloced string.
6084 preglob(const char *pattern, int flag)
6086 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
6090 * Put a string on the stack.
6093 memtodest(const char *p, size_t len, int syntax, int quotes)
6100 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
6103 unsigned char c = *p++;
6105 if (quotes & QUOTES_ESC) {
6106 int n = SIT(c, syntax);
6108 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
6115 } else if (!(quotes & QUOTES_KEEPNUL))
6124 strtodest(const char *p, int syntax, int quotes)
6126 size_t len = strlen(p);
6127 memtodest(p, len, syntax, quotes);
6132 * Record the fact that we have to scan this region of the
6133 * string for IFS characters.
6136 recordregion(int start, int end, int nulonly)
6138 struct ifsregion *ifsp;
6140 if (ifslastp == NULL) {
6144 ifsp = ckzalloc(sizeof(*ifsp));
6145 /*ifsp->next = NULL; - ckzalloc did it */
6146 ifslastp->next = ifsp;
6150 ifslastp->begoff = start;
6151 ifslastp->endoff = end;
6152 ifslastp->nulonly = nulonly;
6156 removerecordregions(int endoff)
6158 if (ifslastp == NULL)
6161 if (ifsfirst.endoff > endoff) {
6162 while (ifsfirst.next) {
6163 struct ifsregion *ifsp;
6165 ifsp = ifsfirst.next->next;
6166 free(ifsfirst.next);
6167 ifsfirst.next = ifsp;
6170 if (ifsfirst.begoff > endoff) {
6173 ifslastp = &ifsfirst;
6174 ifsfirst.endoff = endoff;
6179 ifslastp = &ifsfirst;
6180 while (ifslastp->next && ifslastp->next->begoff < endoff)
6181 ifslastp = ifslastp->next;
6182 while (ifslastp->next) {
6183 struct ifsregion *ifsp;
6185 ifsp = ifslastp->next->next;
6186 free(ifslastp->next);
6187 ifslastp->next = ifsp;
6190 if (ifslastp->endoff > endoff)
6191 ifslastp->endoff = endoff;
6195 exptilde(char *startp, char *p, int flags)
6201 int quotes = flags & QUOTES_ESC;
6205 while ((c = *++p) != '\0') {
6212 if (flags & EXP_VARTILDE)
6222 if (*name == '\0') {
6223 home = lookupvar("HOME");
6225 pw = getpwnam(name);
6230 if (!home || !*home)
6233 strtodest(home, SQSYNTAX, quotes);
6241 * Execute a command inside back quotes. If it's a builtin command, we
6242 * want to save its output in a block obtained from malloc. Otherwise
6243 * we fork off a subprocess and get the output of the command via a pipe.
6244 * Should be called with interrupts off.
6246 struct backcmd { /* result of evalbackcmd */
6247 int fd; /* file descriptor to read from */
6248 int nleft; /* number of chars in buffer */
6249 char *buf; /* buffer */
6250 struct job *jp; /* job structure for command */
6253 /* These forward decls are needed to use "eval" code for backticks handling: */
6254 /* flags in argument to evaltree */
6255 #define EV_EXIT 01 /* exit after evaluating tree */
6256 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
6257 static int evaltree(union node *, int);
6259 /* An evaltree() which is known to never return.
6260 * Used to use an alias:
6261 * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
6262 * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
6264 static ALWAYS_INLINE NORETURN void
6265 evaltreenr(union node *n, int flags)
6268 bb_unreachable(abort());
6272 static void FAST_FUNC
6273 evalbackcmd(union node *n, struct backcmd *result)
6287 ash_msg_and_raise_error("pipe call failed");
6288 jp = makejob(/*n,*/ 1);
6289 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6295 dup2_or_raise(pip[1], 1);
6298 /* TODO: eflag clearing makes the following not abort:
6299 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6300 * which is what bash does (unless it is in POSIX mode).
6301 * dash deleted "eflag = 0" line in the commit
6302 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6303 * [EVAL] Don't clear eflag in evalbackcmd
6304 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6308 evaltreenr(n, EV_EXIT);
6313 result->fd = pip[0];
6317 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6318 result->fd, result->buf, result->nleft, result->jp));
6322 * Expand stuff in backwards quotes.
6325 expbackq(union node *cmd, int flag)
6333 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6334 struct stackmark smark;
6337 startloc = expdest - (char *)stackblock();
6338 pushstackmark(&smark, startloc);
6339 evalbackcmd(cmd, &in);
6340 popstackmark(&smark);
6347 memtodest(p, i, syntax, flag & QUOTES_ESC);
6351 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6352 TRACE(("expbackq: read returns %d\n", i));
6361 back_exitstatus = waitforjob(in.jp);
6365 /* Eat all trailing newlines */
6367 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6371 if (!(flag & EXP_QUOTED))
6372 recordregion(startloc, dest - (char *)stackblock(), 0);
6373 TRACE(("evalbackq: size:%d:'%.*s'\n",
6374 (int)((dest - (char *)stackblock()) - startloc),
6375 (int)((dest - (char *)stackblock()) - startloc),
6376 stackblock() + startloc));
6379 #if ENABLE_FEATURE_SH_MATH
6381 * Expand arithmetic expression. Backup to start of expression,
6382 * evaluate, place result in (backed up) result, adjust string position.
6394 * This routine is slightly over-complicated for
6395 * efficiency. Next we scan backwards looking for the
6396 * start of arithmetic.
6398 start = stackblock();
6405 while ((unsigned char)*p != CTLARI) {
6409 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6414 esc = esclen(start, p);
6424 removerecordregions(begoff);
6428 if (flag & QUOTES_ESC)
6429 rmescapes(p + 1, 0);
6431 len = cvtnum(ash_arith(p + 1));
6433 if (!(flag & EXP_QUOTED))
6434 recordregion(begoff, begoff + len, 0);
6438 /* argstr needs it */
6439 static char *evalvar(char *p, int flags);
6442 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6443 * characters to allow for further processing. Otherwise treat
6444 * $@ like $* since no splitting will be performed.
6447 argstr(char *p, int flags)
6449 static const char spclchars[] ALIGN1 = {
6457 #if ENABLE_FEATURE_SH_MATH
6462 const char *reject = spclchars;
6463 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6468 if (!(flags & EXP_VARTILDE)) {
6470 } else if (flags & EXP_VARTILDE2) {
6475 if (flags & EXP_TILDE) {
6478 flags &= ~EXP_TILDE;
6482 p = exptilde(p, q, flags);
6485 startloc = expdest - (char *)stackblock();
6489 length += strcspn(p + length, reject);
6493 IF_FEATURE_SH_MATH(|| c == CTLENDARI)
6495 /* c == '=' || c == ':' || c == CTLENDARI */
6501 expdest = stack_nputstr(p, length, expdest);
6502 newloc = expdest - (char *)stackblock();
6503 if (breakall && !inquotes && newloc > startloc) {
6504 recordregion(startloc, newloc, 0);
6515 if (flags & EXP_VARTILDE2) {
6519 flags |= EXP_VARTILDE2;
6524 * sort of a hack - expand tildes in variable
6525 * assignments (after the first '=' and after ':'s).
6534 case CTLENDVAR: /* ??? */
6537 inquotes ^= EXP_QUOTED;
6538 /* "$@" syntax adherence hack */
6539 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6540 p = evalvar(p + 1, flags | inquotes) + 1;
6544 if (flags & QUOTES_ESC) {
6555 * Quoted parameter expansion pattern: remove quote
6556 * unless inside inner quotes or we have a literal
6559 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6560 EXP_QPAT && *p != '\\')
6565 TRACE(("argstr: evalvar('%s')\n", p));
6566 p = evalvar(p, flags | inquotes);
6567 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6570 expbackq(argbackq->n, flags | inquotes);
6571 argbackq = argbackq->next;
6573 #if ENABLE_FEATURE_SH_MATH
6576 expari(flags | inquotes);
6585 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6586 char *pattern, int quotes, int zero)
6595 const char *s = loc2;
6602 match = pmatch(pattern, s);
6607 if (quotes && (unsigned char)*loc == CTLESC)
6616 scanright(char *startp, char *rmesc, char *rmescend,
6617 char *pattern, int quotes, int match_at_start)
6619 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6620 int try2optimize = match_at_start;
6626 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6627 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6628 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6630 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6631 * and on each iteration they go back two/one char until they reach the beginning.
6632 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6634 /* TODO: document in what other circumstances we are called. */
6636 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6639 const char *s = loc2;
6640 if (match_at_start) {
6644 match = pmatch(pattern, s);
6645 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6649 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6651 /* Maybe we can optimize this:
6652 * if pattern ends with unescaped *, we can avoid checking
6653 * shorter strings: if "foo*" doesn't match "raw_value_of_v",
6654 * it won't match truncated "raw_value_of_" strings too.
6656 unsigned plen = strlen(pattern);
6657 /* Does it end with "*"? */
6658 if (plen != 0 && pattern[--plen] == '*') {
6659 /* "xxxx*" is not escaped */
6660 /* "xxx\*" is escaped */
6661 /* "xx\\*" is not escaped */
6662 /* "x\\\*" is escaped */
6664 while (plen != 0 && pattern[--plen] == '\\')
6667 break; /* ends with unescaped "*" */
6675 esc = esclen(startp, loc);
6686 static void varunset(const char *, const char *, const char *, int) NORETURN;
6688 varunset(const char *end, const char *var, const char *umsg, int varflags)
6694 msg = "parameter not set";
6696 if ((unsigned char)*end == CTLENDVAR) {
6697 if (varflags & VSNUL)
6703 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6707 subevalvar(char *p, char *varname, int strloc, int subtype,
6708 int startloc, int varflags, int flag)
6710 struct nodelist *saveargbackq = argbackq;
6711 int quotes = flag & QUOTES_ESC;
6714 char *rmesc, *rmescend;
6716 int amount, resetloc;
6717 IF_BASH_PATTERN_SUBST(int workloc;)
6718 IF_BASH_PATTERN_SUBST(char *repl = NULL;)
6720 char *(*scan)(char*, char*, char*, char*, int, int);
6722 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6723 // p, varname, strloc, subtype, startloc, varflags, quotes);
6725 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6726 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0)
6728 STPUTC('\0', expdest);
6729 argbackq = saveargbackq;
6730 startp = (char *)stackblock() + startloc;
6734 setvar0(varname, startp);
6735 amount = startp - expdest;
6736 STADJUST(amount, expdest);
6740 varunset(p, varname, startp, varflags);
6745 int pos, len, orig_len;
6748 loc = str = stackblock() + strloc;
6750 # if !ENABLE_FEATURE_SH_MATH
6751 # define ash_arith number
6753 /* Read POS in ${var:POS:LEN} */
6754 colon = strchr(loc, ':');
6755 if (colon) *colon = '\0';
6756 pos = ash_arith(loc);
6757 if (colon) *colon = ':';
6759 /* Read LEN in ${var:POS:LEN} */
6760 len = str - startp - 1;
6761 /* *loc != '\0', guaranteed by parser */
6765 /* Adjust the length by the number of escapes */
6766 for (ptr = startp; ptr < (str - 1); ptr++) {
6767 if ((unsigned char)*ptr == CTLESC) {
6774 if (*loc++ == ':') {
6776 len = ash_arith(loc);
6778 /* Skip POS in ${var:POS:LEN} */
6780 while (*loc && *loc != ':') {
6783 if (*loc++ == ':') {
6784 len = ash_arith(loc);
6790 /* ${VAR:$((-n)):l} starts n chars from the end */
6791 pos = orig_len + pos;
6793 if ((unsigned)pos >= orig_len) {
6794 /* apart from obvious ${VAR:999999:l},
6795 * covers ${VAR:$((-9999999)):l} - result is ""
6802 /* ${VAR:N:-M} sets LEN to strlen()-M */
6803 len = (orig_len - pos) + len;
6805 if ((unsigned)len > (orig_len - pos))
6806 len = orig_len - pos;
6808 for (str = startp; pos; str++, pos--) {
6809 if (quotes && (unsigned char)*str == CTLESC)
6812 for (loc = startp; len; len--) {
6813 if (quotes && (unsigned char)*str == CTLESC)
6818 amount = loc - expdest;
6819 STADJUST(amount, expdest);
6822 #endif /* BASH_SUBSTR */
6825 resetloc = expdest - (char *)stackblock();
6827 #if BASH_PATTERN_SUBST
6828 /* We'll comeback here if we grow the stack while handling
6829 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6830 * stack will need rebasing, and we'll need to remove our work
6836 amount = expdest - ((char *)stackblock() + resetloc);
6837 STADJUST(-amount, expdest);
6838 startp = (char *)stackblock() + startloc;
6841 rmescend = (char *)stackblock() + strloc;
6843 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6844 if (rmesc != startp) {
6846 startp = (char *)stackblock() + startloc;
6850 str = (char *)stackblock() + strloc;
6852 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6853 * The result is a_\_z_c (not a\_\_z_c)!
6855 * The search pattern and replace string treat backslashes differently!
6856 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6857 * and string. It's only used on the first call.
6859 preglob(str, IF_BASH_PATTERN_SUBST(
6860 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6861 RMESCAPE_SLASH : ) 0);
6863 #if BASH_PATTERN_SUBST
6864 workloc = expdest - (char *)stackblock();
6865 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6870 repl = strchr(str, CTLESC);
6876 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6878 /* If there's no pattern to match, return the expansion unmolested */
6887 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6888 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6890 /* No match, advance */
6891 char *restart_detect = stackblock();
6893 STPUTC(*idx, expdest);
6894 if (quotes && (unsigned char)*idx == CTLESC) {
6897 STPUTC(*idx, expdest);
6899 if (stackblock() != restart_detect)
6904 /* continue; - prone to quadratic behavior, smarter code: */
6907 if (str[0] == '*') {
6908 /* Pattern is "*foo". If "*foo" does not match "long_string",
6909 * it would never match "ong_string" etc, no point in trying.
6916 if (subtype == VSREPLACEALL) {
6918 if (quotes && (unsigned char)*idx == CTLESC)
6927 //bb_error_msg("repl:'%s'", repl);
6928 for (loc = (char*)repl; *loc; loc++) {
6929 char *restart_detect = stackblock();
6930 if (quotes && *loc == '\\') {
6931 STPUTC(CTLESC, expdest);
6934 STPUTC(*loc, expdest);
6935 if (stackblock() != restart_detect)
6940 if (subtype == VSREPLACE) {
6941 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6943 char *restart_detect = stackblock();
6944 STPUTC(*idx, expdest);
6945 if (stackblock() != restart_detect)
6954 /* We've put the replaced text into a buffer at workloc, now
6955 * move it to the right place and adjust the stack.
6957 STPUTC('\0', expdest);
6958 startp = (char *)stackblock() + startloc;
6959 memmove(startp, (char *)stackblock() + workloc, len + 1);
6960 //bb_error_msg("startp:'%s'", startp);
6961 amount = expdest - (startp + len);
6962 STADJUST(-amount, expdest);
6965 #endif /* BASH_PATTERN_SUBST */
6967 subtype -= VSTRIMRIGHT;
6969 if (subtype < 0 || subtype > 7)
6972 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6973 zero = subtype >> 1;
6974 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6975 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6977 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6980 memmove(startp, loc, str - loc);
6981 loc = startp + (str - loc) - 1;
6984 amount = loc - expdest;
6985 STADJUST(amount, expdest);
6991 * Add the value of a specialized variable to the stack string.
6992 * name parameter (examples):
6993 * ash -c 'echo $1' name:'1='
6994 * ash -c 'echo $qwe' name:'qwe='
6995 * ash -c 'echo $$' name:'$='
6996 * ash -c 'echo ${$}' name:'$='
6997 * ash -c 'echo ${$##q}' name:'$=q'
6998 * ash -c 'echo ${#$}' name:'$='
6999 * note: examples with bad shell syntax:
7000 * ash -c 'echo ${#$1}' name:'$=1'
7001 * ash -c 'echo ${#1#}' name:'1=#'
7003 static NOINLINE ssize_t
7004 varvalue(char *name, int varflags, int flags, int *quotedp)
7011 int quoted = *quotedp;
7012 int subtype = varflags & VSTYPE;
7013 int discard = subtype == VSPLUS || subtype == VSLENGTH;
7014 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
7017 sep = (flags & EXP_FULL) << CHAR_BIT;
7018 syntax = quoted ? DQSYNTAX : BASESYNTAX;
7028 num = shellparam.nparam;
7036 goto check_1char_name;
7038 expdest = makestrspace(NOPTS, expdest);
7039 for (i = NOPTS - 1; i >= 0; i--) {
7041 USTPUTC(optletters(i), expdest);
7047 /* handles cases similar to ${#$1} */
7048 if (name[2] != '\0')
7049 raise_error_syntax("bad substitution");
7062 sep |= ifsset() ? ifsval()[0] : ' ';
7069 while ((p = *ap++) != NULL) {
7070 len += strtodest(p, syntax, quotes);
7074 memtodest(&sepc, 1, syntax, quotes);
7089 num = atoi(name); /* number(name) fails on ${N#str} etc */
7090 if (num < 0 || num > shellparam.nparam)
7092 p = num ? shellparam.p[num - 1] : arg0;
7095 /* NB: name has form "VAR=..." */
7096 p = lookupvar(name);
7101 len = strtodest(p, syntax, quotes);
7102 #if ENABLE_UNICODE_SUPPORT
7103 if (subtype == VSLENGTH && len > 0) {
7104 reinit_unicode_for_ash();
7105 if (unicode_status == UNICODE_ON) {
7106 STADJUST(-len, expdest);
7108 len = unicode_strlen(p);
7116 STADJUST(-len, expdest);
7121 * Expand a variable, and return a pointer to the next character in the
7125 evalvar(char *p, int flag)
7136 varflags = (unsigned char) *p++;
7137 subtype = varflags & VSTYPE;
7140 raise_error_syntax("bad substitution");
7142 quoted = flag & EXP_QUOTED;
7144 easy = (!quoted || (*var == '@' && shellparam.nparam));
7145 startloc = expdest - (char *)stackblock();
7146 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
7149 varlen = varvalue(var, varflags, flag, "ed);
7150 if (varflags & VSNUL)
7153 if (subtype == VSPLUS) {
7154 varlen = -1 - varlen;
7158 if (subtype == VSMINUS) {
7163 flag | EXP_TILDE | EXP_WORD
7170 if (subtype == VSASSIGN || subtype == VSQUESTION) {
7174 subevalvar(p, var, 0, subtype, startloc, varflags,
7175 flag & ~QUOTES_ESC);
7178 * Remove any recorded regions beyond
7181 removerecordregions(startloc);
7185 if (varlen < 0 && uflag)
7186 varunset(p, var, 0, 0);
7188 if (subtype == VSLENGTH) {
7189 cvtnum(varlen > 0 ? varlen : 0);
7193 if (subtype == VSNORMAL) {
7197 recordregion(startloc, expdest - (char *)stackblock(), quoted);
7206 case VSTRIMRIGHTMAX:
7210 #if BASH_PATTERN_SUBST
7222 * Terminate the string and start recording the pattern
7225 STPUTC('\0', expdest);
7226 patloc = expdest - (char *)stackblock();
7227 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7228 startloc, varflags, flag)) {
7229 int amount = expdest - (
7230 (char *)stackblock() + patloc - 1
7232 STADJUST(-amount, expdest);
7234 /* Remove any recorded regions beyond start of variable */
7235 removerecordregions(startloc);
7240 if (subtype != VSNORMAL) { /* skip to end of alternative */
7243 unsigned char c = *p++;
7246 else if (c == CTLBACKQ) {
7248 argbackq = argbackq->next;
7249 } else if (c == CTLVAR) {
7250 if ((*p++ & VSTYPE) != VSNORMAL)
7252 } else if (c == CTLENDVAR) {
7262 * Add a file name to the list.
7265 addfname(const char *name)
7269 sp = stzalloc(sizeof(*sp));
7270 sp->text = sstrdup(name);
7272 exparg.lastp = &sp->next;
7275 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7277 hasmeta(const char *p)
7279 static const char chars[] ALIGN1 = {
7280 '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
7284 p = strpbrk(p, chars);
7287 switch ((unsigned char) *p) {
7291 if (*p == CTLQUOTEMARK)
7295 if (*p == '\0') /* huh? */
7306 if (!strchr(p + 1, ']')) {
7307 /* It's not a properly closed [] pattern,
7308 * but other metas may follow. Continue checking.
7309 * my[file* _is_ globbed by bash
7310 * and matches filenames like "my[file1".
7326 /* If we want to use glob() from libc... */
7327 #if !ENABLE_ASH_INTERNAL_GLOB
7329 /* Add the result of glob() to the list */
7331 addglob(const glob_t *pglob)
7333 char **p = pglob->gl_pathv;
7340 expandmeta(struct strlist *str /*, int flag*/)
7342 /* TODO - EXP_REDIR */
7352 if (!hasmeta(str->text))
7356 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7357 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7358 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7360 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7361 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7362 // Which means you need to unescape the string, right? Not so fast:
7363 // if there _is_ a file named "file\?" (with backslash), it is returned
7364 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7365 // You DON'T KNOW by looking at the result whether you need to unescape it.
7367 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7368 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7369 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7370 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7371 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7372 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7373 i = glob(p, 0, NULL, &pglob);
7374 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7379 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7380 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7381 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7393 *exparg.lastp = str;
7394 rmescapes(str->text, 0);
7395 exparg.lastp = &str->next;
7397 default: /* GLOB_NOSPACE */
7400 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7407 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7410 * Do metacharacter (i.e. *, ?, [...]) expansion.
7413 expmeta(char *expdir, char *enddir, char *name)
7429 for (p = name; esc = 0, *p; p += esc + 1) {
7430 if (*p == '*' || *p == '?')
7432 else if (*p == '[') {
7439 if (*q == '/' || *q == '\0')
7449 if (p[esc] == '/') {
7452 start = p + esc + 1;
7456 if (metaflag == 0) { /* we've reached the end of the file name */
7457 if (enddir != expdir)
7465 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7476 } while (p < start);
7478 if (enddir == expdir) {
7480 } else if (enddir == expdir + 1 && *expdir == '/') {
7489 if (enddir != expdir)
7491 if (*endname == 0) {
7504 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7505 if (dp->d_name[0] == '.' && !matchdot)
7507 if (pmatch(start, dp->d_name)) {
7509 strcpy(enddir, dp->d_name);
7512 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7515 expmeta(expdir, p, endname);
7521 endname[-esc - 1] = esc ? '\\' : '/';
7524 static struct strlist *
7525 msort(struct strlist *list, int len)
7527 struct strlist *p, *q = NULL;
7528 struct strlist **lpp;
7536 for (n = half; --n >= 0;) {
7540 q->next = NULL; /* terminate first half of list */
7541 q = msort(list, half); /* sort first half of list */
7542 p = msort(p, len - half); /* sort second half */
7545 #if ENABLE_LOCALE_SUPPORT
7546 if (strcoll(p->text, q->text) < 0)
7548 if (strcmp(p->text, q->text) < 0)
7572 * Sort the results of file name expansion. It calculates the number of
7573 * strings to sort and then calls msort (short for merge sort) to do the
7576 static struct strlist *
7577 expsort(struct strlist *str)
7583 for (sp = str; sp; sp = sp->next)
7585 return msort(str, len);
7589 expandmeta(struct strlist *str /*, int flag*/)
7591 /* TODO - EXP_REDIR */
7595 struct strlist **savelastp;
7601 if (!hasmeta(str->text))
7603 savelastp = exparg.lastp;
7606 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7608 int i = strlen(str->text);
7609 //BUGGY estimation of how long expanded name can be
7610 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7612 expmeta(expdir, expdir, p);
7617 if (exparg.lastp == savelastp) {
7622 *exparg.lastp = str;
7623 rmescapes(str->text, 0);
7624 exparg.lastp = &str->next;
7626 *exparg.lastp = NULL;
7627 *savelastp = sp = expsort(*savelastp);
7628 while (sp->next != NULL)
7630 exparg.lastp = &sp->next;
7635 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7638 * Perform variable substitution and command substitution on an argument,
7639 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7640 * perform splitting and file name expansion. When arglist is NULL, perform
7641 * here document expansion.
7644 expandarg(union node *arg, struct arglist *arglist, int flag)
7649 argbackq = arg->narg.backquote;
7650 STARTSTACKSTR(expdest);
7651 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7652 argstr(arg->narg.text, flag);
7653 p = _STPUTC('\0', expdest);
7655 if (arglist == NULL) {
7656 /* here document expanded */
7659 p = grabstackstr(p);
7660 TRACE(("expandarg: p:'%s'\n", p));
7661 exparg.lastp = &exparg.list;
7665 if (flag & EXP_FULL) {
7666 ifsbreakup(p, &exparg);
7667 *exparg.lastp = NULL;
7668 exparg.lastp = &exparg.list;
7669 expandmeta(exparg.list /*, flag*/);
7671 sp = stzalloc(sizeof(*sp));
7674 exparg.lastp = &sp->next;
7676 *exparg.lastp = NULL;
7678 *arglist->lastp = exparg.list;
7679 arglist->lastp = exparg.lastp;
7687 * Expand shell variables and backquotes inside a here document.
7690 expandhere(union node *arg, int fd)
7692 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7693 full_write(fd, stackblock(), expdest - (char *)stackblock());
7697 * Returns true if the pattern matches the string.
7700 patmatch(char *pattern, const char *string)
7702 char *p = preglob(pattern, 0);
7703 //bb_error_msg("fnmatch(pattern:'%s',str:'%s')", p, string);
7704 return pmatch(p, string);
7708 * See if a pattern matches in a case statement.
7711 casematch(union node *pattern, char *val)
7713 struct stackmark smark;
7716 setstackmark(&smark);
7717 argbackq = pattern->narg.backquote;
7718 STARTSTACKSTR(expdest);
7719 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
7720 STACKSTRNUL(expdest);
7722 result = patmatch(stackblock(), val);
7723 popstackmark(&smark);
7728 /* ============ find_command */
7732 int (*builtin)(int, char **) FAST_FUNC;
7733 /* unsigned flags; */
7735 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7736 /* "regular" builtins always take precedence over commands,
7737 * regardless of PATH=....%builtin... position */
7738 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7739 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7742 smallint cmdtype; /* CMDxxx */
7745 /* index >= 0 for commands without path (slashes) */
7746 /* (TODO: what exactly does the value mean? PATH position?) */
7747 /* index == -1 for commands with slashes */
7748 /* index == (-2 - applet_no) for NOFORK applets */
7749 const struct builtincmd *cmd;
7750 struct funcnode *func;
7753 /* values of cmdtype */
7754 #define CMDUNKNOWN -1 /* no entry in table for command */
7755 #define CMDNORMAL 0 /* command is an executable program */
7756 #define CMDFUNCTION 1 /* command is a shell function */
7757 #define CMDBUILTIN 2 /* command is a shell builtin */
7759 /* action to find_command() */
7760 #define DO_ERR 0x01 /* prints errors */
7761 #define DO_ABS 0x02 /* checks absolute paths */
7762 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7763 #define DO_ALTPATH 0x08 /* using alternate path */
7764 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7766 static void find_command(char *, struct cmdentry *, int, const char *);
7769 /* ============ Hashing commands */
7772 * When commands are first encountered, they are entered in a hash table.
7773 * This ensures that a full path search will not have to be done for them
7774 * on each invocation.
7776 * We should investigate converting to a linear search, even though that
7777 * would make the command name "hash" a misnomer.
7781 struct tblentry *next; /* next entry in hash chain */
7782 union param param; /* definition of builtin function */
7783 smallint cmdtype; /* CMDxxx */
7784 char rehash; /* if set, cd done since entry created */
7785 char cmdname[1]; /* name of command */
7788 static struct tblentry **cmdtable;
7789 #define INIT_G_cmdtable() do { \
7790 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7793 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7797 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
7799 #if ENABLE_FEATURE_SH_STANDALONE
7800 if (applet_no >= 0) {
7801 if (APPLET_IS_NOEXEC(applet_no)) {
7805 popredir(/*drop:*/ 1);
7806 //TODO: prctl(PR_SET_NAME, (long)argv[0], 0, 0, 0);? [think pidof, pgrep, pkill]
7807 //Rewrite /proc/PID/cmdline? (need to save argv0 and length at init for this to work!)
7808 run_applet_no_and_exit(applet_no, cmd, argv);
7810 /* re-exec ourselves with the new arguments */
7811 execve(bb_busybox_exec_path, argv, envp);
7812 /* If they called chroot or otherwise made the binary no longer
7813 * executable, fall through */
7820 execve(cmd, argv, envp);
7821 } while (errno == EINTR);
7823 execve(cmd, argv, envp);
7825 if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
7826 /* Run "cmd" as a shell script:
7827 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7828 * "If the execve() function fails with ENOEXEC, the shell
7829 * shall execute a command equivalent to having a shell invoked
7830 * with the command name as its first operand,
7831 * with any remaining arguments passed to the new shell"
7833 * That is, do not use $SHELL, user's shell, or /bin/sh;
7834 * just call ourselves.
7836 * Note that bash reads ~80 chars of the file, and if it sees
7837 * a zero byte before it sees newline, it doesn't try to
7838 * interpret it, but fails with "cannot execute binary file"
7839 * message and exit code 126. For one, this prevents attempts
7840 * to interpret foreign ELF binaries as shell scripts.
7842 argv[0] = (char*) cmd;
7843 cmd = bb_busybox_exec_path;
7844 /* NB: this is only possible because all callers of shellexec()
7845 * ensure that the argv[-1] slot exists!
7848 argv[0] = (char*) "ash";
7854 * Exec a program. Never returns. If you change this routine, you may
7855 * have to change the find_command routine as well.
7856 * argv[-1] must exist and be writable! See tryexec() for why.
7858 static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
7859 static void shellexec(char *prog, char **argv, const char *path, int idx)
7865 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7867 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7868 if (strchr(prog, '/') != NULL
7869 #if ENABLE_FEATURE_SH_STANDALONE
7870 || (applet_no = find_applet_by_name(prog)) >= 0
7873 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
7874 if (applet_no >= 0) {
7875 /* We tried execing ourself, but it didn't work.
7876 * Maybe /proc/self/exe doesn't exist?
7885 while ((cmdname = path_advance(&path, prog)) != NULL) {
7886 if (--idx < 0 && pathopt == NULL) {
7887 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7888 if (errno != ENOENT && errno != ENOTDIR)
7895 /* Map to POSIX errors */
7907 exitstatus = exerrno;
7908 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7909 prog, e, suppress_int));
7910 ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
7915 printentry(struct tblentry *cmdp)
7921 idx = cmdp->param.index;
7924 name = path_advance(&path, cmdp->cmdname);
7926 } while (--idx >= 0);
7927 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7931 * Clear out command entries. The argument specifies the first entry in
7932 * PATH which has changed.
7935 clearcmdentry(int firstchange)
7937 struct tblentry **tblp;
7938 struct tblentry **pp;
7939 struct tblentry *cmdp;
7942 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7944 while ((cmdp = *pp) != NULL) {
7945 if ((cmdp->cmdtype == CMDNORMAL &&
7946 cmdp->param.index >= firstchange)
7947 || (cmdp->cmdtype == CMDBUILTIN &&
7948 builtinloc >= firstchange)
7961 * Locate a command in the command hash table. If "add" is nonzero,
7962 * add the command to the table if it is not already present. The
7963 * variable "lastcmdentry" is set to point to the address of the link
7964 * pointing to the entry, so that delete_cmd_entry can delete the
7967 * Interrupts must be off if called with add != 0.
7969 static struct tblentry **lastcmdentry;
7971 static struct tblentry *
7972 cmdlookup(const char *name, int add)
7974 unsigned int hashval;
7976 struct tblentry *cmdp;
7977 struct tblentry **pp;
7980 hashval = (unsigned char)*p << 4;
7982 hashval += (unsigned char)*p++;
7984 pp = &cmdtable[hashval % CMDTABLESIZE];
7985 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7986 if (strcmp(cmdp->cmdname, name) == 0)
7990 if (add && cmdp == NULL) {
7991 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7993 /* + 1 - already done because
7994 * tblentry::cmdname is char[1] */);
7995 /*cmdp->next = NULL; - ckzalloc did it */
7996 cmdp->cmdtype = CMDUNKNOWN;
7997 strcpy(cmdp->cmdname, name);
8004 * Delete the command entry returned on the last lookup.
8007 delete_cmd_entry(void)
8009 struct tblentry *cmdp;
8012 cmdp = *lastcmdentry;
8013 *lastcmdentry = cmdp->next;
8014 if (cmdp->cmdtype == CMDFUNCTION)
8015 freefunc(cmdp->param.func);
8021 * Add a new command entry, replacing any existing command entry for
8022 * the same name - except special builtins.
8025 addcmdentry(char *name, struct cmdentry *entry)
8027 struct tblentry *cmdp;
8029 cmdp = cmdlookup(name, 1);
8030 if (cmdp->cmdtype == CMDFUNCTION) {
8031 freefunc(cmdp->param.func);
8033 cmdp->cmdtype = entry->cmdtype;
8034 cmdp->param = entry->u;
8038 static int FAST_FUNC
8039 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8041 struct tblentry **pp;
8042 struct tblentry *cmdp;
8044 struct cmdentry entry;
8047 if (nextopt("r") != '\0') {
8052 if (*argptr == NULL) {
8053 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8054 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8055 if (cmdp->cmdtype == CMDNORMAL)
8063 while ((name = *argptr) != NULL) {
8064 cmdp = cmdlookup(name, 0);
8066 && (cmdp->cmdtype == CMDNORMAL
8067 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
8071 find_command(name, &entry, DO_ERR, pathval());
8072 if (entry.cmdtype == CMDUNKNOWN)
8080 * Called when a cd is done. Marks all commands so the next time they
8081 * are executed they will be rehashed.
8086 struct tblentry **pp;
8087 struct tblentry *cmdp;
8089 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8090 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8091 if (cmdp->cmdtype == CMDNORMAL
8092 || (cmdp->cmdtype == CMDBUILTIN
8093 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
8103 * Fix command hash table when PATH changed.
8104 * Called before PATH is changed. The argument is the new value of PATH;
8105 * pathval() still returns the old value at this point.
8106 * Called with interrupts off.
8108 static void FAST_FUNC
8109 changepath(const char *new)
8117 firstchange = 9999; /* assume no change */
8123 if ((*old == '\0' && *new == ':')
8124 || (*old == ':' && *new == '\0')
8128 old = new; /* ignore subsequent differences */
8132 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
8139 if (builtinloc < 0 && idx_bltin >= 0)
8140 builtinloc = idx_bltin; /* zap builtins */
8141 if (builtinloc >= 0 && idx_bltin < 0)
8143 clearcmdentry(firstchange);
8144 builtinloc = idx_bltin;
8180 typedef smallint token_id_t;
8182 /* Nth bit indicates if token marks the end of a list */
8185 /* 0 */ | (1u << TEOF)
8186 /* 1 */ | (0u << TNL)
8187 /* 2 */ | (0u << TREDIR)
8188 /* 3 */ | (0u << TWORD)
8189 /* 4 */ | (0u << TSEMI)
8190 /* 5 */ | (0u << TBACKGND)
8191 /* 6 */ | (0u << TAND)
8192 /* 7 */ | (0u << TOR)
8193 /* 8 */ | (0u << TPIPE)
8194 /* 9 */ | (0u << TLP)
8195 /* 10 */ | (1u << TRP)
8196 /* 11 */ | (1u << TENDCASE)
8197 /* 12 */ | (1u << TENDBQUOTE)
8198 /* 13 */ | (0u << TNOT)
8199 /* 14 */ | (0u << TCASE)
8200 /* 15 */ | (1u << TDO)
8201 /* 16 */ | (1u << TDONE)
8202 /* 17 */ | (1u << TELIF)
8203 /* 18 */ | (1u << TELSE)
8204 /* 19 */ | (1u << TESAC)
8205 /* 20 */ | (1u << TFI)
8206 /* 21 */ | (0u << TFOR)
8208 /* 22 */ | (0u << TFUNCTION)
8210 /* 23 */ | (0u << TIF)
8211 /* 24 */ | (0u << TIN)
8212 /* 25 */ | (1u << TTHEN)
8213 /* 26 */ | (0u << TUNTIL)
8214 /* 27 */ | (0u << TWHILE)
8215 /* 28 */ | (0u << TBEGIN)
8216 /* 29 */ | (1u << TEND)
8217 , /* thus far 29 bits used */
8220 static const char *const tokname_array[] = {
8234 #define KWDOFFSET 13
8235 /* the following are keywords */
8257 /* Wrapper around strcmp for qsort/bsearch/... */
8259 pstrcmp(const void *a, const void *b)
8261 return strcmp((char*)a, *(char**)b);
8264 static const char *const *
8265 findkwd(const char *s)
8267 return bsearch(s, tokname_array + KWDOFFSET,
8268 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8269 sizeof(tokname_array[0]), pstrcmp);
8273 * Locate and print what a word is...
8276 describe_command(char *command, const char *path, int describe_command_verbose)
8278 struct cmdentry entry;
8279 #if ENABLE_ASH_ALIAS
8280 const struct alias *ap;
8283 path = path ? path : pathval();
8285 if (describe_command_verbose) {
8289 /* First look at the keywords */
8290 if (findkwd(command)) {
8291 out1str(describe_command_verbose ? " is a shell keyword" : command);
8295 #if ENABLE_ASH_ALIAS
8296 /* Then look at the aliases */
8297 ap = lookupalias(command, 0);
8299 if (!describe_command_verbose) {
8304 out1fmt(" is an alias for %s", ap->val);
8309 find_command(command, &entry, DO_ABS, path);
8311 switch (entry.cmdtype) {
8313 int j = entry.u.index;
8319 p = path_advance(&path, command);
8323 if (describe_command_verbose) {
8324 out1fmt(" is %s", p);
8332 if (describe_command_verbose) {
8333 out1str(" is a shell function");
8340 if (describe_command_verbose) {
8341 out1fmt(" is a %sshell builtin",
8342 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8343 "special " : nullstr
8351 if (describe_command_verbose) {
8352 out1str(": not found\n");
8361 static int FAST_FUNC
8362 typecmd(int argc UNUSED_PARAM, char **argv)
8368 /* type -p ... ? (we don't bother checking for 'p') */
8369 if (argv[1] && argv[1][0] == '-') {
8374 err |= describe_command(argv[i++], NULL, verbose);
8379 #if ENABLE_ASH_CMDCMD
8380 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8382 parse_command_args(char **argv, const char **path)
8395 if (c == '-' && !*cp) {
8403 *path = bb_default_path;
8406 /* run 'typecmd' for other options */
8415 static int FAST_FUNC
8416 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8424 const char *path = NULL;
8426 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8427 * never reaches this function.
8430 while ((c = nextopt("pvV")) != '\0')
8432 verify |= VERIFY_VERBOSE;
8434 /*verify |= VERIFY_BRIEF*/;
8440 path = bb_default_path;
8442 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8444 if (/*verify && */ cmd)
8445 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8452 /*static int funcblocksize; // size of structures in function */
8453 /*static int funcstringsize; // size of strings in node */
8454 static void *funcblock; /* block to allocate function from */
8455 static char *funcstring_end; /* end of block to allocate strings from */
8457 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8458 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8459 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8460 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8461 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8462 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8463 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8464 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8465 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8466 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8467 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8468 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8469 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8470 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8471 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8472 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8473 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8474 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8475 #if BASH_REDIR_OUTPUT
8476 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8478 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8479 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8480 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8481 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8482 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8483 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8484 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8485 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8486 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8489 static int calcsize(int funcblocksize, union node *n);
8492 sizenodelist(int funcblocksize, struct nodelist *lp)
8495 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8496 funcblocksize = calcsize(funcblocksize, lp->n);
8499 return funcblocksize;
8503 calcsize(int funcblocksize, union node *n)
8506 return funcblocksize;
8507 funcblocksize += nodesize[n->type];
8510 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8511 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8512 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8515 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8520 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8521 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8528 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8529 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8532 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8533 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8534 funcblocksize = calcsize(funcblocksize, n->nif.test);
8537 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8538 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8539 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8542 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8543 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8546 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8547 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8548 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8552 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8553 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8554 funcblocksize = calcsize(funcblocksize, n->narg.next);
8557 #if BASH_REDIR_OUTPUT
8564 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8565 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8569 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8570 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8574 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8575 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8578 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8581 return funcblocksize;
8585 nodeckstrdup(char *s)
8587 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8588 return strcpy(funcstring_end, s);
8591 static union node *copynode(union node *);
8593 static struct nodelist *
8594 copynodelist(struct nodelist *lp)
8596 struct nodelist *start;
8597 struct nodelist **lpp;
8602 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8603 (*lpp)->n = copynode(lp->n);
8605 lpp = &(*lpp)->next;
8612 copynode(union node *n)
8619 funcblock = (char *) funcblock + nodesize[n->type];
8623 new->ncmd.redirect = copynode(n->ncmd.redirect);
8624 new->ncmd.args = copynode(n->ncmd.args);
8625 new->ncmd.assign = copynode(n->ncmd.assign);
8628 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8629 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8634 new->nredir.redirect = copynode(n->nredir.redirect);
8635 new->nredir.n = copynode(n->nredir.n);
8642 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8643 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8646 new->nif.elsepart = copynode(n->nif.elsepart);
8647 new->nif.ifpart = copynode(n->nif.ifpart);
8648 new->nif.test = copynode(n->nif.test);
8651 new->nfor.var = nodeckstrdup(n->nfor.var);
8652 new->nfor.body = copynode(n->nfor.body);
8653 new->nfor.args = copynode(n->nfor.args);
8656 new->ncase.cases = copynode(n->ncase.cases);
8657 new->ncase.expr = copynode(n->ncase.expr);
8660 new->nclist.body = copynode(n->nclist.body);
8661 new->nclist.pattern = copynode(n->nclist.pattern);
8662 new->nclist.next = copynode(n->nclist.next);
8666 new->narg.backquote = copynodelist(n->narg.backquote);
8667 new->narg.text = nodeckstrdup(n->narg.text);
8668 new->narg.next = copynode(n->narg.next);
8671 #if BASH_REDIR_OUTPUT
8678 new->nfile.fname = copynode(n->nfile.fname);
8679 new->nfile.fd = n->nfile.fd;
8680 new->nfile.next = copynode(n->nfile.next);
8684 new->ndup.vname = copynode(n->ndup.vname);
8685 new->ndup.dupfd = n->ndup.dupfd;
8686 new->ndup.fd = n->ndup.fd;
8687 new->ndup.next = copynode(n->ndup.next);
8691 new->nhere.doc = copynode(n->nhere.doc);
8692 new->nhere.fd = n->nhere.fd;
8693 new->nhere.next = copynode(n->nhere.next);
8696 new->nnot.com = copynode(n->nnot.com);
8699 new->type = n->type;
8704 * Make a copy of a parse tree.
8706 static struct funcnode *
8707 copyfunc(union node *n)
8712 /*funcstringsize = 0;*/
8713 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8714 f = ckzalloc(blocksize /* + funcstringsize */);
8715 funcblock = (char *) f + offsetof(struct funcnode, n);
8716 funcstring_end = (char *) f + blocksize;
8718 /* f->count = 0; - ckzalloc did it */
8723 * Define a shell function.
8726 defun(union node *func)
8728 struct cmdentry entry;
8731 entry.cmdtype = CMDFUNCTION;
8732 entry.u.func = copyfunc(func);
8733 addcmdentry(func->narg.text, &entry);
8737 /* Reasons for skipping commands (see comment on breakcmd routine) */
8738 #define SKIPBREAK (1 << 0)
8739 #define SKIPCONT (1 << 1)
8740 #define SKIPFUNC (1 << 2)
8741 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8742 static int skipcount; /* number of levels to skip */
8743 static int funcnest; /* depth of function calls */
8744 static int loopnest; /* current loop nesting level */
8746 /* Forward decl way out to parsing code - dotrap needs it */
8747 static int evalstring(char *s, int flags);
8749 /* Called to execute a trap.
8750 * Single callsite - at the end of evaltree().
8751 * If we return non-zero, evaltree raises EXEXIT exception.
8753 * Perhaps we should avoid entering new trap handlers
8754 * while we are executing a trap handler. [is it a TODO?]
8761 uint8_t last_status;
8766 last_status = exitstatus;
8770 TRACE(("dotrap entered\n"));
8771 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8783 /* non-trapped SIGINT is handled separately by raise_interrupt,
8784 * don't upset it by resetting gotsig[SIGINT-1] */
8785 if (sig == SIGINT && !p)
8788 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8794 exitstatus = last_status;
8795 TRACE(("dotrap returns\n"));
8798 /* forward declarations - evaluation is fairly recursive business... */
8799 static int evalloop(union node *, int);
8800 static int evalfor(union node *, int);
8801 static int evalcase(union node *, int);
8802 static int evalsubshell(union node *, int);
8803 static void expredir(union node *);
8804 static int evalpipe(union node *, int);
8805 static int evalcommand(union node *, int);
8806 static int evalbltin(const struct builtincmd *, int, char **, int);
8807 static void prehash(union node *);
8810 * Evaluate a parse tree. The value is left in the global variable
8814 evaltree(union node *n, int flags)
8817 int (*evalfn)(union node *, int);
8821 TRACE(("evaltree(NULL) called\n"));
8824 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8831 out1fmt("Node type = %d\n", n->type);
8836 status = !evaltree(n->nnot.com, EV_TESTED);
8839 expredir(n->nredir.redirect);
8840 pushredir(n->nredir.redirect);
8841 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8843 status = evaltree(n->nredir.n, flags & EV_TESTED);
8845 if (n->nredir.redirect)
8846 popredir(/*drop:*/ 0);
8849 evalfn = evalcommand;
8851 if (eflag && !(flags & EV_TESTED))
8863 evalfn = evalsubshell;
8876 #error NAND + 1 != NOR
8878 #if NOR + 1 != NSEMI
8879 #error NOR + 1 != NSEMI
8881 unsigned is_or = n->type - NAND;
8884 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8886 if ((!status) == is_or || evalskip)
8892 status = evalfn(n, flags);
8896 status = evaltree(n->nif.test, EV_TESTED);
8903 if (n->nif.elsepart) {
8904 n = n->nif.elsepart;
8911 /* Not necessary. To test it:
8912 * "false; f() { qwerty; }; echo $?" should print 0.
8916 exitstatus = status;
8920 /* Order of checks below is important:
8921 * signal handlers trigger before exit caused by "set -e".
8925 if (checkexit & status)
8926 raise_exception(EXEXIT);
8927 if (flags & EV_EXIT)
8928 raise_exception(EXEXIT);
8930 TRACE(("leaving evaltree (no interrupts)\n"));
8937 int skip = evalskip;
8944 if (--skipcount <= 0) {
8955 evalloop(union node *n, int flags)
8966 i = evaltree(n->nbinary.ch1, EV_TESTED);
8968 if (skip == SKIPFUNC)
8972 if (n->type != NWHILE)
8976 status = evaltree(n->nbinary.ch2, flags);
8978 } while (!(skip & ~SKIPCONT));
8985 evalfor(union node *n, int flags)
8987 struct arglist arglist;
8990 struct stackmark smark;
8993 setstackmark(&smark);
8994 arglist.list = NULL;
8995 arglist.lastp = &arglist.list;
8996 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8997 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8999 *arglist.lastp = NULL;
9003 for (sp = arglist.list; sp; sp = sp->next) {
9004 setvar0(n->nfor.var, sp->text);
9005 status = evaltree(n->nfor.body, flags);
9006 if (skiploop() & ~SKIPCONT)
9010 popstackmark(&smark);
9016 evalcase(union node *n, int flags)
9020 struct arglist arglist;
9021 struct stackmark smark;
9024 setstackmark(&smark);
9025 arglist.list = NULL;
9026 arglist.lastp = &arglist.list;
9027 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
9028 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
9029 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
9030 if (casematch(patp, arglist.list->text)) {
9031 /* Ensure body is non-empty as otherwise
9032 * EV_EXIT may prevent us from setting the
9035 if (evalskip == 0 && cp->nclist.body) {
9036 status = evaltree(cp->nclist.body, flags);
9043 popstackmark(&smark);
9049 * Kick off a subshell to evaluate a tree.
9052 evalsubshell(union node *n, int flags)
9055 int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
9058 expredir(n->nredir.redirect);
9059 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
9062 if (backgnd == FORK_FG)
9064 jp = makejob(/*n,*/ 1);
9065 if (forkshell(jp, n, backgnd) == 0) {
9070 flags &= ~EV_TESTED;
9072 redirect(n->nredir.redirect, 0);
9073 evaltreenr(n->nredir.n, flags);
9078 if (backgnd == FORK_FG)
9079 status = waitforjob(jp);
9085 * Compute the names of the files in a redirection list.
9087 static void fixredir(union node *, const char *, int);
9089 expredir(union node *n)
9093 for (redir = n; redir; redir = redir->nfile.next) {
9097 fn.lastp = &fn.list;
9098 switch (redir->type) {
9102 #if BASH_REDIR_OUTPUT
9107 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
9108 TRACE(("expredir expanded to '%s'\n", fn.list->text));
9109 #if BASH_REDIR_OUTPUT
9113 // By the design of stack allocator, the loop of this kind:
9114 // while true; do while true; do break; done </dev/null; done
9115 // will look like a memory leak: ash plans to free expfname's
9116 // of "/dev/null" as soon as it finishes running the loop
9117 // (in this case, never).
9118 // This "fix" is wrong:
9119 if (redir->nfile.expfname)
9120 stunalloc(redir->nfile.expfname);
9121 // It results in corrupted state of stacked allocations.
9123 redir->nfile.expfname = fn.list->text;
9126 case NTOFD: /* >& */
9127 if (redir->ndup.vname) {
9128 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
9129 if (fn.list == NULL)
9130 ash_msg_and_raise_error("redir error");
9131 #if BASH_REDIR_OUTPUT
9132 //FIXME: we used expandarg with different args!
9133 if (!isdigit_str9(fn.list->text)) {
9134 /* >&file, not >&fd */
9135 if (redir->nfile.fd != 1) /* 123>&file - BAD */
9136 ash_msg_and_raise_error("redir error");
9138 goto store_expfname;
9141 fixredir(redir, fn.list->text, 1);
9149 * Evaluate a pipeline. All the processes in the pipeline are children
9150 * of the process creating the pipeline. (This differs from some versions
9151 * of the shell, which make the last process in a pipeline the parent
9155 evalpipe(union node *n, int flags)
9158 struct nodelist *lp;
9164 TRACE(("evalpipe(0x%lx) called\n", (long)n));
9166 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
9170 if (n->npipe.pipe_backgnd == 0)
9172 jp = makejob(/*n,*/ pipelen);
9174 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
9178 if (pipe(pip) < 0) {
9180 ash_msg_and_raise_error("pipe call failed");
9183 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
9197 evaltreenr(lp->n, flags);
9204 /* Don't want to trigger debugging */
9208 if (n->npipe.pipe_backgnd == 0) {
9209 status = waitforjob(jp);
9210 TRACE(("evalpipe: job done exit status %d\n", status));
9218 * Controls whether the shell is interactive or not.
9221 setinteractive(int on)
9223 static smallint is_interactive;
9225 if (++on == is_interactive)
9227 is_interactive = on;
9231 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9232 if (is_interactive > 1) {
9233 /* Looks like they want an interactive shell */
9234 static smallint did_banner;
9237 /* note: ash and hush share this string */
9238 out1fmt("\n\n%s %s\n"
9239 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9242 "built-in shell (ash)"
9256 setinteractive(iflag);
9258 #if ENABLE_FEATURE_EDITING_VI
9260 line_input_state->flags |= VI_MODE;
9262 line_input_state->flags &= ~VI_MODE;
9264 viflag = 0; /* forcibly keep the option off */
9268 struct localvar_list {
9269 struct localvar_list *next;
9270 struct localvar *lv;
9273 static struct localvar_list *localvar_stack;
9276 * Called after a function returns.
9277 * Interrupts must be off.
9280 poplocalvars(int keep)
9282 struct localvar_list *ll;
9283 struct localvar *lvp, *next;
9287 ll = localvar_stack;
9288 localvar_stack = ll->next;
9293 while ((lvp = next) != NULL) {
9296 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9298 int bits = VSTRFIXED;
9300 if (lvp->flags != VUNSET) {
9301 if (vp->var_text == lvp->text)
9303 else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
9304 free((char*)lvp->text);
9308 vp->flags |= (lvp->flags & bits);
9311 (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
9312 unsetvar(vp->var_text);
9313 } else if (vp == NULL) { /* $- saved */
9314 memcpy(optlist, lvp->text, sizeof(optlist));
9315 free((char*)lvp->text);
9317 } else if (lvp->flags == VUNSET) {
9318 vp->flags &= ~(VSTRFIXED|VREADONLY);
9319 unsetvar(vp->var_text);
9322 vp->var_func(var_end(lvp->text));
9323 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9324 free((char*)vp->var_text);
9325 vp->flags = lvp->flags;
9326 vp->var_text = lvp->text;
9334 * Create a new localvar environment.
9336 static struct localvar_list *
9339 struct localvar_list *ll;
9342 ll = ckzalloc(sizeof(*ll));
9343 /*ll->lv = NULL; - zalloc did it */
9344 ll->next = localvar_stack;
9345 localvar_stack = ll;
9352 unwindlocalvars(struct localvar_list *stop)
9354 while (localvar_stack != stop)
9359 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9361 volatile struct shparam saveparam;
9362 struct jmploc *volatile savehandler;
9363 struct jmploc jmploc;
9366 saveparam = shellparam;
9367 savehandler = exception_handler;
9368 e = setjmp(jmploc.loc);
9373 exception_handler = &jmploc;
9374 shellparam.malloced = 0;
9378 shellparam.nparam = argc - 1;
9379 shellparam.p = argv + 1;
9380 #if ENABLE_ASH_GETOPTS
9381 shellparam.optind = 1;
9382 shellparam.optoff = -1;
9385 evaltree(func->n.narg.next, flags & EV_TESTED);
9391 freeparam(&shellparam);
9392 shellparam = saveparam;
9393 exception_handler = savehandler;
9395 evalskip &= ~SKIPFUNC;
9400 * Make a variable a local variable. When a variable is made local, it's
9401 * value and flags are saved in a localvar structure. The saved values
9402 * will be restored when the shell function returns. We handle the name
9403 * "-" as a special case: it makes changes to "set +-options" local
9404 * (options will be restored on return from the function).
9409 struct localvar *lvp;
9412 char *eq = strchr(name, '=');
9415 /* Cater for duplicate "local". Examples:
9416 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9417 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9419 lvp = localvar_stack->lv;
9421 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9425 * it's a duplicate "local VAR" declaration, do nothing
9432 lvp = ckzalloc(sizeof(*lvp));
9433 if (LONE_DASH(name)) {
9435 p = ckmalloc(sizeof(optlist));
9436 lvp->text = memcpy(p, optlist, sizeof(optlist));
9439 vpp = hashvar(name);
9440 vp = *findvar(vpp, name);
9442 /* variable did not exist yet */
9444 vp = setvareq(name, VSTRFIXED);
9446 vp = setvar(name, NULL, VSTRFIXED);
9447 lvp->flags = VUNSET;
9449 lvp->text = vp->var_text;
9450 lvp->flags = vp->flags;
9451 /* make sure neither "struct var" nor string gets freed
9452 * during (un)setting:
9454 vp->flags |= VSTRFIXED|VTEXTFIXED;
9458 /* "local VAR" unsets VAR: */
9459 setvar0(name, NULL);
9463 lvp->next = localvar_stack->lv;
9464 localvar_stack->lv = lvp;
9470 * The "local" command.
9472 static int FAST_FUNC
9473 localcmd(int argc UNUSED_PARAM, char **argv)
9477 if (!localvar_stack)
9478 ash_msg_and_raise_error("not in a function");
9481 while ((name = *argv++) != NULL) {
9487 static int FAST_FUNC
9488 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9493 static int FAST_FUNC
9494 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9499 static int FAST_FUNC
9500 execcmd(int argc UNUSED_PARAM, char **argv)
9503 while (nextopt("a:") != '\0')
9504 /* nextopt() sets optionarg to "-a ARGV0" */;
9510 iflag = 0; /* exit on error */
9513 /* We should set up signals for "exec CMD"
9514 * the same way as for "CMD" without "exec".
9515 * But optschanged->setinteractive->setsignal
9516 * still thought we are a root shell. Therefore, for example,
9517 * SIGQUIT is still set to IGN. Fix it:
9521 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9522 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9523 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9527 argv[0] = optionarg;
9528 shellexec(prog, argv, pathval(), 0);
9535 * The return command.
9537 static int FAST_FUNC
9538 returncmd(int argc UNUSED_PARAM, char **argv)
9541 * If called outside a function, do what ksh does;
9542 * skip the rest of the file.
9544 evalskip = SKIPFUNC;
9545 return argv[1] ? number(argv[1]) : exitstatus;
9548 /* Forward declarations for builtintab[] */
9549 static int breakcmd(int, char **) FAST_FUNC;
9550 static int dotcmd(int, char **) FAST_FUNC;
9551 static int evalcmd(int, char **, int) FAST_FUNC;
9552 static int exitcmd(int, char **) FAST_FUNC;
9553 static int exportcmd(int, char **) FAST_FUNC;
9554 #if ENABLE_ASH_GETOPTS
9555 static int getoptscmd(int, char **) FAST_FUNC;
9558 static int helpcmd(int, char **) FAST_FUNC;
9561 static int historycmd(int, char **) FAST_FUNC;
9563 #if ENABLE_FEATURE_SH_MATH
9564 static int letcmd(int, char **) FAST_FUNC;
9566 static int readcmd(int, char **) FAST_FUNC;
9567 static int setcmd(int, char **) FAST_FUNC;
9568 static int shiftcmd(int, char **) FAST_FUNC;
9569 static int timescmd(int, char **) FAST_FUNC;
9570 static int trapcmd(int, char **) FAST_FUNC;
9571 static int umaskcmd(int, char **) FAST_FUNC;
9572 static int unsetcmd(int, char **) FAST_FUNC;
9573 static int ulimitcmd(int, char **) FAST_FUNC;
9575 #define BUILTIN_NOSPEC "0"
9576 #define BUILTIN_SPECIAL "1"
9577 #define BUILTIN_REGULAR "2"
9578 #define BUILTIN_SPEC_REG "3"
9579 #define BUILTIN_ASSIGN "4"
9580 #define BUILTIN_SPEC_ASSG "5"
9581 #define BUILTIN_REG_ASSG "6"
9582 #define BUILTIN_SPEC_REG_ASSG "7"
9584 /* Stubs for calling non-FAST_FUNC's */
9586 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9588 #if ENABLE_ASH_PRINTF
9589 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9591 #if ENABLE_ASH_TEST || BASH_TEST2
9592 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9595 /* Keep these in proper order since it is searched via bsearch() */
9596 static const struct builtincmd builtintab[] = {
9597 { BUILTIN_SPEC_REG "." , dotcmd },
9598 { BUILTIN_SPEC_REG ":" , truecmd },
9600 { BUILTIN_REGULAR "[" , testcmd },
9603 { BUILTIN_REGULAR "[[" , testcmd },
9605 #if ENABLE_ASH_ALIAS
9606 { BUILTIN_REG_ASSG "alias" , aliascmd },
9609 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9611 { BUILTIN_SPEC_REG "break" , breakcmd },
9612 { BUILTIN_REGULAR "cd" , cdcmd },
9613 { BUILTIN_NOSPEC "chdir" , cdcmd },
9614 #if ENABLE_ASH_CMDCMD
9615 { BUILTIN_REGULAR "command" , commandcmd },
9617 { BUILTIN_SPEC_REG "continue", breakcmd },
9619 { BUILTIN_REGULAR "echo" , echocmd },
9621 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9622 { BUILTIN_SPEC_REG "exec" , execcmd },
9623 { BUILTIN_SPEC_REG "exit" , exitcmd },
9624 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9625 { BUILTIN_REGULAR "false" , falsecmd },
9627 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9629 #if ENABLE_ASH_GETOPTS
9630 { BUILTIN_REGULAR "getopts" , getoptscmd },
9632 { BUILTIN_NOSPEC "hash" , hashcmd },
9634 { BUILTIN_NOSPEC "help" , helpcmd },
9637 { BUILTIN_NOSPEC "history" , historycmd },
9640 { BUILTIN_REGULAR "jobs" , jobscmd },
9641 { BUILTIN_REGULAR "kill" , killcmd },
9643 #if ENABLE_FEATURE_SH_MATH
9644 { BUILTIN_NOSPEC "let" , letcmd },
9646 { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
9647 #if ENABLE_ASH_PRINTF
9648 { BUILTIN_REGULAR "printf" , printfcmd },
9650 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9651 { BUILTIN_REGULAR "read" , readcmd },
9652 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9653 { BUILTIN_SPEC_REG "return" , returncmd },
9654 { BUILTIN_SPEC_REG "set" , setcmd },
9655 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9657 { BUILTIN_SPEC_REG "source" , dotcmd },
9660 { BUILTIN_REGULAR "test" , testcmd },
9662 { BUILTIN_SPEC_REG "times" , timescmd },
9663 { BUILTIN_SPEC_REG "trap" , trapcmd },
9664 { BUILTIN_REGULAR "true" , truecmd },
9665 { BUILTIN_NOSPEC "type" , typecmd },
9666 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9667 { BUILTIN_REGULAR "umask" , umaskcmd },
9668 #if ENABLE_ASH_ALIAS
9669 { BUILTIN_REGULAR "unalias" , unaliascmd },
9671 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9672 { BUILTIN_REGULAR "wait" , waitcmd },
9675 /* Should match the above table! */
9676 #define COMMANDCMD (builtintab + \
9678 /* [ */ 1 * ENABLE_ASH_TEST + \
9679 /* [[ */ 1 * BASH_TEST2 + \
9680 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9681 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9682 /* break cd cddir */ 3)
9683 #define EVALCMD (COMMANDCMD + \
9684 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9685 /* continue */ 1 + \
9686 /* echo */ 1 * ENABLE_ASH_ECHO + \
9688 #define EXECCMD (EVALCMD + \
9692 * Search the table of builtin commands.
9695 pstrcmp1(const void *a, const void *b)
9697 return strcmp((char*)a, *(char**)b + 1);
9699 static struct builtincmd *
9700 find_builtin(const char *name)
9702 struct builtincmd *bp;
9705 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9712 * Execute a simple command.
9715 isassignment(const char *p)
9717 const char *q = endofname(p);
9722 static int FAST_FUNC
9723 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9725 /* Preserve exitstatus of a previous possible redirection
9726 * as POSIX mandates */
9727 return back_exitstatus;
9730 evalcommand(union node *cmd, int flags)
9732 static const struct builtincmd null_bltin = {
9733 "\0\0", bltincmd /* why three NULs? */
9735 struct localvar_list *localvar_stop;
9736 struct redirtab *redir_stop;
9737 struct stackmark smark;
9739 struct arglist arglist;
9740 struct arglist varlist;
9743 const struct strlist *sp;
9744 struct cmdentry cmdentry;
9751 smallint cmd_is_exec;
9753 /* First expand the arguments. */
9754 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9755 setstackmark(&smark);
9756 localvar_stop = pushlocalvars();
9757 back_exitstatus = 0;
9759 cmdentry.cmdtype = CMDBUILTIN;
9760 cmdentry.u.cmd = &null_bltin;
9761 varlist.lastp = &varlist.list;
9762 *varlist.lastp = NULL;
9763 arglist.lastp = &arglist.list;
9764 *arglist.lastp = NULL;
9767 if (cmd->ncmd.args) {
9768 struct builtincmd *bcmd;
9769 smallint pseudovarflag;
9771 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9772 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9774 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9775 struct strlist **spp;
9777 spp = arglist.lastp;
9778 if (pseudovarflag && isassignment(argp->narg.text))
9779 expandarg(argp, &arglist, EXP_VARTILDE);
9781 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9783 for (sp = *spp; sp; sp = sp->next)
9788 /* Reserve one extra spot at the front for shellexec. */
9789 nargv = stalloc(sizeof(char *) * (argc + 2));
9791 for (sp = arglist.list; sp; sp = sp->next) {
9792 TRACE(("evalcommand arg: %s\n", sp->text));
9793 *nargv++ = sp->text;
9798 if (iflag && funcnest == 0 && argc > 0)
9799 lastarg = nargv[-1];
9801 expredir(cmd->ncmd.redirect);
9802 redir_stop = pushredir(cmd->ncmd.redirect);
9804 if (BASH_XTRACEFD && xflag) {
9805 /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
9806 * we do not emulate this. We only use its value.
9808 const char *xtracefd = lookupvar("BASH_XTRACEFD");
9809 if (xtracefd && is_number(xtracefd))
9810 preverrout_fd = atoi(xtracefd);
9813 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9815 path = vpath.var_text;
9816 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9817 struct strlist **spp;
9820 spp = varlist.lastp;
9821 expandarg(argp, &varlist, EXP_VARTILDE);
9823 mklocal((*spp)->text);
9826 * Modify the command lookup path, if a PATH= assignment
9830 if (varcmp(p, path) == 0)
9834 /* Print the command if xflag is set. */
9836 const char *pfx = "";
9838 fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
9842 char *varval = sp->text;
9843 char *eq = strchrnul(varval, '=');
9846 fdprintf(preverrout_fd, "%s%.*s%s",
9848 (int)(eq - varval), varval,
9849 maybe_single_quote(eq)
9857 fdprintf(preverrout_fd, "%s%s",
9859 /* always quote if matches reserved word: */
9861 ? single_quote(sp->text)
9862 : maybe_single_quote(sp->text)
9867 safe_write(preverrout_fd, "\n", 1);
9873 /* Now locate the command. */
9875 int cmd_flag = DO_ERR;
9876 #if ENABLE_ASH_CMDCMD
9877 const char *oldpath = path + 5;
9881 find_command(argv[0], &cmdentry, cmd_flag, path);
9882 if (cmdentry.cmdtype == CMDUNKNOWN) {
9883 flush_stdout_stderr();
9888 /* implement bltin and command here */
9889 if (cmdentry.cmdtype != CMDBUILTIN)
9892 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9893 if (cmdentry.u.cmd == EXECCMD)
9895 #if ENABLE_ASH_CMDCMD
9896 if (cmdentry.u.cmd == COMMANDCMD) {
9898 nargv = parse_command_args(argv, &path);
9901 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9902 * nargv => "PROG". path is updated if -p.
9904 argc -= nargv - argv;
9906 cmd_flag |= DO_NOFUNC;
9915 exitstatus = status;
9917 /* We have a redirection error. */
9919 raise_exception(EXERROR);
9924 /* Execute the command. */
9925 switch (cmdentry.cmdtype) {
9928 #if ENABLE_FEATURE_SH_NOFORK
9929 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9930 * around run_nofork_applet() call.
9931 * (2) Should this check also be done in forkshell()?
9932 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9934 /* find_command() encodes applet_no as (-2 - applet_no) */
9935 int applet_no = (- cmdentry.u.index - 2);
9936 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9937 listsetvar(varlist.list, VEXPORT|VSTACK);
9939 * Run <applet>_main().
9940 * Signals (^C) can't interrupt here.
9941 * Otherwise we can mangle stdio or malloc internal state.
9942 * This makes applets which can run for a long time
9943 * and/or wait for user input ineligible for NOFORK:
9944 * for example, "yes" or "rm" (rm -i waits for input).
9947 status = run_nofork_applet(applet_no, argv);
9949 * Try enabling NOFORK for "yes" applet.
9950 * ^C _will_ stop it (write returns EINTR),
9951 * but this causes stdout FILE to be stuck
9952 * and needing clearerr(). What if other applets
9953 * also can get EINTRs? Do we need to switch
9954 * our signals to SA_RESTART?
9956 /*clearerr(stdout);*/
9961 /* Can we avoid forking? For example, very last command
9962 * in a script or a subshell does not need forking,
9963 * we can just exec it.
9965 if (!(flags & EV_EXIT) || may_have_traps) {
9966 /* No, forking off a child is necessary */
9969 jp = makejob(/*cmd,*/ 1);
9970 if (forkshell(jp, cmd, FORK_FG) != 0) {
9972 status = waitforjob(jp);
9974 TRACE(("forked child exited with %d\n", status));
9979 /* fall through to exec'ing external program */
9981 listsetvar(varlist.list, VEXPORT|VSTACK);
9982 shellexec(argv[0], argv, path, cmdentry.u.index);
9986 if (spclbltin > 0 || argc == 0) {
9988 if (cmd_is_exec && argc > 1)
9989 listsetvar(varlist.list, VEXPORT);
9992 /* Tight loop with builtins only:
9993 * "while kill -0 $child; do true; done"
9994 * will never exit even if $child died, unless we do this
9995 * to reap the zombie and make kill detect that it's gone: */
9996 dowait(DOWAIT_NONBLOCK, NULL);
9998 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9999 if (exception_type == EXERROR && spclbltin <= 0) {
10004 longjmp(exception_handler->loc, 1);
10010 /* See above for the rationale */
10011 dowait(DOWAIT_NONBLOCK, NULL);
10012 if (evalfun(cmdentry.u.func, argc, argv, flags))
10015 status = exitstatus;
10020 if (cmd->ncmd.redirect)
10021 popredir(/*drop:*/ cmd_is_exec);
10022 unwindredir(redir_stop);
10023 unwindlocalvars(localvar_stop);
10025 /* dsl: I think this is intended to be used to support
10026 * '_' in 'vi' command mode during line editing...
10027 * However I implemented that within libedit itself.
10029 setvar0("_", lastarg);
10031 popstackmark(&smark);
10037 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
10039 char *volatile savecmdname;
10040 struct jmploc *volatile savehandler;
10041 struct jmploc jmploc;
10045 savecmdname = commandname;
10046 savehandler = exception_handler;
10047 i = setjmp(jmploc.loc);
10050 exception_handler = &jmploc;
10051 commandname = argv[0];
10053 optptr = NULL; /* initialize nextopt */
10054 if (cmd == EVALCMD)
10055 status = evalcmd(argc, argv, flags);
10057 status = (*cmd->builtin)(argc, argv);
10058 flush_stdout_stderr();
10059 status |= ferror(stdout);
10060 exitstatus = status;
10063 commandname = savecmdname;
10064 exception_handler = savehandler;
10070 goodname(const char *p)
10072 return endofname(p)[0] == '\0';
10077 * Search for a command. This is called before we fork so that the
10078 * location of the command will be available in the parent as well as
10079 * the child. The check for "goodname" is an overly conservative
10080 * check that the name will not be subject to expansion.
10083 prehash(union node *n)
10085 struct cmdentry entry;
10087 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
10088 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
10092 /* ============ Builtin commands
10094 * Builtin commands whose functions are closely tied to evaluation
10095 * are implemented here.
10099 * Handle break and continue commands. Break, continue, and return are
10100 * all handled by setting the evalskip flag. The evaluation routines
10101 * above all check this flag, and if it is set they start skipping
10102 * commands rather than executing them. The variable skipcount is
10103 * the number of loops to break/continue, or the number of function
10104 * levels to return. (The latter is always 1.) It should probably
10105 * be an error to break out of more loops than exist, but it isn't
10106 * in the standard shell so we don't make it one here.
10108 static int FAST_FUNC
10109 breakcmd(int argc UNUSED_PARAM, char **argv)
10111 int n = argv[1] ? number(argv[1]) : 1;
10114 ash_msg_and_raise_error(msg_illnum, argv[1]);
10118 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
10126 * This implements the input routines used by the parser.
10130 INPUT_PUSH_FILE = 1,
10131 INPUT_NOFILE_OK = 2,
10134 static smallint checkkwd;
10135 /* values of checkkwd variable */
10136 #define CHKALIAS 0x1
10139 #define CHKEOFMARK 0x8
10142 * Push a string back onto the input at this current parsefile level.
10143 * We handle aliases this way.
10145 #if !ENABLE_ASH_ALIAS
10146 #define pushstring(s, ap) pushstring(s)
10149 pushstring(char *s, struct alias *ap)
10151 struct strpush *sp;
10156 if (g_parsefile->strpush) {
10157 sp = ckzalloc(sizeof(*sp));
10158 sp->prev = g_parsefile->strpush;
10160 sp = &(g_parsefile->basestrpush);
10162 g_parsefile->strpush = sp;
10163 sp->prev_string = g_parsefile->next_to_pgetc;
10164 sp->prev_left_in_line = g_parsefile->left_in_line;
10165 sp->unget = g_parsefile->unget;
10166 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
10167 #if ENABLE_ASH_ALIAS
10170 ap->flag |= ALIASINUSE;
10174 g_parsefile->next_to_pgetc = s;
10175 g_parsefile->left_in_line = len;
10176 g_parsefile->unget = 0;
10183 struct strpush *sp = g_parsefile->strpush;
10186 #if ENABLE_ASH_ALIAS
10188 if (g_parsefile->next_to_pgetc[-1] == ' '
10189 || g_parsefile->next_to_pgetc[-1] == '\t'
10191 checkkwd |= CHKALIAS;
10193 if (sp->string != sp->ap->val) {
10196 sp->ap->flag &= ~ALIASINUSE;
10197 if (sp->ap->flag & ALIASDEAD) {
10198 unalias(sp->ap->name);
10202 g_parsefile->next_to_pgetc = sp->prev_string;
10203 g_parsefile->left_in_line = sp->prev_left_in_line;
10204 g_parsefile->unget = sp->unget;
10205 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
10206 g_parsefile->strpush = sp->prev;
10207 if (sp != &(g_parsefile->basestrpush))
10216 char *buf = g_parsefile->buf;
10218 g_parsefile->next_to_pgetc = buf;
10219 #if ENABLE_FEATURE_EDITING
10221 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
10222 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10224 # if ENABLE_ASH_IDLE_TIMEOUT
10227 const char *tmout_var = lookupvar("TMOUT");
10229 timeout = atoi(tmout_var) * 1000;
10234 line_input_state->timeout = timeout;
10236 # if ENABLE_FEATURE_TAB_COMPLETION
10237 line_input_state->path_lookup = pathval();
10239 reinit_unicode_for_ash();
10240 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
10242 /* ^C pressed, "convert" to SIGINT */
10243 write(STDOUT_FILENO, "^C", 2);
10244 if (trap[SIGINT]) {
10250 exitstatus = 128 + SIGINT;
10256 /* Ctrl+D pressed */
10259 # if ENABLE_ASH_IDLE_TIMEOUT
10260 else if (errno == EAGAIN && timeout > 0) {
10261 puts("\007timed out waiting for input: auto-logout");
10268 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10271 #if 0 /* disabled: nonblock_immune_read() handles this problem */
10273 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
10274 int flags = fcntl(0, F_GETFL);
10275 if (flags >= 0 && (flags & O_NONBLOCK)) {
10276 flags &= ~O_NONBLOCK;
10277 if (fcntl(0, F_SETFL, flags) >= 0) {
10278 out2str("sh: turning off NDELAY mode\n");
10289 * Refill the input buffer and return the next input character:
10291 * 1) If a string was pushed back on the input, pop it;
10292 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
10293 * or we are reading from a string so we can't refill the buffer,
10295 * 3) If there is more stuff in this buffer, use it else call read to fill it.
10296 * 4) Process input up to the next newline, deleting nul characters.
10298 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
10299 #define pgetc_debug(...) ((void)0)
10300 static int pgetc(void);
10307 if (g_parsefile->strpush) {
10308 #if ENABLE_ASH_ALIAS
10309 if (g_parsefile->left_in_line == -1
10310 && g_parsefile->strpush->ap
10311 && g_parsefile->next_to_pgetc[-1] != ' '
10312 && g_parsefile->next_to_pgetc[-1] != '\t'
10314 pgetc_debug("preadbuffer PEOA");
10321 /* on both branches above g_parsefile->left_in_line < 0.
10322 * "pgetc" needs refilling.
10325 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
10326 * pungetc() may increment it a few times.
10327 * Assuming it won't increment it to less than -90.
10329 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
10330 pgetc_debug("preadbuffer PEOF1");
10331 /* even in failure keep left_in_line and next_to_pgetc
10332 * in lock step, for correct multi-layer pungetc.
10333 * left_in_line was decremented before preadbuffer(),
10334 * must inc next_to_pgetc: */
10335 g_parsefile->next_to_pgetc++;
10339 more = g_parsefile->left_in_buffer;
10341 flush_stdout_stderr();
10345 /* don't try reading again */
10346 g_parsefile->left_in_line = -99;
10347 pgetc_debug("preadbuffer PEOF2");
10348 g_parsefile->next_to_pgetc++;
10353 /* Find out where's the end of line.
10354 * Set g_parsefile->left_in_line
10355 * and g_parsefile->left_in_buffer acordingly.
10356 * NUL chars are deleted.
10358 q = g_parsefile->next_to_pgetc;
10366 memmove(q, q + 1, more);
10370 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10376 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10377 if (g_parsefile->left_in_line < 0)
10382 g_parsefile->left_in_buffer = more;
10387 out2str(g_parsefile->next_to_pgetc);
10391 pgetc_debug("preadbuffer at %d:%p'%s'",
10392 g_parsefile->left_in_line,
10393 g_parsefile->next_to_pgetc,
10394 g_parsefile->next_to_pgetc);
10395 return (unsigned char)*g_parsefile->next_to_pgetc++;
10401 g_parsefile->linno++;
10402 setprompt_if(doprompt, 2);
10407 g_parsefile->linno++;
10408 needprompt = doprompt;
10416 pgetc_debug("pgetc at %d:%p'%s'",
10417 g_parsefile->left_in_line,
10418 g_parsefile->next_to_pgetc,
10419 g_parsefile->next_to_pgetc);
10420 if (g_parsefile->unget)
10421 return g_parsefile->lastc[--g_parsefile->unget];
10423 if (--g_parsefile->left_in_line >= 0)
10424 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10428 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10429 g_parsefile->lastc[0] = c;
10434 #if ENABLE_ASH_ALIAS
10436 pgetc_without_PEOA(void)
10440 pgetc_debug("pgetc at %d:%p'%s'",
10441 g_parsefile->left_in_line,
10442 g_parsefile->next_to_pgetc,
10443 g_parsefile->next_to_pgetc);
10445 } while (c == PEOA);
10449 # define pgetc_without_PEOA() pgetc()
10453 * Undo a call to pgetc. Only two characters may be pushed back.
10454 * PEOF may be pushed back.
10459 g_parsefile->unget++;
10462 /* This one eats backslash+newline */
10468 while ((c = pgetc()) == '\\') {
10469 if (pgetc() != '\n') {
10481 * To handle the "." command, a stack of input files is used. Pushfile
10482 * adds a new entry to the stack and popfile restores the previous level.
10487 struct parsefile *pf;
10489 pf = ckzalloc(sizeof(*pf));
10490 pf->prev = g_parsefile;
10492 /*pf->strpush = NULL; - ckzalloc did it */
10493 /*pf->basestrpush.prev = NULL;*/
10501 struct parsefile *pf = g_parsefile;
10507 if (pf->pf_fd >= 0)
10510 while (pf->strpush)
10512 g_parsefile = pf->prev;
10518 * Return to top level.
10523 while (g_parsefile != &basepf)
10528 * Close the file(s) that the shell is reading commands from. Called
10529 * after a fork is done.
10535 if (g_parsefile->pf_fd > 0) {
10536 close(g_parsefile->pf_fd);
10537 g_parsefile->pf_fd = 0;
10542 * Like setinputfile, but takes an open file descriptor. Call this with
10546 setinputfd(int fd, int push)
10550 g_parsefile->buf = NULL;
10552 g_parsefile->pf_fd = fd;
10553 if (g_parsefile->buf == NULL)
10554 g_parsefile->buf = ckmalloc(IBUFSIZ);
10555 g_parsefile->left_in_buffer = 0;
10556 g_parsefile->left_in_line = 0;
10557 g_parsefile->linno = 1;
10561 * Set the input to take input from a file. If push is set, push the
10562 * old input onto the stack first.
10565 setinputfile(const char *fname, int flags)
10570 fd = open(fname, O_RDONLY);
10572 if (flags & INPUT_NOFILE_OK)
10575 ash_msg_and_raise_error("can't open '%s'", fname);
10580 close_on_exec_on(fd);
10581 setinputfd(fd, flags & INPUT_PUSH_FILE);
10588 * Like setinputfile, but takes input from a string.
10591 setinputstring(char *string)
10595 g_parsefile->next_to_pgetc = string;
10596 g_parsefile->left_in_line = strlen(string);
10597 g_parsefile->buf = NULL;
10598 g_parsefile->linno = 1;
10604 * Routines to check for mail.
10607 #if ENABLE_ASH_MAIL
10609 /* Hash of mtimes of mailboxes */
10610 static unsigned mailtime_hash;
10611 /* Set if MAIL or MAILPATH is changed. */
10612 static smallint mail_var_path_changed;
10615 * Print appropriate message(s) if mail has arrived.
10616 * If mail_var_path_changed is set,
10617 * then the value of MAIL has mail_var_path_changed,
10618 * so we just update the values.
10627 struct stackmark smark;
10630 setstackmark(&smark);
10631 mpath = mpathset() ? mpathval() : mailval();
10634 p = path_advance(&mpath, nullstr);
10639 for (q = p; *q; q++)
10645 q[-1] = '\0'; /* delete trailing '/' */
10646 if (stat(p, &statb) < 0) {
10649 /* Very simplistic "hash": just a sum of all mtimes */
10650 new_hash += (unsigned)statb.st_mtime;
10652 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10653 if (mailtime_hash != 0)
10654 out2str("you have mail\n");
10655 mailtime_hash = new_hash;
10657 mail_var_path_changed = 0;
10658 popstackmark(&smark);
10661 static void FAST_FUNC
10662 changemail(const char *val UNUSED_PARAM)
10664 mail_var_path_changed = 1;
10667 #endif /* ASH_MAIL */
10670 /* ============ ??? */
10673 * Set the shell parameters.
10676 setparam(char **argv)
10682 for (nparam = 0; argv[nparam]; nparam++)
10684 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10686 *ap++ = ckstrdup(*argv++);
10689 freeparam(&shellparam);
10690 shellparam.malloced = 1;
10691 shellparam.nparam = nparam;
10692 shellparam.p = newparam;
10693 #if ENABLE_ASH_GETOPTS
10694 shellparam.optind = 1;
10695 shellparam.optoff = -1;
10700 * Process shell options. The global variable argptr contains a pointer
10701 * to the argument list; we advance it past the options.
10703 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10704 * For a non-interactive shell, an error condition encountered
10705 * by a special built-in ... shall cause the shell to write a diagnostic message
10706 * to standard error and exit as shown in the following table:
10707 * Error Special Built-In
10709 * Utility syntax error (option or operand error) Shall exit
10711 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10712 * we see that bash does not do that (set "finishes" with error code 1 instead,
10713 * and shell continues), and people rely on this behavior!
10715 * set -o barfoo 2>/dev/null
10718 * Oh well. Let's mimic that.
10721 plus_minus_o(char *name, int val)
10726 for (i = 0; i < NOPTS; i++) {
10727 if (strcmp(name, optnames(i)) == 0) {
10732 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10735 for (i = 0; i < NOPTS; i++) {
10737 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10739 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10745 setoption(int flag, int val)
10749 for (i = 0; i < NOPTS; i++) {
10750 if (optletters(i) == flag) {
10755 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10759 options(int cmdline, int *login_sh)
10767 while ((p = *argptr) != NULL) {
10769 if (c != '-' && c != '+')
10772 val = 0; /* val = 0 if c == '+' */
10775 if (p[0] == '\0' || LONE_DASH(p)) {
10777 /* "-" means turn off -x and -v */
10780 /* "--" means reset params */
10781 else if (*argptr == NULL)
10784 break; /* "-" or "--" terminates options */
10787 /* first char was + or - */
10788 while ((c = *p++) != '\0') {
10789 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10790 if (c == 'c' && cmdline) {
10791 minusc = p; /* command is after shell args */
10792 } else if (c == 'o') {
10793 if (plus_minus_o(*argptr, val)) {
10794 /* it already printed err message */
10795 return 1; /* error */
10799 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10802 /* bash does not accept +-login, we also won't */
10803 } else if (cmdline && val && (c == '-')) { /* long options */
10804 if (strcmp(p, "login") == 0) {
10818 * The shift builtin command.
10820 static int FAST_FUNC
10821 shiftcmd(int argc UNUSED_PARAM, char **argv)
10828 n = number(argv[1]);
10829 if (n > shellparam.nparam)
10830 n = 0; /* bash compat, was = shellparam.nparam; */
10832 shellparam.nparam -= n;
10833 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10834 if (shellparam.malloced)
10837 ap2 = shellparam.p;
10838 while ((*ap2++ = *ap1++) != NULL)
10840 #if ENABLE_ASH_GETOPTS
10841 shellparam.optind = 1;
10842 shellparam.optoff = -1;
10849 * POSIX requires that 'set' (but not export or readonly) output the
10850 * variables in lexicographic order - by the locale's collating order (sigh).
10851 * Maybe we could keep them in an ordered balanced binary tree
10852 * instead of hashed lists.
10853 * For now just roll 'em through qsort for printing...
10856 showvars(const char *sep_prefix, int on, int off)
10859 char **ep, **epend;
10861 ep = listvars(on, off, &epend);
10862 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10864 sep = *sep_prefix ? " " : sep_prefix;
10866 for (; ep < epend; ep++) {
10870 p = strchrnul(*ep, '=');
10873 q = single_quote(++p);
10874 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10880 * The set command builtin.
10882 static int FAST_FUNC
10883 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10888 return showvars(nullstr, 0, VUNSET);
10891 retval = options(/*cmdline:*/ 0, NULL);
10892 if (retval == 0) { /* if no parse error... */
10894 if (*argptr != NULL) {
10902 #if ENABLE_ASH_RANDOM_SUPPORT
10903 static void FAST_FUNC
10904 change_random(const char *value)
10908 if (value == NULL) {
10909 /* "get", generate */
10910 t = next_random(&random_gen);
10911 /* set without recursion */
10912 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10913 vrandom.flags &= ~VNOFUNC;
10916 t = strtoul(value, NULL, 10);
10917 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10922 #if ENABLE_ASH_GETOPTS
10924 getopts(char *optstr, char *optvar, char **optfirst)
10931 int ind = shellparam.optind;
10932 int off = shellparam.optoff;
10936 shellparam.optind = -1;
10937 optnext = optfirst + ind - 1;
10939 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10942 p = optnext[-1] + off;
10943 if (p == NULL || *p == '\0') {
10944 /* Current word is done, advance */
10946 if (p == NULL || *p != '-' || *++p == '\0') {
10953 if (LONE_DASH(p)) /* check for "--" */
10958 for (q = optstr; *q != c;) {
10960 if (optstr[0] == ':') {
10962 /*sbuf[1] = '\0'; - already is */
10963 setvar0("OPTARG", sbuf);
10965 fprintf(stderr, "Illegal option -%c\n", c);
10966 unsetvar("OPTARG");
10976 if (*p == '\0' && (p = *optnext) == NULL) {
10977 if (optstr[0] == ':') {
10979 /*sbuf[1] = '\0'; - already is */
10980 setvar0("OPTARG", sbuf);
10983 fprintf(stderr, "No arg for -%c option\n", c);
10984 unsetvar("OPTARG");
10992 setvar0("OPTARG", p);
10995 setvar0("OPTARG", nullstr);
10997 ind = optnext - optfirst + 1;
10998 setvar("OPTIND", itoa(ind), VNOFUNC);
11000 /*sbuf[1] = '\0'; - already is */
11001 setvar0(optvar, sbuf);
11003 shellparam.optoff = p ? p - *(optnext - 1) : -1;
11004 shellparam.optind = ind;
11010 * The getopts builtin. Shellparam.optnext points to the next argument
11011 * to be processed. Shellparam.optptr points to the next character to
11012 * be processed in the current argument. If shellparam.optnext is NULL,
11013 * then it's the first time getopts has been called.
11015 static int FAST_FUNC
11016 getoptscmd(int argc, char **argv)
11021 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
11023 optbase = shellparam.p;
11024 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
11025 shellparam.optind = 1;
11026 shellparam.optoff = -1;
11029 optbase = &argv[3];
11030 if ((unsigned)shellparam.optind > argc - 2) {
11031 shellparam.optind = 1;
11032 shellparam.optoff = -1;
11036 return getopts(argv[1], argv[2], optbase);
11038 #endif /* ASH_GETOPTS */
11041 /* ============ Shell parser */
11044 struct heredoc *next; /* next here document in list */
11045 union node *here; /* redirection node */
11046 char *eofmark; /* string indicating end of input */
11047 smallint striptabs; /* if set, strip leading tabs */
11050 static smallint tokpushback; /* last token pushed back */
11051 static smallint quoteflag; /* set if (part of) last token was quoted */
11052 static token_id_t lasttoken; /* last token read (integer id Txxx) */
11053 static struct heredoc *heredoclist; /* list of here documents to read */
11054 static char *wordtext; /* text of last word returned by readtoken */
11055 static struct nodelist *backquotelist;
11056 static union node *redirnode;
11057 static struct heredoc *heredoc;
11059 static const char *
11060 tokname(char *buf, int tok)
11063 return tokname_array[tok];
11064 sprintf(buf, "\"%s\"", tokname_array[tok]);
11068 /* raise_error_unexpected_syntax:
11069 * Called when an unexpected token is read during the parse. The argument
11070 * is the token that is expected, or -1 if more than one type of token can
11071 * occur at this point.
11073 static void raise_error_unexpected_syntax(int) NORETURN;
11075 raise_error_unexpected_syntax(int token)
11081 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
11083 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
11084 raise_error_syntax(msg);
11088 /* parsing is heavily cross-recursive, need these forward decls */
11089 static union node *andor(void);
11090 static union node *pipeline(void);
11091 static union node *parse_command(void);
11092 static void parseheredoc(void);
11093 static int peektoken(void);
11094 static int readtoken(void);
11096 static union node *
11099 union node *n1, *n2, *n3;
11104 switch (peektoken()) {
11112 if (!n1 && (nlflag & 1))
11118 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11119 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
11125 if (tok == TBACKGND) {
11126 if (n2->type == NPIPE) {
11127 n2->npipe.pipe_backgnd = 1;
11129 if (n2->type != NREDIR) {
11130 n3 = stzalloc(sizeof(struct nredir));
11132 /*n3->nredir.redirect = NULL; - stzalloc did it */
11135 n2->type = NBACKGND;
11141 n3 = stzalloc(sizeof(struct nbinary));
11143 n3->nbinary.ch1 = n1;
11144 n3->nbinary.ch2 = n2;
11157 raise_error_unexpected_syntax(-1);
11164 static union node *
11167 union node *n1, *n2, *n3;
11175 } else if (t == TOR) {
11181 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11183 n3 = stzalloc(sizeof(struct nbinary));
11185 n3->nbinary.ch1 = n1;
11186 n3->nbinary.ch2 = n2;
11191 static union node *
11194 union node *n1, *n2, *pipenode;
11195 struct nodelist *lp, *prev;
11199 TRACE(("pipeline: entered\n"));
11200 if (readtoken() == TNOT) {
11202 checkkwd = CHKKWD | CHKALIAS;
11205 n1 = parse_command();
11206 if (readtoken() == TPIPE) {
11207 pipenode = stzalloc(sizeof(struct npipe));
11208 pipenode->type = NPIPE;
11209 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
11210 lp = stzalloc(sizeof(struct nodelist));
11211 pipenode->npipe.cmdlist = lp;
11215 lp = stzalloc(sizeof(struct nodelist));
11216 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11217 lp->n = parse_command();
11219 } while (readtoken() == TPIPE);
11225 n2 = stzalloc(sizeof(struct nnot));
11233 static union node *
11238 n = stzalloc(sizeof(struct narg));
11240 /*n->narg.next = NULL; - stzalloc did it */
11241 n->narg.text = wordtext;
11242 n->narg.backquote = backquotelist;
11247 fixredir(union node *n, const char *text, int err)
11251 TRACE(("Fix redir %s %d\n", text, err));
11253 n->ndup.vname = NULL;
11255 fd = bb_strtou(text, NULL, 10);
11256 if (!errno && fd >= 0)
11257 n->ndup.dupfd = fd;
11258 else if (LONE_DASH(text))
11259 n->ndup.dupfd = -1;
11262 raise_error_syntax("bad fd number");
11263 n->ndup.vname = makename();
11270 union node *n = redirnode;
11272 if (n->type == NHERE)
11273 checkkwd = CHKEOFMARK;
11274 if (readtoken() != TWORD)
11275 raise_error_unexpected_syntax(-1);
11276 if (n->type == NHERE) {
11277 struct heredoc *here = heredoc;
11280 if (quoteflag == 0)
11282 TRACE(("Here document %d\n", n->type));
11283 rmescapes(wordtext, 0);
11284 here->eofmark = wordtext;
11286 if (heredoclist == NULL)
11287 heredoclist = here;
11289 for (p = heredoclist; p->next; p = p->next)
11293 } else if (n->type == NTOFD || n->type == NFROMFD) {
11294 fixredir(n, wordtext, 0);
11296 n->nfile.fname = makename();
11300 static union node *
11303 union node *args, **app;
11304 union node *n = NULL;
11305 union node *vars, **vpp;
11306 union node **rpp, *redir;
11309 smallint double_brackets_flag = 0;
11311 IF_BASH_FUNCTION(smallint function_flag = 0;)
11320 savecheckkwd = CHKALIAS;
11323 checkkwd = savecheckkwd;
11328 if (peektoken() != TWORD)
11329 raise_error_unexpected_syntax(TWORD);
11334 case TAND: /* "&&" */
11335 case TOR: /* "||" */
11336 if (!double_brackets_flag) {
11340 wordtext = (char *) (t == TAND ? "-a" : "-o");
11343 n = stzalloc(sizeof(struct narg));
11345 /*n->narg.next = NULL; - stzalloc did it */
11346 n->narg.text = wordtext;
11348 if (strcmp("[[", wordtext) == 0)
11349 double_brackets_flag = 1;
11350 else if (strcmp("]]", wordtext) == 0)
11351 double_brackets_flag = 0;
11353 n->narg.backquote = backquotelist;
11354 if (savecheckkwd && isassignment(wordtext)) {
11356 vpp = &n->narg.next;
11359 app = &n->narg.next;
11363 if (function_flag) {
11364 checkkwd = CHKNL | CHKKWD;
11365 switch (peektoken()) {
11377 if (strcmp("[[", wordtext) == 0)
11381 raise_error_unexpected_syntax(-1);
11387 *rpp = n = redirnode;
11388 rpp = &n->nfile.next;
11389 parsefname(); /* read name of redirection file */
11392 IF_BASH_FUNCTION(do_func:)
11393 if (args && app == &args->narg.next
11396 struct builtincmd *bcmd;
11399 /* We have a function */
11400 if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
11401 raise_error_unexpected_syntax(TRP);
11402 name = n->narg.text;
11403 if (!goodname(name)
11404 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11406 raise_error_syntax("bad function name");
11409 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11410 n->narg.next = parse_command();
11413 IF_BASH_FUNCTION(function_flag = 0;)
11424 n = stzalloc(sizeof(struct ncmd));
11426 n->ncmd.args = args;
11427 n->ncmd.assign = vars;
11428 n->ncmd.redirect = redir;
11432 static union node *
11433 parse_command(void)
11435 union node *n1, *n2;
11436 union node *ap, **app;
11437 union node *cp, **cpp;
11438 union node *redir, **rpp;
11445 switch (readtoken()) {
11447 raise_error_unexpected_syntax(-1);
11450 n1 = stzalloc(sizeof(struct nif));
11452 n1->nif.test = list(0);
11453 if (readtoken() != TTHEN)
11454 raise_error_unexpected_syntax(TTHEN);
11455 n1->nif.ifpart = list(0);
11457 while (readtoken() == TELIF) {
11458 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11459 n2 = n2->nif.elsepart;
11461 n2->nif.test = list(0);
11462 if (readtoken() != TTHEN)
11463 raise_error_unexpected_syntax(TTHEN);
11464 n2->nif.ifpart = list(0);
11466 if (lasttoken == TELSE)
11467 n2->nif.elsepart = list(0);
11469 n2->nif.elsepart = NULL;
11477 n1 = stzalloc(sizeof(struct nbinary));
11478 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11479 n1->nbinary.ch1 = list(0);
11482 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11483 got == TWORD ? wordtext : ""));
11484 raise_error_unexpected_syntax(TDO);
11486 n1->nbinary.ch2 = list(0);
11491 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11492 raise_error_syntax("bad for loop variable");
11493 n1 = stzalloc(sizeof(struct nfor));
11495 n1->nfor.var = wordtext;
11496 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11497 if (readtoken() == TIN) {
11499 while (readtoken() == TWORD) {
11500 n2 = stzalloc(sizeof(struct narg));
11502 /*n2->narg.next = NULL; - stzalloc did it */
11503 n2->narg.text = wordtext;
11504 n2->narg.backquote = backquotelist;
11506 app = &n2->narg.next;
11509 n1->nfor.args = ap;
11510 if (lasttoken != TNL && lasttoken != TSEMI)
11511 raise_error_unexpected_syntax(-1);
11513 n2 = stzalloc(sizeof(struct narg));
11515 /*n2->narg.next = NULL; - stzalloc did it */
11516 n2->narg.text = (char *)dolatstr;
11517 /*n2->narg.backquote = NULL;*/
11518 n1->nfor.args = n2;
11520 * Newline or semicolon here is optional (but note
11521 * that the original Bourne shell only allowed NL).
11523 if (lasttoken != TSEMI)
11526 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11527 if (readtoken() != TDO)
11528 raise_error_unexpected_syntax(TDO);
11529 n1->nfor.body = list(0);
11533 n1 = stzalloc(sizeof(struct ncase));
11535 if (readtoken() != TWORD)
11536 raise_error_unexpected_syntax(TWORD);
11537 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11539 /*n2->narg.next = NULL; - stzalloc did it */
11540 n2->narg.text = wordtext;
11541 n2->narg.backquote = backquotelist;
11542 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11543 if (readtoken() != TIN)
11544 raise_error_unexpected_syntax(TIN);
11545 cpp = &n1->ncase.cases;
11547 checkkwd = CHKNL | CHKKWD;
11549 while (t != TESAC) {
11550 if (lasttoken == TLP)
11552 *cpp = cp = stzalloc(sizeof(struct nclist));
11554 app = &cp->nclist.pattern;
11556 *app = ap = stzalloc(sizeof(struct narg));
11558 /*ap->narg.next = NULL; - stzalloc did it */
11559 ap->narg.text = wordtext;
11560 ap->narg.backquote = backquotelist;
11561 if (readtoken() != TPIPE)
11563 app = &ap->narg.next;
11566 //ap->narg.next = NULL;
11567 if (lasttoken != TRP)
11568 raise_error_unexpected_syntax(TRP);
11569 cp->nclist.body = list(2);
11571 cpp = &cp->nclist.next;
11573 checkkwd = CHKNL | CHKKWD;
11577 raise_error_unexpected_syntax(TENDCASE);
11584 n1 = stzalloc(sizeof(struct nredir));
11585 n1->type = NSUBSHELL;
11586 n1->nredir.n = list(0);
11587 /*n1->nredir.redirect = NULL; - stzalloc did it */
11594 IF_BASH_FUNCTION(case TFUNCTION:)
11598 return simplecmd();
11601 if (readtoken() != t)
11602 raise_error_unexpected_syntax(t);
11605 /* Now check for redirection which may follow command */
11606 checkkwd = CHKKWD | CHKALIAS;
11608 while (readtoken() == TREDIR) {
11609 *rpp = n2 = redirnode;
11610 rpp = &n2->nfile.next;
11616 if (n1->type != NSUBSHELL) {
11617 n2 = stzalloc(sizeof(struct nredir));
11622 n1->nredir.redirect = redir;
11627 #if BASH_DOLLAR_SQUOTE
11629 decode_dollar_squote(void)
11631 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11637 p = strchr(C_escapes, c);
11642 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11646 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11648 } else if (c == 'x') { /* \xHH */
11652 } while (isxdigit(c) && --cnt);
11654 if (cnt == 3) { /* \x but next char is "bad" */
11658 } else { /* simple seq like \\ or \t */
11663 c = bb_process_escape_sequence((void*)&p);
11664 } else { /* unrecognized "\z": print both chars unless ' or " */
11665 if (c != '\'' && c != '"') {
11667 c |= 0x100; /* "please encode \, then me" */
11674 /* Used by expandstr to get here-doc like behaviour. */
11675 #define FAKEEOFMARK ((char*)(uintptr_t)1)
11677 static ALWAYS_INLINE int
11678 realeofmark(const char *eofmark)
11680 return eofmark && eofmark != FAKEEOFMARK;
11684 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11685 * is not NULL, read a here document. In the latter case, eofmark is the
11686 * word which marks the end of the document and striptabs is true if
11687 * leading tabs should be stripped from the document. The argument c
11688 * is the first character of the input token or document.
11690 * Because C does not have internal subroutines, I have simulated them
11691 * using goto's to implement the subroutine linkage. The following macros
11692 * will run code that appears at the end of readtoken1.
11694 #define CHECKEND() {goto checkend; checkend_return:;}
11695 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11696 #define PARSESUB() {goto parsesub; parsesub_return:;}
11697 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11698 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11699 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11701 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11703 /* NB: syntax parameter fits into smallint */
11704 /* c parameter is an unsigned char or PEOF or PEOA */
11707 struct nodelist *bqlist;
11711 IF_FEATURE_SH_MATH(smallint prevsyntax;) /* syntax before arithmetic */
11712 smallint pssyntax; /* we are expanding a prompt string */
11713 int varnest; /* levels of variables expansion */
11714 IF_FEATURE_SH_MATH(int arinest;) /* levels of arithmetic expansion */
11715 IF_FEATURE_SH_MATH(int parenlevel;) /* levels of parens in arithmetic */
11716 int dqvarnest; /* levels of variables expansion within double quotes */
11718 IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
11720 startlinno = g_parsefile->linno;
11723 IF_FEATURE_SH_MATH(prevsyntax = 0;)
11724 #if ENABLE_ASH_EXPAND_PRMT
11725 pssyntax = (syntax == PSSYNTAX);
11729 pssyntax = 0; /* constant */
11731 dblquote = (syntax == DQSYNTAX);
11733 IF_FEATURE_SH_MATH(arinest = 0;)
11734 IF_FEATURE_SH_MATH(parenlevel = 0;)
11737 STARTSTACKSTR(out);
11739 /* For each line, until end of word */
11740 CHECKEND(); /* set c to PEOF if at end of here document */
11741 for (;;) { /* until end of line or end of word */
11742 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11743 switch (SIT(c, syntax)) {
11744 case CNL: /* '\n' */
11745 if (syntax == BASESYNTAX)
11746 goto endword; /* exit outer loop */
11750 goto loop; /* continue outer loop */
11755 #if BASH_DOLLAR_SQUOTE
11756 if (c == '\\' && bash_dollar_squote) {
11757 c = decode_dollar_squote();
11759 /* skip $'\000', $'\x00' (like bash) */
11763 /* Unknown escape. Encode as '\z' */
11764 c = (unsigned char)c;
11765 if (eofmark == NULL || dblquote)
11766 USTPUTC(CTLESC, out);
11767 USTPUTC('\\', out);
11771 if (eofmark == NULL || dblquote)
11772 USTPUTC(CTLESC, out);
11775 case CBACK: /* backslash */
11776 c = pgetc_without_PEOA();
11778 USTPUTC(CTLESC, out);
11779 USTPUTC('\\', out);
11781 } else if (c == '\n') {
11784 if (pssyntax && c == '$') {
11785 USTPUTC(CTLESC, out);
11786 USTPUTC('\\', out);
11788 /* Backslash is retained if we are in "str" and next char isn't special */
11793 && (c != '"' || eofmark != NULL)
11795 USTPUTC('\\', out);
11797 USTPUTC(CTLESC, out);
11805 if (eofmark == NULL) {
11806 USTPUTC(CTLQUOTEMARK, out);
11814 IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
11815 if (eofmark != NULL && varnest == 0) {
11818 if (dqvarnest == 0) {
11819 syntax = BASESYNTAX;
11826 case CVAR: /* '$' */
11827 PARSESUB(); /* parse substitution */
11829 case CENDVAR: /* '}' */
11832 if (dqvarnest > 0) {
11839 #if ENABLE_FEATURE_SH_MATH
11840 case CLP: /* '(' in arithmetic */
11844 case CRP: /* ')' in arithmetic */
11845 if (parenlevel > 0) {
11848 if (pgetc_eatbnl() == ')') {
11850 if (--arinest == 0) {
11851 syntax = prevsyntax;
11855 * unbalanced parens
11856 * (don't 2nd guess - no error)
11864 case CBQUOTE: /* '`' */
11868 goto endword; /* exit outer loop */
11872 if (varnest == 0) {
11873 #if BASH_REDIR_OUTPUT
11875 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11876 if (pgetc() == '>')
11877 c = 0x100 + '>'; /* flag &> */
11881 goto endword; /* exit outer loop */
11883 IF_ASH_ALIAS(if (c != PEOA))
11890 #if ENABLE_FEATURE_SH_MATH
11891 if (syntax == ARISYNTAX)
11892 raise_error_syntax("missing '))'");
11894 if (syntax != BASESYNTAX && eofmark == NULL)
11895 raise_error_syntax("unterminated quoted string");
11896 if (varnest != 0) {
11897 startlinno = g_parsefile->linno;
11899 raise_error_syntax("missing '}'");
11901 USTPUTC('\0', out);
11902 len = out - (char *)stackblock();
11903 out = stackblock();
11904 if (eofmark == NULL) {
11905 if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
11908 if (isdigit_str9(out)) {
11909 PARSEREDIR(); /* passed as params: out, c */
11910 lasttoken = TREDIR;
11913 /* else: non-number X seen, interpret it
11914 * as "NNNX>file" = "NNNX >file" */
11918 quoteflag = quotef;
11919 backquotelist = bqlist;
11920 grabstackblock(len);
11924 /* end of readtoken routine */
11927 * Check to see whether we are at the end of the here document. When this
11928 * is called, c is set to the first character of the next input line. If
11929 * we are at the end of the here document, this routine sets the c to PEOF.
11932 if (realeofmark(eofmark)) {
11936 #if ENABLE_ASH_ALIAS
11938 c = pgetc_without_PEOA();
11941 while (c == '\t') {
11942 c = pgetc_without_PEOA();
11946 markloc = out - (char *)stackblock();
11947 for (p = eofmark; STPUTC(c, out), *p; p++) {
11951 c = pgetc_without_PEOA();
11954 if (c == '\n' || c == PEOF) {
11956 g_parsefile->linno++;
11957 needprompt = doprompt;
11962 p = (char *)stackblock() + markloc + 1;
11963 len_here = out - p;
11966 len_here -= (c >= PEOF);
11972 str = alloca(len_here + 1);
11973 *(char *)mempcpy(str, p, len_here) = '\0';
11975 pushstring(str, NULL);
11980 STADJUST((char *)stackblock() + markloc - out, out);
11982 goto checkend_return;
11986 * Parse a redirection operator. The variable "out" points to a string
11987 * specifying the fd to be redirected. The variable "c" contains the
11988 * first character of the redirection operator.
11991 /* out is already checked to be a valid number or "" */
11992 int fd = (*out == '\0' ? -1 : atoi(out));
11995 np = stzalloc(sizeof(struct nfile));
12000 np->type = NAPPEND;
12002 np->type = NCLOBBER;
12005 /* it also can be NTO2 (>&file), but we can't figure it out yet */
12011 #if BASH_REDIR_OUTPUT
12012 else if (c == 0x100 + '>') { /* this flags &> redirection */
12014 pgetc(); /* this is '>', no need to check */
12018 else { /* c == '<' */
12019 /*np->nfile.fd = 0; - stzalloc did it */
12023 if (sizeof(struct nfile) != sizeof(struct nhere)) {
12024 np = stzalloc(sizeof(struct nhere));
12025 /*np->nfile.fd = 0; - stzalloc did it */
12028 heredoc = stzalloc(sizeof(struct heredoc));
12029 heredoc->here = np;
12032 heredoc->striptabs = 1;
12034 /*heredoc->striptabs = 0; - stzalloc did it */
12040 np->type = NFROMFD;
12044 np->type = NFROMTO;
12056 goto parseredir_return;
12060 * Parse a substitution. At this point, we have read the dollar sign
12061 * and nothing else.
12064 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
12065 * (assuming ascii char codes, as the original implementation did) */
12066 #define is_special(c) \
12067 (((unsigned)(c) - 33 < 32) \
12068 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
12070 unsigned char subtype;
12073 c = pgetc_eatbnl();
12074 if ((checkkwd & CHKEOFMARK)
12075 || c > 255 /* PEOA or PEOF */
12076 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
12078 #if BASH_DOLLAR_SQUOTE
12079 if (syntax != DQSYNTAX && c == '\'')
12080 bash_dollar_squote = 1;
12085 } else if (c == '(') {
12086 /* $(command) or $((arith)) */
12087 if (pgetc_eatbnl() == '(') {
12088 #if ENABLE_FEATURE_SH_MATH
12091 raise_error_syntax("support for $((arith)) is disabled");
12098 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
12099 USTPUTC(CTLVAR, out);
12100 typeloc = out - (char *)stackblock();
12102 subtype = VSNORMAL;
12104 c = pgetc_eatbnl();
12109 /* $[{[#]]NAME[}] */
12112 c = pgetc_eatbnl();
12113 } while (is_in_name(c));
12114 } else if (isdigit(c)) {
12115 /* $[{[#]]NUM[}] */
12118 c = pgetc_eatbnl();
12119 } while (isdigit(c));
12120 } else if (is_special(c)) {
12121 /* $[{[#]]<specialchar>[}] */
12124 c = pgetc_eatbnl();
12125 if (!subtype && cc == '#') {
12126 subtype = VSLENGTH;
12127 if (c == '_' || isalnum(c))
12130 c = pgetc_eatbnl();
12131 if (cc == '}' || c != '}') {
12142 if (c != '}' && subtype == VSLENGTH) {
12143 /* ${#VAR didn't end with } */
12147 if (subtype == 0) {
12148 static const char types[] ALIGN1 = "}-+?=";
12149 /* ${VAR...} but not $VAR or ${#VAR} */
12150 /* c == first char after VAR */
12153 c = pgetc_eatbnl();
12155 /* This check is only needed to not misinterpret
12156 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
12159 if (!strchr(types, c)) {
12160 subtype = VSSUBSTR;
12162 break; /* "goto badsub" is bigger (!) */
12168 const char *p = strchr(types, c);
12171 subtype |= p - types + VSNORMAL;
12177 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
12178 c = pgetc_eatbnl();
12184 #if BASH_PATTERN_SUBST
12186 /* ${v/[/]pattern/repl} */
12187 //TODO: encode pattern and repl separately.
12188 // Currently ${v/$var_with_slash/repl} is horribly broken
12189 subtype = VSREPLACE;
12190 c = pgetc_eatbnl();
12193 subtype++; /* VSREPLACEALL */
12201 ((unsigned char *)stackblock())[typeloc] = subtype;
12202 if (subtype != VSNORMAL) {
12209 goto parsesub_return;
12213 * Called to parse command substitutions. Newstyle is set if the command
12214 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
12215 * list of commands (passed by reference), and savelen is the number of
12216 * characters on the top of the stack which must be preserved.
12219 struct nodelist **nlpp;
12223 smallint saveprompt = 0;
12226 savelen = out - (char *)stackblock();
12229 * FIXME: this can allocate very large block on stack and SEGV.
12231 * echo "..<100kbytes>..`true` $(true) `true` ..."
12232 * allocates 100kb for every command subst. With about
12233 * a hundred command substitutions stack overflows.
12234 * With larger prepended string, SEGV happens sooner.
12236 str = alloca(savelen);
12237 memcpy(str, stackblock(), savelen);
12241 /* We must read until the closing backquote, giving special
12242 * treatment to some slashes, and then push the string and
12243 * reread it as input, interpreting it normally.
12249 STARTSTACKSTR(pout);
12253 setprompt_if(needprompt, 2);
12264 * If eating a newline, avoid putting
12265 * the newline into the new character
12266 * stream (via the STPUTC after the
12271 if (pc != '\\' && pc != '`' && pc != '$'
12272 && (!dblquote || pc != '"')
12274 STPUTC('\\', pout);
12276 if (pc <= 255 /* not PEOA or PEOF */) {
12282 IF_ASH_ALIAS(case PEOA:)
12283 startlinno = g_parsefile->linno;
12284 raise_error_syntax("EOF in backquote substitution");
12296 STPUTC('\0', pout);
12297 psavelen = pout - (char *)stackblock();
12298 if (psavelen > 0) {
12299 pstr = grabstackstr(pout);
12300 setinputstring(pstr);
12305 nlpp = &(*nlpp)->next;
12306 *nlpp = stzalloc(sizeof(**nlpp));
12307 /* (*nlpp)->next = NULL; - stzalloc did it */
12310 saveprompt = doprompt;
12317 doprompt = saveprompt;
12318 else if (readtoken() != TRP)
12319 raise_error_unexpected_syntax(TRP);
12324 * Start reading from old file again, ignoring any pushed back
12325 * tokens left from the backquote parsing
12330 while (stackblocksize() <= savelen)
12332 STARTSTACKSTR(out);
12334 memcpy(out, str, savelen);
12335 STADJUST(savelen, out);
12337 USTPUTC(CTLBACKQ, out);
12339 goto parsebackq_oldreturn;
12340 goto parsebackq_newreturn;
12343 #if ENABLE_FEATURE_SH_MATH
12345 * Parse an arithmetic expansion (indicate start of one and set state)
12348 if (++arinest == 1) {
12349 prevsyntax = syntax;
12350 syntax = ARISYNTAX;
12352 USTPUTC(CTLARI, out);
12353 goto parsearith_return;
12356 } /* end of readtoken */
12359 * Read the next input token.
12360 * If the token is a word, we set backquotelist to the list of cmds in
12361 * backquotes. We set quoteflag to true if any part of the word was
12363 * If the token is TREDIR, then we set redirnode to a structure containing
12365 * In all cases, the variable startlinno is set to the number of the line
12366 * on which the token starts.
12368 * [Change comment: here documents and internal procedures]
12369 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12370 * word parsing code into a separate routine. In this case, readtoken
12371 * doesn't need to have any internal procedures, but parseword does.
12372 * We could also make parseoperator in essence the main routine, and
12373 * have parseword (readtoken1?) handle both words and redirection.]
12375 #define NEW_xxreadtoken
12376 #ifdef NEW_xxreadtoken
12377 /* singles must be first! */
12378 static const char xxreadtoken_chars[7] ALIGN1 = {
12379 '\n', '(', ')', /* singles */
12380 '&', '|', ';', /* doubles */
12384 #define xxreadtoken_singles 3
12385 #define xxreadtoken_doubles 3
12387 static const char xxreadtoken_tokens[] ALIGN1 = {
12388 TNL, TLP, TRP, /* only single occurrence allowed */
12389 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12390 TEOF, /* corresponds to trailing nul */
12391 TAND, TOR, TENDCASE /* if double occurrence */
12403 setprompt_if(needprompt, 2);
12404 startlinno = g_parsefile->linno;
12405 for (;;) { /* until token or start of word found */
12407 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12411 while ((c = pgetc()) != '\n' && c != PEOF)
12414 } else if (c == '\\') {
12415 if (pgetc() != '\n') {
12417 break; /* return readtoken1(...) */
12423 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12429 p = strchr(xxreadtoken_chars, c);
12431 break; /* return readtoken1(...) */
12433 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12435 if (cc == c) { /* double occurrence? */
12436 p += xxreadtoken_doubles + 1;
12439 #if BASH_REDIR_OUTPUT
12440 if (c == '&' && cc == '>') /* &> */
12441 break; /* return readtoken1(...) */
12446 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12451 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12453 #else /* old xxreadtoken */
12454 #define RETURN(token) return lasttoken = token
12464 setprompt_if(needprompt, 2);
12465 startlinno = g_parsefile->linno;
12466 for (;;) { /* until token or start of word found */
12469 case ' ': case '\t':
12470 IF_ASH_ALIAS(case PEOA:)
12473 while ((c = pgetc()) != '\n' && c != PEOF)
12478 if (pgetc() == '\n') {
12490 if (pgetc() == '&')
12495 if (pgetc() == '|')
12500 if (pgetc() == ';')
12513 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12516 #endif /* old xxreadtoken */
12522 int kwd = checkkwd;
12524 smallint alreadyseen = tokpushback;
12527 #if ENABLE_ASH_ALIAS
12543 if (t != TWORD || quoteflag) {
12548 * check for keywords
12550 if (kwd & CHKKWD) {
12551 const char *const *pp;
12553 pp = findkwd(wordtext);
12555 lasttoken = t = pp - tokname_array;
12556 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12561 if (checkkwd & CHKALIAS) {
12562 #if ENABLE_ASH_ALIAS
12564 ap = lookupalias(wordtext, 1);
12567 pushstring(ap->val, ap);
12577 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12579 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12595 * Read and parse a command. Returns NODE_EOF on end of file.
12596 * (NULL is a valid parse tree indicating a blank line.)
12598 static union node *
12599 parsecmd(int interact)
12604 doprompt = interact;
12605 setprompt_if(doprompt, doprompt);
12611 * Input any here documents.
12616 struct heredoc *here;
12619 here = heredoclist;
12620 heredoclist = NULL;
12623 setprompt_if(needprompt, 2);
12624 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12625 here->eofmark, here->striptabs);
12626 n = stzalloc(sizeof(struct narg));
12627 n->narg.type = NARG;
12628 /*n->narg.next = NULL; - stzalloc did it */
12629 n->narg.text = wordtext;
12630 n->narg.backquote = backquotelist;
12631 here->here->nhere.doc = n;
12637 static const char *
12638 expandstr(const char *ps, int syntax_type)
12643 /* XXX Fix (char *) cast. */
12644 setinputstring((char *)ps);
12646 saveprompt = doprompt;
12648 readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
12649 doprompt = saveprompt;
12653 n.narg.type = NARG;
12654 n.narg.next = NULL;
12655 n.narg.text = wordtext;
12656 n.narg.backquote = backquotelist;
12658 expandarg(&n, NULL, EXP_QUOTED);
12659 return stackblock();
12665 return tokpushback && lasttoken == TEOF;
12669 * Execute a command or commands contained in a string.
12672 evalstring(char *s, int flags)
12674 struct jmploc *volatile savehandler;
12675 struct jmploc jmploc;
12679 struct stackmark smark;
12684 setstackmark(&smark);
12687 /* On exception inside execution loop, we must popfile().
12688 * Try interactively:
12690 * command eval "a=b" # throws "is read only" error
12691 * "command BLTIN" is not supposed to abort (even in non-interactive use).
12692 * But if we skip popfile(), we hit EOF in eval's string, and exit.
12694 savehandler = exception_handler;
12695 ex = setjmp(jmploc.loc);
12698 exception_handler = &jmploc;
12700 while ((n = parsecmd(0)) != NODE_EOF) {
12703 i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
12706 popstackmark(&smark);
12711 popstackmark(&smark);
12715 exception_handler = savehandler;
12717 longjmp(exception_handler->loc, ex);
12723 * The eval command.
12725 static int FAST_FUNC
12726 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12735 STARTSTACKSTR(concat);
12737 concat = stack_putstr(p, concat);
12741 STPUTC(' ', concat);
12743 STPUTC('\0', concat);
12744 p = grabstackstr(concat);
12746 return evalstring(p, flags & EV_TESTED);
12752 * Read and execute commands.
12753 * "Top" is nonzero for the top level command loop;
12754 * it turns on prompting if the shell is interactive.
12760 struct stackmark smark;
12765 TRACE(("cmdloop(%d) called\n", top));
12769 setstackmark(&smark);
12772 showjobs(SHOW_CHANGED|SHOW_STDERR);
12775 if (iflag && top) {
12779 n = parsecmd(inter);
12781 if (DEBUG > 2 && debug && (n != NODE_EOF))
12784 if (n == NODE_EOF) {
12785 if (!top || numeof >= 50)
12787 if (!stoppedjobs()) {
12790 out2str("\nUse \"exit\" to leave shell.\n");
12793 } else if (nflag == 0) {
12796 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12799 i = evaltree(n, 0);
12803 popstackmark(&smark);
12807 evalskip &= ~SKIPFUNC;
12815 * Take commands from a file. To be compatible we should do a path
12816 * search for the file, which is necessary to find sub-commands.
12819 find_dot_file(char *name)
12822 const char *path = pathval();
12825 /* don't try this for absolute or relative paths */
12826 if (strchr(name, '/'))
12829 while ((fullname = path_advance(&path, name)) != NULL) {
12830 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12832 * Don't bother freeing here, since it will
12833 * be freed by the caller.
12837 if (fullname != name)
12838 stunalloc(fullname);
12841 /* not found in the PATH */
12842 ash_msg_and_raise_error("%s: not found", name);
12846 static int FAST_FUNC
12847 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12849 /* "false; . empty_file; echo $?" should print 0, not 1: */
12853 char *args_need_save;
12854 volatile struct shparam saveparam;
12857 // struct strlist *sp;
12858 // for (sp = cmdenviron; sp; sp = sp->next)
12859 // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12861 nextopt(nullstr); /* handle possible "--" */
12865 /* bash says: "bash: .: filename argument required" */
12866 return 2; /* bash compat */
12869 /* This aborts if file isn't found, which is POSIXly correct.
12870 * bash returns exitcode 1 instead.
12872 fullname = find_dot_file(argv[0]);
12874 args_need_save = argv[0];
12875 if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
12877 saveparam = shellparam;
12878 shellparam.malloced = 0;
12882 shellparam.nparam = argc;
12883 shellparam.p = argv;
12886 /* This aborts if file can't be opened, which is POSIXly correct.
12887 * bash returns exitcode 1 instead.
12889 setinputfile(fullname, INPUT_PUSH_FILE);
12890 commandname = fullname;
12891 status = cmdloop(0);
12894 if (args_need_save) {
12895 freeparam(&shellparam);
12896 shellparam = saveparam;
12902 static int FAST_FUNC
12903 exitcmd(int argc UNUSED_PARAM, char **argv)
12908 exitstatus = number(argv[1]);
12909 raise_exception(EXEXIT);
12914 * Read a file containing shell functions.
12917 readcmdfile(char *name)
12919 setinputfile(name, INPUT_PUSH_FILE);
12925 /* ============ find_command inplementation */
12928 * Resolve a command name. If you change this routine, you may have to
12929 * change the shellexec routine as well.
12932 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12934 struct tblentry *cmdp;
12941 struct builtincmd *bcmd;
12943 /* If name contains a slash, don't use PATH or hash table */
12944 if (strchr(name, '/') != NULL) {
12945 entry->u.index = -1;
12946 if (act & DO_ABS) {
12947 while (stat(name, &statb) < 0) {
12949 if (errno == EINTR)
12952 entry->cmdtype = CMDUNKNOWN;
12956 entry->cmdtype = CMDNORMAL;
12960 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12962 updatetbl = (path == pathval());
12965 if (strstr(path, "%builtin") != NULL)
12966 act |= DO_ALTBLTIN;
12969 /* If name is in the table, check answer will be ok */
12970 cmdp = cmdlookup(name, 0);
12971 if (cmdp != NULL) {
12974 switch (cmdp->cmdtype) {
12992 } else if (cmdp->rehash == 0)
12993 /* if not invalidated by cd, we're done */
12997 /* If %builtin not in path, check for builtin next */
12998 bcmd = find_builtin(name);
13000 if (IS_BUILTIN_REGULAR(bcmd))
13001 goto builtin_success;
13002 if (act & DO_ALTPATH) {
13003 if (!(act & DO_ALTBLTIN))
13004 goto builtin_success;
13005 } else if (builtinloc <= 0) {
13006 goto builtin_success;
13010 #if ENABLE_FEATURE_SH_STANDALONE
13012 int applet_no = find_applet_by_name(name);
13013 if (applet_no >= 0) {
13014 entry->cmdtype = CMDNORMAL;
13015 entry->u.index = -2 - applet_no;
13021 /* We have to search path. */
13022 prev = -1; /* where to start */
13023 if (cmdp && cmdp->rehash) { /* doing a rehash */
13024 if (cmdp->cmdtype == CMDBUILTIN)
13027 prev = cmdp->param.index;
13033 while ((fullname = path_advance(&path, name)) != NULL) {
13034 stunalloc(fullname);
13035 /* NB: code below will still use fullname
13036 * despite it being "unallocated" */
13039 if (prefix(pathopt, "builtin")) {
13041 goto builtin_success;
13044 if ((act & DO_NOFUNC)
13045 || !prefix(pathopt, "func")
13046 ) { /* ignore unimplemented options */
13050 /* if rehash, don't redo absolute path names */
13051 if (fullname[0] == '/' && idx <= prev) {
13054 TRACE(("searchexec \"%s\": no change\n", name));
13057 while (stat(fullname, &statb) < 0) {
13059 if (errno == EINTR)
13062 if (errno != ENOENT && errno != ENOTDIR)
13066 e = EACCES; /* if we fail, this will be the error */
13067 if (!S_ISREG(statb.st_mode))
13069 if (pathopt) { /* this is a %func directory */
13070 stalloc(strlen(fullname) + 1);
13071 /* NB: stalloc will return space pointed by fullname
13072 * (because we don't have any intervening allocations
13073 * between stunalloc above and this stalloc) */
13074 readcmdfile(fullname);
13075 cmdp = cmdlookup(name, 0);
13076 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
13077 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
13078 stunalloc(fullname);
13081 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
13083 entry->cmdtype = CMDNORMAL;
13084 entry->u.index = idx;
13088 cmdp = cmdlookup(name, 1);
13089 cmdp->cmdtype = CMDNORMAL;
13090 cmdp->param.index = idx;
13095 /* We failed. If there was an entry for this command, delete it */
13096 if (cmdp && updatetbl)
13097 delete_cmd_entry();
13099 ash_msg("%s: %s", name, errmsg(e, "not found"));
13100 entry->cmdtype = CMDUNKNOWN;
13105 entry->cmdtype = CMDBUILTIN;
13106 entry->u.cmd = bcmd;
13110 cmdp = cmdlookup(name, 1);
13111 cmdp->cmdtype = CMDBUILTIN;
13112 cmdp->param.cmd = bcmd;
13116 entry->cmdtype = cmdp->cmdtype;
13117 entry->u = cmdp->param;
13122 * The trap builtin.
13124 static int FAST_FUNC
13125 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13129 int signo, exitcode;
13134 for (signo = 0; signo < NSIG; signo++) {
13135 char *tr = trap_ptr[signo];
13137 /* note: bash adds "SIG", but only if invoked
13138 * as "bash". If called as "sh", or if set -o posix,
13139 * then it prints short signal names.
13140 * We are printing short names: */
13141 out1fmt("trap -- %s %s\n",
13143 get_signame(signo));
13144 /* trap_ptr != trap only if we are in special-cased `trap` code.
13145 * In this case, we will exit very soon, no need to free(). */
13146 /* if (trap_ptr != trap && tp[0]) */
13151 if (trap_ptr != trap) {
13159 /* Why the second check?
13160 * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
13161 * In this case, NUM is signal no, not an action.
13164 if (ap[1] && !is_number(ap[0]))
13169 signo = get_signum(*ap);
13171 /* Mimic bash message exactly */
13172 ash_msg("%s: invalid signal specification", *ap);
13178 if (LONE_DASH(action))
13181 if (action[0]) /* not NULL and not "" and not "-" */
13182 may_have_traps = 1;
13183 action = ckstrdup(action);
13187 trap[signo] = action;
13198 /* ============ Builtins */
13200 #if ENABLE_ASH_HELP
13201 static int FAST_FUNC
13202 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13208 "Built-in commands:\n"
13209 "------------------\n");
13210 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
13211 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
13212 builtintab[i].name + 1);
13218 # if ENABLE_FEATURE_SH_STANDALONE
13220 const char *a = applet_names;
13222 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
13227 while (*a++ != '\0')
13232 newline_and_flush(stdout);
13233 return EXIT_SUCCESS;
13238 static int FAST_FUNC
13239 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13241 show_history(line_input_state);
13242 return EXIT_SUCCESS;
13247 * The export and readonly commands.
13249 static int FAST_FUNC
13250 exportcmd(int argc UNUSED_PARAM, char **argv)
13260 /* "readonly" in bash accepts, but ignores -n.
13261 * We do the same: it saves a conditional in nextopt's param.
13264 while ((opt = nextopt("np")) != '\0') {
13266 flag_off = VEXPORT;
13269 if (argv[0][0] == 'r') {
13271 flag_off = 0; /* readonly ignores -n */
13273 flag_off = ~flag_off;
13275 /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
13281 p = strchr(name, '=');
13285 vp = *findvar(hashvar(name), name);
13287 vp->flags = ((vp->flags | flag) & flag_off);
13291 setvar(name, p, (flag & flag_off));
13292 } while ((name = *++aptr) != NULL);
13297 /* No arguments. Show the list of exported or readonly vars.
13300 showvars(argv[0], flag, 0);
13305 * Delete a function if it exists.
13308 unsetfunc(const char *name)
13310 struct tblentry *cmdp;
13312 cmdp = cmdlookup(name, 0);
13313 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
13314 delete_cmd_entry();
13318 * The unset builtin command. We unset the function before we unset the
13319 * variable to allow a function to be unset when there is a readonly variable
13320 * with the same name.
13322 static int FAST_FUNC
13323 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13329 while ((i = nextopt("vf")) != 0) {
13333 for (ap = argptr; *ap; ap++) {
13344 static const unsigned char timescmd_str[] ALIGN1 = {
13345 ' ', offsetof(struct tms, tms_utime),
13346 '\n', offsetof(struct tms, tms_stime),
13347 ' ', offsetof(struct tms, tms_cutime),
13348 '\n', offsetof(struct tms, tms_cstime),
13351 static int FAST_FUNC
13352 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13354 unsigned long clk_tck, s, t;
13355 const unsigned char *p;
13358 clk_tck = bb_clk_tck();
13363 t = *(clock_t *)(((char *) &buf) + p[1]);
13366 out1fmt("%lum%lu.%03lus%c",
13368 (t * 1000) / clk_tck,
13376 #if ENABLE_FEATURE_SH_MATH
13378 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13379 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13381 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13383 static int FAST_FUNC
13384 letcmd(int argc UNUSED_PARAM, char **argv)
13390 ash_msg_and_raise_error("expression expected");
13392 i = ash_arith(*argv);
13400 * The read builtin. Options:
13401 * -r Do not interpret '\' specially
13402 * -s Turn off echo (tty only)
13403 * -n NCHARS Read NCHARS max
13404 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13405 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13406 * -u FD Read from given FD instead of fd 0
13407 * This uses unbuffered input, which may be avoidable in some cases.
13408 * TODO: bash also has:
13409 * -a ARRAY Read into array[0],[1],etc
13410 * -d DELIM End on DELIM char, not newline
13411 * -e Use line editing (tty only)
13413 static int FAST_FUNC
13414 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13416 char *opt_n = NULL;
13417 char *opt_p = NULL;
13418 char *opt_t = NULL;
13419 char *opt_u = NULL;
13420 int read_flags = 0;
13424 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13433 read_flags |= BUILTIN_READ_SILENT;
13439 read_flags |= BUILTIN_READ_RAW;
13449 /* "read -s" needs to save/restore termios, can't allow ^C
13450 * to jump out of it.
13454 r = shell_builtin_read(setvar0,
13456 bltinlookup("IFS"), /* can be NULL */
13465 if ((uintptr_t)r == 1 && errno == EINTR) {
13466 /* To get SIGCHLD: sleep 1 & read x; echo $x
13467 * Correct behavior is to not exit "read"
13469 if (pending_sig == 0)
13473 if ((uintptr_t)r > 1)
13474 ash_msg_and_raise_error(r);
13476 return (uintptr_t)r;
13479 static int FAST_FUNC
13480 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13482 static const char permuser[3] ALIGN1 = "ogu";
13485 int symbolic_mode = 0;
13487 while (nextopt("S") != '\0') {
13496 if (*argptr == NULL) {
13497 if (symbolic_mode) {
13498 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13505 *p++ = permuser[i];
13507 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13508 if (!(mask & 0400)) *p++ = 'r';
13509 if (!(mask & 0200)) *p++ = 'w';
13510 if (!(mask & 0100)) *p++ = 'x';
13518 out1fmt("%04o\n", mask);
13521 char *modestr = *argptr;
13522 /* numeric umasks are taken as-is */
13523 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13524 if (!isdigit(modestr[0]))
13526 mask = bb_parse_mode(modestr, mask);
13527 if ((unsigned)mask > 0777) {
13528 ash_msg_and_raise_error("illegal mode: %s", modestr);
13530 if (!isdigit(modestr[0]))
13537 static int FAST_FUNC
13538 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13540 return shell_builtin_ulimit(argv);
13543 /* ============ main() and helpers */
13546 * Called to exit the shell.
13555 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13556 save_history(line_input_state);
13558 status = exitstatus;
13559 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13560 if (setjmp(loc.loc)) {
13561 if (exception_type == EXEXIT)
13562 status = exitstatus;
13565 exception_handler = &loc;
13571 /*free(p); - we'll exit soon */
13574 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13575 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13578 flush_stdout_stderr();
13583 /* Don't inline: conserve stack of caller from having our locals too */
13584 static NOINLINE void
13587 /* we will never free this */
13588 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13590 sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
13591 setsignal(SIGCHLD);
13593 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13594 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13596 signal(SIGHUP, SIG_DFL);
13603 for (envp = environ; envp && *envp; envp++) {
13604 p = endofname(*envp);
13605 if (p != *envp && *p == '=') {
13606 setvareq(*envp, VEXPORT|VTEXTFIXED);
13610 setvareq((char*)defoptindvar, VTEXTFIXED);
13612 setvar0("PPID", utoa(getppid()));
13614 p = lookupvar("SHLVL");
13615 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13617 #if BASH_HOSTNAME_VAR
13618 if (!lookupvar("HOSTNAME")) {
13619 struct utsname uts;
13621 setvar0("HOSTNAME", uts.nodename);
13624 p = lookupvar("PWD");
13626 struct stat st1, st2;
13627 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13628 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13638 //usage:#define ash_trivial_usage
13639 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13640 //usage:#define ash_full_usage "\n\n"
13641 //usage: "Unix shell interpreter"
13644 * Process the shell command line arguments.
13647 procargs(char **argv)
13650 const char *xminusc;
13655 login_sh = xargv[0] && xargv[0][0] == '-';
13657 /* if (xargv[0]) - mmm, this is always true! */
13659 for (i = 0; i < NOPTS; i++)
13662 if (options(/*cmdline:*/ 1, &login_sh)) {
13663 /* it already printed err message */
13664 raise_exception(EXERROR);
13668 if (*xargv == NULL) {
13670 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13673 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13677 for (i = 0; i < NOPTS; i++)
13678 if (optlist[i] == 2)
13683 /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
13688 } else if (!sflag) {
13689 setinputfile(*xargv, 0);
13692 commandname = arg0;
13695 shellparam.p = xargv;
13696 #if ENABLE_ASH_GETOPTS
13697 shellparam.optind = 1;
13698 shellparam.optoff = -1;
13700 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13702 shellparam.nparam++;
13711 * Read /etc/profile, ~/.profile, $ENV.
13714 read_profile(const char *name)
13716 name = expandstr(name, DQSYNTAX);
13717 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13724 * This routine is called when an error or an interrupt occurs in an
13725 * interactive shell and control is returned to the main command loop.
13726 * (In dash, this function is auto-generated by build machinery).
13735 /* from expand.c: */
13738 /* from input.c: */
13739 g_parsefile->left_in_buffer = 0;
13740 g_parsefile->left_in_line = 0; /* clear input buffer */
13743 /* from redir.c: */
13747 unwindlocalvars(NULL);
13751 static short profile_buf[16384];
13752 extern int etext();
13756 * Main routine. We initialize things, parse the arguments, execute
13757 * profiles if we're a login shell, and then call cmdloop to execute
13758 * commands. The setjmp call sets up the location to jump to when an
13759 * exception occurs. When an exception occurs the variable "state"
13760 * is used to figure out how far we had gotten.
13762 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13763 int ash_main(int argc UNUSED_PARAM, char **argv)
13765 volatile smallint state;
13766 struct jmploc jmploc;
13767 struct stackmark smark;
13770 /* Initialize global data */
13774 #if ENABLE_ASH_ALIAS
13780 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13783 #if ENABLE_FEATURE_EDITING
13784 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13787 if (setjmp(jmploc.loc)) {
13793 e = exception_type;
13795 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13799 newline_and_flush(stderr);
13802 popstackmark(&smark);
13803 FORCE_INT_ON; /* enable interrupts */
13812 exception_handler = &jmploc;
13813 rootpid = getpid();
13816 setstackmark(&smark);
13817 login_sh = procargs(argv);
13819 TRACE(("Shell args: "));
13820 trace_puts_args(argv);
13827 read_profile("/etc/profile");
13830 hp = lookupvar("HOME");
13832 read_profile("$HOME/.profile");
13838 getuid() == geteuid() && getgid() == getegid() &&
13842 const char *shinit = lookupvar("ENV");
13843 if (shinit != NULL && *shinit != '\0')
13844 read_profile(shinit);
13846 popstackmark(&smark);
13850 /* evalstring pushes parsefile stack.
13851 * Ensure we don't falsely claim that 0 (stdin)
13852 * is one of stacked source fds.
13853 * Testcase: ash -c 'exec 1>&0' must not complain. */
13854 // if (!sflag) g_parsefile->pf_fd = -1;
13855 // ^^ not necessary since now we special-case fd 0
13856 // in save_fd_on_redirect()
13857 evalstring(minusc, sflag ? 0 : EV_EXIT);
13860 if (sflag || minusc == NULL) {
13861 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13863 const char *hp = lookupvar("HISTFILE");
13865 hp = lookupvar("HOME");
13868 hp = concat_path_file(hp, ".ash_history");
13869 setvar0("HISTFILE", hp);
13872 hp = lookupvar("HISTFILE");
13876 line_input_state->hist_file = hp;
13877 # if ENABLE_FEATURE_SH_HISTFILESIZE
13878 hp = lookupvar("HISTFILESIZE");
13879 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13883 state4: /* XXX ??? - why isn't this before the "if" statement */
13891 extern void _mcleanup(void);
13895 TRACE(("End of main reached\n"));
13902 * Copyright (c) 1989, 1991, 1993, 1994
13903 * The Regents of the University of California. All rights reserved.
13905 * This code is derived from software contributed to Berkeley by
13906 * Kenneth Almquist.
13908 * Redistribution and use in source and binary forms, with or without
13909 * modification, are permitted provided that the following conditions
13911 * 1. Redistributions of source code must retain the above copyright
13912 * notice, this list of conditions and the following disclaimer.
13913 * 2. Redistributions in binary form must reproduce the above copyright
13914 * notice, this list of conditions and the following disclaimer in the
13915 * documentation and/or other materials provided with the distribution.
13916 * 3. Neither the name of the University nor the names of its contributors
13917 * may be used to endorse or promote products derived from this software
13918 * without specific prior written permission.
13920 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
13921 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13922 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13923 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13924 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13925 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13926 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13927 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13928 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13929 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF