1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
21 //config: depends on !NOMMU
23 //config: Tha 'ash' shell adds about 60k in the default configuration and is
24 //config: the most complete and most pedantically correct shell included with
25 //config: busybox. This shell is actually a derivative of the Debian 'dash'
26 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
27 //config: (written by Kenneth Almquist) from NetBSD.
29 //config:# ash options
30 //config:# note: Don't remove !NOMMU part in the next line; it would break
31 //config:# menuconfig's indenting.
32 //config:if !NOMMU && (ASH || SH_IS_ASH || BASH_IS_ASH)
34 //config:config ASH_OPTIMIZE_FOR_SIZE
35 //config: bool "Optimize for size instead of speed"
37 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
39 //config:config ASH_INTERNAL_GLOB
40 //config: bool "Use internal glob() implementation"
41 //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
42 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
44 //config: Do not use glob() function from libc, use internal implementation.
45 //config: Use this if you are getting "glob.h: No such file or directory"
46 //config: or similar build errors.
47 //config: Note that as of now (2017-01), uclibc and musl glob() both have bugs
48 //config: which would break ash if you select N here.
50 //config:config ASH_BASH_COMPAT
51 //config: bool "bash-compatible extensions"
53 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
55 //config:config ASH_JOB_CONTROL
56 //config: bool "Job control"
58 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
60 //config:config ASH_ALIAS
61 //config: bool "Alias support"
63 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
65 //config:config ASH_RANDOM_SUPPORT
66 //config: bool "Pseudorandom generator and $RANDOM variable"
68 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
70 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
71 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
72 //config: You can reset the generator by using a specified start value.
73 //config: After "unset RANDOM" the generator will switch off and this
74 //config: variable will no longer have special treatment.
76 //config:config ASH_EXPAND_PRMT
77 //config: bool "Expand prompt string"
79 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
81 //config: $PS# may contain volatile content, such as backquote commands.
82 //config: This option recreates the prompt string from the environment
83 //config: variable each time it is displayed.
85 //config:config ASH_IDLE_TIMEOUT
86 //config: bool "Idle timeout variable $TMOUT"
88 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
90 //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
92 //config:config ASH_MAIL
93 //config: bool "Check for new mail in interactive shell"
95 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
97 //config: Enable "check for new mail" function:
98 //config: if set, $MAIL file and $MAILPATH list of files
99 //config: are checked for mtime changes, and "you have mail"
100 //config: message is printed if change is detected.
102 //config:config ASH_ECHO
103 //config: bool "echo builtin"
105 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
107 //config:config ASH_PRINTF
108 //config: bool "printf builtin"
110 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
112 //config:config ASH_TEST
113 //config: bool "test builtin"
115 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
117 //config:config ASH_HELP
118 //config: bool "help builtin"
120 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
122 //config:config ASH_GETOPTS
123 //config: bool "getopts builtin"
125 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
127 //config:config ASH_CMDCMD
128 //config: bool "command builtin"
130 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
132 //config: Enable support for the 'command' builtin, which allows
133 //config: you to run the specified command or builtin,
134 //config: even when there is a function with the same name.
136 //config:endif # ash options
138 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
139 // APPLET_ODDNAME:name main location suid_type help
140 //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
141 //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
143 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
144 //kbuild:lib-$(CONFIG_SH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
145 //kbuild:lib-$(CONFIG_BASH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
146 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
149 * DEBUG=1 to compile in debugging ('set -o debug' turns on)
150 * DEBUG=2 to compile in and turn on debugging.
151 * When debugging is on ("set -o debug" was executed, or DEBUG=2),
152 * debugging info is written to ./trace, quit signal generates core dump.
155 /* Tweak debug output verbosity here */
159 #define DEBUG_INTONOFF 0
163 #define JOBS ENABLE_ASH_JOB_CONTROL
167 #include <sys/times.h>
168 #include <sys/utsname.h> /* for setting $HOSTNAME */
169 #include "busybox.h" /* for applet_names */
171 /* So far, all bash compat is controlled by one config option */
172 /* Separate defines document which part of code implements what */
173 /* function keyword */
174 #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
175 #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
177 #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
178 #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
180 #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
181 #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
182 #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
183 #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
184 #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
185 #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
187 #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
188 #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
189 #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
190 #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
191 #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
193 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
194 /* Bionic at least up to version 24 has no glob() */
195 # undef ENABLE_ASH_INTERNAL_GLOB
196 # define ENABLE_ASH_INTERNAL_GLOB 1
199 #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
200 # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
201 # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
202 # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
203 # error glob() should unbackslash them and match. uClibc does not unbackslash,
204 # error fails to match dirname, subsequently not expanding <pattern> in it.
206 // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
207 // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
210 #if !ENABLE_ASH_INTERNAL_GLOB
215 #include "shell_common.h"
216 #if ENABLE_FEATURE_SH_MATH
219 #if ENABLE_ASH_RANDOM_SUPPORT
222 # define CLEAR_RANDOM_T(rnd) ((void)0)
225 #include "NUM_APPLETS.h"
227 /* STANDALONE does not make sense, and won't compile */
228 # undef CONFIG_FEATURE_SH_STANDALONE
229 # undef ENABLE_FEATURE_SH_STANDALONE
230 # undef IF_FEATURE_SH_STANDALONE
231 # undef IF_NOT_FEATURE_SH_STANDALONE
232 # define ENABLE_FEATURE_SH_STANDALONE 0
233 # define IF_FEATURE_SH_STANDALONE(...)
234 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
238 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
242 # error "Do not even bother, ash will not run on NOMMU machine"
246 /* ============ Hash table sizes. Configurable. */
250 #define CMDTABLESIZE 31 /* should be prime */
253 /* ============ Shell options */
255 static const char *const optletters_optnames[] = {
279 #define optletters(n) optletters_optnames[n][0]
280 #define optnames(n) (optletters_optnames[n] + 1)
282 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
285 /* ============ Misc data */
287 #define msg_illnum "Illegal number: %s"
290 * We enclose jmp_buf in a structure so that we can declare pointers to
291 * jump locations. The global variable handler contains the location to
292 * jump to when an exception occurs, and the global variable exception_type
293 * contains a code identifying the exception. To implement nested
294 * exception handlers, the user should save the value of handler on entry
295 * to an inner scope, set handler to point to a jmploc structure for the
296 * inner scope, and restore handler on exit from the scope.
302 struct globals_misc {
303 uint8_t exitstatus; /* exit status of last command */
304 uint8_t back_exitstatus;/* exit status of backquoted command */
305 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
306 int rootpid; /* pid of main shell */
307 /* shell level: 0 for the main shell, 1 for its children, and so on */
309 #define rootshell (!shlvl)
310 char *minusc; /* argument to -c option */
312 char *curdir; // = nullstr; /* current working directory */
313 char *physdir; // = nullstr; /* physical working directory */
315 char *arg0; /* value of $0 */
317 struct jmploc *exception_handler;
319 volatile int suppress_int; /* counter */
320 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
321 volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
322 volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
323 smallint exception_type; /* kind of exception (0..5) */
325 #define EXINT 0 /* SIGINT received */
326 #define EXERROR 1 /* a generic error */
327 #define EXEXIT 4 /* exit the shell */
330 char nullstr[1]; /* zero length string */
333 #define eflag optlist[0]
334 #define fflag optlist[1]
335 #define Iflag optlist[2]
336 #define iflag optlist[3]
337 #define mflag optlist[4]
338 #define nflag optlist[5]
339 #define sflag optlist[6]
340 #define xflag optlist[7]
341 #define vflag optlist[8]
342 #define Cflag optlist[9]
343 #define aflag optlist[10]
344 #define bflag optlist[11]
345 #define uflag optlist[12]
346 #define viflag optlist[13]
348 # define pipefail optlist[14]
353 # define nolog optlist[14 + BASH_PIPEFAIL]
354 # define debug optlist[15 + BASH_PIPEFAIL]
357 /* trap handler commands */
359 * Sigmode records the current value of the signal handlers for the various
360 * modes. A value of zero means that the current handler is not known.
361 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
363 char sigmode[NSIG - 1];
364 #define S_DFL 1 /* default signal handling (SIG_DFL) */
365 #define S_CATCH 2 /* signal is caught */
366 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
367 #define S_HARD_IGN 4 /* signal is ignored permanently */
369 /* indicates specified signal received */
370 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
371 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
373 char **trap_ptr; /* used only by "trap hack" */
375 /* Rarely referenced stuff */
376 #if ENABLE_ASH_RANDOM_SUPPORT
379 pid_t backgndpid; /* pid of last background process */
381 extern struct globals_misc *const ash_ptr_to_globals_misc;
382 #define G_misc (*ash_ptr_to_globals_misc)
383 #define exitstatus (G_misc.exitstatus )
384 #define back_exitstatus (G_misc.back_exitstatus )
385 #define job_warning (G_misc.job_warning)
386 #define rootpid (G_misc.rootpid )
387 #define shlvl (G_misc.shlvl )
388 #define minusc (G_misc.minusc )
389 #define curdir (G_misc.curdir )
390 #define physdir (G_misc.physdir )
391 #define arg0 (G_misc.arg0 )
392 #define exception_handler (G_misc.exception_handler)
393 #define exception_type (G_misc.exception_type )
394 #define suppress_int (G_misc.suppress_int )
395 #define pending_int (G_misc.pending_int )
396 #define got_sigchld (G_misc.got_sigchld )
397 #define pending_sig (G_misc.pending_sig )
398 #define isloginsh (G_misc.isloginsh )
399 #define nullstr (G_misc.nullstr )
400 #define optlist (G_misc.optlist )
401 #define sigmode (G_misc.sigmode )
402 #define gotsig (G_misc.gotsig )
403 #define may_have_traps (G_misc.may_have_traps )
404 #define trap (G_misc.trap )
405 #define trap_ptr (G_misc.trap_ptr )
406 #define random_gen (G_misc.random_gen )
407 #define backgndpid (G_misc.backgndpid )
408 #define INIT_G_misc() do { \
409 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
417 /* ============ DEBUG */
419 static void trace_printf(const char *fmt, ...);
420 static void trace_vprintf(const char *fmt, va_list va);
421 # define TRACE(param) trace_printf param
422 # define TRACEV(param) trace_vprintf param
423 # define close(fd) do { \
425 if (close(dfd) < 0) \
426 bb_error_msg("bug on %d: closing %d(0x%x)", \
427 __LINE__, dfd, dfd); \
430 # define TRACE(param)
431 # define TRACEV(param)
435 /* ============ Utility functions */
436 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
437 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
440 isdigit_str9(const char *str)
442 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
443 while (--maxlen && isdigit(*str))
445 return (*str == '\0');
449 var_end(const char *var)
458 /* ============ Interrupts / exceptions */
460 static void exitshell(void) NORETURN;
463 * These macros allow the user to suspend the handling of interrupt signals
464 * over a period of time. This is similar to SIGHOLD or to sigblock, but
465 * much more efficient and portable. (But hacking the kernel is so much
466 * more fun than worrying about efficiency and portability. :-))
469 # define INT_OFF do { \
470 TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
475 # define INT_OFF do { \
482 * Called to raise an exception. Since C doesn't include exceptions, we
483 * just do a longjmp to the exception handler. The type of exception is
484 * stored in the global variable "exception_type".
486 static void raise_exception(int) NORETURN;
488 raise_exception(int e)
491 if (exception_handler == NULL)
496 longjmp(exception_handler->loc, 1);
499 #define raise_exception(e) do { \
500 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
501 raise_exception(e); \
506 * Called when a SIGINT is received. (If the user specifies
507 * that SIGINT is to be trapped or ignored using the trap builtin, then
508 * this routine is not called.) Suppressint is nonzero when interrupts
509 * are held using the INT_OFF macro. (The test for iflag is just
510 * defensive programming.)
512 static void raise_interrupt(void) NORETURN;
514 raise_interrupt(void)
517 /* Signal is not automatically unmasked after it is raised,
518 * do it ourself - unmask all signals */
519 sigprocmask_allsigs(SIG_UNBLOCK);
520 /* pending_sig = 0; - now done in signal_handler() */
522 if (!(rootshell && iflag)) {
523 /* Kill ourself with SIGINT */
524 signal(SIGINT, SIG_DFL);
527 /* bash: ^C even on empty command line sets $? */
528 exitstatus = SIGINT + 128;
529 raise_exception(EXINT);
533 #define raise_interrupt() do { \
534 TRACE(("raising interrupt on line %d\n", __LINE__)); \
539 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
543 if (--suppress_int == 0 && pending_int) {
548 # define INT_ON do { \
549 TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
553 # define INT_ON int_on()
555 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
563 #define FORCE_INT_ON force_int_on()
565 #define SAVE_INT(v) ((v) = suppress_int)
567 #define RESTORE_INT(v) do { \
569 suppress_int = (v); \
570 if (suppress_int == 0 && pending_int) \
575 /* ============ Stdout/stderr output */
578 outstr(const char *p, FILE *file)
586 flush_stdout_stderr(void)
593 /* Was called outcslow(c,FILE*), but c was always '\n' */
595 newline_and_flush(FILE *dest)
603 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
605 out1fmt(const char *fmt, ...)
612 r = vprintf(fmt, ap);
618 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
620 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
627 ret = vsnprintf(outbuf, length, fmt, ap);
634 out1str(const char *p)
640 out2str(const char *p)
643 flush_stdout_stderr();
647 /* ============ Parser structures */
649 /* control characters in argument strings */
650 #define CTL_FIRST CTLESC
651 #define CTLESC ((unsigned char)'\201') /* escape next character */
652 #define CTLVAR ((unsigned char)'\202') /* variable defn */
653 #define CTLENDVAR ((unsigned char)'\203')
654 #define CTLBACKQ ((unsigned char)'\204')
655 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
656 #define CTLENDARI ((unsigned char)'\207')
657 #define CTLQUOTEMARK ((unsigned char)'\210')
658 #define CTL_LAST CTLQUOTEMARK
660 /* variable substitution byte (follows CTLVAR) */
661 #define VSTYPE 0x0f /* type of variable substitution */
662 #define VSNUL 0x10 /* colon--treat the empty string as unset */
664 /* values of VSTYPE field */
665 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
666 #define VSMINUS 0x2 /* ${var-text} */
667 #define VSPLUS 0x3 /* ${var+text} */
668 #define VSQUESTION 0x4 /* ${var?message} */
669 #define VSASSIGN 0x5 /* ${var=text} */
670 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
671 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
672 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
673 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
674 #define VSLENGTH 0xa /* ${#var} */
676 #define VSSUBSTR 0xc /* ${var:position:length} */
678 #if BASH_PATTERN_SUBST
679 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
680 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
683 static const char dolatstr[] ALIGN1 = {
684 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
686 #define DOLATSTRLEN 6
705 #if BASH_REDIR_OUTPUT
722 smallint type; /* Nxxxx */
725 union node *redirect;
730 smallint pipe_backgnd;
731 struct nodelist *cmdlist;
737 union node *redirect;
750 union node *elsepart;
777 struct nodelist *backquote;
780 /* nfile and ndup layout must match!
781 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
782 * that it is actually NTO2 (>&file), and change its type.
799 char *_unused_expfname;
818 struct nredir nredir;
819 struct nbinary nbinary;
823 struct nclist nclist;
832 * NODE_EOF is returned by parsecmd when it encounters an end of file.
833 * It must be distinct from NULL.
835 #define NODE_EOF ((union node *) -1L)
838 struct nodelist *next;
851 freefunc(struct funcnode *f)
853 if (f && --f->count < 0)
858 /* ============ Debugging output */
862 static FILE *tracefile;
865 trace_printf(const char *fmt, ...)
872 fprintf(tracefile, "%u ", (int) time(NULL));
874 fprintf(tracefile, "[%u] ", (int) getpid());
876 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
878 vfprintf(tracefile, fmt, va);
883 trace_vprintf(const char *fmt, va_list va)
887 vfprintf(tracefile, fmt, va);
888 fprintf(tracefile, "\n");
892 trace_puts(const char *s)
900 trace_puts_quoted(char *s)
907 putc('"', tracefile);
908 for (p = s; *p; p++) {
909 switch ((unsigned char)*p) {
910 case '\n': c = 'n'; goto backslash;
911 case '\t': c = 't'; goto backslash;
912 case '\r': c = 'r'; goto backslash;
913 case '\"': c = '\"'; goto backslash;
914 case '\\': c = '\\'; goto backslash;
915 case CTLESC: c = 'e'; goto backslash;
916 case CTLVAR: c = 'v'; goto backslash;
917 case CTLBACKQ: c = 'q'; goto backslash;
919 putc('\\', tracefile);
923 if (*p >= ' ' && *p <= '~')
926 putc('\\', tracefile);
927 putc((*p >> 6) & 03, tracefile);
928 putc((*p >> 3) & 07, tracefile);
929 putc(*p & 07, tracefile);
934 putc('"', tracefile);
938 trace_puts_args(char **ap)
945 trace_puts_quoted(*ap);
947 putc('\n', tracefile);
950 putc(' ', tracefile);
965 /* leave open because libedit might be using it */
968 strcpy(s, "./trace");
970 if (!freopen(s, "a", tracefile)) {
971 fprintf(stderr, "Can't re-open %s\n", s);
976 tracefile = fopen(s, "a");
977 if (tracefile == NULL) {
978 fprintf(stderr, "Can't open %s\n", s);
984 flags = fcntl(fileno(tracefile), F_GETFL);
986 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
988 setlinebuf(tracefile);
989 fputs("\nTracing started.\n", tracefile);
993 indent(int amount, char *pfx, FILE *fp)
997 for (i = 0; i < amount; i++) {
998 if (pfx && i == amount - 1)
1004 /* little circular references here... */
1005 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
1008 sharg(union node *arg, FILE *fp)
1011 struct nodelist *bqlist;
1012 unsigned char subtype;
1014 if (arg->type != NARG) {
1015 out1fmt("<node type %d>\n", arg->type);
1018 bqlist = arg->narg.backquote;
1019 for (p = arg->narg.text; *p; p++) {
1020 switch ((unsigned char)*p) {
1029 if (subtype == VSLENGTH)
1037 if (subtype & VSNUL)
1040 switch (subtype & VSTYPE) {
1066 case VSTRIMRIGHTMAX:
1073 out1fmt("<subtype %d>", subtype);
1082 shtree(bqlist->n, -1, NULL, fp);
1093 shcmd(union node *cmd, FILE *fp)
1101 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1107 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1111 switch (np->nfile.type) {
1112 case NTO: s = ">>"+1; dftfd = 1; break;
1113 case NCLOBBER: s = ">|"; dftfd = 1; break;
1114 case NAPPEND: s = ">>"; dftfd = 1; break;
1115 #if BASH_REDIR_OUTPUT
1118 case NTOFD: s = ">&"; dftfd = 1; break;
1119 case NFROM: s = "<"; break;
1120 case NFROMFD: s = "<&"; break;
1121 case NFROMTO: s = "<>"; break;
1122 default: s = "*error*"; break;
1124 if (np->nfile.fd != dftfd)
1125 fprintf(fp, "%d", np->nfile.fd);
1127 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1128 fprintf(fp, "%d", np->ndup.dupfd);
1130 sharg(np->nfile.fname, fp);
1137 shtree(union node *n, int ind, char *pfx, FILE *fp)
1139 struct nodelist *lp;
1145 indent(ind, pfx, fp);
1147 if (n == NODE_EOF) {
1162 shtree(n->nbinary.ch1, ind, NULL, fp);
1165 shtree(n->nbinary.ch2, ind, NULL, fp);
1173 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1174 shtree(lp->n, 0, NULL, fp);
1178 if (n->npipe.pipe_backgnd)
1184 fprintf(fp, "<node type %d>", n->type);
1192 showtree(union node *n)
1194 trace_puts("showtree called\n");
1195 shtree(n, 1, NULL, stderr);
1201 /* ============ Parser data */
1204 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1207 struct strlist *next;
1214 struct strpush *prev; /* preceding string on stack */
1216 int prev_left_in_line;
1217 #if ENABLE_ASH_ALIAS
1218 struct alias *ap; /* if push was associated with an alias */
1220 char *string; /* remember the string since it may change */
1222 /* Remember last two characters for pungetc. */
1225 /* Number of outstanding calls to pungetc. */
1230 struct parsefile *prev; /* preceding file on stack */
1231 int linno; /* current line */
1232 int pf_fd; /* file descriptor (or -1 if string) */
1233 int left_in_line; /* number of chars left in this line */
1234 int left_in_buffer; /* number of chars left in this buffer past the line */
1235 char *next_to_pgetc; /* next char in buffer */
1236 char *buf; /* input buffer */
1237 struct strpush *strpush; /* for pushing strings at this level */
1238 struct strpush basestrpush; /* so pushing one is fast */
1240 /* Remember last two characters for pungetc. */
1243 /* Number of outstanding calls to pungetc. */
1247 static struct parsefile basepf; /* top level input file */
1248 static struct parsefile *g_parsefile = &basepf; /* current input file */
1249 static int startlinno; /* line # where last token started */
1250 static char *commandname; /* currently executing command */
1251 static struct strlist *cmdenviron; /* environment for builtin command */
1254 /* ============ Message printing */
1257 ash_vmsg(const char *msg, va_list ap)
1259 fprintf(stderr, "%s: ", arg0);
1261 if (strcmp(arg0, commandname))
1262 fprintf(stderr, "%s: ", commandname);
1263 if (!iflag || g_parsefile->pf_fd > 0)
1264 fprintf(stderr, "line %d: ", startlinno);
1266 vfprintf(stderr, msg, ap);
1267 newline_and_flush(stderr);
1271 * Exverror is called to raise the error exception. If the second argument
1272 * is not NULL then error prints an error message using printf style
1273 * formatting. It then raises the error exception.
1275 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1277 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1281 TRACE(("ash_vmsg_and_raise(%d):", cond));
1284 TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
1289 flush_stdout_stderr();
1290 raise_exception(cond);
1294 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1296 ash_msg_and_raise_error(const char *msg, ...)
1303 ash_vmsg_and_raise(EXERROR, msg, ap);
1308 static void raise_error_syntax(const char *) NORETURN;
1310 raise_error_syntax(const char *msg)
1312 ash_msg_and_raise_error("syntax error: %s", msg);
1316 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1318 ash_msg_and_raise(int cond, const char *msg, ...)
1323 ash_vmsg_and_raise(cond, msg, ap);
1329 * error/warning routines for external builtins
1332 ash_msg(const char *fmt, ...)
1342 * Return a string describing an error. The returned string may be a
1343 * pointer to a static buffer that will be overwritten on the next call.
1344 * Action describes the operation that got the error.
1347 errmsg(int e, const char *em)
1349 if (e == ENOENT || e == ENOTDIR) {
1356 /* ============ Memory allocation */
1359 /* I consider these wrappers nearly useless:
1360 * ok, they return you to nearest exception handler, but
1361 * how much memory do you leak in the process, making
1362 * memory starvation worse?
1365 ckrealloc(void * p, size_t nbytes)
1367 p = realloc(p, nbytes);
1369 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1374 ckmalloc(size_t nbytes)
1376 return ckrealloc(NULL, nbytes);
1380 ckzalloc(size_t nbytes)
1382 return memset(ckmalloc(nbytes), 0, nbytes);
1386 ckstrdup(const char *s)
1388 char *p = strdup(s);
1390 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1394 /* Using bbox equivalents. They exit if out of memory */
1395 # define ckrealloc xrealloc
1396 # define ckmalloc xmalloc
1397 # define ckzalloc xzalloc
1398 # define ckstrdup xstrdup
1402 * It appears that grabstackstr() will barf with such alignments
1403 * because stalloc() will return a string allocated in a new stackblock.
1405 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1407 /* Most machines require the value returned from malloc to be aligned
1408 * in some way. The following macro will get this right
1409 * on many machines. */
1410 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1411 /* Minimum size of a block */
1412 MINSIZE = SHELL_ALIGN(504),
1415 struct stack_block {
1416 struct stack_block *prev;
1417 char space[MINSIZE];
1421 struct stack_block *stackp;
1427 struct globals_memstack {
1428 struct stack_block *g_stackp; // = &stackbase;
1429 char *g_stacknxt; // = stackbase.space;
1430 char *sstrend; // = stackbase.space + MINSIZE;
1431 size_t g_stacknleft; // = MINSIZE;
1432 struct stack_block stackbase;
1434 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1435 #define G_memstack (*ash_ptr_to_globals_memstack)
1436 #define g_stackp (G_memstack.g_stackp )
1437 #define g_stacknxt (G_memstack.g_stacknxt )
1438 #define sstrend (G_memstack.sstrend )
1439 #define g_stacknleft (G_memstack.g_stacknleft)
1440 #define stackbase (G_memstack.stackbase )
1441 #define INIT_G_memstack() do { \
1442 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1444 g_stackp = &stackbase; \
1445 g_stacknxt = stackbase.space; \
1446 g_stacknleft = MINSIZE; \
1447 sstrend = stackbase.space + MINSIZE; \
1451 #define stackblock() ((void *)g_stacknxt)
1452 #define stackblocksize() g_stacknleft
1455 * Parse trees for commands are allocated in lifo order, so we use a stack
1456 * to make this more efficient, and also to avoid all sorts of exception
1457 * handling code to handle interrupts in the middle of a parse.
1459 * The size 504 was chosen because the Ultrix malloc handles that size
1463 stalloc(size_t nbytes)
1468 aligned = SHELL_ALIGN(nbytes);
1469 if (aligned > g_stacknleft) {
1472 struct stack_block *sp;
1474 blocksize = aligned;
1475 if (blocksize < MINSIZE)
1476 blocksize = MINSIZE;
1477 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1478 if (len < blocksize)
1479 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1482 sp->prev = g_stackp;
1483 g_stacknxt = sp->space;
1484 g_stacknleft = blocksize;
1485 sstrend = g_stacknxt + blocksize;
1490 g_stacknxt += aligned;
1491 g_stacknleft -= aligned;
1496 stzalloc(size_t nbytes)
1498 return memset(stalloc(nbytes), 0, nbytes);
1505 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1506 write(STDERR_FILENO, "stunalloc\n", 10);
1510 g_stacknleft += g_stacknxt - (char *)p;
1515 * Like strdup but works with the ash stack.
1518 sstrdup(const char *p)
1520 size_t len = strlen(p) + 1;
1521 return memcpy(stalloc(len), p, len);
1525 grabstackblock(size_t len)
1531 pushstackmark(struct stackmark *mark, size_t len)
1533 mark->stackp = g_stackp;
1534 mark->stacknxt = g_stacknxt;
1535 mark->stacknleft = g_stacknleft;
1536 grabstackblock(len);
1540 setstackmark(struct stackmark *mark)
1542 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1546 popstackmark(struct stackmark *mark)
1548 struct stack_block *sp;
1554 while (g_stackp != mark->stackp) {
1556 g_stackp = sp->prev;
1559 g_stacknxt = mark->stacknxt;
1560 g_stacknleft = mark->stacknleft;
1561 sstrend = mark->stacknxt + mark->stacknleft;
1566 * When the parser reads in a string, it wants to stick the string on the
1567 * stack and only adjust the stack pointer when it knows how big the
1568 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1569 * of space on top of the stack and stackblocklen returns the length of
1570 * this block. Growstackblock will grow this space by at least one byte,
1571 * possibly moving it (like realloc). Grabstackblock actually allocates the
1572 * part of the block that has been used.
1575 growstackblock(void)
1579 newlen = g_stacknleft * 2;
1580 if (newlen < g_stacknleft)
1581 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1585 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1586 struct stack_block *sp;
1587 struct stack_block *prevstackp;
1592 prevstackp = sp->prev;
1593 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1594 sp = ckrealloc(sp, grosslen);
1595 sp->prev = prevstackp;
1597 g_stacknxt = sp->space;
1598 g_stacknleft = newlen;
1599 sstrend = sp->space + newlen;
1602 char *oldspace = g_stacknxt;
1603 size_t oldlen = g_stacknleft;
1604 char *p = stalloc(newlen);
1606 /* free the space we just allocated */
1607 g_stacknxt = memcpy(p, oldspace, oldlen);
1608 g_stacknleft += newlen;
1613 * The following routines are somewhat easier to use than the above.
1614 * The user declares a variable of type STACKSTR, which may be declared
1615 * to be a register. The macro STARTSTACKSTR initializes things. Then
1616 * the user uses the macro STPUTC to add characters to the string. In
1617 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1618 * grown as necessary. When the user is done, she can just leave the
1619 * string there and refer to it using stackblock(). Or she can allocate
1620 * the space for it using grabstackstr(). If it is necessary to allow
1621 * someone else to use the stack temporarily and then continue to grow
1622 * the string, the user should use grabstack to allocate the space, and
1623 * then call ungrabstr(p) to return to the previous mode of operation.
1625 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1626 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1627 * is space for at least one character.
1632 size_t len = stackblocksize();
1634 return (char *)stackblock() + len;
1638 * Called from CHECKSTRSPACE.
1641 makestrspace(size_t newlen, char *p)
1643 size_t len = p - g_stacknxt;
1649 size = stackblocksize();
1651 if (nleft >= newlen)
1655 return (char *)stackblock() + len;
1659 stack_nputstr(const char *s, size_t n, char *p)
1661 p = makestrspace(n, p);
1662 p = (char *)memcpy(p, s, n) + n;
1667 stack_putstr(const char *s, char *p)
1669 return stack_nputstr(s, strlen(s), p);
1673 _STPUTC(int c, char *p)
1681 #define STARTSTACKSTR(p) ((p) = stackblock())
1682 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1683 #define CHECKSTRSPACE(n, p) do { \
1686 size_t m = sstrend - q; \
1688 (p) = makestrspace(l, q); \
1690 #define USTPUTC(c, p) (*(p)++ = (c))
1691 #define STACKSTRNUL(p) do { \
1692 if ((p) == sstrend) \
1693 (p) = growstackstr(); \
1696 #define STUNPUTC(p) (--(p))
1697 #define STTOPC(p) ((p)[-1])
1698 #define STADJUST(amount, p) ((p) += (amount))
1700 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1701 #define ungrabstackstr(s, p) stunalloc(s)
1702 #define stackstrend() ((void *)sstrend)
1705 /* ============ String helpers */
1708 * prefix -- see if pfx is a prefix of string.
1711 prefix(const char *string, const char *pfx)
1714 if (*pfx++ != *string++)
1717 return (char *) string;
1721 * Check for a valid number. This should be elsewhere.
1724 is_number(const char *p)
1729 } while (*++p != '\0');
1734 * Convert a string of digits to an integer, printing an error message on
1738 number(const char *s)
1741 ash_msg_and_raise_error(msg_illnum, s);
1746 * Produce a possibly single quoted string suitable as input to the shell.
1747 * The return string is allocated on the stack.
1750 single_quote(const char *s)
1760 len = strchrnul(s, '\'') - s;
1762 q = p = makestrspace(len + 3, p);
1765 q = (char *)memcpy(q, s, len) + len;
1774 do len++; while (*++s == '\'');
1776 q = p = makestrspace(len + 3, p);
1779 q = (char *)memcpy(q, s - len, len) + len;
1787 return stackblock();
1791 /* ============ nextopt */
1793 static char **argptr; /* argument list for builtin commands */
1794 static char *optionarg; /* set by nextopt (like getopt) */
1795 static char *optptr; /* used by nextopt */
1798 * XXX - should get rid of. Have all builtins use getopt(3).
1799 * The library getopt must have the BSD extension static variable
1800 * "optreset", otherwise it can't be used within the shell safely.
1802 * Standard option processing (a la getopt) for builtin routines.
1803 * The only argument that is passed to nextopt is the option string;
1804 * the other arguments are unnecessary. It returns the character,
1805 * or '\0' on end of input.
1808 nextopt(const char *optstring)
1815 if (p == NULL || *p == '\0') {
1816 /* We ate entire "-param", take next one */
1822 if (*++p == '\0') /* just "-" ? */
1825 if (LONE_DASH(p)) /* "--" ? */
1827 /* p => next "-param" */
1829 /* p => some option char in the middle of a "-param" */
1831 for (q = optstring; *q != c;) {
1833 ash_msg_and_raise_error("illegal option -%c", c);
1841 ash_msg_and_raise_error("no arg for -%c option", c);
1851 /* ============ Shell variables */
1854 * The parsefile structure pointed to by the global variable parsefile
1855 * contains information about the current file being read.
1858 int nparam; /* # of positional parameters (without $0) */
1859 #if ENABLE_ASH_GETOPTS
1860 int optind; /* next parameter to be processed by getopts */
1861 int optoff; /* used by getopts */
1863 unsigned char malloced; /* if parameter list dynamically allocated */
1864 char **p; /* parameter list */
1868 * Free the list of positional parameters.
1871 freeparam(volatile struct shparam *param)
1873 if (param->malloced) {
1875 ap = ap1 = param->p;
1882 #if ENABLE_ASH_GETOPTS
1883 static void FAST_FUNC getoptsreset(const char *value);
1887 struct var *next; /* next entry in hash list */
1888 int flags; /* flags are defined above */
1889 const char *var_text; /* name=value */
1890 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1891 /* the variable gets set/unset */
1895 struct localvar *next; /* next local variable in list */
1896 struct var *vp; /* the variable that was made local */
1897 int flags; /* saved flags */
1898 const char *text; /* saved text */
1902 #define VEXPORT 0x01 /* variable is exported */
1903 #define VREADONLY 0x02 /* variable cannot be modified */
1904 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1905 #define VTEXTFIXED 0x08 /* text is statically allocated */
1906 #define VSTACK 0x10 /* text is allocated on the stack */
1907 #define VUNSET 0x20 /* the variable is not set */
1908 #define VNOFUNC 0x40 /* don't call the callback function */
1909 #define VNOSET 0x80 /* do not set variable - just readonly test */
1910 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1911 #if ENABLE_ASH_RANDOM_SUPPORT
1912 # define VDYNAMIC 0x200 /* dynamic variable */
1918 /* Need to be before varinit_data[] */
1919 #if ENABLE_LOCALE_SUPPORT
1920 static void FAST_FUNC
1921 change_lc_all(const char *value)
1923 if (value && *value != '\0')
1924 setlocale(LC_ALL, value);
1926 static void FAST_FUNC
1927 change_lc_ctype(const char *value)
1929 if (value && *value != '\0')
1930 setlocale(LC_CTYPE, value);
1934 static void chkmail(void);
1935 static void changemail(const char *var_value) FAST_FUNC;
1937 # define chkmail() ((void)0)
1939 static void changepath(const char *) FAST_FUNC;
1940 #if ENABLE_ASH_RANDOM_SUPPORT
1941 static void change_random(const char *) FAST_FUNC;
1944 static const struct {
1946 const char *var_text;
1947 void (*var_func)(const char *) FAST_FUNC;
1948 } varinit_data[] = {
1950 * Note: VEXPORT would not work correctly here for NOFORK applets:
1951 * some environment strings may be constant.
1953 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1955 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1956 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1958 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1959 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1960 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1961 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1962 #if ENABLE_ASH_GETOPTS
1963 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
1965 #if ENABLE_ASH_RANDOM_SUPPORT
1966 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1968 #if ENABLE_LOCALE_SUPPORT
1969 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1970 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1972 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1973 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1979 struct globals_var {
1980 struct shparam shellparam; /* $@ current positional parameters */
1981 struct redirtab *redirlist;
1982 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1983 struct var *vartab[VTABSIZE];
1984 struct var varinit[ARRAY_SIZE(varinit_data)];
1986 extern struct globals_var *const ash_ptr_to_globals_var;
1987 #define G_var (*ash_ptr_to_globals_var)
1988 #define shellparam (G_var.shellparam )
1989 //#define redirlist (G_var.redirlist )
1990 #define preverrout_fd (G_var.preverrout_fd)
1991 #define vartab (G_var.vartab )
1992 #define varinit (G_var.varinit )
1993 #define INIT_G_var() do { \
1995 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1997 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1998 varinit[i].flags = varinit_data[i].flags; \
1999 varinit[i].var_text = varinit_data[i].var_text; \
2000 varinit[i].var_func = varinit_data[i].var_func; \
2004 #define vifs varinit[0]
2006 # define vmail (&vifs)[1]
2007 # define vmpath (&vmail)[1]
2008 # define vpath (&vmpath)[1]
2010 # define vpath (&vifs)[1]
2012 #define vps1 (&vpath)[1]
2013 #define vps2 (&vps1)[1]
2014 #define vps4 (&vps2)[1]
2015 #if ENABLE_ASH_GETOPTS
2016 # define voptind (&vps4)[1]
2017 # if ENABLE_ASH_RANDOM_SUPPORT
2018 # define vrandom (&voptind)[1]
2021 # if ENABLE_ASH_RANDOM_SUPPORT
2022 # define vrandom (&vps4)[1]
2027 * The following macros access the values of the above variables.
2028 * They have to skip over the name. They return the null string
2029 * for unset variables.
2031 #define ifsval() (vifs.var_text + 4)
2032 #define ifsset() ((vifs.flags & VUNSET) == 0)
2034 # define mailval() (vmail.var_text + 5)
2035 # define mpathval() (vmpath.var_text + 9)
2036 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2038 #define pathval() (vpath.var_text + 5)
2039 #define ps1val() (vps1.var_text + 4)
2040 #define ps2val() (vps2.var_text + 4)
2041 #define ps4val() (vps4.var_text + 4)
2042 #if ENABLE_ASH_GETOPTS
2043 # define optindval() (voptind.var_text + 7)
2046 #if ENABLE_ASH_GETOPTS
2047 static void FAST_FUNC
2048 getoptsreset(const char *value)
2050 shellparam.optind = number(value) ?: 1;
2051 shellparam.optoff = -1;
2056 * Compares two strings up to the first = or '\0'. The first
2057 * string must be terminated by '='; the second may be terminated by
2058 * either '=' or '\0'.
2061 varcmp(const char *p, const char *q)
2065 while ((c = *p) == (d = *q)) {
2066 if (c == '\0' || c == '=')
2080 * Find the appropriate entry in the hash table from the name.
2082 static struct var **
2083 hashvar(const char *p)
2087 hashval = ((unsigned char) *p) << 4;
2088 while (*p && *p != '=')
2089 hashval += (unsigned char) *p++;
2090 return &vartab[hashval % VTABSIZE];
2094 vpcmp(const void *a, const void *b)
2096 return varcmp(*(const char **)a, *(const char **)b);
2100 * This routine initializes the builtin variables.
2110 * PS1 depends on uid
2112 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2113 vps1.var_text = "PS1=\\w \\$ ";
2116 vps1.var_text = "PS1=# ";
2119 end = vp + ARRAY_SIZE(varinit);
2121 vpp = hashvar(vp->var_text);
2124 } while (++vp < end);
2127 static struct var **
2128 findvar(struct var **vpp, const char *name)
2130 for (; *vpp; vpp = &(*vpp)->next) {
2131 if (varcmp((*vpp)->var_text, name) == 0) {
2139 * Find the value of a variable. Returns NULL if not set.
2141 static const char* FAST_FUNC
2142 lookupvar(const char *name)
2146 v = *findvar(hashvar(name), name);
2148 #if ENABLE_ASH_RANDOM_SUPPORT
2150 * Dynamic variables are implemented roughly the same way they are
2151 * in bash. Namely, they're "special" so long as they aren't unset.
2152 * As soon as they're unset, they're no longer dynamic, and dynamic
2153 * lookup will no longer happen at that point. -- PFM.
2155 if (v->flags & VDYNAMIC)
2158 if (!(v->flags & VUNSET))
2159 return var_end(v->var_text);
2164 #if ENABLE_UNICODE_SUPPORT
2166 reinit_unicode_for_ash(void)
2168 /* Unicode support should be activated even if LANG is set
2169 * _during_ shell execution, not only if it was set when
2170 * shell was started. Therefore, re-check LANG every time:
2172 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2173 || ENABLE_UNICODE_USING_LOCALE
2175 const char *s = lookupvar("LC_ALL");
2176 if (!s) s = lookupvar("LC_CTYPE");
2177 if (!s) s = lookupvar("LANG");
2182 # define reinit_unicode_for_ash() ((void)0)
2186 * Search the environment of a builtin command.
2189 bltinlookup(const char *name)
2193 for (sp = cmdenviron; sp; sp = sp->next) {
2194 if (varcmp(sp->text, name) == 0)
2195 return var_end(sp->text);
2197 return lookupvar(name);
2201 * Same as setvar except that the variable and value are passed in
2202 * the first argument as name=value. Since the first argument will
2203 * be actually stored in the table, it should not be a string that
2205 * Called with interrupts off.
2208 setvareq(char *s, int flags)
2210 struct var *vp, **vpp;
2213 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2214 vp = *findvar(vpp, s);
2216 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2219 if (flags & VNOSAVE)
2223 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2229 if (vp->var_func && !(flags & VNOFUNC))
2230 vp->var_func(var_end(s));
2232 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2233 free((char*)vp->var_text);
2235 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2237 /* variable s is not found */
2240 vp = ckzalloc(sizeof(*vp));
2242 /*vp->func = NULL; - ckzalloc did it */
2245 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2252 * Set the value of a variable. The flags argument is ored with the
2253 * flags of the variable. If val is NULL, the variable is unset.
2256 setvar(const char *name, const char *val, int flags)
2264 q = endofname(name);
2265 p = strchrnul(q, '=');
2267 if (!namelen || p != q)
2268 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2273 vallen = strlen(val);
2277 nameeq = ckmalloc(namelen + vallen + 2);
2278 p = memcpy(nameeq, name, namelen) + namelen;
2281 p = memcpy(p, val, vallen) + vallen;
2284 setvareq(nameeq, flags | VNOSAVE);
2288 static void FAST_FUNC
2289 setvar0(const char *name, const char *val)
2291 setvar(name, val, 0);
2295 * Unset the specified variable.
2298 unsetvar(const char *s)
2304 vpp = findvar(hashvar(s), s);
2308 int flags = vp->flags;
2311 if (flags & VREADONLY)
2313 #if ENABLE_ASH_RANDOM_SUPPORT
2314 vp->flags &= ~VDYNAMIC;
2318 if ((flags & VSTRFIXED) == 0) {
2320 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2321 free((char*)vp->var_text);
2327 vp->flags &= ~VEXPORT;
2337 * Process a linked list of variable assignments.
2340 listsetvar(struct strlist *list_set_var, int flags)
2342 struct strlist *lp = list_set_var;
2348 setvareq(lp->text, flags);
2355 * Generate a list of variables satisfying the given conditions.
2358 listvars(int on, int off, char ***end)
2369 for (vp = *vpp; vp; vp = vp->next) {
2370 if ((vp->flags & mask) == on) {
2371 if (ep == stackstrend())
2372 ep = growstackstr();
2373 *ep++ = (char*)vp->var_text;
2376 } while (++vpp < vartab + VTABSIZE);
2377 if (ep == stackstrend())
2378 ep = growstackstr();
2382 return grabstackstr(ep);
2386 /* ============ Path search helper
2388 * The variable path (passed by reference) should be set to the start
2389 * of the path before the first call; path_advance will update
2390 * this value as it proceeds. Successive calls to path_advance will return
2391 * the possible path expansions in sequence. If an option (indicated by
2392 * a percent sign) appears in the path entry then the global variable
2393 * pathopt will be set to point to it; otherwise pathopt will be set to
2396 static const char *pathopt; /* set by path_advance */
2399 path_advance(const char **path, const char *name)
2409 for (p = start; *p && *p != ':' && *p != '%'; p++)
2411 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2412 while (stackblocksize() < len)
2416 memcpy(q, start, p - start);
2424 while (*p && *p != ':')
2431 return stalloc(len);
2435 /* ============ Prompt */
2437 static smallint doprompt; /* if set, prompt the user */
2438 static smallint needprompt; /* true if interactive and at start of line */
2440 #if ENABLE_FEATURE_EDITING
2441 static line_input_t *line_input_state;
2442 static const char *cmdedit_prompt;
2444 putprompt(const char *s)
2446 if (ENABLE_ASH_EXPAND_PRMT) {
2447 free((char*)cmdedit_prompt);
2448 cmdedit_prompt = ckstrdup(s);
2455 putprompt(const char *s)
2461 /* expandstr() needs parsing machinery, so it is far away ahead... */
2462 static const char *expandstr(const char *ps);
2465 setprompt_if(smallint do_set, int whichprompt)
2468 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2475 switch (whichprompt) {
2485 #if ENABLE_ASH_EXPAND_PRMT
2486 pushstackmark(&smark, stackblocksize());
2487 putprompt(expandstr(prompt));
2488 popstackmark(&smark);
2495 /* ============ The cd and pwd commands */
2497 #define CD_PHYSICAL 1
2507 while ((i = nextopt("LP")) != '\0') {
2509 flags ^= CD_PHYSICAL;
2518 * Update curdir (the name of the current directory) in response to a
2522 updatepwd(const char *dir)
2529 cdcomppath = sstrdup(dir);
2532 if (curdir == nullstr)
2534 new = stack_putstr(curdir, new);
2536 new = makestrspace(strlen(dir) + 2, new);
2537 lim = (char *)stackblock() + 1;
2541 if (new > lim && *lim == '/')
2546 if (dir[1] == '/' && dir[2] != '/') {
2552 p = strtok(cdcomppath, "/");
2556 if (p[1] == '.' && p[2] == '\0') {
2568 new = stack_putstr(p, new);
2571 p = strtok(NULL, "/");
2576 return stackblock();
2580 * Find out what the current directory is. If we already know the current
2581 * directory, this routine returns immediately.
2586 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2587 return dir ? dir : nullstr;
2591 setpwd(const char *val, int setold)
2595 oldcur = dir = curdir;
2598 setvar("OLDPWD", oldcur, VEXPORT);
2601 if (physdir != nullstr) {
2602 if (physdir != oldcur)
2606 if (oldcur == val || !val) {
2612 dir = ckstrdup(val);
2613 if (oldcur != dir && oldcur != nullstr) {
2618 setvar("PWD", dir, VEXPORT);
2621 static void hashcd(void);
2624 * Actually do the chdir. We also call hashcd to let other routines
2625 * know that the current directory has changed.
2628 docd(const char *dest, int flags)
2630 const char *dir = NULL;
2633 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2636 if (!(flags & CD_PHYSICAL)) {
2637 dir = updatepwd(dest);
2651 static int FAST_FUNC
2652 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2664 dest = bltinlookup("HOME");
2665 else if (LONE_DASH(dest)) {
2666 dest = bltinlookup("OLDPWD");
2688 path = bltinlookup("CDPATH");
2691 p = path_advance(&path, dest);
2692 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2696 if (!docd(p, flags))
2707 ash_msg_and_raise_error("can't cd to %s", dest);
2710 if (flags & CD_PRINT)
2711 out1fmt("%s\n", curdir);
2715 static int FAST_FUNC
2716 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2719 const char *dir = curdir;
2723 if (physdir == nullstr)
2727 out1fmt("%s\n", dir);
2732 /* ============ ... */
2735 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2737 /* Syntax classes */
2738 #define CWORD 0 /* character is nothing special */
2739 #define CNL 1 /* newline character */
2740 #define CBACK 2 /* a backslash character */
2741 #define CSQUOTE 3 /* single quote */
2742 #define CDQUOTE 4 /* double quote */
2743 #define CENDQUOTE 5 /* a terminating quote */
2744 #define CBQUOTE 6 /* backwards single quote */
2745 #define CVAR 7 /* a dollar sign */
2746 #define CENDVAR 8 /* a '}' character */
2747 #define CLP 9 /* a left paren in arithmetic */
2748 #define CRP 10 /* a right paren in arithmetic */
2749 #define CENDFILE 11 /* end of file */
2750 #define CCTL 12 /* like CWORD, except it must be escaped */
2751 #define CSPCL 13 /* these terminate a word */
2752 #define CIGN 14 /* character should be ignored */
2755 #if ENABLE_ASH_ALIAS
2759 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2761 #if ENABLE_FEATURE_SH_MATH
2762 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2764 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2766 static const uint16_t S_I_T[] ALIGN2 = {
2767 #if ENABLE_ASH_ALIAS
2768 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2770 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2771 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2772 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2773 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2774 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2775 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2776 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2777 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2778 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2779 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2780 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2781 #if !USE_SIT_FUNCTION
2782 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2783 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2784 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2788 /* Constants below must match table above */
2790 #if ENABLE_ASH_ALIAS
2791 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2793 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2794 CNL_CNL_CNL_CNL , /* 2 */
2795 CWORD_CCTL_CCTL_CWORD , /* 3 */
2796 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2797 CVAR_CVAR_CWORD_CVAR , /* 5 */
2798 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2799 CSPCL_CWORD_CWORD_CLP , /* 7 */
2800 CSPCL_CWORD_CWORD_CRP , /* 8 */
2801 CBACK_CBACK_CCTL_CBACK , /* 9 */
2802 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2803 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2804 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2805 CWORD_CWORD_CWORD_CWORD , /* 13 */
2806 CCTL_CCTL_CCTL_CCTL , /* 14 */
2809 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2810 * caller must ensure proper cast on it if c is *char_ptr!
2812 /* Values for syntax param */
2813 #define BASESYNTAX 0 /* not in quotes */
2814 #define DQSYNTAX 1 /* in double quotes */
2815 #define SQSYNTAX 2 /* in single quotes */
2816 #define ARISYNTAX 3 /* in arithmetic */
2817 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2819 #if USE_SIT_FUNCTION
2822 SIT(int c, int syntax)
2824 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2825 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2827 * This causes '/' to be prepended with CTLESC in dquoted string,
2828 * making "./file"* treated incorrectly because we feed
2829 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2830 * The "homegrown" glob implementation is okay with that,
2831 * but glibc one isn't. With '/' always treated as CWORD,
2834 # if ENABLE_ASH_ALIAS
2835 static const uint8_t syntax_index_table[] ALIGN1 = {
2836 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2837 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2838 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2842 static const uint8_t syntax_index_table[] ALIGN1 = {
2843 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2844 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2845 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2854 # if ENABLE_ASH_ALIAS
2860 /* Cast is purely for paranoia here,
2861 * just in case someone passed signed char to us */
2862 if ((unsigned char)c >= CTL_FIRST
2863 && (unsigned char)c <= CTL_LAST
2867 s = strchrnul(spec_symbls, c);
2870 indx = syntax_index_table[s - spec_symbls];
2872 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2875 #else /* !USE_SIT_FUNCTION */
2877 static const uint8_t syntax_index_table[] ALIGN1 = {
2878 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2879 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2889 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2890 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2912 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2913 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2914 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2916 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2918 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2919 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2920 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2921 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2922 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2924 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2925 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2926 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2927 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2939 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2940 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2941 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2942 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2943 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2944 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2972 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2973 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2974 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2977 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3005 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3006 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3007 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3008 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3010 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3011 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3012 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3013 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3014 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3015 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3016 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3017 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3120 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3121 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3122 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3123 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3124 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3125 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3126 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3127 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3128 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3129 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3130 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3131 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3132 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3133 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3134 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3135 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3136 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3137 # if ENABLE_ASH_ALIAS
3138 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3143 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3144 #else /* debug version, caught one signed char bug */
3145 # define SIT(c, syntax) \
3147 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3148 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3149 if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
3150 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3151 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3155 #endif /* !USE_SIT_FUNCTION */
3158 /* ============ Alias handling */
3160 #if ENABLE_ASH_ALIAS
3162 #define ALIASINUSE 1
3173 static struct alias **atab; // [ATABSIZE];
3174 #define INIT_G_alias() do { \
3175 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3179 static struct alias **
3180 __lookupalias(const char *name)
3182 unsigned int hashval;
3189 ch = (unsigned char)*p;
3193 ch = (unsigned char)*++p;
3195 app = &atab[hashval % ATABSIZE];
3197 for (; *app; app = &(*app)->next) {
3198 if (strcmp(name, (*app)->name) == 0) {
3206 static struct alias *
3207 lookupalias(const char *name, int check)
3209 struct alias *ap = *__lookupalias(name);
3211 if (check && ap && (ap->flag & ALIASINUSE))
3216 static struct alias *
3217 freealias(struct alias *ap)
3221 if (ap->flag & ALIASINUSE) {
3222 ap->flag |= ALIASDEAD;
3234 setalias(const char *name, const char *val)
3236 struct alias *ap, **app;
3238 app = __lookupalias(name);
3242 if (!(ap->flag & ALIASINUSE)) {
3245 ap->val = ckstrdup(val);
3246 ap->flag &= ~ALIASDEAD;
3249 ap = ckzalloc(sizeof(struct alias));
3250 ap->name = ckstrdup(name);
3251 ap->val = ckstrdup(val);
3252 /*ap->flag = 0; - ckzalloc did it */
3253 /*ap->next = NULL;*/
3260 unalias(const char *name)
3264 app = __lookupalias(name);
3268 *app = freealias(*app);
3279 struct alias *ap, **app;
3283 for (i = 0; i < ATABSIZE; i++) {
3285 for (ap = *app; ap; ap = *app) {
3286 *app = freealias(*app);
3296 printalias(const struct alias *ap)
3298 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3302 * TODO - sort output
3304 static int FAST_FUNC
3305 aliascmd(int argc UNUSED_PARAM, char **argv)
3314 for (i = 0; i < ATABSIZE; i++) {
3315 for (ap = atab[i]; ap; ap = ap->next) {
3321 while ((n = *++argv) != NULL) {
3322 v = strchr(n+1, '=');
3323 if (v == NULL) { /* n+1: funny ksh stuff */
3324 ap = *__lookupalias(n);
3326 fprintf(stderr, "%s: %s not found\n", "alias", n);
3339 static int FAST_FUNC
3340 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3344 while (nextopt("a") != '\0') {
3348 for (i = 0; *argptr; argptr++) {
3349 if (unalias(*argptr)) {
3350 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3358 #endif /* ASH_ALIAS */
3361 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3364 #define FORK_NOJOB 2
3366 /* mode flags for showjob(s) */
3367 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3368 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3369 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3370 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3373 * A job structure contains information about a job. A job is either a
3374 * single process or a set of processes contained in a pipeline. In the
3375 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3379 pid_t ps_pid; /* process id */
3380 int ps_status; /* last process status from wait() */
3381 char *ps_cmd; /* text of command being run */
3385 struct procstat ps0; /* status of process */
3386 struct procstat *ps; /* status or processes when more than one */
3388 int stopstatus; /* status of a stopped job */
3390 unsigned nprocs; /* number of processes */
3392 #define JOBRUNNING 0 /* at least one proc running */
3393 #define JOBSTOPPED 1 /* all procs are stopped */
3394 #define JOBDONE 2 /* all procs are completed */
3398 sigint: 1, /* job was killed by SIGINT */
3399 jobctl: 1, /* job running under job control */
3401 waited: 1, /* true if this entry has been waited for */
3402 used: 1, /* true if this entry is in used */
3403 changed: 1; /* true if status has changed */
3404 struct job *prev_job; /* previous job */
3407 static struct job *makejob(/*union node *,*/ int);
3408 static int forkshell(struct job *, union node *, int);
3409 static int waitforjob(struct job *);
3412 enum { doing_jobctl = 0 };
3413 #define setjobctl(on) do {} while (0)
3415 static smallint doing_jobctl; //references:8
3416 static void setjobctl(int);
3423 ignoresig(int signo)
3425 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3426 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3427 /* No, need to do it */
3428 signal(signo, SIG_IGN);
3430 sigmode[signo - 1] = S_HARD_IGN;
3434 * Only one usage site - in setsignal()
3437 signal_handler(int signo)
3439 if (signo == SIGCHLD) {
3445 gotsig[signo - 1] = 1;
3446 pending_sig = signo;
3448 if (signo == SIGINT && !trap[SIGINT]) {
3449 if (!suppress_int) {
3451 raise_interrupt(); /* does not return */
3458 * Set the signal handler for the specified signal. The routine figures
3459 * out what it should be set to.
3462 setsignal(int signo)
3465 char cur_act, new_act;
3466 struct sigaction act;
3470 if (t != NULL) { /* trap for this sig is set */
3472 if (t[0] == '\0') /* trap is "": ignore this sig */
3476 if (rootshell && new_act == S_DFL) {
3479 if (iflag || minusc || sflag == 0)
3488 * "In all cases, bash ignores SIGQUIT. Non-builtin
3489 * commands run by bash have signal handlers
3490 * set to the values inherited by the shell
3491 * from its parent". */
3507 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3508 //whereas we have to restore it to what shell got on entry
3509 //from the parent. See comment above
3511 if (signo == SIGCHLD)
3514 t = &sigmode[signo - 1];
3517 /* current setting is not yet known */
3518 if (sigaction(signo, NULL, &act)) {
3519 /* pretend it worked; maybe we should give a warning,
3520 * but other shells don't. We don't alter sigmode,
3521 * so we retry every time.
3522 * btw, in Linux it never fails. --vda */
3525 if (act.sa_handler == SIG_IGN) {
3526 cur_act = S_HARD_IGN;
3528 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3530 cur_act = S_IGN; /* don't hard ignore these */
3534 if (cur_act == S_HARD_IGN || cur_act == new_act)
3537 act.sa_handler = SIG_DFL;
3540 act.sa_handler = signal_handler;
3543 act.sa_handler = SIG_IGN;
3547 /* flags and mask matter only if !DFL and !IGN, but we do it
3548 * for all cases for more deterministic behavior:
3551 sigfillset(&act.sa_mask);
3553 sigaction_set(signo, &act);
3558 /* mode flags for set_curjob */
3559 #define CUR_DELETE 2
3560 #define CUR_RUNNING 1
3561 #define CUR_STOPPED 0
3564 /* pgrp of shell on invocation */
3565 static int initialpgrp; //references:2
3566 static int ttyfd = -1; //5
3569 static struct job *jobtab; //5
3571 static unsigned njobs; //4
3573 static struct job *curjob; //lots
3574 /* number of presumed living untracked jobs */
3575 static int jobless; //4
3578 /* Bash has a feature: it restores termios after a successful wait for
3579 * a foreground job which had at least one stopped or sigkilled member.
3580 * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
3581 * properly restoring tty state. Should we do this too?
3582 * A reproducer: ^Z an interactive python:
3585 * Python 2.7.12 (...)
3587 * { python leaves tty in -icanon -echo state. We do survive that... }
3588 * [1]+ Stopped python
3589 * { ...however, next program (python #2) does not survive it well: }
3591 * Python 2.7.12 (...)
3592 * >>> Traceback (most recent call last):
3593 * { above, I typed "qwerty<CR>", but -echo state is still in effect }
3594 * File "<stdin>", line 1, in <module>
3595 * NameError: name 'qwerty' is not defined
3597 * The implementation below is modeled on bash code and seems to work.
3598 * However, I'm not sure we should do this. For one: what if I'd fg
3599 * the stopped python instead? It'll be confused by "restored" tty state.
3601 static struct termios shell_tty_info;
3605 if (rootshell && ttyfd >= 0)
3606 tcgetattr(ttyfd, &shell_tty_info);
3611 /* if (rootshell) - caller ensures this */
3613 tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
3616 job_signal_status(struct job *jp)
3620 struct procstat *ps = jp->ps;
3621 for (i = 0; i < jp->nprocs; i++) {
3622 status = ps[i].ps_status;
3623 if (WIFSIGNALED(status) || WIFSTOPPED(status))
3629 restore_tty_if_stopped_or_signaled(struct job *jp)
3631 //TODO: check what happens if we come from waitforjob() in expbackq()
3633 int s = job_signal_status(jp);
3634 if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
3639 # define get_tty_state() ((void)0)
3640 # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
3644 set_curjob(struct job *jp, unsigned mode)
3647 struct job **jpp, **curp;
3649 /* first remove from list */
3650 jpp = curp = &curjob;
3655 jpp = &jp1->prev_job;
3657 *jpp = jp1->prev_job;
3659 /* Then re-insert in correct position */
3667 /* job being deleted */
3670 /* newly created job or backgrounded job,
3671 * put after all stopped jobs.
3676 if (!jp1 || jp1->state != JOBSTOPPED)
3679 jpp = &jp1->prev_job;
3685 /* newly stopped job - becomes curjob */
3686 jp->prev_job = *jpp;
3694 jobno(const struct job *jp)
3696 return jp - jobtab + 1;
3701 * Convert a job name to a job structure.
3704 #define getjob(name, getctl) getjob(name)
3707 getjob(const char *name, int getctl)
3711 const char *err_msg = "%s: no such job";
3715 char *(*match)(const char *, const char *);
3730 if (c == '+' || c == '%') {
3732 err_msg = "No current job";
3738 err_msg = "No previous job";
3748 if (num > 0 && num <= njobs) {
3749 jp = jobtab + num - 1;
3764 if (match(jp->ps[0].ps_cmd, p)) {
3768 err_msg = "%s: ambiguous";
3778 err_msg = "job %s not created under job control";
3779 if (getctl && jp->jobctl == 0)
3784 ash_msg_and_raise_error(err_msg, name);
3788 * Mark a job structure as unused.
3791 freejob(struct job *jp)
3793 struct procstat *ps;
3797 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3798 if (ps->ps_cmd != nullstr)
3801 if (jp->ps != &jp->ps0)
3804 set_curjob(jp, CUR_DELETE);
3810 xtcsetpgrp(int fd, pid_t pgrp)
3812 if (tcsetpgrp(fd, pgrp))
3813 ash_msg_and_raise_error("can't set tty process group (%m)");
3817 * Turn job control on and off.
3819 * Note: This code assumes that the third arg to ioctl is a character
3820 * pointer, which is true on Berkeley systems but not System V. Since
3821 * System V doesn't have job control yet, this isn't a problem now.
3823 * Called with interrupts off.
3831 if (on == doing_jobctl || rootshell == 0)
3835 ofd = fd = open(_PATH_TTY, O_RDWR);
3837 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3838 * That sometimes helps to acquire controlling tty.
3839 * Obviously, a workaround for bugs when someone
3840 * failed to provide a controlling tty to bash! :) */
3846 /* fd is a tty at this point */
3847 fd = fcntl(fd, F_DUPFD, 10);
3848 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
3851 goto out; /* F_DUPFD failed */
3852 close_on_exec_on(fd);
3853 while (1) { /* while we are in the background */
3854 pgrp = tcgetpgrp(fd);
3857 ash_msg("can't access tty; job control turned off");
3861 if (pgrp == getpgrp())
3872 xtcsetpgrp(fd, pgrp);
3874 /* turning job control off */
3877 /* was xtcsetpgrp, but this can make exiting ash
3878 * loop forever if pty is already deleted */
3879 tcsetpgrp(fd, pgrp);
3893 static int FAST_FUNC
3894 killcmd(int argc, char **argv)
3896 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3899 if (argv[i][0] == '%') {
3901 * "kill %N" - job kill
3902 * Converting to pgrp / pid kill
3908 jp = getjob(argv[i], 0);
3910 * In jobs started under job control, we signal
3911 * entire process group by kill -PGRP_ID.
3912 * This happens, f.e., in interactive shell.
3914 * Otherwise, we signal each child via
3915 * kill PID1 PID2 PID3.
3917 * sh -c 'sleep 1|sleep 1 & kill %1'
3918 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3919 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3921 n = jp->nprocs; /* can't be 0 (I hope) */
3924 dst = alloca(n * sizeof(int)*4);
3926 for (j = 0; j < n; j++) {
3927 struct procstat *ps = &jp->ps[j];
3928 /* Skip non-running and not-stopped members
3929 * (i.e. dead members) of the job
3931 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3934 * kill_main has matching code to expect
3935 * leading space. Needed to not confuse
3936 * negative pids with "kill -SIGNAL_NO" syntax
3938 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3942 } while (argv[++i]);
3944 return kill_main(argc, argv);
3948 showpipe(struct job *jp /*, FILE *out*/)
3950 struct procstat *ps;
3951 struct procstat *psend;
3953 psend = jp->ps + jp->nprocs;
3954 for (ps = jp->ps + 1; ps < psend; ps++)
3955 printf(" | %s", ps->ps_cmd);
3956 newline_and_flush(stdout);
3957 flush_stdout_stderr();
3962 restartjob(struct job *jp, int mode)
3964 struct procstat *ps;
3970 if (jp->state == JOBDONE)
3972 jp->state = JOBRUNNING;
3973 pgid = jp->ps[0].ps_pid;
3974 if (mode == FORK_FG) {
3976 xtcsetpgrp(ttyfd, pgid);
3978 killpg(pgid, SIGCONT);
3982 if (WIFSTOPPED(ps->ps_status)) {
3988 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3993 static int FAST_FUNC
3994 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
4000 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
4004 jp = getjob(*argv, 1);
4005 if (mode == FORK_BG) {
4006 set_curjob(jp, CUR_RUNNING);
4007 printf("[%d] ", jobno(jp));
4009 out1str(jp->ps[0].ps_cmd);
4010 showpipe(jp /*, stdout*/);
4011 retval = restartjob(jp, mode);
4012 } while (*argv && *++argv);
4018 sprint_status48(char *s, int status, int sigonly)
4024 if (!WIFEXITED(status)) {
4025 if (JOBS && WIFSTOPPED(status))
4026 st = WSTOPSIG(status);
4028 st = WTERMSIG(status);
4030 if (st == SIGINT || st == SIGPIPE)
4032 if (JOBS && WIFSTOPPED(status))
4036 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
4037 col = fmtstr(s, 32, strsignal(st));
4038 if (WCOREDUMP(status)) {
4039 strcpy(s + col, " (core dumped)");
4040 col += sizeof(" (core dumped)")-1;
4042 } else if (!sigonly) {
4043 st = WEXITSTATUS(status);
4044 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
4051 wait_block_or_sig(int *status)
4058 /* Poll all children for changes in their state */
4060 /* if job control is active, accept stopped processes too */
4061 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
4063 break; /* Error (e.g. EINTR, ECHILD) or pid */
4065 /* Children exist, but none are ready. Sleep until interesting signal */
4068 sigprocmask(SIG_SETMASK, &mask, &mask);
4069 while (!got_sigchld && !pending_sig)
4071 sigprocmask(SIG_SETMASK, &mask, NULL);
4072 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
4073 while (!got_sigchld && !pending_sig)
4077 /* If it was SIGCHLD, poll children again */
4078 } while (got_sigchld);
4083 #define DOWAIT_NONBLOCK 0
4084 #define DOWAIT_BLOCK 1
4085 #define DOWAIT_BLOCK_OR_SIG 2
4088 dowait(int block, struct job *job)
4093 struct job *thisjob = NULL;
4095 TRACE(("dowait(0x%x) called\n", block));
4097 /* It's wrong to call waitpid() outside of INT_OFF region:
4098 * signal can arrive just after syscall return and handler can
4099 * longjmp away, losing stop/exit notification processing.
4100 * Thus, for "jobs" builtin, and for waiting for a fg job,
4101 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4103 * However, for "wait" builtin it is wrong to simply call waitpid()
4104 * in INT_OFF region: "wait" needs to wait for any running job
4105 * to change state, but should exit on any trap too.
4106 * In INT_OFF region, a signal just before syscall entry can set
4107 * pending_sig variables, but we can't check them, and we would
4108 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4110 * Because of this, we run inside INT_OFF, but use a special routine
4111 * which combines waitpid() and sigsuspend().
4112 * This is the reason why we need to have a handler for SIGCHLD:
4113 * SIG_DFL handler does not wake sigsuspend().
4116 if (block == DOWAIT_BLOCK_OR_SIG) {
4117 pid = wait_block_or_sig(&status);
4120 if (block == DOWAIT_NONBLOCK)
4121 wait_flags = WNOHANG;
4122 /* if job control is active, accept stopped processes too */
4124 wait_flags |= WUNTRACED;
4125 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4126 pid = waitpid(-1, &status, wait_flags);
4128 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4129 pid, status, errno, strerror(errno)));
4134 for (jp = curjob; jp; jp = jp->prev_job) {
4136 struct procstat *ps;
4137 struct procstat *psend;
4138 if (jp->state == JOBDONE)
4142 psend = ps + jp->nprocs;
4144 if (ps->ps_pid == pid) {
4145 TRACE(("Job %d: changing status of proc %d "
4146 "from 0x%x to 0x%x\n",
4147 jobno(jp), pid, ps->ps_status, status));
4148 ps->ps_status = status;
4151 if (ps->ps_status == -1)
4152 jobstate = JOBRUNNING;
4154 if (jobstate == JOBRUNNING)
4156 if (WIFSTOPPED(ps->ps_status)) {
4157 jp->stopstatus = ps->ps_status;
4158 jobstate = JOBSTOPPED;
4161 } while (++ps < psend);
4165 /* Found the job where one of its processes changed its state.
4166 * Is there at least one live and running process in this job? */
4167 if (jobstate != JOBRUNNING) {
4168 /* No. All live processes in the job are stopped
4169 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4171 thisjob->changed = 1;
4172 if (thisjob->state != jobstate) {
4173 TRACE(("Job %d: changing state from %d to %d\n",
4174 jobno(thisjob), thisjob->state, jobstate));
4175 thisjob->state = jobstate;
4177 if (jobstate == JOBSTOPPED)
4178 set_curjob(thisjob, CUR_STOPPED);
4184 /* The process wasn't found in job list */
4185 if (JOBS && !WIFSTOPPED(status))
4190 if (thisjob && thisjob == job) {
4194 len = sprint_status48(s, status, 1);
4206 showjob(struct job *jp, int mode)
4208 struct procstat *ps;
4209 struct procstat *psend;
4212 char s[16 + 16 + 48];
4213 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4217 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4218 /* just output process (group) id of pipeline */
4219 fprintf(out, "%d\n", ps->ps_pid);
4223 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4228 else if (curjob && jp == curjob->prev_job)
4231 if (mode & SHOW_PIDS)
4232 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4234 psend = ps + jp->nprocs;
4236 if (jp->state == JOBRUNNING) {
4237 strcpy(s + col, "Running");
4238 col += sizeof("Running") - 1;
4240 int status = psend[-1].ps_status;
4241 if (jp->state == JOBSTOPPED)
4242 status = jp->stopstatus;
4243 col += sprint_status48(s + col, status, 0);
4245 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4247 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4248 * or prints several "PID | <cmdN>" lines,
4249 * depending on SHOW_PIDS bit.
4250 * We do not print status of individual processes
4251 * between PID and <cmdN>. bash does it, but not very well:
4252 * first line shows overall job status, not process status,
4253 * making it impossible to know 1st process status.
4257 /* for each process */
4260 if (mode & SHOW_PIDS)
4261 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4263 fprintf(out, "%s%*c%s%s",
4265 33 - col >= 0 ? 33 - col : 0, ' ',
4266 ps == jp->ps ? "" : "| ",
4269 } while (++ps != psend);
4270 newline_and_flush(out);
4274 if (jp->state == JOBDONE) {
4275 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4281 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4282 * statuses have changed since the last call to showjobs.
4289 TRACE(("showjobs(0x%x) called\n", mode));
4291 /* Handle all finished jobs */
4292 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4295 for (jp = curjob; jp; jp = jp->prev_job) {
4296 if (!(mode & SHOW_CHANGED) || jp->changed) {
4302 static int FAST_FUNC
4303 jobscmd(int argc UNUSED_PARAM, char **argv)
4308 while ((m = nextopt("lp")) != '\0') {
4312 mode |= SHOW_ONLY_PGID;
4318 showjob(getjob(*argv, 0), mode);
4328 /* Called only on finished or stopped jobs (no members are running) */
4330 getstatus(struct job *job)
4334 struct procstat *ps;
4336 /* Fetch last member's status */
4337 ps = job->ps + job->nprocs - 1;
4338 status = ps->ps_status;
4340 /* "set -o pipefail" mode: use last _nonzero_ status */
4341 while (status == 0 && --ps >= job->ps)
4342 status = ps->ps_status;
4345 retval = WEXITSTATUS(status);
4346 if (!WIFEXITED(status)) {
4348 retval = WSTOPSIG(status);
4349 if (!WIFSTOPPED(status))
4352 /* XXX: limits number of signals */
4353 retval = WTERMSIG(status);
4355 if (retval == SIGINT)
4361 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4362 jobno(job), job->nprocs, status, retval));
4366 static int FAST_FUNC
4367 waitcmd(int argc UNUSED_PARAM, char **argv)
4378 /* wait for all jobs */
4382 if (!jp) /* no running procs */
4384 if (jp->state == JOBRUNNING)
4390 * "When bash is waiting for an asynchronous command via
4391 * the wait builtin, the reception of a signal for which a trap
4392 * has been set will cause the wait builtin to return immediately
4393 * with an exit status greater than 128, immediately after which
4394 * the trap is executed."
4396 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4397 /* if child sends us a signal *and immediately exits*,
4398 * dowait() returns pid > 0. Check this case,
4399 * not "if (dowait() < 0)"!
4408 if (**argv != '%') {
4409 pid_t pid = number(*argv);
4414 if (job->ps[job->nprocs - 1].ps_pid == pid)
4416 job = job->prev_job;
4419 job = getjob(*argv, 0);
4421 /* loop until process terminated or stopped */
4422 while (job->state == JOBRUNNING) {
4423 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4428 retval = getstatus(job);
4435 retval = 128 + pending_sig;
4444 struct job *jp, *jq;
4446 len = njobs * sizeof(*jp);
4448 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4450 offset = (char *)jp - (char *)jq;
4452 /* Relocate pointers */
4455 jq = (struct job *)((char *)jq + l);
4459 #define joff(p) ((struct job *)((char *)(p) + l))
4460 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4461 if (joff(jp)->ps == &jq->ps0)
4462 jmove(joff(jp)->ps);
4463 if (joff(jp)->prev_job)
4464 jmove(joff(jp)->prev_job);
4474 jp = (struct job *)((char *)jp + len);
4478 } while (--jq >= jp);
4483 * Return a new job structure.
4484 * Called with interrupts off.
4487 makejob(/*union node *node,*/ int nprocs)
4492 for (i = njobs, jp = jobtab; ; jp++) {
4499 if (jp->state != JOBDONE || !jp->waited)
4508 memset(jp, 0, sizeof(*jp));
4510 /* jp->jobctl is a bitfield.
4511 * "jp->jobctl |= doing_jobctl" likely to give awful code */
4515 jp->prev_job = curjob;
4520 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4522 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4529 * Return a string identifying a command (to be printed by the
4532 static char *cmdnextc;
4535 cmdputs(const char *s)
4537 static const char vstype[VSTYPE + 1][3] = {
4538 "", "}", "-", "+", "?", "=",
4539 "%", "%%", "#", "##"
4540 IF_BASH_SUBSTR(, ":")
4541 IF_BASH_PATTERN_SUBST(, "/", "//")
4544 const char *p, *str;
4548 unsigned char subtype = 0;
4552 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4554 while ((c = *p++) != '\0') {
4562 if ((subtype & VSTYPE) == VSLENGTH)
4568 str = "\"}" + !(quoted & 1);
4575 #if ENABLE_FEATURE_SH_MATH
4590 if ((subtype & VSTYPE) != VSNORMAL)
4592 str = vstype[subtype & VSTYPE];
4593 if (subtype & VSNUL)
4602 /* These can only happen inside quotes */
4615 while ((c = *str++) != '\0') {
4618 } /* while *p++ not NUL */
4621 USTPUTC('"', nextc);
4627 /* cmdtxt() and cmdlist() call each other */
4628 static void cmdtxt(union node *n);
4631 cmdlist(union node *np, int sep)
4633 for (; np; np = np->narg.next) {
4637 if (sep && np->narg.next)
4643 cmdtxt(union node *n)
4646 struct nodelist *lp;
4657 lp = n->npipe.cmdlist;
4675 cmdtxt(n->nbinary.ch1);
4691 cmdtxt(n->nif.test);
4693 if (n->nif.elsepart) {
4694 cmdtxt(n->nif.ifpart);
4696 n = n->nif.elsepart;
4714 cmdtxt(n->nbinary.ch1);
4724 cmdputs(n->nfor.var);
4726 cmdlist(n->nfor.args, 1);
4731 cmdputs(n->narg.text);
4735 cmdlist(n->ncmd.args, 1);
4736 cmdlist(n->ncmd.redirect, 0);
4749 cmdputs(n->ncase.expr->narg.text);
4751 for (np = n->ncase.cases; np; np = np->nclist.next) {
4752 cmdtxt(np->nclist.pattern);
4754 cmdtxt(np->nclist.body);
4768 #if BASH_REDIR_OUTPUT
4783 cmdputs(utoa(n->nfile.fd));
4785 if (n->type == NTOFD || n->type == NFROMFD) {
4786 cmdputs(utoa(n->ndup.dupfd));
4795 commandtext(union node *n)
4799 STARTSTACKSTR(cmdnextc);
4801 name = stackblock();
4802 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4803 return ckstrdup(name);
4808 * Fork off a subshell. If we are doing job control, give the subshell its
4809 * own process group. Jp is a job structure that the job is to be added to.
4810 * N is the command that will be evaluated by the child. Both jp and n may
4811 * be NULL. The mode parameter can be one of the following:
4812 * FORK_FG - Fork off a foreground process.
4813 * FORK_BG - Fork off a background process.
4814 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4815 * process group even if job control is on.
4817 * When job control is turned off, background processes have their standard
4818 * input redirected to /dev/null (except for the second and later processes
4821 * Called with interrupts off.
4824 * Clear traps on a fork.
4832 for (tp = trap; tp < &trap[NSIG]; tp++) {
4833 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4834 if (trap_ptr == trap)
4836 /* else: it "belongs" to trap_ptr vector, don't free */
4838 if ((tp - trap) != 0)
4839 setsignal(tp - trap);
4846 /* Lives far away from here, needed for forkchild */
4847 static void closescript(void);
4849 /* Called after fork(), in child */
4850 /* jp and n are NULL when called by openhere() for heredoc support */
4851 static NOINLINE void
4852 forkchild(struct job *jp, union node *n, int mode)
4856 TRACE(("Child shell %d\n", getpid()));
4860 /* man bash: "Non-builtin commands run by bash have signal handlers
4861 * set to the values inherited by the shell from its parent".
4862 * Do we do it correctly? */
4866 if (mode == FORK_NOJOB /* is it `xxx` ? */
4867 && n && n->type == NCMD /* is it single cmd? */
4868 /* && n->ncmd.args->type == NARG - always true? */
4869 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4870 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4871 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4873 TRACE(("Trap hack\n"));
4874 /* Awful hack for `trap` or $(trap).
4876 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4877 * contains an example where "trap" is executed in a subshell:
4879 * save_traps=$(trap)
4881 * eval "$save_traps"
4883 * Standard does not say that "trap" in subshell shall print
4884 * parent shell's traps. It only says that its output
4885 * must have suitable form, but then, in the above example
4886 * (which is not supposed to be normative), it implies that.
4888 * bash (and probably other shell) does implement it
4889 * (traps are reset to defaults, but "trap" still shows them),
4890 * but as a result, "trap" logic is hopelessly messed up:
4893 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4894 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4895 * # true | trap <--- trap is in subshell - no output (ditto)
4896 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4897 * trap -- 'echo Ho' SIGWINCH
4898 * # echo `(trap)` <--- in subshell in subshell - output
4899 * trap -- 'echo Ho' SIGWINCH
4900 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4901 * trap -- 'echo Ho' SIGWINCH
4903 * The rules when to forget and when to not forget traps
4904 * get really complex and nonsensical.
4906 * Our solution: ONLY bare $(trap) or `trap` is special.
4908 /* Save trap handler strings for trap builtin to print */
4909 trap_ptr = xmemdup(trap, sizeof(trap));
4910 /* Fall through into clearing traps */
4914 /* do job control only in root shell */
4916 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4919 if (jp->nprocs == 0)
4922 pgrp = jp->ps[0].ps_pid;
4923 /* this can fail because we are doing it in the parent also */
4925 if (mode == FORK_FG)
4926 xtcsetpgrp(ttyfd, pgrp);
4931 if (mode == FORK_BG) {
4932 /* man bash: "When job control is not in effect,
4933 * asynchronous commands ignore SIGINT and SIGQUIT" */
4936 if (jp->nprocs == 0) {
4938 if (open(bb_dev_null, O_RDONLY) != 0)
4939 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4943 if (iflag) { /* why if iflag only? */
4948 * "In all cases, bash ignores SIGQUIT. Non-builtin
4949 * commands run by bash have signal handlers
4950 * set to the values inherited by the shell
4952 * Take care of the second rule: */
4956 if (n && n->type == NCMD
4957 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4959 TRACE(("Job hack\n"));
4960 /* "jobs": we do not want to clear job list for it,
4961 * instead we remove only _its_ own_ job from job list.
4962 * This makes "jobs .... | cat" more useful.
4968 for (jp = curjob; jp; jp = jp->prev_job)
4973 /* Called after fork(), in parent */
4975 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4978 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4980 TRACE(("In parent shell: child = %d\n", pid));
4982 /* jp is NULL when called by openhere() for heredoc support */
4983 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4989 if (mode != FORK_NOJOB && jp->jobctl) {
4992 if (jp->nprocs == 0)
4995 pgrp = jp->ps[0].ps_pid;
4996 /* This can fail because we are doing it in the child also */
5000 if (mode == FORK_BG) {
5001 backgndpid = pid; /* set $! */
5002 set_curjob(jp, CUR_RUNNING);
5005 struct procstat *ps = &jp->ps[jp->nprocs++];
5008 ps->ps_cmd = nullstr;
5010 if (doing_jobctl && n)
5011 ps->ps_cmd = commandtext(n);
5016 /* jp and n are NULL when called by openhere() for heredoc support */
5018 forkshell(struct job *jp, union node *n, int mode)
5022 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
5025 TRACE(("Fork failed, errno=%d", errno));
5028 ash_msg_and_raise_error("can't fork");
5031 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
5032 forkchild(jp, n, mode);
5034 forkparent(jp, n, mode, pid);
5040 * Wait for job to finish.
5042 * Under job control we have the problem that while a child process
5043 * is running interrupts generated by the user are sent to the child
5044 * but not to the shell. This means that an infinite loop started by
5045 * an interactive user may be hard to kill. With job control turned off,
5046 * an interactive user may place an interactive program inside a loop.
5047 * If the interactive program catches interrupts, the user doesn't want
5048 * these interrupts to also abort the loop. The approach we take here
5049 * is to have the shell ignore interrupt signals while waiting for a
5050 * foreground process to terminate, and then send itself an interrupt
5051 * signal if the child process was terminated by an interrupt signal.
5052 * Unfortunately, some programs want to do a bit of cleanup and then
5053 * exit on interrupt; unless these processes terminate themselves by
5054 * sending a signal to themselves (instead of calling exit) they will
5055 * confuse this approach.
5057 * Called with interrupts off.
5060 waitforjob(struct job *jp)
5064 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
5067 while (jp->state == JOBRUNNING) {
5068 /* In non-interactive shells, we _can_ get
5069 * a keyboard signal here and be EINTRed,
5070 * but we just loop back, waiting for command to complete.
5073 * "If bash is waiting for a command to complete and receives
5074 * a signal for which a trap has been set, the trap
5075 * will not be executed until the command completes."
5077 * Reality is that even if trap is not set, bash
5078 * will not act on the signal until command completes.
5079 * Try this. sleep5intoff.c:
5080 * #include <signal.h>
5081 * #include <unistd.h>
5084 * sigemptyset(&set);
5085 * sigaddset(&set, SIGINT);
5086 * sigaddset(&set, SIGQUIT);
5087 * sigprocmask(SIG_BLOCK, &set, NULL);
5091 * $ bash -c './sleep5intoff; echo hi'
5092 * ^C^C^C^C <--- pressing ^C once a second
5094 * $ bash -c './sleep5intoff; echo hi'
5095 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5098 dowait(DOWAIT_BLOCK, jp);
5105 xtcsetpgrp(ttyfd, rootpid);
5106 restore_tty_if_stopped_or_signaled(jp);
5109 * This is truly gross.
5110 * If we're doing job control, then we did a TIOCSPGRP which
5111 * caused us (the shell) to no longer be in the controlling
5112 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5113 * intuit from the subprocess exit status whether a SIGINT
5114 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5116 if (jp->sigint) /* TODO: do the same with all signals */
5117 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5119 if (jp->state == JOBDONE)
5126 * return 1 if there are stopped jobs, otherwise 0
5138 if (jp && jp->state == JOBSTOPPED) {
5139 out2str("You have stopped jobs.\n");
5149 * Code for dealing with input/output redirection.
5154 #define EMPTY -2 /* marks an unused slot in redirtab */
5155 #define CLOSED -3 /* marks a slot of previously-closed fd */
5158 * Open a file in noclobber mode.
5159 * The code was copied from bash.
5162 noclobberopen(const char *fname)
5165 struct stat finfo, finfo2;
5168 * If the file exists and is a regular file, return an error
5171 r = stat(fname, &finfo);
5172 if (r == 0 && S_ISREG(finfo.st_mode)) {
5178 * If the file was not present (r != 0), make sure we open it
5179 * exclusively so that if it is created before we open it, our open
5180 * will fail. Make sure that we do not truncate an existing file.
5181 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5182 * file was not a regular file, we leave O_EXCL off.
5185 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5186 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5188 /* If the open failed, return the file descriptor right away. */
5193 * OK, the open succeeded, but the file may have been changed from a
5194 * non-regular file to a regular file between the stat and the open.
5195 * We are assuming that the O_EXCL open handles the case where FILENAME
5196 * did not exist and is symlinked to an existing file between the stat
5201 * If we can open it and fstat the file descriptor, and neither check
5202 * revealed that it was a regular file, and the file has not been
5203 * replaced, return the file descriptor.
5205 if (fstat(fd, &finfo2) == 0
5206 && !S_ISREG(finfo2.st_mode)
5207 && finfo.st_dev == finfo2.st_dev
5208 && finfo.st_ino == finfo2.st_ino
5213 /* The file has been replaced. badness. */
5220 * Handle here documents. Normally we fork off a process to write the
5221 * data to a pipe. If the document is short, we can stuff the data in
5222 * the pipe without forking.
5224 /* openhere needs this forward reference */
5225 static void expandhere(union node *arg, int fd);
5227 openhere(union node *redir)
5233 ash_msg_and_raise_error("pipe call failed");
5234 if (redir->type == NHERE) {
5235 len = strlen(redir->nhere.doc->narg.text);
5236 if (len <= PIPE_BUF) {
5237 full_write(pip[1], redir->nhere.doc->narg.text, len);
5241 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5244 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5245 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5246 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5247 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5248 signal(SIGPIPE, SIG_DFL);
5249 if (redir->type == NHERE)
5250 full_write(pip[1], redir->nhere.doc->narg.text, len);
5252 expandhere(redir->nhere.doc, pip[1]);
5253 _exit(EXIT_SUCCESS);
5261 openredirect(union node *redir)
5266 switch (redir->nfile.type) {
5267 /* Can't happen, our single caller does this itself */
5273 return openhere(redir);
5276 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5277 * allocated space. Do it only when we know it is safe.
5279 fname = redir->nfile.expfname;
5281 switch (redir->nfile.type) {
5287 f = open(fname, O_RDONLY);
5292 f = open(fname, O_RDWR|O_CREAT, 0666);
5297 #if BASH_REDIR_OUTPUT
5300 /* Take care of noclobber mode. */
5302 f = noclobberopen(fname);
5309 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5314 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5322 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5324 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5328 * Copy a file descriptor to be >= 10. Throws exception on error.
5336 newfd = fcntl(from, F_DUPFD, 10);
5337 err = newfd < 0 ? errno : 0;
5340 ash_msg_and_raise_error("%d: %m", from);
5342 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5348 dup2_or_raise(int from, int to)
5352 newfd = (from != to) ? dup2(from, to) : to;
5354 /* Happens when source fd is not open: try "echo >&99" */
5355 ash_msg_and_raise_error("%d: %m", from);
5360 /* Struct def and variable are moved down to the first usage site */
5365 struct redirtab *next;
5367 struct two_fd_t two_fd[];
5369 #define redirlist (G_var.redirlist)
5371 COPYFD_RESTORE = (int)~(INT_MAX),
5375 need_to_remember(struct redirtab *rp, int fd)
5379 if (!rp) /* remembering was not requested */
5382 for (i = 0; i < rp->pair_count; i++) {
5383 if (rp->two_fd[i].orig == fd) {
5384 /* already remembered */
5391 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5393 is_hidden_fd(struct redirtab *rp, int fd)
5396 struct parsefile *pf;
5400 /* Check open scripts' fds */
5403 /* We skip pf_fd == 0 case because of the following case:
5404 * $ ash # running ash interactively
5406 * and in script.sh: "exec 9>&0".
5407 * Even though top-level pf_fd _is_ 0,
5408 * it's still ok to use it: "read" builtin uses it,
5409 * why should we cripple "exec" builtin?
5411 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5419 /* Check saved fds of redirects */
5420 fd |= COPYFD_RESTORE;
5421 for (i = 0; i < rp->pair_count; i++) {
5422 if (rp->two_fd[i].copy == fd) {
5430 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5431 * old file descriptors are stashed away so that the redirection can be
5432 * undone by calling popredir.
5434 /* flags passed to redirect */
5435 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5436 #define REDIR_SAVEFD2 03 /* set preverrout */
5438 redirect(union node *redir, int flags)
5440 struct redirtab *sv;
5445 int copied_fd2 = -1;
5454 if (flags & REDIR_PUSH) {
5455 union node *tmp = redir;
5458 #if BASH_REDIR_OUTPUT
5459 if (tmp->nfile.type == NTO2)
5462 tmp = tmp->nfile.next;
5464 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5465 sv->next = redirlist;
5466 sv->pair_count = sv_pos;
5468 while (sv_pos > 0) {
5470 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5476 fd = redir->nfile.fd;
5477 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5478 right_fd = redir->ndup.dupfd;
5479 //bb_error_msg("doing %d > %d", fd, right_fd);
5480 /* redirect from/to same file descriptor? */
5483 /* "echo >&10" and 10 is a fd opened to a sh script? */
5484 if (is_hidden_fd(sv, right_fd)) {
5485 errno = EBADF; /* as if it is closed */
5486 ash_msg_and_raise_error("%d: %m", right_fd);
5490 newfd = openredirect(redir); /* always >= 0 */
5492 /* Descriptor wasn't open before redirect.
5493 * Mark it for close in the future */
5494 if (need_to_remember(sv, fd)) {
5495 goto remember_to_close;
5500 #if BASH_REDIR_OUTPUT
5503 if (need_to_remember(sv, fd)) {
5504 /* Copy old descriptor */
5505 /* Careful to not accidentally "save"
5506 * to the same fd as right side fd in N>&M */
5507 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5508 #if defined(F_DUPFD_CLOEXEC)
5509 i = fcntl(fd, F_DUPFD_CLOEXEC, minfd);
5511 i = fcntl(fd, F_DUPFD, minfd);
5516 /* Strange error (e.g. "too many files" EMFILE?) */
5520 ash_msg_and_raise_error("%d: %m", fd);
5523 /* EBADF: it is not open - good, remember to close it */
5526 } else { /* fd is open, save its copy */
5527 #if !defined(F_DUPFD_CLOEXEC)
5528 fcntl(i, F_SETFD, FD_CLOEXEC);
5530 /* "exec fd>&-" should not close fds
5531 * which point to script file(s).
5532 * Force them to be restored afterwards */
5533 if (is_hidden_fd(sv, fd))
5534 i |= COPYFD_RESTORE;
5538 sv->two_fd[sv_pos].orig = fd;
5539 sv->two_fd[sv_pos].copy = i;
5543 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5544 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5545 /* Don't want to trigger debugging */
5549 dup2_or_raise(redir->ndup.dupfd, fd);
5551 } else if (fd != newfd) { /* move newfd to fd */
5552 dup2_or_raise(newfd, fd);
5553 #if BASH_REDIR_OUTPUT
5554 if (!(redir->nfile.type == NTO2 && fd == 2))
5558 #if BASH_REDIR_OUTPUT
5559 if (redir->nfile.type == NTO2 && fd == 1) {
5560 /* We already redirected it to fd 1, now copy it to 2 */
5566 } while ((redir = redir->nfile.next) != NULL);
5569 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5570 preverrout_fd = copied_fd2;
5574 * Undo the effects of the last redirection.
5577 popredir(int drop, int restore)
5579 struct redirtab *rp;
5582 if (redirlist == NULL)
5586 for (i = 0; i < rp->pair_count; i++) {
5587 int fd = rp->two_fd[i].orig;
5588 int copy = rp->two_fd[i].copy;
5589 if (copy == CLOSED) {
5594 if (copy != EMPTY) {
5595 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5596 copy &= ~COPYFD_RESTORE;
5598 dup2_or_raise(copy, fd);
5600 close(copy & ~COPYFD_RESTORE);
5603 redirlist = rp->next;
5609 * Undo all redirections. Called on error or interrupt.
5613 redirectsafe(union node *redir, int flags)
5616 volatile int saveint;
5617 struct jmploc *volatile savehandler = exception_handler;
5618 struct jmploc jmploc;
5621 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5622 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5624 exception_handler = &jmploc;
5625 redirect(redir, flags);
5627 exception_handler = savehandler;
5628 if (err && exception_type != EXERROR)
5629 longjmp(exception_handler->loc, 1);
5630 RESTORE_INT(saveint);
5635 /* ============ Routines to expand arguments to commands
5637 * We have to deal with backquotes, shell variables, and file metacharacters.
5640 #if ENABLE_FEATURE_SH_MATH
5642 ash_arith(const char *s)
5644 arith_state_t math_state;
5647 math_state.lookupvar = lookupvar;
5648 math_state.setvar = setvar0;
5649 //math_state.endofname = endofname;
5652 result = arith(&math_state, s);
5653 if (math_state.errmsg)
5654 ash_msg_and_raise_error(math_state.errmsg);
5664 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5665 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5666 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5667 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5668 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5669 * POSIX says for this case:
5670 * Pathname expansion shall not be performed on the word by a
5671 * non-interactive shell; an interactive shell may perform it, but shall
5672 * do so only when the expansion would result in one word.
5673 * Currently, our code complies to the above rule by never globbing
5674 * redirection filenames.
5675 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5676 * (this means that on a typical Linux distro, bash almost always
5677 * performs globbing, and thus diverges from what we do).
5679 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5680 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5681 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5682 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5683 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5687 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5688 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5689 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5690 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5691 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5693 /* Add CTLESC when necessary. */
5694 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5695 /* Do not skip NUL characters. */
5696 #define QUOTES_KEEPNUL EXP_TILDE
5699 * Structure specifying which parts of the string should be searched
5700 * for IFS characters.
5703 struct ifsregion *next; /* next region in list */
5704 int begoff; /* offset of start of region */
5705 int endoff; /* offset of end of region */
5706 int nulonly; /* search for nul bytes only */
5710 struct strlist *list;
5711 struct strlist **lastp;
5714 /* output of current string */
5715 static char *expdest;
5716 /* list of back quote expressions */
5717 static struct nodelist *argbackq;
5718 /* first struct in list of ifs regions */
5719 static struct ifsregion ifsfirst;
5720 /* last struct in list */
5721 static struct ifsregion *ifslastp;
5722 /* holds expanded arg list */
5723 static struct arglist exparg;
5728 #if !ENABLE_FEATURE_SH_MATH
5729 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5730 typedef long arith_t;
5731 # define ARITH_FMT "%ld"
5738 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5739 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5740 STADJUST(len, expdest);
5745 * Break the argument string into pieces based upon IFS and add the
5746 * strings to the argument list. The regions of the string to be
5747 * searched for IFS characters have been stored by recordregion.
5750 ifsbreakup(char *string, struct arglist *arglist)
5752 struct ifsregion *ifsp;
5757 const char *ifs, *realifs;
5762 if (ifslastp != NULL) {
5765 realifs = ifsset() ? ifsval() : defifs;
5768 p = string + ifsp->begoff;
5769 nulonly = ifsp->nulonly;
5770 ifs = nulonly ? nullstr : realifs;
5772 while (p < string + ifsp->endoff) {
5774 if ((unsigned char)*p == CTLESC)
5776 if (!strchr(ifs, *p)) {
5781 ifsspc = (strchr(defifs, *p) != NULL);
5782 /* Ignore IFS whitespace at start */
5783 if (q == start && ifsspc) {
5789 sp = stzalloc(sizeof(*sp));
5791 *arglist->lastp = sp;
5792 arglist->lastp = &sp->next;
5796 if (p >= string + ifsp->endoff) {
5800 if ((unsigned char)*p == CTLESC)
5802 if (strchr(ifs, *p) == NULL) {
5806 if (strchr(defifs, *p) == NULL) {
5821 } while (ifsp != NULL);
5830 sp = stzalloc(sizeof(*sp));
5832 *arglist->lastp = sp;
5833 arglist->lastp = &sp->next;
5839 struct ifsregion *p = ifsfirst.next;
5846 struct ifsregion *ifsp;
5851 ifsfirst.next = NULL;
5858 esclen(const char *start, const char *p)
5862 while (p > start && (unsigned char)*--p == CTLESC) {
5869 * Remove any CTLESC characters from a string.
5872 rmescapes(char *str, int flag)
5874 static const char qchars[] ALIGN1 = {
5875 IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
5879 unsigned protect_against_glob;
5881 IF_BASH_PATTERN_SUBST(unsigned slash = flag & RMESCAPE_SLASH;)
5883 p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash));
5889 if (flag & RMESCAPE_ALLOC) {
5890 size_t len = p - str;
5891 size_t fulllen = len + strlen(p) + 1;
5893 if (flag & RMESCAPE_GROW) {
5894 int strloc = str - (char *)stackblock();
5895 r = makestrspace(fulllen, expdest);
5896 /* p and str may be invalidated by makestrspace */
5897 str = (char *)stackblock() + strloc;
5899 } else if (flag & RMESCAPE_HEAP) {
5900 r = ckmalloc(fulllen);
5902 r = stalloc(fulllen);
5906 q = (char *)memcpy(q, str, len) + len;
5911 globbing = flag & RMESCAPE_GLOB;
5912 protect_against_glob = globbing;
5914 if ((unsigned char)*p == CTLQUOTEMARK) {
5915 // Note: both inquotes and protect_against_glob only affect whether
5916 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5917 inquotes = ~inquotes;
5919 protect_against_glob = globbing;
5922 if ((unsigned char)*p == CTLESC) {
5926 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5928 if (protect_against_glob) {
5930 * We used to trust glob() and fnmatch() to eat
5931 * superfluous escapes (\z where z has no
5932 * special meaning anyway). But this causes
5933 * bugs such as string of one greek letter rho
5934 * (unicode-encoded as two bytes 'cf,81")
5935 * getting encoded as "cf,CTLESC,81"
5936 * and here, converted to "cf,\,81" -
5937 * which does not go well with some flavors
5938 * of fnmatch() in unicode locales.
5940 * Lets add "\" only on the chars which need it.
5945 /* || *p == ']' maybe also this? */
5951 } else if (*p == '\\' && !inquotes) {
5952 /* naked back slash */
5953 protect_against_glob = 0;
5956 #if BASH_PATTERN_SUBST
5957 else if (*p == '/' && slash) {
5958 /* stop handling globbing and mark location of slash */
5959 globbing = slash = 0;
5963 protect_against_glob = globbing;
5968 if (flag & RMESCAPE_GROW) {
5970 STADJUST(q - r + 1, expdest);
5974 #define pmatch(a, b) !fnmatch((a), (b), 0)
5977 * Prepare a pattern for a expmeta (internal glob(3)) call.
5979 * Returns an stalloced string.
5982 preglob(const char *pattern, int flag)
5984 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5988 * Put a string on the stack.
5991 memtodest(const char *p, size_t len, int syntax, int quotes)
5998 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
6001 unsigned char c = *p++;
6003 if (quotes & QUOTES_ESC) {
6004 int n = SIT(c, syntax);
6006 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
6013 } else if (!(quotes & QUOTES_KEEPNUL))
6022 strtodest(const char *p, int syntax, int quotes)
6024 size_t len = strlen(p);
6025 memtodest(p, len, syntax, quotes);
6030 * Record the fact that we have to scan this region of the
6031 * string for IFS characters.
6034 recordregion(int start, int end, int nulonly)
6036 struct ifsregion *ifsp;
6038 if (ifslastp == NULL) {
6042 ifsp = ckzalloc(sizeof(*ifsp));
6043 /*ifsp->next = NULL; - ckzalloc did it */
6044 ifslastp->next = ifsp;
6048 ifslastp->begoff = start;
6049 ifslastp->endoff = end;
6050 ifslastp->nulonly = nulonly;
6054 removerecordregions(int endoff)
6056 if (ifslastp == NULL)
6059 if (ifsfirst.endoff > endoff) {
6060 while (ifsfirst.next) {
6061 struct ifsregion *ifsp;
6063 ifsp = ifsfirst.next->next;
6064 free(ifsfirst.next);
6065 ifsfirst.next = ifsp;
6068 if (ifsfirst.begoff > endoff) {
6071 ifslastp = &ifsfirst;
6072 ifsfirst.endoff = endoff;
6077 ifslastp = &ifsfirst;
6078 while (ifslastp->next && ifslastp->next->begoff < endoff)
6079 ifslastp = ifslastp->next;
6080 while (ifslastp->next) {
6081 struct ifsregion *ifsp;
6083 ifsp = ifslastp->next->next;
6084 free(ifslastp->next);
6085 ifslastp->next = ifsp;
6088 if (ifslastp->endoff > endoff)
6089 ifslastp->endoff = endoff;
6093 exptilde(char *startp, char *p, int flags)
6099 int quotes = flags & QUOTES_ESC;
6103 while ((c = *++p) != '\0') {
6110 if (flags & EXP_VARTILDE)
6120 if (*name == '\0') {
6121 home = lookupvar("HOME");
6123 pw = getpwnam(name);
6128 if (!home || !*home)
6131 strtodest(home, SQSYNTAX, quotes);
6139 * Execute a command inside back quotes. If it's a builtin command, we
6140 * want to save its output in a block obtained from malloc. Otherwise
6141 * we fork off a subprocess and get the output of the command via a pipe.
6142 * Should be called with interrupts off.
6144 struct backcmd { /* result of evalbackcmd */
6145 int fd; /* file descriptor to read from */
6146 int nleft; /* number of chars in buffer */
6147 char *buf; /* buffer */
6148 struct job *jp; /* job structure for command */
6151 /* These forward decls are needed to use "eval" code for backticks handling: */
6152 #define EV_EXIT 01 /* exit after evaluating tree */
6153 static int evaltree(union node *, int);
6155 static void FAST_FUNC
6156 evalbackcmd(union node *n, struct backcmd *result)
6170 ash_msg_and_raise_error("pipe call failed");
6171 jp = makejob(/*n,*/ 1);
6172 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6178 dup2_or_raise(pip[1], 1);
6181 /* TODO: eflag clearing makes the following not abort:
6182 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6183 * which is what bash does (unless it is in POSIX mode).
6184 * dash deleted "eflag = 0" line in the commit
6185 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6186 * [EVAL] Don't clear eflag in evalbackcmd
6187 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6191 evaltree(n, EV_EXIT); /* actually evaltreenr... */
6196 result->fd = pip[0];
6200 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6201 result->fd, result->buf, result->nleft, result->jp));
6205 * Expand stuff in backwards quotes.
6208 expbackq(union node *cmd, int flag)
6216 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6217 struct stackmark smark;
6220 startloc = expdest - (char *)stackblock();
6221 pushstackmark(&smark, startloc);
6222 evalbackcmd(cmd, &in);
6223 popstackmark(&smark);
6230 memtodest(p, i, syntax, flag & QUOTES_ESC);
6234 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6235 TRACE(("expbackq: read returns %d\n", i));
6244 back_exitstatus = waitforjob(in.jp);
6248 /* Eat all trailing newlines */
6250 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6254 if (!(flag & EXP_QUOTED))
6255 recordregion(startloc, dest - (char *)stackblock(), 0);
6256 TRACE(("evalbackq: size:%d:'%.*s'\n",
6257 (int)((dest - (char *)stackblock()) - startloc),
6258 (int)((dest - (char *)stackblock()) - startloc),
6259 stackblock() + startloc));
6262 #if ENABLE_FEATURE_SH_MATH
6264 * Expand arithmetic expression. Backup to start of expression,
6265 * evaluate, place result in (backed up) result, adjust string position.
6277 * This routine is slightly over-complicated for
6278 * efficiency. Next we scan backwards looking for the
6279 * start of arithmetic.
6281 start = stackblock();
6288 while ((unsigned char)*p != CTLARI) {
6292 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6297 esc = esclen(start, p);
6307 removerecordregions(begoff);
6311 if (flag & QUOTES_ESC)
6312 rmescapes(p + 1, 0);
6314 len = cvtnum(ash_arith(p + 1));
6316 if (!(flag & EXP_QUOTED))
6317 recordregion(begoff, begoff + len, 0);
6321 /* argstr needs it */
6322 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6325 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6326 * characters to allow for further processing. Otherwise treat
6327 * $@ like $* since no splitting will be performed.
6329 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6330 * over shell variables. Needed for "A=a B=$A; echo $B" case - we use it
6331 * for correct expansion of "B=$A" word.
6334 argstr(char *p, int flags, struct strlist *var_str_list)
6336 static const char spclchars[] ALIGN1 = {
6344 #if ENABLE_FEATURE_SH_MATH
6349 const char *reject = spclchars;
6350 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6355 if (!(flags & EXP_VARTILDE)) {
6357 } else if (flags & EXP_VARTILDE2) {
6362 if (flags & EXP_TILDE) {
6365 flags &= ~EXP_TILDE;
6369 p = exptilde(p, q, flags);
6372 startloc = expdest - (char *)stackblock();
6376 length += strcspn(p + length, reject);
6380 IF_FEATURE_SH_MATH(|| c == CTLENDARI)
6382 /* c == '=' || c == ':' || c == CTLENDARI */
6388 expdest = stack_nputstr(p, length, expdest);
6389 newloc = expdest - (char *)stackblock();
6390 if (breakall && !inquotes && newloc > startloc) {
6391 recordregion(startloc, newloc, 0);
6402 if (flags & EXP_VARTILDE2) {
6406 flags |= EXP_VARTILDE2;
6411 * sort of a hack - expand tildes in variable
6412 * assignments (after the first '=' and after ':'s).
6421 case CTLENDVAR: /* ??? */
6424 inquotes ^= EXP_QUOTED;
6425 /* "$@" syntax adherence hack */
6426 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6427 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6431 if (flags & QUOTES_ESC) {
6442 * Quoted parameter expansion pattern: remove quote
6443 * unless inside inner quotes or we have a literal
6446 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6447 EXP_QPAT && *p != '\\')
6452 TRACE(("argstr: evalvar('%s')\n", p));
6453 p = evalvar(p, flags | inquotes, var_str_list);
6454 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6457 expbackq(argbackq->n, flags | inquotes);
6458 argbackq = argbackq->next;
6460 #if ENABLE_FEATURE_SH_MATH
6463 expari(flags | inquotes);
6472 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6473 char *pattern, int quotes, int zero)
6482 const char *s = loc2;
6489 match = pmatch(pattern, s);
6494 if (quotes && (unsigned char)*loc == CTLESC)
6503 scanright(char *startp, char *rmesc, char *rmescend,
6504 char *pattern, int quotes, int match_at_start)
6506 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6507 int try2optimize = match_at_start;
6513 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6514 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6515 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6517 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6518 * and on each iteration they go back two/one char until they reach the beginning.
6519 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6521 /* TODO: document in what other circumstances we are called. */
6523 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6526 const char *s = loc2;
6527 if (match_at_start) {
6531 match = pmatch(pattern, s);
6532 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6536 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6538 /* Maybe we can optimize this:
6539 * if pattern ends with unescaped *, we can avoid checking
6540 * shorter strings: if "foo*" doesn't match "raw_value_of_v",
6541 * it won't match truncated "raw_value_of_" strings too.
6543 unsigned plen = strlen(pattern);
6544 /* Does it end with "*"? */
6545 if (plen != 0 && pattern[--plen] == '*') {
6546 /* "xxxx*" is not escaped */
6547 /* "xxx\*" is escaped */
6548 /* "xx\\*" is not escaped */
6549 /* "x\\\*" is escaped */
6551 while (plen != 0 && pattern[--plen] == '\\')
6554 break; /* ends with unescaped "*" */
6562 esc = esclen(startp, loc);
6573 static void varunset(const char *, const char *, const char *, int) NORETURN;
6575 varunset(const char *end, const char *var, const char *umsg, int varflags)
6581 msg = "parameter not set";
6583 if ((unsigned char)*end == CTLENDVAR) {
6584 if (varflags & VSNUL)
6590 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6594 subevalvar(char *p, char *varname, int strloc, int subtype,
6595 int startloc, int varflags, int flag, struct strlist *var_str_list)
6597 struct nodelist *saveargbackq = argbackq;
6598 int quotes = flag & QUOTES_ESC;
6601 char *rmesc, *rmescend;
6603 IF_BASH_SUBSTR(int pos, len, orig_len;)
6604 int amount, resetloc;
6605 IF_BASH_PATTERN_SUBST(int workloc;)
6606 IF_BASH_PATTERN_SUBST(char *repl = NULL;)
6608 char *(*scan)(char*, char*, char*, char*, int, int);
6610 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6611 // p, varname, strloc, subtype, startloc, varflags, quotes);
6613 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6614 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6616 STPUTC('\0', expdest);
6617 argbackq = saveargbackq;
6618 startp = (char *)stackblock() + startloc;
6622 setvar0(varname, startp);
6623 amount = startp - expdest;
6624 STADJUST(amount, expdest);
6628 varunset(p, varname, startp, varflags);
6633 //TODO: support more general format ${v:EXPR:EXPR},
6634 // where EXPR follows $(()) rules
6635 loc = str = stackblock() + strloc;
6636 /* Read POS in ${var:POS:LEN} */
6637 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6638 len = str - startp - 1;
6640 /* *loc != '\0', guaranteed by parser */
6644 /* Adjust the length by the number of escapes */
6645 for (ptr = startp; ptr < (str - 1); ptr++) {
6646 if ((unsigned char)*ptr == CTLESC) {
6654 if (*loc++ == ':') {
6658 /* Skip POS in ${var:POS:LEN} */
6660 while (*loc && *loc != ':') {
6662 * bash complains on: var=qwe; echo ${var:1a:123}
6664 ash_msg_and_raise_error(msg_illnum, str);
6668 if (*loc++ == ':') {
6673 /* ${VAR:$((-n)):l} starts n chars from the end */
6674 pos = orig_len + pos;
6676 if ((unsigned)pos >= orig_len) {
6677 /* apart from obvious ${VAR:999999:l},
6678 * covers ${VAR:$((-9999999)):l} - result is ""
6684 if (len > (orig_len - pos))
6685 len = orig_len - pos;
6687 for (str = startp; pos; str++, pos--) {
6688 if (quotes && (unsigned char)*str == CTLESC)
6691 for (loc = startp; len; len--) {
6692 if (quotes && (unsigned char)*str == CTLESC)
6697 amount = loc - expdest;
6698 STADJUST(amount, expdest);
6700 #endif /* BASH_SUBSTR */
6703 resetloc = expdest - (char *)stackblock();
6705 #if BASH_PATTERN_SUBST
6706 /* We'll comeback here if we grow the stack while handling
6707 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6708 * stack will need rebasing, and we'll need to remove our work
6714 amount = expdest - ((char *)stackblock() + resetloc);
6715 STADJUST(-amount, expdest);
6716 startp = (char *)stackblock() + startloc;
6719 rmescend = (char *)stackblock() + strloc;
6721 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6722 if (rmesc != startp) {
6724 startp = (char *)stackblock() + startloc;
6728 str = (char *)stackblock() + strloc;
6730 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6731 * The result is a_\_z_c (not a\_\_z_c)!
6733 * The search pattern and replace string treat backslashes differently!
6734 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6735 * and string. It's only used on the first call.
6737 preglob(str, IF_BASH_PATTERN_SUBST(
6738 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6739 RMESCAPE_SLASH : ) 0);
6741 #if BASH_PATTERN_SUBST
6742 workloc = expdest - (char *)stackblock();
6743 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6747 repl = strchr(str, CTLESC);
6753 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6755 /* If there's no pattern to match, return the expansion unmolested */
6764 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6765 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6767 /* No match, advance */
6768 char *restart_detect = stackblock();
6770 STPUTC(*idx, expdest);
6771 if (quotes && (unsigned char)*idx == CTLESC) {
6774 STPUTC(*idx, expdest);
6776 if (stackblock() != restart_detect)
6781 /* continue; - prone to quadratic behavior, smarter code: */
6784 if (str[0] == '*') {
6785 /* Pattern is "*foo". If "*foo" does not match "long_string",
6786 * it would never match "ong_string" etc, no point in trying.
6793 if (subtype == VSREPLACEALL) {
6795 if (quotes && (unsigned char)*idx == CTLESC)
6804 //bb_error_msg("repl:'%s'", repl);
6805 for (loc = (char*)repl; *loc; loc++) {
6806 char *restart_detect = stackblock();
6807 if (quotes && *loc == '\\') {
6808 STPUTC(CTLESC, expdest);
6811 STPUTC(*loc, expdest);
6812 if (stackblock() != restart_detect)
6817 if (subtype == VSREPLACE) {
6818 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6820 char *restart_detect = stackblock();
6821 STPUTC(*idx, expdest);
6822 if (stackblock() != restart_detect)
6831 /* We've put the replaced text into a buffer at workloc, now
6832 * move it to the right place and adjust the stack.
6834 STPUTC('\0', expdest);
6835 startp = (char *)stackblock() + startloc;
6836 memmove(startp, (char *)stackblock() + workloc, len + 1);
6837 //bb_error_msg("startp:'%s'", startp);
6838 amount = expdest - (startp + len);
6839 STADJUST(-amount, expdest);
6842 #endif /* BASH_PATTERN_SUBST */
6844 subtype -= VSTRIMRIGHT;
6846 if (subtype < 0 || subtype > 7)
6849 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6850 zero = subtype >> 1;
6851 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6852 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6854 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6857 memmove(startp, loc, str - loc);
6858 loc = startp + (str - loc) - 1;
6861 amount = loc - expdest;
6862 STADJUST(amount, expdest);
6868 * Add the value of a specialized variable to the stack string.
6869 * name parameter (examples):
6870 * ash -c 'echo $1' name:'1='
6871 * ash -c 'echo $qwe' name:'qwe='
6872 * ash -c 'echo $$' name:'$='
6873 * ash -c 'echo ${$}' name:'$='
6874 * ash -c 'echo ${$##q}' name:'$=q'
6875 * ash -c 'echo ${#$}' name:'$='
6876 * note: examples with bad shell syntax:
6877 * ash -c 'echo ${#$1}' name:'$=1'
6878 * ash -c 'echo ${#1#}' name:'1=#'
6880 static NOINLINE ssize_t
6881 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list, int *quotedp)
6888 int quoted = *quotedp;
6889 int subtype = varflags & VSTYPE;
6890 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6891 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6894 sep = (flags & EXP_FULL) << CHAR_BIT;
6895 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6905 num = shellparam.nparam;
6913 goto check_1char_name;
6915 expdest = makestrspace(NOPTS, expdest);
6916 for (i = NOPTS - 1; i >= 0; i--) {
6918 USTPUTC(optletters(i), expdest);
6924 /* handles cases similar to ${#$1} */
6925 if (name[2] != '\0')
6926 raise_error_syntax("bad substitution");
6939 sep |= ifsset() ? ifsval()[0] : ' ';
6946 while ((p = *ap++) != NULL) {
6947 len += strtodest(p, syntax, quotes);
6951 memtodest(&sepc, 1, syntax, quotes);
6966 num = atoi(name); /* number(name) fails on ${N#str} etc */
6967 if (num < 0 || num > shellparam.nparam)
6969 p = num ? shellparam.p[num - 1] : arg0;
6972 /* NB: name has form "VAR=..." */
6974 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6975 * which should be considered before we check variables. */
6977 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6981 str = var_str_list->text;
6982 eq = strchr(str, '=');
6983 if (!eq) /* stop at first non-assignment */
6986 if (name_len == (unsigned)(eq - str)
6987 && strncmp(str, name, name_len) == 0
6990 /* goto value; - WRONG! */
6991 /* think "A=1 A=2 B=$A" */
6993 var_str_list = var_str_list->next;
6994 } while (var_str_list);
6998 p = lookupvar(name);
7003 len = strtodest(p, syntax, quotes);
7004 #if ENABLE_UNICODE_SUPPORT
7005 if (subtype == VSLENGTH && len > 0) {
7006 reinit_unicode_for_ash();
7007 if (unicode_status == UNICODE_ON) {
7008 STADJUST(-len, expdest);
7010 len = unicode_strlen(p);
7018 STADJUST(-len, expdest);
7023 * Expand a variable, and return a pointer to the next character in the
7027 evalvar(char *p, int flag, struct strlist *var_str_list)
7038 varflags = (unsigned char) *p++;
7039 subtype = varflags & VSTYPE;
7042 raise_error_syntax("bad substitution");
7044 quoted = flag & EXP_QUOTED;
7046 easy = (!quoted || (*var == '@' && shellparam.nparam));
7047 startloc = expdest - (char *)stackblock();
7048 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
7051 varlen = varvalue(var, varflags, flag, var_str_list, "ed);
7052 if (varflags & VSNUL)
7055 if (subtype == VSPLUS) {
7056 varlen = -1 - varlen;
7060 if (subtype == VSMINUS) {
7065 flag | EXP_TILDE | EXP_WORD,
7073 if (subtype == VSASSIGN || subtype == VSQUESTION) {
7077 subevalvar(p, var, 0, subtype, startloc, varflags,
7078 flag & ~QUOTES_ESC, var_str_list);
7081 * Remove any recorded regions beyond
7084 removerecordregions(startloc);
7088 if (varlen < 0 && uflag)
7089 varunset(p, var, 0, 0);
7091 if (subtype == VSLENGTH) {
7092 cvtnum(varlen > 0 ? varlen : 0);
7096 if (subtype == VSNORMAL) {
7100 recordregion(startloc, expdest - (char *)stackblock(), quoted);
7109 case VSTRIMRIGHTMAX:
7113 #if BASH_PATTERN_SUBST
7125 * Terminate the string and start recording the pattern
7128 STPUTC('\0', expdest);
7129 patloc = expdest - (char *)stackblock();
7130 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7131 startloc, varflags, flag, var_str_list)) {
7132 int amount = expdest - (
7133 (char *)stackblock() + patloc - 1
7135 STADJUST(-amount, expdest);
7137 /* Remove any recorded regions beyond start of variable */
7138 removerecordregions(startloc);
7143 if (subtype != VSNORMAL) { /* skip to end of alternative */
7146 unsigned char c = *p++;
7149 else if (c == CTLBACKQ) {
7151 argbackq = argbackq->next;
7152 } else if (c == CTLVAR) {
7153 if ((*p++ & VSTYPE) != VSNORMAL)
7155 } else if (c == CTLENDVAR) {
7165 * Add a file name to the list.
7168 addfname(const char *name)
7172 sp = stzalloc(sizeof(*sp));
7173 sp->text = sstrdup(name);
7175 exparg.lastp = &sp->next;
7178 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7180 hasmeta(const char *p)
7182 static const char chars[] ALIGN1 = {
7183 '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
7187 p = strpbrk(p, chars);
7190 switch ((unsigned char) *p) {
7194 if (*p == CTLQUOTEMARK)
7198 if (*p == '\0') /* huh? */
7209 if (!strchr(p + 1, ']')) {
7210 /* It's not a properly closed [] pattern,
7211 * but other metas may follow. Continue checking.
7212 * my[file* _is_ globbed by bash
7213 * and matches filenames like "my[file1".
7229 /* If we want to use glob() from libc... */
7230 #if !ENABLE_ASH_INTERNAL_GLOB
7232 /* Add the result of glob() to the list */
7234 addglob(const glob_t *pglob)
7236 char **p = pglob->gl_pathv;
7243 expandmeta(struct strlist *str /*, int flag*/)
7245 /* TODO - EXP_REDIR */
7255 if (!hasmeta(str->text))
7259 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7260 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7261 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7263 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7264 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7265 // Which means you need to unescape the string, right? Not so fast:
7266 // if there _is_ a file named "file\?" (with backslash), it is returned
7267 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7268 // You DON'T KNOW by looking at the result whether you need to unescape it.
7270 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7271 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7272 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7273 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7274 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7275 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7276 i = glob(p, 0, NULL, &pglob);
7277 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7282 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7283 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7284 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7296 *exparg.lastp = str;
7297 rmescapes(str->text, 0);
7298 exparg.lastp = &str->next;
7300 default: /* GLOB_NOSPACE */
7303 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7310 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7313 * Do metacharacter (i.e. *, ?, [...]) expansion.
7316 expmeta(char *expdir, char *enddir, char *name)
7332 for (p = name; esc = 0, *p; p += esc + 1) {
7333 if (*p == '*' || *p == '?')
7335 else if (*p == '[') {
7342 if (*q == '/' || *q == '\0')
7352 if (p[esc] == '/') {
7355 start = p + esc + 1;
7359 if (metaflag == 0) { /* we've reached the end of the file name */
7360 if (enddir != expdir)
7368 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7379 } while (p < start);
7381 if (enddir == expdir) {
7383 } else if (enddir == expdir + 1 && *expdir == '/') {
7392 if (enddir != expdir)
7394 if (*endname == 0) {
7407 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7408 if (dp->d_name[0] == '.' && !matchdot)
7410 if (pmatch(start, dp->d_name)) {
7412 strcpy(enddir, dp->d_name);
7415 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7418 expmeta(expdir, p, endname);
7424 endname[-esc - 1] = esc ? '\\' : '/';
7427 static struct strlist *
7428 msort(struct strlist *list, int len)
7430 struct strlist *p, *q = NULL;
7431 struct strlist **lpp;
7439 for (n = half; --n >= 0;) {
7443 q->next = NULL; /* terminate first half of list */
7444 q = msort(list, half); /* sort first half of list */
7445 p = msort(p, len - half); /* sort second half */
7448 #if ENABLE_LOCALE_SUPPORT
7449 if (strcoll(p->text, q->text) < 0)
7451 if (strcmp(p->text, q->text) < 0)
7475 * Sort the results of file name expansion. It calculates the number of
7476 * strings to sort and then calls msort (short for merge sort) to do the
7479 static struct strlist *
7480 expsort(struct strlist *str)
7486 for (sp = str; sp; sp = sp->next)
7488 return msort(str, len);
7492 expandmeta(struct strlist *str /*, int flag*/)
7494 /* TODO - EXP_REDIR */
7498 struct strlist **savelastp;
7504 if (!hasmeta(str->text))
7506 savelastp = exparg.lastp;
7509 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7511 int i = strlen(str->text);
7512 //BUGGY estimation of how long expanded name can be
7513 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7515 expmeta(expdir, expdir, p);
7520 if (exparg.lastp == savelastp) {
7525 *exparg.lastp = str;
7526 rmescapes(str->text, 0);
7527 exparg.lastp = &str->next;
7529 *exparg.lastp = NULL;
7530 *savelastp = sp = expsort(*savelastp);
7531 while (sp->next != NULL)
7533 exparg.lastp = &sp->next;
7538 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7541 * Perform variable substitution and command substitution on an argument,
7542 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7543 * perform splitting and file name expansion. When arglist is NULL, perform
7544 * here document expansion.
7547 expandarg(union node *arg, struct arglist *arglist, int flag)
7552 argbackq = arg->narg.backquote;
7553 STARTSTACKSTR(expdest);
7554 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7555 argstr(arg->narg.text, flag,
7556 /* var_str_list: */ arglist ? arglist->list : NULL);
7557 p = _STPUTC('\0', expdest);
7559 if (arglist == NULL) {
7560 /* here document expanded */
7563 p = grabstackstr(p);
7564 TRACE(("expandarg: p:'%s'\n", p));
7565 exparg.lastp = &exparg.list;
7569 if (flag & EXP_FULL) {
7570 ifsbreakup(p, &exparg);
7571 *exparg.lastp = NULL;
7572 exparg.lastp = &exparg.list;
7573 expandmeta(exparg.list /*, flag*/);
7575 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7577 TRACE(("expandarg: rmescapes:'%s'\n", p));
7579 sp = stzalloc(sizeof(*sp));
7582 exparg.lastp = &sp->next;
7584 *exparg.lastp = NULL;
7586 *arglist->lastp = exparg.list;
7587 arglist->lastp = exparg.lastp;
7595 * Expand shell variables and backquotes inside a here document.
7598 expandhere(union node *arg, int fd)
7600 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7601 full_write(fd, stackblock(), expdest - (char *)stackblock());
7605 * Returns true if the pattern matches the string.
7608 patmatch(char *pattern, const char *string)
7610 return pmatch(preglob(pattern, 0), string);
7614 * See if a pattern matches in a case statement.
7617 casematch(union node *pattern, char *val)
7619 struct stackmark smark;
7622 setstackmark(&smark);
7623 argbackq = pattern->narg.backquote;
7624 STARTSTACKSTR(expdest);
7625 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7626 /* var_str_list: */ NULL);
7627 STACKSTRNUL(expdest);
7629 result = patmatch(stackblock(), val);
7630 popstackmark(&smark);
7635 /* ============ find_command */
7639 int (*builtin)(int, char **) FAST_FUNC;
7640 /* unsigned flags; */
7642 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7643 /* "regular" builtins always take precedence over commands,
7644 * regardless of PATH=....%builtin... position */
7645 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7646 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7649 smallint cmdtype; /* CMDxxx */
7652 /* index >= 0 for commands without path (slashes) */
7653 /* (TODO: what exactly does the value mean? PATH position?) */
7654 /* index == -1 for commands with slashes */
7655 /* index == (-2 - applet_no) for NOFORK applets */
7656 const struct builtincmd *cmd;
7657 struct funcnode *func;
7660 /* values of cmdtype */
7661 #define CMDUNKNOWN -1 /* no entry in table for command */
7662 #define CMDNORMAL 0 /* command is an executable program */
7663 #define CMDFUNCTION 1 /* command is a shell function */
7664 #define CMDBUILTIN 2 /* command is a shell builtin */
7666 /* action to find_command() */
7667 #define DO_ERR 0x01 /* prints errors */
7668 #define DO_ABS 0x02 /* checks absolute paths */
7669 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7670 #define DO_ALTPATH 0x08 /* using alternate path */
7671 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7673 static void find_command(char *, struct cmdentry *, int, const char *);
7676 /* ============ Hashing commands */
7679 * When commands are first encountered, they are entered in a hash table.
7680 * This ensures that a full path search will not have to be done for them
7681 * on each invocation.
7683 * We should investigate converting to a linear search, even though that
7684 * would make the command name "hash" a misnomer.
7688 struct tblentry *next; /* next entry in hash chain */
7689 union param param; /* definition of builtin function */
7690 smallint cmdtype; /* CMDxxx */
7691 char rehash; /* if set, cd done since entry created */
7692 char cmdname[1]; /* name of command */
7695 static struct tblentry **cmdtable;
7696 #define INIT_G_cmdtable() do { \
7697 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7700 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7704 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7706 #if ENABLE_FEATURE_SH_STANDALONE
7707 if (applet_no >= 0) {
7708 if (APPLET_IS_NOEXEC(applet_no)) {
7712 run_applet_no_and_exit(applet_no, argv);
7714 /* re-exec ourselves with the new arguments */
7715 execve(bb_busybox_exec_path, argv, envp);
7716 /* If they called chroot or otherwise made the binary no longer
7717 * executable, fall through */
7724 execve(cmd, argv, envp);
7725 } while (errno == EINTR);
7727 execve(cmd, argv, envp);
7729 if (cmd != (char*) bb_busybox_exec_path && errno == ENOEXEC) {
7730 /* Run "cmd" as a shell script:
7731 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7732 * "If the execve() function fails with ENOEXEC, the shell
7733 * shall execute a command equivalent to having a shell invoked
7734 * with the command name as its first operand,
7735 * with any remaining arguments passed to the new shell"
7737 * That is, do not use $SHELL, user's shell, or /bin/sh;
7738 * just call ourselves.
7740 * Note that bash reads ~80 chars of the file, and if it sees
7741 * a zero byte before it sees newline, it doesn't try to
7742 * interpret it, but fails with "cannot execute binary file"
7743 * message and exit code 126. For one, this prevents attempts
7744 * to interpret foreign ELF binaries as shell scripts.
7747 cmd = (char*) bb_busybox_exec_path;
7748 /* NB: this is only possible because all callers of shellexec()
7749 * ensure that the argv[-1] slot exists!
7752 argv[0] = (char*) "ash";
7758 * Exec a program. Never returns. If you change this routine, you may
7759 * have to change the find_command routine as well.
7760 * argv[-1] must exist and be writable! See tryexec() for why.
7762 static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
7763 static void shellexec(char *prog, char **argv, const char *path, int idx)
7769 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7771 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7772 if (strchr(prog, '/') != NULL
7773 #if ENABLE_FEATURE_SH_STANDALONE
7774 || (applet_no = find_applet_by_name(prog)) >= 0
7777 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
7778 if (applet_no >= 0) {
7779 /* We tried execing ourself, but it didn't work.
7780 * Maybe /proc/self/exe doesn't exist?
7789 while ((cmdname = path_advance(&path, prog)) != NULL) {
7790 if (--idx < 0 && pathopt == NULL) {
7791 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7792 if (errno != ENOENT && errno != ENOTDIR)
7799 /* Map to POSIX errors */
7811 exitstatus = exerrno;
7812 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7813 prog, e, suppress_int));
7814 ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
7819 printentry(struct tblentry *cmdp)
7825 idx = cmdp->param.index;
7828 name = path_advance(&path, cmdp->cmdname);
7830 } while (--idx >= 0);
7831 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7835 * Clear out command entries. The argument specifies the first entry in
7836 * PATH which has changed.
7839 clearcmdentry(int firstchange)
7841 struct tblentry **tblp;
7842 struct tblentry **pp;
7843 struct tblentry *cmdp;
7846 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7848 while ((cmdp = *pp) != NULL) {
7849 if ((cmdp->cmdtype == CMDNORMAL &&
7850 cmdp->param.index >= firstchange)
7851 || (cmdp->cmdtype == CMDBUILTIN &&
7852 builtinloc >= firstchange)
7865 * Locate a command in the command hash table. If "add" is nonzero,
7866 * add the command to the table if it is not already present. The
7867 * variable "lastcmdentry" is set to point to the address of the link
7868 * pointing to the entry, so that delete_cmd_entry can delete the
7871 * Interrupts must be off if called with add != 0.
7873 static struct tblentry **lastcmdentry;
7875 static struct tblentry *
7876 cmdlookup(const char *name, int add)
7878 unsigned int hashval;
7880 struct tblentry *cmdp;
7881 struct tblentry **pp;
7884 hashval = (unsigned char)*p << 4;
7886 hashval += (unsigned char)*p++;
7888 pp = &cmdtable[hashval % CMDTABLESIZE];
7889 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7890 if (strcmp(cmdp->cmdname, name) == 0)
7894 if (add && cmdp == NULL) {
7895 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7897 /* + 1 - already done because
7898 * tblentry::cmdname is char[1] */);
7899 /*cmdp->next = NULL; - ckzalloc did it */
7900 cmdp->cmdtype = CMDUNKNOWN;
7901 strcpy(cmdp->cmdname, name);
7908 * Delete the command entry returned on the last lookup.
7911 delete_cmd_entry(void)
7913 struct tblentry *cmdp;
7916 cmdp = *lastcmdentry;
7917 *lastcmdentry = cmdp->next;
7918 if (cmdp->cmdtype == CMDFUNCTION)
7919 freefunc(cmdp->param.func);
7925 * Add a new command entry, replacing any existing command entry for
7926 * the same name - except special builtins.
7929 addcmdentry(char *name, struct cmdentry *entry)
7931 struct tblentry *cmdp;
7933 cmdp = cmdlookup(name, 1);
7934 if (cmdp->cmdtype == CMDFUNCTION) {
7935 freefunc(cmdp->param.func);
7937 cmdp->cmdtype = entry->cmdtype;
7938 cmdp->param = entry->u;
7942 static int FAST_FUNC
7943 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7945 struct tblentry **pp;
7946 struct tblentry *cmdp;
7948 struct cmdentry entry;
7951 if (nextopt("r") != '\0') {
7956 if (*argptr == NULL) {
7957 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7958 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7959 if (cmdp->cmdtype == CMDNORMAL)
7967 while ((name = *argptr) != NULL) {
7968 cmdp = cmdlookup(name, 0);
7970 && (cmdp->cmdtype == CMDNORMAL
7971 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7975 find_command(name, &entry, DO_ERR, pathval());
7976 if (entry.cmdtype == CMDUNKNOWN)
7984 * Called when a cd is done. Marks all commands so the next time they
7985 * are executed they will be rehashed.
7990 struct tblentry **pp;
7991 struct tblentry *cmdp;
7993 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7994 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7995 if (cmdp->cmdtype == CMDNORMAL
7996 || (cmdp->cmdtype == CMDBUILTIN
7997 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
8007 * Fix command hash table when PATH changed.
8008 * Called before PATH is changed. The argument is the new value of PATH;
8009 * pathval() still returns the old value at this point.
8010 * Called with interrupts off.
8012 static void FAST_FUNC
8013 changepath(const char *new)
8021 firstchange = 9999; /* assume no change */
8027 if ((*old == '\0' && *new == ':')
8028 || (*old == ':' && *new == '\0')
8032 old = new; /* ignore subsequent differences */
8036 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
8043 if (builtinloc < 0 && idx_bltin >= 0)
8044 builtinloc = idx_bltin; /* zap builtins */
8045 if (builtinloc >= 0 && idx_bltin < 0)
8047 clearcmdentry(firstchange);
8048 builtinloc = idx_bltin;
8084 typedef smallint token_id_t;
8086 /* Nth bit indicates if token marks the end of a list */
8089 /* 0 */ | (1u << TEOF)
8090 /* 1 */ | (0u << TNL)
8091 /* 2 */ | (0u << TREDIR)
8092 /* 3 */ | (0u << TWORD)
8093 /* 4 */ | (0u << TSEMI)
8094 /* 5 */ | (0u << TBACKGND)
8095 /* 6 */ | (0u << TAND)
8096 /* 7 */ | (0u << TOR)
8097 /* 8 */ | (0u << TPIPE)
8098 /* 9 */ | (0u << TLP)
8099 /* 10 */ | (1u << TRP)
8100 /* 11 */ | (1u << TENDCASE)
8101 /* 12 */ | (1u << TENDBQUOTE)
8102 /* 13 */ | (0u << TNOT)
8103 /* 14 */ | (0u << TCASE)
8104 /* 15 */ | (1u << TDO)
8105 /* 16 */ | (1u << TDONE)
8106 /* 17 */ | (1u << TELIF)
8107 /* 18 */ | (1u << TELSE)
8108 /* 19 */ | (1u << TESAC)
8109 /* 20 */ | (1u << TFI)
8110 /* 21 */ | (0u << TFOR)
8112 /* 22 */ | (0u << TFUNCTION)
8114 /* 23 */ | (0u << TIF)
8115 /* 24 */ | (0u << TIN)
8116 /* 25 */ | (1u << TTHEN)
8117 /* 26 */ | (0u << TUNTIL)
8118 /* 27 */ | (0u << TWHILE)
8119 /* 28 */ | (0u << TBEGIN)
8120 /* 29 */ | (1u << TEND)
8121 , /* thus far 29 bits used */
8124 static const char *const tokname_array[] = {
8138 #define KWDOFFSET 13
8139 /* the following are keywords */
8161 /* Wrapper around strcmp for qsort/bsearch/... */
8163 pstrcmp(const void *a, const void *b)
8165 return strcmp((char*)a, *(char**)b);
8168 static const char *const *
8169 findkwd(const char *s)
8171 return bsearch(s, tokname_array + KWDOFFSET,
8172 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8173 sizeof(tokname_array[0]), pstrcmp);
8177 * Locate and print what a word is...
8180 describe_command(char *command, const char *path, int describe_command_verbose)
8182 struct cmdentry entry;
8183 #if ENABLE_ASH_ALIAS
8184 const struct alias *ap;
8187 path = path ? path : pathval();
8189 if (describe_command_verbose) {
8193 /* First look at the keywords */
8194 if (findkwd(command)) {
8195 out1str(describe_command_verbose ? " is a shell keyword" : command);
8199 #if ENABLE_ASH_ALIAS
8200 /* Then look at the aliases */
8201 ap = lookupalias(command, 0);
8203 if (!describe_command_verbose) {
8208 out1fmt(" is an alias for %s", ap->val);
8213 find_command(command, &entry, DO_ABS, path);
8215 switch (entry.cmdtype) {
8217 int j = entry.u.index;
8223 p = path_advance(&path, command);
8227 if (describe_command_verbose) {
8228 out1fmt(" is %s", p);
8236 if (describe_command_verbose) {
8237 out1str(" is a shell function");
8244 if (describe_command_verbose) {
8245 out1fmt(" is a %sshell builtin",
8246 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8247 "special " : nullstr
8255 if (describe_command_verbose) {
8256 out1str(": not found\n");
8265 static int FAST_FUNC
8266 typecmd(int argc UNUSED_PARAM, char **argv)
8272 /* type -p ... ? (we don't bother checking for 'p') */
8273 if (argv[1] && argv[1][0] == '-') {
8278 err |= describe_command(argv[i++], NULL, verbose);
8283 #if ENABLE_ASH_CMDCMD
8284 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8286 parse_command_args(char **argv, const char **path)
8299 if (c == '-' && !*cp) {
8307 *path = bb_default_path;
8310 /* run 'typecmd' for other options */
8319 static int FAST_FUNC
8320 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8328 const char *path = NULL;
8330 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8331 * never reaches this function.
8334 while ((c = nextopt("pvV")) != '\0')
8336 verify |= VERIFY_VERBOSE;
8338 /*verify |= VERIFY_BRIEF*/;
8344 path = bb_default_path;
8346 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8348 if (/*verify && */ cmd)
8349 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8356 /*static int funcblocksize; // size of structures in function */
8357 /*static int funcstringsize; // size of strings in node */
8358 static void *funcblock; /* block to allocate function from */
8359 static char *funcstring_end; /* end of block to allocate strings from */
8361 /* flags in argument to evaltree */
8362 #define EV_EXIT 01 /* exit after evaluating tree */
8363 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8365 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8366 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8367 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8368 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8369 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8370 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8371 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8372 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8373 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8374 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8375 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8376 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8377 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8378 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8379 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8380 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8381 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8382 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8383 #if BASH_REDIR_OUTPUT
8384 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8386 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8387 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8388 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8389 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8390 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8391 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8392 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8393 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8394 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8397 static int calcsize(int funcblocksize, union node *n);
8400 sizenodelist(int funcblocksize, struct nodelist *lp)
8403 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8404 funcblocksize = calcsize(funcblocksize, lp->n);
8407 return funcblocksize;
8411 calcsize(int funcblocksize, union node *n)
8414 return funcblocksize;
8415 funcblocksize += nodesize[n->type];
8418 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8419 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8420 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8423 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8428 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8429 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8436 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8437 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8440 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8441 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8442 funcblocksize = calcsize(funcblocksize, n->nif.test);
8445 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8446 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8447 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8450 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8451 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8454 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8455 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8456 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8460 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8461 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8462 funcblocksize = calcsize(funcblocksize, n->narg.next);
8465 #if BASH_REDIR_OUTPUT
8472 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8473 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8477 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8478 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8482 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8483 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8486 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8489 return funcblocksize;
8493 nodeckstrdup(char *s)
8495 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8496 return strcpy(funcstring_end, s);
8499 static union node *copynode(union node *);
8501 static struct nodelist *
8502 copynodelist(struct nodelist *lp)
8504 struct nodelist *start;
8505 struct nodelist **lpp;
8510 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8511 (*lpp)->n = copynode(lp->n);
8513 lpp = &(*lpp)->next;
8520 copynode(union node *n)
8527 funcblock = (char *) funcblock + nodesize[n->type];
8531 new->ncmd.redirect = copynode(n->ncmd.redirect);
8532 new->ncmd.args = copynode(n->ncmd.args);
8533 new->ncmd.assign = copynode(n->ncmd.assign);
8536 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8537 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8542 new->nredir.redirect = copynode(n->nredir.redirect);
8543 new->nredir.n = copynode(n->nredir.n);
8550 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8551 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8554 new->nif.elsepart = copynode(n->nif.elsepart);
8555 new->nif.ifpart = copynode(n->nif.ifpart);
8556 new->nif.test = copynode(n->nif.test);
8559 new->nfor.var = nodeckstrdup(n->nfor.var);
8560 new->nfor.body = copynode(n->nfor.body);
8561 new->nfor.args = copynode(n->nfor.args);
8564 new->ncase.cases = copynode(n->ncase.cases);
8565 new->ncase.expr = copynode(n->ncase.expr);
8568 new->nclist.body = copynode(n->nclist.body);
8569 new->nclist.pattern = copynode(n->nclist.pattern);
8570 new->nclist.next = copynode(n->nclist.next);
8574 new->narg.backquote = copynodelist(n->narg.backquote);
8575 new->narg.text = nodeckstrdup(n->narg.text);
8576 new->narg.next = copynode(n->narg.next);
8579 #if BASH_REDIR_OUTPUT
8586 new->nfile.fname = copynode(n->nfile.fname);
8587 new->nfile.fd = n->nfile.fd;
8588 new->nfile.next = copynode(n->nfile.next);
8592 new->ndup.vname = copynode(n->ndup.vname);
8593 new->ndup.dupfd = n->ndup.dupfd;
8594 new->ndup.fd = n->ndup.fd;
8595 new->ndup.next = copynode(n->ndup.next);
8599 new->nhere.doc = copynode(n->nhere.doc);
8600 new->nhere.fd = n->nhere.fd;
8601 new->nhere.next = copynode(n->nhere.next);
8604 new->nnot.com = copynode(n->nnot.com);
8607 new->type = n->type;
8612 * Make a copy of a parse tree.
8614 static struct funcnode *
8615 copyfunc(union node *n)
8620 /*funcstringsize = 0;*/
8621 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8622 f = ckzalloc(blocksize /* + funcstringsize */);
8623 funcblock = (char *) f + offsetof(struct funcnode, n);
8624 funcstring_end = (char *) f + blocksize;
8626 /* f->count = 0; - ckzalloc did it */
8631 * Define a shell function.
8634 defun(union node *func)
8636 struct cmdentry entry;
8639 entry.cmdtype = CMDFUNCTION;
8640 entry.u.func = copyfunc(func);
8641 addcmdentry(func->narg.text, &entry);
8645 /* Reasons for skipping commands (see comment on breakcmd routine) */
8646 #define SKIPBREAK (1 << 0)
8647 #define SKIPCONT (1 << 1)
8648 #define SKIPFUNC (1 << 2)
8649 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8650 static int skipcount; /* number of levels to skip */
8651 static int funcnest; /* depth of function calls */
8652 static int loopnest; /* current loop nesting level */
8654 /* Forward decl way out to parsing code - dotrap needs it */
8655 static int evalstring(char *s, int flags);
8657 /* Called to execute a trap.
8658 * Single callsite - at the end of evaltree().
8659 * If we return non-zero, evaltree raises EXEXIT exception.
8661 * Perhaps we should avoid entering new trap handlers
8662 * while we are executing a trap handler. [is it a TODO?]
8669 uint8_t last_status;
8674 last_status = exitstatus;
8678 TRACE(("dotrap entered\n"));
8679 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8691 /* non-trapped SIGINT is handled separately by raise_interrupt,
8692 * don't upset it by resetting gotsig[SIGINT-1] */
8693 if (sig == SIGINT && !p)
8696 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8702 exitstatus = last_status;
8703 TRACE(("dotrap returns\n"));
8706 /* forward declarations - evaluation is fairly recursive business... */
8707 static int evalloop(union node *, int);
8708 static int evalfor(union node *, int);
8709 static int evalcase(union node *, int);
8710 static int evalsubshell(union node *, int);
8711 static void expredir(union node *);
8712 static int evalpipe(union node *, int);
8713 static int evalcommand(union node *, int);
8714 static int evalbltin(const struct builtincmd *, int, char **, int);
8715 static void prehash(union node *);
8718 * Evaluate a parse tree. The value is left in the global variable
8722 evaltree(union node *n, int flags)
8725 int (*evalfn)(union node *, int);
8729 TRACE(("evaltree(NULL) called\n"));
8732 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8739 out1fmt("Node type = %d\n", n->type);
8744 status = !evaltree(n->nnot.com, EV_TESTED);
8747 expredir(n->nredir.redirect);
8748 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8750 status = evaltree(n->nredir.n, flags & EV_TESTED);
8752 if (n->nredir.redirect)
8753 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8756 evalfn = evalcommand;
8758 if (eflag && !(flags & EV_TESTED))
8770 evalfn = evalsubshell;
8783 #error NAND + 1 != NOR
8785 #if NOR + 1 != NSEMI
8786 #error NOR + 1 != NSEMI
8788 unsigned is_or = n->type - NAND;
8791 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8793 if ((!status) == is_or || evalskip)
8799 status = evalfn(n, flags);
8803 status = evaltree(n->nif.test, EV_TESTED);
8810 if (n->nif.elsepart) {
8811 n = n->nif.elsepart;
8818 /* Not necessary. To test it:
8819 * "false; f() { qwerty; }; echo $?" should print 0.
8823 exitstatus = status;
8827 /* Order of checks below is important:
8828 * signal handlers trigger before exit caused by "set -e".
8832 if (checkexit & status)
8833 raise_exception(EXEXIT);
8834 if (flags & EV_EXIT)
8835 raise_exception(EXEXIT);
8837 TRACE(("leaving evaltree (no interrupts)\n"));
8841 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8844 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8849 int skip = evalskip;
8856 if (--skipcount <= 0) {
8867 evalloop(union node *n, int flags)
8878 i = evaltree(n->nbinary.ch1, EV_TESTED);
8880 if (skip == SKIPFUNC)
8884 if (n->type != NWHILE)
8888 status = evaltree(n->nbinary.ch2, flags);
8890 } while (!(skip & ~SKIPCONT));
8897 evalfor(union node *n, int flags)
8899 struct arglist arglist;
8902 struct stackmark smark;
8905 setstackmark(&smark);
8906 arglist.list = NULL;
8907 arglist.lastp = &arglist.list;
8908 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8909 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8911 *arglist.lastp = NULL;
8915 for (sp = arglist.list; sp; sp = sp->next) {
8916 setvar0(n->nfor.var, sp->text);
8917 status = evaltree(n->nfor.body, flags);
8918 if (skiploop() & ~SKIPCONT)
8922 popstackmark(&smark);
8928 evalcase(union node *n, int flags)
8932 struct arglist arglist;
8933 struct stackmark smark;
8936 setstackmark(&smark);
8937 arglist.list = NULL;
8938 arglist.lastp = &arglist.list;
8939 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8940 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8941 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8942 if (casematch(patp, arglist.list->text)) {
8943 /* Ensure body is non-empty as otherwise
8944 * EV_EXIT may prevent us from setting the
8947 if (evalskip == 0 && cp->nclist.body) {
8948 status = evaltree(cp->nclist.body, flags);
8955 popstackmark(&smark);
8961 * Kick off a subshell to evaluate a tree.
8964 evalsubshell(union node *n, int flags)
8967 int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
8970 expredir(n->nredir.redirect);
8971 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8974 if (backgnd == FORK_FG)
8976 jp = makejob(/*n,*/ 1);
8977 if (forkshell(jp, n, backgnd) == 0) {
8982 flags &= ~EV_TESTED;
8984 redirect(n->nredir.redirect, 0);
8985 evaltreenr(n->nredir.n, flags);
8990 if (backgnd == FORK_FG)
8991 status = waitforjob(jp);
8997 * Compute the names of the files in a redirection list.
8999 static void fixredir(union node *, const char *, int);
9001 expredir(union node *n)
9005 for (redir = n; redir; redir = redir->nfile.next) {
9009 fn.lastp = &fn.list;
9010 switch (redir->type) {
9014 #if BASH_REDIR_OUTPUT
9019 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
9020 TRACE(("expredir expanded to '%s'\n", fn.list->text));
9021 #if BASH_REDIR_OUTPUT
9025 // By the design of stack allocator, the loop of this kind:
9026 // while true; do while true; do break; done </dev/null; done
9027 // will look like a memory leak: ash plans to free expfname's
9028 // of "/dev/null" as soon as it finishes running the loop
9029 // (in this case, never).
9030 // This "fix" is wrong:
9031 if (redir->nfile.expfname)
9032 stunalloc(redir->nfile.expfname);
9033 // It results in corrupted state of stacked allocations.
9035 redir->nfile.expfname = fn.list->text;
9038 case NTOFD: /* >& */
9039 if (redir->ndup.vname) {
9040 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
9041 if (fn.list == NULL)
9042 ash_msg_and_raise_error("redir error");
9043 #if BASH_REDIR_OUTPUT
9044 //FIXME: we used expandarg with different args!
9045 if (!isdigit_str9(fn.list->text)) {
9046 /* >&file, not >&fd */
9047 if (redir->nfile.fd != 1) /* 123>&file - BAD */
9048 ash_msg_and_raise_error("redir error");
9050 goto store_expfname;
9053 fixredir(redir, fn.list->text, 1);
9061 * Evaluate a pipeline. All the processes in the pipeline are children
9062 * of the process creating the pipeline. (This differs from some versions
9063 * of the shell, which make the last process in a pipeline the parent
9067 evalpipe(union node *n, int flags)
9070 struct nodelist *lp;
9076 TRACE(("evalpipe(0x%lx) called\n", (long)n));
9078 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
9082 if (n->npipe.pipe_backgnd == 0)
9084 jp = makejob(/*n,*/ pipelen);
9086 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
9090 if (pipe(pip) < 0) {
9092 ash_msg_and_raise_error("pipe call failed");
9095 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
9109 evaltreenr(lp->n, flags);
9116 /* Don't want to trigger debugging */
9120 if (n->npipe.pipe_backgnd == 0) {
9121 status = waitforjob(jp);
9122 TRACE(("evalpipe: job done exit status %d\n", status));
9130 * Controls whether the shell is interactive or not.
9133 setinteractive(int on)
9135 static smallint is_interactive;
9137 if (++on == is_interactive)
9139 is_interactive = on;
9143 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9144 if (is_interactive > 1) {
9145 /* Looks like they want an interactive shell */
9146 static smallint did_banner;
9149 /* note: ash and hush share this string */
9150 out1fmt("\n\n%s %s\n"
9151 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9154 "built-in shell (ash)"
9168 setinteractive(iflag);
9170 #if ENABLE_FEATURE_EDITING_VI
9172 line_input_state->flags |= VI_MODE;
9174 line_input_state->flags &= ~VI_MODE;
9176 viflag = 0; /* forcibly keep the option off */
9180 static struct localvar *localvars;
9183 * Called after a function returns.
9184 * Interrupts must be off.
9189 struct localvar *lvp;
9192 while ((lvp = localvars) != NULL) {
9193 localvars = lvp->next;
9195 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9196 if (vp == NULL) { /* $- saved */
9197 memcpy(optlist, lvp->text, sizeof(optlist));
9198 free((char*)lvp->text);
9200 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
9201 unsetvar(vp->var_text);
9204 vp->var_func(var_end(lvp->text));
9205 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9206 free((char*)vp->var_text);
9207 vp->flags = lvp->flags;
9208 vp->var_text = lvp->text;
9215 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9217 volatile struct shparam saveparam;
9218 struct localvar *volatile savelocalvars;
9219 struct jmploc *volatile savehandler;
9220 struct jmploc jmploc;
9223 saveparam = shellparam;
9224 savelocalvars = localvars;
9225 savehandler = exception_handler;
9226 e = setjmp(jmploc.loc);
9231 exception_handler = &jmploc;
9233 shellparam.malloced = 0;
9237 shellparam.nparam = argc - 1;
9238 shellparam.p = argv + 1;
9239 #if ENABLE_ASH_GETOPTS
9240 shellparam.optind = 1;
9241 shellparam.optoff = -1;
9243 evaltree(func->n.narg.next, flags & EV_TESTED);
9249 localvars = savelocalvars;
9250 freeparam(&shellparam);
9251 shellparam = saveparam;
9252 exception_handler = savehandler;
9254 evalskip &= ~SKIPFUNC;
9259 * Make a variable a local variable. When a variable is made local, it's
9260 * value and flags are saved in a localvar structure. The saved values
9261 * will be restored when the shell function returns. We handle the name
9262 * "-" as a special case: it makes changes to "set +-options" local
9263 * (options will be restored on return from the function).
9268 struct localvar *lvp;
9271 char *eq = strchr(name, '=');
9274 /* Cater for duplicate "local". Examples:
9275 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9276 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9280 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9284 * it's a duplicate "local VAR" declaration, do nothing
9291 lvp = ckzalloc(sizeof(*lvp));
9292 if (LONE_DASH(name)) {
9294 p = ckmalloc(sizeof(optlist));
9295 lvp->text = memcpy(p, optlist, sizeof(optlist));
9298 vpp = hashvar(name);
9299 vp = *findvar(vpp, name);
9301 /* variable did not exist yet */
9303 setvareq(name, VSTRFIXED);
9305 setvar(name, NULL, VSTRFIXED);
9306 vp = *vpp; /* the new variable */
9307 lvp->flags = VUNSET;
9309 lvp->text = vp->var_text;
9310 lvp->flags = vp->flags;
9311 /* make sure neither "struct var" nor string gets freed
9312 * during (un)setting:
9314 vp->flags |= VSTRFIXED|VTEXTFIXED;
9318 /* "local VAR" unsets VAR: */
9319 setvar0(name, NULL);
9323 lvp->next = localvars;
9330 * The "local" command.
9332 static int FAST_FUNC
9333 localcmd(int argc UNUSED_PARAM, char **argv)
9338 ash_msg_and_raise_error("not in a function");
9341 while ((name = *argv++) != NULL) {
9347 static int FAST_FUNC
9348 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9353 static int FAST_FUNC
9354 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9359 static int FAST_FUNC
9360 execcmd(int argc UNUSED_PARAM, char **argv)
9363 while (nextopt("a:") != '\0')
9364 /* nextopt() sets optionarg to "-a ARGV0" */;
9370 iflag = 0; /* exit on error */
9373 /* We should set up signals for "exec CMD"
9374 * the same way as for "CMD" without "exec".
9375 * But optschanged->setinteractive->setsignal
9376 * still thought we are a root shell. Therefore, for example,
9377 * SIGQUIT is still set to IGN. Fix it:
9381 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9382 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9383 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9387 argv[0] = optionarg;
9388 shellexec(prog, argv, pathval(), 0);
9395 * The return command.
9397 static int FAST_FUNC
9398 returncmd(int argc UNUSED_PARAM, char **argv)
9401 * If called outside a function, do what ksh does;
9402 * skip the rest of the file.
9404 evalskip = SKIPFUNC;
9405 return argv[1] ? number(argv[1]) : exitstatus;
9408 /* Forward declarations for builtintab[] */
9409 static int breakcmd(int, char **) FAST_FUNC;
9410 static int dotcmd(int, char **) FAST_FUNC;
9411 static int evalcmd(int, char **, int) FAST_FUNC;
9412 static int exitcmd(int, char **) FAST_FUNC;
9413 static int exportcmd(int, char **) FAST_FUNC;
9414 #if ENABLE_ASH_GETOPTS
9415 static int getoptscmd(int, char **) FAST_FUNC;
9418 static int helpcmd(int, char **) FAST_FUNC;
9421 static int historycmd(int, char **) FAST_FUNC;
9423 #if ENABLE_FEATURE_SH_MATH
9424 static int letcmd(int, char **) FAST_FUNC;
9426 static int readcmd(int, char **) FAST_FUNC;
9427 static int setcmd(int, char **) FAST_FUNC;
9428 static int shiftcmd(int, char **) FAST_FUNC;
9429 static int timescmd(int, char **) FAST_FUNC;
9430 static int trapcmd(int, char **) FAST_FUNC;
9431 static int umaskcmd(int, char **) FAST_FUNC;
9432 static int unsetcmd(int, char **) FAST_FUNC;
9433 static int ulimitcmd(int, char **) FAST_FUNC;
9435 #define BUILTIN_NOSPEC "0"
9436 #define BUILTIN_SPECIAL "1"
9437 #define BUILTIN_REGULAR "2"
9438 #define BUILTIN_SPEC_REG "3"
9439 #define BUILTIN_ASSIGN "4"
9440 #define BUILTIN_SPEC_ASSG "5"
9441 #define BUILTIN_REG_ASSG "6"
9442 #define BUILTIN_SPEC_REG_ASSG "7"
9444 /* Stubs for calling non-FAST_FUNC's */
9446 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9448 #if ENABLE_ASH_PRINTF
9449 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9451 #if ENABLE_ASH_TEST || BASH_TEST2
9452 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9455 /* Keep these in proper order since it is searched via bsearch() */
9456 static const struct builtincmd builtintab[] = {
9457 { BUILTIN_SPEC_REG "." , dotcmd },
9458 { BUILTIN_SPEC_REG ":" , truecmd },
9460 { BUILTIN_REGULAR "[" , testcmd },
9463 { BUILTIN_REGULAR "[[" , testcmd },
9465 #if ENABLE_ASH_ALIAS
9466 { BUILTIN_REG_ASSG "alias" , aliascmd },
9469 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9471 { BUILTIN_SPEC_REG "break" , breakcmd },
9472 { BUILTIN_REGULAR "cd" , cdcmd },
9473 { BUILTIN_NOSPEC "chdir" , cdcmd },
9474 #if ENABLE_ASH_CMDCMD
9475 { BUILTIN_REGULAR "command" , commandcmd },
9477 { BUILTIN_SPEC_REG "continue", breakcmd },
9479 { BUILTIN_REGULAR "echo" , echocmd },
9481 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9482 { BUILTIN_SPEC_REG "exec" , execcmd },
9483 { BUILTIN_SPEC_REG "exit" , exitcmd },
9484 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9485 { BUILTIN_REGULAR "false" , falsecmd },
9487 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9489 #if ENABLE_ASH_GETOPTS
9490 { BUILTIN_REGULAR "getopts" , getoptscmd },
9492 { BUILTIN_NOSPEC "hash" , hashcmd },
9494 { BUILTIN_NOSPEC "help" , helpcmd },
9497 { BUILTIN_NOSPEC "history" , historycmd },
9500 { BUILTIN_REGULAR "jobs" , jobscmd },
9501 { BUILTIN_REGULAR "kill" , killcmd },
9503 #if ENABLE_FEATURE_SH_MATH
9504 { BUILTIN_NOSPEC "let" , letcmd },
9506 { BUILTIN_ASSIGN "local" , localcmd },
9507 #if ENABLE_ASH_PRINTF
9508 { BUILTIN_REGULAR "printf" , printfcmd },
9510 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9511 { BUILTIN_REGULAR "read" , readcmd },
9512 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9513 { BUILTIN_SPEC_REG "return" , returncmd },
9514 { BUILTIN_SPEC_REG "set" , setcmd },
9515 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9517 { BUILTIN_SPEC_REG "source" , dotcmd },
9520 { BUILTIN_REGULAR "test" , testcmd },
9522 { BUILTIN_SPEC_REG "times" , timescmd },
9523 { BUILTIN_SPEC_REG "trap" , trapcmd },
9524 { BUILTIN_REGULAR "true" , truecmd },
9525 { BUILTIN_NOSPEC "type" , typecmd },
9526 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9527 { BUILTIN_REGULAR "umask" , umaskcmd },
9528 #if ENABLE_ASH_ALIAS
9529 { BUILTIN_REGULAR "unalias" , unaliascmd },
9531 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9532 { BUILTIN_REGULAR "wait" , waitcmd },
9535 /* Should match the above table! */
9536 #define COMMANDCMD (builtintab + \
9538 /* [ */ 1 * ENABLE_ASH_TEST + \
9539 /* [[ */ 1 * BASH_TEST2 + \
9540 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9541 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9542 /* break cd cddir */ 3)
9543 #define EVALCMD (COMMANDCMD + \
9544 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9545 /* continue */ 1 + \
9546 /* echo */ 1 * ENABLE_ASH_ECHO + \
9548 #define EXECCMD (EVALCMD + \
9552 * Search the table of builtin commands.
9555 pstrcmp1(const void *a, const void *b)
9557 return strcmp((char*)a, *(char**)b + 1);
9559 static struct builtincmd *
9560 find_builtin(const char *name)
9562 struct builtincmd *bp;
9565 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9572 * Execute a simple command.
9575 isassignment(const char *p)
9577 const char *q = endofname(p);
9582 static int FAST_FUNC
9583 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9585 /* Preserve exitstatus of a previous possible redirection
9586 * as POSIX mandates */
9587 return back_exitstatus;
9590 evalcommand(union node *cmd, int flags)
9592 static const struct builtincmd null_bltin = {
9593 "\0\0", bltincmd /* why three NULs? */
9595 struct stackmark smark;
9597 struct arglist arglist;
9598 struct arglist varlist;
9601 const struct strlist *sp;
9602 struct cmdentry cmdentry;
9609 struct builtincmd *bcmd;
9610 smallint cmd_is_exec;
9611 smallint pseudovarflag = 0;
9613 /* First expand the arguments. */
9614 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9615 setstackmark(&smark);
9616 back_exitstatus = 0;
9618 cmdentry.cmdtype = CMDBUILTIN;
9619 cmdentry.u.cmd = &null_bltin;
9620 varlist.lastp = &varlist.list;
9621 *varlist.lastp = NULL;
9622 arglist.lastp = &arglist.list;
9623 *arglist.lastp = NULL;
9626 if (cmd->ncmd.args) {
9627 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9628 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9631 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9632 struct strlist **spp;
9634 spp = arglist.lastp;
9635 if (pseudovarflag && isassignment(argp->narg.text))
9636 expandarg(argp, &arglist, EXP_VARTILDE);
9638 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9640 for (sp = *spp; sp; sp = sp->next)
9644 /* Reserve one extra spot at the front for shellexec. */
9645 nargv = stalloc(sizeof(char *) * (argc + 2));
9647 for (sp = arglist.list; sp; sp = sp->next) {
9648 TRACE(("evalcommand arg: %s\n", sp->text));
9649 *nargv++ = sp->text;
9654 if (iflag && funcnest == 0 && argc > 0)
9655 lastarg = nargv[-1];
9658 expredir(cmd->ncmd.redirect);
9659 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9661 path = vpath.var_text;
9662 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9663 struct strlist **spp;
9666 spp = varlist.lastp;
9667 expandarg(argp, &varlist, EXP_VARTILDE);
9670 * Modify the command lookup path, if a PATH= assignment
9674 if (varcmp(p, path) == 0)
9678 /* Print the command if xflag is set. */
9681 const char *p = " %s" + 1;
9683 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9685 for (n = 0; n < 2; n++) {
9687 fdprintf(preverrout_fd, p, sp->text);
9693 safe_write(preverrout_fd, "\n", 1);
9699 /* Now locate the command. */
9701 int cmd_flag = DO_ERR;
9702 #if ENABLE_ASH_CMDCMD
9703 const char *oldpath = path + 5;
9707 find_command(argv[0], &cmdentry, cmd_flag, path);
9708 if (cmdentry.cmdtype == CMDUNKNOWN) {
9709 flush_stdout_stderr();
9714 /* implement bltin and command here */
9715 if (cmdentry.cmdtype != CMDBUILTIN)
9718 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9719 if (cmdentry.u.cmd == EXECCMD)
9721 #if ENABLE_ASH_CMDCMD
9722 if (cmdentry.u.cmd == COMMANDCMD) {
9724 nargv = parse_command_args(argv, &path);
9727 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9728 * nargv => "PROG". path is updated if -p.
9730 argc -= nargv - argv;
9732 cmd_flag |= DO_NOFUNC;
9741 exitstatus = status;
9743 /* We have a redirection error. */
9745 raise_exception(EXERROR);
9750 /* Execute the command. */
9751 switch (cmdentry.cmdtype) {
9754 #if ENABLE_FEATURE_SH_NOFORK
9755 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9756 * around run_nofork_applet() call.
9757 * (2) Should this check also be done in forkshell()?
9758 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9760 /* find_command() encodes applet_no as (-2 - applet_no) */
9761 int applet_no = (- cmdentry.u.index - 2);
9762 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9763 listsetvar(varlist.list, VEXPORT|VSTACK);
9764 /* run <applet>_main() */
9765 status = run_nofork_applet(applet_no, argv);
9769 /* Can we avoid forking off? For example, very last command
9770 * in a script or a subshell does not need forking,
9771 * we can just exec it.
9773 if (!(flags & EV_EXIT) || may_have_traps) {
9774 /* No, forking off a child is necessary */
9777 jp = makejob(/*cmd,*/ 1);
9778 if (forkshell(jp, cmd, FORK_FG) != 0) {
9780 status = waitforjob(jp);
9782 TRACE(("forked child exited with %d\n", status));
9787 /* fall through to exec'ing external program */
9789 listsetvar(varlist.list, VEXPORT|VSTACK);
9790 shellexec(argv[0], argv, path, cmdentry.u.index);
9794 cmdenviron = varlist.list;
9796 struct strlist *list = cmdenviron;
9798 if (spclbltin > 0 || argc == 0) {
9800 if (cmd_is_exec && argc > 1)
9803 listsetvar(list, i);
9805 /* Tight loop with builtins only:
9806 * "while kill -0 $child; do true; done"
9807 * will never exit even if $child died, unless we do this
9808 * to reap the zombie and make kill detect that it's gone: */
9809 dowait(DOWAIT_NONBLOCK, NULL);
9811 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9812 if (exception_type == EXERROR && spclbltin <= 0) {
9817 longjmp(exception_handler->loc, 1);
9822 listsetvar(varlist.list, 0);
9823 /* See above for the rationale */
9824 dowait(DOWAIT_NONBLOCK, NULL);
9825 if (evalfun(cmdentry.u.func, argc, argv, flags))
9828 status = exitstatus;
9833 if (cmd->ncmd.redirect)
9834 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9836 /* dsl: I think this is intended to be used to support
9837 * '_' in 'vi' command mode during line editing...
9838 * However I implemented that within libedit itself.
9840 setvar0("_", lastarg);
9842 popstackmark(&smark);
9848 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9850 char *volatile savecmdname;
9851 struct jmploc *volatile savehandler;
9852 struct jmploc jmploc;
9856 savecmdname = commandname;
9857 savehandler = exception_handler;
9858 i = setjmp(jmploc.loc);
9861 exception_handler = &jmploc;
9862 commandname = argv[0];
9864 optptr = NULL; /* initialize nextopt */
9866 status = evalcmd(argc, argv, flags);
9868 status = (*cmd->builtin)(argc, argv);
9869 flush_stdout_stderr();
9870 status |= ferror(stdout);
9871 exitstatus = status;
9874 commandname = savecmdname;
9875 exception_handler = savehandler;
9881 goodname(const char *p)
9883 return endofname(p)[0] == '\0';
9888 * Search for a command. This is called before we fork so that the
9889 * location of the command will be available in the parent as well as
9890 * the child. The check for "goodname" is an overly conservative
9891 * check that the name will not be subject to expansion.
9894 prehash(union node *n)
9896 struct cmdentry entry;
9898 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9899 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9903 /* ============ Builtin commands
9905 * Builtin commands whose functions are closely tied to evaluation
9906 * are implemented here.
9910 * Handle break and continue commands. Break, continue, and return are
9911 * all handled by setting the evalskip flag. The evaluation routines
9912 * above all check this flag, and if it is set they start skipping
9913 * commands rather than executing them. The variable skipcount is
9914 * the number of loops to break/continue, or the number of function
9915 * levels to return. (The latter is always 1.) It should probably
9916 * be an error to break out of more loops than exist, but it isn't
9917 * in the standard shell so we don't make it one here.
9919 static int FAST_FUNC
9920 breakcmd(int argc UNUSED_PARAM, char **argv)
9922 int n = argv[1] ? number(argv[1]) : 1;
9925 ash_msg_and_raise_error(msg_illnum, argv[1]);
9929 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9937 * This implements the input routines used by the parser.
9941 INPUT_PUSH_FILE = 1,
9942 INPUT_NOFILE_OK = 2,
9945 static smallint checkkwd;
9946 /* values of checkkwd variable */
9947 #define CHKALIAS 0x1
9952 * Push a string back onto the input at this current parsefile level.
9953 * We handle aliases this way.
9955 #if !ENABLE_ASH_ALIAS
9956 #define pushstring(s, ap) pushstring(s)
9959 pushstring(char *s, struct alias *ap)
9966 if (g_parsefile->strpush) {
9967 sp = ckzalloc(sizeof(*sp));
9968 sp->prev = g_parsefile->strpush;
9970 sp = &(g_parsefile->basestrpush);
9972 g_parsefile->strpush = sp;
9973 sp->prev_string = g_parsefile->next_to_pgetc;
9974 sp->prev_left_in_line = g_parsefile->left_in_line;
9975 sp->unget = g_parsefile->unget;
9976 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9977 #if ENABLE_ASH_ALIAS
9980 ap->flag |= ALIASINUSE;
9984 g_parsefile->next_to_pgetc = s;
9985 g_parsefile->left_in_line = len;
9986 g_parsefile->unget = 0;
9993 struct strpush *sp = g_parsefile->strpush;
9996 #if ENABLE_ASH_ALIAS
9998 if (g_parsefile->next_to_pgetc[-1] == ' '
9999 || g_parsefile->next_to_pgetc[-1] == '\t'
10001 checkkwd |= CHKALIAS;
10003 if (sp->string != sp->ap->val) {
10006 sp->ap->flag &= ~ALIASINUSE;
10007 if (sp->ap->flag & ALIASDEAD) {
10008 unalias(sp->ap->name);
10012 g_parsefile->next_to_pgetc = sp->prev_string;
10013 g_parsefile->left_in_line = sp->prev_left_in_line;
10014 g_parsefile->unget = sp->unget;
10015 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
10016 g_parsefile->strpush = sp->prev;
10017 if (sp != &(g_parsefile->basestrpush))
10026 char *buf = g_parsefile->buf;
10028 g_parsefile->next_to_pgetc = buf;
10029 #if ENABLE_FEATURE_EDITING
10031 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
10032 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10035 # if ENABLE_ASH_IDLE_TIMEOUT
10037 const char *tmout_var = lookupvar("TMOUT");
10039 timeout = atoi(tmout_var) * 1000;
10045 # if ENABLE_FEATURE_TAB_COMPLETION
10046 line_input_state->path_lookup = pathval();
10048 reinit_unicode_for_ash();
10049 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
10051 /* ^C pressed, "convert" to SIGINT */
10052 write(STDOUT_FILENO, "^C", 2);
10053 if (trap[SIGINT]) {
10059 exitstatus = 128 + SIGINT;
10065 /* Ctrl+D pressed */
10068 # if ENABLE_ASH_IDLE_TIMEOUT
10069 else if (errno == EAGAIN && timeout > 0) {
10070 puts("\007timed out waiting for input: auto-logout");
10077 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10080 #if 0 /* disabled: nonblock_immune_read() handles this problem */
10082 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
10083 int flags = fcntl(0, F_GETFL);
10084 if (flags >= 0 && (flags & O_NONBLOCK)) {
10085 flags &= ~O_NONBLOCK;
10086 if (fcntl(0, F_SETFL, flags) >= 0) {
10087 out2str("sh: turning off NDELAY mode\n");
10098 * Refill the input buffer and return the next input character:
10100 * 1) If a string was pushed back on the input, pop it;
10101 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
10102 * or we are reading from a string so we can't refill the buffer,
10104 * 3) If there is more stuff in this buffer, use it else call read to fill it.
10105 * 4) Process input up to the next newline, deleting nul characters.
10107 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
10108 #define pgetc_debug(...) ((void)0)
10109 static int pgetc(void);
10116 if (g_parsefile->strpush) {
10117 #if ENABLE_ASH_ALIAS
10118 if (g_parsefile->left_in_line == -1
10119 && g_parsefile->strpush->ap
10120 && g_parsefile->next_to_pgetc[-1] != ' '
10121 && g_parsefile->next_to_pgetc[-1] != '\t'
10123 pgetc_debug("preadbuffer PEOA");
10130 /* on both branches above g_parsefile->left_in_line < 0.
10131 * "pgetc" needs refilling.
10134 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
10135 * pungetc() may increment it a few times.
10136 * Assuming it won't increment it to less than -90.
10138 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
10139 pgetc_debug("preadbuffer PEOF1");
10140 /* even in failure keep left_in_line and next_to_pgetc
10141 * in lock step, for correct multi-layer pungetc.
10142 * left_in_line was decremented before preadbuffer(),
10143 * must inc next_to_pgetc: */
10144 g_parsefile->next_to_pgetc++;
10148 more = g_parsefile->left_in_buffer;
10150 flush_stdout_stderr();
10154 /* don't try reading again */
10155 g_parsefile->left_in_line = -99;
10156 pgetc_debug("preadbuffer PEOF2");
10157 g_parsefile->next_to_pgetc++;
10162 /* Find out where's the end of line.
10163 * Set g_parsefile->left_in_line
10164 * and g_parsefile->left_in_buffer acordingly.
10165 * NUL chars are deleted.
10167 q = g_parsefile->next_to_pgetc;
10175 memmove(q, q + 1, more);
10179 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10185 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10186 if (g_parsefile->left_in_line < 0)
10191 g_parsefile->left_in_buffer = more;
10196 out2str(g_parsefile->next_to_pgetc);
10200 pgetc_debug("preadbuffer at %d:%p'%s'",
10201 g_parsefile->left_in_line,
10202 g_parsefile->next_to_pgetc,
10203 g_parsefile->next_to_pgetc);
10204 return (unsigned char)*g_parsefile->next_to_pgetc++;
10210 g_parsefile->linno++;
10211 setprompt_if(doprompt, 2);
10216 g_parsefile->linno++;
10217 needprompt = doprompt;
10225 pgetc_debug("pgetc at %d:%p'%s'",
10226 g_parsefile->left_in_line,
10227 g_parsefile->next_to_pgetc,
10228 g_parsefile->next_to_pgetc);
10229 if (g_parsefile->unget)
10230 return g_parsefile->lastc[--g_parsefile->unget];
10232 if (--g_parsefile->left_in_line >= 0)
10233 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10237 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10238 g_parsefile->lastc[0] = c;
10243 #if ENABLE_ASH_ALIAS
10245 pgetc_without_PEOA(void)
10249 pgetc_debug("pgetc at %d:%p'%s'",
10250 g_parsefile->left_in_line,
10251 g_parsefile->next_to_pgetc,
10252 g_parsefile->next_to_pgetc);
10254 } while (c == PEOA);
10258 # define pgetc_without_PEOA() pgetc()
10262 * Read a line from the script.
10265 pfgets(char *line, int len)
10271 while (--nleft > 0) {
10272 c = pgetc_without_PEOA();
10287 * Undo a call to pgetc. Only two characters may be pushed back.
10288 * PEOF may be pushed back.
10293 g_parsefile->unget++;
10296 /* This one eats backslash+newline */
10302 while ((c = pgetc()) == '\\') {
10303 if (pgetc() != '\n') {
10315 * To handle the "." command, a stack of input files is used. Pushfile
10316 * adds a new entry to the stack and popfile restores the previous level.
10321 struct parsefile *pf;
10323 pf = ckzalloc(sizeof(*pf));
10324 pf->prev = g_parsefile;
10326 /*pf->strpush = NULL; - ckzalloc did it */
10327 /*pf->basestrpush.prev = NULL;*/
10335 struct parsefile *pf = g_parsefile;
10341 if (pf->pf_fd >= 0)
10344 while (pf->strpush)
10346 g_parsefile = pf->prev;
10352 * Return to top level.
10357 while (g_parsefile != &basepf)
10362 * Close the file(s) that the shell is reading commands from. Called
10363 * after a fork is done.
10369 if (g_parsefile->pf_fd > 0) {
10370 close(g_parsefile->pf_fd);
10371 g_parsefile->pf_fd = 0;
10376 * Like setinputfile, but takes an open file descriptor. Call this with
10380 setinputfd(int fd, int push)
10384 g_parsefile->buf = NULL;
10386 g_parsefile->pf_fd = fd;
10387 if (g_parsefile->buf == NULL)
10388 g_parsefile->buf = ckmalloc(IBUFSIZ);
10389 g_parsefile->left_in_buffer = 0;
10390 g_parsefile->left_in_line = 0;
10391 g_parsefile->linno = 1;
10395 * Set the input to take input from a file. If push is set, push the
10396 * old input onto the stack first.
10399 setinputfile(const char *fname, int flags)
10404 fd = open(fname, O_RDONLY);
10406 if (flags & INPUT_NOFILE_OK)
10409 ash_msg_and_raise_error("can't open '%s'", fname);
10414 close_on_exec_on(fd);
10415 setinputfd(fd, flags & INPUT_PUSH_FILE);
10422 * Like setinputfile, but takes input from a string.
10425 setinputstring(char *string)
10429 g_parsefile->next_to_pgetc = string;
10430 g_parsefile->left_in_line = strlen(string);
10431 g_parsefile->buf = NULL;
10432 g_parsefile->linno = 1;
10438 * Routines to check for mail.
10441 #if ENABLE_ASH_MAIL
10443 /* Hash of mtimes of mailboxes */
10444 static unsigned mailtime_hash;
10445 /* Set if MAIL or MAILPATH is changed. */
10446 static smallint mail_var_path_changed;
10449 * Print appropriate message(s) if mail has arrived.
10450 * If mail_var_path_changed is set,
10451 * then the value of MAIL has mail_var_path_changed,
10452 * so we just update the values.
10461 struct stackmark smark;
10464 setstackmark(&smark);
10465 mpath = mpathset() ? mpathval() : mailval();
10468 p = path_advance(&mpath, nullstr);
10473 for (q = p; *q; q++)
10479 q[-1] = '\0'; /* delete trailing '/' */
10480 if (stat(p, &statb) < 0) {
10483 /* Very simplistic "hash": just a sum of all mtimes */
10484 new_hash += (unsigned)statb.st_mtime;
10486 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10487 if (mailtime_hash != 0)
10488 out2str("you have mail\n");
10489 mailtime_hash = new_hash;
10491 mail_var_path_changed = 0;
10492 popstackmark(&smark);
10495 static void FAST_FUNC
10496 changemail(const char *val UNUSED_PARAM)
10498 mail_var_path_changed = 1;
10501 #endif /* ASH_MAIL */
10504 /* ============ ??? */
10507 * Set the shell parameters.
10510 setparam(char **argv)
10516 for (nparam = 0; argv[nparam]; nparam++)
10518 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10520 *ap++ = ckstrdup(*argv++);
10523 freeparam(&shellparam);
10524 shellparam.malloced = 1;
10525 shellparam.nparam = nparam;
10526 shellparam.p = newparam;
10527 #if ENABLE_ASH_GETOPTS
10528 shellparam.optind = 1;
10529 shellparam.optoff = -1;
10534 * Process shell options. The global variable argptr contains a pointer
10535 * to the argument list; we advance it past the options.
10537 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10538 * For a non-interactive shell, an error condition encountered
10539 * by a special built-in ... shall cause the shell to write a diagnostic message
10540 * to standard error and exit as shown in the following table:
10541 * Error Special Built-In
10543 * Utility syntax error (option or operand error) Shall exit
10545 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10546 * we see that bash does not do that (set "finishes" with error code 1 instead,
10547 * and shell continues), and people rely on this behavior!
10549 * set -o barfoo 2>/dev/null
10552 * Oh well. Let's mimic that.
10555 plus_minus_o(char *name, int val)
10560 for (i = 0; i < NOPTS; i++) {
10561 if (strcmp(name, optnames(i)) == 0) {
10566 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10569 for (i = 0; i < NOPTS; i++) {
10571 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10573 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10579 setoption(int flag, int val)
10583 for (i = 0; i < NOPTS; i++) {
10584 if (optletters(i) == flag) {
10589 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10593 options(int cmdline)
10601 while ((p = *argptr) != NULL) {
10603 if (c != '-' && c != '+')
10606 val = 0; /* val = 0 if c == '+' */
10609 if (p[0] == '\0' || LONE_DASH(p)) {
10611 /* "-" means turn off -x and -v */
10614 /* "--" means reset params */
10615 else if (*argptr == NULL)
10618 break; /* "-" or "--" terminates options */
10621 /* first char was + or - */
10622 while ((c = *p++) != '\0') {
10623 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10624 if (c == 'c' && cmdline) {
10625 minusc = p; /* command is after shell args */
10626 } else if (c == 'o') {
10627 if (plus_minus_o(*argptr, val)) {
10628 /* it already printed err message */
10629 return 1; /* error */
10633 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10635 /* bash does not accept +-login, we also won't */
10636 } else if (cmdline && val && (c == '-')) { /* long options */
10637 if (strcmp(p, "login") == 0)
10649 * The shift builtin command.
10651 static int FAST_FUNC
10652 shiftcmd(int argc UNUSED_PARAM, char **argv)
10659 n = number(argv[1]);
10660 if (n > shellparam.nparam)
10661 n = 0; /* bash compat, was = shellparam.nparam; */
10663 shellparam.nparam -= n;
10664 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10665 if (shellparam.malloced)
10668 ap2 = shellparam.p;
10669 while ((*ap2++ = *ap1++) != NULL)
10671 #if ENABLE_ASH_GETOPTS
10672 shellparam.optind = 1;
10673 shellparam.optoff = -1;
10680 * POSIX requires that 'set' (but not export or readonly) output the
10681 * variables in lexicographic order - by the locale's collating order (sigh).
10682 * Maybe we could keep them in an ordered balanced binary tree
10683 * instead of hashed lists.
10684 * For now just roll 'em through qsort for printing...
10687 showvars(const char *sep_prefix, int on, int off)
10690 char **ep, **epend;
10692 ep = listvars(on, off, &epend);
10693 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10695 sep = *sep_prefix ? " " : sep_prefix;
10697 for (; ep < epend; ep++) {
10701 p = strchrnul(*ep, '=');
10704 q = single_quote(++p);
10705 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10711 * The set command builtin.
10713 static int FAST_FUNC
10714 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10719 return showvars(nullstr, 0, VUNSET);
10722 retval = options(/*cmdline:*/ 0);
10723 if (retval == 0) { /* if no parse error... */
10725 if (*argptr != NULL) {
10733 #if ENABLE_ASH_RANDOM_SUPPORT
10734 static void FAST_FUNC
10735 change_random(const char *value)
10739 if (value == NULL) {
10740 /* "get", generate */
10741 t = next_random(&random_gen);
10742 /* set without recursion */
10743 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10744 vrandom.flags &= ~VNOFUNC;
10747 t = strtoul(value, NULL, 10);
10748 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10753 #if ENABLE_ASH_GETOPTS
10755 getopts(char *optstr, char *optvar, char **optfirst)
10762 int ind = shellparam.optind;
10763 int off = shellparam.optoff;
10767 shellparam.optind = -1;
10768 optnext = optfirst + ind - 1;
10770 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10773 p = optnext[-1] + off;
10774 if (p == NULL || *p == '\0') {
10775 /* Current word is done, advance */
10777 if (p == NULL || *p != '-' || *++p == '\0') {
10784 if (LONE_DASH(p)) /* check for "--" */
10789 for (q = optstr; *q != c;) {
10791 if (optstr[0] == ':') {
10793 /*sbuf[1] = '\0'; - already is */
10794 setvar0("OPTARG", sbuf);
10796 fprintf(stderr, "Illegal option -%c\n", c);
10797 unsetvar("OPTARG");
10807 if (*p == '\0' && (p = *optnext) == NULL) {
10808 if (optstr[0] == ':') {
10810 /*sbuf[1] = '\0'; - already is */
10811 setvar0("OPTARG", sbuf);
10814 fprintf(stderr, "No arg for -%c option\n", c);
10815 unsetvar("OPTARG");
10823 setvar0("OPTARG", p);
10826 setvar0("OPTARG", nullstr);
10828 ind = optnext - optfirst + 1;
10829 setvar("OPTIND", itoa(ind), VNOFUNC);
10831 /*sbuf[1] = '\0'; - already is */
10832 setvar0(optvar, sbuf);
10834 shellparam.optoff = p ? p - *(optnext - 1) : -1;
10835 shellparam.optind = ind;
10841 * The getopts builtin. Shellparam.optnext points to the next argument
10842 * to be processed. Shellparam.optptr points to the next character to
10843 * be processed in the current argument. If shellparam.optnext is NULL,
10844 * then it's the first time getopts has been called.
10846 static int FAST_FUNC
10847 getoptscmd(int argc, char **argv)
10852 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10854 optbase = shellparam.p;
10855 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
10856 shellparam.optind = 1;
10857 shellparam.optoff = -1;
10860 optbase = &argv[3];
10861 if ((unsigned)shellparam.optind > argc - 2) {
10862 shellparam.optind = 1;
10863 shellparam.optoff = -1;
10867 return getopts(argv[1], argv[2], optbase);
10869 #endif /* ASH_GETOPTS */
10872 /* ============ Shell parser */
10875 struct heredoc *next; /* next here document in list */
10876 union node *here; /* redirection node */
10877 char *eofmark; /* string indicating end of input */
10878 smallint striptabs; /* if set, strip leading tabs */
10881 static smallint tokpushback; /* last token pushed back */
10882 static smallint quoteflag; /* set if (part of) last token was quoted */
10883 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10884 static struct heredoc *heredoclist; /* list of here documents to read */
10885 static char *wordtext; /* text of last word returned by readtoken */
10886 static struct nodelist *backquotelist;
10887 static union node *redirnode;
10888 static struct heredoc *heredoc;
10890 static const char *
10891 tokname(char *buf, int tok)
10894 return tokname_array[tok];
10895 sprintf(buf, "\"%s\"", tokname_array[tok]);
10899 /* raise_error_unexpected_syntax:
10900 * Called when an unexpected token is read during the parse. The argument
10901 * is the token that is expected, or -1 if more than one type of token can
10902 * occur at this point.
10904 static void raise_error_unexpected_syntax(int) NORETURN;
10906 raise_error_unexpected_syntax(int token)
10912 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10914 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10915 raise_error_syntax(msg);
10919 #define EOFMARKLEN 79
10921 /* parsing is heavily cross-recursive, need these forward decls */
10922 static union node *andor(void);
10923 static union node *pipeline(void);
10924 static union node *parse_command(void);
10925 static void parseheredoc(void);
10926 static int peektoken(void);
10927 static int readtoken(void);
10929 static union node *
10932 union node *n1, *n2, *n3;
10937 switch (peektoken()) {
10945 if (!n1 && (nlflag & 1))
10951 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10952 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
10958 if (tok == TBACKGND) {
10959 if (n2->type == NPIPE) {
10960 n2->npipe.pipe_backgnd = 1;
10962 if (n2->type != NREDIR) {
10963 n3 = stzalloc(sizeof(struct nredir));
10965 /*n3->nredir.redirect = NULL; - stzalloc did it */
10968 n2->type = NBACKGND;
10974 n3 = stzalloc(sizeof(struct nbinary));
10976 n3->nbinary.ch1 = n1;
10977 n3->nbinary.ch2 = n2;
10990 raise_error_unexpected_syntax(-1);
10997 static union node *
11000 union node *n1, *n2, *n3;
11008 } else if (t == TOR) {
11014 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11016 n3 = stzalloc(sizeof(struct nbinary));
11018 n3->nbinary.ch1 = n1;
11019 n3->nbinary.ch2 = n2;
11024 static union node *
11027 union node *n1, *n2, *pipenode;
11028 struct nodelist *lp, *prev;
11032 TRACE(("pipeline: entered\n"));
11033 if (readtoken() == TNOT) {
11035 checkkwd = CHKKWD | CHKALIAS;
11038 n1 = parse_command();
11039 if (readtoken() == TPIPE) {
11040 pipenode = stzalloc(sizeof(struct npipe));
11041 pipenode->type = NPIPE;
11042 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
11043 lp = stzalloc(sizeof(struct nodelist));
11044 pipenode->npipe.cmdlist = lp;
11048 lp = stzalloc(sizeof(struct nodelist));
11049 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11050 lp->n = parse_command();
11052 } while (readtoken() == TPIPE);
11058 n2 = stzalloc(sizeof(struct nnot));
11066 static union node *
11071 n = stzalloc(sizeof(struct narg));
11073 /*n->narg.next = NULL; - stzalloc did it */
11074 n->narg.text = wordtext;
11075 n->narg.backquote = backquotelist;
11080 fixredir(union node *n, const char *text, int err)
11084 TRACE(("Fix redir %s %d\n", text, err));
11086 n->ndup.vname = NULL;
11088 fd = bb_strtou(text, NULL, 10);
11089 if (!errno && fd >= 0)
11090 n->ndup.dupfd = fd;
11091 else if (LONE_DASH(text))
11092 n->ndup.dupfd = -1;
11095 raise_error_syntax("bad fd number");
11096 n->ndup.vname = makename();
11101 * Returns true if the text contains nothing to expand (no dollar signs
11105 noexpand(const char *text)
11109 while ((c = *text++) != '\0') {
11110 if (c == CTLQUOTEMARK)
11114 else if (SIT(c, BASESYNTAX) == CCTL)
11123 union node *n = redirnode;
11125 if (readtoken() != TWORD)
11126 raise_error_unexpected_syntax(-1);
11127 if (n->type == NHERE) {
11128 struct heredoc *here = heredoc;
11132 if (quoteflag == 0)
11134 TRACE(("Here document %d\n", n->type));
11135 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
11136 raise_error_syntax("illegal eof marker for << redirection");
11137 rmescapes(wordtext, 0);
11138 here->eofmark = wordtext;
11140 if (heredoclist == NULL)
11141 heredoclist = here;
11143 for (p = heredoclist; p->next; p = p->next)
11147 } else if (n->type == NTOFD || n->type == NFROMFD) {
11148 fixredir(n, wordtext, 0);
11150 n->nfile.fname = makename();
11154 static union node *
11157 union node *args, **app;
11158 union node *n = NULL;
11159 union node *vars, **vpp;
11160 union node **rpp, *redir;
11163 smallint double_brackets_flag = 0;
11165 IF_BASH_FUNCTION(smallint function_flag = 0;)
11174 savecheckkwd = CHKALIAS;
11177 checkkwd = savecheckkwd;
11182 if (peektoken() != TWORD)
11183 raise_error_unexpected_syntax(TWORD);
11188 case TAND: /* "&&" */
11189 case TOR: /* "||" */
11190 if (!double_brackets_flag) {
11194 wordtext = (char *) (t == TAND ? "-a" : "-o");
11197 n = stzalloc(sizeof(struct narg));
11199 /*n->narg.next = NULL; - stzalloc did it */
11200 n->narg.text = wordtext;
11202 if (strcmp("[[", wordtext) == 0)
11203 double_brackets_flag = 1;
11204 else if (strcmp("]]", wordtext) == 0)
11205 double_brackets_flag = 0;
11207 n->narg.backquote = backquotelist;
11208 if (savecheckkwd && isassignment(wordtext)) {
11210 vpp = &n->narg.next;
11213 app = &n->narg.next;
11217 if (function_flag) {
11218 checkkwd = CHKNL | CHKKWD;
11219 switch (peektoken()) {
11231 if (strcmp("[[", wordtext) == 0)
11235 raise_error_unexpected_syntax(-1);
11241 *rpp = n = redirnode;
11242 rpp = &n->nfile.next;
11243 parsefname(); /* read name of redirection file */
11246 IF_BASH_FUNCTION(do_func:)
11247 if (args && app == &args->narg.next
11250 struct builtincmd *bcmd;
11253 /* We have a function */
11254 if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
11255 raise_error_unexpected_syntax(TRP);
11256 name = n->narg.text;
11257 if (!goodname(name)
11258 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11260 raise_error_syntax("bad function name");
11263 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11264 n->narg.next = parse_command();
11267 IF_BASH_FUNCTION(function_flag = 0;)
11278 n = stzalloc(sizeof(struct ncmd));
11280 n->ncmd.args = args;
11281 n->ncmd.assign = vars;
11282 n->ncmd.redirect = redir;
11286 static union node *
11287 parse_command(void)
11289 union node *n1, *n2;
11290 union node *ap, **app;
11291 union node *cp, **cpp;
11292 union node *redir, **rpp;
11299 switch (readtoken()) {
11301 raise_error_unexpected_syntax(-1);
11304 n1 = stzalloc(sizeof(struct nif));
11306 n1->nif.test = list(0);
11307 if (readtoken() != TTHEN)
11308 raise_error_unexpected_syntax(TTHEN);
11309 n1->nif.ifpart = list(0);
11311 while (readtoken() == TELIF) {
11312 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11313 n2 = n2->nif.elsepart;
11315 n2->nif.test = list(0);
11316 if (readtoken() != TTHEN)
11317 raise_error_unexpected_syntax(TTHEN);
11318 n2->nif.ifpart = list(0);
11320 if (lasttoken == TELSE)
11321 n2->nif.elsepart = list(0);
11323 n2->nif.elsepart = NULL;
11331 n1 = stzalloc(sizeof(struct nbinary));
11332 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11333 n1->nbinary.ch1 = list(0);
11336 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11337 got == TWORD ? wordtext : ""));
11338 raise_error_unexpected_syntax(TDO);
11340 n1->nbinary.ch2 = list(0);
11345 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11346 raise_error_syntax("bad for loop variable");
11347 n1 = stzalloc(sizeof(struct nfor));
11349 n1->nfor.var = wordtext;
11350 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11351 if (readtoken() == TIN) {
11353 while (readtoken() == TWORD) {
11354 n2 = stzalloc(sizeof(struct narg));
11356 /*n2->narg.next = NULL; - stzalloc did it */
11357 n2->narg.text = wordtext;
11358 n2->narg.backquote = backquotelist;
11360 app = &n2->narg.next;
11363 n1->nfor.args = ap;
11364 if (lasttoken != TNL && lasttoken != TSEMI)
11365 raise_error_unexpected_syntax(-1);
11367 n2 = stzalloc(sizeof(struct narg));
11369 /*n2->narg.next = NULL; - stzalloc did it */
11370 n2->narg.text = (char *)dolatstr;
11371 /*n2->narg.backquote = NULL;*/
11372 n1->nfor.args = n2;
11374 * Newline or semicolon here is optional (but note
11375 * that the original Bourne shell only allowed NL).
11377 if (lasttoken != TSEMI)
11380 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11381 if (readtoken() != TDO)
11382 raise_error_unexpected_syntax(TDO);
11383 n1->nfor.body = list(0);
11387 n1 = stzalloc(sizeof(struct ncase));
11389 if (readtoken() != TWORD)
11390 raise_error_unexpected_syntax(TWORD);
11391 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11393 /*n2->narg.next = NULL; - stzalloc did it */
11394 n2->narg.text = wordtext;
11395 n2->narg.backquote = backquotelist;
11396 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11397 if (readtoken() != TIN)
11398 raise_error_unexpected_syntax(TIN);
11399 cpp = &n1->ncase.cases;
11401 checkkwd = CHKNL | CHKKWD;
11403 while (t != TESAC) {
11404 if (lasttoken == TLP)
11406 *cpp = cp = stzalloc(sizeof(struct nclist));
11408 app = &cp->nclist.pattern;
11410 *app = ap = stzalloc(sizeof(struct narg));
11412 /*ap->narg.next = NULL; - stzalloc did it */
11413 ap->narg.text = wordtext;
11414 ap->narg.backquote = backquotelist;
11415 if (readtoken() != TPIPE)
11417 app = &ap->narg.next;
11420 //ap->narg.next = NULL;
11421 if (lasttoken != TRP)
11422 raise_error_unexpected_syntax(TRP);
11423 cp->nclist.body = list(2);
11425 cpp = &cp->nclist.next;
11427 checkkwd = CHKNL | CHKKWD;
11431 raise_error_unexpected_syntax(TENDCASE);
11438 n1 = stzalloc(sizeof(struct nredir));
11439 n1->type = NSUBSHELL;
11440 n1->nredir.n = list(0);
11441 /*n1->nredir.redirect = NULL; - stzalloc did it */
11448 IF_BASH_FUNCTION(case TFUNCTION:)
11452 return simplecmd();
11455 if (readtoken() != t)
11456 raise_error_unexpected_syntax(t);
11459 /* Now check for redirection which may follow command */
11460 checkkwd = CHKKWD | CHKALIAS;
11462 while (readtoken() == TREDIR) {
11463 *rpp = n2 = redirnode;
11464 rpp = &n2->nfile.next;
11470 if (n1->type != NSUBSHELL) {
11471 n2 = stzalloc(sizeof(struct nredir));
11476 n1->nredir.redirect = redir;
11481 #if BASH_DOLLAR_SQUOTE
11483 decode_dollar_squote(void)
11485 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11491 p = strchr(C_escapes, c);
11496 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11500 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11502 } else if (c == 'x') { /* \xHH */
11506 } while (isxdigit(c) && --cnt);
11508 if (cnt == 3) { /* \x but next char is "bad" */
11512 } else { /* simple seq like \\ or \t */
11517 c = bb_process_escape_sequence((void*)&p);
11518 } else { /* unrecognized "\z": print both chars unless ' or " */
11519 if (c != '\'' && c != '"') {
11521 c |= 0x100; /* "please encode \, then me" */
11529 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11530 * is not NULL, read a here document. In the latter case, eofmark is the
11531 * word which marks the end of the document and striptabs is true if
11532 * leading tabs should be stripped from the document. The argument c
11533 * is the first character of the input token or document.
11535 * Because C does not have internal subroutines, I have simulated them
11536 * using goto's to implement the subroutine linkage. The following macros
11537 * will run code that appears at the end of readtoken1.
11539 #define CHECKEND() {goto checkend; checkend_return:;}
11540 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11541 #define PARSESUB() {goto parsesub; parsesub_return:;}
11542 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11543 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11544 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11546 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11548 /* NB: syntax parameter fits into smallint */
11549 /* c parameter is an unsigned char or PEOF or PEOA */
11552 char line[EOFMARKLEN + 1];
11553 struct nodelist *bqlist;
11557 IF_FEATURE_SH_MATH(smallint prevsyntax;) /* syntax before arithmetic */
11558 smallint pssyntax; /* we are expanding a prompt string */
11559 int varnest; /* levels of variables expansion */
11560 IF_FEATURE_SH_MATH(int arinest;) /* levels of arithmetic expansion */
11561 IF_FEATURE_SH_MATH(int parenlevel;) /* levels of parens in arithmetic */
11562 int dqvarnest; /* levels of variables expansion within double quotes */
11564 IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
11566 startlinno = g_parsefile->linno;
11569 IF_FEATURE_SH_MATH(prevsyntax = 0;)
11570 pssyntax = (syntax == PSSYNTAX);
11573 dblquote = (syntax == DQSYNTAX);
11575 IF_FEATURE_SH_MATH(arinest = 0;)
11576 IF_FEATURE_SH_MATH(parenlevel = 0;)
11579 STARTSTACKSTR(out);
11581 /* For each line, until end of word */
11582 CHECKEND(); /* set c to PEOF if at end of here document */
11583 for (;;) { /* until end of line or end of word */
11584 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11585 switch (SIT(c, syntax)) {
11586 case CNL: /* '\n' */
11587 if (syntax == BASESYNTAX)
11588 goto endword; /* exit outer loop */
11592 goto loop; /* continue outer loop */
11597 #if BASH_DOLLAR_SQUOTE
11598 if (c == '\\' && bash_dollar_squote) {
11599 c = decode_dollar_squote();
11601 /* skip $'\000', $'\x00' (like bash) */
11605 /* Unknown escape. Encode as '\z' */
11606 c = (unsigned char)c;
11607 if (eofmark == NULL || dblquote)
11608 USTPUTC(CTLESC, out);
11609 USTPUTC('\\', out);
11613 if (eofmark == NULL || dblquote)
11614 USTPUTC(CTLESC, out);
11617 case CBACK: /* backslash */
11618 c = pgetc_without_PEOA();
11620 USTPUTC(CTLESC, out);
11621 USTPUTC('\\', out);
11623 } else if (c == '\n') {
11626 if (c == '$' && pssyntax) {
11627 USTPUTC(CTLESC, out);
11628 USTPUTC('\\', out);
11630 /* Backslash is retained if we are in "str" and next char isn't special */
11635 && (c != '"' || eofmark != NULL)
11637 USTPUTC('\\', out);
11639 USTPUTC(CTLESC, out);
11647 if (eofmark == NULL) {
11648 USTPUTC(CTLQUOTEMARK, out);
11656 IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
11657 if (eofmark != NULL && varnest == 0) {
11660 if (dqvarnest == 0) {
11661 syntax = BASESYNTAX;
11668 case CVAR: /* '$' */
11669 PARSESUB(); /* parse substitution */
11671 case CENDVAR: /* '}' */
11674 if (dqvarnest > 0) {
11681 #if ENABLE_FEATURE_SH_MATH
11682 case CLP: /* '(' in arithmetic */
11686 case CRP: /* ')' in arithmetic */
11687 if (parenlevel > 0) {
11690 if (pgetc_eatbnl() == ')') {
11692 if (--arinest == 0) {
11693 syntax = prevsyntax;
11697 * unbalanced parens
11698 * (don't 2nd guess - no error)
11706 case CBQUOTE: /* '`' */
11710 goto endword; /* exit outer loop */
11714 if (varnest == 0) {
11715 #if BASH_REDIR_OUTPUT
11717 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11718 if (pgetc() == '>')
11719 c = 0x100 + '>'; /* flag &> */
11723 goto endword; /* exit outer loop */
11725 IF_ASH_ALIAS(if (c != PEOA))
11732 #if ENABLE_FEATURE_SH_MATH
11733 if (syntax == ARISYNTAX)
11734 raise_error_syntax("missing '))'");
11736 if (syntax != BASESYNTAX && eofmark == NULL)
11737 raise_error_syntax("unterminated quoted string");
11738 if (varnest != 0) {
11739 startlinno = g_parsefile->linno;
11741 raise_error_syntax("missing '}'");
11743 USTPUTC('\0', out);
11744 len = out - (char *)stackblock();
11745 out = stackblock();
11746 if (eofmark == NULL) {
11747 if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
11750 if (isdigit_str9(out)) {
11751 PARSEREDIR(); /* passed as params: out, c */
11752 lasttoken = TREDIR;
11755 /* else: non-number X seen, interpret it
11756 * as "NNNX>file" = "NNNX >file" */
11760 quoteflag = quotef;
11761 backquotelist = bqlist;
11762 grabstackblock(len);
11766 /* end of readtoken routine */
11769 * Check to see whether we are at the end of the here document. When this
11770 * is called, c is set to the first character of the next input line. If
11771 * we are at the end of the here document, this routine sets the c to PEOF.
11775 #if ENABLE_ASH_ALIAS
11777 c = pgetc_without_PEOA();
11780 while (c == '\t') {
11781 c = pgetc_without_PEOA();
11784 if (c == *eofmark) {
11785 if (pfgets(line, sizeof(line)) != NULL) {
11790 for (q = eofmark + 1;; p++, q++) {
11794 if (!*q || cc != *q)
11801 pushstring(line, NULL);
11806 goto checkend_return;
11810 * Parse a redirection operator. The variable "out" points to a string
11811 * specifying the fd to be redirected. The variable "c" contains the
11812 * first character of the redirection operator.
11815 /* out is already checked to be a valid number or "" */
11816 int fd = (*out == '\0' ? -1 : atoi(out));
11819 np = stzalloc(sizeof(struct nfile));
11824 np->type = NAPPEND;
11826 np->type = NCLOBBER;
11829 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11835 #if BASH_REDIR_OUTPUT
11836 else if (c == 0x100 + '>') { /* this flags &> redirection */
11838 pgetc(); /* this is '>', no need to check */
11842 else { /* c == '<' */
11843 /*np->nfile.fd = 0; - stzalloc did it */
11847 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11848 np = stzalloc(sizeof(struct nhere));
11849 /*np->nfile.fd = 0; - stzalloc did it */
11852 heredoc = stzalloc(sizeof(struct heredoc));
11853 heredoc->here = np;
11856 heredoc->striptabs = 1;
11858 /*heredoc->striptabs = 0; - stzalloc did it */
11864 np->type = NFROMFD;
11868 np->type = NFROMTO;
11880 goto parseredir_return;
11884 * Parse a substitution. At this point, we have read the dollar sign
11885 * and nothing else.
11888 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11889 * (assuming ascii char codes, as the original implementation did) */
11890 #define is_special(c) \
11891 (((unsigned)(c) - 33 < 32) \
11892 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11894 unsigned char subtype;
11897 c = pgetc_eatbnl();
11898 if (c > 255 /* PEOA or PEOF */
11899 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11901 #if BASH_DOLLAR_SQUOTE
11902 if (syntax != DQSYNTAX && c == '\'')
11903 bash_dollar_squote = 1;
11908 } else if (c == '(') {
11909 /* $(command) or $((arith)) */
11910 if (pgetc_eatbnl() == '(') {
11911 #if ENABLE_FEATURE_SH_MATH
11914 raise_error_syntax("you disabled math support for $((arith)) syntax");
11921 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11922 USTPUTC(CTLVAR, out);
11923 typeloc = out - (char *)stackblock();
11925 subtype = VSNORMAL;
11927 c = pgetc_eatbnl();
11932 /* $[{[#]]NAME[}] */
11935 c = pgetc_eatbnl();
11936 } while (is_in_name(c));
11937 } else if (isdigit(c)) {
11938 /* $[{[#]]NUM[}] */
11941 c = pgetc_eatbnl();
11942 } while (isdigit(c));
11943 } else if (is_special(c)) {
11944 /* $[{[#]]<specialchar>[}] */
11947 c = pgetc_eatbnl();
11948 if (!subtype && cc == '#') {
11949 subtype = VSLENGTH;
11950 if (c == '_' || isalnum(c))
11953 c = pgetc_eatbnl();
11954 if (cc == '}' || c != '}') {
11965 if (c != '}' && subtype == VSLENGTH) {
11966 /* ${#VAR didn't end with } */
11970 if (subtype == 0) {
11971 static const char types[] ALIGN1 = "}-+?=";
11972 /* ${VAR...} but not $VAR or ${#VAR} */
11973 /* c == first char after VAR */
11976 c = pgetc_eatbnl();
11978 /* This check is only needed to not misinterpret
11979 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11982 if (!strchr(types, c)) {
11983 subtype = VSSUBSTR;
11985 break; /* "goto badsub" is bigger (!) */
11991 const char *p = strchr(types, c);
11994 subtype |= p - types + VSNORMAL;
12000 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
12001 c = pgetc_eatbnl();
12007 #if BASH_PATTERN_SUBST
12009 /* ${v/[/]pattern/repl} */
12010 //TODO: encode pattern and repl separately.
12011 // Currently ${v/$var_with_slash/repl} is horribly broken
12012 subtype = VSREPLACE;
12013 c = pgetc_eatbnl();
12016 subtype++; /* VSREPLACEALL */
12024 ((unsigned char *)stackblock())[typeloc] = subtype;
12025 if (subtype != VSNORMAL) {
12032 goto parsesub_return;
12036 * Called to parse command substitutions. Newstyle is set if the command
12037 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
12038 * list of commands (passed by reference), and savelen is the number of
12039 * characters on the top of the stack which must be preserved.
12042 struct nodelist **nlpp;
12046 smallint saveprompt = 0;
12049 savelen = out - (char *)stackblock();
12052 * FIXME: this can allocate very large block on stack and SEGV.
12054 * echo "..<100kbytes>..`true` $(true) `true` ..."
12055 * allocates 100kb for every command subst. With about
12056 * a hundred command substitutions stack overflows.
12057 * With larger prepended string, SEGV happens sooner.
12059 str = alloca(savelen);
12060 memcpy(str, stackblock(), savelen);
12064 /* We must read until the closing backquote, giving special
12065 * treatment to some slashes, and then push the string and
12066 * reread it as input, interpreting it normally.
12072 STARTSTACKSTR(pout);
12076 setprompt_if(needprompt, 2);
12087 * If eating a newline, avoid putting
12088 * the newline into the new character
12089 * stream (via the STPUTC after the
12094 if (pc != '\\' && pc != '`' && pc != '$'
12095 && (!dblquote || pc != '"')
12097 STPUTC('\\', pout);
12099 if (pc <= 255 /* not PEOA or PEOF */) {
12105 IF_ASH_ALIAS(case PEOA:)
12106 startlinno = g_parsefile->linno;
12107 raise_error_syntax("EOF in backquote substitution");
12119 STPUTC('\0', pout);
12120 psavelen = pout - (char *)stackblock();
12121 if (psavelen > 0) {
12122 pstr = grabstackstr(pout);
12123 setinputstring(pstr);
12128 nlpp = &(*nlpp)->next;
12129 *nlpp = stzalloc(sizeof(**nlpp));
12130 /* (*nlpp)->next = NULL; - stzalloc did it */
12133 saveprompt = doprompt;
12140 doprompt = saveprompt;
12141 else if (readtoken() != TRP)
12142 raise_error_unexpected_syntax(TRP);
12147 * Start reading from old file again, ignoring any pushed back
12148 * tokens left from the backquote parsing
12153 while (stackblocksize() <= savelen)
12155 STARTSTACKSTR(out);
12157 memcpy(out, str, savelen);
12158 STADJUST(savelen, out);
12160 USTPUTC(CTLBACKQ, out);
12162 goto parsebackq_oldreturn;
12163 goto parsebackq_newreturn;
12166 #if ENABLE_FEATURE_SH_MATH
12168 * Parse an arithmetic expansion (indicate start of one and set state)
12171 if (++arinest == 1) {
12172 prevsyntax = syntax;
12173 syntax = ARISYNTAX;
12175 USTPUTC(CTLARI, out);
12176 goto parsearith_return;
12179 } /* end of readtoken */
12182 * Read the next input token.
12183 * If the token is a word, we set backquotelist to the list of cmds in
12184 * backquotes. We set quoteflag to true if any part of the word was
12186 * If the token is TREDIR, then we set redirnode to a structure containing
12188 * In all cases, the variable startlinno is set to the number of the line
12189 * on which the token starts.
12191 * [Change comment: here documents and internal procedures]
12192 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12193 * word parsing code into a separate routine. In this case, readtoken
12194 * doesn't need to have any internal procedures, but parseword does.
12195 * We could also make parseoperator in essence the main routine, and
12196 * have parseword (readtoken1?) handle both words and redirection.]
12198 #define NEW_xxreadtoken
12199 #ifdef NEW_xxreadtoken
12200 /* singles must be first! */
12201 static const char xxreadtoken_chars[7] ALIGN1 = {
12202 '\n', '(', ')', /* singles */
12203 '&', '|', ';', /* doubles */
12207 #define xxreadtoken_singles 3
12208 #define xxreadtoken_doubles 3
12210 static const char xxreadtoken_tokens[] ALIGN1 = {
12211 TNL, TLP, TRP, /* only single occurrence allowed */
12212 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12213 TEOF, /* corresponds to trailing nul */
12214 TAND, TOR, TENDCASE /* if double occurrence */
12226 setprompt_if(needprompt, 2);
12227 startlinno = g_parsefile->linno;
12228 for (;;) { /* until token or start of word found */
12230 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12234 while ((c = pgetc()) != '\n' && c != PEOF)
12237 } else if (c == '\\') {
12238 if (pgetc() != '\n') {
12240 break; /* return readtoken1(...) */
12246 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12252 p = strchr(xxreadtoken_chars, c);
12254 break; /* return readtoken1(...) */
12256 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12258 if (cc == c) { /* double occurrence? */
12259 p += xxreadtoken_doubles + 1;
12262 #if BASH_REDIR_OUTPUT
12263 if (c == '&' && cc == '>') /* &> */
12264 break; /* return readtoken1(...) */
12269 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12274 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12276 #else /* old xxreadtoken */
12277 #define RETURN(token) return lasttoken = token
12287 setprompt_if(needprompt, 2);
12288 startlinno = g_parsefile->linno;
12289 for (;;) { /* until token or start of word found */
12292 case ' ': case '\t':
12293 IF_ASH_ALIAS(case PEOA:)
12296 while ((c = pgetc()) != '\n' && c != PEOF)
12301 if (pgetc() == '\n') {
12313 if (pgetc() == '&')
12318 if (pgetc() == '|')
12323 if (pgetc() == ';')
12336 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12339 #endif /* old xxreadtoken */
12345 int kwd = checkkwd;
12347 smallint alreadyseen = tokpushback;
12350 #if ENABLE_ASH_ALIAS
12366 if (t != TWORD || quoteflag) {
12371 * check for keywords
12373 if (kwd & CHKKWD) {
12374 const char *const *pp;
12376 pp = findkwd(wordtext);
12378 lasttoken = t = pp - tokname_array;
12379 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12384 if (checkkwd & CHKALIAS) {
12385 #if ENABLE_ASH_ALIAS
12387 ap = lookupalias(wordtext, 1);
12390 pushstring(ap->val, ap);
12400 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12402 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12418 * Read and parse a command. Returns NODE_EOF on end of file.
12419 * (NULL is a valid parse tree indicating a blank line.)
12421 static union node *
12422 parsecmd(int interact)
12427 doprompt = interact;
12428 setprompt_if(doprompt, doprompt);
12434 * Input any here documents.
12439 struct heredoc *here;
12442 here = heredoclist;
12443 heredoclist = NULL;
12446 setprompt_if(needprompt, 2);
12447 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12448 here->eofmark, here->striptabs);
12449 n = stzalloc(sizeof(struct narg));
12450 n->narg.type = NARG;
12451 /*n->narg.next = NULL; - stzalloc did it */
12452 n->narg.text = wordtext;
12453 n->narg.backquote = backquotelist;
12454 here->here->nhere.doc = n;
12461 * called by editline -- any expansions to the prompt should be added here.
12463 static const char *
12464 expandstr(const char *ps)
12469 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12470 * and token processing _can_ alter it (delete NULs etc). */
12471 setinputstring((char *)ps);
12473 saveprompt = doprompt;
12475 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12476 doprompt = saveprompt;
12480 n.narg.type = NARG;
12481 n.narg.next = NULL;
12482 n.narg.text = wordtext;
12483 n.narg.backquote = backquotelist;
12485 expandarg(&n, NULL, EXP_QUOTED);
12486 return stackblock();
12490 * Execute a command or commands contained in a string.
12493 evalstring(char *s, int flags)
12495 struct jmploc *volatile savehandler;
12496 struct jmploc jmploc;
12500 struct stackmark smark;
12505 setstackmark(&smark);
12508 /* On exception inside execution loop, we must popfile().
12509 * Try interactively:
12511 * command eval "a=b" # throws "is read only" error
12512 * "command BLTIN" is not supposed to abort (even in non-interactive use).
12513 * But if we skip popfile(), we hit EOF in eval's string, and exit.
12515 savehandler = exception_handler;
12516 ex = setjmp(jmploc.loc);
12519 exception_handler = &jmploc;
12521 while ((n = parsecmd(0)) != NODE_EOF) {
12524 i = evaltree(n, flags);
12527 popstackmark(&smark);
12532 popstackmark(&smark);
12536 exception_handler = savehandler;
12538 longjmp(exception_handler->loc, ex);
12544 * The eval command.
12546 static int FAST_FUNC
12547 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12556 STARTSTACKSTR(concat);
12558 concat = stack_putstr(p, concat);
12562 STPUTC(' ', concat);
12564 STPUTC('\0', concat);
12565 p = grabstackstr(concat);
12567 return evalstring(p, flags & EV_TESTED);
12573 * Read and execute commands.
12574 * "Top" is nonzero for the top level command loop;
12575 * it turns on prompting if the shell is interactive.
12581 struct stackmark smark;
12586 TRACE(("cmdloop(%d) called\n", top));
12590 setstackmark(&smark);
12593 showjobs(SHOW_CHANGED|SHOW_STDERR);
12596 if (iflag && top) {
12600 n = parsecmd(inter);
12602 if (DEBUG > 2 && debug && (n != NODE_EOF))
12605 if (n == NODE_EOF) {
12606 if (!top || numeof >= 50)
12608 if (!stoppedjobs()) {
12611 out2str("\nUse \"exit\" to leave shell.\n");
12614 } else if (nflag == 0) {
12617 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12620 i = evaltree(n, 0);
12624 popstackmark(&smark);
12628 evalskip &= ~SKIPFUNC;
12636 * Take commands from a file. To be compatible we should do a path
12637 * search for the file, which is necessary to find sub-commands.
12640 find_dot_file(char *name)
12643 const char *path = pathval();
12646 /* don't try this for absolute or relative paths */
12647 if (strchr(name, '/'))
12650 while ((fullname = path_advance(&path, name)) != NULL) {
12651 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12653 * Don't bother freeing here, since it will
12654 * be freed by the caller.
12658 if (fullname != name)
12659 stunalloc(fullname);
12662 /* not found in the PATH */
12663 ash_msg_and_raise_error("%s: not found", name);
12667 static int FAST_FUNC
12668 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12670 /* "false; . empty_file; echo $?" should print 0, not 1: */
12674 char *args_need_save;
12675 struct strlist *sp;
12676 volatile struct shparam saveparam;
12678 for (sp = cmdenviron; sp; sp = sp->next)
12679 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12681 nextopt(nullstr); /* handle possible "--" */
12685 /* bash says: "bash: .: filename argument required" */
12686 return 2; /* bash compat */
12689 /* This aborts if file isn't found, which is POSIXly correct.
12690 * bash returns exitcode 1 instead.
12692 fullname = find_dot_file(argv[0]);
12694 args_need_save = argv[0];
12695 if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
12697 saveparam = shellparam;
12698 shellparam.malloced = 0;
12702 shellparam.nparam = argc;
12703 shellparam.p = argv;
12706 /* This aborts if file can't be opened, which is POSIXly correct.
12707 * bash returns exitcode 1 instead.
12709 setinputfile(fullname, INPUT_PUSH_FILE);
12710 commandname = fullname;
12711 status = cmdloop(0);
12714 if (args_need_save) {
12715 freeparam(&shellparam);
12716 shellparam = saveparam;
12722 static int FAST_FUNC
12723 exitcmd(int argc UNUSED_PARAM, char **argv)
12728 exitstatus = number(argv[1]);
12729 raise_exception(EXEXIT);
12734 * Read a file containing shell functions.
12737 readcmdfile(char *name)
12739 setinputfile(name, INPUT_PUSH_FILE);
12745 /* ============ find_command inplementation */
12748 * Resolve a command name. If you change this routine, you may have to
12749 * change the shellexec routine as well.
12752 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12754 struct tblentry *cmdp;
12761 struct builtincmd *bcmd;
12763 /* If name contains a slash, don't use PATH or hash table */
12764 if (strchr(name, '/') != NULL) {
12765 entry->u.index = -1;
12766 if (act & DO_ABS) {
12767 while (stat(name, &statb) < 0) {
12769 if (errno == EINTR)
12772 entry->cmdtype = CMDUNKNOWN;
12776 entry->cmdtype = CMDNORMAL;
12780 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12782 updatetbl = (path == pathval());
12785 if (strstr(path, "%builtin") != NULL)
12786 act |= DO_ALTBLTIN;
12789 /* If name is in the table, check answer will be ok */
12790 cmdp = cmdlookup(name, 0);
12791 if (cmdp != NULL) {
12794 switch (cmdp->cmdtype) {
12812 } else if (cmdp->rehash == 0)
12813 /* if not invalidated by cd, we're done */
12817 /* If %builtin not in path, check for builtin next */
12818 bcmd = find_builtin(name);
12820 if (IS_BUILTIN_REGULAR(bcmd))
12821 goto builtin_success;
12822 if (act & DO_ALTPATH) {
12823 if (!(act & DO_ALTBLTIN))
12824 goto builtin_success;
12825 } else if (builtinloc <= 0) {
12826 goto builtin_success;
12830 #if ENABLE_FEATURE_SH_STANDALONE
12832 int applet_no = find_applet_by_name(name);
12833 if (applet_no >= 0) {
12834 entry->cmdtype = CMDNORMAL;
12835 entry->u.index = -2 - applet_no;
12841 /* We have to search path. */
12842 prev = -1; /* where to start */
12843 if (cmdp && cmdp->rehash) { /* doing a rehash */
12844 if (cmdp->cmdtype == CMDBUILTIN)
12847 prev = cmdp->param.index;
12853 while ((fullname = path_advance(&path, name)) != NULL) {
12854 stunalloc(fullname);
12855 /* NB: code below will still use fullname
12856 * despite it being "unallocated" */
12859 if (prefix(pathopt, "builtin")) {
12861 goto builtin_success;
12864 if ((act & DO_NOFUNC)
12865 || !prefix(pathopt, "func")
12866 ) { /* ignore unimplemented options */
12870 /* if rehash, don't redo absolute path names */
12871 if (fullname[0] == '/' && idx <= prev) {
12874 TRACE(("searchexec \"%s\": no change\n", name));
12877 while (stat(fullname, &statb) < 0) {
12879 if (errno == EINTR)
12882 if (errno != ENOENT && errno != ENOTDIR)
12886 e = EACCES; /* if we fail, this will be the error */
12887 if (!S_ISREG(statb.st_mode))
12889 if (pathopt) { /* this is a %func directory */
12890 stalloc(strlen(fullname) + 1);
12891 /* NB: stalloc will return space pointed by fullname
12892 * (because we don't have any intervening allocations
12893 * between stunalloc above and this stalloc) */
12894 readcmdfile(fullname);
12895 cmdp = cmdlookup(name, 0);
12896 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12897 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12898 stunalloc(fullname);
12901 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12903 entry->cmdtype = CMDNORMAL;
12904 entry->u.index = idx;
12908 cmdp = cmdlookup(name, 1);
12909 cmdp->cmdtype = CMDNORMAL;
12910 cmdp->param.index = idx;
12915 /* We failed. If there was an entry for this command, delete it */
12916 if (cmdp && updatetbl)
12917 delete_cmd_entry();
12919 ash_msg("%s: %s", name, errmsg(e, "not found"));
12920 entry->cmdtype = CMDUNKNOWN;
12925 entry->cmdtype = CMDBUILTIN;
12926 entry->u.cmd = bcmd;
12930 cmdp = cmdlookup(name, 1);
12931 cmdp->cmdtype = CMDBUILTIN;
12932 cmdp->param.cmd = bcmd;
12936 entry->cmdtype = cmdp->cmdtype;
12937 entry->u = cmdp->param;
12942 * The trap builtin.
12944 static int FAST_FUNC
12945 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12949 int signo, exitcode;
12954 for (signo = 0; signo < NSIG; signo++) {
12955 char *tr = trap_ptr[signo];
12957 /* note: bash adds "SIG", but only if invoked
12958 * as "bash". If called as "sh", or if set -o posix,
12959 * then it prints short signal names.
12960 * We are printing short names: */
12961 out1fmt("trap -- %s %s\n",
12963 get_signame(signo));
12964 /* trap_ptr != trap only if we are in special-cased `trap` code.
12965 * In this case, we will exit very soon, no need to free(). */
12966 /* if (trap_ptr != trap && tp[0]) */
12971 if (trap_ptr != trap) {
12984 signo = get_signum(*ap);
12985 if (signo < 0 || signo >= NSIG) {
12986 /* Mimic bash message exactly */
12987 ash_msg("%s: invalid signal specification", *ap);
12993 if (LONE_DASH(action))
12996 if (action[0]) /* not NULL and not "" and not "-" */
12997 may_have_traps = 1;
12998 action = ckstrdup(action);
13002 trap[signo] = action;
13013 /* ============ Builtins */
13015 #if ENABLE_ASH_HELP
13016 static int FAST_FUNC
13017 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13023 "Built-in commands:\n"
13024 "------------------\n");
13025 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
13026 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
13027 builtintab[i].name + 1);
13033 # if ENABLE_FEATURE_SH_STANDALONE
13035 const char *a = applet_names;
13037 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
13042 while (*a++ != '\0')
13047 newline_and_flush(stdout);
13048 return EXIT_SUCCESS;
13053 static int FAST_FUNC
13054 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13056 show_history(line_input_state);
13057 return EXIT_SUCCESS;
13062 * The export and readonly commands.
13064 static int FAST_FUNC
13065 exportcmd(int argc UNUSED_PARAM, char **argv)
13075 /* "readonly" in bash accepts, but ignores -n.
13076 * We do the same: it saves a conditional in nextopt's param.
13079 while ((opt = nextopt("np")) != '\0') {
13081 flag_off = VEXPORT;
13084 if (argv[0][0] == 'r') {
13086 flag_off = 0; /* readonly ignores -n */
13088 flag_off = ~flag_off;
13090 /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
13096 p = strchr(name, '=');
13100 vp = *findvar(hashvar(name), name);
13102 vp->flags = ((vp->flags | flag) & flag_off);
13106 setvar(name, p, (flag & flag_off));
13107 } while ((name = *++aptr) != NULL);
13112 /* No arguments. Show the list of exported or readonly vars.
13115 showvars(argv[0], flag, 0);
13120 * Delete a function if it exists.
13123 unsetfunc(const char *name)
13125 struct tblentry *cmdp;
13127 cmdp = cmdlookup(name, 0);
13128 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
13129 delete_cmd_entry();
13133 * The unset builtin command. We unset the function before we unset the
13134 * variable to allow a function to be unset when there is a readonly variable
13135 * with the same name.
13137 static int FAST_FUNC
13138 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13145 while ((i = nextopt("vf")) != 0) {
13149 for (ap = argptr; *ap; ap++) {
13162 static const unsigned char timescmd_str[] ALIGN1 = {
13163 ' ', offsetof(struct tms, tms_utime),
13164 '\n', offsetof(struct tms, tms_stime),
13165 ' ', offsetof(struct tms, tms_cutime),
13166 '\n', offsetof(struct tms, tms_cstime),
13169 static int FAST_FUNC
13170 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13172 unsigned long clk_tck, s, t;
13173 const unsigned char *p;
13176 clk_tck = bb_clk_tck();
13181 t = *(clock_t *)(((char *) &buf) + p[1]);
13184 out1fmt("%lum%lu.%03lus%c",
13186 (t * 1000) / clk_tck,
13194 #if ENABLE_FEATURE_SH_MATH
13196 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13197 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13199 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13201 static int FAST_FUNC
13202 letcmd(int argc UNUSED_PARAM, char **argv)
13208 ash_msg_and_raise_error("expression expected");
13210 i = ash_arith(*argv);
13218 * The read builtin. Options:
13219 * -r Do not interpret '\' specially
13220 * -s Turn off echo (tty only)
13221 * -n NCHARS Read NCHARS max
13222 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13223 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13224 * -u FD Read from given FD instead of fd 0
13225 * This uses unbuffered input, which may be avoidable in some cases.
13226 * TODO: bash also has:
13227 * -a ARRAY Read into array[0],[1],etc
13228 * -d DELIM End on DELIM char, not newline
13229 * -e Use line editing (tty only)
13231 static int FAST_FUNC
13232 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13234 char *opt_n = NULL;
13235 char *opt_p = NULL;
13236 char *opt_t = NULL;
13237 char *opt_u = NULL;
13238 int read_flags = 0;
13242 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13251 read_flags |= BUILTIN_READ_SILENT;
13257 read_flags |= BUILTIN_READ_RAW;
13267 /* "read -s" needs to save/restore termios, can't allow ^C
13268 * to jump out of it.
13272 r = shell_builtin_read(setvar0,
13274 bltinlookup("IFS"), /* can be NULL */
13283 if ((uintptr_t)r == 1 && errno == EINTR) {
13284 /* to get SIGCHLD: sleep 1 & read x; echo $x */
13285 if (pending_sig == 0)
13289 if ((uintptr_t)r > 1)
13290 ash_msg_and_raise_error(r);
13292 return (uintptr_t)r;
13295 static int FAST_FUNC
13296 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13298 static const char permuser[3] ALIGN1 = "ogu";
13301 int symbolic_mode = 0;
13303 while (nextopt("S") != '\0') {
13312 if (*argptr == NULL) {
13313 if (symbolic_mode) {
13314 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13321 *p++ = permuser[i];
13323 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13324 if (!(mask & 0400)) *p++ = 'r';
13325 if (!(mask & 0200)) *p++ = 'w';
13326 if (!(mask & 0100)) *p++ = 'x';
13334 out1fmt("%04o\n", mask);
13337 char *modestr = *argptr;
13338 /* numeric umasks are taken as-is */
13339 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13340 if (!isdigit(modestr[0]))
13342 mask = bb_parse_mode(modestr, mask);
13343 if ((unsigned)mask > 0777) {
13344 ash_msg_and_raise_error("illegal mode: %s", modestr);
13346 if (!isdigit(modestr[0]))
13353 static int FAST_FUNC
13354 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13356 return shell_builtin_ulimit(argv);
13359 /* ============ main() and helpers */
13362 * Called to exit the shell.
13371 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13372 save_history(line_input_state);
13374 status = exitstatus;
13375 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13376 if (setjmp(loc.loc)) {
13377 if (exception_type == EXEXIT)
13378 status = exitstatus;
13381 exception_handler = &loc;
13387 /*free(p); - we'll exit soon */
13390 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13391 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13394 flush_stdout_stderr();
13402 /* we will never free this */
13403 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13405 sigmode[SIGCHLD - 1] = S_DFL;
13406 setsignal(SIGCHLD);
13408 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13409 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13411 signal(SIGHUP, SIG_DFL);
13416 struct stat st1, st2;
13419 for (envp = environ; envp && *envp; envp++) {
13420 p = endofname(*envp);
13421 if (p != *envp && *p == '=') {
13422 setvareq(*envp, VEXPORT|VTEXTFIXED);
13426 setvareq((char*)defoptindvar, VTEXTFIXED);
13428 setvar0("PPID", utoa(getppid()));
13430 p = lookupvar("SHLVL");
13431 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13433 #if BASH_HOSTNAME_VAR
13434 if (!lookupvar("HOSTNAME")) {
13435 struct utsname uts;
13437 setvar0("HOSTNAME", uts.nodename);
13440 p = lookupvar("PWD");
13442 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13443 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13453 //usage:#define ash_trivial_usage
13454 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13455 //usage:#define ash_full_usage "\n\n"
13456 //usage: "Unix shell interpreter"
13459 * Process the shell command line arguments.
13462 procargs(char **argv)
13465 const char *xminusc;
13470 /* if (xargv[0]) - mmm, this is always true! */
13472 for (i = 0; i < NOPTS; i++)
13475 if (options(/*cmdline:*/ 1)) {
13476 /* it already printed err message */
13477 raise_exception(EXERROR);
13481 if (*xargv == NULL) {
13483 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13486 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13490 for (i = 0; i < NOPTS; i++)
13491 if (optlist[i] == 2)
13496 /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
13501 } else if (!sflag) {
13502 setinputfile(*xargv, 0);
13505 commandname = arg0;
13508 shellparam.p = xargv;
13509 #if ENABLE_ASH_GETOPTS
13510 shellparam.optind = 1;
13511 shellparam.optoff = -1;
13513 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13515 shellparam.nparam++;
13522 * Read /etc/profile, ~/.profile, $ENV.
13525 read_profile(const char *name)
13527 name = expandstr(name);
13528 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13535 * This routine is called when an error or an interrupt occurs in an
13536 * interactive shell and control is returned to the main command loop.
13537 * (In dash, this function is auto-generated by build machinery).
13546 /* from expand.c: */
13549 /* from input.c: */
13550 g_parsefile->left_in_buffer = 0;
13551 g_parsefile->left_in_line = 0; /* clear input buffer */
13554 /* from redir.c: */
13556 popredir(/*drop:*/ 0, /*restore:*/ 0);
13560 static short profile_buf[16384];
13561 extern int etext();
13565 * Main routine. We initialize things, parse the arguments, execute
13566 * profiles if we're a login shell, and then call cmdloop to execute
13567 * commands. The setjmp call sets up the location to jump to when an
13568 * exception occurs. When an exception occurs the variable "state"
13569 * is used to figure out how far we had gotten.
13571 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13572 int ash_main(int argc UNUSED_PARAM, char **argv)
13574 volatile smallint state;
13575 struct jmploc jmploc;
13576 struct stackmark smark;
13578 /* Initialize global data */
13582 #if ENABLE_ASH_ALIAS
13588 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13591 #if ENABLE_FEATURE_EDITING
13592 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13595 if (setjmp(jmploc.loc)) {
13601 e = exception_type;
13603 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13607 newline_and_flush(stderr);
13610 popstackmark(&smark);
13611 FORCE_INT_ON; /* enable interrupts */
13620 exception_handler = &jmploc;
13621 rootpid = getpid();
13624 setstackmark(&smark);
13627 TRACE(("Shell args: "));
13628 trace_puts_args(argv);
13631 if (argv[0] && argv[0][0] == '-')
13637 read_profile("/etc/profile");
13640 hp = lookupvar("HOME");
13642 read_profile("$HOME/.profile");
13648 getuid() == geteuid() && getgid() == getegid() &&
13652 const char *shinit = lookupvar("ENV");
13653 if (shinit != NULL && *shinit != '\0')
13654 read_profile(shinit);
13656 popstackmark(&smark);
13660 /* evalstring pushes parsefile stack.
13661 * Ensure we don't falsely claim that 0 (stdin)
13662 * is one of stacked source fds.
13663 * Testcase: ash -c 'exec 1>&0' must not complain. */
13664 // if (!sflag) g_parsefile->pf_fd = -1;
13665 // ^^ not necessary since now we special-case fd 0
13666 // in is_hidden_fd() to not be considered "hidden fd"
13667 evalstring(minusc, 0);
13670 if (sflag || minusc == NULL) {
13671 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13673 const char *hp = lookupvar("HISTFILE");
13675 hp = lookupvar("HOME");
13678 hp = concat_path_file(hp, ".ash_history");
13679 setvar0("HISTFILE", hp);
13682 hp = lookupvar("HISTFILE");
13686 line_input_state->hist_file = hp;
13687 # if ENABLE_FEATURE_SH_HISTFILESIZE
13688 hp = lookupvar("HISTFILESIZE");
13689 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13693 state4: /* XXX ??? - why isn't this before the "if" statement */
13701 extern void _mcleanup(void);
13705 TRACE(("End of main reached\n"));
13712 * Copyright (c) 1989, 1991, 1993, 1994
13713 * The Regents of the University of California. All rights reserved.
13715 * This code is derived from software contributed to Berkeley by
13716 * Kenneth Almquist.
13718 * Redistribution and use in source and binary forms, with or without
13719 * modification, are permitted provided that the following conditions
13721 * 1. Redistributions of source code must retain the above copyright
13722 * notice, this list of conditions and the following disclaimer.
13723 * 2. Redistributions in binary form must reproduce the above copyright
13724 * notice, this list of conditions and the following disclaimer in the
13725 * documentation and/or other materials provided with the distribution.
13726 * 3. Neither the name of the University nor the names of its contributors
13727 * may be used to endorse or promote products derived from this software
13728 * without specific prior written permission.
13730 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13731 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13732 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13733 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13734 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13735 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13736 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13737 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13738 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13739 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF