1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
19 //config: bool "ash (77 kb)"
21 //config: depends on !NOMMU
23 //config: The most complete and most pedantically correct shell included with
24 //config: busybox. This shell is actually a derivative of the Debian 'dash'
25 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
26 //config: (written by Kenneth Almquist) from NetBSD.
28 //config:# ash options
29 //config:# note: Don't remove !NOMMU part in the next line; it would break
30 //config:# menuconfig's indenting.
31 //config:if !NOMMU && (ASH || SH_IS_ASH || BASH_IS_ASH)
33 //config:config ASH_OPTIMIZE_FOR_SIZE
34 //config: bool "Optimize for size instead of speed"
36 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
38 //config:config ASH_INTERNAL_GLOB
39 //config: bool "Use internal glob() implementation"
40 //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
41 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
43 //config: Do not use glob() function from libc, use internal implementation.
44 //config: Use this if you are getting "glob.h: No such file or directory"
45 //config: or similar build errors.
46 //config: Note that as of now (2017-01), uclibc and musl glob() both have bugs
47 //config: which would break ash if you select N here.
49 //config:config ASH_BASH_COMPAT
50 //config: bool "bash-compatible extensions"
52 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
54 //config:config ASH_JOB_CONTROL
55 //config: bool "Job control"
57 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
59 //config:config ASH_ALIAS
60 //config: bool "Alias support"
62 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
64 //config:config ASH_RANDOM_SUPPORT
65 //config: bool "Pseudorandom generator and $RANDOM variable"
67 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
69 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
70 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
71 //config: You can reset the generator by using a specified start value.
72 //config: After "unset RANDOM" the generator will switch off and this
73 //config: variable will no longer have special treatment.
75 //config:config ASH_EXPAND_PRMT
76 //config: bool "Expand prompt string"
78 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
80 //config: $PS# may contain volatile content, such as backquote commands.
81 //config: This option recreates the prompt string from the environment
82 //config: variable each time it is displayed.
84 //config:config ASH_IDLE_TIMEOUT
85 //config: bool "Idle timeout variable $TMOUT"
87 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
89 //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
91 //config:config ASH_MAIL
92 //config: bool "Check for new mail in interactive shell"
94 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
96 //config: Enable "check for new mail" function:
97 //config: if set, $MAIL file and $MAILPATH list of files
98 //config: are checked for mtime changes, and "you have mail"
99 //config: message is printed if change is detected.
101 //config:config ASH_ECHO
102 //config: bool "echo builtin"
104 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
106 //config:config ASH_PRINTF
107 //config: bool "printf builtin"
109 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
111 //config:config ASH_TEST
112 //config: bool "test builtin"
114 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
116 //config:config ASH_HELP
117 //config: bool "help builtin"
119 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
121 //config:config ASH_GETOPTS
122 //config: bool "getopts builtin"
124 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
126 //config:config ASH_CMDCMD
127 //config: bool "command builtin"
129 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
131 //config: Enable support for the 'command' builtin, which allows
132 //config: you to run the specified command or builtin,
133 //config: even when there is a function with the same name.
135 //config:endif # ash options
137 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
138 // APPLET_ODDNAME:name main location suid_type help
139 //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
140 //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
142 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
143 //kbuild:lib-$(CONFIG_SH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
144 //kbuild:lib-$(CONFIG_BASH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
145 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
148 * DEBUG=1 to compile in debugging ('set -o debug' turns on)
149 * DEBUG=2 to compile in and turn on debugging.
150 * When debugging is on ("set -o debug" was executed, or DEBUG=2),
151 * debugging info is written to ./trace, quit signal generates core dump.
154 /* Tweak debug output verbosity here */
158 #define DEBUG_INTONOFF 0
162 #define JOBS ENABLE_ASH_JOB_CONTROL
166 #include <sys/times.h>
167 #include <sys/utsname.h> /* for setting $HOSTNAME */
168 #include "busybox.h" /* for applet_names */
170 /* So far, all bash compat is controlled by one config option */
171 /* Separate defines document which part of code implements what */
172 /* function keyword */
173 #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
174 #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
176 #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
177 #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
179 #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
180 #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
181 #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
182 #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
183 #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
184 #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
186 #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
187 #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
188 #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
189 #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
190 #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
192 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
193 /* Bionic at least up to version 24 has no glob() */
194 # undef ENABLE_ASH_INTERNAL_GLOB
195 # define ENABLE_ASH_INTERNAL_GLOB 1
198 #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
199 # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
200 # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
201 # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
202 # error glob() should unbackslash them and match. uClibc does not unbackslash,
203 # error fails to match dirname, subsequently not expanding <pattern> in it.
205 // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
206 // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
209 #if !ENABLE_ASH_INTERNAL_GLOB
214 #include "shell_common.h"
215 #if ENABLE_FEATURE_SH_MATH
218 #if ENABLE_ASH_RANDOM_SUPPORT
221 # define CLEAR_RANDOM_T(rnd) ((void)0)
224 #include "NUM_APPLETS.h"
226 /* STANDALONE does not make sense, and won't compile */
227 # undef CONFIG_FEATURE_SH_STANDALONE
228 # undef ENABLE_FEATURE_SH_STANDALONE
229 # undef IF_FEATURE_SH_STANDALONE
230 # undef IF_NOT_FEATURE_SH_STANDALONE
231 # define ENABLE_FEATURE_SH_STANDALONE 0
232 # define IF_FEATURE_SH_STANDALONE(...)
233 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
237 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
241 # error "Do not even bother, ash will not run on NOMMU machine"
245 /* ============ Hash table sizes. Configurable. */
249 #define CMDTABLESIZE 31 /* should be prime */
252 /* ============ Shell options */
254 static const char *const optletters_optnames[] = {
278 #define optletters(n) optletters_optnames[n][0]
279 #define optnames(n) (optletters_optnames[n] + 1)
281 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
284 /* ============ Misc data */
286 #define msg_illnum "Illegal number: %s"
289 * We enclose jmp_buf in a structure so that we can declare pointers to
290 * jump locations. The global variable handler contains the location to
291 * jump to when an exception occurs, and the global variable exception_type
292 * contains a code identifying the exception. To implement nested
293 * exception handlers, the user should save the value of handler on entry
294 * to an inner scope, set handler to point to a jmploc structure for the
295 * inner scope, and restore handler on exit from the scope.
301 struct globals_misc {
302 uint8_t exitstatus; /* exit status of last command */
303 uint8_t back_exitstatus;/* exit status of backquoted command */
304 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
305 int rootpid; /* pid of main shell */
306 /* shell level: 0 for the main shell, 1 for its children, and so on */
308 #define rootshell (!shlvl)
309 char *minusc; /* argument to -c option */
311 char *curdir; // = nullstr; /* current working directory */
312 char *physdir; // = nullstr; /* physical working directory */
314 char *arg0; /* value of $0 */
316 struct jmploc *exception_handler;
318 volatile int suppress_int; /* counter */
319 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
320 volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
321 volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
322 smallint exception_type; /* kind of exception (0..5) */
324 #define EXINT 0 /* SIGINT received */
325 #define EXERROR 1 /* a generic error */
326 #define EXEXIT 4 /* exit the shell */
329 char nullstr[1]; /* zero length string */
332 #define eflag optlist[0]
333 #define fflag optlist[1]
334 #define Iflag optlist[2]
335 #define iflag optlist[3]
336 #define mflag optlist[4]
337 #define nflag optlist[5]
338 #define sflag optlist[6]
339 #define xflag optlist[7]
340 #define vflag optlist[8]
341 #define Cflag optlist[9]
342 #define aflag optlist[10]
343 #define bflag optlist[11]
344 #define uflag optlist[12]
345 #define viflag optlist[13]
347 # define pipefail optlist[14]
352 # define nolog optlist[14 + BASH_PIPEFAIL]
353 # define debug optlist[15 + BASH_PIPEFAIL]
356 /* trap handler commands */
358 * Sigmode records the current value of the signal handlers for the various
359 * modes. A value of zero means that the current handler is not known.
360 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
362 char sigmode[NSIG - 1];
363 #define S_DFL 1 /* default signal handling (SIG_DFL) */
364 #define S_CATCH 2 /* signal is caught */
365 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
366 #define S_HARD_IGN 4 /* signal is ignored permanently */
368 /* indicates specified signal received */
369 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
370 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
372 char **trap_ptr; /* used only by "trap hack" */
374 /* Rarely referenced stuff */
375 #if ENABLE_ASH_RANDOM_SUPPORT
378 pid_t backgndpid; /* pid of last background process */
380 extern struct globals_misc *const ash_ptr_to_globals_misc;
381 #define G_misc (*ash_ptr_to_globals_misc)
382 #define exitstatus (G_misc.exitstatus )
383 #define back_exitstatus (G_misc.back_exitstatus )
384 #define job_warning (G_misc.job_warning)
385 #define rootpid (G_misc.rootpid )
386 #define shlvl (G_misc.shlvl )
387 #define minusc (G_misc.minusc )
388 #define curdir (G_misc.curdir )
389 #define physdir (G_misc.physdir )
390 #define arg0 (G_misc.arg0 )
391 #define exception_handler (G_misc.exception_handler)
392 #define exception_type (G_misc.exception_type )
393 #define suppress_int (G_misc.suppress_int )
394 #define pending_int (G_misc.pending_int )
395 #define got_sigchld (G_misc.got_sigchld )
396 #define pending_sig (G_misc.pending_sig )
397 #define isloginsh (G_misc.isloginsh )
398 #define nullstr (G_misc.nullstr )
399 #define optlist (G_misc.optlist )
400 #define sigmode (G_misc.sigmode )
401 #define gotsig (G_misc.gotsig )
402 #define may_have_traps (G_misc.may_have_traps )
403 #define trap (G_misc.trap )
404 #define trap_ptr (G_misc.trap_ptr )
405 #define random_gen (G_misc.random_gen )
406 #define backgndpid (G_misc.backgndpid )
407 #define INIT_G_misc() do { \
408 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
416 /* ============ DEBUG */
418 static void trace_printf(const char *fmt, ...);
419 static void trace_vprintf(const char *fmt, va_list va);
420 # define TRACE(param) trace_printf param
421 # define TRACEV(param) trace_vprintf param
422 # define close(fd) do { \
424 if (close(dfd) < 0) \
425 bb_error_msg("bug on %d: closing %d(0x%x)", \
426 __LINE__, dfd, dfd); \
429 # define TRACE(param)
430 # define TRACEV(param)
434 /* ============ Utility functions */
435 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
436 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
439 isdigit_str9(const char *str)
441 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
442 while (--maxlen && isdigit(*str))
444 return (*str == '\0');
448 var_end(const char *var)
457 /* ============ Interrupts / exceptions */
459 static void exitshell(void) NORETURN;
462 * These macros allow the user to suspend the handling of interrupt signals
463 * over a period of time. This is similar to SIGHOLD or to sigblock, but
464 * much more efficient and portable. (But hacking the kernel is so much
465 * more fun than worrying about efficiency and portability. :-))
468 # define INT_OFF do { \
469 TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
474 # define INT_OFF do { \
481 * Called to raise an exception. Since C doesn't include exceptions, we
482 * just do a longjmp to the exception handler. The type of exception is
483 * stored in the global variable "exception_type".
485 static void raise_exception(int) NORETURN;
487 raise_exception(int e)
490 if (exception_handler == NULL)
495 longjmp(exception_handler->loc, 1);
498 #define raise_exception(e) do { \
499 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
500 raise_exception(e); \
505 * Called when a SIGINT is received. (If the user specifies
506 * that SIGINT is to be trapped or ignored using the trap builtin, then
507 * this routine is not called.) Suppressint is nonzero when interrupts
508 * are held using the INT_OFF macro. (The test for iflag is just
509 * defensive programming.)
511 static void raise_interrupt(void) NORETURN;
513 raise_interrupt(void)
516 /* Signal is not automatically unmasked after it is raised,
517 * do it ourself - unmask all signals */
518 sigprocmask_allsigs(SIG_UNBLOCK);
519 /* pending_sig = 0; - now done in signal_handler() */
521 if (!(rootshell && iflag)) {
522 /* Kill ourself with SIGINT */
523 signal(SIGINT, SIG_DFL);
526 /* bash: ^C even on empty command line sets $? */
527 exitstatus = SIGINT + 128;
528 raise_exception(EXINT);
532 #define raise_interrupt() do { \
533 TRACE(("raising interrupt on line %d\n", __LINE__)); \
538 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
542 if (--suppress_int == 0 && pending_int) {
547 # define INT_ON do { \
548 TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
552 # define INT_ON int_on()
554 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
562 #define FORCE_INT_ON force_int_on()
564 #define SAVE_INT(v) ((v) = suppress_int)
566 #define RESTORE_INT(v) do { \
568 suppress_int = (v); \
569 if (suppress_int == 0 && pending_int) \
574 /* ============ Stdout/stderr output */
577 outstr(const char *p, FILE *file)
585 flush_stdout_stderr(void)
592 /* Was called outcslow(c,FILE*), but c was always '\n' */
594 newline_and_flush(FILE *dest)
602 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
604 out1fmt(const char *fmt, ...)
611 r = vprintf(fmt, ap);
617 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
619 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
626 ret = vsnprintf(outbuf, length, fmt, ap);
633 out1str(const char *p)
639 out2str(const char *p)
642 flush_stdout_stderr();
646 /* ============ Parser structures */
648 /* control characters in argument strings */
649 #define CTL_FIRST CTLESC
650 #define CTLESC ((unsigned char)'\201') /* escape next character */
651 #define CTLVAR ((unsigned char)'\202') /* variable defn */
652 #define CTLENDVAR ((unsigned char)'\203')
653 #define CTLBACKQ ((unsigned char)'\204')
654 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
655 #define CTLENDARI ((unsigned char)'\207')
656 #define CTLQUOTEMARK ((unsigned char)'\210')
657 #define CTL_LAST CTLQUOTEMARK
659 /* variable substitution byte (follows CTLVAR) */
660 #define VSTYPE 0x0f /* type of variable substitution */
661 #define VSNUL 0x10 /* colon--treat the empty string as unset */
663 /* values of VSTYPE field */
664 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
665 #define VSMINUS 0x2 /* ${var-text} */
666 #define VSPLUS 0x3 /* ${var+text} */
667 #define VSQUESTION 0x4 /* ${var?message} */
668 #define VSASSIGN 0x5 /* ${var=text} */
669 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
670 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
671 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
672 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
673 #define VSLENGTH 0xa /* ${#var} */
675 #define VSSUBSTR 0xc /* ${var:position:length} */
677 #if BASH_PATTERN_SUBST
678 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
679 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
682 static const char dolatstr[] ALIGN1 = {
683 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
685 #define DOLATSTRLEN 6
704 #if BASH_REDIR_OUTPUT
721 smallint type; /* Nxxxx */
724 union node *redirect;
729 smallint pipe_backgnd;
730 struct nodelist *cmdlist;
736 union node *redirect;
749 union node *elsepart;
776 struct nodelist *backquote;
779 /* nfile and ndup layout must match!
780 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
781 * that it is actually NTO2 (>&file), and change its type.
798 char *_unused_expfname;
817 struct nredir nredir;
818 struct nbinary nbinary;
822 struct nclist nclist;
831 * NODE_EOF is returned by parsecmd when it encounters an end of file.
832 * It must be distinct from NULL.
834 #define NODE_EOF ((union node *) -1L)
837 struct nodelist *next;
850 freefunc(struct funcnode *f)
852 if (f && --f->count < 0)
857 /* ============ Debugging output */
861 static FILE *tracefile;
864 trace_printf(const char *fmt, ...)
871 fprintf(tracefile, "%u ", (int) time(NULL));
873 fprintf(tracefile, "[%u] ", (int) getpid());
875 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
877 vfprintf(tracefile, fmt, va);
882 trace_vprintf(const char *fmt, va_list va)
886 vfprintf(tracefile, fmt, va);
887 fprintf(tracefile, "\n");
891 trace_puts(const char *s)
899 trace_puts_quoted(char *s)
906 putc('"', tracefile);
907 for (p = s; *p; p++) {
908 switch ((unsigned char)*p) {
909 case '\n': c = 'n'; goto backslash;
910 case '\t': c = 't'; goto backslash;
911 case '\r': c = 'r'; goto backslash;
912 case '\"': c = '\"'; goto backslash;
913 case '\\': c = '\\'; goto backslash;
914 case CTLESC: c = 'e'; goto backslash;
915 case CTLVAR: c = 'v'; goto backslash;
916 case CTLBACKQ: c = 'q'; goto backslash;
918 putc('\\', tracefile);
922 if (*p >= ' ' && *p <= '~')
925 putc('\\', tracefile);
926 putc((*p >> 6) & 03, tracefile);
927 putc((*p >> 3) & 07, tracefile);
928 putc(*p & 07, tracefile);
933 putc('"', tracefile);
937 trace_puts_args(char **ap)
944 trace_puts_quoted(*ap);
946 putc('\n', tracefile);
949 putc(' ', tracefile);
964 /* leave open because libedit might be using it */
967 strcpy(s, "./trace");
969 if (!freopen(s, "a", tracefile)) {
970 fprintf(stderr, "Can't re-open %s\n", s);
975 tracefile = fopen(s, "a");
976 if (tracefile == NULL) {
977 fprintf(stderr, "Can't open %s\n", s);
983 flags = fcntl(fileno(tracefile), F_GETFL);
985 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
987 setlinebuf(tracefile);
988 fputs("\nTracing started.\n", tracefile);
992 indent(int amount, char *pfx, FILE *fp)
996 for (i = 0; i < amount; i++) {
997 if (pfx && i == amount - 1)
1003 /* little circular references here... */
1004 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
1007 sharg(union node *arg, FILE *fp)
1010 struct nodelist *bqlist;
1011 unsigned char subtype;
1013 if (arg->type != NARG) {
1014 out1fmt("<node type %d>\n", arg->type);
1017 bqlist = arg->narg.backquote;
1018 for (p = arg->narg.text; *p; p++) {
1019 switch ((unsigned char)*p) {
1028 if (subtype == VSLENGTH)
1036 if (subtype & VSNUL)
1039 switch (subtype & VSTYPE) {
1065 case VSTRIMRIGHTMAX:
1072 out1fmt("<subtype %d>", subtype);
1081 shtree(bqlist->n, -1, NULL, fp);
1092 shcmd(union node *cmd, FILE *fp)
1100 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1106 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1110 switch (np->nfile.type) {
1111 case NTO: s = ">>"+1; dftfd = 1; break;
1112 case NCLOBBER: s = ">|"; dftfd = 1; break;
1113 case NAPPEND: s = ">>"; dftfd = 1; break;
1114 #if BASH_REDIR_OUTPUT
1117 case NTOFD: s = ">&"; dftfd = 1; break;
1118 case NFROM: s = "<"; break;
1119 case NFROMFD: s = "<&"; break;
1120 case NFROMTO: s = "<>"; break;
1121 default: s = "*error*"; break;
1123 if (np->nfile.fd != dftfd)
1124 fprintf(fp, "%d", np->nfile.fd);
1126 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1127 fprintf(fp, "%d", np->ndup.dupfd);
1129 sharg(np->nfile.fname, fp);
1136 shtree(union node *n, int ind, char *pfx, FILE *fp)
1138 struct nodelist *lp;
1144 indent(ind, pfx, fp);
1146 if (n == NODE_EOF) {
1161 shtree(n->nbinary.ch1, ind, NULL, fp);
1164 shtree(n->nbinary.ch2, ind, NULL, fp);
1172 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1173 shtree(lp->n, 0, NULL, fp);
1177 if (n->npipe.pipe_backgnd)
1183 fprintf(fp, "<node type %d>", n->type);
1191 showtree(union node *n)
1193 trace_puts("showtree called\n");
1194 shtree(n, 1, NULL, stderr);
1200 /* ============ Parser data */
1203 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1206 struct strlist *next;
1213 struct strpush *prev; /* preceding string on stack */
1215 int prev_left_in_line;
1216 #if ENABLE_ASH_ALIAS
1217 struct alias *ap; /* if push was associated with an alias */
1219 char *string; /* remember the string since it may change */
1221 /* Remember last two characters for pungetc. */
1224 /* Number of outstanding calls to pungetc. */
1229 struct parsefile *prev; /* preceding file on stack */
1230 int linno; /* current line */
1231 int pf_fd; /* file descriptor (or -1 if string) */
1232 int left_in_line; /* number of chars left in this line */
1233 int left_in_buffer; /* number of chars left in this buffer past the line */
1234 char *next_to_pgetc; /* next char in buffer */
1235 char *buf; /* input buffer */
1236 struct strpush *strpush; /* for pushing strings at this level */
1237 struct strpush basestrpush; /* so pushing one is fast */
1239 /* Remember last two characters for pungetc. */
1242 /* Number of outstanding calls to pungetc. */
1246 static struct parsefile basepf; /* top level input file */
1247 static struct parsefile *g_parsefile = &basepf; /* current input file */
1248 static int startlinno; /* line # where last token started */
1249 static char *commandname; /* currently executing command */
1250 static struct strlist *cmdenviron; /* environment for builtin command */
1253 /* ============ Message printing */
1256 ash_vmsg(const char *msg, va_list ap)
1258 fprintf(stderr, "%s: ", arg0);
1260 if (strcmp(arg0, commandname))
1261 fprintf(stderr, "%s: ", commandname);
1262 if (!iflag || g_parsefile->pf_fd > 0)
1263 fprintf(stderr, "line %d: ", startlinno);
1265 vfprintf(stderr, msg, ap);
1266 newline_and_flush(stderr);
1270 * Exverror is called to raise the error exception. If the second argument
1271 * is not NULL then error prints an error message using printf style
1272 * formatting. It then raises the error exception.
1274 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1276 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1280 TRACE(("ash_vmsg_and_raise(%d):", cond));
1283 TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
1288 flush_stdout_stderr();
1289 raise_exception(cond);
1293 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1295 ash_msg_and_raise_error(const char *msg, ...)
1302 ash_vmsg_and_raise(EXERROR, msg, ap);
1307 static void raise_error_syntax(const char *) NORETURN;
1309 raise_error_syntax(const char *msg)
1311 ash_msg_and_raise_error("syntax error: %s", msg);
1315 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1317 ash_msg_and_raise(int cond, const char *msg, ...)
1322 ash_vmsg_and_raise(cond, msg, ap);
1328 * error/warning routines for external builtins
1331 ash_msg(const char *fmt, ...)
1341 * Return a string describing an error. The returned string may be a
1342 * pointer to a static buffer that will be overwritten on the next call.
1343 * Action describes the operation that got the error.
1346 errmsg(int e, const char *em)
1348 if (e == ENOENT || e == ENOTDIR) {
1355 /* ============ Memory allocation */
1358 /* I consider these wrappers nearly useless:
1359 * ok, they return you to nearest exception handler, but
1360 * how much memory do you leak in the process, making
1361 * memory starvation worse?
1364 ckrealloc(void * p, size_t nbytes)
1366 p = realloc(p, nbytes);
1368 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1373 ckmalloc(size_t nbytes)
1375 return ckrealloc(NULL, nbytes);
1379 ckzalloc(size_t nbytes)
1381 return memset(ckmalloc(nbytes), 0, nbytes);
1385 ckstrdup(const char *s)
1387 char *p = strdup(s);
1389 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1393 /* Using bbox equivalents. They exit if out of memory */
1394 # define ckrealloc xrealloc
1395 # define ckmalloc xmalloc
1396 # define ckzalloc xzalloc
1397 # define ckstrdup xstrdup
1401 * It appears that grabstackstr() will barf with such alignments
1402 * because stalloc() will return a string allocated in a new stackblock.
1404 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1406 /* Most machines require the value returned from malloc to be aligned
1407 * in some way. The following macro will get this right
1408 * on many machines. */
1409 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1410 /* Minimum size of a block */
1411 MINSIZE = SHELL_ALIGN(504),
1414 struct stack_block {
1415 struct stack_block *prev;
1416 char space[MINSIZE];
1420 struct stack_block *stackp;
1426 struct globals_memstack {
1427 struct stack_block *g_stackp; // = &stackbase;
1428 char *g_stacknxt; // = stackbase.space;
1429 char *sstrend; // = stackbase.space + MINSIZE;
1430 size_t g_stacknleft; // = MINSIZE;
1431 struct stack_block stackbase;
1433 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1434 #define G_memstack (*ash_ptr_to_globals_memstack)
1435 #define g_stackp (G_memstack.g_stackp )
1436 #define g_stacknxt (G_memstack.g_stacknxt )
1437 #define sstrend (G_memstack.sstrend )
1438 #define g_stacknleft (G_memstack.g_stacknleft)
1439 #define stackbase (G_memstack.stackbase )
1440 #define INIT_G_memstack() do { \
1441 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1443 g_stackp = &stackbase; \
1444 g_stacknxt = stackbase.space; \
1445 g_stacknleft = MINSIZE; \
1446 sstrend = stackbase.space + MINSIZE; \
1450 #define stackblock() ((void *)g_stacknxt)
1451 #define stackblocksize() g_stacknleft
1454 * Parse trees for commands are allocated in lifo order, so we use a stack
1455 * to make this more efficient, and also to avoid all sorts of exception
1456 * handling code to handle interrupts in the middle of a parse.
1458 * The size 504 was chosen because the Ultrix malloc handles that size
1462 stalloc(size_t nbytes)
1467 aligned = SHELL_ALIGN(nbytes);
1468 if (aligned > g_stacknleft) {
1471 struct stack_block *sp;
1473 blocksize = aligned;
1474 if (blocksize < MINSIZE)
1475 blocksize = MINSIZE;
1476 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1477 if (len < blocksize)
1478 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1481 sp->prev = g_stackp;
1482 g_stacknxt = sp->space;
1483 g_stacknleft = blocksize;
1484 sstrend = g_stacknxt + blocksize;
1489 g_stacknxt += aligned;
1490 g_stacknleft -= aligned;
1495 stzalloc(size_t nbytes)
1497 return memset(stalloc(nbytes), 0, nbytes);
1504 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1505 write(STDERR_FILENO, "stunalloc\n", 10);
1509 g_stacknleft += g_stacknxt - (char *)p;
1514 * Like strdup but works with the ash stack.
1517 sstrdup(const char *p)
1519 size_t len = strlen(p) + 1;
1520 return memcpy(stalloc(len), p, len);
1524 grabstackblock(size_t len)
1530 pushstackmark(struct stackmark *mark, size_t len)
1532 mark->stackp = g_stackp;
1533 mark->stacknxt = g_stacknxt;
1534 mark->stacknleft = g_stacknleft;
1535 grabstackblock(len);
1539 setstackmark(struct stackmark *mark)
1541 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1545 popstackmark(struct stackmark *mark)
1547 struct stack_block *sp;
1553 while (g_stackp != mark->stackp) {
1555 g_stackp = sp->prev;
1558 g_stacknxt = mark->stacknxt;
1559 g_stacknleft = mark->stacknleft;
1560 sstrend = mark->stacknxt + mark->stacknleft;
1565 * When the parser reads in a string, it wants to stick the string on the
1566 * stack and only adjust the stack pointer when it knows how big the
1567 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1568 * of space on top of the stack and stackblocklen returns the length of
1569 * this block. Growstackblock will grow this space by at least one byte,
1570 * possibly moving it (like realloc). Grabstackblock actually allocates the
1571 * part of the block that has been used.
1574 growstackblock(void)
1578 newlen = g_stacknleft * 2;
1579 if (newlen < g_stacknleft)
1580 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1584 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1585 struct stack_block *sp;
1586 struct stack_block *prevstackp;
1591 prevstackp = sp->prev;
1592 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1593 sp = ckrealloc(sp, grosslen);
1594 sp->prev = prevstackp;
1596 g_stacknxt = sp->space;
1597 g_stacknleft = newlen;
1598 sstrend = sp->space + newlen;
1601 char *oldspace = g_stacknxt;
1602 size_t oldlen = g_stacknleft;
1603 char *p = stalloc(newlen);
1605 /* free the space we just allocated */
1606 g_stacknxt = memcpy(p, oldspace, oldlen);
1607 g_stacknleft += newlen;
1612 * The following routines are somewhat easier to use than the above.
1613 * The user declares a variable of type STACKSTR, which may be declared
1614 * to be a register. The macro STARTSTACKSTR initializes things. Then
1615 * the user uses the macro STPUTC to add characters to the string. In
1616 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1617 * grown as necessary. When the user is done, she can just leave the
1618 * string there and refer to it using stackblock(). Or she can allocate
1619 * the space for it using grabstackstr(). If it is necessary to allow
1620 * someone else to use the stack temporarily and then continue to grow
1621 * the string, the user should use grabstack to allocate the space, and
1622 * then call ungrabstr(p) to return to the previous mode of operation.
1624 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1625 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1626 * is space for at least one character.
1631 size_t len = stackblocksize();
1633 return (char *)stackblock() + len;
1637 * Called from CHECKSTRSPACE.
1640 makestrspace(size_t newlen, char *p)
1642 size_t len = p - g_stacknxt;
1648 size = stackblocksize();
1650 if (nleft >= newlen)
1654 return (char *)stackblock() + len;
1658 stack_nputstr(const char *s, size_t n, char *p)
1660 p = makestrspace(n, p);
1661 p = (char *)memcpy(p, s, n) + n;
1666 stack_putstr(const char *s, char *p)
1668 return stack_nputstr(s, strlen(s), p);
1672 _STPUTC(int c, char *p)
1680 #define STARTSTACKSTR(p) ((p) = stackblock())
1681 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1682 #define CHECKSTRSPACE(n, p) do { \
1685 size_t m = sstrend - q; \
1687 (p) = makestrspace(l, q); \
1689 #define USTPUTC(c, p) (*(p)++ = (c))
1690 #define STACKSTRNUL(p) do { \
1691 if ((p) == sstrend) \
1692 (p) = growstackstr(); \
1695 #define STUNPUTC(p) (--(p))
1696 #define STTOPC(p) ((p)[-1])
1697 #define STADJUST(amount, p) ((p) += (amount))
1699 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1700 #define ungrabstackstr(s, p) stunalloc(s)
1701 #define stackstrend() ((void *)sstrend)
1704 /* ============ String helpers */
1707 * prefix -- see if pfx is a prefix of string.
1710 prefix(const char *string, const char *pfx)
1713 if (*pfx++ != *string++)
1716 return (char *) string;
1720 * Check for a valid number. This should be elsewhere.
1723 is_number(const char *p)
1728 } while (*++p != '\0');
1733 * Convert a string of digits to an integer, printing an error message on
1737 number(const char *s)
1740 ash_msg_and_raise_error(msg_illnum, s);
1745 * Produce a single quoted string suitable as input to the shell.
1746 * The return string is allocated on the stack.
1749 single_quote(const char *s)
1759 len = strchrnul(s, '\'') - s;
1761 q = p = makestrspace(len + 3, p);
1764 q = (char *)memcpy(q, s, len) + len;
1773 do len++; while (*++s == '\'');
1775 q = p = makestrspace(len + 3, p);
1778 q = (char *)memcpy(q, s - len, len) + len;
1786 return stackblock();
1790 * Produce a possibly single quoted string suitable as input to the shell.
1791 * If 'conditional' is nonzero, quoting is only done if the string contains
1792 * non-shellsafe characters, or is identical to a shell keyword (reserved
1793 * word); if it is zero, quoting is always done.
1794 * If quoting was done, the return string is allocated on the stack,
1795 * otherwise a pointer to the original string is returned.
1798 maybe_single_quote(const char *s)
1803 /* Assuming ACSII */
1804 /* quote ctrl_chars space !"#$%&'()* */
1808 if (*p >= ';' && *p <= '?')
1817 /* quote {|}~ DEL and high bytes */
1820 /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
1821 /* TODO: maybe avoid quoting % */
1827 return single_quote(s);
1831 /* ============ nextopt */
1833 static char **argptr; /* argument list for builtin commands */
1834 static char *optionarg; /* set by nextopt (like getopt) */
1835 static char *optptr; /* used by nextopt */
1838 * XXX - should get rid of. Have all builtins use getopt(3).
1839 * The library getopt must have the BSD extension static variable
1840 * "optreset", otherwise it can't be used within the shell safely.
1842 * Standard option processing (a la getopt) for builtin routines.
1843 * The only argument that is passed to nextopt is the option string;
1844 * the other arguments are unnecessary. It returns the character,
1845 * or '\0' on end of input.
1848 nextopt(const char *optstring)
1855 if (p == NULL || *p == '\0') {
1856 /* We ate entire "-param", take next one */
1862 if (*++p == '\0') /* just "-" ? */
1865 if (LONE_DASH(p)) /* "--" ? */
1867 /* p => next "-param" */
1869 /* p => some option char in the middle of a "-param" */
1871 for (q = optstring; *q != c;) {
1873 ash_msg_and_raise_error("illegal option -%c", c);
1881 ash_msg_and_raise_error("no arg for -%c option", c);
1891 /* ============ Shell variables */
1894 * The parsefile structure pointed to by the global variable parsefile
1895 * contains information about the current file being read.
1898 int nparam; /* # of positional parameters (without $0) */
1899 #if ENABLE_ASH_GETOPTS
1900 int optind; /* next parameter to be processed by getopts */
1901 int optoff; /* used by getopts */
1903 unsigned char malloced; /* if parameter list dynamically allocated */
1904 char **p; /* parameter list */
1908 * Free the list of positional parameters.
1911 freeparam(volatile struct shparam *param)
1913 if (param->malloced) {
1915 ap = ap1 = param->p;
1922 #if ENABLE_ASH_GETOPTS
1923 static void FAST_FUNC getoptsreset(const char *value);
1927 struct var *next; /* next entry in hash list */
1928 int flags; /* flags are defined above */
1929 const char *var_text; /* name=value */
1930 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1931 /* the variable gets set/unset */
1935 struct localvar *next; /* next local variable in list */
1936 struct var *vp; /* the variable that was made local */
1937 int flags; /* saved flags */
1938 const char *text; /* saved text */
1942 #define VEXPORT 0x01 /* variable is exported */
1943 #define VREADONLY 0x02 /* variable cannot be modified */
1944 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1945 #define VTEXTFIXED 0x08 /* text is statically allocated */
1946 #define VSTACK 0x10 /* text is allocated on the stack */
1947 #define VUNSET 0x20 /* the variable is not set */
1948 #define VNOFUNC 0x40 /* don't call the callback function */
1949 #define VNOSET 0x80 /* do not set variable - just readonly test */
1950 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1951 #if ENABLE_ASH_RANDOM_SUPPORT
1952 # define VDYNAMIC 0x200 /* dynamic variable */
1958 /* Need to be before varinit_data[] */
1959 #if ENABLE_LOCALE_SUPPORT
1960 static void FAST_FUNC
1961 change_lc_all(const char *value)
1963 if (value && *value != '\0')
1964 setlocale(LC_ALL, value);
1966 static void FAST_FUNC
1967 change_lc_ctype(const char *value)
1969 if (value && *value != '\0')
1970 setlocale(LC_CTYPE, value);
1974 static void chkmail(void);
1975 static void changemail(const char *var_value) FAST_FUNC;
1977 # define chkmail() ((void)0)
1979 static void changepath(const char *) FAST_FUNC;
1980 #if ENABLE_ASH_RANDOM_SUPPORT
1981 static void change_random(const char *) FAST_FUNC;
1984 static const struct {
1986 const char *var_text;
1987 void (*var_func)(const char *) FAST_FUNC;
1988 } varinit_data[] = {
1990 * Note: VEXPORT would not work correctly here for NOFORK applets:
1991 * some environment strings may be constant.
1993 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1995 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1996 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1998 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1999 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
2000 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
2001 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
2002 #if ENABLE_ASH_GETOPTS
2003 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
2005 #if ENABLE_ASH_RANDOM_SUPPORT
2006 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
2008 #if ENABLE_LOCALE_SUPPORT
2009 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
2010 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
2012 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
2013 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
2019 struct globals_var {
2020 struct shparam shellparam; /* $@ current positional parameters */
2021 struct redirtab *redirlist;
2022 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
2023 struct var *vartab[VTABSIZE];
2024 struct var varinit[ARRAY_SIZE(varinit_data)];
2026 extern struct globals_var *const ash_ptr_to_globals_var;
2027 #define G_var (*ash_ptr_to_globals_var)
2028 #define shellparam (G_var.shellparam )
2029 //#define redirlist (G_var.redirlist )
2030 #define preverrout_fd (G_var.preverrout_fd)
2031 #define vartab (G_var.vartab )
2032 #define varinit (G_var.varinit )
2033 #define INIT_G_var() do { \
2035 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
2037 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
2038 varinit[i].flags = varinit_data[i].flags; \
2039 varinit[i].var_text = varinit_data[i].var_text; \
2040 varinit[i].var_func = varinit_data[i].var_func; \
2044 #define vifs varinit[0]
2046 # define vmail (&vifs)[1]
2047 # define vmpath (&vmail)[1]
2048 # define vpath (&vmpath)[1]
2050 # define vpath (&vifs)[1]
2052 #define vps1 (&vpath)[1]
2053 #define vps2 (&vps1)[1]
2054 #define vps4 (&vps2)[1]
2055 #if ENABLE_ASH_GETOPTS
2056 # define voptind (&vps4)[1]
2057 # if ENABLE_ASH_RANDOM_SUPPORT
2058 # define vrandom (&voptind)[1]
2061 # if ENABLE_ASH_RANDOM_SUPPORT
2062 # define vrandom (&vps4)[1]
2067 * The following macros access the values of the above variables.
2068 * They have to skip over the name. They return the null string
2069 * for unset variables.
2071 #define ifsval() (vifs.var_text + 4)
2072 #define ifsset() ((vifs.flags & VUNSET) == 0)
2074 # define mailval() (vmail.var_text + 5)
2075 # define mpathval() (vmpath.var_text + 9)
2076 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2078 #define pathval() (vpath.var_text + 5)
2079 #define ps1val() (vps1.var_text + 4)
2080 #define ps2val() (vps2.var_text + 4)
2081 #define ps4val() (vps4.var_text + 4)
2082 #if ENABLE_ASH_GETOPTS
2083 # define optindval() (voptind.var_text + 7)
2086 #if ENABLE_ASH_GETOPTS
2087 static void FAST_FUNC
2088 getoptsreset(const char *value)
2090 shellparam.optind = number(value) ?: 1;
2091 shellparam.optoff = -1;
2096 * Compares two strings up to the first = or '\0'. The first
2097 * string must be terminated by '='; the second may be terminated by
2098 * either '=' or '\0'.
2101 varcmp(const char *p, const char *q)
2105 while ((c = *p) == (d = *q)) {
2106 if (c == '\0' || c == '=')
2120 * Find the appropriate entry in the hash table from the name.
2122 static struct var **
2123 hashvar(const char *p)
2127 hashval = ((unsigned char) *p) << 4;
2128 while (*p && *p != '=')
2129 hashval += (unsigned char) *p++;
2130 return &vartab[hashval % VTABSIZE];
2134 vpcmp(const void *a, const void *b)
2136 return varcmp(*(const char **)a, *(const char **)b);
2140 * This routine initializes the builtin variables.
2150 * PS1 depends on uid
2152 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2153 vps1.var_text = "PS1=\\w \\$ ";
2156 vps1.var_text = "PS1=# ";
2159 end = vp + ARRAY_SIZE(varinit);
2161 vpp = hashvar(vp->var_text);
2164 } while (++vp < end);
2167 static struct var **
2168 findvar(struct var **vpp, const char *name)
2170 for (; *vpp; vpp = &(*vpp)->next) {
2171 if (varcmp((*vpp)->var_text, name) == 0) {
2179 * Find the value of a variable. Returns NULL if not set.
2181 static const char* FAST_FUNC
2182 lookupvar(const char *name)
2186 v = *findvar(hashvar(name), name);
2188 #if ENABLE_ASH_RANDOM_SUPPORT
2190 * Dynamic variables are implemented roughly the same way they are
2191 * in bash. Namely, they're "special" so long as they aren't unset.
2192 * As soon as they're unset, they're no longer dynamic, and dynamic
2193 * lookup will no longer happen at that point. -- PFM.
2195 if (v->flags & VDYNAMIC)
2198 if (!(v->flags & VUNSET))
2199 return var_end(v->var_text);
2204 #if ENABLE_UNICODE_SUPPORT
2206 reinit_unicode_for_ash(void)
2208 /* Unicode support should be activated even if LANG is set
2209 * _during_ shell execution, not only if it was set when
2210 * shell was started. Therefore, re-check LANG every time:
2212 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2213 || ENABLE_UNICODE_USING_LOCALE
2215 const char *s = lookupvar("LC_ALL");
2216 if (!s) s = lookupvar("LC_CTYPE");
2217 if (!s) s = lookupvar("LANG");
2222 # define reinit_unicode_for_ash() ((void)0)
2226 * Search the environment of a builtin command.
2229 bltinlookup(const char *name)
2233 for (sp = cmdenviron; sp; sp = sp->next) {
2234 if (varcmp(sp->text, name) == 0)
2235 return var_end(sp->text);
2237 return lookupvar(name);
2241 * Same as setvar except that the variable and value are passed in
2242 * the first argument as name=value. Since the first argument will
2243 * be actually stored in the table, it should not be a string that
2245 * Called with interrupts off.
2248 setvareq(char *s, int flags)
2250 struct var *vp, **vpp;
2253 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2254 vp = *findvar(vpp, s);
2256 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2259 if (flags & VNOSAVE)
2263 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2269 if (vp->var_func && !(flags & VNOFUNC))
2270 vp->var_func(var_end(s));
2272 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2273 free((char*)vp->var_text);
2275 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2277 /* variable s is not found */
2280 vp = ckzalloc(sizeof(*vp));
2282 /*vp->func = NULL; - ckzalloc did it */
2285 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2292 * Set the value of a variable. The flags argument is ored with the
2293 * flags of the variable. If val is NULL, the variable is unset.
2296 setvar(const char *name, const char *val, int flags)
2304 q = endofname(name);
2305 p = strchrnul(q, '=');
2307 if (!namelen || p != q)
2308 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2313 vallen = strlen(val);
2317 nameeq = ckmalloc(namelen + vallen + 2);
2318 p = mempcpy(nameeq, name, namelen);
2321 p = mempcpy(p, val, vallen);
2324 setvareq(nameeq, flags | VNOSAVE);
2328 static void FAST_FUNC
2329 setvar0(const char *name, const char *val)
2331 setvar(name, val, 0);
2335 * Unset the specified variable.
2338 unsetvar(const char *s)
2344 vpp = findvar(hashvar(s), s);
2348 int flags = vp->flags;
2351 if (flags & VREADONLY)
2353 #if ENABLE_ASH_RANDOM_SUPPORT
2354 vp->flags &= ~VDYNAMIC;
2358 if ((flags & VSTRFIXED) == 0) {
2360 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2361 free((char*)vp->var_text);
2367 vp->flags &= ~VEXPORT;
2377 * Process a linked list of variable assignments.
2380 listsetvar(struct strlist *list_set_var, int flags)
2382 struct strlist *lp = list_set_var;
2388 setvareq(lp->text, flags);
2395 * Generate a list of variables satisfying the given conditions.
2398 listvars(int on, int off, char ***end)
2409 for (vp = *vpp; vp; vp = vp->next) {
2410 if ((vp->flags & mask) == on) {
2411 if (ep == stackstrend())
2412 ep = growstackstr();
2413 *ep++ = (char*)vp->var_text;
2416 } while (++vpp < vartab + VTABSIZE);
2417 if (ep == stackstrend())
2418 ep = growstackstr();
2422 return grabstackstr(ep);
2426 /* ============ Path search helper
2428 * The variable path (passed by reference) should be set to the start
2429 * of the path before the first call; path_advance will update
2430 * this value as it proceeds. Successive calls to path_advance will return
2431 * the possible path expansions in sequence. If an option (indicated by
2432 * a percent sign) appears in the path entry then the global variable
2433 * pathopt will be set to point to it; otherwise pathopt will be set to
2436 static const char *pathopt; /* set by path_advance */
2439 path_advance(const char **path, const char *name)
2449 for (p = start; *p && *p != ':' && *p != '%'; p++)
2451 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2452 while (stackblocksize() < len)
2456 memcpy(q, start, p - start);
2464 while (*p && *p != ':')
2471 return stalloc(len);
2475 /* ============ Prompt */
2477 static smallint doprompt; /* if set, prompt the user */
2478 static smallint needprompt; /* true if interactive and at start of line */
2480 #if ENABLE_FEATURE_EDITING
2481 static line_input_t *line_input_state;
2482 static const char *cmdedit_prompt;
2484 putprompt(const char *s)
2486 if (ENABLE_ASH_EXPAND_PRMT) {
2487 free((char*)cmdedit_prompt);
2488 cmdedit_prompt = ckstrdup(s);
2495 putprompt(const char *s)
2501 /* expandstr() needs parsing machinery, so it is far away ahead... */
2502 static const char *expandstr(const char *ps);
2505 setprompt_if(smallint do_set, int whichprompt)
2508 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2515 switch (whichprompt) {
2525 #if ENABLE_ASH_EXPAND_PRMT
2526 pushstackmark(&smark, stackblocksize());
2527 putprompt(expandstr(prompt));
2528 popstackmark(&smark);
2535 /* ============ The cd and pwd commands */
2537 #define CD_PHYSICAL 1
2547 while ((i = nextopt("LP")) != '\0') {
2549 flags ^= CD_PHYSICAL;
2558 * Update curdir (the name of the current directory) in response to a
2562 updatepwd(const char *dir)
2569 cdcomppath = sstrdup(dir);
2572 if (curdir == nullstr)
2574 new = stack_putstr(curdir, new);
2576 new = makestrspace(strlen(dir) + 2, new);
2577 lim = (char *)stackblock() + 1;
2581 if (new > lim && *lim == '/')
2586 if (dir[1] == '/' && dir[2] != '/') {
2592 p = strtok(cdcomppath, "/");
2596 if (p[1] == '.' && p[2] == '\0') {
2608 new = stack_putstr(p, new);
2611 p = strtok(NULL, "/");
2616 return stackblock();
2620 * Find out what the current directory is. If we already know the current
2621 * directory, this routine returns immediately.
2626 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2627 return dir ? dir : nullstr;
2631 setpwd(const char *val, int setold)
2635 oldcur = dir = curdir;
2638 setvar("OLDPWD", oldcur, VEXPORT);
2641 if (physdir != nullstr) {
2642 if (physdir != oldcur)
2646 if (oldcur == val || !val) {
2652 dir = ckstrdup(val);
2653 if (oldcur != dir && oldcur != nullstr) {
2658 setvar("PWD", dir, VEXPORT);
2661 static void hashcd(void);
2664 * Actually do the chdir. We also call hashcd to let other routines
2665 * know that the current directory has changed.
2668 docd(const char *dest, int flags)
2670 const char *dir = NULL;
2673 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2676 if (!(flags & CD_PHYSICAL)) {
2677 dir = updatepwd(dest);
2691 static int FAST_FUNC
2692 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2704 dest = bltinlookup("HOME");
2705 else if (LONE_DASH(dest)) {
2706 dest = bltinlookup("OLDPWD");
2728 path = bltinlookup("CDPATH");
2731 p = path_advance(&path, dest);
2732 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2736 if (!docd(p, flags))
2747 ash_msg_and_raise_error("can't cd to %s", dest);
2750 if (flags & CD_PRINT)
2751 out1fmt("%s\n", curdir);
2755 static int FAST_FUNC
2756 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2759 const char *dir = curdir;
2763 if (physdir == nullstr)
2767 out1fmt("%s\n", dir);
2772 /* ============ ... */
2775 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2777 /* Syntax classes */
2778 #define CWORD 0 /* character is nothing special */
2779 #define CNL 1 /* newline character */
2780 #define CBACK 2 /* a backslash character */
2781 #define CSQUOTE 3 /* single quote */
2782 #define CDQUOTE 4 /* double quote */
2783 #define CENDQUOTE 5 /* a terminating quote */
2784 #define CBQUOTE 6 /* backwards single quote */
2785 #define CVAR 7 /* a dollar sign */
2786 #define CENDVAR 8 /* a '}' character */
2787 #define CLP 9 /* a left paren in arithmetic */
2788 #define CRP 10 /* a right paren in arithmetic */
2789 #define CENDFILE 11 /* end of file */
2790 #define CCTL 12 /* like CWORD, except it must be escaped */
2791 #define CSPCL 13 /* these terminate a word */
2792 #define CIGN 14 /* character should be ignored */
2795 #if ENABLE_ASH_ALIAS
2799 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2801 #if ENABLE_FEATURE_SH_MATH
2802 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2804 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2806 static const uint16_t S_I_T[] ALIGN2 = {
2807 #if ENABLE_ASH_ALIAS
2808 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2810 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2811 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2812 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2813 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2814 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2815 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2816 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2817 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2818 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2819 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2820 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2821 #if !USE_SIT_FUNCTION
2822 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2823 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2824 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2828 /* Constants below must match table above */
2830 #if ENABLE_ASH_ALIAS
2831 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2833 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2834 CNL_CNL_CNL_CNL , /* 2 */
2835 CWORD_CCTL_CCTL_CWORD , /* 3 */
2836 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2837 CVAR_CVAR_CWORD_CVAR , /* 5 */
2838 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2839 CSPCL_CWORD_CWORD_CLP , /* 7 */
2840 CSPCL_CWORD_CWORD_CRP , /* 8 */
2841 CBACK_CBACK_CCTL_CBACK , /* 9 */
2842 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2843 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2844 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2845 CWORD_CWORD_CWORD_CWORD , /* 13 */
2846 CCTL_CCTL_CCTL_CCTL , /* 14 */
2849 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2850 * caller must ensure proper cast on it if c is *char_ptr!
2852 /* Values for syntax param */
2853 #define BASESYNTAX 0 /* not in quotes */
2854 #define DQSYNTAX 1 /* in double quotes */
2855 #define SQSYNTAX 2 /* in single quotes */
2856 #define ARISYNTAX 3 /* in arithmetic */
2857 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2859 #if USE_SIT_FUNCTION
2862 SIT(int c, int syntax)
2864 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2865 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2867 * This causes '/' to be prepended with CTLESC in dquoted string,
2868 * making "./file"* treated incorrectly because we feed
2869 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2870 * The "homegrown" glob implementation is okay with that,
2871 * but glibc one isn't. With '/' always treated as CWORD,
2874 # if ENABLE_ASH_ALIAS
2875 static const uint8_t syntax_index_table[] ALIGN1 = {
2876 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2877 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2878 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2882 static const uint8_t syntax_index_table[] ALIGN1 = {
2883 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2884 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2885 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2894 # if ENABLE_ASH_ALIAS
2900 /* Cast is purely for paranoia here,
2901 * just in case someone passed signed char to us */
2902 if ((unsigned char)c >= CTL_FIRST
2903 && (unsigned char)c <= CTL_LAST
2907 s = strchrnul(spec_symbls, c);
2910 indx = syntax_index_table[s - spec_symbls];
2912 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2915 #else /* !USE_SIT_FUNCTION */
2917 static const uint8_t syntax_index_table[] ALIGN1 = {
2918 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2919 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2929 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2930 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2952 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2953 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2954 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2956 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2958 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2959 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2960 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2961 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2962 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2964 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2965 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2966 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2967 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2979 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2980 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2981 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2982 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2983 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2984 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
3006 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
3007 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
3008 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
3009 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
3010 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
3011 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
3012 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
3013 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
3014 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
3015 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
3016 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
3017 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
3018 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
3019 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
3020 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
3021 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
3022 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
3023 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
3024 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
3025 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
3026 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
3027 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3028 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3029 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3030 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3031 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3032 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3033 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3034 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3035 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3036 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3037 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3038 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3039 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3040 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3041 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3042 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3043 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3044 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3045 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3046 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3047 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3048 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3050 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3051 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3052 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3053 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3054 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3055 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3056 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3057 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3120 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3121 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3122 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3123 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3124 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3125 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3126 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3127 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3128 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3129 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3130 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3131 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3132 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3133 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3134 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3135 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3136 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3137 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3138 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3139 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3140 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3141 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3142 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3143 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3144 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3145 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3146 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3147 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3148 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3149 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3150 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3151 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3152 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3153 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3154 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3155 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3156 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3157 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3158 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3159 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3160 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3161 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3162 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3163 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3164 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3165 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3166 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3167 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3168 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3169 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3170 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3171 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3172 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3173 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3174 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3175 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3176 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3177 # if ENABLE_ASH_ALIAS
3178 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3183 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3184 #else /* debug version, caught one signed char bug */
3185 # define SIT(c, syntax) \
3187 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3188 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3189 if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
3190 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3191 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3195 #endif /* !USE_SIT_FUNCTION */
3198 /* ============ Alias handling */
3200 #if ENABLE_ASH_ALIAS
3202 #define ALIASINUSE 1
3213 static struct alias **atab; // [ATABSIZE];
3214 #define INIT_G_alias() do { \
3215 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3219 static struct alias **
3220 __lookupalias(const char *name)
3222 unsigned int hashval;
3229 ch = (unsigned char)*p;
3233 ch = (unsigned char)*++p;
3235 app = &atab[hashval % ATABSIZE];
3237 for (; *app; app = &(*app)->next) {
3238 if (strcmp(name, (*app)->name) == 0) {
3246 static struct alias *
3247 lookupalias(const char *name, int check)
3249 struct alias *ap = *__lookupalias(name);
3251 if (check && ap && (ap->flag & ALIASINUSE))
3256 static struct alias *
3257 freealias(struct alias *ap)
3261 if (ap->flag & ALIASINUSE) {
3262 ap->flag |= ALIASDEAD;
3274 setalias(const char *name, const char *val)
3276 struct alias *ap, **app;
3278 app = __lookupalias(name);
3282 if (!(ap->flag & ALIASINUSE)) {
3285 ap->val = ckstrdup(val);
3286 ap->flag &= ~ALIASDEAD;
3289 ap = ckzalloc(sizeof(struct alias));
3290 ap->name = ckstrdup(name);
3291 ap->val = ckstrdup(val);
3292 /*ap->flag = 0; - ckzalloc did it */
3293 /*ap->next = NULL;*/
3300 unalias(const char *name)
3304 app = __lookupalias(name);
3308 *app = freealias(*app);
3319 struct alias *ap, **app;
3323 for (i = 0; i < ATABSIZE; i++) {
3325 for (ap = *app; ap; ap = *app) {
3326 *app = freealias(*app);
3336 printalias(const struct alias *ap)
3338 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3342 * TODO - sort output
3344 static int FAST_FUNC
3345 aliascmd(int argc UNUSED_PARAM, char **argv)
3354 for (i = 0; i < ATABSIZE; i++) {
3355 for (ap = atab[i]; ap; ap = ap->next) {
3361 while ((n = *++argv) != NULL) {
3362 v = strchr(n+1, '=');
3363 if (v == NULL) { /* n+1: funny ksh stuff */
3364 ap = *__lookupalias(n);
3366 fprintf(stderr, "%s: %s not found\n", "alias", n);
3379 static int FAST_FUNC
3380 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3384 while (nextopt("a") != '\0') {
3388 for (i = 0; *argptr; argptr++) {
3389 if (unalias(*argptr)) {
3390 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3398 #endif /* ASH_ALIAS */
3401 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3404 #define FORK_NOJOB 2
3406 /* mode flags for showjob(s) */
3407 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3408 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3409 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3410 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3413 * A job structure contains information about a job. A job is either a
3414 * single process or a set of processes contained in a pipeline. In the
3415 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3419 pid_t ps_pid; /* process id */
3420 int ps_status; /* last process status from wait() */
3421 char *ps_cmd; /* text of command being run */
3425 struct procstat ps0; /* status of process */
3426 struct procstat *ps; /* status or processes when more than one */
3428 int stopstatus; /* status of a stopped job */
3430 unsigned nprocs; /* number of processes */
3432 #define JOBRUNNING 0 /* at least one proc running */
3433 #define JOBSTOPPED 1 /* all procs are stopped */
3434 #define JOBDONE 2 /* all procs are completed */
3438 sigint: 1, /* job was killed by SIGINT */
3439 jobctl: 1, /* job running under job control */
3441 waited: 1, /* true if this entry has been waited for */
3442 used: 1, /* true if this entry is in used */
3443 changed: 1; /* true if status has changed */
3444 struct job *prev_job; /* previous job */
3447 static struct job *makejob(/*union node *,*/ int);
3448 static int forkshell(struct job *, union node *, int);
3449 static int waitforjob(struct job *);
3452 enum { doing_jobctl = 0 };
3453 #define setjobctl(on) do {} while (0)
3455 static smallint doing_jobctl; //references:8
3456 static void setjobctl(int);
3463 ignoresig(int signo)
3465 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3466 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3467 /* No, need to do it */
3468 signal(signo, SIG_IGN);
3470 sigmode[signo - 1] = S_HARD_IGN;
3474 * Only one usage site - in setsignal()
3477 signal_handler(int signo)
3479 if (signo == SIGCHLD) {
3485 gotsig[signo - 1] = 1;
3486 pending_sig = signo;
3488 if (signo == SIGINT && !trap[SIGINT]) {
3489 if (!suppress_int) {
3491 raise_interrupt(); /* does not return */
3498 * Set the signal handler for the specified signal. The routine figures
3499 * out what it should be set to.
3502 setsignal(int signo)
3505 char cur_act, new_act;
3506 struct sigaction act;
3510 if (t != NULL) { /* trap for this sig is set */
3512 if (t[0] == '\0') /* trap is "": ignore this sig */
3516 if (rootshell && new_act == S_DFL) {
3519 if (iflag || minusc || sflag == 0)
3528 * "In all cases, bash ignores SIGQUIT. Non-builtin
3529 * commands run by bash have signal handlers
3530 * set to the values inherited by the shell
3531 * from its parent". */
3547 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3548 //whereas we have to restore it to what shell got on entry
3549 //from the parent. See comment above
3551 if (signo == SIGCHLD)
3554 t = &sigmode[signo - 1];
3557 /* current setting is not yet known */
3558 if (sigaction(signo, NULL, &act)) {
3559 /* pretend it worked; maybe we should give a warning,
3560 * but other shells don't. We don't alter sigmode,
3561 * so we retry every time.
3562 * btw, in Linux it never fails. --vda */
3565 if (act.sa_handler == SIG_IGN) {
3566 cur_act = S_HARD_IGN;
3568 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3570 cur_act = S_IGN; /* don't hard ignore these */
3574 if (cur_act == S_HARD_IGN || cur_act == new_act)
3577 act.sa_handler = SIG_DFL;
3580 act.sa_handler = signal_handler;
3583 act.sa_handler = SIG_IGN;
3587 /* flags and mask matter only if !DFL and !IGN, but we do it
3588 * for all cases for more deterministic behavior:
3591 sigfillset(&act.sa_mask);
3593 sigaction_set(signo, &act);
3598 /* mode flags for set_curjob */
3599 #define CUR_DELETE 2
3600 #define CUR_RUNNING 1
3601 #define CUR_STOPPED 0
3604 /* pgrp of shell on invocation */
3605 static int initialpgrp; //references:2
3606 static int ttyfd = -1; //5
3609 static struct job *jobtab; //5
3611 static unsigned njobs; //4
3613 static struct job *curjob; //lots
3614 /* number of presumed living untracked jobs */
3615 static int jobless; //4
3618 /* Bash has a feature: it restores termios after a successful wait for
3619 * a foreground job which had at least one stopped or sigkilled member.
3620 * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
3621 * properly restoring tty state. Should we do this too?
3622 * A reproducer: ^Z an interactive python:
3625 * Python 2.7.12 (...)
3627 * { python leaves tty in -icanon -echo state. We do survive that... }
3628 * [1]+ Stopped python
3629 * { ...however, next program (python #2) does not survive it well: }
3631 * Python 2.7.12 (...)
3632 * >>> Traceback (most recent call last):
3633 * { above, I typed "qwerty<CR>", but -echo state is still in effect }
3634 * File "<stdin>", line 1, in <module>
3635 * NameError: name 'qwerty' is not defined
3637 * The implementation below is modeled on bash code and seems to work.
3638 * However, I'm not sure we should do this. For one: what if I'd fg
3639 * the stopped python instead? It'll be confused by "restored" tty state.
3641 static struct termios shell_tty_info;
3645 if (rootshell && ttyfd >= 0)
3646 tcgetattr(ttyfd, &shell_tty_info);
3651 /* if (rootshell) - caller ensures this */
3653 tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
3656 job_signal_status(struct job *jp)
3660 struct procstat *ps = jp->ps;
3661 for (i = 0; i < jp->nprocs; i++) {
3662 status = ps[i].ps_status;
3663 if (WIFSIGNALED(status) || WIFSTOPPED(status))
3669 restore_tty_if_stopped_or_signaled(struct job *jp)
3671 //TODO: check what happens if we come from waitforjob() in expbackq()
3673 int s = job_signal_status(jp);
3674 if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
3679 # define get_tty_state() ((void)0)
3680 # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
3684 set_curjob(struct job *jp, unsigned mode)
3687 struct job **jpp, **curp;
3689 /* first remove from list */
3690 jpp = curp = &curjob;
3695 jpp = &jp1->prev_job;
3697 *jpp = jp1->prev_job;
3699 /* Then re-insert in correct position */
3707 /* job being deleted */
3710 /* newly created job or backgrounded job,
3711 * put after all stopped jobs.
3716 if (!jp1 || jp1->state != JOBSTOPPED)
3719 jpp = &jp1->prev_job;
3725 /* newly stopped job - becomes curjob */
3726 jp->prev_job = *jpp;
3734 jobno(const struct job *jp)
3736 return jp - jobtab + 1;
3741 * Convert a job name to a job structure.
3744 #define getjob(name, getctl) getjob(name)
3747 getjob(const char *name, int getctl)
3751 const char *err_msg = "%s: no such job";
3755 char *(*match)(const char *, const char *);
3770 if (c == '+' || c == '%') {
3772 err_msg = "No current job";
3778 err_msg = "No previous job";
3788 if (num > 0 && num <= njobs) {
3789 jp = jobtab + num - 1;
3804 if (match(jp->ps[0].ps_cmd, p)) {
3808 err_msg = "%s: ambiguous";
3818 err_msg = "job %s not created under job control";
3819 if (getctl && jp->jobctl == 0)
3824 ash_msg_and_raise_error(err_msg, name);
3828 * Mark a job structure as unused.
3831 freejob(struct job *jp)
3833 struct procstat *ps;
3837 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3838 if (ps->ps_cmd != nullstr)
3841 if (jp->ps != &jp->ps0)
3844 set_curjob(jp, CUR_DELETE);
3850 xtcsetpgrp(int fd, pid_t pgrp)
3852 if (tcsetpgrp(fd, pgrp))
3853 ash_msg_and_raise_error("can't set tty process group (%m)");
3857 * Turn job control on and off.
3859 * Note: This code assumes that the third arg to ioctl is a character
3860 * pointer, which is true on Berkeley systems but not System V. Since
3861 * System V doesn't have job control yet, this isn't a problem now.
3863 * Called with interrupts off.
3871 if (on == doing_jobctl || rootshell == 0)
3875 ofd = fd = open(_PATH_TTY, O_RDWR);
3877 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3878 * That sometimes helps to acquire controlling tty.
3879 * Obviously, a workaround for bugs when someone
3880 * failed to provide a controlling tty to bash! :) */
3886 /* fd is a tty at this point */
3887 fd = fcntl(fd, F_DUPFD, 10);
3888 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
3891 goto out; /* F_DUPFD failed */
3892 close_on_exec_on(fd);
3893 while (1) { /* while we are in the background */
3894 pgrp = tcgetpgrp(fd);
3897 ash_msg("can't access tty; job control turned off");
3901 if (pgrp == getpgrp())
3912 xtcsetpgrp(fd, pgrp);
3914 /* turning job control off */
3917 /* was xtcsetpgrp, but this can make exiting ash
3918 * loop forever if pty is already deleted */
3919 tcsetpgrp(fd, pgrp);
3933 static int FAST_FUNC
3934 killcmd(int argc, char **argv)
3936 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3939 if (argv[i][0] == '%') {
3941 * "kill %N" - job kill
3942 * Converting to pgrp / pid kill
3948 jp = getjob(argv[i], 0);
3950 * In jobs started under job control, we signal
3951 * entire process group by kill -PGRP_ID.
3952 * This happens, f.e., in interactive shell.
3954 * Otherwise, we signal each child via
3955 * kill PID1 PID2 PID3.
3957 * sh -c 'sleep 1|sleep 1 & kill %1'
3958 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3959 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3961 n = jp->nprocs; /* can't be 0 (I hope) */
3964 dst = alloca(n * sizeof(int)*4);
3966 for (j = 0; j < n; j++) {
3967 struct procstat *ps = &jp->ps[j];
3968 /* Skip non-running and not-stopped members
3969 * (i.e. dead members) of the job
3971 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3974 * kill_main has matching code to expect
3975 * leading space. Needed to not confuse
3976 * negative pids with "kill -SIGNAL_NO" syntax
3978 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3982 } while (argv[++i]);
3984 return kill_main(argc, argv);
3988 showpipe(struct job *jp /*, FILE *out*/)
3990 struct procstat *ps;
3991 struct procstat *psend;
3993 psend = jp->ps + jp->nprocs;
3994 for (ps = jp->ps + 1; ps < psend; ps++)
3995 printf(" | %s", ps->ps_cmd);
3996 newline_and_flush(stdout);
3997 flush_stdout_stderr();
4002 restartjob(struct job *jp, int mode)
4004 struct procstat *ps;
4010 if (jp->state == JOBDONE)
4012 jp->state = JOBRUNNING;
4013 pgid = jp->ps[0].ps_pid;
4014 if (mode == FORK_FG) {
4016 xtcsetpgrp(ttyfd, pgid);
4018 killpg(pgid, SIGCONT);
4022 if (WIFSTOPPED(ps->ps_status)) {
4028 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
4033 static int FAST_FUNC
4034 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
4040 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
4044 jp = getjob(*argv, 1);
4045 if (mode == FORK_BG) {
4046 set_curjob(jp, CUR_RUNNING);
4047 printf("[%d] ", jobno(jp));
4049 out1str(jp->ps[0].ps_cmd);
4050 showpipe(jp /*, stdout*/);
4051 retval = restartjob(jp, mode);
4052 } while (*argv && *++argv);
4058 sprint_status48(char *s, int status, int sigonly)
4064 if (!WIFEXITED(status)) {
4066 if (WIFSTOPPED(status))
4067 st = WSTOPSIG(status);
4070 st = WTERMSIG(status);
4072 if (st == SIGINT || st == SIGPIPE)
4075 if (WIFSTOPPED(status))
4080 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
4081 col = fmtstr(s, 32, strsignal(st));
4082 if (WCOREDUMP(status)) {
4083 strcpy(s + col, " (core dumped)");
4084 col += sizeof(" (core dumped)")-1;
4086 } else if (!sigonly) {
4087 st = WEXITSTATUS(status);
4088 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
4095 wait_block_or_sig(int *status)
4102 /* Poll all children for changes in their state */
4104 /* if job control is active, accept stopped processes too */
4105 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
4107 break; /* Error (e.g. EINTR, ECHILD) or pid */
4109 /* Children exist, but none are ready. Sleep until interesting signal */
4112 sigprocmask(SIG_SETMASK, &mask, &mask);
4113 while (!got_sigchld && !pending_sig)
4115 sigprocmask(SIG_SETMASK, &mask, NULL);
4116 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
4117 while (!got_sigchld && !pending_sig)
4121 /* If it was SIGCHLD, poll children again */
4122 } while (got_sigchld);
4127 #define DOWAIT_NONBLOCK 0
4128 #define DOWAIT_BLOCK 1
4129 #define DOWAIT_BLOCK_OR_SIG 2
4132 dowait(int block, struct job *job)
4137 struct job *thisjob = NULL;
4139 TRACE(("dowait(0x%x) called\n", block));
4141 /* It's wrong to call waitpid() outside of INT_OFF region:
4142 * signal can arrive just after syscall return and handler can
4143 * longjmp away, losing stop/exit notification processing.
4144 * Thus, for "jobs" builtin, and for waiting for a fg job,
4145 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4147 * However, for "wait" builtin it is wrong to simply call waitpid()
4148 * in INT_OFF region: "wait" needs to wait for any running job
4149 * to change state, but should exit on any trap too.
4150 * In INT_OFF region, a signal just before syscall entry can set
4151 * pending_sig variables, but we can't check them, and we would
4152 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4154 * Because of this, we run inside INT_OFF, but use a special routine
4155 * which combines waitpid() and sigsuspend().
4156 * This is the reason why we need to have a handler for SIGCHLD:
4157 * SIG_DFL handler does not wake sigsuspend().
4160 if (block == DOWAIT_BLOCK_OR_SIG) {
4161 pid = wait_block_or_sig(&status);
4164 if (block == DOWAIT_NONBLOCK)
4165 wait_flags = WNOHANG;
4166 /* if job control is active, accept stopped processes too */
4168 wait_flags |= WUNTRACED;
4169 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4170 pid = waitpid(-1, &status, wait_flags);
4172 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4173 pid, status, errno, strerror(errno)));
4178 for (jp = curjob; jp; jp = jp->prev_job) {
4180 struct procstat *ps;
4181 struct procstat *psend;
4182 if (jp->state == JOBDONE)
4186 psend = ps + jp->nprocs;
4188 if (ps->ps_pid == pid) {
4189 TRACE(("Job %d: changing status of proc %d "
4190 "from 0x%x to 0x%x\n",
4191 jobno(jp), pid, ps->ps_status, status));
4192 ps->ps_status = status;
4195 if (ps->ps_status == -1)
4196 jobstate = JOBRUNNING;
4198 if (jobstate == JOBRUNNING)
4200 if (WIFSTOPPED(ps->ps_status)) {
4201 jp->stopstatus = ps->ps_status;
4202 jobstate = JOBSTOPPED;
4205 } while (++ps < psend);
4209 /* Found the job where one of its processes changed its state.
4210 * Is there at least one live and running process in this job? */
4211 if (jobstate != JOBRUNNING) {
4212 /* No. All live processes in the job are stopped
4213 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4215 thisjob->changed = 1;
4216 if (thisjob->state != jobstate) {
4217 TRACE(("Job %d: changing state from %d to %d\n",
4218 jobno(thisjob), thisjob->state, jobstate));
4219 thisjob->state = jobstate;
4221 if (jobstate == JOBSTOPPED)
4222 set_curjob(thisjob, CUR_STOPPED);
4228 /* The process wasn't found in job list */
4230 if (!WIFSTOPPED(status))
4236 if (thisjob && thisjob == job) {
4240 len = sprint_status48(s, status, 1);
4252 showjob(struct job *jp, int mode)
4254 struct procstat *ps;
4255 struct procstat *psend;
4258 char s[16 + 16 + 48];
4259 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4263 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4264 /* just output process (group) id of pipeline */
4265 fprintf(out, "%d\n", ps->ps_pid);
4269 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4274 else if (curjob && jp == curjob->prev_job)
4277 if (mode & SHOW_PIDS)
4278 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4280 psend = ps + jp->nprocs;
4282 if (jp->state == JOBRUNNING) {
4283 strcpy(s + col, "Running");
4284 col += sizeof("Running") - 1;
4286 int status = psend[-1].ps_status;
4287 if (jp->state == JOBSTOPPED)
4288 status = jp->stopstatus;
4289 col += sprint_status48(s + col, status, 0);
4291 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4293 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4294 * or prints several "PID | <cmdN>" lines,
4295 * depending on SHOW_PIDS bit.
4296 * We do not print status of individual processes
4297 * between PID and <cmdN>. bash does it, but not very well:
4298 * first line shows overall job status, not process status,
4299 * making it impossible to know 1st process status.
4303 /* for each process */
4306 if (mode & SHOW_PIDS)
4307 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4309 fprintf(out, "%s%*c%s%s",
4311 33 - col >= 0 ? 33 - col : 0, ' ',
4312 ps == jp->ps ? "" : "| ",
4315 } while (++ps != psend);
4316 newline_and_flush(out);
4320 if (jp->state == JOBDONE) {
4321 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4327 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4328 * statuses have changed since the last call to showjobs.
4335 TRACE(("showjobs(0x%x) called\n", mode));
4337 /* Handle all finished jobs */
4338 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4341 for (jp = curjob; jp; jp = jp->prev_job) {
4342 if (!(mode & SHOW_CHANGED) || jp->changed) {
4348 static int FAST_FUNC
4349 jobscmd(int argc UNUSED_PARAM, char **argv)
4354 while ((m = nextopt("lp")) != '\0') {
4358 mode |= SHOW_ONLY_PGID;
4364 showjob(getjob(*argv, 0), mode);
4374 /* Called only on finished or stopped jobs (no members are running) */
4376 getstatus(struct job *job)
4380 struct procstat *ps;
4382 /* Fetch last member's status */
4383 ps = job->ps + job->nprocs - 1;
4384 status = ps->ps_status;
4386 /* "set -o pipefail" mode: use last _nonzero_ status */
4387 while (status == 0 && --ps >= job->ps)
4388 status = ps->ps_status;
4391 retval = WEXITSTATUS(status);
4392 if (!WIFEXITED(status)) {
4394 retval = WSTOPSIG(status);
4395 if (!WIFSTOPPED(status))
4398 /* XXX: limits number of signals */
4399 retval = WTERMSIG(status);
4401 if (retval == SIGINT)
4407 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4408 jobno(job), job->nprocs, status, retval));
4412 static int FAST_FUNC
4413 waitcmd(int argc UNUSED_PARAM, char **argv)
4424 /* wait for all jobs */
4428 if (!jp) /* no running procs */
4430 if (jp->state == JOBRUNNING)
4436 * "When bash is waiting for an asynchronous command via
4437 * the wait builtin, the reception of a signal for which a trap
4438 * has been set will cause the wait builtin to return immediately
4439 * with an exit status greater than 128, immediately after which
4440 * the trap is executed."
4442 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4443 /* if child sends us a signal *and immediately exits*,
4444 * dowait() returns pid > 0. Check this case,
4445 * not "if (dowait() < 0)"!
4454 if (**argv != '%') {
4455 pid_t pid = number(*argv);
4460 if (job->ps[job->nprocs - 1].ps_pid == pid)
4462 job = job->prev_job;
4465 job = getjob(*argv, 0);
4467 /* loop until process terminated or stopped */
4468 while (job->state == JOBRUNNING) {
4469 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4474 retval = getstatus(job);
4481 retval = 128 + pending_sig;
4490 struct job *jp, *jq;
4492 len = njobs * sizeof(*jp);
4494 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4496 offset = (char *)jp - (char *)jq;
4498 /* Relocate pointers */
4501 jq = (struct job *)((char *)jq + l);
4505 #define joff(p) ((struct job *)((char *)(p) + l))
4506 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4507 if (joff(jp)->ps == &jq->ps0)
4508 jmove(joff(jp)->ps);
4509 if (joff(jp)->prev_job)
4510 jmove(joff(jp)->prev_job);
4520 jp = (struct job *)((char *)jp + len);
4524 } while (--jq >= jp);
4529 * Return a new job structure.
4530 * Called with interrupts off.
4533 makejob(/*union node *node,*/ int nprocs)
4538 for (i = njobs, jp = jobtab; ; jp++) {
4545 if (jp->state != JOBDONE || !jp->waited)
4554 memset(jp, 0, sizeof(*jp));
4556 /* jp->jobctl is a bitfield.
4557 * "jp->jobctl |= doing_jobctl" likely to give awful code */
4561 jp->prev_job = curjob;
4566 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4568 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4575 * Return a string identifying a command (to be printed by the
4578 static char *cmdnextc;
4581 cmdputs(const char *s)
4583 static const char vstype[VSTYPE + 1][3] = {
4584 "", "}", "-", "+", "?", "=",
4585 "%", "%%", "#", "##"
4586 IF_BASH_SUBSTR(, ":")
4587 IF_BASH_PATTERN_SUBST(, "/", "//")
4590 const char *p, *str;
4594 unsigned char subtype = 0;
4598 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4600 while ((c = *p++) != '\0') {
4608 if ((subtype & VSTYPE) == VSLENGTH)
4614 str = "\"}" + !(quoted & 1);
4621 #if ENABLE_FEATURE_SH_MATH
4636 if ((subtype & VSTYPE) != VSNORMAL)
4638 str = vstype[subtype & VSTYPE];
4639 if (subtype & VSNUL)
4648 /* These can only happen inside quotes */
4661 while ((c = *str++) != '\0') {
4664 } /* while *p++ not NUL */
4667 USTPUTC('"', nextc);
4673 /* cmdtxt() and cmdlist() call each other */
4674 static void cmdtxt(union node *n);
4677 cmdlist(union node *np, int sep)
4679 for (; np; np = np->narg.next) {
4683 if (sep && np->narg.next)
4689 cmdtxt(union node *n)
4692 struct nodelist *lp;
4703 lp = n->npipe.cmdlist;
4721 cmdtxt(n->nbinary.ch1);
4737 cmdtxt(n->nif.test);
4739 if (n->nif.elsepart) {
4740 cmdtxt(n->nif.ifpart);
4742 n = n->nif.elsepart;
4760 cmdtxt(n->nbinary.ch1);
4770 cmdputs(n->nfor.var);
4772 cmdlist(n->nfor.args, 1);
4777 cmdputs(n->narg.text);
4781 cmdlist(n->ncmd.args, 1);
4782 cmdlist(n->ncmd.redirect, 0);
4795 cmdputs(n->ncase.expr->narg.text);
4797 for (np = n->ncase.cases; np; np = np->nclist.next) {
4798 cmdtxt(np->nclist.pattern);
4800 cmdtxt(np->nclist.body);
4814 #if BASH_REDIR_OUTPUT
4829 cmdputs(utoa(n->nfile.fd));
4831 if (n->type == NTOFD || n->type == NFROMFD) {
4832 cmdputs(utoa(n->ndup.dupfd));
4841 commandtext(union node *n)
4845 STARTSTACKSTR(cmdnextc);
4847 name = stackblock();
4848 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4849 return ckstrdup(name);
4854 * Fork off a subshell. If we are doing job control, give the subshell its
4855 * own process group. Jp is a job structure that the job is to be added to.
4856 * N is the command that will be evaluated by the child. Both jp and n may
4857 * be NULL. The mode parameter can be one of the following:
4858 * FORK_FG - Fork off a foreground process.
4859 * FORK_BG - Fork off a background process.
4860 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4861 * process group even if job control is on.
4863 * When job control is turned off, background processes have their standard
4864 * input redirected to /dev/null (except for the second and later processes
4867 * Called with interrupts off.
4870 * Clear traps on a fork.
4878 for (tp = trap; tp < &trap[NSIG]; tp++) {
4879 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4880 if (trap_ptr == trap)
4882 /* else: it "belongs" to trap_ptr vector, don't free */
4884 if ((tp - trap) != 0)
4885 setsignal(tp - trap);
4892 /* Lives far away from here, needed for forkchild */
4893 static void closescript(void);
4895 /* Called after fork(), in child */
4896 /* jp and n are NULL when called by openhere() for heredoc support */
4897 static NOINLINE void
4898 forkchild(struct job *jp, union node *n, int mode)
4902 TRACE(("Child shell %d\n", getpid()));
4906 /* man bash: "Non-builtin commands run by bash have signal handlers
4907 * set to the values inherited by the shell from its parent".
4908 * Do we do it correctly? */
4912 if (mode == FORK_NOJOB /* is it `xxx` ? */
4913 && n && n->type == NCMD /* is it single cmd? */
4914 /* && n->ncmd.args->type == NARG - always true? */
4915 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4916 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4917 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4919 TRACE(("Trap hack\n"));
4920 /* Awful hack for `trap` or $(trap).
4922 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4923 * contains an example where "trap" is executed in a subshell:
4925 * save_traps=$(trap)
4927 * eval "$save_traps"
4929 * Standard does not say that "trap" in subshell shall print
4930 * parent shell's traps. It only says that its output
4931 * must have suitable form, but then, in the above example
4932 * (which is not supposed to be normative), it implies that.
4934 * bash (and probably other shell) does implement it
4935 * (traps are reset to defaults, but "trap" still shows them),
4936 * but as a result, "trap" logic is hopelessly messed up:
4939 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4940 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4941 * # true | trap <--- trap is in subshell - no output (ditto)
4942 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4943 * trap -- 'echo Ho' SIGWINCH
4944 * # echo `(trap)` <--- in subshell in subshell - output
4945 * trap -- 'echo Ho' SIGWINCH
4946 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4947 * trap -- 'echo Ho' SIGWINCH
4949 * The rules when to forget and when to not forget traps
4950 * get really complex and nonsensical.
4952 * Our solution: ONLY bare $(trap) or `trap` is special.
4954 /* Save trap handler strings for trap builtin to print */
4955 trap_ptr = xmemdup(trap, sizeof(trap));
4956 /* Fall through into clearing traps */
4960 /* do job control only in root shell */
4962 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4965 if (jp->nprocs == 0)
4968 pgrp = jp->ps[0].ps_pid;
4969 /* this can fail because we are doing it in the parent also */
4971 if (mode == FORK_FG)
4972 xtcsetpgrp(ttyfd, pgrp);
4977 if (mode == FORK_BG) {
4978 /* man bash: "When job control is not in effect,
4979 * asynchronous commands ignore SIGINT and SIGQUIT" */
4982 if (jp->nprocs == 0) {
4984 if (open(bb_dev_null, O_RDONLY) != 0)
4985 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4989 if (iflag) { /* why if iflag only? */
4994 * "In all cases, bash ignores SIGQUIT. Non-builtin
4995 * commands run by bash have signal handlers
4996 * set to the values inherited by the shell
4998 * Take care of the second rule: */
5002 if (n && n->type == NCMD
5003 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
5005 TRACE(("Job hack\n"));
5006 /* "jobs": we do not want to clear job list for it,
5007 * instead we remove only _its_ own_ job from job list.
5008 * This makes "jobs .... | cat" more useful.
5014 for (jp = curjob; jp; jp = jp->prev_job)
5019 /* Called after fork(), in parent */
5021 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
5024 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
5026 TRACE(("In parent shell: child = %d\n", pid));
5028 /* jp is NULL when called by openhere() for heredoc support */
5029 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
5035 if (mode != FORK_NOJOB && jp->jobctl) {
5038 if (jp->nprocs == 0)
5041 pgrp = jp->ps[0].ps_pid;
5042 /* This can fail because we are doing it in the child also */
5046 if (mode == FORK_BG) {
5047 backgndpid = pid; /* set $! */
5048 set_curjob(jp, CUR_RUNNING);
5051 struct procstat *ps = &jp->ps[jp->nprocs++];
5054 ps->ps_cmd = nullstr;
5056 if (doing_jobctl && n)
5057 ps->ps_cmd = commandtext(n);
5062 /* jp and n are NULL when called by openhere() for heredoc support */
5064 forkshell(struct job *jp, union node *n, int mode)
5068 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
5071 TRACE(("Fork failed, errno=%d", errno));
5074 ash_msg_and_raise_error("can't fork");
5077 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
5078 forkchild(jp, n, mode);
5080 forkparent(jp, n, mode, pid);
5086 * Wait for job to finish.
5088 * Under job control we have the problem that while a child process
5089 * is running interrupts generated by the user are sent to the child
5090 * but not to the shell. This means that an infinite loop started by
5091 * an interactive user may be hard to kill. With job control turned off,
5092 * an interactive user may place an interactive program inside a loop.
5093 * If the interactive program catches interrupts, the user doesn't want
5094 * these interrupts to also abort the loop. The approach we take here
5095 * is to have the shell ignore interrupt signals while waiting for a
5096 * foreground process to terminate, and then send itself an interrupt
5097 * signal if the child process was terminated by an interrupt signal.
5098 * Unfortunately, some programs want to do a bit of cleanup and then
5099 * exit on interrupt; unless these processes terminate themselves by
5100 * sending a signal to themselves (instead of calling exit) they will
5101 * confuse this approach.
5103 * Called with interrupts off.
5106 waitforjob(struct job *jp)
5110 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
5113 while (jp->state == JOBRUNNING) {
5114 /* In non-interactive shells, we _can_ get
5115 * a keyboard signal here and be EINTRed,
5116 * but we just loop back, waiting for command to complete.
5119 * "If bash is waiting for a command to complete and receives
5120 * a signal for which a trap has been set, the trap
5121 * will not be executed until the command completes."
5123 * Reality is that even if trap is not set, bash
5124 * will not act on the signal until command completes.
5125 * Try this. sleep5intoff.c:
5126 * #include <signal.h>
5127 * #include <unistd.h>
5130 * sigemptyset(&set);
5131 * sigaddset(&set, SIGINT);
5132 * sigaddset(&set, SIGQUIT);
5133 * sigprocmask(SIG_BLOCK, &set, NULL);
5137 * $ bash -c './sleep5intoff; echo hi'
5138 * ^C^C^C^C <--- pressing ^C once a second
5140 * $ bash -c './sleep5intoff; echo hi'
5141 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5144 dowait(DOWAIT_BLOCK, jp);
5151 xtcsetpgrp(ttyfd, rootpid);
5152 restore_tty_if_stopped_or_signaled(jp);
5155 * This is truly gross.
5156 * If we're doing job control, then we did a TIOCSPGRP which
5157 * caused us (the shell) to no longer be in the controlling
5158 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5159 * intuit from the subprocess exit status whether a SIGINT
5160 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5162 if (jp->sigint) /* TODO: do the same with all signals */
5163 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5165 if (jp->state == JOBDONE)
5172 * return 1 if there are stopped jobs, otherwise 0
5184 if (jp && jp->state == JOBSTOPPED) {
5185 out2str("You have stopped jobs.\n");
5195 * Code for dealing with input/output redirection.
5200 #define EMPTY -2 /* marks an unused slot in redirtab */
5201 #define CLOSED -3 /* marks a slot of previously-closed fd */
5204 * Open a file in noclobber mode.
5205 * The code was copied from bash.
5208 noclobberopen(const char *fname)
5211 struct stat finfo, finfo2;
5214 * If the file exists and is a regular file, return an error
5217 r = stat(fname, &finfo);
5218 if (r == 0 && S_ISREG(finfo.st_mode)) {
5224 * If the file was not present (r != 0), make sure we open it
5225 * exclusively so that if it is created before we open it, our open
5226 * will fail. Make sure that we do not truncate an existing file.
5227 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5228 * file was not a regular file, we leave O_EXCL off.
5231 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5232 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5234 /* If the open failed, return the file descriptor right away. */
5239 * OK, the open succeeded, but the file may have been changed from a
5240 * non-regular file to a regular file between the stat and the open.
5241 * We are assuming that the O_EXCL open handles the case where FILENAME
5242 * did not exist and is symlinked to an existing file between the stat
5247 * If we can open it and fstat the file descriptor, and neither check
5248 * revealed that it was a regular file, and the file has not been
5249 * replaced, return the file descriptor.
5251 if (fstat(fd, &finfo2) == 0
5252 && !S_ISREG(finfo2.st_mode)
5253 && finfo.st_dev == finfo2.st_dev
5254 && finfo.st_ino == finfo2.st_ino
5259 /* The file has been replaced. badness. */
5266 * Handle here documents. Normally we fork off a process to write the
5267 * data to a pipe. If the document is short, we can stuff the data in
5268 * the pipe without forking.
5270 /* openhere needs this forward reference */
5271 static void expandhere(union node *arg, int fd);
5273 openhere(union node *redir)
5279 ash_msg_and_raise_error("pipe call failed");
5280 if (redir->type == NHERE) {
5281 len = strlen(redir->nhere.doc->narg.text);
5282 if (len <= PIPE_BUF) {
5283 full_write(pip[1], redir->nhere.doc->narg.text, len);
5287 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5290 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5291 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5292 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5293 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5294 signal(SIGPIPE, SIG_DFL);
5295 if (redir->type == NHERE)
5296 full_write(pip[1], redir->nhere.doc->narg.text, len);
5298 expandhere(redir->nhere.doc, pip[1]);
5299 _exit(EXIT_SUCCESS);
5307 openredirect(union node *redir)
5312 switch (redir->nfile.type) {
5313 /* Can't happen, our single caller does this itself */
5319 return openhere(redir);
5322 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5323 * allocated space. Do it only when we know it is safe.
5325 fname = redir->nfile.expfname;
5327 switch (redir->nfile.type) {
5333 f = open(fname, O_RDONLY);
5338 f = open(fname, O_RDWR|O_CREAT, 0666);
5343 #if BASH_REDIR_OUTPUT
5346 /* Take care of noclobber mode. */
5348 f = noclobberopen(fname);
5355 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5360 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5368 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5370 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5374 * Copy a file descriptor to be >= 10. Throws exception on error.
5382 newfd = fcntl(from, F_DUPFD, 10);
5383 err = newfd < 0 ? errno : 0;
5386 ash_msg_and_raise_error("%d: %m", from);
5388 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5394 dup2_or_raise(int from, int to)
5398 newfd = (from != to) ? dup2(from, to) : to;
5400 /* Happens when source fd is not open: try "echo >&99" */
5401 ash_msg_and_raise_error("%d: %m", from);
5406 /* Struct def and variable are moved down to the first usage site */
5411 struct redirtab *next;
5413 struct two_fd_t two_fd[];
5415 #define redirlist (G_var.redirlist)
5417 COPYFD_RESTORE = (int)~(INT_MAX),
5421 need_to_remember(struct redirtab *rp, int fd)
5425 if (!rp) /* remembering was not requested */
5428 for (i = 0; i < rp->pair_count; i++) {
5429 if (rp->two_fd[i].orig == fd) {
5430 /* already remembered */
5437 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5439 is_hidden_fd(struct redirtab *rp, int fd)
5442 struct parsefile *pf;
5446 /* Check open scripts' fds */
5449 /* We skip pf_fd == 0 case because of the following case:
5450 * $ ash # running ash interactively
5452 * and in script.sh: "exec 9>&0".
5453 * Even though top-level pf_fd _is_ 0,
5454 * it's still ok to use it: "read" builtin uses it,
5455 * why should we cripple "exec" builtin?
5457 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5465 /* Check saved fds of redirects */
5466 fd |= COPYFD_RESTORE;
5467 for (i = 0; i < rp->pair_count; i++) {
5468 if (rp->two_fd[i].copy == fd) {
5476 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5477 * old file descriptors are stashed away so that the redirection can be
5478 * undone by calling popredir.
5480 /* flags passed to redirect */
5481 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5482 #define REDIR_SAVEFD2 03 /* set preverrout */
5484 redirect(union node *redir, int flags)
5486 struct redirtab *sv;
5491 int copied_fd2 = -1;
5500 if (flags & REDIR_PUSH) {
5501 union node *tmp = redir;
5504 #if BASH_REDIR_OUTPUT
5505 if (tmp->nfile.type == NTO2)
5508 tmp = tmp->nfile.next;
5510 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5511 sv->next = redirlist;
5512 sv->pair_count = sv_pos;
5514 while (sv_pos > 0) {
5516 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5522 fd = redir->nfile.fd;
5523 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5524 right_fd = redir->ndup.dupfd;
5525 //bb_error_msg("doing %d > %d", fd, right_fd);
5526 /* redirect from/to same file descriptor? */
5529 /* "echo >&10" and 10 is a fd opened to a sh script? */
5530 if (is_hidden_fd(sv, right_fd)) {
5531 errno = EBADF; /* as if it is closed */
5532 ash_msg_and_raise_error("%d: %m", right_fd);
5536 newfd = openredirect(redir); /* always >= 0 */
5538 /* Descriptor wasn't open before redirect.
5539 * Mark it for close in the future */
5540 if (need_to_remember(sv, fd)) {
5541 goto remember_to_close;
5546 #if BASH_REDIR_OUTPUT
5549 if (need_to_remember(sv, fd)) {
5550 /* Copy old descriptor */
5551 /* Careful to not accidentally "save"
5552 * to the same fd as right side fd in N>&M */
5553 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5554 #if defined(F_DUPFD_CLOEXEC)
5555 i = fcntl(fd, F_DUPFD_CLOEXEC, minfd);
5557 i = fcntl(fd, F_DUPFD, minfd);
5562 /* Strange error (e.g. "too many files" EMFILE?) */
5566 ash_msg_and_raise_error("%d: %m", fd);
5569 /* EBADF: it is not open - good, remember to close it */
5572 } else { /* fd is open, save its copy */
5573 #if !defined(F_DUPFD_CLOEXEC)
5574 fcntl(i, F_SETFD, FD_CLOEXEC);
5576 /* "exec fd>&-" should not close fds
5577 * which point to script file(s).
5578 * Force them to be restored afterwards */
5579 if (is_hidden_fd(sv, fd))
5580 i |= COPYFD_RESTORE;
5584 sv->two_fd[sv_pos].orig = fd;
5585 sv->two_fd[sv_pos].copy = i;
5589 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5590 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5591 /* Don't want to trigger debugging */
5595 dup2_or_raise(redir->ndup.dupfd, fd);
5597 } else if (fd != newfd) { /* move newfd to fd */
5598 dup2_or_raise(newfd, fd);
5599 #if BASH_REDIR_OUTPUT
5600 if (!(redir->nfile.type == NTO2 && fd == 2))
5604 #if BASH_REDIR_OUTPUT
5605 if (redir->nfile.type == NTO2 && fd == 1) {
5606 /* We already redirected it to fd 1, now copy it to 2 */
5612 } while ((redir = redir->nfile.next) != NULL);
5615 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5616 preverrout_fd = copied_fd2;
5620 * Undo the effects of the last redirection.
5623 popredir(int drop, int restore)
5625 struct redirtab *rp;
5628 if (redirlist == NULL)
5632 for (i = 0; i < rp->pair_count; i++) {
5633 int fd = rp->two_fd[i].orig;
5634 int copy = rp->two_fd[i].copy;
5635 if (copy == CLOSED) {
5640 if (copy != EMPTY) {
5641 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5642 copy &= ~COPYFD_RESTORE;
5644 dup2_or_raise(copy, fd);
5646 close(copy & ~COPYFD_RESTORE);
5649 redirlist = rp->next;
5655 * Undo all redirections. Called on error or interrupt.
5659 redirectsafe(union node *redir, int flags)
5662 volatile int saveint;
5663 struct jmploc *volatile savehandler = exception_handler;
5664 struct jmploc jmploc;
5667 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5668 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5670 exception_handler = &jmploc;
5671 redirect(redir, flags);
5673 exception_handler = savehandler;
5674 if (err && exception_type != EXERROR)
5675 longjmp(exception_handler->loc, 1);
5676 RESTORE_INT(saveint);
5681 /* ============ Routines to expand arguments to commands
5683 * We have to deal with backquotes, shell variables, and file metacharacters.
5686 #if ENABLE_FEATURE_SH_MATH
5688 ash_arith(const char *s)
5690 arith_state_t math_state;
5693 math_state.lookupvar = lookupvar;
5694 math_state.setvar = setvar0;
5695 //math_state.endofname = endofname;
5698 result = arith(&math_state, s);
5699 if (math_state.errmsg)
5700 ash_msg_and_raise_error(math_state.errmsg);
5710 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5711 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5712 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5713 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5714 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5715 * POSIX says for this case:
5716 * Pathname expansion shall not be performed on the word by a
5717 * non-interactive shell; an interactive shell may perform it, but shall
5718 * do so only when the expansion would result in one word.
5719 * Currently, our code complies to the above rule by never globbing
5720 * redirection filenames.
5721 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5722 * (this means that on a typical Linux distro, bash almost always
5723 * performs globbing, and thus diverges from what we do).
5725 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5726 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5727 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5728 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5729 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5733 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5734 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5735 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5736 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5737 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5739 /* Add CTLESC when necessary. */
5740 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5741 /* Do not skip NUL characters. */
5742 #define QUOTES_KEEPNUL EXP_TILDE
5745 * Structure specifying which parts of the string should be searched
5746 * for IFS characters.
5749 struct ifsregion *next; /* next region in list */
5750 int begoff; /* offset of start of region */
5751 int endoff; /* offset of end of region */
5752 int nulonly; /* search for nul bytes only */
5756 struct strlist *list;
5757 struct strlist **lastp;
5760 /* output of current string */
5761 static char *expdest;
5762 /* list of back quote expressions */
5763 static struct nodelist *argbackq;
5764 /* first struct in list of ifs regions */
5765 static struct ifsregion ifsfirst;
5766 /* last struct in list */
5767 static struct ifsregion *ifslastp;
5768 /* holds expanded arg list */
5769 static struct arglist exparg;
5774 #if !ENABLE_FEATURE_SH_MATH
5775 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5776 typedef long arith_t;
5777 # define ARITH_FMT "%ld"
5784 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5785 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5786 STADJUST(len, expdest);
5791 * Break the argument string into pieces based upon IFS and add the
5792 * strings to the argument list. The regions of the string to be
5793 * searched for IFS characters have been stored by recordregion.
5796 ifsbreakup(char *string, struct arglist *arglist)
5798 struct ifsregion *ifsp;
5803 const char *ifs, *realifs;
5808 if (ifslastp != NULL) {
5811 realifs = ifsset() ? ifsval() : defifs;
5814 p = string + ifsp->begoff;
5815 nulonly = ifsp->nulonly;
5816 ifs = nulonly ? nullstr : realifs;
5818 while (p < string + ifsp->endoff) {
5820 if ((unsigned char)*p == CTLESC)
5822 if (!strchr(ifs, *p)) {
5827 ifsspc = (strchr(defifs, *p) != NULL);
5828 /* Ignore IFS whitespace at start */
5829 if (q == start && ifsspc) {
5835 sp = stzalloc(sizeof(*sp));
5837 *arglist->lastp = sp;
5838 arglist->lastp = &sp->next;
5842 if (p >= string + ifsp->endoff) {
5846 if ((unsigned char)*p == CTLESC)
5848 if (strchr(ifs, *p) == NULL) {
5852 if (strchr(defifs, *p) == NULL) {
5867 } while (ifsp != NULL);
5876 sp = stzalloc(sizeof(*sp));
5878 *arglist->lastp = sp;
5879 arglist->lastp = &sp->next;
5885 struct ifsregion *p = ifsfirst.next;
5892 struct ifsregion *ifsp;
5897 ifsfirst.next = NULL;
5904 esclen(const char *start, const char *p)
5908 while (p > start && (unsigned char)*--p == CTLESC) {
5915 * Remove any CTLESC characters from a string.
5918 rmescapes(char *str, int flag)
5920 static const char qchars[] ALIGN1 = {
5921 IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
5925 unsigned protect_against_glob;
5927 IF_BASH_PATTERN_SUBST(unsigned slash = flag & RMESCAPE_SLASH;)
5929 p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash));
5935 if (flag & RMESCAPE_ALLOC) {
5936 size_t len = p - str;
5937 size_t fulllen = len + strlen(p) + 1;
5939 if (flag & RMESCAPE_GROW) {
5940 int strloc = str - (char *)stackblock();
5941 r = makestrspace(fulllen, expdest);
5942 /* p and str may be invalidated by makestrspace */
5943 str = (char *)stackblock() + strloc;
5945 } else if (flag & RMESCAPE_HEAP) {
5946 r = ckmalloc(fulllen);
5948 r = stalloc(fulllen);
5952 q = (char *)memcpy(q, str, len) + len;
5957 globbing = flag & RMESCAPE_GLOB;
5958 protect_against_glob = globbing;
5960 if ((unsigned char)*p == CTLQUOTEMARK) {
5961 // Note: both inquotes and protect_against_glob only affect whether
5962 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5963 inquotes = ~inquotes;
5965 protect_against_glob = globbing;
5968 if ((unsigned char)*p == CTLESC) {
5972 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5974 if (protect_against_glob) {
5976 * We used to trust glob() and fnmatch() to eat
5977 * superfluous escapes (\z where z has no
5978 * special meaning anyway). But this causes
5979 * bugs such as string of one greek letter rho
5980 * (unicode-encoded as two bytes "cf,81")
5981 * getting encoded as "cf,CTLESC,81"
5982 * and here, converted to "cf,\,81" -
5983 * which does not go well with some flavors
5984 * of fnmatch() in unicode locales
5985 * (for example, glibc <= 2.22).
5987 * Lets add "\" only on the chars which need it.
5988 * Testcases for less obvious chars are shown.
5993 || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
5994 || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
5995 || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
5996 || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
5997 /* Some libc support [^negate], that's why "^" also needs love */
5998 || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
6003 } else if (*p == '\\' && !inquotes) {
6004 /* naked back slash */
6005 protect_against_glob = 0;
6008 #if BASH_PATTERN_SUBST
6009 else if (*p == '/' && slash) {
6010 /* stop handling globbing and mark location of slash */
6011 globbing = slash = 0;
6015 protect_against_glob = globbing;
6020 if (flag & RMESCAPE_GROW) {
6022 STADJUST(q - r + 1, expdest);
6026 #define pmatch(a, b) !fnmatch((a), (b), 0)
6029 * Prepare a pattern for a expmeta (internal glob(3)) call.
6031 * Returns an stalloced string.
6034 preglob(const char *pattern, int flag)
6036 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
6040 * Put a string on the stack.
6043 memtodest(const char *p, size_t len, int syntax, int quotes)
6050 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
6053 unsigned char c = *p++;
6055 if (quotes & QUOTES_ESC) {
6056 int n = SIT(c, syntax);
6058 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
6065 } else if (!(quotes & QUOTES_KEEPNUL))
6074 strtodest(const char *p, int syntax, int quotes)
6076 size_t len = strlen(p);
6077 memtodest(p, len, syntax, quotes);
6082 * Record the fact that we have to scan this region of the
6083 * string for IFS characters.
6086 recordregion(int start, int end, int nulonly)
6088 struct ifsregion *ifsp;
6090 if (ifslastp == NULL) {
6094 ifsp = ckzalloc(sizeof(*ifsp));
6095 /*ifsp->next = NULL; - ckzalloc did it */
6096 ifslastp->next = ifsp;
6100 ifslastp->begoff = start;
6101 ifslastp->endoff = end;
6102 ifslastp->nulonly = nulonly;
6106 removerecordregions(int endoff)
6108 if (ifslastp == NULL)
6111 if (ifsfirst.endoff > endoff) {
6112 while (ifsfirst.next) {
6113 struct ifsregion *ifsp;
6115 ifsp = ifsfirst.next->next;
6116 free(ifsfirst.next);
6117 ifsfirst.next = ifsp;
6120 if (ifsfirst.begoff > endoff) {
6123 ifslastp = &ifsfirst;
6124 ifsfirst.endoff = endoff;
6129 ifslastp = &ifsfirst;
6130 while (ifslastp->next && ifslastp->next->begoff < endoff)
6131 ifslastp = ifslastp->next;
6132 while (ifslastp->next) {
6133 struct ifsregion *ifsp;
6135 ifsp = ifslastp->next->next;
6136 free(ifslastp->next);
6137 ifslastp->next = ifsp;
6140 if (ifslastp->endoff > endoff)
6141 ifslastp->endoff = endoff;
6145 exptilde(char *startp, char *p, int flags)
6151 int quotes = flags & QUOTES_ESC;
6155 while ((c = *++p) != '\0') {
6162 if (flags & EXP_VARTILDE)
6172 if (*name == '\0') {
6173 home = lookupvar("HOME");
6175 pw = getpwnam(name);
6180 if (!home || !*home)
6183 strtodest(home, SQSYNTAX, quotes);
6191 * Execute a command inside back quotes. If it's a builtin command, we
6192 * want to save its output in a block obtained from malloc. Otherwise
6193 * we fork off a subprocess and get the output of the command via a pipe.
6194 * Should be called with interrupts off.
6196 struct backcmd { /* result of evalbackcmd */
6197 int fd; /* file descriptor to read from */
6198 int nleft; /* number of chars in buffer */
6199 char *buf; /* buffer */
6200 struct job *jp; /* job structure for command */
6203 /* These forward decls are needed to use "eval" code for backticks handling: */
6204 #define EV_EXIT 01 /* exit after evaluating tree */
6205 static int evaltree(union node *, int);
6207 static void FAST_FUNC
6208 evalbackcmd(union node *n, struct backcmd *result)
6222 ash_msg_and_raise_error("pipe call failed");
6223 jp = makejob(/*n,*/ 1);
6224 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6230 dup2_or_raise(pip[1], 1);
6233 /* TODO: eflag clearing makes the following not abort:
6234 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6235 * which is what bash does (unless it is in POSIX mode).
6236 * dash deleted "eflag = 0" line in the commit
6237 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6238 * [EVAL] Don't clear eflag in evalbackcmd
6239 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6243 evaltree(n, EV_EXIT); /* actually evaltreenr... */
6248 result->fd = pip[0];
6252 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6253 result->fd, result->buf, result->nleft, result->jp));
6257 * Expand stuff in backwards quotes.
6260 expbackq(union node *cmd, int flag)
6268 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6269 struct stackmark smark;
6272 startloc = expdest - (char *)stackblock();
6273 pushstackmark(&smark, startloc);
6274 evalbackcmd(cmd, &in);
6275 popstackmark(&smark);
6282 memtodest(p, i, syntax, flag & QUOTES_ESC);
6286 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6287 TRACE(("expbackq: read returns %d\n", i));
6296 back_exitstatus = waitforjob(in.jp);
6300 /* Eat all trailing newlines */
6302 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6306 if (!(flag & EXP_QUOTED))
6307 recordregion(startloc, dest - (char *)stackblock(), 0);
6308 TRACE(("evalbackq: size:%d:'%.*s'\n",
6309 (int)((dest - (char *)stackblock()) - startloc),
6310 (int)((dest - (char *)stackblock()) - startloc),
6311 stackblock() + startloc));
6314 #if ENABLE_FEATURE_SH_MATH
6316 * Expand arithmetic expression. Backup to start of expression,
6317 * evaluate, place result in (backed up) result, adjust string position.
6329 * This routine is slightly over-complicated for
6330 * efficiency. Next we scan backwards looking for the
6331 * start of arithmetic.
6333 start = stackblock();
6340 while ((unsigned char)*p != CTLARI) {
6344 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6349 esc = esclen(start, p);
6359 removerecordregions(begoff);
6363 if (flag & QUOTES_ESC)
6364 rmescapes(p + 1, 0);
6366 len = cvtnum(ash_arith(p + 1));
6368 if (!(flag & EXP_QUOTED))
6369 recordregion(begoff, begoff + len, 0);
6373 /* argstr needs it */
6374 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6377 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6378 * characters to allow for further processing. Otherwise treat
6379 * $@ like $* since no splitting will be performed.
6381 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6382 * over shell variables. Needed for "A=a B=$A; echo $B" case - we use it
6383 * for correct expansion of "B=$A" word.
6386 argstr(char *p, int flags, struct strlist *var_str_list)
6388 static const char spclchars[] ALIGN1 = {
6396 #if ENABLE_FEATURE_SH_MATH
6401 const char *reject = spclchars;
6402 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6407 if (!(flags & EXP_VARTILDE)) {
6409 } else if (flags & EXP_VARTILDE2) {
6414 if (flags & EXP_TILDE) {
6417 flags &= ~EXP_TILDE;
6421 p = exptilde(p, q, flags);
6424 startloc = expdest - (char *)stackblock();
6428 length += strcspn(p + length, reject);
6432 IF_FEATURE_SH_MATH(|| c == CTLENDARI)
6434 /* c == '=' || c == ':' || c == CTLENDARI */
6440 expdest = stack_nputstr(p, length, expdest);
6441 newloc = expdest - (char *)stackblock();
6442 if (breakall && !inquotes && newloc > startloc) {
6443 recordregion(startloc, newloc, 0);
6454 if (flags & EXP_VARTILDE2) {
6458 flags |= EXP_VARTILDE2;
6463 * sort of a hack - expand tildes in variable
6464 * assignments (after the first '=' and after ':'s).
6473 case CTLENDVAR: /* ??? */
6476 inquotes ^= EXP_QUOTED;
6477 /* "$@" syntax adherence hack */
6478 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6479 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6483 if (flags & QUOTES_ESC) {
6494 * Quoted parameter expansion pattern: remove quote
6495 * unless inside inner quotes or we have a literal
6498 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6499 EXP_QPAT && *p != '\\')
6504 TRACE(("argstr: evalvar('%s')\n", p));
6505 p = evalvar(p, flags | inquotes, var_str_list);
6506 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6509 expbackq(argbackq->n, flags | inquotes);
6510 argbackq = argbackq->next;
6512 #if ENABLE_FEATURE_SH_MATH
6515 expari(flags | inquotes);
6524 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6525 char *pattern, int quotes, int zero)
6534 const char *s = loc2;
6541 match = pmatch(pattern, s);
6546 if (quotes && (unsigned char)*loc == CTLESC)
6555 scanright(char *startp, char *rmesc, char *rmescend,
6556 char *pattern, int quotes, int match_at_start)
6558 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6559 int try2optimize = match_at_start;
6565 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6566 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6567 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6569 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6570 * and on each iteration they go back two/one char until they reach the beginning.
6571 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6573 /* TODO: document in what other circumstances we are called. */
6575 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6578 const char *s = loc2;
6579 if (match_at_start) {
6583 match = pmatch(pattern, s);
6584 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6588 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6590 /* Maybe we can optimize this:
6591 * if pattern ends with unescaped *, we can avoid checking
6592 * shorter strings: if "foo*" doesn't match "raw_value_of_v",
6593 * it won't match truncated "raw_value_of_" strings too.
6595 unsigned plen = strlen(pattern);
6596 /* Does it end with "*"? */
6597 if (plen != 0 && pattern[--plen] == '*') {
6598 /* "xxxx*" is not escaped */
6599 /* "xxx\*" is escaped */
6600 /* "xx\\*" is not escaped */
6601 /* "x\\\*" is escaped */
6603 while (plen != 0 && pattern[--plen] == '\\')
6606 break; /* ends with unescaped "*" */
6614 esc = esclen(startp, loc);
6625 static void varunset(const char *, const char *, const char *, int) NORETURN;
6627 varunset(const char *end, const char *var, const char *umsg, int varflags)
6633 msg = "parameter not set";
6635 if ((unsigned char)*end == CTLENDVAR) {
6636 if (varflags & VSNUL)
6642 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6646 subevalvar(char *p, char *varname, int strloc, int subtype,
6647 int startloc, int varflags, int flag, struct strlist *var_str_list)
6649 struct nodelist *saveargbackq = argbackq;
6650 int quotes = flag & QUOTES_ESC;
6653 char *rmesc, *rmescend;
6655 int amount, resetloc;
6656 IF_BASH_PATTERN_SUBST(int workloc;)
6657 IF_BASH_PATTERN_SUBST(char *repl = NULL;)
6659 char *(*scan)(char*, char*, char*, char*, int, int);
6661 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6662 // p, varname, strloc, subtype, startloc, varflags, quotes);
6664 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6665 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6667 STPUTC('\0', expdest);
6668 argbackq = saveargbackq;
6669 startp = (char *)stackblock() + startloc;
6673 setvar0(varname, startp);
6674 amount = startp - expdest;
6675 STADJUST(amount, expdest);
6679 varunset(p, varname, startp, varflags);
6684 int pos, len, orig_len;
6687 loc = str = stackblock() + strloc;
6689 # if !ENABLE_FEATURE_SH_MATH
6690 # define ash_arith number
6692 /* Read POS in ${var:POS:LEN} */
6693 colon = strchr(loc, ':');
6694 if (colon) *colon = '\0';
6695 pos = ash_arith(loc);
6696 if (colon) *colon = ':';
6698 /* Read LEN in ${var:POS:LEN} */
6699 len = str - startp - 1;
6700 /* *loc != '\0', guaranteed by parser */
6704 /* Adjust the length by the number of escapes */
6705 for (ptr = startp; ptr < (str - 1); ptr++) {
6706 if ((unsigned char)*ptr == CTLESC) {
6713 if (*loc++ == ':') {
6715 len = ash_arith(loc);
6717 /* Skip POS in ${var:POS:LEN} */
6719 while (*loc && *loc != ':') {
6722 if (*loc++ == ':') {
6723 len = ash_arith(loc);
6729 /* ${VAR:$((-n)):l} starts n chars from the end */
6730 pos = orig_len + pos;
6732 if ((unsigned)pos >= orig_len) {
6733 /* apart from obvious ${VAR:999999:l},
6734 * covers ${VAR:$((-9999999)):l} - result is ""
6741 /* ${VAR:N:-M} sets LEN to strlen()-M */
6742 len = (orig_len - pos) + len;
6744 if ((unsigned)len > (orig_len - pos))
6745 len = orig_len - pos;
6747 for (str = startp; pos; str++, pos--) {
6748 if (quotes && (unsigned char)*str == CTLESC)
6751 for (loc = startp; len; len--) {
6752 if (quotes && (unsigned char)*str == CTLESC)
6757 amount = loc - expdest;
6758 STADJUST(amount, expdest);
6761 #endif /* BASH_SUBSTR */
6764 resetloc = expdest - (char *)stackblock();
6766 #if BASH_PATTERN_SUBST
6767 /* We'll comeback here if we grow the stack while handling
6768 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6769 * stack will need rebasing, and we'll need to remove our work
6775 amount = expdest - ((char *)stackblock() + resetloc);
6776 STADJUST(-amount, expdest);
6777 startp = (char *)stackblock() + startloc;
6780 rmescend = (char *)stackblock() + strloc;
6782 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6783 if (rmesc != startp) {
6785 startp = (char *)stackblock() + startloc;
6789 str = (char *)stackblock() + strloc;
6791 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6792 * The result is a_\_z_c (not a\_\_z_c)!
6794 * The search pattern and replace string treat backslashes differently!
6795 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6796 * and string. It's only used on the first call.
6798 preglob(str, IF_BASH_PATTERN_SUBST(
6799 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6800 RMESCAPE_SLASH : ) 0);
6802 #if BASH_PATTERN_SUBST
6803 workloc = expdest - (char *)stackblock();
6804 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6809 repl = strchr(str, CTLESC);
6815 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6817 /* If there's no pattern to match, return the expansion unmolested */
6826 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6827 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6829 /* No match, advance */
6830 char *restart_detect = stackblock();
6832 STPUTC(*idx, expdest);
6833 if (quotes && (unsigned char)*idx == CTLESC) {
6836 STPUTC(*idx, expdest);
6838 if (stackblock() != restart_detect)
6843 /* continue; - prone to quadratic behavior, smarter code: */
6846 if (str[0] == '*') {
6847 /* Pattern is "*foo". If "*foo" does not match "long_string",
6848 * it would never match "ong_string" etc, no point in trying.
6855 if (subtype == VSREPLACEALL) {
6857 if (quotes && (unsigned char)*idx == CTLESC)
6866 //bb_error_msg("repl:'%s'", repl);
6867 for (loc = (char*)repl; *loc; loc++) {
6868 char *restart_detect = stackblock();
6869 if (quotes && *loc == '\\') {
6870 STPUTC(CTLESC, expdest);
6873 STPUTC(*loc, expdest);
6874 if (stackblock() != restart_detect)
6879 if (subtype == VSREPLACE) {
6880 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6882 char *restart_detect = stackblock();
6883 STPUTC(*idx, expdest);
6884 if (stackblock() != restart_detect)
6893 /* We've put the replaced text into a buffer at workloc, now
6894 * move it to the right place and adjust the stack.
6896 STPUTC('\0', expdest);
6897 startp = (char *)stackblock() + startloc;
6898 memmove(startp, (char *)stackblock() + workloc, len + 1);
6899 //bb_error_msg("startp:'%s'", startp);
6900 amount = expdest - (startp + len);
6901 STADJUST(-amount, expdest);
6904 #endif /* BASH_PATTERN_SUBST */
6906 subtype -= VSTRIMRIGHT;
6908 if (subtype < 0 || subtype > 7)
6911 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6912 zero = subtype >> 1;
6913 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6914 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6916 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6919 memmove(startp, loc, str - loc);
6920 loc = startp + (str - loc) - 1;
6923 amount = loc - expdest;
6924 STADJUST(amount, expdest);
6930 * Add the value of a specialized variable to the stack string.
6931 * name parameter (examples):
6932 * ash -c 'echo $1' name:'1='
6933 * ash -c 'echo $qwe' name:'qwe='
6934 * ash -c 'echo $$' name:'$='
6935 * ash -c 'echo ${$}' name:'$='
6936 * ash -c 'echo ${$##q}' name:'$=q'
6937 * ash -c 'echo ${#$}' name:'$='
6938 * note: examples with bad shell syntax:
6939 * ash -c 'echo ${#$1}' name:'$=1'
6940 * ash -c 'echo ${#1#}' name:'1=#'
6942 static NOINLINE ssize_t
6943 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list, int *quotedp)
6950 int quoted = *quotedp;
6951 int subtype = varflags & VSTYPE;
6952 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6953 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6956 sep = (flags & EXP_FULL) << CHAR_BIT;
6957 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6967 num = shellparam.nparam;
6975 goto check_1char_name;
6977 expdest = makestrspace(NOPTS, expdest);
6978 for (i = NOPTS - 1; i >= 0; i--) {
6980 USTPUTC(optletters(i), expdest);
6986 /* handles cases similar to ${#$1} */
6987 if (name[2] != '\0')
6988 raise_error_syntax("bad substitution");
7001 sep |= ifsset() ? ifsval()[0] : ' ';
7008 while ((p = *ap++) != NULL) {
7009 len += strtodest(p, syntax, quotes);
7013 memtodest(&sepc, 1, syntax, quotes);
7028 num = atoi(name); /* number(name) fails on ${N#str} etc */
7029 if (num < 0 || num > shellparam.nparam)
7031 p = num ? shellparam.p[num - 1] : arg0;
7034 /* NB: name has form "VAR=..." */
7036 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
7037 * which should be considered before we check variables. */
7039 unsigned name_len = (strchrnul(name, '=') - name) + 1;
7043 str = var_str_list->text;
7044 eq = strchr(str, '=');
7045 if (!eq) /* stop at first non-assignment */
7048 if (name_len == (unsigned)(eq - str)
7049 && strncmp(str, name, name_len) == 0
7052 /* goto value; - WRONG! */
7053 /* think "A=1 A=2 B=$A" */
7055 var_str_list = var_str_list->next;
7056 } while (var_str_list);
7060 p = lookupvar(name);
7065 len = strtodest(p, syntax, quotes);
7066 #if ENABLE_UNICODE_SUPPORT
7067 if (subtype == VSLENGTH && len > 0) {
7068 reinit_unicode_for_ash();
7069 if (unicode_status == UNICODE_ON) {
7070 STADJUST(-len, expdest);
7072 len = unicode_strlen(p);
7080 STADJUST(-len, expdest);
7085 * Expand a variable, and return a pointer to the next character in the
7089 evalvar(char *p, int flag, struct strlist *var_str_list)
7100 varflags = (unsigned char) *p++;
7101 subtype = varflags & VSTYPE;
7104 raise_error_syntax("bad substitution");
7106 quoted = flag & EXP_QUOTED;
7108 easy = (!quoted || (*var == '@' && shellparam.nparam));
7109 startloc = expdest - (char *)stackblock();
7110 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
7113 varlen = varvalue(var, varflags, flag, var_str_list, "ed);
7114 if (varflags & VSNUL)
7117 if (subtype == VSPLUS) {
7118 varlen = -1 - varlen;
7122 if (subtype == VSMINUS) {
7127 flag | EXP_TILDE | EXP_WORD,
7135 if (subtype == VSASSIGN || subtype == VSQUESTION) {
7139 subevalvar(p, var, 0, subtype, startloc, varflags,
7140 flag & ~QUOTES_ESC, var_str_list);
7143 * Remove any recorded regions beyond
7146 removerecordregions(startloc);
7150 if (varlen < 0 && uflag)
7151 varunset(p, var, 0, 0);
7153 if (subtype == VSLENGTH) {
7154 cvtnum(varlen > 0 ? varlen : 0);
7158 if (subtype == VSNORMAL) {
7162 recordregion(startloc, expdest - (char *)stackblock(), quoted);
7171 case VSTRIMRIGHTMAX:
7175 #if BASH_PATTERN_SUBST
7187 * Terminate the string and start recording the pattern
7190 STPUTC('\0', expdest);
7191 patloc = expdest - (char *)stackblock();
7192 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7193 startloc, varflags, flag, var_str_list)) {
7194 int amount = expdest - (
7195 (char *)stackblock() + patloc - 1
7197 STADJUST(-amount, expdest);
7199 /* Remove any recorded regions beyond start of variable */
7200 removerecordregions(startloc);
7205 if (subtype != VSNORMAL) { /* skip to end of alternative */
7208 unsigned char c = *p++;
7211 else if (c == CTLBACKQ) {
7213 argbackq = argbackq->next;
7214 } else if (c == CTLVAR) {
7215 if ((*p++ & VSTYPE) != VSNORMAL)
7217 } else if (c == CTLENDVAR) {
7227 * Add a file name to the list.
7230 addfname(const char *name)
7234 sp = stzalloc(sizeof(*sp));
7235 sp->text = sstrdup(name);
7237 exparg.lastp = &sp->next;
7240 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7242 hasmeta(const char *p)
7244 static const char chars[] ALIGN1 = {
7245 '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
7249 p = strpbrk(p, chars);
7252 switch ((unsigned char) *p) {
7256 if (*p == CTLQUOTEMARK)
7260 if (*p == '\0') /* huh? */
7271 if (!strchr(p + 1, ']')) {
7272 /* It's not a properly closed [] pattern,
7273 * but other metas may follow. Continue checking.
7274 * my[file* _is_ globbed by bash
7275 * and matches filenames like "my[file1".
7291 /* If we want to use glob() from libc... */
7292 #if !ENABLE_ASH_INTERNAL_GLOB
7294 /* Add the result of glob() to the list */
7296 addglob(const glob_t *pglob)
7298 char **p = pglob->gl_pathv;
7305 expandmeta(struct strlist *str /*, int flag*/)
7307 /* TODO - EXP_REDIR */
7317 if (!hasmeta(str->text))
7321 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7322 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7323 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7325 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7326 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7327 // Which means you need to unescape the string, right? Not so fast:
7328 // if there _is_ a file named "file\?" (with backslash), it is returned
7329 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7330 // You DON'T KNOW by looking at the result whether you need to unescape it.
7332 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7333 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7334 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7335 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7336 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7337 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7338 i = glob(p, 0, NULL, &pglob);
7339 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7344 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7345 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7346 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7358 *exparg.lastp = str;
7359 rmescapes(str->text, 0);
7360 exparg.lastp = &str->next;
7362 default: /* GLOB_NOSPACE */
7365 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7372 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7375 * Do metacharacter (i.e. *, ?, [...]) expansion.
7378 expmeta(char *expdir, char *enddir, char *name)
7394 for (p = name; esc = 0, *p; p += esc + 1) {
7395 if (*p == '*' || *p == '?')
7397 else if (*p == '[') {
7404 if (*q == '/' || *q == '\0')
7414 if (p[esc] == '/') {
7417 start = p + esc + 1;
7421 if (metaflag == 0) { /* we've reached the end of the file name */
7422 if (enddir != expdir)
7430 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7441 } while (p < start);
7443 if (enddir == expdir) {
7445 } else if (enddir == expdir + 1 && *expdir == '/') {
7454 if (enddir != expdir)
7456 if (*endname == 0) {
7469 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7470 if (dp->d_name[0] == '.' && !matchdot)
7472 if (pmatch(start, dp->d_name)) {
7474 strcpy(enddir, dp->d_name);
7477 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7480 expmeta(expdir, p, endname);
7486 endname[-esc - 1] = esc ? '\\' : '/';
7489 static struct strlist *
7490 msort(struct strlist *list, int len)
7492 struct strlist *p, *q = NULL;
7493 struct strlist **lpp;
7501 for (n = half; --n >= 0;) {
7505 q->next = NULL; /* terminate first half of list */
7506 q = msort(list, half); /* sort first half of list */
7507 p = msort(p, len - half); /* sort second half */
7510 #if ENABLE_LOCALE_SUPPORT
7511 if (strcoll(p->text, q->text) < 0)
7513 if (strcmp(p->text, q->text) < 0)
7537 * Sort the results of file name expansion. It calculates the number of
7538 * strings to sort and then calls msort (short for merge sort) to do the
7541 static struct strlist *
7542 expsort(struct strlist *str)
7548 for (sp = str; sp; sp = sp->next)
7550 return msort(str, len);
7554 expandmeta(struct strlist *str /*, int flag*/)
7556 /* TODO - EXP_REDIR */
7560 struct strlist **savelastp;
7566 if (!hasmeta(str->text))
7568 savelastp = exparg.lastp;
7571 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7573 int i = strlen(str->text);
7574 //BUGGY estimation of how long expanded name can be
7575 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7577 expmeta(expdir, expdir, p);
7582 if (exparg.lastp == savelastp) {
7587 *exparg.lastp = str;
7588 rmescapes(str->text, 0);
7589 exparg.lastp = &str->next;
7591 *exparg.lastp = NULL;
7592 *savelastp = sp = expsort(*savelastp);
7593 while (sp->next != NULL)
7595 exparg.lastp = &sp->next;
7600 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7603 * Perform variable substitution and command substitution on an argument,
7604 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7605 * perform splitting and file name expansion. When arglist is NULL, perform
7606 * here document expansion.
7609 expandarg(union node *arg, struct arglist *arglist, int flag)
7614 argbackq = arg->narg.backquote;
7615 STARTSTACKSTR(expdest);
7616 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7617 argstr(arg->narg.text, flag,
7618 /* var_str_list: */ arglist ? arglist->list : NULL);
7619 p = _STPUTC('\0', expdest);
7621 if (arglist == NULL) {
7622 /* here document expanded */
7625 p = grabstackstr(p);
7626 TRACE(("expandarg: p:'%s'\n", p));
7627 exparg.lastp = &exparg.list;
7631 if (flag & EXP_FULL) {
7632 ifsbreakup(p, &exparg);
7633 *exparg.lastp = NULL;
7634 exparg.lastp = &exparg.list;
7635 expandmeta(exparg.list /*, flag*/);
7637 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7639 TRACE(("expandarg: rmescapes:'%s'\n", p));
7641 sp = stzalloc(sizeof(*sp));
7644 exparg.lastp = &sp->next;
7646 *exparg.lastp = NULL;
7648 *arglist->lastp = exparg.list;
7649 arglist->lastp = exparg.lastp;
7657 * Expand shell variables and backquotes inside a here document.
7660 expandhere(union node *arg, int fd)
7662 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7663 full_write(fd, stackblock(), expdest - (char *)stackblock());
7667 * Returns true if the pattern matches the string.
7670 patmatch(char *pattern, const char *string)
7672 char *p = preglob(pattern, 0);
7673 //bb_error_msg("fnmatch(pattern:'%s',str:'%s')", p, string);
7674 return pmatch(p, string);
7678 * See if a pattern matches in a case statement.
7681 casematch(union node *pattern, char *val)
7683 struct stackmark smark;
7686 setstackmark(&smark);
7687 argbackq = pattern->narg.backquote;
7688 STARTSTACKSTR(expdest);
7689 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7690 /* var_str_list: */ NULL);
7691 STACKSTRNUL(expdest);
7693 result = patmatch(stackblock(), val);
7694 popstackmark(&smark);
7699 /* ============ find_command */
7703 int (*builtin)(int, char **) FAST_FUNC;
7704 /* unsigned flags; */
7706 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7707 /* "regular" builtins always take precedence over commands,
7708 * regardless of PATH=....%builtin... position */
7709 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7710 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7713 smallint cmdtype; /* CMDxxx */
7716 /* index >= 0 for commands without path (slashes) */
7717 /* (TODO: what exactly does the value mean? PATH position?) */
7718 /* index == -1 for commands with slashes */
7719 /* index == (-2 - applet_no) for NOFORK applets */
7720 const struct builtincmd *cmd;
7721 struct funcnode *func;
7724 /* values of cmdtype */
7725 #define CMDUNKNOWN -1 /* no entry in table for command */
7726 #define CMDNORMAL 0 /* command is an executable program */
7727 #define CMDFUNCTION 1 /* command is a shell function */
7728 #define CMDBUILTIN 2 /* command is a shell builtin */
7730 /* action to find_command() */
7731 #define DO_ERR 0x01 /* prints errors */
7732 #define DO_ABS 0x02 /* checks absolute paths */
7733 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7734 #define DO_ALTPATH 0x08 /* using alternate path */
7735 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7737 static void find_command(char *, struct cmdentry *, int, const char *);
7740 /* ============ Hashing commands */
7743 * When commands are first encountered, they are entered in a hash table.
7744 * This ensures that a full path search will not have to be done for them
7745 * on each invocation.
7747 * We should investigate converting to a linear search, even though that
7748 * would make the command name "hash" a misnomer.
7752 struct tblentry *next; /* next entry in hash chain */
7753 union param param; /* definition of builtin function */
7754 smallint cmdtype; /* CMDxxx */
7755 char rehash; /* if set, cd done since entry created */
7756 char cmdname[1]; /* name of command */
7759 static struct tblentry **cmdtable;
7760 #define INIT_G_cmdtable() do { \
7761 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7764 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7768 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7770 #if ENABLE_FEATURE_SH_STANDALONE
7771 if (applet_no >= 0) {
7772 if (APPLET_IS_NOEXEC(applet_no)) {
7776 run_applet_no_and_exit(applet_no, cmd, argv);
7778 /* re-exec ourselves with the new arguments */
7779 execve(bb_busybox_exec_path, argv, envp);
7780 /* If they called chroot or otherwise made the binary no longer
7781 * executable, fall through */
7788 execve(cmd, argv, envp);
7789 } while (errno == EINTR);
7791 execve(cmd, argv, envp);
7793 if (cmd != (char*) bb_busybox_exec_path && errno == ENOEXEC) {
7794 /* Run "cmd" as a shell script:
7795 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7796 * "If the execve() function fails with ENOEXEC, the shell
7797 * shall execute a command equivalent to having a shell invoked
7798 * with the command name as its first operand,
7799 * with any remaining arguments passed to the new shell"
7801 * That is, do not use $SHELL, user's shell, or /bin/sh;
7802 * just call ourselves.
7804 * Note that bash reads ~80 chars of the file, and if it sees
7805 * a zero byte before it sees newline, it doesn't try to
7806 * interpret it, but fails with "cannot execute binary file"
7807 * message and exit code 126. For one, this prevents attempts
7808 * to interpret foreign ELF binaries as shell scripts.
7811 cmd = (char*) bb_busybox_exec_path;
7812 /* NB: this is only possible because all callers of shellexec()
7813 * ensure that the argv[-1] slot exists!
7816 argv[0] = (char*) "ash";
7822 * Exec a program. Never returns. If you change this routine, you may
7823 * have to change the find_command routine as well.
7824 * argv[-1] must exist and be writable! See tryexec() for why.
7826 static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
7827 static void shellexec(char *prog, char **argv, const char *path, int idx)
7833 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7835 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7836 if (strchr(prog, '/') != NULL
7837 #if ENABLE_FEATURE_SH_STANDALONE
7838 || (applet_no = find_applet_by_name(prog)) >= 0
7841 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
7842 if (applet_no >= 0) {
7843 /* We tried execing ourself, but it didn't work.
7844 * Maybe /proc/self/exe doesn't exist?
7853 while ((cmdname = path_advance(&path, prog)) != NULL) {
7854 if (--idx < 0 && pathopt == NULL) {
7855 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7856 if (errno != ENOENT && errno != ENOTDIR)
7863 /* Map to POSIX errors */
7875 exitstatus = exerrno;
7876 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7877 prog, e, suppress_int));
7878 ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
7883 printentry(struct tblentry *cmdp)
7889 idx = cmdp->param.index;
7892 name = path_advance(&path, cmdp->cmdname);
7894 } while (--idx >= 0);
7895 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7899 * Clear out command entries. The argument specifies the first entry in
7900 * PATH which has changed.
7903 clearcmdentry(int firstchange)
7905 struct tblentry **tblp;
7906 struct tblentry **pp;
7907 struct tblentry *cmdp;
7910 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7912 while ((cmdp = *pp) != NULL) {
7913 if ((cmdp->cmdtype == CMDNORMAL &&
7914 cmdp->param.index >= firstchange)
7915 || (cmdp->cmdtype == CMDBUILTIN &&
7916 builtinloc >= firstchange)
7929 * Locate a command in the command hash table. If "add" is nonzero,
7930 * add the command to the table if it is not already present. The
7931 * variable "lastcmdentry" is set to point to the address of the link
7932 * pointing to the entry, so that delete_cmd_entry can delete the
7935 * Interrupts must be off if called with add != 0.
7937 static struct tblentry **lastcmdentry;
7939 static struct tblentry *
7940 cmdlookup(const char *name, int add)
7942 unsigned int hashval;
7944 struct tblentry *cmdp;
7945 struct tblentry **pp;
7948 hashval = (unsigned char)*p << 4;
7950 hashval += (unsigned char)*p++;
7952 pp = &cmdtable[hashval % CMDTABLESIZE];
7953 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7954 if (strcmp(cmdp->cmdname, name) == 0)
7958 if (add && cmdp == NULL) {
7959 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7961 /* + 1 - already done because
7962 * tblentry::cmdname is char[1] */);
7963 /*cmdp->next = NULL; - ckzalloc did it */
7964 cmdp->cmdtype = CMDUNKNOWN;
7965 strcpy(cmdp->cmdname, name);
7972 * Delete the command entry returned on the last lookup.
7975 delete_cmd_entry(void)
7977 struct tblentry *cmdp;
7980 cmdp = *lastcmdentry;
7981 *lastcmdentry = cmdp->next;
7982 if (cmdp->cmdtype == CMDFUNCTION)
7983 freefunc(cmdp->param.func);
7989 * Add a new command entry, replacing any existing command entry for
7990 * the same name - except special builtins.
7993 addcmdentry(char *name, struct cmdentry *entry)
7995 struct tblentry *cmdp;
7997 cmdp = cmdlookup(name, 1);
7998 if (cmdp->cmdtype == CMDFUNCTION) {
7999 freefunc(cmdp->param.func);
8001 cmdp->cmdtype = entry->cmdtype;
8002 cmdp->param = entry->u;
8006 static int FAST_FUNC
8007 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8009 struct tblentry **pp;
8010 struct tblentry *cmdp;
8012 struct cmdentry entry;
8015 if (nextopt("r") != '\0') {
8020 if (*argptr == NULL) {
8021 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8022 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8023 if (cmdp->cmdtype == CMDNORMAL)
8031 while ((name = *argptr) != NULL) {
8032 cmdp = cmdlookup(name, 0);
8034 && (cmdp->cmdtype == CMDNORMAL
8035 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
8039 find_command(name, &entry, DO_ERR, pathval());
8040 if (entry.cmdtype == CMDUNKNOWN)
8048 * Called when a cd is done. Marks all commands so the next time they
8049 * are executed they will be rehashed.
8054 struct tblentry **pp;
8055 struct tblentry *cmdp;
8057 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8058 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8059 if (cmdp->cmdtype == CMDNORMAL
8060 || (cmdp->cmdtype == CMDBUILTIN
8061 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
8071 * Fix command hash table when PATH changed.
8072 * Called before PATH is changed. The argument is the new value of PATH;
8073 * pathval() still returns the old value at this point.
8074 * Called with interrupts off.
8076 static void FAST_FUNC
8077 changepath(const char *new)
8085 firstchange = 9999; /* assume no change */
8091 if ((*old == '\0' && *new == ':')
8092 || (*old == ':' && *new == '\0')
8096 old = new; /* ignore subsequent differences */
8100 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
8107 if (builtinloc < 0 && idx_bltin >= 0)
8108 builtinloc = idx_bltin; /* zap builtins */
8109 if (builtinloc >= 0 && idx_bltin < 0)
8111 clearcmdentry(firstchange);
8112 builtinloc = idx_bltin;
8148 typedef smallint token_id_t;
8150 /* Nth bit indicates if token marks the end of a list */
8153 /* 0 */ | (1u << TEOF)
8154 /* 1 */ | (0u << TNL)
8155 /* 2 */ | (0u << TREDIR)
8156 /* 3 */ | (0u << TWORD)
8157 /* 4 */ | (0u << TSEMI)
8158 /* 5 */ | (0u << TBACKGND)
8159 /* 6 */ | (0u << TAND)
8160 /* 7 */ | (0u << TOR)
8161 /* 8 */ | (0u << TPIPE)
8162 /* 9 */ | (0u << TLP)
8163 /* 10 */ | (1u << TRP)
8164 /* 11 */ | (1u << TENDCASE)
8165 /* 12 */ | (1u << TENDBQUOTE)
8166 /* 13 */ | (0u << TNOT)
8167 /* 14 */ | (0u << TCASE)
8168 /* 15 */ | (1u << TDO)
8169 /* 16 */ | (1u << TDONE)
8170 /* 17 */ | (1u << TELIF)
8171 /* 18 */ | (1u << TELSE)
8172 /* 19 */ | (1u << TESAC)
8173 /* 20 */ | (1u << TFI)
8174 /* 21 */ | (0u << TFOR)
8176 /* 22 */ | (0u << TFUNCTION)
8178 /* 23 */ | (0u << TIF)
8179 /* 24 */ | (0u << TIN)
8180 /* 25 */ | (1u << TTHEN)
8181 /* 26 */ | (0u << TUNTIL)
8182 /* 27 */ | (0u << TWHILE)
8183 /* 28 */ | (0u << TBEGIN)
8184 /* 29 */ | (1u << TEND)
8185 , /* thus far 29 bits used */
8188 static const char *const tokname_array[] = {
8202 #define KWDOFFSET 13
8203 /* the following are keywords */
8225 /* Wrapper around strcmp for qsort/bsearch/... */
8227 pstrcmp(const void *a, const void *b)
8229 return strcmp((char*)a, *(char**)b);
8232 static const char *const *
8233 findkwd(const char *s)
8235 return bsearch(s, tokname_array + KWDOFFSET,
8236 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8237 sizeof(tokname_array[0]), pstrcmp);
8241 * Locate and print what a word is...
8244 describe_command(char *command, const char *path, int describe_command_verbose)
8246 struct cmdentry entry;
8247 #if ENABLE_ASH_ALIAS
8248 const struct alias *ap;
8251 path = path ? path : pathval();
8253 if (describe_command_verbose) {
8257 /* First look at the keywords */
8258 if (findkwd(command)) {
8259 out1str(describe_command_verbose ? " is a shell keyword" : command);
8263 #if ENABLE_ASH_ALIAS
8264 /* Then look at the aliases */
8265 ap = lookupalias(command, 0);
8267 if (!describe_command_verbose) {
8272 out1fmt(" is an alias for %s", ap->val);
8277 find_command(command, &entry, DO_ABS, path);
8279 switch (entry.cmdtype) {
8281 int j = entry.u.index;
8287 p = path_advance(&path, command);
8291 if (describe_command_verbose) {
8292 out1fmt(" is %s", p);
8300 if (describe_command_verbose) {
8301 out1str(" is a shell function");
8308 if (describe_command_verbose) {
8309 out1fmt(" is a %sshell builtin",
8310 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8311 "special " : nullstr
8319 if (describe_command_verbose) {
8320 out1str(": not found\n");
8329 static int FAST_FUNC
8330 typecmd(int argc UNUSED_PARAM, char **argv)
8336 /* type -p ... ? (we don't bother checking for 'p') */
8337 if (argv[1] && argv[1][0] == '-') {
8342 err |= describe_command(argv[i++], NULL, verbose);
8347 #if ENABLE_ASH_CMDCMD
8348 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8350 parse_command_args(char **argv, const char **path)
8363 if (c == '-' && !*cp) {
8371 *path = bb_default_path;
8374 /* run 'typecmd' for other options */
8383 static int FAST_FUNC
8384 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8392 const char *path = NULL;
8394 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8395 * never reaches this function.
8398 while ((c = nextopt("pvV")) != '\0')
8400 verify |= VERIFY_VERBOSE;
8402 /*verify |= VERIFY_BRIEF*/;
8408 path = bb_default_path;
8410 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8412 if (/*verify && */ cmd)
8413 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8420 /*static int funcblocksize; // size of structures in function */
8421 /*static int funcstringsize; // size of strings in node */
8422 static void *funcblock; /* block to allocate function from */
8423 static char *funcstring_end; /* end of block to allocate strings from */
8425 /* flags in argument to evaltree */
8426 #define EV_EXIT 01 /* exit after evaluating tree */
8427 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8429 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8430 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8431 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8432 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8433 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8434 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8435 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8436 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8437 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8438 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8439 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8440 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8441 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8442 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8443 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8444 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8445 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8446 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8447 #if BASH_REDIR_OUTPUT
8448 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8450 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8451 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8452 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8453 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8454 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8455 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8456 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8457 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8458 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8461 static int calcsize(int funcblocksize, union node *n);
8464 sizenodelist(int funcblocksize, struct nodelist *lp)
8467 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8468 funcblocksize = calcsize(funcblocksize, lp->n);
8471 return funcblocksize;
8475 calcsize(int funcblocksize, union node *n)
8478 return funcblocksize;
8479 funcblocksize += nodesize[n->type];
8482 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8483 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8484 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8487 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8492 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8493 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8500 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8501 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8504 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8505 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8506 funcblocksize = calcsize(funcblocksize, n->nif.test);
8509 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8510 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8511 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8514 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8515 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8518 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8519 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8520 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8524 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8525 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8526 funcblocksize = calcsize(funcblocksize, n->narg.next);
8529 #if BASH_REDIR_OUTPUT
8536 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8537 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8541 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8542 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8546 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8547 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8550 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8553 return funcblocksize;
8557 nodeckstrdup(char *s)
8559 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8560 return strcpy(funcstring_end, s);
8563 static union node *copynode(union node *);
8565 static struct nodelist *
8566 copynodelist(struct nodelist *lp)
8568 struct nodelist *start;
8569 struct nodelist **lpp;
8574 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8575 (*lpp)->n = copynode(lp->n);
8577 lpp = &(*lpp)->next;
8584 copynode(union node *n)
8591 funcblock = (char *) funcblock + nodesize[n->type];
8595 new->ncmd.redirect = copynode(n->ncmd.redirect);
8596 new->ncmd.args = copynode(n->ncmd.args);
8597 new->ncmd.assign = copynode(n->ncmd.assign);
8600 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8601 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8606 new->nredir.redirect = copynode(n->nredir.redirect);
8607 new->nredir.n = copynode(n->nredir.n);
8614 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8615 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8618 new->nif.elsepart = copynode(n->nif.elsepart);
8619 new->nif.ifpart = copynode(n->nif.ifpart);
8620 new->nif.test = copynode(n->nif.test);
8623 new->nfor.var = nodeckstrdup(n->nfor.var);
8624 new->nfor.body = copynode(n->nfor.body);
8625 new->nfor.args = copynode(n->nfor.args);
8628 new->ncase.cases = copynode(n->ncase.cases);
8629 new->ncase.expr = copynode(n->ncase.expr);
8632 new->nclist.body = copynode(n->nclist.body);
8633 new->nclist.pattern = copynode(n->nclist.pattern);
8634 new->nclist.next = copynode(n->nclist.next);
8638 new->narg.backquote = copynodelist(n->narg.backquote);
8639 new->narg.text = nodeckstrdup(n->narg.text);
8640 new->narg.next = copynode(n->narg.next);
8643 #if BASH_REDIR_OUTPUT
8650 new->nfile.fname = copynode(n->nfile.fname);
8651 new->nfile.fd = n->nfile.fd;
8652 new->nfile.next = copynode(n->nfile.next);
8656 new->ndup.vname = copynode(n->ndup.vname);
8657 new->ndup.dupfd = n->ndup.dupfd;
8658 new->ndup.fd = n->ndup.fd;
8659 new->ndup.next = copynode(n->ndup.next);
8663 new->nhere.doc = copynode(n->nhere.doc);
8664 new->nhere.fd = n->nhere.fd;
8665 new->nhere.next = copynode(n->nhere.next);
8668 new->nnot.com = copynode(n->nnot.com);
8671 new->type = n->type;
8676 * Make a copy of a parse tree.
8678 static struct funcnode *
8679 copyfunc(union node *n)
8684 /*funcstringsize = 0;*/
8685 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8686 f = ckzalloc(blocksize /* + funcstringsize */);
8687 funcblock = (char *) f + offsetof(struct funcnode, n);
8688 funcstring_end = (char *) f + blocksize;
8690 /* f->count = 0; - ckzalloc did it */
8695 * Define a shell function.
8698 defun(union node *func)
8700 struct cmdentry entry;
8703 entry.cmdtype = CMDFUNCTION;
8704 entry.u.func = copyfunc(func);
8705 addcmdentry(func->narg.text, &entry);
8709 /* Reasons for skipping commands (see comment on breakcmd routine) */
8710 #define SKIPBREAK (1 << 0)
8711 #define SKIPCONT (1 << 1)
8712 #define SKIPFUNC (1 << 2)
8713 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8714 static int skipcount; /* number of levels to skip */
8715 static int funcnest; /* depth of function calls */
8716 static int loopnest; /* current loop nesting level */
8718 /* Forward decl way out to parsing code - dotrap needs it */
8719 static int evalstring(char *s, int flags);
8721 /* Called to execute a trap.
8722 * Single callsite - at the end of evaltree().
8723 * If we return non-zero, evaltree raises EXEXIT exception.
8725 * Perhaps we should avoid entering new trap handlers
8726 * while we are executing a trap handler. [is it a TODO?]
8733 uint8_t last_status;
8738 last_status = exitstatus;
8742 TRACE(("dotrap entered\n"));
8743 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8755 /* non-trapped SIGINT is handled separately by raise_interrupt,
8756 * don't upset it by resetting gotsig[SIGINT-1] */
8757 if (sig == SIGINT && !p)
8760 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8766 exitstatus = last_status;
8767 TRACE(("dotrap returns\n"));
8770 /* forward declarations - evaluation is fairly recursive business... */
8771 static int evalloop(union node *, int);
8772 static int evalfor(union node *, int);
8773 static int evalcase(union node *, int);
8774 static int evalsubshell(union node *, int);
8775 static void expredir(union node *);
8776 static int evalpipe(union node *, int);
8777 static int evalcommand(union node *, int);
8778 static int evalbltin(const struct builtincmd *, int, char **, int);
8779 static void prehash(union node *);
8782 * Evaluate a parse tree. The value is left in the global variable
8786 evaltree(union node *n, int flags)
8789 int (*evalfn)(union node *, int);
8793 TRACE(("evaltree(NULL) called\n"));
8796 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8803 out1fmt("Node type = %d\n", n->type);
8808 status = !evaltree(n->nnot.com, EV_TESTED);
8811 expredir(n->nredir.redirect);
8812 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8814 status = evaltree(n->nredir.n, flags & EV_TESTED);
8816 if (n->nredir.redirect)
8817 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8820 evalfn = evalcommand;
8822 if (eflag && !(flags & EV_TESTED))
8834 evalfn = evalsubshell;
8847 #error NAND + 1 != NOR
8849 #if NOR + 1 != NSEMI
8850 #error NOR + 1 != NSEMI
8852 unsigned is_or = n->type - NAND;
8855 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8857 if ((!status) == is_or || evalskip)
8863 status = evalfn(n, flags);
8867 status = evaltree(n->nif.test, EV_TESTED);
8874 if (n->nif.elsepart) {
8875 n = n->nif.elsepart;
8882 /* Not necessary. To test it:
8883 * "false; f() { qwerty; }; echo $?" should print 0.
8887 exitstatus = status;
8891 /* Order of checks below is important:
8892 * signal handlers trigger before exit caused by "set -e".
8896 if (checkexit & status)
8897 raise_exception(EXEXIT);
8898 if (flags & EV_EXIT)
8899 raise_exception(EXEXIT);
8901 TRACE(("leaving evaltree (no interrupts)\n"));
8905 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8908 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8913 int skip = evalskip;
8920 if (--skipcount <= 0) {
8931 evalloop(union node *n, int flags)
8942 i = evaltree(n->nbinary.ch1, EV_TESTED);
8944 if (skip == SKIPFUNC)
8948 if (n->type != NWHILE)
8952 status = evaltree(n->nbinary.ch2, flags);
8954 } while (!(skip & ~SKIPCONT));
8961 evalfor(union node *n, int flags)
8963 struct arglist arglist;
8966 struct stackmark smark;
8969 setstackmark(&smark);
8970 arglist.list = NULL;
8971 arglist.lastp = &arglist.list;
8972 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8973 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8975 *arglist.lastp = NULL;
8979 for (sp = arglist.list; sp; sp = sp->next) {
8980 setvar0(n->nfor.var, sp->text);
8981 status = evaltree(n->nfor.body, flags);
8982 if (skiploop() & ~SKIPCONT)
8986 popstackmark(&smark);
8992 evalcase(union node *n, int flags)
8996 struct arglist arglist;
8997 struct stackmark smark;
9000 setstackmark(&smark);
9001 arglist.list = NULL;
9002 arglist.lastp = &arglist.list;
9003 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
9004 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
9005 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
9006 if (casematch(patp, arglist.list->text)) {
9007 /* Ensure body is non-empty as otherwise
9008 * EV_EXIT may prevent us from setting the
9011 if (evalskip == 0 && cp->nclist.body) {
9012 status = evaltree(cp->nclist.body, flags);
9019 popstackmark(&smark);
9025 * Kick off a subshell to evaluate a tree.
9028 evalsubshell(union node *n, int flags)
9031 int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
9034 expredir(n->nredir.redirect);
9035 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
9038 if (backgnd == FORK_FG)
9040 jp = makejob(/*n,*/ 1);
9041 if (forkshell(jp, n, backgnd) == 0) {
9046 flags &= ~EV_TESTED;
9048 redirect(n->nredir.redirect, 0);
9049 evaltreenr(n->nredir.n, flags);
9054 if (backgnd == FORK_FG)
9055 status = waitforjob(jp);
9061 * Compute the names of the files in a redirection list.
9063 static void fixredir(union node *, const char *, int);
9065 expredir(union node *n)
9069 for (redir = n; redir; redir = redir->nfile.next) {
9073 fn.lastp = &fn.list;
9074 switch (redir->type) {
9078 #if BASH_REDIR_OUTPUT
9083 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
9084 TRACE(("expredir expanded to '%s'\n", fn.list->text));
9085 #if BASH_REDIR_OUTPUT
9089 // By the design of stack allocator, the loop of this kind:
9090 // while true; do while true; do break; done </dev/null; done
9091 // will look like a memory leak: ash plans to free expfname's
9092 // of "/dev/null" as soon as it finishes running the loop
9093 // (in this case, never).
9094 // This "fix" is wrong:
9095 if (redir->nfile.expfname)
9096 stunalloc(redir->nfile.expfname);
9097 // It results in corrupted state of stacked allocations.
9099 redir->nfile.expfname = fn.list->text;
9102 case NTOFD: /* >& */
9103 if (redir->ndup.vname) {
9104 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
9105 if (fn.list == NULL)
9106 ash_msg_and_raise_error("redir error");
9107 #if BASH_REDIR_OUTPUT
9108 //FIXME: we used expandarg with different args!
9109 if (!isdigit_str9(fn.list->text)) {
9110 /* >&file, not >&fd */
9111 if (redir->nfile.fd != 1) /* 123>&file - BAD */
9112 ash_msg_and_raise_error("redir error");
9114 goto store_expfname;
9117 fixredir(redir, fn.list->text, 1);
9125 * Evaluate a pipeline. All the processes in the pipeline are children
9126 * of the process creating the pipeline. (This differs from some versions
9127 * of the shell, which make the last process in a pipeline the parent
9131 evalpipe(union node *n, int flags)
9134 struct nodelist *lp;
9140 TRACE(("evalpipe(0x%lx) called\n", (long)n));
9142 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
9146 if (n->npipe.pipe_backgnd == 0)
9148 jp = makejob(/*n,*/ pipelen);
9150 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
9154 if (pipe(pip) < 0) {
9156 ash_msg_and_raise_error("pipe call failed");
9159 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
9173 evaltreenr(lp->n, flags);
9180 /* Don't want to trigger debugging */
9184 if (n->npipe.pipe_backgnd == 0) {
9185 status = waitforjob(jp);
9186 TRACE(("evalpipe: job done exit status %d\n", status));
9194 * Controls whether the shell is interactive or not.
9197 setinteractive(int on)
9199 static smallint is_interactive;
9201 if (++on == is_interactive)
9203 is_interactive = on;
9207 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9208 if (is_interactive > 1) {
9209 /* Looks like they want an interactive shell */
9210 static smallint did_banner;
9213 /* note: ash and hush share this string */
9214 out1fmt("\n\n%s %s\n"
9215 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9218 "built-in shell (ash)"
9232 setinteractive(iflag);
9234 #if ENABLE_FEATURE_EDITING_VI
9236 line_input_state->flags |= VI_MODE;
9238 line_input_state->flags &= ~VI_MODE;
9240 viflag = 0; /* forcibly keep the option off */
9244 static struct localvar *localvars;
9247 * Called after a function returns.
9248 * Interrupts must be off.
9253 struct localvar *lvp;
9256 while ((lvp = localvars) != NULL) {
9257 localvars = lvp->next;
9259 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9260 if (vp == NULL) { /* $- saved */
9261 memcpy(optlist, lvp->text, sizeof(optlist));
9262 free((char*)lvp->text);
9264 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
9265 unsetvar(vp->var_text);
9268 vp->var_func(var_end(lvp->text));
9269 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9270 free((char*)vp->var_text);
9271 vp->flags = lvp->flags;
9272 vp->var_text = lvp->text;
9279 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9281 volatile struct shparam saveparam;
9282 struct localvar *volatile savelocalvars;
9283 struct jmploc *volatile savehandler;
9284 struct jmploc jmploc;
9287 saveparam = shellparam;
9288 savelocalvars = localvars;
9289 savehandler = exception_handler;
9290 e = setjmp(jmploc.loc);
9295 exception_handler = &jmploc;
9297 shellparam.malloced = 0;
9301 shellparam.nparam = argc - 1;
9302 shellparam.p = argv + 1;
9303 #if ENABLE_ASH_GETOPTS
9304 shellparam.optind = 1;
9305 shellparam.optoff = -1;
9307 evaltree(func->n.narg.next, flags & EV_TESTED);
9313 localvars = savelocalvars;
9314 freeparam(&shellparam);
9315 shellparam = saveparam;
9316 exception_handler = savehandler;
9318 evalskip &= ~SKIPFUNC;
9323 * Make a variable a local variable. When a variable is made local, it's
9324 * value and flags are saved in a localvar structure. The saved values
9325 * will be restored when the shell function returns. We handle the name
9326 * "-" as a special case: it makes changes to "set +-options" local
9327 * (options will be restored on return from the function).
9332 struct localvar *lvp;
9335 char *eq = strchr(name, '=');
9338 /* Cater for duplicate "local". Examples:
9339 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9340 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9344 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9348 * it's a duplicate "local VAR" declaration, do nothing
9355 lvp = ckzalloc(sizeof(*lvp));
9356 if (LONE_DASH(name)) {
9358 p = ckmalloc(sizeof(optlist));
9359 lvp->text = memcpy(p, optlist, sizeof(optlist));
9362 vpp = hashvar(name);
9363 vp = *findvar(vpp, name);
9365 /* variable did not exist yet */
9367 setvareq(name, VSTRFIXED);
9369 setvar(name, NULL, VSTRFIXED);
9370 vp = *vpp; /* the new variable */
9371 lvp->flags = VUNSET;
9373 lvp->text = vp->var_text;
9374 lvp->flags = vp->flags;
9375 /* make sure neither "struct var" nor string gets freed
9376 * during (un)setting:
9378 vp->flags |= VSTRFIXED|VTEXTFIXED;
9382 /* "local VAR" unsets VAR: */
9383 setvar0(name, NULL);
9387 lvp->next = localvars;
9394 * The "local" command.
9396 static int FAST_FUNC
9397 localcmd(int argc UNUSED_PARAM, char **argv)
9402 ash_msg_and_raise_error("not in a function");
9405 while ((name = *argv++) != NULL) {
9411 static int FAST_FUNC
9412 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9417 static int FAST_FUNC
9418 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9423 static int FAST_FUNC
9424 execcmd(int argc UNUSED_PARAM, char **argv)
9427 while (nextopt("a:") != '\0')
9428 /* nextopt() sets optionarg to "-a ARGV0" */;
9434 iflag = 0; /* exit on error */
9437 /* We should set up signals for "exec CMD"
9438 * the same way as for "CMD" without "exec".
9439 * But optschanged->setinteractive->setsignal
9440 * still thought we are a root shell. Therefore, for example,
9441 * SIGQUIT is still set to IGN. Fix it:
9445 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9446 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9447 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9451 argv[0] = optionarg;
9452 shellexec(prog, argv, pathval(), 0);
9459 * The return command.
9461 static int FAST_FUNC
9462 returncmd(int argc UNUSED_PARAM, char **argv)
9465 * If called outside a function, do what ksh does;
9466 * skip the rest of the file.
9468 evalskip = SKIPFUNC;
9469 return argv[1] ? number(argv[1]) : exitstatus;
9472 /* Forward declarations for builtintab[] */
9473 static int breakcmd(int, char **) FAST_FUNC;
9474 static int dotcmd(int, char **) FAST_FUNC;
9475 static int evalcmd(int, char **, int) FAST_FUNC;
9476 static int exitcmd(int, char **) FAST_FUNC;
9477 static int exportcmd(int, char **) FAST_FUNC;
9478 #if ENABLE_ASH_GETOPTS
9479 static int getoptscmd(int, char **) FAST_FUNC;
9482 static int helpcmd(int, char **) FAST_FUNC;
9485 static int historycmd(int, char **) FAST_FUNC;
9487 #if ENABLE_FEATURE_SH_MATH
9488 static int letcmd(int, char **) FAST_FUNC;
9490 static int readcmd(int, char **) FAST_FUNC;
9491 static int setcmd(int, char **) FAST_FUNC;
9492 static int shiftcmd(int, char **) FAST_FUNC;
9493 static int timescmd(int, char **) FAST_FUNC;
9494 static int trapcmd(int, char **) FAST_FUNC;
9495 static int umaskcmd(int, char **) FAST_FUNC;
9496 static int unsetcmd(int, char **) FAST_FUNC;
9497 static int ulimitcmd(int, char **) FAST_FUNC;
9499 #define BUILTIN_NOSPEC "0"
9500 #define BUILTIN_SPECIAL "1"
9501 #define BUILTIN_REGULAR "2"
9502 #define BUILTIN_SPEC_REG "3"
9503 #define BUILTIN_ASSIGN "4"
9504 #define BUILTIN_SPEC_ASSG "5"
9505 #define BUILTIN_REG_ASSG "6"
9506 #define BUILTIN_SPEC_REG_ASSG "7"
9508 /* Stubs for calling non-FAST_FUNC's */
9510 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9512 #if ENABLE_ASH_PRINTF
9513 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9515 #if ENABLE_ASH_TEST || BASH_TEST2
9516 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9519 /* Keep these in proper order since it is searched via bsearch() */
9520 static const struct builtincmd builtintab[] = {
9521 { BUILTIN_SPEC_REG "." , dotcmd },
9522 { BUILTIN_SPEC_REG ":" , truecmd },
9524 { BUILTIN_REGULAR "[" , testcmd },
9527 { BUILTIN_REGULAR "[[" , testcmd },
9529 #if ENABLE_ASH_ALIAS
9530 { BUILTIN_REG_ASSG "alias" , aliascmd },
9533 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9535 { BUILTIN_SPEC_REG "break" , breakcmd },
9536 { BUILTIN_REGULAR "cd" , cdcmd },
9537 { BUILTIN_NOSPEC "chdir" , cdcmd },
9538 #if ENABLE_ASH_CMDCMD
9539 { BUILTIN_REGULAR "command" , commandcmd },
9541 { BUILTIN_SPEC_REG "continue", breakcmd },
9543 { BUILTIN_REGULAR "echo" , echocmd },
9545 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9546 { BUILTIN_SPEC_REG "exec" , execcmd },
9547 { BUILTIN_SPEC_REG "exit" , exitcmd },
9548 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9549 { BUILTIN_REGULAR "false" , falsecmd },
9551 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9553 #if ENABLE_ASH_GETOPTS
9554 { BUILTIN_REGULAR "getopts" , getoptscmd },
9556 { BUILTIN_NOSPEC "hash" , hashcmd },
9558 { BUILTIN_NOSPEC "help" , helpcmd },
9561 { BUILTIN_NOSPEC "history" , historycmd },
9564 { BUILTIN_REGULAR "jobs" , jobscmd },
9565 { BUILTIN_REGULAR "kill" , killcmd },
9567 #if ENABLE_FEATURE_SH_MATH
9568 { BUILTIN_NOSPEC "let" , letcmd },
9570 { BUILTIN_ASSIGN "local" , localcmd },
9571 #if ENABLE_ASH_PRINTF
9572 { BUILTIN_REGULAR "printf" , printfcmd },
9574 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9575 { BUILTIN_REGULAR "read" , readcmd },
9576 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9577 { BUILTIN_SPEC_REG "return" , returncmd },
9578 { BUILTIN_SPEC_REG "set" , setcmd },
9579 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9581 { BUILTIN_SPEC_REG "source" , dotcmd },
9584 { BUILTIN_REGULAR "test" , testcmd },
9586 { BUILTIN_SPEC_REG "times" , timescmd },
9587 { BUILTIN_SPEC_REG "trap" , trapcmd },
9588 { BUILTIN_REGULAR "true" , truecmd },
9589 { BUILTIN_NOSPEC "type" , typecmd },
9590 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9591 { BUILTIN_REGULAR "umask" , umaskcmd },
9592 #if ENABLE_ASH_ALIAS
9593 { BUILTIN_REGULAR "unalias" , unaliascmd },
9595 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9596 { BUILTIN_REGULAR "wait" , waitcmd },
9599 /* Should match the above table! */
9600 #define COMMANDCMD (builtintab + \
9602 /* [ */ 1 * ENABLE_ASH_TEST + \
9603 /* [[ */ 1 * BASH_TEST2 + \
9604 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9605 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9606 /* break cd cddir */ 3)
9607 #define EVALCMD (COMMANDCMD + \
9608 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9609 /* continue */ 1 + \
9610 /* echo */ 1 * ENABLE_ASH_ECHO + \
9612 #define EXECCMD (EVALCMD + \
9616 * Search the table of builtin commands.
9619 pstrcmp1(const void *a, const void *b)
9621 return strcmp((char*)a, *(char**)b + 1);
9623 static struct builtincmd *
9624 find_builtin(const char *name)
9626 struct builtincmd *bp;
9629 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9636 * Execute a simple command.
9639 isassignment(const char *p)
9641 const char *q = endofname(p);
9646 static int FAST_FUNC
9647 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9649 /* Preserve exitstatus of a previous possible redirection
9650 * as POSIX mandates */
9651 return back_exitstatus;
9654 evalcommand(union node *cmd, int flags)
9656 static const struct builtincmd null_bltin = {
9657 "\0\0", bltincmd /* why three NULs? */
9659 struct stackmark smark;
9661 struct arglist arglist;
9662 struct arglist varlist;
9665 const struct strlist *sp;
9666 struct cmdentry cmdentry;
9673 struct builtincmd *bcmd;
9674 smallint cmd_is_exec;
9675 smallint pseudovarflag = 0;
9677 /* First expand the arguments. */
9678 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9679 setstackmark(&smark);
9680 back_exitstatus = 0;
9682 cmdentry.cmdtype = CMDBUILTIN;
9683 cmdentry.u.cmd = &null_bltin;
9684 varlist.lastp = &varlist.list;
9685 *varlist.lastp = NULL;
9686 arglist.lastp = &arglist.list;
9687 *arglist.lastp = NULL;
9690 if (cmd->ncmd.args) {
9691 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9692 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9695 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9696 struct strlist **spp;
9698 spp = arglist.lastp;
9699 if (pseudovarflag && isassignment(argp->narg.text))
9700 expandarg(argp, &arglist, EXP_VARTILDE);
9702 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9704 for (sp = *spp; sp; sp = sp->next)
9708 /* Reserve one extra spot at the front for shellexec. */
9709 nargv = stalloc(sizeof(char *) * (argc + 2));
9711 for (sp = arglist.list; sp; sp = sp->next) {
9712 TRACE(("evalcommand arg: %s\n", sp->text));
9713 *nargv++ = sp->text;
9718 if (iflag && funcnest == 0 && argc > 0)
9719 lastarg = nargv[-1];
9722 expredir(cmd->ncmd.redirect);
9723 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9725 path = vpath.var_text;
9726 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9727 struct strlist **spp;
9730 spp = varlist.lastp;
9731 expandarg(argp, &varlist, EXP_VARTILDE);
9734 * Modify the command lookup path, if a PATH= assignment
9738 if (varcmp(p, path) == 0)
9742 /* Print the command if xflag is set. */
9744 const char *pfx = "";
9746 fdprintf(preverrout_fd, "%s", expandstr(ps4val()));
9750 char *varval = sp->text;
9751 char *eq = strchrnul(varval, '=');
9754 fdprintf(preverrout_fd, "%s%.*s%s",
9756 (int)(eq - varval), varval,
9757 maybe_single_quote(eq)
9765 fdprintf(preverrout_fd, "%s%s",
9767 /* always quote if matches reserved word: */
9769 ? single_quote(sp->text)
9770 : maybe_single_quote(sp->text)
9775 safe_write(preverrout_fd, "\n", 1);
9781 /* Now locate the command. */
9783 int cmd_flag = DO_ERR;
9784 #if ENABLE_ASH_CMDCMD
9785 const char *oldpath = path + 5;
9789 find_command(argv[0], &cmdentry, cmd_flag, path);
9790 if (cmdentry.cmdtype == CMDUNKNOWN) {
9791 flush_stdout_stderr();
9796 /* implement bltin and command here */
9797 if (cmdentry.cmdtype != CMDBUILTIN)
9800 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9801 if (cmdentry.u.cmd == EXECCMD)
9803 #if ENABLE_ASH_CMDCMD
9804 if (cmdentry.u.cmd == COMMANDCMD) {
9806 nargv = parse_command_args(argv, &path);
9809 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9810 * nargv => "PROG". path is updated if -p.
9812 argc -= nargv - argv;
9814 cmd_flag |= DO_NOFUNC;
9823 exitstatus = status;
9825 /* We have a redirection error. */
9827 raise_exception(EXERROR);
9832 /* Execute the command. */
9833 switch (cmdentry.cmdtype) {
9836 #if ENABLE_FEATURE_SH_NOFORK
9837 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9838 * around run_nofork_applet() call.
9839 * (2) Should this check also be done in forkshell()?
9840 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9842 /* find_command() encodes applet_no as (-2 - applet_no) */
9843 int applet_no = (- cmdentry.u.index - 2);
9844 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9845 listsetvar(varlist.list, VEXPORT|VSTACK);
9846 /* run <applet>_main() */
9847 status = run_nofork_applet(applet_no, argv);
9851 /* Can we avoid forking off? For example, very last command
9852 * in a script or a subshell does not need forking,
9853 * we can just exec it.
9855 if (!(flags & EV_EXIT) || may_have_traps) {
9856 /* No, forking off a child is necessary */
9859 jp = makejob(/*cmd,*/ 1);
9860 if (forkshell(jp, cmd, FORK_FG) != 0) {
9862 status = waitforjob(jp);
9864 TRACE(("forked child exited with %d\n", status));
9869 /* fall through to exec'ing external program */
9871 listsetvar(varlist.list, VEXPORT|VSTACK);
9872 shellexec(argv[0], argv, path, cmdentry.u.index);
9876 cmdenviron = varlist.list;
9878 struct strlist *list = cmdenviron;
9880 if (spclbltin > 0 || argc == 0) {
9882 if (cmd_is_exec && argc > 1)
9885 listsetvar(list, i);
9887 /* Tight loop with builtins only:
9888 * "while kill -0 $child; do true; done"
9889 * will never exit even if $child died, unless we do this
9890 * to reap the zombie and make kill detect that it's gone: */
9891 dowait(DOWAIT_NONBLOCK, NULL);
9893 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9894 if (exception_type == EXERROR && spclbltin <= 0) {
9899 longjmp(exception_handler->loc, 1);
9904 listsetvar(varlist.list, 0);
9905 /* See above for the rationale */
9906 dowait(DOWAIT_NONBLOCK, NULL);
9907 if (evalfun(cmdentry.u.func, argc, argv, flags))
9910 status = exitstatus;
9915 if (cmd->ncmd.redirect)
9916 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9918 /* dsl: I think this is intended to be used to support
9919 * '_' in 'vi' command mode during line editing...
9920 * However I implemented that within libedit itself.
9922 setvar0("_", lastarg);
9924 popstackmark(&smark);
9930 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9932 char *volatile savecmdname;
9933 struct jmploc *volatile savehandler;
9934 struct jmploc jmploc;
9938 savecmdname = commandname;
9939 savehandler = exception_handler;
9940 i = setjmp(jmploc.loc);
9943 exception_handler = &jmploc;
9944 commandname = argv[0];
9946 optptr = NULL; /* initialize nextopt */
9948 status = evalcmd(argc, argv, flags);
9950 status = (*cmd->builtin)(argc, argv);
9951 flush_stdout_stderr();
9952 status |= ferror(stdout);
9953 exitstatus = status;
9956 commandname = savecmdname;
9957 exception_handler = savehandler;
9963 goodname(const char *p)
9965 return endofname(p)[0] == '\0';
9970 * Search for a command. This is called before we fork so that the
9971 * location of the command will be available in the parent as well as
9972 * the child. The check for "goodname" is an overly conservative
9973 * check that the name will not be subject to expansion.
9976 prehash(union node *n)
9978 struct cmdentry entry;
9980 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9981 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9985 /* ============ Builtin commands
9987 * Builtin commands whose functions are closely tied to evaluation
9988 * are implemented here.
9992 * Handle break and continue commands. Break, continue, and return are
9993 * all handled by setting the evalskip flag. The evaluation routines
9994 * above all check this flag, and if it is set they start skipping
9995 * commands rather than executing them. The variable skipcount is
9996 * the number of loops to break/continue, or the number of function
9997 * levels to return. (The latter is always 1.) It should probably
9998 * be an error to break out of more loops than exist, but it isn't
9999 * in the standard shell so we don't make it one here.
10001 static int FAST_FUNC
10002 breakcmd(int argc UNUSED_PARAM, char **argv)
10004 int n = argv[1] ? number(argv[1]) : 1;
10007 ash_msg_and_raise_error(msg_illnum, argv[1]);
10011 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
10019 * This implements the input routines used by the parser.
10023 INPUT_PUSH_FILE = 1,
10024 INPUT_NOFILE_OK = 2,
10027 static smallint checkkwd;
10028 /* values of checkkwd variable */
10029 #define CHKALIAS 0x1
10034 * Push a string back onto the input at this current parsefile level.
10035 * We handle aliases this way.
10037 #if !ENABLE_ASH_ALIAS
10038 #define pushstring(s, ap) pushstring(s)
10041 pushstring(char *s, struct alias *ap)
10043 struct strpush *sp;
10048 if (g_parsefile->strpush) {
10049 sp = ckzalloc(sizeof(*sp));
10050 sp->prev = g_parsefile->strpush;
10052 sp = &(g_parsefile->basestrpush);
10054 g_parsefile->strpush = sp;
10055 sp->prev_string = g_parsefile->next_to_pgetc;
10056 sp->prev_left_in_line = g_parsefile->left_in_line;
10057 sp->unget = g_parsefile->unget;
10058 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
10059 #if ENABLE_ASH_ALIAS
10062 ap->flag |= ALIASINUSE;
10066 g_parsefile->next_to_pgetc = s;
10067 g_parsefile->left_in_line = len;
10068 g_parsefile->unget = 0;
10075 struct strpush *sp = g_parsefile->strpush;
10078 #if ENABLE_ASH_ALIAS
10080 if (g_parsefile->next_to_pgetc[-1] == ' '
10081 || g_parsefile->next_to_pgetc[-1] == '\t'
10083 checkkwd |= CHKALIAS;
10085 if (sp->string != sp->ap->val) {
10088 sp->ap->flag &= ~ALIASINUSE;
10089 if (sp->ap->flag & ALIASDEAD) {
10090 unalias(sp->ap->name);
10094 g_parsefile->next_to_pgetc = sp->prev_string;
10095 g_parsefile->left_in_line = sp->prev_left_in_line;
10096 g_parsefile->unget = sp->unget;
10097 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
10098 g_parsefile->strpush = sp->prev;
10099 if (sp != &(g_parsefile->basestrpush))
10108 char *buf = g_parsefile->buf;
10110 g_parsefile->next_to_pgetc = buf;
10111 #if ENABLE_FEATURE_EDITING
10113 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
10114 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10117 # if ENABLE_ASH_IDLE_TIMEOUT
10119 const char *tmout_var = lookupvar("TMOUT");
10121 timeout = atoi(tmout_var) * 1000;
10127 # if ENABLE_FEATURE_TAB_COMPLETION
10128 line_input_state->path_lookup = pathval();
10130 reinit_unicode_for_ash();
10131 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
10133 /* ^C pressed, "convert" to SIGINT */
10134 write(STDOUT_FILENO, "^C", 2);
10135 if (trap[SIGINT]) {
10141 exitstatus = 128 + SIGINT;
10147 /* Ctrl+D pressed */
10150 # if ENABLE_ASH_IDLE_TIMEOUT
10151 else if (errno == EAGAIN && timeout > 0) {
10152 puts("\007timed out waiting for input: auto-logout");
10159 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10162 #if 0 /* disabled: nonblock_immune_read() handles this problem */
10164 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
10165 int flags = fcntl(0, F_GETFL);
10166 if (flags >= 0 && (flags & O_NONBLOCK)) {
10167 flags &= ~O_NONBLOCK;
10168 if (fcntl(0, F_SETFL, flags) >= 0) {
10169 out2str("sh: turning off NDELAY mode\n");
10180 * Refill the input buffer and return the next input character:
10182 * 1) If a string was pushed back on the input, pop it;
10183 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
10184 * or we are reading from a string so we can't refill the buffer,
10186 * 3) If there is more stuff in this buffer, use it else call read to fill it.
10187 * 4) Process input up to the next newline, deleting nul characters.
10189 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
10190 #define pgetc_debug(...) ((void)0)
10191 static int pgetc(void);
10198 if (g_parsefile->strpush) {
10199 #if ENABLE_ASH_ALIAS
10200 if (g_parsefile->left_in_line == -1
10201 && g_parsefile->strpush->ap
10202 && g_parsefile->next_to_pgetc[-1] != ' '
10203 && g_parsefile->next_to_pgetc[-1] != '\t'
10205 pgetc_debug("preadbuffer PEOA");
10212 /* on both branches above g_parsefile->left_in_line < 0.
10213 * "pgetc" needs refilling.
10216 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
10217 * pungetc() may increment it a few times.
10218 * Assuming it won't increment it to less than -90.
10220 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
10221 pgetc_debug("preadbuffer PEOF1");
10222 /* even in failure keep left_in_line and next_to_pgetc
10223 * in lock step, for correct multi-layer pungetc.
10224 * left_in_line was decremented before preadbuffer(),
10225 * must inc next_to_pgetc: */
10226 g_parsefile->next_to_pgetc++;
10230 more = g_parsefile->left_in_buffer;
10232 flush_stdout_stderr();
10236 /* don't try reading again */
10237 g_parsefile->left_in_line = -99;
10238 pgetc_debug("preadbuffer PEOF2");
10239 g_parsefile->next_to_pgetc++;
10244 /* Find out where's the end of line.
10245 * Set g_parsefile->left_in_line
10246 * and g_parsefile->left_in_buffer acordingly.
10247 * NUL chars are deleted.
10249 q = g_parsefile->next_to_pgetc;
10257 memmove(q, q + 1, more);
10261 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10267 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10268 if (g_parsefile->left_in_line < 0)
10273 g_parsefile->left_in_buffer = more;
10278 out2str(g_parsefile->next_to_pgetc);
10282 pgetc_debug("preadbuffer at %d:%p'%s'",
10283 g_parsefile->left_in_line,
10284 g_parsefile->next_to_pgetc,
10285 g_parsefile->next_to_pgetc);
10286 return (unsigned char)*g_parsefile->next_to_pgetc++;
10292 g_parsefile->linno++;
10293 setprompt_if(doprompt, 2);
10298 g_parsefile->linno++;
10299 needprompt = doprompt;
10307 pgetc_debug("pgetc at %d:%p'%s'",
10308 g_parsefile->left_in_line,
10309 g_parsefile->next_to_pgetc,
10310 g_parsefile->next_to_pgetc);
10311 if (g_parsefile->unget)
10312 return g_parsefile->lastc[--g_parsefile->unget];
10314 if (--g_parsefile->left_in_line >= 0)
10315 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10319 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10320 g_parsefile->lastc[0] = c;
10325 #if ENABLE_ASH_ALIAS
10327 pgetc_without_PEOA(void)
10331 pgetc_debug("pgetc at %d:%p'%s'",
10332 g_parsefile->left_in_line,
10333 g_parsefile->next_to_pgetc,
10334 g_parsefile->next_to_pgetc);
10336 } while (c == PEOA);
10340 # define pgetc_without_PEOA() pgetc()
10344 * Read a line from the script.
10347 pfgets(char *line, int len)
10353 while (--nleft > 0) {
10354 c = pgetc_without_PEOA();
10369 * Undo a call to pgetc. Only two characters may be pushed back.
10370 * PEOF may be pushed back.
10375 g_parsefile->unget++;
10378 /* This one eats backslash+newline */
10384 while ((c = pgetc()) == '\\') {
10385 if (pgetc() != '\n') {
10397 * To handle the "." command, a stack of input files is used. Pushfile
10398 * adds a new entry to the stack and popfile restores the previous level.
10403 struct parsefile *pf;
10405 pf = ckzalloc(sizeof(*pf));
10406 pf->prev = g_parsefile;
10408 /*pf->strpush = NULL; - ckzalloc did it */
10409 /*pf->basestrpush.prev = NULL;*/
10417 struct parsefile *pf = g_parsefile;
10423 if (pf->pf_fd >= 0)
10426 while (pf->strpush)
10428 g_parsefile = pf->prev;
10434 * Return to top level.
10439 while (g_parsefile != &basepf)
10444 * Close the file(s) that the shell is reading commands from. Called
10445 * after a fork is done.
10451 if (g_parsefile->pf_fd > 0) {
10452 close(g_parsefile->pf_fd);
10453 g_parsefile->pf_fd = 0;
10458 * Like setinputfile, but takes an open file descriptor. Call this with
10462 setinputfd(int fd, int push)
10466 g_parsefile->buf = NULL;
10468 g_parsefile->pf_fd = fd;
10469 if (g_parsefile->buf == NULL)
10470 g_parsefile->buf = ckmalloc(IBUFSIZ);
10471 g_parsefile->left_in_buffer = 0;
10472 g_parsefile->left_in_line = 0;
10473 g_parsefile->linno = 1;
10477 * Set the input to take input from a file. If push is set, push the
10478 * old input onto the stack first.
10481 setinputfile(const char *fname, int flags)
10486 fd = open(fname, O_RDONLY);
10488 if (flags & INPUT_NOFILE_OK)
10491 ash_msg_and_raise_error("can't open '%s'", fname);
10496 close_on_exec_on(fd);
10497 setinputfd(fd, flags & INPUT_PUSH_FILE);
10504 * Like setinputfile, but takes input from a string.
10507 setinputstring(char *string)
10511 g_parsefile->next_to_pgetc = string;
10512 g_parsefile->left_in_line = strlen(string);
10513 g_parsefile->buf = NULL;
10514 g_parsefile->linno = 1;
10520 * Routines to check for mail.
10523 #if ENABLE_ASH_MAIL
10525 /* Hash of mtimes of mailboxes */
10526 static unsigned mailtime_hash;
10527 /* Set if MAIL or MAILPATH is changed. */
10528 static smallint mail_var_path_changed;
10531 * Print appropriate message(s) if mail has arrived.
10532 * If mail_var_path_changed is set,
10533 * then the value of MAIL has mail_var_path_changed,
10534 * so we just update the values.
10543 struct stackmark smark;
10546 setstackmark(&smark);
10547 mpath = mpathset() ? mpathval() : mailval();
10550 p = path_advance(&mpath, nullstr);
10555 for (q = p; *q; q++)
10561 q[-1] = '\0'; /* delete trailing '/' */
10562 if (stat(p, &statb) < 0) {
10565 /* Very simplistic "hash": just a sum of all mtimes */
10566 new_hash += (unsigned)statb.st_mtime;
10568 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10569 if (mailtime_hash != 0)
10570 out2str("you have mail\n");
10571 mailtime_hash = new_hash;
10573 mail_var_path_changed = 0;
10574 popstackmark(&smark);
10577 static void FAST_FUNC
10578 changemail(const char *val UNUSED_PARAM)
10580 mail_var_path_changed = 1;
10583 #endif /* ASH_MAIL */
10586 /* ============ ??? */
10589 * Set the shell parameters.
10592 setparam(char **argv)
10598 for (nparam = 0; argv[nparam]; nparam++)
10600 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10602 *ap++ = ckstrdup(*argv++);
10605 freeparam(&shellparam);
10606 shellparam.malloced = 1;
10607 shellparam.nparam = nparam;
10608 shellparam.p = newparam;
10609 #if ENABLE_ASH_GETOPTS
10610 shellparam.optind = 1;
10611 shellparam.optoff = -1;
10616 * Process shell options. The global variable argptr contains a pointer
10617 * to the argument list; we advance it past the options.
10619 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10620 * For a non-interactive shell, an error condition encountered
10621 * by a special built-in ... shall cause the shell to write a diagnostic message
10622 * to standard error and exit as shown in the following table:
10623 * Error Special Built-In
10625 * Utility syntax error (option or operand error) Shall exit
10627 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10628 * we see that bash does not do that (set "finishes" with error code 1 instead,
10629 * and shell continues), and people rely on this behavior!
10631 * set -o barfoo 2>/dev/null
10634 * Oh well. Let's mimic that.
10637 plus_minus_o(char *name, int val)
10642 for (i = 0; i < NOPTS; i++) {
10643 if (strcmp(name, optnames(i)) == 0) {
10648 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10651 for (i = 0; i < NOPTS; i++) {
10653 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10655 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10661 setoption(int flag, int val)
10665 for (i = 0; i < NOPTS; i++) {
10666 if (optletters(i) == flag) {
10671 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10675 options(int cmdline)
10683 while ((p = *argptr) != NULL) {
10685 if (c != '-' && c != '+')
10688 val = 0; /* val = 0 if c == '+' */
10691 if (p[0] == '\0' || LONE_DASH(p)) {
10693 /* "-" means turn off -x and -v */
10696 /* "--" means reset params */
10697 else if (*argptr == NULL)
10700 break; /* "-" or "--" terminates options */
10703 /* first char was + or - */
10704 while ((c = *p++) != '\0') {
10705 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10706 if (c == 'c' && cmdline) {
10707 minusc = p; /* command is after shell args */
10708 } else if (c == 'o') {
10709 if (plus_minus_o(*argptr, val)) {
10710 /* it already printed err message */
10711 return 1; /* error */
10715 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10717 /* bash does not accept +-login, we also won't */
10718 } else if (cmdline && val && (c == '-')) { /* long options */
10719 if (strcmp(p, "login") == 0)
10731 * The shift builtin command.
10733 static int FAST_FUNC
10734 shiftcmd(int argc UNUSED_PARAM, char **argv)
10741 n = number(argv[1]);
10742 if (n > shellparam.nparam)
10743 n = 0; /* bash compat, was = shellparam.nparam; */
10745 shellparam.nparam -= n;
10746 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10747 if (shellparam.malloced)
10750 ap2 = shellparam.p;
10751 while ((*ap2++ = *ap1++) != NULL)
10753 #if ENABLE_ASH_GETOPTS
10754 shellparam.optind = 1;
10755 shellparam.optoff = -1;
10762 * POSIX requires that 'set' (but not export or readonly) output the
10763 * variables in lexicographic order - by the locale's collating order (sigh).
10764 * Maybe we could keep them in an ordered balanced binary tree
10765 * instead of hashed lists.
10766 * For now just roll 'em through qsort for printing...
10769 showvars(const char *sep_prefix, int on, int off)
10772 char **ep, **epend;
10774 ep = listvars(on, off, &epend);
10775 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10777 sep = *sep_prefix ? " " : sep_prefix;
10779 for (; ep < epend; ep++) {
10783 p = strchrnul(*ep, '=');
10786 q = single_quote(++p);
10787 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10793 * The set command builtin.
10795 static int FAST_FUNC
10796 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10801 return showvars(nullstr, 0, VUNSET);
10804 retval = options(/*cmdline:*/ 0);
10805 if (retval == 0) { /* if no parse error... */
10807 if (*argptr != NULL) {
10815 #if ENABLE_ASH_RANDOM_SUPPORT
10816 static void FAST_FUNC
10817 change_random(const char *value)
10821 if (value == NULL) {
10822 /* "get", generate */
10823 t = next_random(&random_gen);
10824 /* set without recursion */
10825 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10826 vrandom.flags &= ~VNOFUNC;
10829 t = strtoul(value, NULL, 10);
10830 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10835 #if ENABLE_ASH_GETOPTS
10837 getopts(char *optstr, char *optvar, char **optfirst)
10844 int ind = shellparam.optind;
10845 int off = shellparam.optoff;
10849 shellparam.optind = -1;
10850 optnext = optfirst + ind - 1;
10852 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10855 p = optnext[-1] + off;
10856 if (p == NULL || *p == '\0') {
10857 /* Current word is done, advance */
10859 if (p == NULL || *p != '-' || *++p == '\0') {
10866 if (LONE_DASH(p)) /* check for "--" */
10871 for (q = optstr; *q != c;) {
10873 if (optstr[0] == ':') {
10875 /*sbuf[1] = '\0'; - already is */
10876 setvar0("OPTARG", sbuf);
10878 fprintf(stderr, "Illegal option -%c\n", c);
10879 unsetvar("OPTARG");
10889 if (*p == '\0' && (p = *optnext) == NULL) {
10890 if (optstr[0] == ':') {
10892 /*sbuf[1] = '\0'; - already is */
10893 setvar0("OPTARG", sbuf);
10896 fprintf(stderr, "No arg for -%c option\n", c);
10897 unsetvar("OPTARG");
10905 setvar0("OPTARG", p);
10908 setvar0("OPTARG", nullstr);
10910 ind = optnext - optfirst + 1;
10911 setvar("OPTIND", itoa(ind), VNOFUNC);
10913 /*sbuf[1] = '\0'; - already is */
10914 setvar0(optvar, sbuf);
10916 shellparam.optoff = p ? p - *(optnext - 1) : -1;
10917 shellparam.optind = ind;
10923 * The getopts builtin. Shellparam.optnext points to the next argument
10924 * to be processed. Shellparam.optptr points to the next character to
10925 * be processed in the current argument. If shellparam.optnext is NULL,
10926 * then it's the first time getopts has been called.
10928 static int FAST_FUNC
10929 getoptscmd(int argc, char **argv)
10934 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10936 optbase = shellparam.p;
10937 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
10938 shellparam.optind = 1;
10939 shellparam.optoff = -1;
10942 optbase = &argv[3];
10943 if ((unsigned)shellparam.optind > argc - 2) {
10944 shellparam.optind = 1;
10945 shellparam.optoff = -1;
10949 return getopts(argv[1], argv[2], optbase);
10951 #endif /* ASH_GETOPTS */
10954 /* ============ Shell parser */
10957 struct heredoc *next; /* next here document in list */
10958 union node *here; /* redirection node */
10959 char *eofmark; /* string indicating end of input */
10960 smallint striptabs; /* if set, strip leading tabs */
10963 static smallint tokpushback; /* last token pushed back */
10964 static smallint quoteflag; /* set if (part of) last token was quoted */
10965 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10966 static struct heredoc *heredoclist; /* list of here documents to read */
10967 static char *wordtext; /* text of last word returned by readtoken */
10968 static struct nodelist *backquotelist;
10969 static union node *redirnode;
10970 static struct heredoc *heredoc;
10972 static const char *
10973 tokname(char *buf, int tok)
10976 return tokname_array[tok];
10977 sprintf(buf, "\"%s\"", tokname_array[tok]);
10981 /* raise_error_unexpected_syntax:
10982 * Called when an unexpected token is read during the parse. The argument
10983 * is the token that is expected, or -1 if more than one type of token can
10984 * occur at this point.
10986 static void raise_error_unexpected_syntax(int) NORETURN;
10988 raise_error_unexpected_syntax(int token)
10994 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10996 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10997 raise_error_syntax(msg);
11001 #define EOFMARKLEN 79
11003 /* parsing is heavily cross-recursive, need these forward decls */
11004 static union node *andor(void);
11005 static union node *pipeline(void);
11006 static union node *parse_command(void);
11007 static void parseheredoc(void);
11008 static int peektoken(void);
11009 static int readtoken(void);
11011 static union node *
11014 union node *n1, *n2, *n3;
11019 switch (peektoken()) {
11027 if (!n1 && (nlflag & 1))
11033 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11034 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
11040 if (tok == TBACKGND) {
11041 if (n2->type == NPIPE) {
11042 n2->npipe.pipe_backgnd = 1;
11044 if (n2->type != NREDIR) {
11045 n3 = stzalloc(sizeof(struct nredir));
11047 /*n3->nredir.redirect = NULL; - stzalloc did it */
11050 n2->type = NBACKGND;
11056 n3 = stzalloc(sizeof(struct nbinary));
11058 n3->nbinary.ch1 = n1;
11059 n3->nbinary.ch2 = n2;
11072 raise_error_unexpected_syntax(-1);
11079 static union node *
11082 union node *n1, *n2, *n3;
11090 } else if (t == TOR) {
11096 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11098 n3 = stzalloc(sizeof(struct nbinary));
11100 n3->nbinary.ch1 = n1;
11101 n3->nbinary.ch2 = n2;
11106 static union node *
11109 union node *n1, *n2, *pipenode;
11110 struct nodelist *lp, *prev;
11114 TRACE(("pipeline: entered\n"));
11115 if (readtoken() == TNOT) {
11117 checkkwd = CHKKWD | CHKALIAS;
11120 n1 = parse_command();
11121 if (readtoken() == TPIPE) {
11122 pipenode = stzalloc(sizeof(struct npipe));
11123 pipenode->type = NPIPE;
11124 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
11125 lp = stzalloc(sizeof(struct nodelist));
11126 pipenode->npipe.cmdlist = lp;
11130 lp = stzalloc(sizeof(struct nodelist));
11131 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11132 lp->n = parse_command();
11134 } while (readtoken() == TPIPE);
11140 n2 = stzalloc(sizeof(struct nnot));
11148 static union node *
11153 n = stzalloc(sizeof(struct narg));
11155 /*n->narg.next = NULL; - stzalloc did it */
11156 n->narg.text = wordtext;
11157 n->narg.backquote = backquotelist;
11162 fixredir(union node *n, const char *text, int err)
11166 TRACE(("Fix redir %s %d\n", text, err));
11168 n->ndup.vname = NULL;
11170 fd = bb_strtou(text, NULL, 10);
11171 if (!errno && fd >= 0)
11172 n->ndup.dupfd = fd;
11173 else if (LONE_DASH(text))
11174 n->ndup.dupfd = -1;
11177 raise_error_syntax("bad fd number");
11178 n->ndup.vname = makename();
11183 * Returns true if the text contains nothing to expand (no dollar signs
11187 noexpand(const char *text)
11191 while ((c = *text++) != '\0') {
11192 if (c == CTLQUOTEMARK)
11196 else if (SIT(c, BASESYNTAX) == CCTL)
11205 union node *n = redirnode;
11207 if (readtoken() != TWORD)
11208 raise_error_unexpected_syntax(-1);
11209 if (n->type == NHERE) {
11210 struct heredoc *here = heredoc;
11214 if (quoteflag == 0)
11216 TRACE(("Here document %d\n", n->type));
11217 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
11218 raise_error_syntax("illegal eof marker for << redirection");
11219 rmescapes(wordtext, 0);
11220 here->eofmark = wordtext;
11222 if (heredoclist == NULL)
11223 heredoclist = here;
11225 for (p = heredoclist; p->next; p = p->next)
11229 } else if (n->type == NTOFD || n->type == NFROMFD) {
11230 fixredir(n, wordtext, 0);
11232 n->nfile.fname = makename();
11236 static union node *
11239 union node *args, **app;
11240 union node *n = NULL;
11241 union node *vars, **vpp;
11242 union node **rpp, *redir;
11245 smallint double_brackets_flag = 0;
11247 IF_BASH_FUNCTION(smallint function_flag = 0;)
11256 savecheckkwd = CHKALIAS;
11259 checkkwd = savecheckkwd;
11264 if (peektoken() != TWORD)
11265 raise_error_unexpected_syntax(TWORD);
11270 case TAND: /* "&&" */
11271 case TOR: /* "||" */
11272 if (!double_brackets_flag) {
11276 wordtext = (char *) (t == TAND ? "-a" : "-o");
11279 n = stzalloc(sizeof(struct narg));
11281 /*n->narg.next = NULL; - stzalloc did it */
11282 n->narg.text = wordtext;
11284 if (strcmp("[[", wordtext) == 0)
11285 double_brackets_flag = 1;
11286 else if (strcmp("]]", wordtext) == 0)
11287 double_brackets_flag = 0;
11289 n->narg.backquote = backquotelist;
11290 if (savecheckkwd && isassignment(wordtext)) {
11292 vpp = &n->narg.next;
11295 app = &n->narg.next;
11299 if (function_flag) {
11300 checkkwd = CHKNL | CHKKWD;
11301 switch (peektoken()) {
11313 if (strcmp("[[", wordtext) == 0)
11317 raise_error_unexpected_syntax(-1);
11323 *rpp = n = redirnode;
11324 rpp = &n->nfile.next;
11325 parsefname(); /* read name of redirection file */
11328 IF_BASH_FUNCTION(do_func:)
11329 if (args && app == &args->narg.next
11332 struct builtincmd *bcmd;
11335 /* We have a function */
11336 if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
11337 raise_error_unexpected_syntax(TRP);
11338 name = n->narg.text;
11339 if (!goodname(name)
11340 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11342 raise_error_syntax("bad function name");
11345 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11346 n->narg.next = parse_command();
11349 IF_BASH_FUNCTION(function_flag = 0;)
11360 n = stzalloc(sizeof(struct ncmd));
11362 n->ncmd.args = args;
11363 n->ncmd.assign = vars;
11364 n->ncmd.redirect = redir;
11368 static union node *
11369 parse_command(void)
11371 union node *n1, *n2;
11372 union node *ap, **app;
11373 union node *cp, **cpp;
11374 union node *redir, **rpp;
11381 switch (readtoken()) {
11383 raise_error_unexpected_syntax(-1);
11386 n1 = stzalloc(sizeof(struct nif));
11388 n1->nif.test = list(0);
11389 if (readtoken() != TTHEN)
11390 raise_error_unexpected_syntax(TTHEN);
11391 n1->nif.ifpart = list(0);
11393 while (readtoken() == TELIF) {
11394 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11395 n2 = n2->nif.elsepart;
11397 n2->nif.test = list(0);
11398 if (readtoken() != TTHEN)
11399 raise_error_unexpected_syntax(TTHEN);
11400 n2->nif.ifpart = list(0);
11402 if (lasttoken == TELSE)
11403 n2->nif.elsepart = list(0);
11405 n2->nif.elsepart = NULL;
11413 n1 = stzalloc(sizeof(struct nbinary));
11414 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11415 n1->nbinary.ch1 = list(0);
11418 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11419 got == TWORD ? wordtext : ""));
11420 raise_error_unexpected_syntax(TDO);
11422 n1->nbinary.ch2 = list(0);
11427 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11428 raise_error_syntax("bad for loop variable");
11429 n1 = stzalloc(sizeof(struct nfor));
11431 n1->nfor.var = wordtext;
11432 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11433 if (readtoken() == TIN) {
11435 while (readtoken() == TWORD) {
11436 n2 = stzalloc(sizeof(struct narg));
11438 /*n2->narg.next = NULL; - stzalloc did it */
11439 n2->narg.text = wordtext;
11440 n2->narg.backquote = backquotelist;
11442 app = &n2->narg.next;
11445 n1->nfor.args = ap;
11446 if (lasttoken != TNL && lasttoken != TSEMI)
11447 raise_error_unexpected_syntax(-1);
11449 n2 = stzalloc(sizeof(struct narg));
11451 /*n2->narg.next = NULL; - stzalloc did it */
11452 n2->narg.text = (char *)dolatstr;
11453 /*n2->narg.backquote = NULL;*/
11454 n1->nfor.args = n2;
11456 * Newline or semicolon here is optional (but note
11457 * that the original Bourne shell only allowed NL).
11459 if (lasttoken != TSEMI)
11462 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11463 if (readtoken() != TDO)
11464 raise_error_unexpected_syntax(TDO);
11465 n1->nfor.body = list(0);
11469 n1 = stzalloc(sizeof(struct ncase));
11471 if (readtoken() != TWORD)
11472 raise_error_unexpected_syntax(TWORD);
11473 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11475 /*n2->narg.next = NULL; - stzalloc did it */
11476 n2->narg.text = wordtext;
11477 n2->narg.backquote = backquotelist;
11478 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11479 if (readtoken() != TIN)
11480 raise_error_unexpected_syntax(TIN);
11481 cpp = &n1->ncase.cases;
11483 checkkwd = CHKNL | CHKKWD;
11485 while (t != TESAC) {
11486 if (lasttoken == TLP)
11488 *cpp = cp = stzalloc(sizeof(struct nclist));
11490 app = &cp->nclist.pattern;
11492 *app = ap = stzalloc(sizeof(struct narg));
11494 /*ap->narg.next = NULL; - stzalloc did it */
11495 ap->narg.text = wordtext;
11496 ap->narg.backquote = backquotelist;
11497 if (readtoken() != TPIPE)
11499 app = &ap->narg.next;
11502 //ap->narg.next = NULL;
11503 if (lasttoken != TRP)
11504 raise_error_unexpected_syntax(TRP);
11505 cp->nclist.body = list(2);
11507 cpp = &cp->nclist.next;
11509 checkkwd = CHKNL | CHKKWD;
11513 raise_error_unexpected_syntax(TENDCASE);
11520 n1 = stzalloc(sizeof(struct nredir));
11521 n1->type = NSUBSHELL;
11522 n1->nredir.n = list(0);
11523 /*n1->nredir.redirect = NULL; - stzalloc did it */
11530 IF_BASH_FUNCTION(case TFUNCTION:)
11534 return simplecmd();
11537 if (readtoken() != t)
11538 raise_error_unexpected_syntax(t);
11541 /* Now check for redirection which may follow command */
11542 checkkwd = CHKKWD | CHKALIAS;
11544 while (readtoken() == TREDIR) {
11545 *rpp = n2 = redirnode;
11546 rpp = &n2->nfile.next;
11552 if (n1->type != NSUBSHELL) {
11553 n2 = stzalloc(sizeof(struct nredir));
11558 n1->nredir.redirect = redir;
11563 #if BASH_DOLLAR_SQUOTE
11565 decode_dollar_squote(void)
11567 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11573 p = strchr(C_escapes, c);
11578 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11582 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11584 } else if (c == 'x') { /* \xHH */
11588 } while (isxdigit(c) && --cnt);
11590 if (cnt == 3) { /* \x but next char is "bad" */
11594 } else { /* simple seq like \\ or \t */
11599 c = bb_process_escape_sequence((void*)&p);
11600 } else { /* unrecognized "\z": print both chars unless ' or " */
11601 if (c != '\'' && c != '"') {
11603 c |= 0x100; /* "please encode \, then me" */
11611 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11612 * is not NULL, read a here document. In the latter case, eofmark is the
11613 * word which marks the end of the document and striptabs is true if
11614 * leading tabs should be stripped from the document. The argument c
11615 * is the first character of the input token or document.
11617 * Because C does not have internal subroutines, I have simulated them
11618 * using goto's to implement the subroutine linkage. The following macros
11619 * will run code that appears at the end of readtoken1.
11621 #define CHECKEND() {goto checkend; checkend_return:;}
11622 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11623 #define PARSESUB() {goto parsesub; parsesub_return:;}
11624 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11625 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11626 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11628 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11630 /* NB: syntax parameter fits into smallint */
11631 /* c parameter is an unsigned char or PEOF or PEOA */
11634 char line[EOFMARKLEN + 1];
11635 struct nodelist *bqlist;
11639 IF_FEATURE_SH_MATH(smallint prevsyntax;) /* syntax before arithmetic */
11640 smallint pssyntax; /* we are expanding a prompt string */
11641 int varnest; /* levels of variables expansion */
11642 IF_FEATURE_SH_MATH(int arinest;) /* levels of arithmetic expansion */
11643 IF_FEATURE_SH_MATH(int parenlevel;) /* levels of parens in arithmetic */
11644 int dqvarnest; /* levels of variables expansion within double quotes */
11646 IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
11648 startlinno = g_parsefile->linno;
11651 IF_FEATURE_SH_MATH(prevsyntax = 0;)
11652 pssyntax = (syntax == PSSYNTAX);
11655 dblquote = (syntax == DQSYNTAX);
11657 IF_FEATURE_SH_MATH(arinest = 0;)
11658 IF_FEATURE_SH_MATH(parenlevel = 0;)
11661 STARTSTACKSTR(out);
11663 /* For each line, until end of word */
11664 CHECKEND(); /* set c to PEOF if at end of here document */
11665 for (;;) { /* until end of line or end of word */
11666 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11667 switch (SIT(c, syntax)) {
11668 case CNL: /* '\n' */
11669 if (syntax == BASESYNTAX)
11670 goto endword; /* exit outer loop */
11674 goto loop; /* continue outer loop */
11679 #if BASH_DOLLAR_SQUOTE
11680 if (c == '\\' && bash_dollar_squote) {
11681 c = decode_dollar_squote();
11683 /* skip $'\000', $'\x00' (like bash) */
11687 /* Unknown escape. Encode as '\z' */
11688 c = (unsigned char)c;
11689 if (eofmark == NULL || dblquote)
11690 USTPUTC(CTLESC, out);
11691 USTPUTC('\\', out);
11695 if (eofmark == NULL || dblquote)
11696 USTPUTC(CTLESC, out);
11699 case CBACK: /* backslash */
11700 c = pgetc_without_PEOA();
11702 USTPUTC(CTLESC, out);
11703 USTPUTC('\\', out);
11705 } else if (c == '\n') {
11708 if (c == '$' && pssyntax) {
11709 USTPUTC(CTLESC, out);
11710 USTPUTC('\\', out);
11712 /* Backslash is retained if we are in "str" and next char isn't special */
11717 && (c != '"' || eofmark != NULL)
11719 USTPUTC('\\', out);
11721 USTPUTC(CTLESC, out);
11729 if (eofmark == NULL) {
11730 USTPUTC(CTLQUOTEMARK, out);
11738 IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
11739 if (eofmark != NULL && varnest == 0) {
11742 if (dqvarnest == 0) {
11743 syntax = BASESYNTAX;
11750 case CVAR: /* '$' */
11751 PARSESUB(); /* parse substitution */
11753 case CENDVAR: /* '}' */
11756 if (dqvarnest > 0) {
11763 #if ENABLE_FEATURE_SH_MATH
11764 case CLP: /* '(' in arithmetic */
11768 case CRP: /* ')' in arithmetic */
11769 if (parenlevel > 0) {
11772 if (pgetc_eatbnl() == ')') {
11774 if (--arinest == 0) {
11775 syntax = prevsyntax;
11779 * unbalanced parens
11780 * (don't 2nd guess - no error)
11788 case CBQUOTE: /* '`' */
11792 goto endword; /* exit outer loop */
11796 if (varnest == 0) {
11797 #if BASH_REDIR_OUTPUT
11799 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11800 if (pgetc() == '>')
11801 c = 0x100 + '>'; /* flag &> */
11805 goto endword; /* exit outer loop */
11807 IF_ASH_ALIAS(if (c != PEOA))
11814 #if ENABLE_FEATURE_SH_MATH
11815 if (syntax == ARISYNTAX)
11816 raise_error_syntax("missing '))'");
11818 if (syntax != BASESYNTAX && eofmark == NULL)
11819 raise_error_syntax("unterminated quoted string");
11820 if (varnest != 0) {
11821 startlinno = g_parsefile->linno;
11823 raise_error_syntax("missing '}'");
11825 USTPUTC('\0', out);
11826 len = out - (char *)stackblock();
11827 out = stackblock();
11828 if (eofmark == NULL) {
11829 if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
11832 if (isdigit_str9(out)) {
11833 PARSEREDIR(); /* passed as params: out, c */
11834 lasttoken = TREDIR;
11837 /* else: non-number X seen, interpret it
11838 * as "NNNX>file" = "NNNX >file" */
11842 quoteflag = quotef;
11843 backquotelist = bqlist;
11844 grabstackblock(len);
11848 /* end of readtoken routine */
11851 * Check to see whether we are at the end of the here document. When this
11852 * is called, c is set to the first character of the next input line. If
11853 * we are at the end of the here document, this routine sets the c to PEOF.
11857 #if ENABLE_ASH_ALIAS
11859 c = pgetc_without_PEOA();
11862 while (c == '\t') {
11863 c = pgetc_without_PEOA();
11866 if (c == *eofmark) {
11867 if (pfgets(line, sizeof(line)) != NULL) {
11872 for (q = eofmark + 1;; p++, q++) {
11876 if (!*q || cc != *q)
11883 pushstring(line, NULL);
11888 goto checkend_return;
11892 * Parse a redirection operator. The variable "out" points to a string
11893 * specifying the fd to be redirected. The variable "c" contains the
11894 * first character of the redirection operator.
11897 /* out is already checked to be a valid number or "" */
11898 int fd = (*out == '\0' ? -1 : atoi(out));
11901 np = stzalloc(sizeof(struct nfile));
11906 np->type = NAPPEND;
11908 np->type = NCLOBBER;
11911 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11917 #if BASH_REDIR_OUTPUT
11918 else if (c == 0x100 + '>') { /* this flags &> redirection */
11920 pgetc(); /* this is '>', no need to check */
11924 else { /* c == '<' */
11925 /*np->nfile.fd = 0; - stzalloc did it */
11929 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11930 np = stzalloc(sizeof(struct nhere));
11931 /*np->nfile.fd = 0; - stzalloc did it */
11934 heredoc = stzalloc(sizeof(struct heredoc));
11935 heredoc->here = np;
11938 heredoc->striptabs = 1;
11940 /*heredoc->striptabs = 0; - stzalloc did it */
11946 np->type = NFROMFD;
11950 np->type = NFROMTO;
11962 goto parseredir_return;
11966 * Parse a substitution. At this point, we have read the dollar sign
11967 * and nothing else.
11970 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11971 * (assuming ascii char codes, as the original implementation did) */
11972 #define is_special(c) \
11973 (((unsigned)(c) - 33 < 32) \
11974 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11976 unsigned char subtype;
11979 c = pgetc_eatbnl();
11980 if (c > 255 /* PEOA or PEOF */
11981 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11983 #if BASH_DOLLAR_SQUOTE
11984 if (syntax != DQSYNTAX && c == '\'')
11985 bash_dollar_squote = 1;
11990 } else if (c == '(') {
11991 /* $(command) or $((arith)) */
11992 if (pgetc_eatbnl() == '(') {
11993 #if ENABLE_FEATURE_SH_MATH
11996 raise_error_syntax("support for $((arith)) is disabled");
12003 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
12004 USTPUTC(CTLVAR, out);
12005 typeloc = out - (char *)stackblock();
12007 subtype = VSNORMAL;
12009 c = pgetc_eatbnl();
12014 /* $[{[#]]NAME[}] */
12017 c = pgetc_eatbnl();
12018 } while (is_in_name(c));
12019 } else if (isdigit(c)) {
12020 /* $[{[#]]NUM[}] */
12023 c = pgetc_eatbnl();
12024 } while (isdigit(c));
12025 } else if (is_special(c)) {
12026 /* $[{[#]]<specialchar>[}] */
12029 c = pgetc_eatbnl();
12030 if (!subtype && cc == '#') {
12031 subtype = VSLENGTH;
12032 if (c == '_' || isalnum(c))
12035 c = pgetc_eatbnl();
12036 if (cc == '}' || c != '}') {
12047 if (c != '}' && subtype == VSLENGTH) {
12048 /* ${#VAR didn't end with } */
12052 if (subtype == 0) {
12053 static const char types[] ALIGN1 = "}-+?=";
12054 /* ${VAR...} but not $VAR or ${#VAR} */
12055 /* c == first char after VAR */
12058 c = pgetc_eatbnl();
12060 /* This check is only needed to not misinterpret
12061 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
12064 if (!strchr(types, c)) {
12065 subtype = VSSUBSTR;
12067 break; /* "goto badsub" is bigger (!) */
12073 const char *p = strchr(types, c);
12076 subtype |= p - types + VSNORMAL;
12082 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
12083 c = pgetc_eatbnl();
12089 #if BASH_PATTERN_SUBST
12091 /* ${v/[/]pattern/repl} */
12092 //TODO: encode pattern and repl separately.
12093 // Currently ${v/$var_with_slash/repl} is horribly broken
12094 subtype = VSREPLACE;
12095 c = pgetc_eatbnl();
12098 subtype++; /* VSREPLACEALL */
12106 ((unsigned char *)stackblock())[typeloc] = subtype;
12107 if (subtype != VSNORMAL) {
12114 goto parsesub_return;
12118 * Called to parse command substitutions. Newstyle is set if the command
12119 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
12120 * list of commands (passed by reference), and savelen is the number of
12121 * characters on the top of the stack which must be preserved.
12124 struct nodelist **nlpp;
12128 smallint saveprompt = 0;
12131 savelen = out - (char *)stackblock();
12134 * FIXME: this can allocate very large block on stack and SEGV.
12136 * echo "..<100kbytes>..`true` $(true) `true` ..."
12137 * allocates 100kb for every command subst. With about
12138 * a hundred command substitutions stack overflows.
12139 * With larger prepended string, SEGV happens sooner.
12141 str = alloca(savelen);
12142 memcpy(str, stackblock(), savelen);
12146 /* We must read until the closing backquote, giving special
12147 * treatment to some slashes, and then push the string and
12148 * reread it as input, interpreting it normally.
12154 STARTSTACKSTR(pout);
12158 setprompt_if(needprompt, 2);
12169 * If eating a newline, avoid putting
12170 * the newline into the new character
12171 * stream (via the STPUTC after the
12176 if (pc != '\\' && pc != '`' && pc != '$'
12177 && (!dblquote || pc != '"')
12179 STPUTC('\\', pout);
12181 if (pc <= 255 /* not PEOA or PEOF */) {
12187 IF_ASH_ALIAS(case PEOA:)
12188 startlinno = g_parsefile->linno;
12189 raise_error_syntax("EOF in backquote substitution");
12201 STPUTC('\0', pout);
12202 psavelen = pout - (char *)stackblock();
12203 if (psavelen > 0) {
12204 pstr = grabstackstr(pout);
12205 setinputstring(pstr);
12210 nlpp = &(*nlpp)->next;
12211 *nlpp = stzalloc(sizeof(**nlpp));
12212 /* (*nlpp)->next = NULL; - stzalloc did it */
12215 saveprompt = doprompt;
12222 doprompt = saveprompt;
12223 else if (readtoken() != TRP)
12224 raise_error_unexpected_syntax(TRP);
12229 * Start reading from old file again, ignoring any pushed back
12230 * tokens left from the backquote parsing
12235 while (stackblocksize() <= savelen)
12237 STARTSTACKSTR(out);
12239 memcpy(out, str, savelen);
12240 STADJUST(savelen, out);
12242 USTPUTC(CTLBACKQ, out);
12244 goto parsebackq_oldreturn;
12245 goto parsebackq_newreturn;
12248 #if ENABLE_FEATURE_SH_MATH
12250 * Parse an arithmetic expansion (indicate start of one and set state)
12253 if (++arinest == 1) {
12254 prevsyntax = syntax;
12255 syntax = ARISYNTAX;
12257 USTPUTC(CTLARI, out);
12258 goto parsearith_return;
12261 } /* end of readtoken */
12264 * Read the next input token.
12265 * If the token is a word, we set backquotelist to the list of cmds in
12266 * backquotes. We set quoteflag to true if any part of the word was
12268 * If the token is TREDIR, then we set redirnode to a structure containing
12270 * In all cases, the variable startlinno is set to the number of the line
12271 * on which the token starts.
12273 * [Change comment: here documents and internal procedures]
12274 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12275 * word parsing code into a separate routine. In this case, readtoken
12276 * doesn't need to have any internal procedures, but parseword does.
12277 * We could also make parseoperator in essence the main routine, and
12278 * have parseword (readtoken1?) handle both words and redirection.]
12280 #define NEW_xxreadtoken
12281 #ifdef NEW_xxreadtoken
12282 /* singles must be first! */
12283 static const char xxreadtoken_chars[7] ALIGN1 = {
12284 '\n', '(', ')', /* singles */
12285 '&', '|', ';', /* doubles */
12289 #define xxreadtoken_singles 3
12290 #define xxreadtoken_doubles 3
12292 static const char xxreadtoken_tokens[] ALIGN1 = {
12293 TNL, TLP, TRP, /* only single occurrence allowed */
12294 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12295 TEOF, /* corresponds to trailing nul */
12296 TAND, TOR, TENDCASE /* if double occurrence */
12308 setprompt_if(needprompt, 2);
12309 startlinno = g_parsefile->linno;
12310 for (;;) { /* until token or start of word found */
12312 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12316 while ((c = pgetc()) != '\n' && c != PEOF)
12319 } else if (c == '\\') {
12320 if (pgetc() != '\n') {
12322 break; /* return readtoken1(...) */
12328 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12334 p = strchr(xxreadtoken_chars, c);
12336 break; /* return readtoken1(...) */
12338 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12340 if (cc == c) { /* double occurrence? */
12341 p += xxreadtoken_doubles + 1;
12344 #if BASH_REDIR_OUTPUT
12345 if (c == '&' && cc == '>') /* &> */
12346 break; /* return readtoken1(...) */
12351 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12356 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12358 #else /* old xxreadtoken */
12359 #define RETURN(token) return lasttoken = token
12369 setprompt_if(needprompt, 2);
12370 startlinno = g_parsefile->linno;
12371 for (;;) { /* until token or start of word found */
12374 case ' ': case '\t':
12375 IF_ASH_ALIAS(case PEOA:)
12378 while ((c = pgetc()) != '\n' && c != PEOF)
12383 if (pgetc() == '\n') {
12395 if (pgetc() == '&')
12400 if (pgetc() == '|')
12405 if (pgetc() == ';')
12418 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12421 #endif /* old xxreadtoken */
12427 int kwd = checkkwd;
12429 smallint alreadyseen = tokpushback;
12432 #if ENABLE_ASH_ALIAS
12448 if (t != TWORD || quoteflag) {
12453 * check for keywords
12455 if (kwd & CHKKWD) {
12456 const char *const *pp;
12458 pp = findkwd(wordtext);
12460 lasttoken = t = pp - tokname_array;
12461 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12466 if (checkkwd & CHKALIAS) {
12467 #if ENABLE_ASH_ALIAS
12469 ap = lookupalias(wordtext, 1);
12472 pushstring(ap->val, ap);
12482 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12484 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12500 * Read and parse a command. Returns NODE_EOF on end of file.
12501 * (NULL is a valid parse tree indicating a blank line.)
12503 static union node *
12504 parsecmd(int interact)
12509 doprompt = interact;
12510 setprompt_if(doprompt, doprompt);
12516 * Input any here documents.
12521 struct heredoc *here;
12524 here = heredoclist;
12525 heredoclist = NULL;
12528 setprompt_if(needprompt, 2);
12529 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12530 here->eofmark, here->striptabs);
12531 n = stzalloc(sizeof(struct narg));
12532 n->narg.type = NARG;
12533 /*n->narg.next = NULL; - stzalloc did it */
12534 n->narg.text = wordtext;
12535 n->narg.backquote = backquotelist;
12536 here->here->nhere.doc = n;
12543 * called by editline -- any expansions to the prompt should be added here.
12545 static const char *
12546 expandstr(const char *ps)
12551 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12552 * and token processing _can_ alter it (delete NULs etc). */
12553 setinputstring((char *)ps);
12555 saveprompt = doprompt;
12557 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12558 doprompt = saveprompt;
12562 n.narg.type = NARG;
12563 n.narg.next = NULL;
12564 n.narg.text = wordtext;
12565 n.narg.backquote = backquotelist;
12567 expandarg(&n, NULL, EXP_QUOTED);
12568 return stackblock();
12572 * Execute a command or commands contained in a string.
12575 evalstring(char *s, int flags)
12577 struct jmploc *volatile savehandler;
12578 struct jmploc jmploc;
12582 struct stackmark smark;
12587 setstackmark(&smark);
12590 /* On exception inside execution loop, we must popfile().
12591 * Try interactively:
12593 * command eval "a=b" # throws "is read only" error
12594 * "command BLTIN" is not supposed to abort (even in non-interactive use).
12595 * But if we skip popfile(), we hit EOF in eval's string, and exit.
12597 savehandler = exception_handler;
12598 ex = setjmp(jmploc.loc);
12601 exception_handler = &jmploc;
12603 while ((n = parsecmd(0)) != NODE_EOF) {
12606 i = evaltree(n, flags);
12609 popstackmark(&smark);
12614 popstackmark(&smark);
12618 exception_handler = savehandler;
12620 longjmp(exception_handler->loc, ex);
12626 * The eval command.
12628 static int FAST_FUNC
12629 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12638 STARTSTACKSTR(concat);
12640 concat = stack_putstr(p, concat);
12644 STPUTC(' ', concat);
12646 STPUTC('\0', concat);
12647 p = grabstackstr(concat);
12649 return evalstring(p, flags & EV_TESTED);
12655 * Read and execute commands.
12656 * "Top" is nonzero for the top level command loop;
12657 * it turns on prompting if the shell is interactive.
12663 struct stackmark smark;
12668 TRACE(("cmdloop(%d) called\n", top));
12672 setstackmark(&smark);
12675 showjobs(SHOW_CHANGED|SHOW_STDERR);
12678 if (iflag && top) {
12682 n = parsecmd(inter);
12684 if (DEBUG > 2 && debug && (n != NODE_EOF))
12687 if (n == NODE_EOF) {
12688 if (!top || numeof >= 50)
12690 if (!stoppedjobs()) {
12693 out2str("\nUse \"exit\" to leave shell.\n");
12696 } else if (nflag == 0) {
12699 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12702 i = evaltree(n, 0);
12706 popstackmark(&smark);
12710 evalskip &= ~SKIPFUNC;
12718 * Take commands from a file. To be compatible we should do a path
12719 * search for the file, which is necessary to find sub-commands.
12722 find_dot_file(char *name)
12725 const char *path = pathval();
12728 /* don't try this for absolute or relative paths */
12729 if (strchr(name, '/'))
12732 while ((fullname = path_advance(&path, name)) != NULL) {
12733 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12735 * Don't bother freeing here, since it will
12736 * be freed by the caller.
12740 if (fullname != name)
12741 stunalloc(fullname);
12744 /* not found in the PATH */
12745 ash_msg_and_raise_error("%s: not found", name);
12749 static int FAST_FUNC
12750 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12752 /* "false; . empty_file; echo $?" should print 0, not 1: */
12756 char *args_need_save;
12757 struct strlist *sp;
12758 volatile struct shparam saveparam;
12760 for (sp = cmdenviron; sp; sp = sp->next)
12761 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12763 nextopt(nullstr); /* handle possible "--" */
12767 /* bash says: "bash: .: filename argument required" */
12768 return 2; /* bash compat */
12771 /* This aborts if file isn't found, which is POSIXly correct.
12772 * bash returns exitcode 1 instead.
12774 fullname = find_dot_file(argv[0]);
12776 args_need_save = argv[0];
12777 if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
12779 saveparam = shellparam;
12780 shellparam.malloced = 0;
12784 shellparam.nparam = argc;
12785 shellparam.p = argv;
12788 /* This aborts if file can't be opened, which is POSIXly correct.
12789 * bash returns exitcode 1 instead.
12791 setinputfile(fullname, INPUT_PUSH_FILE);
12792 commandname = fullname;
12793 status = cmdloop(0);
12796 if (args_need_save) {
12797 freeparam(&shellparam);
12798 shellparam = saveparam;
12804 static int FAST_FUNC
12805 exitcmd(int argc UNUSED_PARAM, char **argv)
12810 exitstatus = number(argv[1]);
12811 raise_exception(EXEXIT);
12816 * Read a file containing shell functions.
12819 readcmdfile(char *name)
12821 setinputfile(name, INPUT_PUSH_FILE);
12827 /* ============ find_command inplementation */
12830 * Resolve a command name. If you change this routine, you may have to
12831 * change the shellexec routine as well.
12834 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12836 struct tblentry *cmdp;
12843 struct builtincmd *bcmd;
12845 /* If name contains a slash, don't use PATH or hash table */
12846 if (strchr(name, '/') != NULL) {
12847 entry->u.index = -1;
12848 if (act & DO_ABS) {
12849 while (stat(name, &statb) < 0) {
12851 if (errno == EINTR)
12854 entry->cmdtype = CMDUNKNOWN;
12858 entry->cmdtype = CMDNORMAL;
12862 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12864 updatetbl = (path == pathval());
12867 if (strstr(path, "%builtin") != NULL)
12868 act |= DO_ALTBLTIN;
12871 /* If name is in the table, check answer will be ok */
12872 cmdp = cmdlookup(name, 0);
12873 if (cmdp != NULL) {
12876 switch (cmdp->cmdtype) {
12894 } else if (cmdp->rehash == 0)
12895 /* if not invalidated by cd, we're done */
12899 /* If %builtin not in path, check for builtin next */
12900 bcmd = find_builtin(name);
12902 if (IS_BUILTIN_REGULAR(bcmd))
12903 goto builtin_success;
12904 if (act & DO_ALTPATH) {
12905 if (!(act & DO_ALTBLTIN))
12906 goto builtin_success;
12907 } else if (builtinloc <= 0) {
12908 goto builtin_success;
12912 #if ENABLE_FEATURE_SH_STANDALONE
12914 int applet_no = find_applet_by_name(name);
12915 if (applet_no >= 0) {
12916 entry->cmdtype = CMDNORMAL;
12917 entry->u.index = -2 - applet_no;
12923 /* We have to search path. */
12924 prev = -1; /* where to start */
12925 if (cmdp && cmdp->rehash) { /* doing a rehash */
12926 if (cmdp->cmdtype == CMDBUILTIN)
12929 prev = cmdp->param.index;
12935 while ((fullname = path_advance(&path, name)) != NULL) {
12936 stunalloc(fullname);
12937 /* NB: code below will still use fullname
12938 * despite it being "unallocated" */
12941 if (prefix(pathopt, "builtin")) {
12943 goto builtin_success;
12946 if ((act & DO_NOFUNC)
12947 || !prefix(pathopt, "func")
12948 ) { /* ignore unimplemented options */
12952 /* if rehash, don't redo absolute path names */
12953 if (fullname[0] == '/' && idx <= prev) {
12956 TRACE(("searchexec \"%s\": no change\n", name));
12959 while (stat(fullname, &statb) < 0) {
12961 if (errno == EINTR)
12964 if (errno != ENOENT && errno != ENOTDIR)
12968 e = EACCES; /* if we fail, this will be the error */
12969 if (!S_ISREG(statb.st_mode))
12971 if (pathopt) { /* this is a %func directory */
12972 stalloc(strlen(fullname) + 1);
12973 /* NB: stalloc will return space pointed by fullname
12974 * (because we don't have any intervening allocations
12975 * between stunalloc above and this stalloc) */
12976 readcmdfile(fullname);
12977 cmdp = cmdlookup(name, 0);
12978 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12979 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12980 stunalloc(fullname);
12983 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12985 entry->cmdtype = CMDNORMAL;
12986 entry->u.index = idx;
12990 cmdp = cmdlookup(name, 1);
12991 cmdp->cmdtype = CMDNORMAL;
12992 cmdp->param.index = idx;
12997 /* We failed. If there was an entry for this command, delete it */
12998 if (cmdp && updatetbl)
12999 delete_cmd_entry();
13001 ash_msg("%s: %s", name, errmsg(e, "not found"));
13002 entry->cmdtype = CMDUNKNOWN;
13007 entry->cmdtype = CMDBUILTIN;
13008 entry->u.cmd = bcmd;
13012 cmdp = cmdlookup(name, 1);
13013 cmdp->cmdtype = CMDBUILTIN;
13014 cmdp->param.cmd = bcmd;
13018 entry->cmdtype = cmdp->cmdtype;
13019 entry->u = cmdp->param;
13024 * The trap builtin.
13026 static int FAST_FUNC
13027 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13031 int signo, exitcode;
13036 for (signo = 0; signo < NSIG; signo++) {
13037 char *tr = trap_ptr[signo];
13039 /* note: bash adds "SIG", but only if invoked
13040 * as "bash". If called as "sh", or if set -o posix,
13041 * then it prints short signal names.
13042 * We are printing short names: */
13043 out1fmt("trap -- %s %s\n",
13045 get_signame(signo));
13046 /* trap_ptr != trap only if we are in special-cased `trap` code.
13047 * In this case, we will exit very soon, no need to free(). */
13048 /* if (trap_ptr != trap && tp[0]) */
13053 if (trap_ptr != trap) {
13066 signo = get_signum(*ap);
13067 if (signo < 0 || signo >= NSIG) {
13068 /* Mimic bash message exactly */
13069 ash_msg("%s: invalid signal specification", *ap);
13075 if (LONE_DASH(action))
13078 if (action[0]) /* not NULL and not "" and not "-" */
13079 may_have_traps = 1;
13080 action = ckstrdup(action);
13084 trap[signo] = action;
13095 /* ============ Builtins */
13097 #if ENABLE_ASH_HELP
13098 static int FAST_FUNC
13099 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13105 "Built-in commands:\n"
13106 "------------------\n");
13107 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
13108 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
13109 builtintab[i].name + 1);
13115 # if ENABLE_FEATURE_SH_STANDALONE
13117 const char *a = applet_names;
13119 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
13124 while (*a++ != '\0')
13129 newline_and_flush(stdout);
13130 return EXIT_SUCCESS;
13135 static int FAST_FUNC
13136 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13138 show_history(line_input_state);
13139 return EXIT_SUCCESS;
13144 * The export and readonly commands.
13146 static int FAST_FUNC
13147 exportcmd(int argc UNUSED_PARAM, char **argv)
13157 /* "readonly" in bash accepts, but ignores -n.
13158 * We do the same: it saves a conditional in nextopt's param.
13161 while ((opt = nextopt("np")) != '\0') {
13163 flag_off = VEXPORT;
13166 if (argv[0][0] == 'r') {
13168 flag_off = 0; /* readonly ignores -n */
13170 flag_off = ~flag_off;
13172 /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
13178 p = strchr(name, '=');
13182 vp = *findvar(hashvar(name), name);
13184 vp->flags = ((vp->flags | flag) & flag_off);
13188 setvar(name, p, (flag & flag_off));
13189 } while ((name = *++aptr) != NULL);
13194 /* No arguments. Show the list of exported or readonly vars.
13197 showvars(argv[0], flag, 0);
13202 * Delete a function if it exists.
13205 unsetfunc(const char *name)
13207 struct tblentry *cmdp;
13209 cmdp = cmdlookup(name, 0);
13210 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
13211 delete_cmd_entry();
13215 * The unset builtin command. We unset the function before we unset the
13216 * variable to allow a function to be unset when there is a readonly variable
13217 * with the same name.
13219 static int FAST_FUNC
13220 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13227 while ((i = nextopt("vf")) != 0) {
13231 for (ap = argptr; *ap; ap++) {
13244 static const unsigned char timescmd_str[] ALIGN1 = {
13245 ' ', offsetof(struct tms, tms_utime),
13246 '\n', offsetof(struct tms, tms_stime),
13247 ' ', offsetof(struct tms, tms_cutime),
13248 '\n', offsetof(struct tms, tms_cstime),
13251 static int FAST_FUNC
13252 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13254 unsigned long clk_tck, s, t;
13255 const unsigned char *p;
13258 clk_tck = bb_clk_tck();
13263 t = *(clock_t *)(((char *) &buf) + p[1]);
13266 out1fmt("%lum%lu.%03lus%c",
13268 (t * 1000) / clk_tck,
13276 #if ENABLE_FEATURE_SH_MATH
13278 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13279 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13281 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13283 static int FAST_FUNC
13284 letcmd(int argc UNUSED_PARAM, char **argv)
13290 ash_msg_and_raise_error("expression expected");
13292 i = ash_arith(*argv);
13300 * The read builtin. Options:
13301 * -r Do not interpret '\' specially
13302 * -s Turn off echo (tty only)
13303 * -n NCHARS Read NCHARS max
13304 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13305 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13306 * -u FD Read from given FD instead of fd 0
13307 * This uses unbuffered input, which may be avoidable in some cases.
13308 * TODO: bash also has:
13309 * -a ARRAY Read into array[0],[1],etc
13310 * -d DELIM End on DELIM char, not newline
13311 * -e Use line editing (tty only)
13313 static int FAST_FUNC
13314 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13316 char *opt_n = NULL;
13317 char *opt_p = NULL;
13318 char *opt_t = NULL;
13319 char *opt_u = NULL;
13320 int read_flags = 0;
13324 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13333 read_flags |= BUILTIN_READ_SILENT;
13339 read_flags |= BUILTIN_READ_RAW;
13349 /* "read -s" needs to save/restore termios, can't allow ^C
13350 * to jump out of it.
13354 r = shell_builtin_read(setvar0,
13356 bltinlookup("IFS"), /* can be NULL */
13365 if ((uintptr_t)r == 1 && errno == EINTR) {
13366 /* to get SIGCHLD: sleep 1 & read x; echo $x */
13367 if (pending_sig == 0)
13371 if ((uintptr_t)r > 1)
13372 ash_msg_and_raise_error(r);
13374 return (uintptr_t)r;
13377 static int FAST_FUNC
13378 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13380 static const char permuser[3] ALIGN1 = "ogu";
13383 int symbolic_mode = 0;
13385 while (nextopt("S") != '\0') {
13394 if (*argptr == NULL) {
13395 if (symbolic_mode) {
13396 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13403 *p++ = permuser[i];
13405 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13406 if (!(mask & 0400)) *p++ = 'r';
13407 if (!(mask & 0200)) *p++ = 'w';
13408 if (!(mask & 0100)) *p++ = 'x';
13416 out1fmt("%04o\n", mask);
13419 char *modestr = *argptr;
13420 /* numeric umasks are taken as-is */
13421 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13422 if (!isdigit(modestr[0]))
13424 mask = bb_parse_mode(modestr, mask);
13425 if ((unsigned)mask > 0777) {
13426 ash_msg_and_raise_error("illegal mode: %s", modestr);
13428 if (!isdigit(modestr[0]))
13435 static int FAST_FUNC
13436 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13438 return shell_builtin_ulimit(argv);
13441 /* ============ main() and helpers */
13444 * Called to exit the shell.
13453 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13454 save_history(line_input_state);
13456 status = exitstatus;
13457 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13458 if (setjmp(loc.loc)) {
13459 if (exception_type == EXEXIT)
13460 status = exitstatus;
13463 exception_handler = &loc;
13469 /*free(p); - we'll exit soon */
13472 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13473 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13476 flush_stdout_stderr();
13484 /* we will never free this */
13485 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13487 sigmode[SIGCHLD - 1] = S_DFL;
13488 setsignal(SIGCHLD);
13490 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13491 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13493 signal(SIGHUP, SIG_DFL);
13498 struct stat st1, st2;
13501 for (envp = environ; envp && *envp; envp++) {
13502 p = endofname(*envp);
13503 if (p != *envp && *p == '=') {
13504 setvareq(*envp, VEXPORT|VTEXTFIXED);
13508 setvareq((char*)defoptindvar, VTEXTFIXED);
13510 setvar0("PPID", utoa(getppid()));
13512 p = lookupvar("SHLVL");
13513 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13515 #if BASH_HOSTNAME_VAR
13516 if (!lookupvar("HOSTNAME")) {
13517 struct utsname uts;
13519 setvar0("HOSTNAME", uts.nodename);
13522 p = lookupvar("PWD");
13524 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13525 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13535 //usage:#define ash_trivial_usage
13536 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13537 //usage:#define ash_full_usage "\n\n"
13538 //usage: "Unix shell interpreter"
13541 * Process the shell command line arguments.
13544 procargs(char **argv)
13547 const char *xminusc;
13552 /* if (xargv[0]) - mmm, this is always true! */
13554 for (i = 0; i < NOPTS; i++)
13557 if (options(/*cmdline:*/ 1)) {
13558 /* it already printed err message */
13559 raise_exception(EXERROR);
13563 if (*xargv == NULL) {
13565 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13568 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13572 for (i = 0; i < NOPTS; i++)
13573 if (optlist[i] == 2)
13578 /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
13583 } else if (!sflag) {
13584 setinputfile(*xargv, 0);
13587 commandname = arg0;
13590 shellparam.p = xargv;
13591 #if ENABLE_ASH_GETOPTS
13592 shellparam.optind = 1;
13593 shellparam.optoff = -1;
13595 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13597 shellparam.nparam++;
13604 * Read /etc/profile, ~/.profile, $ENV.
13607 read_profile(const char *name)
13609 name = expandstr(name);
13610 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13617 * This routine is called when an error or an interrupt occurs in an
13618 * interactive shell and control is returned to the main command loop.
13619 * (In dash, this function is auto-generated by build machinery).
13628 /* from expand.c: */
13631 /* from input.c: */
13632 g_parsefile->left_in_buffer = 0;
13633 g_parsefile->left_in_line = 0; /* clear input buffer */
13636 /* from redir.c: */
13638 popredir(/*drop:*/ 0, /*restore:*/ 0);
13642 static short profile_buf[16384];
13643 extern int etext();
13647 * Main routine. We initialize things, parse the arguments, execute
13648 * profiles if we're a login shell, and then call cmdloop to execute
13649 * commands. The setjmp call sets up the location to jump to when an
13650 * exception occurs. When an exception occurs the variable "state"
13651 * is used to figure out how far we had gotten.
13653 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13654 int ash_main(int argc UNUSED_PARAM, char **argv)
13656 volatile smallint state;
13657 struct jmploc jmploc;
13658 struct stackmark smark;
13660 /* Initialize global data */
13664 #if ENABLE_ASH_ALIAS
13670 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13673 #if ENABLE_FEATURE_EDITING
13674 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13677 if (setjmp(jmploc.loc)) {
13683 e = exception_type;
13685 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13689 newline_and_flush(stderr);
13692 popstackmark(&smark);
13693 FORCE_INT_ON; /* enable interrupts */
13702 exception_handler = &jmploc;
13703 rootpid = getpid();
13706 setstackmark(&smark);
13709 TRACE(("Shell args: "));
13710 trace_puts_args(argv);
13713 if (argv[0] && argv[0][0] == '-')
13719 read_profile("/etc/profile");
13722 hp = lookupvar("HOME");
13724 read_profile("$HOME/.profile");
13730 getuid() == geteuid() && getgid() == getegid() &&
13734 const char *shinit = lookupvar("ENV");
13735 if (shinit != NULL && *shinit != '\0')
13736 read_profile(shinit);
13738 popstackmark(&smark);
13742 /* evalstring pushes parsefile stack.
13743 * Ensure we don't falsely claim that 0 (stdin)
13744 * is one of stacked source fds.
13745 * Testcase: ash -c 'exec 1>&0' must not complain. */
13746 // if (!sflag) g_parsefile->pf_fd = -1;
13747 // ^^ not necessary since now we special-case fd 0
13748 // in is_hidden_fd() to not be considered "hidden fd"
13749 evalstring(minusc, 0);
13752 if (sflag || minusc == NULL) {
13753 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13755 const char *hp = lookupvar("HISTFILE");
13757 hp = lookupvar("HOME");
13760 hp = concat_path_file(hp, ".ash_history");
13761 setvar0("HISTFILE", hp);
13764 hp = lookupvar("HISTFILE");
13768 line_input_state->hist_file = hp;
13769 # if ENABLE_FEATURE_SH_HISTFILESIZE
13770 hp = lookupvar("HISTFILESIZE");
13771 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13775 state4: /* XXX ??? - why isn't this before the "if" statement */
13783 extern void _mcleanup(void);
13787 TRACE(("End of main reached\n"));
13794 * Copyright (c) 1989, 1991, 1993, 1994
13795 * The Regents of the University of California. All rights reserved.
13797 * This code is derived from software contributed to Berkeley by
13798 * Kenneth Almquist.
13800 * Redistribution and use in source and binary forms, with or without
13801 * modification, are permitted provided that the following conditions
13803 * 1. Redistributions of source code must retain the above copyright
13804 * notice, this list of conditions and the following disclaimer.
13805 * 2. Redistributions in binary form must reproduce the above copyright
13806 * notice, this list of conditions and the following disclaimer in the
13807 * documentation and/or other materials provided with the distribution.
13808 * 3. Neither the name of the University nor the names of its contributors
13809 * may be used to endorse or promote products derived from this software
13810 * without specific prior written permission.
13812 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13813 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13814 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13815 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13816 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13817 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13818 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13819 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13820 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13821 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF