1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
21 //config: depends on !NOMMU
23 //config: Tha 'ash' shell adds about 60k in the default configuration and is
24 //config: the most complete and most pedantically correct shell included with
25 //config: busybox. This shell is actually a derivative of the Debian 'dash'
26 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
27 //config: (written by Kenneth Almquist) from NetBSD.
29 //config:# ash options
30 //config:# note: Don't remove !NOMMU part in the next line; it would break
31 //config:# menuconfig's indenting.
32 //config:if !NOMMU && (ASH || SH_IS_ASH || BASH_IS_ASH)
34 //config:config ASH_OPTIMIZE_FOR_SIZE
35 //config: bool "Optimize for size instead of speed"
37 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
39 //config:config ASH_INTERNAL_GLOB
40 //config: bool "Use internal glob() implementation"
41 //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
42 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
44 //config: Do not use glob() function from libc, use internal implementation.
45 //config: Use this if you are getting "glob.h: No such file or directory"
46 //config: or similar build errors.
47 //config: Note that as of now (2017-01), uclibc and musl glob() both have bugs
48 //config: which would break ash if you select N here.
50 //config:config ASH_BASH_COMPAT
51 //config: bool "bash-compatible extensions"
53 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
55 //config:config ASH_JOB_CONTROL
56 //config: bool "Job control"
58 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
60 //config:config ASH_ALIAS
61 //config: bool "Alias support"
63 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
65 //config:config ASH_RANDOM_SUPPORT
66 //config: bool "Pseudorandom generator and $RANDOM variable"
68 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
70 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
71 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
72 //config: You can reset the generator by using a specified start value.
73 //config: After "unset RANDOM" the generator will switch off and this
74 //config: variable will no longer have special treatment.
76 //config:config ASH_EXPAND_PRMT
77 //config: bool "Expand prompt string"
79 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
81 //config: $PS# may contain volatile content, such as backquote commands.
82 //config: This option recreates the prompt string from the environment
83 //config: variable each time it is displayed.
85 //config:config ASH_IDLE_TIMEOUT
86 //config: bool "Idle timeout variable $TMOUT"
88 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
90 //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
92 //config:config ASH_MAIL
93 //config: bool "Check for new mail in interactive shell"
95 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
97 //config: Enable "check for new mail" function:
98 //config: if set, $MAIL file and $MAILPATH list of files
99 //config: are checked for mtime changes, and "you have mail"
100 //config: message is printed if change is detected.
102 //config:config ASH_ECHO
103 //config: bool "echo builtin"
105 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
107 //config:config ASH_PRINTF
108 //config: bool "printf builtin"
110 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
112 //config:config ASH_TEST
113 //config: bool "test builtin"
115 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
117 //config:config ASH_HELP
118 //config: bool "help builtin"
120 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
122 //config:config ASH_GETOPTS
123 //config: bool "getopts builtin"
125 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
127 //config:config ASH_CMDCMD
128 //config: bool "command builtin"
130 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
132 //config: Enable support for the 'command' builtin, which allows
133 //config: you to run the specified command or builtin,
134 //config: even when there is a function with the same name.
136 //config:endif # ash options
138 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
139 //applet: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 possibly 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 /* ============ nextopt */
1792 static char **argptr; /* argument list for builtin commands */
1793 static char *optionarg; /* set by nextopt (like getopt) */
1794 static char *optptr; /* used by nextopt */
1797 * XXX - should get rid of. Have all builtins use getopt(3).
1798 * The library getopt must have the BSD extension static variable
1799 * "optreset", otherwise it can't be used within the shell safely.
1801 * Standard option processing (a la getopt) for builtin routines.
1802 * The only argument that is passed to nextopt is the option string;
1803 * the other arguments are unnecessary. It returns the character,
1804 * or '\0' on end of input.
1807 nextopt(const char *optstring)
1814 if (p == NULL || *p == '\0') {
1815 /* We ate entire "-param", take next one */
1821 if (*++p == '\0') /* just "-" ? */
1824 if (LONE_DASH(p)) /* "--" ? */
1826 /* p => next "-param" */
1828 /* p => some option char in the middle of a "-param" */
1830 for (q = optstring; *q != c;) {
1832 ash_msg_and_raise_error("illegal option -%c", c);
1840 ash_msg_and_raise_error("no arg for -%c option", c);
1850 /* ============ Shell variables */
1853 * The parsefile structure pointed to by the global variable parsefile
1854 * contains information about the current file being read.
1857 int nparam; /* # of positional parameters (without $0) */
1858 #if ENABLE_ASH_GETOPTS
1859 int optind; /* next parameter to be processed by getopts */
1860 int optoff; /* used by getopts */
1862 unsigned char malloced; /* if parameter list dynamically allocated */
1863 char **p; /* parameter list */
1867 * Free the list of positional parameters.
1870 freeparam(volatile struct shparam *param)
1872 if (param->malloced) {
1874 ap = ap1 = param->p;
1881 #if ENABLE_ASH_GETOPTS
1882 static void FAST_FUNC getoptsreset(const char *value);
1886 struct var *next; /* next entry in hash list */
1887 int flags; /* flags are defined above */
1888 const char *var_text; /* name=value */
1889 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1890 /* the variable gets set/unset */
1894 struct localvar *next; /* next local variable in list */
1895 struct var *vp; /* the variable that was made local */
1896 int flags; /* saved flags */
1897 const char *text; /* saved text */
1901 #define VEXPORT 0x01 /* variable is exported */
1902 #define VREADONLY 0x02 /* variable cannot be modified */
1903 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1904 #define VTEXTFIXED 0x08 /* text is statically allocated */
1905 #define VSTACK 0x10 /* text is allocated on the stack */
1906 #define VUNSET 0x20 /* the variable is not set */
1907 #define VNOFUNC 0x40 /* don't call the callback function */
1908 #define VNOSET 0x80 /* do not set variable - just readonly test */
1909 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1910 #if ENABLE_ASH_RANDOM_SUPPORT
1911 # define VDYNAMIC 0x200 /* dynamic variable */
1917 /* Need to be before varinit_data[] */
1918 #if ENABLE_LOCALE_SUPPORT
1919 static void FAST_FUNC
1920 change_lc_all(const char *value)
1922 if (value && *value != '\0')
1923 setlocale(LC_ALL, value);
1925 static void FAST_FUNC
1926 change_lc_ctype(const char *value)
1928 if (value && *value != '\0')
1929 setlocale(LC_CTYPE, value);
1933 static void chkmail(void);
1934 static void changemail(const char *var_value) FAST_FUNC;
1936 # define chkmail() ((void)0)
1938 static void changepath(const char *) FAST_FUNC;
1939 #if ENABLE_ASH_RANDOM_SUPPORT
1940 static void change_random(const char *) FAST_FUNC;
1943 static const struct {
1945 const char *var_text;
1946 void (*var_func)(const char *) FAST_FUNC;
1947 } varinit_data[] = {
1949 * Note: VEXPORT would not work correctly here for NOFORK applets:
1950 * some environment strings may be constant.
1952 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1954 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1955 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1957 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1958 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1959 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1960 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1961 #if ENABLE_ASH_GETOPTS
1962 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
1964 #if ENABLE_ASH_RANDOM_SUPPORT
1965 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1967 #if ENABLE_LOCALE_SUPPORT
1968 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1969 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1971 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1972 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1978 struct globals_var {
1979 struct shparam shellparam; /* $@ current positional parameters */
1980 struct redirtab *redirlist;
1981 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1982 struct var *vartab[VTABSIZE];
1983 struct var varinit[ARRAY_SIZE(varinit_data)];
1985 extern struct globals_var *const ash_ptr_to_globals_var;
1986 #define G_var (*ash_ptr_to_globals_var)
1987 #define shellparam (G_var.shellparam )
1988 //#define redirlist (G_var.redirlist )
1989 #define preverrout_fd (G_var.preverrout_fd)
1990 #define vartab (G_var.vartab )
1991 #define varinit (G_var.varinit )
1992 #define INIT_G_var() do { \
1994 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1996 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1997 varinit[i].flags = varinit_data[i].flags; \
1998 varinit[i].var_text = varinit_data[i].var_text; \
1999 varinit[i].var_func = varinit_data[i].var_func; \
2003 #define vifs varinit[0]
2005 # define vmail (&vifs)[1]
2006 # define vmpath (&vmail)[1]
2007 # define vpath (&vmpath)[1]
2009 # define vpath (&vifs)[1]
2011 #define vps1 (&vpath)[1]
2012 #define vps2 (&vps1)[1]
2013 #define vps4 (&vps2)[1]
2014 #if ENABLE_ASH_GETOPTS
2015 # define voptind (&vps4)[1]
2016 # if ENABLE_ASH_RANDOM_SUPPORT
2017 # define vrandom (&voptind)[1]
2020 # if ENABLE_ASH_RANDOM_SUPPORT
2021 # define vrandom (&vps4)[1]
2026 * The following macros access the values of the above variables.
2027 * They have to skip over the name. They return the null string
2028 * for unset variables.
2030 #define ifsval() (vifs.var_text + 4)
2031 #define ifsset() ((vifs.flags & VUNSET) == 0)
2033 # define mailval() (vmail.var_text + 5)
2034 # define mpathval() (vmpath.var_text + 9)
2035 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2037 #define pathval() (vpath.var_text + 5)
2038 #define ps1val() (vps1.var_text + 4)
2039 #define ps2val() (vps2.var_text + 4)
2040 #define ps4val() (vps4.var_text + 4)
2041 #if ENABLE_ASH_GETOPTS
2042 # define optindval() (voptind.var_text + 7)
2045 #if ENABLE_ASH_GETOPTS
2046 static void FAST_FUNC
2047 getoptsreset(const char *value)
2049 shellparam.optind = number(value) ?: 1;
2050 shellparam.optoff = -1;
2055 * Compares two strings up to the first = or '\0'. The first
2056 * string must be terminated by '='; the second may be terminated by
2057 * either '=' or '\0'.
2060 varcmp(const char *p, const char *q)
2064 while ((c = *p) == (d = *q)) {
2065 if (c == '\0' || c == '=')
2079 * Find the appropriate entry in the hash table from the name.
2081 static struct var **
2082 hashvar(const char *p)
2086 hashval = ((unsigned char) *p) << 4;
2087 while (*p && *p != '=')
2088 hashval += (unsigned char) *p++;
2089 return &vartab[hashval % VTABSIZE];
2093 vpcmp(const void *a, const void *b)
2095 return varcmp(*(const char **)a, *(const char **)b);
2099 * This routine initializes the builtin variables.
2109 * PS1 depends on uid
2111 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2112 vps1.var_text = "PS1=\\w \\$ ";
2115 vps1.var_text = "PS1=# ";
2118 end = vp + ARRAY_SIZE(varinit);
2120 vpp = hashvar(vp->var_text);
2123 } while (++vp < end);
2126 static struct var **
2127 findvar(struct var **vpp, const char *name)
2129 for (; *vpp; vpp = &(*vpp)->next) {
2130 if (varcmp((*vpp)->var_text, name) == 0) {
2138 * Find the value of a variable. Returns NULL if not set.
2140 static const char* FAST_FUNC
2141 lookupvar(const char *name)
2145 v = *findvar(hashvar(name), name);
2147 #if ENABLE_ASH_RANDOM_SUPPORT
2149 * Dynamic variables are implemented roughly the same way they are
2150 * in bash. Namely, they're "special" so long as they aren't unset.
2151 * As soon as they're unset, they're no longer dynamic, and dynamic
2152 * lookup will no longer happen at that point. -- PFM.
2154 if (v->flags & VDYNAMIC)
2157 if (!(v->flags & VUNSET))
2158 return var_end(v->var_text);
2163 #if ENABLE_UNICODE_SUPPORT
2165 reinit_unicode_for_ash(void)
2167 /* Unicode support should be activated even if LANG is set
2168 * _during_ shell execution, not only if it was set when
2169 * shell was started. Therefore, re-check LANG every time:
2171 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2172 || ENABLE_UNICODE_USING_LOCALE
2174 const char *s = lookupvar("LC_ALL");
2175 if (!s) s = lookupvar("LC_CTYPE");
2176 if (!s) s = lookupvar("LANG");
2181 # define reinit_unicode_for_ash() ((void)0)
2185 * Search the environment of a builtin command.
2188 bltinlookup(const char *name)
2192 for (sp = cmdenviron; sp; sp = sp->next) {
2193 if (varcmp(sp->text, name) == 0)
2194 return var_end(sp->text);
2196 return lookupvar(name);
2200 * Same as setvar except that the variable and value are passed in
2201 * the first argument as name=value. Since the first argument will
2202 * be actually stored in the table, it should not be a string that
2204 * Called with interrupts off.
2207 setvareq(char *s, int flags)
2209 struct var *vp, **vpp;
2212 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2213 vp = *findvar(vpp, s);
2215 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2218 if (flags & VNOSAVE)
2222 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2228 if (vp->var_func && !(flags & VNOFUNC))
2229 vp->var_func(var_end(s));
2231 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2232 free((char*)vp->var_text);
2234 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2236 /* variable s is not found */
2239 vp = ckzalloc(sizeof(*vp));
2241 /*vp->func = NULL; - ckzalloc did it */
2244 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2251 * Set the value of a variable. The flags argument is ored with the
2252 * flags of the variable. If val is NULL, the variable is unset.
2255 setvar(const char *name, const char *val, int flags)
2263 q = endofname(name);
2264 p = strchrnul(q, '=');
2266 if (!namelen || p != q)
2267 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2272 vallen = strlen(val);
2276 nameeq = ckmalloc(namelen + vallen + 2);
2277 p = memcpy(nameeq, name, namelen) + namelen;
2280 p = memcpy(p, val, vallen) + vallen;
2283 setvareq(nameeq, flags | VNOSAVE);
2287 static void FAST_FUNC
2288 setvar0(const char *name, const char *val)
2290 setvar(name, val, 0);
2294 * Unset the specified variable.
2297 unsetvar(const char *s)
2303 vpp = findvar(hashvar(s), s);
2307 int flags = vp->flags;
2310 if (flags & VREADONLY)
2312 #if ENABLE_ASH_RANDOM_SUPPORT
2313 vp->flags &= ~VDYNAMIC;
2317 if ((flags & VSTRFIXED) == 0) {
2319 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2320 free((char*)vp->var_text);
2326 vp->flags &= ~VEXPORT;
2336 * Process a linked list of variable assignments.
2339 listsetvar(struct strlist *list_set_var, int flags)
2341 struct strlist *lp = list_set_var;
2347 setvareq(lp->text, flags);
2354 * Generate a list of variables satisfying the given conditions.
2357 listvars(int on, int off, char ***end)
2368 for (vp = *vpp; vp; vp = vp->next) {
2369 if ((vp->flags & mask) == on) {
2370 if (ep == stackstrend())
2371 ep = growstackstr();
2372 *ep++ = (char*)vp->var_text;
2375 } while (++vpp < vartab + VTABSIZE);
2376 if (ep == stackstrend())
2377 ep = growstackstr();
2381 return grabstackstr(ep);
2385 /* ============ Path search helper
2387 * The variable path (passed by reference) should be set to the start
2388 * of the path before the first call; path_advance will update
2389 * this value as it proceeds. Successive calls to path_advance will return
2390 * the possible path expansions in sequence. If an option (indicated by
2391 * a percent sign) appears in the path entry then the global variable
2392 * pathopt will be set to point to it; otherwise pathopt will be set to
2395 static const char *pathopt; /* set by path_advance */
2398 path_advance(const char **path, const char *name)
2408 for (p = start; *p && *p != ':' && *p != '%'; p++)
2410 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2411 while (stackblocksize() < len)
2415 memcpy(q, start, p - start);
2423 while (*p && *p != ':')
2430 return stalloc(len);
2434 /* ============ Prompt */
2436 static smallint doprompt; /* if set, prompt the user */
2437 static smallint needprompt; /* true if interactive and at start of line */
2439 #if ENABLE_FEATURE_EDITING
2440 static line_input_t *line_input_state;
2441 static const char *cmdedit_prompt;
2443 putprompt(const char *s)
2445 if (ENABLE_ASH_EXPAND_PRMT) {
2446 free((char*)cmdedit_prompt);
2447 cmdedit_prompt = ckstrdup(s);
2454 putprompt(const char *s)
2460 #if ENABLE_ASH_EXPAND_PRMT
2461 /* expandstr() needs parsing machinery, so it is far away ahead... */
2462 static const char *expandstr(const char *ps);
2464 #define expandstr(s) s
2468 setprompt_if(smallint do_set, int whichprompt)
2471 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2478 switch (whichprompt) {
2488 #if ENABLE_ASH_EXPAND_PRMT
2489 pushstackmark(&smark, stackblocksize());
2491 putprompt(expandstr(prompt));
2492 #if ENABLE_ASH_EXPAND_PRMT
2493 popstackmark(&smark);
2498 /* ============ The cd and pwd commands */
2500 #define CD_PHYSICAL 1
2510 while ((i = nextopt("LP")) != '\0') {
2512 flags ^= CD_PHYSICAL;
2521 * Update curdir (the name of the current directory) in response to a
2525 updatepwd(const char *dir)
2532 cdcomppath = sstrdup(dir);
2535 if (curdir == nullstr)
2537 new = stack_putstr(curdir, new);
2539 new = makestrspace(strlen(dir) + 2, new);
2540 lim = (char *)stackblock() + 1;
2544 if (new > lim && *lim == '/')
2549 if (dir[1] == '/' && dir[2] != '/') {
2555 p = strtok(cdcomppath, "/");
2559 if (p[1] == '.' && p[2] == '\0') {
2571 new = stack_putstr(p, new);
2574 p = strtok(NULL, "/");
2579 return stackblock();
2583 * Find out what the current directory is. If we already know the current
2584 * directory, this routine returns immediately.
2589 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2590 return dir ? dir : nullstr;
2594 setpwd(const char *val, int setold)
2598 oldcur = dir = curdir;
2601 setvar("OLDPWD", oldcur, VEXPORT);
2604 if (physdir != nullstr) {
2605 if (physdir != oldcur)
2609 if (oldcur == val || !val) {
2615 dir = ckstrdup(val);
2616 if (oldcur != dir && oldcur != nullstr) {
2621 setvar("PWD", dir, VEXPORT);
2624 static void hashcd(void);
2627 * Actually do the chdir. We also call hashcd to let other routines
2628 * know that the current directory has changed.
2631 docd(const char *dest, int flags)
2633 const char *dir = NULL;
2636 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2639 if (!(flags & CD_PHYSICAL)) {
2640 dir = updatepwd(dest);
2654 static int FAST_FUNC
2655 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2667 dest = bltinlookup("HOME");
2668 else if (LONE_DASH(dest)) {
2669 dest = bltinlookup("OLDPWD");
2691 path = bltinlookup("CDPATH");
2694 p = path_advance(&path, dest);
2695 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2699 if (!docd(p, flags))
2710 ash_msg_and_raise_error("can't cd to %s", dest);
2713 if (flags & CD_PRINT)
2714 out1fmt("%s\n", curdir);
2718 static int FAST_FUNC
2719 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2722 const char *dir = curdir;
2726 if (physdir == nullstr)
2730 out1fmt("%s\n", dir);
2735 /* ============ ... */
2738 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2740 /* Syntax classes */
2741 #define CWORD 0 /* character is nothing special */
2742 #define CNL 1 /* newline character */
2743 #define CBACK 2 /* a backslash character */
2744 #define CSQUOTE 3 /* single quote */
2745 #define CDQUOTE 4 /* double quote */
2746 #define CENDQUOTE 5 /* a terminating quote */
2747 #define CBQUOTE 6 /* backwards single quote */
2748 #define CVAR 7 /* a dollar sign */
2749 #define CENDVAR 8 /* a '}' character */
2750 #define CLP 9 /* a left paren in arithmetic */
2751 #define CRP 10 /* a right paren in arithmetic */
2752 #define CENDFILE 11 /* end of file */
2753 #define CCTL 12 /* like CWORD, except it must be escaped */
2754 #define CSPCL 13 /* these terminate a word */
2755 #define CIGN 14 /* character should be ignored */
2758 #if ENABLE_ASH_ALIAS
2762 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2764 #if ENABLE_FEATURE_SH_MATH
2765 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2767 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2769 static const uint16_t S_I_T[] ALIGN2 = {
2770 #if ENABLE_ASH_ALIAS
2771 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2773 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2774 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2775 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2776 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2777 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2778 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2779 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2780 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2781 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2782 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2783 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2784 #if !USE_SIT_FUNCTION
2785 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2786 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2787 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2791 /* Constants below must match table above */
2793 #if ENABLE_ASH_ALIAS
2794 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2796 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2797 CNL_CNL_CNL_CNL , /* 2 */
2798 CWORD_CCTL_CCTL_CWORD , /* 3 */
2799 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2800 CVAR_CVAR_CWORD_CVAR , /* 5 */
2801 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2802 CSPCL_CWORD_CWORD_CLP , /* 7 */
2803 CSPCL_CWORD_CWORD_CRP , /* 8 */
2804 CBACK_CBACK_CCTL_CBACK , /* 9 */
2805 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2806 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2807 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2808 CWORD_CWORD_CWORD_CWORD , /* 13 */
2809 CCTL_CCTL_CCTL_CCTL , /* 14 */
2812 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2813 * caller must ensure proper cast on it if c is *char_ptr!
2815 /* Values for syntax param */
2816 #define BASESYNTAX 0 /* not in quotes */
2817 #define DQSYNTAX 1 /* in double quotes */
2818 #define SQSYNTAX 2 /* in single quotes */
2819 #define ARISYNTAX 3 /* in arithmetic */
2820 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2822 #if USE_SIT_FUNCTION
2825 SIT(int c, int syntax)
2827 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2828 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2830 * This causes '/' to be prepended with CTLESC in dquoted string,
2831 * making "./file"* treated incorrectly because we feed
2832 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2833 * The "homegrown" glob implementation is okay with that,
2834 * but glibc one isn't. With '/' always treated as CWORD,
2837 # if ENABLE_ASH_ALIAS
2838 static const uint8_t syntax_index_table[] ALIGN1 = {
2839 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2840 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2841 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2845 static const uint8_t syntax_index_table[] ALIGN1 = {
2846 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2847 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2848 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2857 # if ENABLE_ASH_ALIAS
2863 /* Cast is purely for paranoia here,
2864 * just in case someone passed signed char to us */
2865 if ((unsigned char)c >= CTL_FIRST
2866 && (unsigned char)c <= CTL_LAST
2870 s = strchrnul(spec_symbls, c);
2873 indx = syntax_index_table[s - spec_symbls];
2875 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2878 #else /* !USE_SIT_FUNCTION */
2880 static const uint8_t syntax_index_table[] ALIGN1 = {
2881 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2882 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2892 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2893 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2915 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2916 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2917 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2918 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2919 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2921 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2922 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2923 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2924 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2925 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2927 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2928 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2929 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2930 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2942 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2943 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2944 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2945 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2946 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2947 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2975 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2976 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2977 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2980 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3006 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3007 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3008 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3009 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3010 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3011 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3013 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3014 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3015 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3016 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3017 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3018 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3019 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3020 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3120 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3121 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3122 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3123 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3124 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3125 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3126 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3127 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3128 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3129 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3130 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3131 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3132 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3133 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3134 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3135 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3136 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3137 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3138 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3139 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3140 # if ENABLE_ASH_ALIAS
3141 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3146 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3147 #else /* debug version, caught one signed char bug */
3148 # define SIT(c, syntax) \
3150 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3151 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3152 if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
3153 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3154 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3158 #endif /* !USE_SIT_FUNCTION */
3161 /* ============ Alias handling */
3163 #if ENABLE_ASH_ALIAS
3165 #define ALIASINUSE 1
3176 static struct alias **atab; // [ATABSIZE];
3177 #define INIT_G_alias() do { \
3178 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3182 static struct alias **
3183 __lookupalias(const char *name)
3185 unsigned int hashval;
3192 ch = (unsigned char)*p;
3196 ch = (unsigned char)*++p;
3198 app = &atab[hashval % ATABSIZE];
3200 for (; *app; app = &(*app)->next) {
3201 if (strcmp(name, (*app)->name) == 0) {
3209 static struct alias *
3210 lookupalias(const char *name, int check)
3212 struct alias *ap = *__lookupalias(name);
3214 if (check && ap && (ap->flag & ALIASINUSE))
3219 static struct alias *
3220 freealias(struct alias *ap)
3224 if (ap->flag & ALIASINUSE) {
3225 ap->flag |= ALIASDEAD;
3237 setalias(const char *name, const char *val)
3239 struct alias *ap, **app;
3241 app = __lookupalias(name);
3245 if (!(ap->flag & ALIASINUSE)) {
3248 ap->val = ckstrdup(val);
3249 ap->flag &= ~ALIASDEAD;
3252 ap = ckzalloc(sizeof(struct alias));
3253 ap->name = ckstrdup(name);
3254 ap->val = ckstrdup(val);
3255 /*ap->flag = 0; - ckzalloc did it */
3256 /*ap->next = NULL;*/
3263 unalias(const char *name)
3267 app = __lookupalias(name);
3271 *app = freealias(*app);
3282 struct alias *ap, **app;
3286 for (i = 0; i < ATABSIZE; i++) {
3288 for (ap = *app; ap; ap = *app) {
3289 *app = freealias(*app);
3299 printalias(const struct alias *ap)
3301 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3305 * TODO - sort output
3307 static int FAST_FUNC
3308 aliascmd(int argc UNUSED_PARAM, char **argv)
3317 for (i = 0; i < ATABSIZE; i++) {
3318 for (ap = atab[i]; ap; ap = ap->next) {
3324 while ((n = *++argv) != NULL) {
3325 v = strchr(n+1, '=');
3326 if (v == NULL) { /* n+1: funny ksh stuff */
3327 ap = *__lookupalias(n);
3329 fprintf(stderr, "%s: %s not found\n", "alias", n);
3342 static int FAST_FUNC
3343 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3347 while ((i = nextopt("a")) != '\0') {
3353 for (i = 0; *argptr; argptr++) {
3354 if (unalias(*argptr)) {
3355 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3363 #endif /* ASH_ALIAS */
3366 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3369 #define FORK_NOJOB 2
3371 /* mode flags for showjob(s) */
3372 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3373 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3374 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3375 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3378 * A job structure contains information about a job. A job is either a
3379 * single process or a set of processes contained in a pipeline. In the
3380 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3384 pid_t ps_pid; /* process id */
3385 int ps_status; /* last process status from wait() */
3386 char *ps_cmd; /* text of command being run */
3390 struct procstat ps0; /* status of process */
3391 struct procstat *ps; /* status or processes when more than one */
3393 int stopstatus; /* status of a stopped job */
3395 unsigned nprocs; /* number of processes */
3397 #define JOBRUNNING 0 /* at least one proc running */
3398 #define JOBSTOPPED 1 /* all procs are stopped */
3399 #define JOBDONE 2 /* all procs are completed */
3403 sigint: 1, /* job was killed by SIGINT */
3404 jobctl: 1, /* job running under job control */
3406 waited: 1, /* true if this entry has been waited for */
3407 used: 1, /* true if this entry is in used */
3408 changed: 1; /* true if status has changed */
3409 struct job *prev_job; /* previous job */
3412 static struct job *makejob(/*union node *,*/ int);
3413 static int forkshell(struct job *, union node *, int);
3414 static int waitforjob(struct job *);
3417 enum { doing_jobctl = 0 };
3418 #define setjobctl(on) do {} while (0)
3420 static smallint doing_jobctl; //references:8
3421 static void setjobctl(int);
3428 ignoresig(int signo)
3430 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3431 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3432 /* No, need to do it */
3433 signal(signo, SIG_IGN);
3435 sigmode[signo - 1] = S_HARD_IGN;
3439 * Only one usage site - in setsignal()
3442 signal_handler(int signo)
3444 if (signo == SIGCHLD) {
3450 gotsig[signo - 1] = 1;
3451 pending_sig = signo;
3453 if (signo == SIGINT && !trap[SIGINT]) {
3454 if (!suppress_int) {
3456 raise_interrupt(); /* does not return */
3463 * Set the signal handler for the specified signal. The routine figures
3464 * out what it should be set to.
3467 setsignal(int signo)
3470 char cur_act, new_act;
3471 struct sigaction act;
3475 if (t != NULL) { /* trap for this sig is set */
3477 if (t[0] == '\0') /* trap is "": ignore this sig */
3481 if (rootshell && new_act == S_DFL) {
3484 if (iflag || minusc || sflag == 0)
3493 * "In all cases, bash ignores SIGQUIT. Non-builtin
3494 * commands run by bash have signal handlers
3495 * set to the values inherited by the shell
3496 * from its parent". */
3512 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3513 //whereas we have to restore it to what shell got on entry
3514 //from the parent. See comment above
3516 if (signo == SIGCHLD)
3519 t = &sigmode[signo - 1];
3522 /* current setting is not yet known */
3523 if (sigaction(signo, NULL, &act)) {
3524 /* pretend it worked; maybe we should give a warning,
3525 * but other shells don't. We don't alter sigmode,
3526 * so we retry every time.
3527 * btw, in Linux it never fails. --vda */
3530 if (act.sa_handler == SIG_IGN) {
3531 cur_act = S_HARD_IGN;
3533 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3535 cur_act = S_IGN; /* don't hard ignore these */
3539 if (cur_act == S_HARD_IGN || cur_act == new_act)
3542 act.sa_handler = SIG_DFL;
3545 act.sa_handler = signal_handler;
3548 act.sa_handler = SIG_IGN;
3552 /* flags and mask matter only if !DFL and !IGN, but we do it
3553 * for all cases for more deterministic behavior:
3556 sigfillset(&act.sa_mask);
3558 sigaction_set(signo, &act);
3563 /* mode flags for set_curjob */
3564 #define CUR_DELETE 2
3565 #define CUR_RUNNING 1
3566 #define CUR_STOPPED 0
3569 /* pgrp of shell on invocation */
3570 static int initialpgrp; //references:2
3571 static int ttyfd = -1; //5
3574 static struct job *jobtab; //5
3576 static unsigned njobs; //4
3578 static struct job *curjob; //lots
3579 /* number of presumed living untracked jobs */
3580 static int jobless; //4
3583 set_curjob(struct job *jp, unsigned mode)
3586 struct job **jpp, **curp;
3588 /* first remove from list */
3589 jpp = curp = &curjob;
3594 jpp = &jp1->prev_job;
3596 *jpp = jp1->prev_job;
3598 /* Then re-insert in correct position */
3606 /* job being deleted */
3609 /* newly created job or backgrounded job,
3610 * put after all stopped jobs.
3615 if (!jp1 || jp1->state != JOBSTOPPED)
3618 jpp = &jp1->prev_job;
3624 /* newly stopped job - becomes curjob */
3625 jp->prev_job = *jpp;
3633 jobno(const struct job *jp)
3635 return jp - jobtab + 1;
3640 * Convert a job name to a job structure.
3643 #define getjob(name, getctl) getjob(name)
3646 getjob(const char *name, int getctl)
3650 const char *err_msg = "%s: no such job";
3654 char *(*match)(const char *, const char *);
3669 if (c == '+' || c == '%') {
3671 err_msg = "No current job";
3677 err_msg = "No previous job";
3687 if (num > 0 && num <= njobs) {
3688 jp = jobtab + num - 1;
3703 if (match(jp->ps[0].ps_cmd, p)) {
3707 err_msg = "%s: ambiguous";
3717 err_msg = "job %s not created under job control";
3718 if (getctl && jp->jobctl == 0)
3723 ash_msg_and_raise_error(err_msg, name);
3727 * Mark a job structure as unused.
3730 freejob(struct job *jp)
3732 struct procstat *ps;
3736 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3737 if (ps->ps_cmd != nullstr)
3740 if (jp->ps != &jp->ps0)
3743 set_curjob(jp, CUR_DELETE);
3749 xtcsetpgrp(int fd, pid_t pgrp)
3751 if (tcsetpgrp(fd, pgrp))
3752 ash_msg_and_raise_error("can't set tty process group (%m)");
3756 * Turn job control on and off.
3758 * Note: This code assumes that the third arg to ioctl is a character
3759 * pointer, which is true on Berkeley systems but not System V. Since
3760 * System V doesn't have job control yet, this isn't a problem now.
3762 * Called with interrupts off.
3770 if (on == doing_jobctl || rootshell == 0)
3774 ofd = fd = open(_PATH_TTY, O_RDWR);
3776 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3777 * That sometimes helps to acquire controlling tty.
3778 * Obviously, a workaround for bugs when someone
3779 * failed to provide a controlling tty to bash! :) */
3785 /* fd is a tty at this point */
3786 fd = fcntl(fd, F_DUPFD, 10);
3787 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, dont */
3790 goto out; /* F_DUPFD failed */
3791 close_on_exec_on(fd);
3792 while (1) { /* while we are in the background */
3793 pgrp = tcgetpgrp(fd);
3796 ash_msg("can't access tty; job control turned off");
3800 if (pgrp == getpgrp())
3811 xtcsetpgrp(fd, pgrp);
3813 /* turning job control off */
3816 /* was xtcsetpgrp, but this can make exiting ash
3817 * loop forever if pty is already deleted */
3818 tcsetpgrp(fd, pgrp);
3832 static int FAST_FUNC
3833 killcmd(int argc, char **argv)
3835 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3838 if (argv[i][0] == '%') {
3840 * "kill %N" - job kill
3841 * Converting to pgrp / pid kill
3847 jp = getjob(argv[i], 0);
3849 * In jobs started under job control, we signal
3850 * entire process group by kill -PGRP_ID.
3851 * This happens, f.e., in interactive shell.
3853 * Otherwise, we signal each child via
3854 * kill PID1 PID2 PID3.
3856 * sh -c 'sleep 1|sleep 1 & kill %1'
3857 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3858 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3860 n = jp->nprocs; /* can't be 0 (I hope) */
3863 dst = alloca(n * sizeof(int)*4);
3865 for (j = 0; j < n; j++) {
3866 struct procstat *ps = &jp->ps[j];
3867 /* Skip non-running and not-stopped members
3868 * (i.e. dead members) of the job
3870 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3873 * kill_main has matching code to expect
3874 * leading space. Needed to not confuse
3875 * negative pids with "kill -SIGNAL_NO" syntax
3877 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3881 } while (argv[++i]);
3883 return kill_main(argc, argv);
3887 showpipe(struct job *jp /*, FILE *out*/)
3889 struct procstat *ps;
3890 struct procstat *psend;
3892 psend = jp->ps + jp->nprocs;
3893 for (ps = jp->ps + 1; ps < psend; ps++)
3894 printf(" | %s", ps->ps_cmd);
3895 newline_and_flush(stdout);
3896 flush_stdout_stderr();
3901 restartjob(struct job *jp, int mode)
3903 struct procstat *ps;
3909 if (jp->state == JOBDONE)
3911 jp->state = JOBRUNNING;
3912 pgid = jp->ps[0].ps_pid;
3913 if (mode == FORK_FG)
3914 xtcsetpgrp(ttyfd, pgid);
3915 killpg(pgid, SIGCONT);
3919 if (WIFSTOPPED(ps->ps_status)) {
3925 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3930 static int FAST_FUNC
3931 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3937 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3941 jp = getjob(*argv, 1);
3942 if (mode == FORK_BG) {
3943 set_curjob(jp, CUR_RUNNING);
3944 printf("[%d] ", jobno(jp));
3946 out1str(jp->ps[0].ps_cmd);
3947 showpipe(jp /*, stdout*/);
3948 retval = restartjob(jp, mode);
3949 } while (*argv && *++argv);
3955 sprint_status48(char *s, int status, int sigonly)
3961 if (!WIFEXITED(status)) {
3962 if (JOBS && WIFSTOPPED(status))
3963 st = WSTOPSIG(status);
3965 st = WTERMSIG(status);
3967 if (st == SIGINT || st == SIGPIPE)
3969 if (JOBS && WIFSTOPPED(status))
3973 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3974 col = fmtstr(s, 32, strsignal(st));
3975 if (WCOREDUMP(status)) {
3976 strcpy(s + col, " (core dumped)");
3977 col += sizeof(" (core dumped)")-1;
3979 } else if (!sigonly) {
3980 st = WEXITSTATUS(status);
3981 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
3988 wait_block_or_sig(int *status)
3995 /* Poll all children for changes in their state */
3997 /* if job control is active, accept stopped processes too */
3998 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
4000 break; /* Error (e.g. EINTR, ECHILD) or pid */
4002 /* Children exist, but none are ready. Sleep until interesting signal */
4005 sigprocmask(SIG_SETMASK, &mask, &mask);
4006 while (!got_sigchld && !pending_sig)
4008 sigprocmask(SIG_SETMASK, &mask, NULL);
4009 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
4010 while (!got_sigchld && !pending_sig)
4014 /* If it was SIGCHLD, poll children again */
4015 } while (got_sigchld);
4020 #define DOWAIT_NONBLOCK 0
4021 #define DOWAIT_BLOCK 1
4022 #define DOWAIT_BLOCK_OR_SIG 2
4025 dowait(int block, struct job *job)
4030 struct job *thisjob = NULL;
4032 TRACE(("dowait(0x%x) called\n", block));
4034 /* It's wrong to call waitpid() outside of INT_OFF region:
4035 * signal can arrive just after syscall return and handler can
4036 * longjmp away, losing stop/exit notification processing.
4037 * Thus, for "jobs" builtin, and for waiting for a fg job,
4038 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4040 * However, for "wait" builtin it is wrong to simply call waitpid()
4041 * in INT_OFF region: "wait" needs to wait for any running job
4042 * to change state, but should exit on any trap too.
4043 * In INT_OFF region, a signal just before syscall entry can set
4044 * pending_sig variables, but we can't check them, and we would
4045 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4047 * Because of this, we run inside INT_OFF, but use a special routine
4048 * which combines waitpid() and sigsuspend().
4049 * This is the reason why we need to have a handler for SIGCHLD:
4050 * SIG_DFL handler does not wake sigsuspend().
4053 if (block == DOWAIT_BLOCK_OR_SIG) {
4054 pid = wait_block_or_sig(&status);
4057 if (block == DOWAIT_NONBLOCK)
4058 wait_flags = WNOHANG;
4059 /* if job control is active, accept stopped processes too */
4061 wait_flags |= WUNTRACED;
4062 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4063 pid = waitpid(-1, &status, wait_flags);
4065 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4066 pid, status, errno, strerror(errno)));
4071 for (jp = curjob; jp; jp = jp->prev_job) {
4073 struct procstat *ps;
4074 struct procstat *psend;
4075 if (jp->state == JOBDONE)
4079 psend = ps + jp->nprocs;
4081 if (ps->ps_pid == pid) {
4082 TRACE(("Job %d: changing status of proc %d "
4083 "from 0x%x to 0x%x\n",
4084 jobno(jp), pid, ps->ps_status, status));
4085 ps->ps_status = status;
4088 if (ps->ps_status == -1)
4089 jobstate = JOBRUNNING;
4091 if (jobstate == JOBRUNNING)
4093 if (WIFSTOPPED(ps->ps_status)) {
4094 jp->stopstatus = ps->ps_status;
4095 jobstate = JOBSTOPPED;
4098 } while (++ps < psend);
4102 /* Found the job where one of its processes changed its state.
4103 * Is there at least one live and running process in this job? */
4104 if (jobstate != JOBRUNNING) {
4105 /* No. All live processes in the job are stopped
4106 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4108 thisjob->changed = 1;
4109 if (thisjob->state != jobstate) {
4110 TRACE(("Job %d: changing state from %d to %d\n",
4111 jobno(thisjob), thisjob->state, jobstate));
4112 thisjob->state = jobstate;
4114 if (jobstate == JOBSTOPPED)
4115 set_curjob(thisjob, CUR_STOPPED);
4121 /* The process wasn't found in job list */
4122 if (JOBS && !WIFSTOPPED(status))
4127 if (thisjob && thisjob == job) {
4131 len = sprint_status48(s, status, 1);
4143 showjob(struct job *jp, int mode)
4145 struct procstat *ps;
4146 struct procstat *psend;
4149 char s[16 + 16 + 48];
4150 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4154 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4155 /* just output process (group) id of pipeline */
4156 fprintf(out, "%d\n", ps->ps_pid);
4160 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4165 else if (curjob && jp == curjob->prev_job)
4168 if (mode & SHOW_PIDS)
4169 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4171 psend = ps + jp->nprocs;
4173 if (jp->state == JOBRUNNING) {
4174 strcpy(s + col, "Running");
4175 col += sizeof("Running") - 1;
4177 int status = psend[-1].ps_status;
4178 if (jp->state == JOBSTOPPED)
4179 status = jp->stopstatus;
4180 col += sprint_status48(s + col, status, 0);
4182 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4184 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4185 * or prints several "PID | <cmdN>" lines,
4186 * depending on SHOW_PIDS bit.
4187 * We do not print status of individual processes
4188 * between PID and <cmdN>. bash does it, but not very well:
4189 * first line shows overall job status, not process status,
4190 * making it impossible to know 1st process status.
4194 /* for each process */
4197 if (mode & SHOW_PIDS)
4198 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4200 fprintf(out, "%s%*c%s%s",
4202 33 - col >= 0 ? 33 - col : 0, ' ',
4203 ps == jp->ps ? "" : "| ",
4206 } while (++ps != psend);
4207 newline_and_flush(out);
4211 if (jp->state == JOBDONE) {
4212 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4218 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4219 * statuses have changed since the last call to showjobs.
4226 TRACE(("showjobs(0x%x) called\n", mode));
4228 /* Handle all finished jobs */
4229 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4232 for (jp = curjob; jp; jp = jp->prev_job) {
4233 if (!(mode & SHOW_CHANGED) || jp->changed) {
4239 static int FAST_FUNC
4240 jobscmd(int argc UNUSED_PARAM, char **argv)
4245 while ((m = nextopt("lp")) != '\0') {
4249 mode |= SHOW_ONLY_PGID;
4255 showjob(getjob(*argv, 0), mode);
4265 /* Called only on finished or stopped jobs (no members are running) */
4267 getstatus(struct job *job)
4271 struct procstat *ps;
4273 /* Fetch last member's status */
4274 ps = job->ps + job->nprocs - 1;
4275 status = ps->ps_status;
4277 /* "set -o pipefail" mode: use last _nonzero_ status */
4278 while (status == 0 && --ps >= job->ps)
4279 status = ps->ps_status;
4282 retval = WEXITSTATUS(status);
4283 if (!WIFEXITED(status)) {
4285 retval = WSTOPSIG(status);
4286 if (!WIFSTOPPED(status))
4289 /* XXX: limits number of signals */
4290 retval = WTERMSIG(status);
4292 if (retval == SIGINT)
4298 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4299 jobno(job), job->nprocs, status, retval));
4303 static int FAST_FUNC
4304 waitcmd(int argc UNUSED_PARAM, char **argv)
4315 /* wait for all jobs */
4319 if (!jp) /* no running procs */
4321 if (jp->state == JOBRUNNING)
4327 * "When bash is waiting for an asynchronous command via
4328 * the wait builtin, the reception of a signal for which a trap
4329 * has been set will cause the wait builtin to return immediately
4330 * with an exit status greater than 128, immediately after which
4331 * the trap is executed."
4333 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4334 /* if child sends us a signal *and immediately exits*,
4335 * dowait() returns pid > 0. Check this case,
4336 * not "if (dowait() < 0)"!
4345 if (**argv != '%') {
4346 pid_t pid = number(*argv);
4351 if (job->ps[job->nprocs - 1].ps_pid == pid)
4353 job = job->prev_job;
4356 job = getjob(*argv, 0);
4358 /* loop until process terminated or stopped */
4359 while (job->state == JOBRUNNING) {
4360 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4365 retval = getstatus(job);
4372 retval = 128 + pending_sig;
4381 struct job *jp, *jq;
4383 len = njobs * sizeof(*jp);
4385 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4387 offset = (char *)jp - (char *)jq;
4389 /* Relocate pointers */
4392 jq = (struct job *)((char *)jq + l);
4396 #define joff(p) ((struct job *)((char *)(p) + l))
4397 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4398 if (joff(jp)->ps == &jq->ps0)
4399 jmove(joff(jp)->ps);
4400 if (joff(jp)->prev_job)
4401 jmove(joff(jp)->prev_job);
4411 jp = (struct job *)((char *)jp + len);
4415 } while (--jq >= jp);
4420 * Return a new job structure.
4421 * Called with interrupts off.
4424 makejob(/*union node *node,*/ int nprocs)
4429 for (i = njobs, jp = jobtab; ; jp++) {
4436 if (jp->state != JOBDONE || !jp->waited)
4445 memset(jp, 0, sizeof(*jp));
4447 /* jp->jobctl is a bitfield.
4448 * "jp->jobctl |= jobctl" likely to give awful code */
4452 jp->prev_job = curjob;
4457 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4459 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4466 * Return a string identifying a command (to be printed by the
4469 static char *cmdnextc;
4472 cmdputs(const char *s)
4474 static const char vstype[VSTYPE + 1][3] = {
4475 "", "}", "-", "+", "?", "=",
4476 "%", "%%", "#", "##"
4477 IF_BASH_SUBSTR(, ":")
4478 IF_BASH_PATTERN_SUBST(, "/", "//")
4481 const char *p, *str;
4485 unsigned char subtype = 0;
4489 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4491 while ((c = *p++) != '\0') {
4499 if ((subtype & VSTYPE) == VSLENGTH)
4505 str = "\"}" + !(quoted & 1);
4512 #if ENABLE_FEATURE_SH_MATH
4527 if ((subtype & VSTYPE) != VSNORMAL)
4529 str = vstype[subtype & VSTYPE];
4530 if (subtype & VSNUL)
4539 /* These can only happen inside quotes */
4552 while ((c = *str++) != '\0') {
4555 } /* while *p++ not NUL */
4558 USTPUTC('"', nextc);
4564 /* cmdtxt() and cmdlist() call each other */
4565 static void cmdtxt(union node *n);
4568 cmdlist(union node *np, int sep)
4570 for (; np; np = np->narg.next) {
4574 if (sep && np->narg.next)
4580 cmdtxt(union node *n)
4583 struct nodelist *lp;
4594 lp = n->npipe.cmdlist;
4612 cmdtxt(n->nbinary.ch1);
4628 cmdtxt(n->nif.test);
4630 if (n->nif.elsepart) {
4631 cmdtxt(n->nif.ifpart);
4633 n = n->nif.elsepart;
4651 cmdtxt(n->nbinary.ch1);
4661 cmdputs(n->nfor.var);
4663 cmdlist(n->nfor.args, 1);
4668 cmdputs(n->narg.text);
4672 cmdlist(n->ncmd.args, 1);
4673 cmdlist(n->ncmd.redirect, 0);
4686 cmdputs(n->ncase.expr->narg.text);
4688 for (np = n->ncase.cases; np; np = np->nclist.next) {
4689 cmdtxt(np->nclist.pattern);
4691 cmdtxt(np->nclist.body);
4705 #if BASH_REDIR_OUTPUT
4720 cmdputs(utoa(n->nfile.fd));
4722 if (n->type == NTOFD || n->type == NFROMFD) {
4723 cmdputs(utoa(n->ndup.dupfd));
4732 commandtext(union node *n)
4736 STARTSTACKSTR(cmdnextc);
4738 name = stackblock();
4739 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4740 return ckstrdup(name);
4745 * Fork off a subshell. If we are doing job control, give the subshell its
4746 * own process group. Jp is a job structure that the job is to be added to.
4747 * N is the command that will be evaluated by the child. Both jp and n may
4748 * be NULL. The mode parameter can be one of the following:
4749 * FORK_FG - Fork off a foreground process.
4750 * FORK_BG - Fork off a background process.
4751 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4752 * process group even if job control is on.
4754 * When job control is turned off, background processes have their standard
4755 * input redirected to /dev/null (except for the second and later processes
4758 * Called with interrupts off.
4761 * Clear traps on a fork.
4769 for (tp = trap; tp < &trap[NSIG]; tp++) {
4770 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4771 if (trap_ptr == trap)
4773 /* else: it "belongs" to trap_ptr vector, don't free */
4775 if ((tp - trap) != 0)
4776 setsignal(tp - trap);
4783 /* Lives far away from here, needed for forkchild */
4784 static void closescript(void);
4786 /* Called after fork(), in child */
4787 /* jp and n are NULL when called by openhere() for heredoc support */
4788 static NOINLINE void
4789 forkchild(struct job *jp, union node *n, int mode)
4793 TRACE(("Child shell %d\n", getpid()));
4797 /* man bash: "Non-builtin commands run by bash have signal handlers
4798 * set to the values inherited by the shell from its parent".
4799 * Do we do it correctly? */
4803 if (mode == FORK_NOJOB /* is it `xxx` ? */
4804 && n && n->type == NCMD /* is it single cmd? */
4805 /* && n->ncmd.args->type == NARG - always true? */
4806 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4807 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4808 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4810 TRACE(("Trap hack\n"));
4811 /* Awful hack for `trap` or $(trap).
4813 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4814 * contains an example where "trap" is executed in a subshell:
4816 * save_traps=$(trap)
4818 * eval "$save_traps"
4820 * Standard does not say that "trap" in subshell shall print
4821 * parent shell's traps. It only says that its output
4822 * must have suitable form, but then, in the above example
4823 * (which is not supposed to be normative), it implies that.
4825 * bash (and probably other shell) does implement it
4826 * (traps are reset to defaults, but "trap" still shows them),
4827 * but as a result, "trap" logic is hopelessly messed up:
4830 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4831 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4832 * # true | trap <--- trap is in subshell - no output (ditto)
4833 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4834 * trap -- 'echo Ho' SIGWINCH
4835 * # echo `(trap)` <--- in subshell in subshell - output
4836 * trap -- 'echo Ho' SIGWINCH
4837 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4838 * trap -- 'echo Ho' SIGWINCH
4840 * The rules when to forget and when to not forget traps
4841 * get really complex and nonsensical.
4843 * Our solution: ONLY bare $(trap) or `trap` is special.
4845 /* Save trap handler strings for trap builtin to print */
4846 trap_ptr = xmemdup(trap, sizeof(trap));
4847 /* Fall through into clearing traps */
4851 /* do job control only in root shell */
4853 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4856 if (jp->nprocs == 0)
4859 pgrp = jp->ps[0].ps_pid;
4860 /* this can fail because we are doing it in the parent also */
4862 if (mode == FORK_FG)
4863 xtcsetpgrp(ttyfd, pgrp);
4868 if (mode == FORK_BG) {
4869 /* man bash: "When job control is not in effect,
4870 * asynchronous commands ignore SIGINT and SIGQUIT" */
4873 if (jp->nprocs == 0) {
4875 if (open(bb_dev_null, O_RDONLY) != 0)
4876 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4880 if (iflag) { /* why if iflag only? */
4885 * "In all cases, bash ignores SIGQUIT. Non-builtin
4886 * commands run by bash have signal handlers
4887 * set to the values inherited by the shell
4889 * Take care of the second rule: */
4893 if (n && n->type == NCMD
4894 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4896 TRACE(("Job hack\n"));
4897 /* "jobs": we do not want to clear job list for it,
4898 * instead we remove only _its_ own_ job from job list.
4899 * This makes "jobs .... | cat" more useful.
4905 for (jp = curjob; jp; jp = jp->prev_job)
4910 /* Called after fork(), in parent */
4912 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4915 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4917 TRACE(("In parent shell: child = %d\n", pid));
4919 /* jp is NULL when called by openhere() for heredoc support */
4920 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4926 if (mode != FORK_NOJOB && jp->jobctl) {
4929 if (jp->nprocs == 0)
4932 pgrp = jp->ps[0].ps_pid;
4933 /* This can fail because we are doing it in the child also */
4937 if (mode == FORK_BG) {
4938 backgndpid = pid; /* set $! */
4939 set_curjob(jp, CUR_RUNNING);
4942 struct procstat *ps = &jp->ps[jp->nprocs++];
4945 ps->ps_cmd = nullstr;
4947 if (doing_jobctl && n)
4948 ps->ps_cmd = commandtext(n);
4953 /* jp and n are NULL when called by openhere() for heredoc support */
4955 forkshell(struct job *jp, union node *n, int mode)
4959 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4962 TRACE(("Fork failed, errno=%d", errno));
4965 ash_msg_and_raise_error("can't fork");
4968 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4969 forkchild(jp, n, mode);
4971 forkparent(jp, n, mode, pid);
4977 * Wait for job to finish.
4979 * Under job control we have the problem that while a child process
4980 * is running interrupts generated by the user are sent to the child
4981 * but not to the shell. This means that an infinite loop started by
4982 * an interactive user may be hard to kill. With job control turned off,
4983 * an interactive user may place an interactive program inside a loop.
4984 * If the interactive program catches interrupts, the user doesn't want
4985 * these interrupts to also abort the loop. The approach we take here
4986 * is to have the shell ignore interrupt signals while waiting for a
4987 * foreground process to terminate, and then send itself an interrupt
4988 * signal if the child process was terminated by an interrupt signal.
4989 * Unfortunately, some programs want to do a bit of cleanup and then
4990 * exit on interrupt; unless these processes terminate themselves by
4991 * sending a signal to themselves (instead of calling exit) they will
4992 * confuse this approach.
4994 * Called with interrupts off.
4997 waitforjob(struct job *jp)
5001 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
5004 while (jp->state == JOBRUNNING) {
5005 /* In non-interactive shells, we _can_ get
5006 * a keyboard signal here and be EINTRed,
5007 * but we just loop back, waiting for command to complete.
5010 * "If bash is waiting for a command to complete and receives
5011 * a signal for which a trap has been set, the trap
5012 * will not be executed until the command completes."
5014 * Reality is that even if trap is not set, bash
5015 * will not act on the signal until command completes.
5016 * Try this. sleep5intoff.c:
5017 * #include <signal.h>
5018 * #include <unistd.h>
5021 * sigemptyset(&set);
5022 * sigaddset(&set, SIGINT);
5023 * sigaddset(&set, SIGQUIT);
5024 * sigprocmask(SIG_BLOCK, &set, NULL);
5028 * $ bash -c './sleep5intoff; echo hi'
5029 * ^C^C^C^C <--- pressing ^C once a second
5031 * $ bash -c './sleep5intoff; echo hi'
5032 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5035 dowait(DOWAIT_BLOCK, jp);
5042 xtcsetpgrp(ttyfd, rootpid);
5044 * This is truly gross.
5045 * If we're doing job control, then we did a TIOCSPGRP which
5046 * caused us (the shell) to no longer be in the controlling
5047 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5048 * intuit from the subprocess exit status whether a SIGINT
5049 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5051 if (jp->sigint) /* TODO: do the same with all signals */
5052 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5054 if (jp->state == JOBDONE)
5061 * return 1 if there are stopped jobs, otherwise 0
5073 if (jp && jp->state == JOBSTOPPED) {
5074 out2str("You have stopped jobs.\n");
5084 * Code for dealing with input/output redirection.
5089 #define EMPTY -2 /* marks an unused slot in redirtab */
5090 #define CLOSED -3 /* marks a slot of previously-closed fd */
5093 * Open a file in noclobber mode.
5094 * The code was copied from bash.
5097 noclobberopen(const char *fname)
5100 struct stat finfo, finfo2;
5103 * If the file exists and is a regular file, return an error
5106 r = stat(fname, &finfo);
5107 if (r == 0 && S_ISREG(finfo.st_mode)) {
5113 * If the file was not present (r != 0), make sure we open it
5114 * exclusively so that if it is created before we open it, our open
5115 * will fail. Make sure that we do not truncate an existing file.
5116 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5117 * file was not a regular file, we leave O_EXCL off.
5120 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5121 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5123 /* If the open failed, return the file descriptor right away. */
5128 * OK, the open succeeded, but the file may have been changed from a
5129 * non-regular file to a regular file between the stat and the open.
5130 * We are assuming that the O_EXCL open handles the case where FILENAME
5131 * did not exist and is symlinked to an existing file between the stat
5136 * If we can open it and fstat the file descriptor, and neither check
5137 * revealed that it was a regular file, and the file has not been
5138 * replaced, return the file descriptor.
5140 if (fstat(fd, &finfo2) == 0
5141 && !S_ISREG(finfo2.st_mode)
5142 && finfo.st_dev == finfo2.st_dev
5143 && finfo.st_ino == finfo2.st_ino
5148 /* The file has been replaced. badness. */
5155 * Handle here documents. Normally we fork off a process to write the
5156 * data to a pipe. If the document is short, we can stuff the data in
5157 * the pipe without forking.
5159 /* openhere needs this forward reference */
5160 static void expandhere(union node *arg, int fd);
5162 openhere(union node *redir)
5168 ash_msg_and_raise_error("pipe call failed");
5169 if (redir->type == NHERE) {
5170 len = strlen(redir->nhere.doc->narg.text);
5171 if (len <= PIPE_BUF) {
5172 full_write(pip[1], redir->nhere.doc->narg.text, len);
5176 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5179 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5180 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5181 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5182 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5183 signal(SIGPIPE, SIG_DFL);
5184 if (redir->type == NHERE)
5185 full_write(pip[1], redir->nhere.doc->narg.text, len);
5187 expandhere(redir->nhere.doc, pip[1]);
5188 _exit(EXIT_SUCCESS);
5196 openredirect(union node *redir)
5201 switch (redir->nfile.type) {
5202 /* Can't happen, our single caller does this itself */
5208 return openhere(redir);
5211 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5212 * allocated space. Do it only when we know it is safe.
5214 fname = redir->nfile.expfname;
5216 switch (redir->nfile.type) {
5222 f = open(fname, O_RDONLY);
5227 f = open(fname, O_RDWR|O_CREAT, 0666);
5232 #if BASH_REDIR_OUTPUT
5235 /* Take care of noclobber mode. */
5237 f = noclobberopen(fname);
5244 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5249 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5257 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5259 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5263 * Copy a file descriptor to be >= 10. Throws exception on error.
5271 newfd = fcntl(from, F_DUPFD, 10);
5272 err = newfd < 0 ? errno : 0;
5275 ash_msg_and_raise_error("%d: %m", from);
5277 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5283 dup2_or_raise(int from, int to)
5287 newfd = (from != to) ? dup2(from, to) : to;
5289 /* Happens when source fd is not open: try "echo >&99" */
5290 ash_msg_and_raise_error("%d: %m", from);
5295 /* Struct def and variable are moved down to the first usage site */
5300 struct redirtab *next;
5302 struct two_fd_t two_fd[];
5304 #define redirlist (G_var.redirlist)
5306 COPYFD_RESTORE = (int)~(INT_MAX),
5310 need_to_remember(struct redirtab *rp, int fd)
5314 if (!rp) /* remembering was not requested */
5317 for (i = 0; i < rp->pair_count; i++) {
5318 if (rp->two_fd[i].orig == fd) {
5319 /* already remembered */
5326 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5328 is_hidden_fd(struct redirtab *rp, int fd)
5331 struct parsefile *pf;
5335 /* Check open scripts' fds */
5338 /* We skip pf_fd == 0 case because of the following case:
5339 * $ ash # running ash interactively
5341 * and in script.sh: "exec 9>&0".
5342 * Even though top-level pf_fd _is_ 0,
5343 * it's still ok to use it: "read" builtin uses it,
5344 * why should we cripple "exec" builtin?
5346 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5354 /* Check saved fds of redirects */
5355 fd |= COPYFD_RESTORE;
5356 for (i = 0; i < rp->pair_count; i++) {
5357 if (rp->two_fd[i].copy == fd) {
5365 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5366 * old file descriptors are stashed away so that the redirection can be
5367 * undone by calling popredir.
5369 /* flags passed to redirect */
5370 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5371 #define REDIR_SAVEFD2 03 /* set preverrout */
5373 redirect(union node *redir, int flags)
5375 struct redirtab *sv;
5380 int copied_fd2 = -1;
5389 if (flags & REDIR_PUSH) {
5390 union node *tmp = redir;
5393 #if BASH_REDIR_OUTPUT
5394 if (tmp->nfile.type == NTO2)
5397 tmp = tmp->nfile.next;
5399 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5400 sv->next = redirlist;
5401 sv->pair_count = sv_pos;
5403 while (sv_pos > 0) {
5405 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5411 fd = redir->nfile.fd;
5412 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5413 right_fd = redir->ndup.dupfd;
5414 //bb_error_msg("doing %d > %d", fd, right_fd);
5415 /* redirect from/to same file descriptor? */
5418 /* "echo >&10" and 10 is a fd opened to a sh script? */
5419 if (is_hidden_fd(sv, right_fd)) {
5420 errno = EBADF; /* as if it is closed */
5421 ash_msg_and_raise_error("%d: %m", right_fd);
5425 newfd = openredirect(redir); /* always >= 0 */
5427 /* Descriptor wasn't open before redirect.
5428 * Mark it for close in the future */
5429 if (need_to_remember(sv, fd)) {
5430 goto remember_to_close;
5435 #if BASH_REDIR_OUTPUT
5438 if (need_to_remember(sv, fd)) {
5439 /* Copy old descriptor */
5440 /* Careful to not accidentally "save"
5441 * to the same fd as right side fd in N>&M */
5442 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5443 #if defined(F_DUPFD_CLOEXEC)
5444 i = fcntl(fd, F_DUPFD_CLOEXEC, minfd);
5446 i = fcntl(fd, F_DUPFD, minfd);
5451 /* Strange error (e.g. "too many files" EMFILE?) */
5455 ash_msg_and_raise_error("%d: %m", fd);
5458 /* EBADF: it is not open - good, remember to close it */
5461 } else { /* fd is open, save its copy */
5462 #if !defined(F_DUPFD_CLOEXEC)
5463 fcntl(i, F_SETFD, FD_CLOEXEC);
5465 /* "exec fd>&-" should not close fds
5466 * which point to script file(s).
5467 * Force them to be restored afterwards */
5468 if (is_hidden_fd(sv, fd))
5469 i |= COPYFD_RESTORE;
5473 sv->two_fd[sv_pos].orig = fd;
5474 sv->two_fd[sv_pos].copy = i;
5478 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5479 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5480 /* Don't want to trigger debugging */
5484 dup2_or_raise(redir->ndup.dupfd, fd);
5486 } else if (fd != newfd) { /* move newfd to fd */
5487 dup2_or_raise(newfd, fd);
5488 #if BASH_REDIR_OUTPUT
5489 if (!(redir->nfile.type == NTO2 && fd == 2))
5493 #if BASH_REDIR_OUTPUT
5494 if (redir->nfile.type == NTO2 && fd == 1) {
5495 /* We already redirected it to fd 1, now copy it to 2 */
5501 } while ((redir = redir->nfile.next) != NULL);
5504 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5505 preverrout_fd = copied_fd2;
5509 * Undo the effects of the last redirection.
5512 popredir(int drop, int restore)
5514 struct redirtab *rp;
5517 if (redirlist == NULL)
5521 for (i = 0; i < rp->pair_count; i++) {
5522 int fd = rp->two_fd[i].orig;
5523 int copy = rp->two_fd[i].copy;
5524 if (copy == CLOSED) {
5529 if (copy != EMPTY) {
5530 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5531 copy &= ~COPYFD_RESTORE;
5533 dup2_or_raise(copy, fd);
5535 close(copy & ~COPYFD_RESTORE);
5538 redirlist = rp->next;
5544 * Undo all redirections. Called on error or interrupt.
5548 redirectsafe(union node *redir, int flags)
5551 volatile int saveint;
5552 struct jmploc *volatile savehandler = exception_handler;
5553 struct jmploc jmploc;
5556 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5557 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5559 exception_handler = &jmploc;
5560 redirect(redir, flags);
5562 exception_handler = savehandler;
5563 if (err && exception_type != EXERROR)
5564 longjmp(exception_handler->loc, 1);
5565 RESTORE_INT(saveint);
5570 /* ============ Routines to expand arguments to commands
5572 * We have to deal with backquotes, shell variables, and file metacharacters.
5575 #if ENABLE_FEATURE_SH_MATH
5577 ash_arith(const char *s)
5579 arith_state_t math_state;
5582 math_state.lookupvar = lookupvar;
5583 math_state.setvar = setvar0;
5584 //math_state.endofname = endofname;
5587 result = arith(&math_state, s);
5588 if (math_state.errmsg)
5589 ash_msg_and_raise_error(math_state.errmsg);
5599 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5600 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5601 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5602 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5603 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5604 * POSIX says for this case:
5605 * Pathname expansion shall not be performed on the word by a
5606 * non-interactive shell; an interactive shell may perform it, but shall
5607 * do so only when the expansion would result in one word.
5608 * Currently, our code complies to the above rule by never globbing
5609 * redirection filenames.
5610 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5611 * (this means that on a typical Linux distro, bash almost always
5612 * performs globbing, and thus diverges from what we do).
5614 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5615 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5616 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5617 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5618 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5622 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5623 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5624 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5625 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5626 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5628 /* Add CTLESC when necessary. */
5629 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5630 /* Do not skip NUL characters. */
5631 #define QUOTES_KEEPNUL EXP_TILDE
5634 * Structure specifying which parts of the string should be searched
5635 * for IFS characters.
5638 struct ifsregion *next; /* next region in list */
5639 int begoff; /* offset of start of region */
5640 int endoff; /* offset of end of region */
5641 int nulonly; /* search for nul bytes only */
5645 struct strlist *list;
5646 struct strlist **lastp;
5649 /* output of current string */
5650 static char *expdest;
5651 /* list of back quote expressions */
5652 static struct nodelist *argbackq;
5653 /* first struct in list of ifs regions */
5654 static struct ifsregion ifsfirst;
5655 /* last struct in list */
5656 static struct ifsregion *ifslastp;
5657 /* holds expanded arg list */
5658 static struct arglist exparg;
5663 #if !ENABLE_FEATURE_SH_MATH
5664 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5665 typedef long arith_t;
5666 # define ARITH_FMT "%ld"
5673 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5674 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5675 STADJUST(len, expdest);
5680 * Break the argument string into pieces based upon IFS and add the
5681 * strings to the argument list. The regions of the string to be
5682 * searched for IFS characters have been stored by recordregion.
5685 ifsbreakup(char *string, struct arglist *arglist)
5687 struct ifsregion *ifsp;
5692 const char *ifs, *realifs;
5697 if (ifslastp != NULL) {
5700 realifs = ifsset() ? ifsval() : defifs;
5703 p = string + ifsp->begoff;
5704 nulonly = ifsp->nulonly;
5705 ifs = nulonly ? nullstr : realifs;
5707 while (p < string + ifsp->endoff) {
5709 if ((unsigned char)*p == CTLESC)
5711 if (!strchr(ifs, *p)) {
5716 ifsspc = (strchr(defifs, *p) != NULL);
5717 /* Ignore IFS whitespace at start */
5718 if (q == start && ifsspc) {
5724 sp = stzalloc(sizeof(*sp));
5726 *arglist->lastp = sp;
5727 arglist->lastp = &sp->next;
5731 if (p >= string + ifsp->endoff) {
5735 if ((unsigned char)*p == CTLESC)
5737 if (strchr(ifs, *p) == NULL) {
5741 if (strchr(defifs, *p) == NULL) {
5756 } while (ifsp != NULL);
5765 sp = stzalloc(sizeof(*sp));
5767 *arglist->lastp = sp;
5768 arglist->lastp = &sp->next;
5774 struct ifsregion *p = ifsfirst.next;
5781 struct ifsregion *ifsp;
5786 ifsfirst.next = NULL;
5793 esclen(const char *start, const char *p)
5797 while (p > start && (unsigned char)*--p == CTLESC) {
5804 * Remove any CTLESC characters from a string.
5807 rmescapes(char *str, int flag)
5809 static const char qchars[] ALIGN1 = {
5810 IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
5814 unsigned protect_against_glob;
5816 IF_BASH_PATTERN_SUBST(unsigned slash = flag & RMESCAPE_SLASH;)
5818 p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash));
5824 if (flag & RMESCAPE_ALLOC) {
5825 size_t len = p - str;
5826 size_t fulllen = len + strlen(p) + 1;
5828 if (flag & RMESCAPE_GROW) {
5829 int strloc = str - (char *)stackblock();
5830 r = makestrspace(fulllen, expdest);
5831 /* p and str may be invalidated by makestrspace */
5832 str = (char *)stackblock() + strloc;
5834 } else if (flag & RMESCAPE_HEAP) {
5835 r = ckmalloc(fulllen);
5837 r = stalloc(fulllen);
5841 q = (char *)memcpy(q, str, len) + len;
5846 globbing = flag & RMESCAPE_GLOB;
5847 protect_against_glob = globbing;
5849 if ((unsigned char)*p == CTLQUOTEMARK) {
5850 // Note: both inquotes and protect_against_glob only affect whether
5851 inquotes = ~inquotes;
5853 protect_against_glob = globbing;
5856 if ((unsigned char)*p == CTLESC) {
5860 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5862 if (protect_against_glob) {
5865 } else if (*p == '\\' && !inquotes) {
5866 /* naked back slash */
5867 protect_against_glob = 0;
5870 #if BASH_PATTERN_SUBST
5871 else if (*p == '/' && slash) {
5872 /* stop handling globbing and mark location of slash */
5873 globbing = slash = 0;
5877 protect_against_glob = globbing;
5882 if (flag & RMESCAPE_GROW) {
5884 STADJUST(q - r + 1, expdest);
5888 #define pmatch(a, b) !fnmatch((a), (b), 0)
5891 * Prepare a pattern for a expmeta (internal glob(3)) call.
5893 * Returns an stalloced string.
5896 preglob(const char *pattern, int flag)
5898 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5902 * Put a string on the stack.
5905 memtodest(const char *p, size_t len, int syntax, int quotes)
5912 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5915 unsigned char c = *p++;
5917 if (quotes & QUOTES_ESC) {
5918 int n = SIT(c, syntax);
5920 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
5927 } else if (!(quotes & QUOTES_KEEPNUL))
5936 strtodest(const char *p, int syntax, int quotes)
5938 size_t len = strlen(p);
5939 memtodest(p, len, syntax, quotes);
5944 * Record the fact that we have to scan this region of the
5945 * string for IFS characters.
5948 recordregion(int start, int end, int nulonly)
5950 struct ifsregion *ifsp;
5952 if (ifslastp == NULL) {
5956 ifsp = ckzalloc(sizeof(*ifsp));
5957 /*ifsp->next = NULL; - ckzalloc did it */
5958 ifslastp->next = ifsp;
5962 ifslastp->begoff = start;
5963 ifslastp->endoff = end;
5964 ifslastp->nulonly = nulonly;
5968 removerecordregions(int endoff)
5970 if (ifslastp == NULL)
5973 if (ifsfirst.endoff > endoff) {
5974 while (ifsfirst.next) {
5975 struct ifsregion *ifsp;
5977 ifsp = ifsfirst.next->next;
5978 free(ifsfirst.next);
5979 ifsfirst.next = ifsp;
5982 if (ifsfirst.begoff > endoff) {
5985 ifslastp = &ifsfirst;
5986 ifsfirst.endoff = endoff;
5991 ifslastp = &ifsfirst;
5992 while (ifslastp->next && ifslastp->next->begoff < endoff)
5993 ifslastp = ifslastp->next;
5994 while (ifslastp->next) {
5995 struct ifsregion *ifsp;
5997 ifsp = ifslastp->next->next;
5998 free(ifslastp->next);
5999 ifslastp->next = ifsp;
6002 if (ifslastp->endoff > endoff)
6003 ifslastp->endoff = endoff;
6007 exptilde(char *startp, char *p, int flags)
6013 int quotes = flags & QUOTES_ESC;
6017 while ((c = *++p) != '\0') {
6024 if (flags & EXP_VARTILDE)
6034 if (*name == '\0') {
6035 home = lookupvar("HOME");
6037 pw = getpwnam(name);
6042 if (!home || !*home)
6045 strtodest(home, SQSYNTAX, quotes);
6053 * Execute a command inside back quotes. If it's a builtin command, we
6054 * want to save its output in a block obtained from malloc. Otherwise
6055 * we fork off a subprocess and get the output of the command via a pipe.
6056 * Should be called with interrupts off.
6058 struct backcmd { /* result of evalbackcmd */
6059 int fd; /* file descriptor to read from */
6060 int nleft; /* number of chars in buffer */
6061 char *buf; /* buffer */
6062 struct job *jp; /* job structure for command */
6065 /* These forward decls are needed to use "eval" code for backticks handling: */
6066 #define EV_EXIT 01 /* exit after evaluating tree */
6067 static int evaltree(union node *, int);
6069 static void FAST_FUNC
6070 evalbackcmd(union node *n, struct backcmd *result)
6084 ash_msg_and_raise_error("pipe call failed");
6085 jp = makejob(/*n,*/ 1);
6086 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6092 dup2_or_raise(pip[1], 1);
6095 /* TODO: eflag clearing makes the following not abort:
6096 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6097 * which is what bash does (unless it is in POSIX mode).
6098 * dash deleted "eflag = 0" line in the commit
6099 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6100 * [EVAL] Don't clear eflag in evalbackcmd
6101 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6105 evaltree(n, EV_EXIT); /* actually evaltreenr... */
6110 result->fd = pip[0];
6114 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6115 result->fd, result->buf, result->nleft, result->jp));
6119 * Expand stuff in backwards quotes.
6122 expbackq(union node *cmd, int flag)
6130 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6131 struct stackmark smark;
6134 startloc = expdest - (char *)stackblock();
6135 pushstackmark(&smark, startloc);
6136 evalbackcmd(cmd, &in);
6137 popstackmark(&smark);
6144 memtodest(p, i, syntax, flag & QUOTES_ESC);
6148 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6149 TRACE(("expbackq: read returns %d\n", i));
6158 back_exitstatus = waitforjob(in.jp);
6162 /* Eat all trailing newlines */
6164 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6168 if (!(flag & EXP_QUOTED))
6169 recordregion(startloc, dest - (char *)stackblock(), 0);
6170 TRACE(("evalbackq: size:%d:'%.*s'\n",
6171 (int)((dest - (char *)stackblock()) - startloc),
6172 (int)((dest - (char *)stackblock()) - startloc),
6173 stackblock() + startloc));
6176 #if ENABLE_FEATURE_SH_MATH
6178 * Expand arithmetic expression. Backup to start of expression,
6179 * evaluate, place result in (backed up) result, adjust string position.
6191 * This routine is slightly over-complicated for
6192 * efficiency. Next we scan backwards looking for the
6193 * start of arithmetic.
6195 start = stackblock();
6202 while ((unsigned char)*p != CTLARI) {
6206 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6211 esc = esclen(start, p);
6221 removerecordregions(begoff);
6225 if (flag & QUOTES_ESC)
6226 rmescapes(p + 1, 0);
6228 len = cvtnum(ash_arith(p + 1));
6230 if (!(flag & EXP_QUOTED))
6231 recordregion(begoff, begoff + len, 0);
6235 /* argstr needs it */
6236 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6239 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6240 * characters to allow for further processing. Otherwise treat
6241 * $@ like $* since no splitting will be performed.
6243 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6244 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6245 * for correct expansion of "B=$A" word.
6248 argstr(char *p, int flags, struct strlist *var_str_list)
6250 static const char spclchars[] ALIGN1 = {
6258 #if ENABLE_FEATURE_SH_MATH
6263 const char *reject = spclchars;
6264 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6269 if (!(flags & EXP_VARTILDE)) {
6271 } else if (flags & EXP_VARTILDE2) {
6276 if (flags & EXP_TILDE) {
6279 flags &= ~EXP_TILDE;
6283 p = exptilde(p, q, flags);
6286 startloc = expdest - (char *)stackblock();
6290 length += strcspn(p + length, reject);
6294 IF_FEATURE_SH_MATH(|| c == CTLENDARI)
6296 /* c == '=' || c == ':' || c == CTLENDARI */
6302 expdest = stack_nputstr(p, length, expdest);
6303 newloc = expdest - (char *)stackblock();
6304 if (breakall && !inquotes && newloc > startloc) {
6305 recordregion(startloc, newloc, 0);
6316 if (flags & EXP_VARTILDE2) {
6320 flags |= EXP_VARTILDE2;
6325 * sort of a hack - expand tildes in variable
6326 * assignments (after the first '=' and after ':'s).
6335 case CTLENDVAR: /* ??? */
6338 inquotes ^= EXP_QUOTED;
6339 /* "$@" syntax adherence hack */
6340 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6341 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6345 if (flags & QUOTES_ESC) {
6356 * Quoted parameter expansion pattern: remove quote
6357 * unless inside inner quotes or we have a literal
6360 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6361 EXP_QPAT && *p != '\\')
6366 TRACE(("argstr: evalvar('%s')\n", p));
6367 p = evalvar(p, flags | inquotes, var_str_list);
6368 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6371 expbackq(argbackq->n, flags | inquotes);
6372 argbackq = argbackq->next;
6374 #if ENABLE_FEATURE_SH_MATH
6377 expari(flags | inquotes);
6386 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6387 char *pattern, int quotes, int zero)
6396 const char *s = loc2;
6403 match = pmatch(pattern, s);
6408 if (quotes && (unsigned char)*loc == CTLESC)
6417 scanright(char *startp, char *rmesc, char *rmescend,
6418 char *pattern, int quotes, int match_at_start)
6420 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6421 int try2optimize = match_at_start;
6427 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6428 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6429 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6431 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6432 * and on each iteration they go back two/one char until they reach the beginning.
6433 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6435 /* TODO: document in what other circumstances we are called. */
6437 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6440 const char *s = loc2;
6441 if (match_at_start) {
6445 match = pmatch(pattern, s);
6446 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6450 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6452 /* Maybe we can optimize this:
6453 * if pattern ends with unescaped *, we can avoid checking
6454 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6455 * it wont match truncated "raw_value_of_" strings too.
6457 unsigned plen = strlen(pattern);
6458 /* Does it end with "*"? */
6459 if (plen != 0 && pattern[--plen] == '*') {
6460 /* "xxxx*" is not escaped */
6461 /* "xxx\*" is escaped */
6462 /* "xx\\*" is not escaped */
6463 /* "x\\\*" is escaped */
6465 while (plen != 0 && pattern[--plen] == '\\')
6468 break; /* ends with unescaped "*" */
6476 esc = esclen(startp, loc);
6487 static void varunset(const char *, const char *, const char *, int) NORETURN;
6489 varunset(const char *end, const char *var, const char *umsg, int varflags)
6495 msg = "parameter not set";
6497 if ((unsigned char)*end == CTLENDVAR) {
6498 if (varflags & VSNUL)
6504 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6508 subevalvar(char *p, char *varname, int strloc, int subtype,
6509 int startloc, int varflags, int flag, struct strlist *var_str_list)
6511 struct nodelist *saveargbackq = argbackq;
6512 int quotes = flag & QUOTES_ESC;
6515 char *rmesc, *rmescend;
6517 IF_BASH_SUBSTR(int pos, len, orig_len;)
6518 int amount, resetloc;
6519 IF_BASH_PATTERN_SUBST(int workloc;)
6520 IF_BASH_PATTERN_SUBST(char *repl = NULL;)
6522 char *(*scan)(char*, char*, char*, char*, int, int);
6524 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6525 // p, varname, strloc, subtype, startloc, varflags, quotes);
6527 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6528 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6530 STPUTC('\0', expdest);
6531 argbackq = saveargbackq;
6532 startp = (char *)stackblock() + startloc;
6536 setvar0(varname, startp);
6537 amount = startp - expdest;
6538 STADJUST(amount, expdest);
6542 varunset(p, varname, startp, varflags);
6547 //TODO: support more general format ${v:EXPR:EXPR},
6548 // where EXPR follows $(()) rules
6549 loc = str = stackblock() + strloc;
6550 /* Read POS in ${var:POS:LEN} */
6551 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6552 len = str - startp - 1;
6554 /* *loc != '\0', guaranteed by parser */
6558 /* Adjust the length by the number of escapes */
6559 for (ptr = startp; ptr < (str - 1); ptr++) {
6560 if ((unsigned char)*ptr == CTLESC) {
6568 if (*loc++ == ':') {
6572 /* Skip POS in ${var:POS:LEN} */
6574 while (*loc && *loc != ':') {
6576 * bash complains on: var=qwe; echo ${var:1a:123}
6578 ash_msg_and_raise_error(msg_illnum, str);
6582 if (*loc++ == ':') {
6587 /* ${VAR:$((-n)):l} starts n chars from the end */
6588 pos = orig_len + pos;
6590 if ((unsigned)pos >= orig_len) {
6591 /* apart from obvious ${VAR:999999:l},
6592 * covers ${VAR:$((-9999999)):l} - result is ""
6598 if (len > (orig_len - pos))
6599 len = orig_len - pos;
6601 for (str = startp; pos; str++, pos--) {
6602 if (quotes && (unsigned char)*str == CTLESC)
6605 for (loc = startp; len; len--) {
6606 if (quotes && (unsigned char)*str == CTLESC)
6611 amount = loc - expdest;
6612 STADJUST(amount, expdest);
6614 #endif /* BASH_SUBSTR */
6617 resetloc = expdest - (char *)stackblock();
6619 #if BASH_PATTERN_SUBST
6620 /* We'll comeback here if we grow the stack while handling
6621 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6622 * stack will need rebasing, and we'll need to remove our work
6628 amount = expdest - ((char *)stackblock() + resetloc);
6629 STADJUST(-amount, expdest);
6630 startp = (char *)stackblock() + startloc;
6633 rmescend = (char *)stackblock() + strloc;
6635 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6636 if (rmesc != startp) {
6638 startp = (char *)stackblock() + startloc;
6642 str = (char *)stackblock() + strloc;
6644 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6645 * The result is a_\_z_c (not a\_\_z_c)!
6647 * The search pattern and replace string treat backslashes differently!
6648 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6649 * and string. It's only used on the first call.
6651 preglob(str, IF_BASH_PATTERN_SUBST(
6652 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6653 RMESCAPE_SLASH : ) 0);
6655 #if BASH_PATTERN_SUBST
6656 workloc = expdest - (char *)stackblock();
6657 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6661 repl = strchr(str, CTLESC);
6667 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6669 /* If there's no pattern to match, return the expansion unmolested */
6678 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6679 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6681 /* No match, advance */
6682 char *restart_detect = stackblock();
6684 STPUTC(*idx, expdest);
6685 if (quotes && (unsigned char)*idx == CTLESC) {
6688 STPUTC(*idx, expdest);
6690 if (stackblock() != restart_detect)
6695 /* continue; - prone to quadratic behavior, smarter code: */
6698 if (str[0] == '*') {
6699 /* Pattern is "*foo". If "*foo" does not match "long_string",
6700 * it would never match "ong_string" etc, no point in trying.
6707 if (subtype == VSREPLACEALL) {
6709 if (quotes && (unsigned char)*idx == CTLESC)
6718 //bb_error_msg("repl:'%s'", repl);
6719 for (loc = (char*)repl; *loc; loc++) {
6720 char *restart_detect = stackblock();
6721 if (quotes && *loc == '\\') {
6722 STPUTC(CTLESC, expdest);
6725 STPUTC(*loc, expdest);
6726 if (stackblock() != restart_detect)
6731 if (subtype == VSREPLACE) {
6732 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6734 char *restart_detect = stackblock();
6735 STPUTC(*idx, expdest);
6736 if (stackblock() != restart_detect)
6745 /* We've put the replaced text into a buffer at workloc, now
6746 * move it to the right place and adjust the stack.
6748 STPUTC('\0', expdest);
6749 startp = (char *)stackblock() + startloc;
6750 memmove(startp, (char *)stackblock() + workloc, len + 1);
6751 //bb_error_msg("startp:'%s'", startp);
6752 amount = expdest - (startp + len);
6753 STADJUST(-amount, expdest);
6756 #endif /* BASH_PATTERN_SUBST */
6758 subtype -= VSTRIMRIGHT;
6760 if (subtype < 0 || subtype > 7)
6763 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6764 zero = subtype >> 1;
6765 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6766 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6768 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6771 memmove(startp, loc, str - loc);
6772 loc = startp + (str - loc) - 1;
6775 amount = loc - expdest;
6776 STADJUST(amount, expdest);
6782 * Add the value of a specialized variable to the stack string.
6783 * name parameter (examples):
6784 * ash -c 'echo $1' name:'1='
6785 * ash -c 'echo $qwe' name:'qwe='
6786 * ash -c 'echo $$' name:'$='
6787 * ash -c 'echo ${$}' name:'$='
6788 * ash -c 'echo ${$##q}' name:'$=q'
6789 * ash -c 'echo ${#$}' name:'$='
6790 * note: examples with bad shell syntax:
6791 * ash -c 'echo ${#$1}' name:'$=1'
6792 * ash -c 'echo ${#1#}' name:'1=#'
6794 static NOINLINE ssize_t
6795 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list, int *quotedp)
6802 int quoted = *quotedp;
6803 int subtype = varflags & VSTYPE;
6804 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6805 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6808 sep = (flags & EXP_FULL) << CHAR_BIT;
6809 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6819 num = shellparam.nparam;
6827 goto check_1char_name;
6829 expdest = makestrspace(NOPTS, expdest);
6830 for (i = NOPTS - 1; i >= 0; i--) {
6832 USTPUTC(optletters(i), expdest);
6838 /* handles cases similar to ${#$1} */
6839 if (name[2] != '\0')
6840 raise_error_syntax("bad substitution");
6853 sep |= ifsset() ? ifsval()[0] : ' ';
6860 while ((p = *ap++) != NULL) {
6861 len += strtodest(p, syntax, quotes);
6865 memtodest(&sepc, 1, syntax, quotes);
6880 num = atoi(name); /* number(name) fails on ${N#str} etc */
6881 if (num < 0 || num > shellparam.nparam)
6883 p = num ? shellparam.p[num - 1] : arg0;
6886 /* NB: name has form "VAR=..." */
6888 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6889 * which should be considered before we check variables. */
6891 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6895 str = var_str_list->text;
6896 eq = strchr(str, '=');
6897 if (!eq) /* stop at first non-assignment */
6900 if (name_len == (unsigned)(eq - str)
6901 && strncmp(str, name, name_len) == 0
6904 /* goto value; - WRONG! */
6905 /* think "A=1 A=2 B=$A" */
6907 var_str_list = var_str_list->next;
6908 } while (var_str_list);
6912 p = lookupvar(name);
6917 len = strtodest(p, syntax, quotes);
6918 #if ENABLE_UNICODE_SUPPORT
6919 if (subtype == VSLENGTH && len > 0) {
6920 reinit_unicode_for_ash();
6921 if (unicode_status == UNICODE_ON) {
6922 STADJUST(-len, expdest);
6924 len = unicode_strlen(p);
6932 STADJUST(-len, expdest);
6937 * Expand a variable, and return a pointer to the next character in the
6941 evalvar(char *p, int flag, struct strlist *var_str_list)
6952 varflags = (unsigned char) *p++;
6953 subtype = varflags & VSTYPE;
6956 raise_error_syntax("bad substitution");
6958 quoted = flag & EXP_QUOTED;
6960 easy = (!quoted || (*var == '@' && shellparam.nparam));
6961 startloc = expdest - (char *)stackblock();
6962 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6965 varlen = varvalue(var, varflags, flag, var_str_list, "ed);
6966 if (varflags & VSNUL)
6969 if (subtype == VSPLUS) {
6970 varlen = -1 - varlen;
6974 if (subtype == VSMINUS) {
6979 flag | EXP_TILDE | EXP_WORD,
6987 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6991 subevalvar(p, var, 0, subtype, startloc, varflags,
6992 flag & ~QUOTES_ESC, var_str_list);
6995 * Remove any recorded regions beyond
6998 removerecordregions(startloc);
7002 if (varlen < 0 && uflag)
7003 varunset(p, var, 0, 0);
7005 if (subtype == VSLENGTH) {
7006 cvtnum(varlen > 0 ? varlen : 0);
7010 if (subtype == VSNORMAL) {
7014 recordregion(startloc, expdest - (char *)stackblock(), quoted);
7023 case VSTRIMRIGHTMAX:
7027 #if BASH_PATTERN_SUBST
7039 * Terminate the string and start recording the pattern
7042 STPUTC('\0', expdest);
7043 patloc = expdest - (char *)stackblock();
7044 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7045 startloc, varflags, flag, var_str_list)) {
7046 int amount = expdest - (
7047 (char *)stackblock() + patloc - 1
7049 STADJUST(-amount, expdest);
7051 /* Remove any recorded regions beyond start of variable */
7052 removerecordregions(startloc);
7057 if (subtype != VSNORMAL) { /* skip to end of alternative */
7060 unsigned char c = *p++;
7063 else if (c == CTLBACKQ) {
7065 argbackq = argbackq->next;
7066 } else if (c == CTLVAR) {
7067 if ((*p++ & VSTYPE) != VSNORMAL)
7069 } else if (c == CTLENDVAR) {
7079 * Add a file name to the list.
7082 addfname(const char *name)
7086 sp = stzalloc(sizeof(*sp));
7087 sp->text = sstrdup(name);
7089 exparg.lastp = &sp->next;
7092 /* If we want to use glob() from libc... */
7093 #if !ENABLE_ASH_INTERNAL_GLOB
7095 /* Add the result of glob() to the list */
7097 addglob(const glob_t *pglob)
7099 char **p = pglob->gl_pathv;
7106 expandmeta(struct strlist *str /*, int flag*/)
7108 /* TODO - EXP_REDIR */
7118 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7133 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7134 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7135 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7137 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7138 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7139 // Which means you need to unescape the string, right? Not so fast:
7140 // if there _is_ a file named "file\?" (with backslash), it is returned
7141 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7142 // You DONT KNOW by looking at the result whether you need to unescape it.
7144 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7145 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7146 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7147 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7148 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7149 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7150 i = glob(p, 0, NULL, &pglob);
7151 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7156 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7157 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7158 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7170 *exparg.lastp = str;
7171 rmescapes(str->text, 0);
7172 exparg.lastp = &str->next;
7174 default: /* GLOB_NOSPACE */
7177 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7184 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7187 * Do metacharacter (i.e. *, ?, [...]) expansion.
7190 expmeta(char *expdir, char *enddir, char *name)
7206 for (p = name; esc = 0, *p; p += esc + 1) {
7207 if (*p == '*' || *p == '?')
7209 else if (*p == '[') {
7216 if (*q == '/' || *q == '\0')
7226 if (p[esc] == '/') {
7229 start = p + esc + 1;
7233 if (metaflag == 0) { /* we've reached the end of the file name */
7234 if (enddir != expdir)
7242 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7253 } while (p < start);
7255 if (enddir == expdir) {
7257 } else if (enddir == expdir + 1 && *expdir == '/') {
7266 if (enddir != expdir)
7268 if (*endname == 0) {
7281 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7282 if (dp->d_name[0] == '.' && !matchdot)
7284 if (pmatch(start, dp->d_name)) {
7286 strcpy(enddir, dp->d_name);
7289 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7292 expmeta(expdir, p, endname);
7298 endname[-esc - 1] = esc ? '\\' : '/';
7301 static struct strlist *
7302 msort(struct strlist *list, int len)
7304 struct strlist *p, *q = NULL;
7305 struct strlist **lpp;
7313 for (n = half; --n >= 0;) {
7317 q->next = NULL; /* terminate first half of list */
7318 q = msort(list, half); /* sort first half of list */
7319 p = msort(p, len - half); /* sort second half */
7322 #if ENABLE_LOCALE_SUPPORT
7323 if (strcoll(p->text, q->text) < 0)
7325 if (strcmp(p->text, q->text) < 0)
7349 * Sort the results of file name expansion. It calculates the number of
7350 * strings to sort and then calls msort (short for merge sort) to do the
7353 static struct strlist *
7354 expsort(struct strlist *str)
7360 for (sp = str; sp; sp = sp->next)
7362 return msort(str, len);
7366 expandmeta(struct strlist *str /*, int flag*/)
7368 static const char metachars[] ALIGN1 = {
7371 /* TODO - EXP_REDIR */
7375 struct strlist **savelastp;
7381 if (!strpbrk(str->text, metachars))
7383 savelastp = exparg.lastp;
7386 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7388 int i = strlen(str->text);
7389 //BUGGY estimation of how long expanded name can be
7390 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7392 expmeta(expdir, expdir, p);
7397 if (exparg.lastp == savelastp) {
7402 *exparg.lastp = str;
7403 rmescapes(str->text, 0);
7404 exparg.lastp = &str->next;
7406 *exparg.lastp = NULL;
7407 *savelastp = sp = expsort(*savelastp);
7408 while (sp->next != NULL)
7410 exparg.lastp = &sp->next;
7415 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7418 * Perform variable substitution and command substitution on an argument,
7419 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7420 * perform splitting and file name expansion. When arglist is NULL, perform
7421 * here document expansion.
7424 expandarg(union node *arg, struct arglist *arglist, int flag)
7429 argbackq = arg->narg.backquote;
7430 STARTSTACKSTR(expdest);
7431 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7432 argstr(arg->narg.text, flag,
7433 /* var_str_list: */ arglist ? arglist->list : NULL);
7434 p = _STPUTC('\0', expdest);
7436 if (arglist == NULL) {
7437 /* here document expanded */
7440 p = grabstackstr(p);
7441 TRACE(("expandarg: p:'%s'\n", p));
7442 exparg.lastp = &exparg.list;
7446 if (flag & EXP_FULL) {
7447 ifsbreakup(p, &exparg);
7448 *exparg.lastp = NULL;
7449 exparg.lastp = &exparg.list;
7450 expandmeta(exparg.list /*, flag*/);
7452 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7454 TRACE(("expandarg: rmescapes:'%s'\n", p));
7456 sp = stzalloc(sizeof(*sp));
7459 exparg.lastp = &sp->next;
7461 *exparg.lastp = NULL;
7463 *arglist->lastp = exparg.list;
7464 arglist->lastp = exparg.lastp;
7472 * Expand shell variables and backquotes inside a here document.
7475 expandhere(union node *arg, int fd)
7477 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7478 full_write(fd, stackblock(), expdest - (char *)stackblock());
7482 * Returns true if the pattern matches the string.
7485 patmatch(char *pattern, const char *string)
7487 return pmatch(preglob(pattern, 0), string);
7491 * See if a pattern matches in a case statement.
7494 casematch(union node *pattern, char *val)
7496 struct stackmark smark;
7499 setstackmark(&smark);
7500 argbackq = pattern->narg.backquote;
7501 STARTSTACKSTR(expdest);
7502 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7503 /* var_str_list: */ NULL);
7504 STACKSTRNUL(expdest);
7506 result = patmatch(stackblock(), val);
7507 popstackmark(&smark);
7512 /* ============ find_command */
7516 int (*builtin)(int, char **) FAST_FUNC;
7517 /* unsigned flags; */
7519 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7520 /* "regular" builtins always take precedence over commands,
7521 * regardless of PATH=....%builtin... position */
7522 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7523 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7526 smallint cmdtype; /* CMDxxx */
7529 /* index >= 0 for commands without path (slashes) */
7530 /* (TODO: what exactly does the value mean? PATH position?) */
7531 /* index == -1 for commands with slashes */
7532 /* index == (-2 - applet_no) for NOFORK applets */
7533 const struct builtincmd *cmd;
7534 struct funcnode *func;
7537 /* values of cmdtype */
7538 #define CMDUNKNOWN -1 /* no entry in table for command */
7539 #define CMDNORMAL 0 /* command is an executable program */
7540 #define CMDFUNCTION 1 /* command is a shell function */
7541 #define CMDBUILTIN 2 /* command is a shell builtin */
7543 /* action to find_command() */
7544 #define DO_ERR 0x01 /* prints errors */
7545 #define DO_ABS 0x02 /* checks absolute paths */
7546 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7547 #define DO_ALTPATH 0x08 /* using alternate path */
7548 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7550 static void find_command(char *, struct cmdentry *, int, const char *);
7553 /* ============ Hashing commands */
7556 * When commands are first encountered, they are entered in a hash table.
7557 * This ensures that a full path search will not have to be done for them
7558 * on each invocation.
7560 * We should investigate converting to a linear search, even though that
7561 * would make the command name "hash" a misnomer.
7565 struct tblentry *next; /* next entry in hash chain */
7566 union param param; /* definition of builtin function */
7567 smallint cmdtype; /* CMDxxx */
7568 char rehash; /* if set, cd done since entry created */
7569 char cmdname[1]; /* name of command */
7572 static struct tblentry **cmdtable;
7573 #define INIT_G_cmdtable() do { \
7574 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7577 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7581 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7583 #if ENABLE_FEATURE_SH_STANDALONE
7584 if (applet_no >= 0) {
7585 if (APPLET_IS_NOEXEC(applet_no)) {
7589 run_applet_no_and_exit(applet_no, argv);
7591 /* re-exec ourselves with the new arguments */
7592 execve(bb_busybox_exec_path, argv, envp);
7593 /* If they called chroot or otherwise made the binary no longer
7594 * executable, fall through */
7601 execve(cmd, argv, envp);
7602 } while (errno == EINTR);
7604 execve(cmd, argv, envp);
7606 if (cmd != (char*) bb_busybox_exec_path && errno == ENOEXEC) {
7607 /* Run "cmd" as a shell script:
7608 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7609 * "If the execve() function fails with ENOEXEC, the shell
7610 * shall execute a command equivalent to having a shell invoked
7611 * with the command name as its first operand,
7612 * with any remaining arguments passed to the new shell"
7614 * That is, do not use $SHELL, user's shell, or /bin/sh;
7615 * just call ourselves.
7617 * Note that bash reads ~80 chars of the file, and if it sees
7618 * a zero byte before it sees newline, it doesn't try to
7619 * interpret it, but fails with "cannot execute binary file"
7620 * message and exit code 126. For one, this prevents attempts
7621 * to interpret foreign ELF binaries as shell scripts.
7624 cmd = (char*) bb_busybox_exec_path;
7625 /* NB: this is only possible because all callers of shellexec()
7626 * ensure that the argv[-1] slot exists!
7629 argv[0] = (char*) "ash";
7635 * Exec a program. Never returns. If you change this routine, you may
7636 * have to change the find_command routine as well.
7637 * argv[-1] must exist and be writable! See tryexec() for why.
7639 static void shellexec(char **, const char *, int) NORETURN;
7641 shellexec(char **argv, const char *path, int idx)
7647 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7649 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7650 if (strchr(argv[0], '/') != NULL
7651 #if ENABLE_FEATURE_SH_STANDALONE
7652 || (applet_no = find_applet_by_name(argv[0])) >= 0
7655 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7656 if (applet_no >= 0) {
7657 /* We tried execing ourself, but it didn't work.
7658 * Maybe /proc/self/exe doesn't exist?
7667 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7668 if (--idx < 0 && pathopt == NULL) {
7669 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7670 if (errno != ENOENT && errno != ENOTDIR)
7677 /* Map to POSIX errors */
7689 exitstatus = exerrno;
7690 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7691 argv[0], e, suppress_int));
7692 ash_msg_and_raise(EXEXIT, "%s: %s", argv[0], errmsg(e, "not found"));
7697 printentry(struct tblentry *cmdp)
7703 idx = cmdp->param.index;
7706 name = path_advance(&path, cmdp->cmdname);
7708 } while (--idx >= 0);
7709 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7713 * Clear out command entries. The argument specifies the first entry in
7714 * PATH which has changed.
7717 clearcmdentry(int firstchange)
7719 struct tblentry **tblp;
7720 struct tblentry **pp;
7721 struct tblentry *cmdp;
7724 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7726 while ((cmdp = *pp) != NULL) {
7727 if ((cmdp->cmdtype == CMDNORMAL &&
7728 cmdp->param.index >= firstchange)
7729 || (cmdp->cmdtype == CMDBUILTIN &&
7730 builtinloc >= firstchange)
7743 * Locate a command in the command hash table. If "add" is nonzero,
7744 * add the command to the table if it is not already present. The
7745 * variable "lastcmdentry" is set to point to the address of the link
7746 * pointing to the entry, so that delete_cmd_entry can delete the
7749 * Interrupts must be off if called with add != 0.
7751 static struct tblentry **lastcmdentry;
7753 static struct tblentry *
7754 cmdlookup(const char *name, int add)
7756 unsigned int hashval;
7758 struct tblentry *cmdp;
7759 struct tblentry **pp;
7762 hashval = (unsigned char)*p << 4;
7764 hashval += (unsigned char)*p++;
7766 pp = &cmdtable[hashval % CMDTABLESIZE];
7767 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7768 if (strcmp(cmdp->cmdname, name) == 0)
7772 if (add && cmdp == NULL) {
7773 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7775 /* + 1 - already done because
7776 * tblentry::cmdname is char[1] */);
7777 /*cmdp->next = NULL; - ckzalloc did it */
7778 cmdp->cmdtype = CMDUNKNOWN;
7779 strcpy(cmdp->cmdname, name);
7786 * Delete the command entry returned on the last lookup.
7789 delete_cmd_entry(void)
7791 struct tblentry *cmdp;
7794 cmdp = *lastcmdentry;
7795 *lastcmdentry = cmdp->next;
7796 if (cmdp->cmdtype == CMDFUNCTION)
7797 freefunc(cmdp->param.func);
7803 * Add a new command entry, replacing any existing command entry for
7804 * the same name - except special builtins.
7807 addcmdentry(char *name, struct cmdentry *entry)
7809 struct tblentry *cmdp;
7811 cmdp = cmdlookup(name, 1);
7812 if (cmdp->cmdtype == CMDFUNCTION) {
7813 freefunc(cmdp->param.func);
7815 cmdp->cmdtype = entry->cmdtype;
7816 cmdp->param = entry->u;
7820 static int FAST_FUNC
7821 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7823 struct tblentry **pp;
7824 struct tblentry *cmdp;
7826 struct cmdentry entry;
7829 if (nextopt("r") != '\0') {
7834 if (*argptr == NULL) {
7835 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7836 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7837 if (cmdp->cmdtype == CMDNORMAL)
7845 while ((name = *argptr) != NULL) {
7846 cmdp = cmdlookup(name, 0);
7848 && (cmdp->cmdtype == CMDNORMAL
7849 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7853 find_command(name, &entry, DO_ERR, pathval());
7854 if (entry.cmdtype == CMDUNKNOWN)
7862 * Called when a cd is done. Marks all commands so the next time they
7863 * are executed they will be rehashed.
7868 struct tblentry **pp;
7869 struct tblentry *cmdp;
7871 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7872 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7873 if (cmdp->cmdtype == CMDNORMAL
7874 || (cmdp->cmdtype == CMDBUILTIN
7875 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7885 * Fix command hash table when PATH changed.
7886 * Called before PATH is changed. The argument is the new value of PATH;
7887 * pathval() still returns the old value at this point.
7888 * Called with interrupts off.
7890 static void FAST_FUNC
7891 changepath(const char *new)
7899 firstchange = 9999; /* assume no change */
7905 if ((*old == '\0' && *new == ':')
7906 || (*old == ':' && *new == '\0')
7910 old = new; /* ignore subsequent differences */
7914 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7921 if (builtinloc < 0 && idx_bltin >= 0)
7922 builtinloc = idx_bltin; /* zap builtins */
7923 if (builtinloc >= 0 && idx_bltin < 0)
7925 clearcmdentry(firstchange);
7926 builtinloc = idx_bltin;
7962 typedef smallint token_id_t;
7964 /* Nth bit indicates if token marks the end of a list */
7967 /* 0 */ | (1u << TEOF)
7968 /* 1 */ | (0u << TNL)
7969 /* 2 */ | (0u << TREDIR)
7970 /* 3 */ | (0u << TWORD)
7971 /* 4 */ | (0u << TSEMI)
7972 /* 5 */ | (0u << TBACKGND)
7973 /* 6 */ | (0u << TAND)
7974 /* 7 */ | (0u << TOR)
7975 /* 8 */ | (0u << TPIPE)
7976 /* 9 */ | (0u << TLP)
7977 /* 10 */ | (1u << TRP)
7978 /* 11 */ | (1u << TENDCASE)
7979 /* 12 */ | (1u << TENDBQUOTE)
7980 /* 13 */ | (0u << TNOT)
7981 /* 14 */ | (0u << TCASE)
7982 /* 15 */ | (1u << TDO)
7983 /* 16 */ | (1u << TDONE)
7984 /* 17 */ | (1u << TELIF)
7985 /* 18 */ | (1u << TELSE)
7986 /* 19 */ | (1u << TESAC)
7987 /* 20 */ | (1u << TFI)
7988 /* 21 */ | (0u << TFOR)
7990 /* 22 */ | (0u << TFUNCTION)
7992 /* 23 */ | (0u << TIF)
7993 /* 24 */ | (0u << TIN)
7994 /* 25 */ | (1u << TTHEN)
7995 /* 26 */ | (0u << TUNTIL)
7996 /* 27 */ | (0u << TWHILE)
7997 /* 28 */ | (0u << TBEGIN)
7998 /* 29 */ | (1u << TEND)
7999 , /* thus far 29 bits used */
8002 static const char *const tokname_array[] = {
8016 #define KWDOFFSET 13
8017 /* the following are keywords */
8039 /* Wrapper around strcmp for qsort/bsearch/... */
8041 pstrcmp(const void *a, const void *b)
8043 return strcmp((char*)a, *(char**)b);
8046 static const char *const *
8047 findkwd(const char *s)
8049 return bsearch(s, tokname_array + KWDOFFSET,
8050 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8051 sizeof(tokname_array[0]), pstrcmp);
8055 * Locate and print what a word is...
8058 describe_command(char *command, const char *path, int describe_command_verbose)
8060 struct cmdentry entry;
8061 struct tblentry *cmdp;
8062 #if ENABLE_ASH_ALIAS
8063 const struct alias *ap;
8066 path = path ? path : pathval();
8068 if (describe_command_verbose) {
8072 /* First look at the keywords */
8073 if (findkwd(command)) {
8074 out1str(describe_command_verbose ? " is a shell keyword" : command);
8078 #if ENABLE_ASH_ALIAS
8079 /* Then look at the aliases */
8080 ap = lookupalias(command, 0);
8082 if (!describe_command_verbose) {
8087 out1fmt(" is an alias for %s", ap->val);
8091 /* Then check if it is a tracked alias */
8092 cmdp = cmdlookup(command, 0);
8094 entry.cmdtype = cmdp->cmdtype;
8095 entry.u = cmdp->param;
8097 /* Finally use brute force */
8098 find_command(command, &entry, DO_ABS, path);
8101 switch (entry.cmdtype) {
8103 int j = entry.u.index;
8109 p = path_advance(&path, command);
8113 if (describe_command_verbose) {
8115 (cmdp ? " a tracked alias for" : nullstr), p
8124 if (describe_command_verbose) {
8125 out1str(" is a shell function");
8132 if (describe_command_verbose) {
8133 out1fmt(" is a %sshell builtin",
8134 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8135 "special " : nullstr
8143 if (describe_command_verbose) {
8144 out1str(": not found\n");
8153 static int FAST_FUNC
8154 typecmd(int argc UNUSED_PARAM, char **argv)
8160 /* type -p ... ? (we don't bother checking for 'p') */
8161 if (argv[1] && argv[1][0] == '-') {
8166 err |= describe_command(argv[i++], NULL, verbose);
8171 #if ENABLE_ASH_CMDCMD
8172 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8174 parse_command_args(char **argv, const char **path)
8187 if (c == '-' && !*cp) {
8195 *path = bb_default_path;
8198 /* run 'typecmd' for other options */
8207 static int FAST_FUNC
8208 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8216 const char *path = NULL;
8218 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8219 * never reaches this function.
8222 while ((c = nextopt("pvV")) != '\0')
8224 verify |= VERIFY_VERBOSE;
8226 /*verify |= VERIFY_BRIEF*/;
8232 path = bb_default_path;
8234 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8236 if (/*verify && */ cmd)
8237 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8244 /*static int funcblocksize; // size of structures in function */
8245 /*static int funcstringsize; // size of strings in node */
8246 static void *funcblock; /* block to allocate function from */
8247 static char *funcstring_end; /* end of block to allocate strings from */
8249 /* flags in argument to evaltree */
8250 #define EV_EXIT 01 /* exit after evaluating tree */
8251 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8253 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8254 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8255 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8256 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8257 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8258 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8259 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8260 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8261 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8262 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8263 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8264 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8265 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8266 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8267 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8268 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8269 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8270 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8271 #if BASH_REDIR_OUTPUT
8272 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8274 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8275 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8276 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8277 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8278 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8279 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8280 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8281 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8282 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8285 static int calcsize(int funcblocksize, union node *n);
8288 sizenodelist(int funcblocksize, struct nodelist *lp)
8291 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8292 funcblocksize = calcsize(funcblocksize, lp->n);
8295 return funcblocksize;
8299 calcsize(int funcblocksize, union node *n)
8302 return funcblocksize;
8303 funcblocksize += nodesize[n->type];
8306 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8307 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8308 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8311 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8316 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8317 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8324 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8325 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8328 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8329 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8330 funcblocksize = calcsize(funcblocksize, n->nif.test);
8333 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8334 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8335 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8338 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8339 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8342 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8343 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8344 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8348 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8349 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8350 funcblocksize = calcsize(funcblocksize, n->narg.next);
8353 #if BASH_REDIR_OUTPUT
8360 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8361 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8365 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8366 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8370 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8371 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8374 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8377 return funcblocksize;
8381 nodeckstrdup(char *s)
8383 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8384 return strcpy(funcstring_end, s);
8387 static union node *copynode(union node *);
8389 static struct nodelist *
8390 copynodelist(struct nodelist *lp)
8392 struct nodelist *start;
8393 struct nodelist **lpp;
8398 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8399 (*lpp)->n = copynode(lp->n);
8401 lpp = &(*lpp)->next;
8408 copynode(union node *n)
8415 funcblock = (char *) funcblock + nodesize[n->type];
8419 new->ncmd.redirect = copynode(n->ncmd.redirect);
8420 new->ncmd.args = copynode(n->ncmd.args);
8421 new->ncmd.assign = copynode(n->ncmd.assign);
8424 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8425 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8430 new->nredir.redirect = copynode(n->nredir.redirect);
8431 new->nredir.n = copynode(n->nredir.n);
8438 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8439 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8442 new->nif.elsepart = copynode(n->nif.elsepart);
8443 new->nif.ifpart = copynode(n->nif.ifpart);
8444 new->nif.test = copynode(n->nif.test);
8447 new->nfor.var = nodeckstrdup(n->nfor.var);
8448 new->nfor.body = copynode(n->nfor.body);
8449 new->nfor.args = copynode(n->nfor.args);
8452 new->ncase.cases = copynode(n->ncase.cases);
8453 new->ncase.expr = copynode(n->ncase.expr);
8456 new->nclist.body = copynode(n->nclist.body);
8457 new->nclist.pattern = copynode(n->nclist.pattern);
8458 new->nclist.next = copynode(n->nclist.next);
8462 new->narg.backquote = copynodelist(n->narg.backquote);
8463 new->narg.text = nodeckstrdup(n->narg.text);
8464 new->narg.next = copynode(n->narg.next);
8467 #if BASH_REDIR_OUTPUT
8474 new->nfile.fname = copynode(n->nfile.fname);
8475 new->nfile.fd = n->nfile.fd;
8476 new->nfile.next = copynode(n->nfile.next);
8480 new->ndup.vname = copynode(n->ndup.vname);
8481 new->ndup.dupfd = n->ndup.dupfd;
8482 new->ndup.fd = n->ndup.fd;
8483 new->ndup.next = copynode(n->ndup.next);
8487 new->nhere.doc = copynode(n->nhere.doc);
8488 new->nhere.fd = n->nhere.fd;
8489 new->nhere.next = copynode(n->nhere.next);
8492 new->nnot.com = copynode(n->nnot.com);
8495 new->type = n->type;
8500 * Make a copy of a parse tree.
8502 static struct funcnode *
8503 copyfunc(union node *n)
8508 /*funcstringsize = 0;*/
8509 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8510 f = ckzalloc(blocksize /* + funcstringsize */);
8511 funcblock = (char *) f + offsetof(struct funcnode, n);
8512 funcstring_end = (char *) f + blocksize;
8514 /* f->count = 0; - ckzalloc did it */
8519 * Define a shell function.
8522 defun(union node *func)
8524 struct cmdentry entry;
8527 entry.cmdtype = CMDFUNCTION;
8528 entry.u.func = copyfunc(func);
8529 addcmdentry(func->narg.text, &entry);
8533 /* Reasons for skipping commands (see comment on breakcmd routine) */
8534 #define SKIPBREAK (1 << 0)
8535 #define SKIPCONT (1 << 1)
8536 #define SKIPFUNC (1 << 2)
8537 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8538 static int skipcount; /* number of levels to skip */
8539 static int funcnest; /* depth of function calls */
8540 static int loopnest; /* current loop nesting level */
8542 /* Forward decl way out to parsing code - dotrap needs it */
8543 static int evalstring(char *s, int flags);
8545 /* Called to execute a trap.
8546 * Single callsite - at the end of evaltree().
8547 * If we return non-zero, evaltree raises EXEXIT exception.
8549 * Perhaps we should avoid entering new trap handlers
8550 * while we are executing a trap handler. [is it a TODO?]
8557 uint8_t last_status;
8562 last_status = exitstatus;
8566 TRACE(("dotrap entered\n"));
8567 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8579 /* non-trapped SIGINT is handled separately by raise_interrupt,
8580 * don't upset it by resetting gotsig[SIGINT-1] */
8581 if (sig == SIGINT && !p)
8584 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8590 exitstatus = last_status;
8591 TRACE(("dotrap returns\n"));
8594 /* forward declarations - evaluation is fairly recursive business... */
8595 static int evalloop(union node *, int);
8596 static int evalfor(union node *, int);
8597 static int evalcase(union node *, int);
8598 static int evalsubshell(union node *, int);
8599 static void expredir(union node *);
8600 static int evalpipe(union node *, int);
8601 static int evalcommand(union node *, int);
8602 static int evalbltin(const struct builtincmd *, int, char **, int);
8603 static void prehash(union node *);
8606 * Evaluate a parse tree. The value is left in the global variable
8610 evaltree(union node *n, int flags)
8613 int (*evalfn)(union node *, int);
8617 TRACE(("evaltree(NULL) called\n"));
8620 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8627 out1fmt("Node type = %d\n", n->type);
8632 status = !evaltree(n->nnot.com, EV_TESTED);
8635 expredir(n->nredir.redirect);
8636 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8638 status = evaltree(n->nredir.n, flags & EV_TESTED);
8640 if (n->nredir.redirect)
8641 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8644 evalfn = evalcommand;
8646 if (eflag && !(flags & EV_TESTED))
8658 evalfn = evalsubshell;
8671 #error NAND + 1 != NOR
8673 #if NOR + 1 != NSEMI
8674 #error NOR + 1 != NSEMI
8676 unsigned is_or = n->type - NAND;
8679 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8681 if ((!status) == is_or || evalskip)
8687 status = evalfn(n, flags);
8691 status = evaltree(n->nif.test, EV_TESTED);
8698 if (n->nif.elsepart) {
8699 n = n->nif.elsepart;
8706 /* Not necessary. To test it:
8707 * "false; f() { qwerty; }; echo $?" should print 0.
8711 exitstatus = status;
8715 /* Order of checks below is important:
8716 * signal handlers trigger before exit caused by "set -e".
8720 if (checkexit & status)
8721 raise_exception(EXEXIT);
8722 if (flags & EV_EXIT)
8723 raise_exception(EXEXIT);
8725 TRACE(("leaving evaltree (no interrupts)\n"));
8729 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8732 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8737 int skip = evalskip;
8744 if (--skipcount <= 0) {
8755 evalloop(union node *n, int flags)
8766 i = evaltree(n->nbinary.ch1, EV_TESTED);
8768 if (skip == SKIPFUNC)
8772 if (n->type != NWHILE)
8776 status = evaltree(n->nbinary.ch2, flags);
8778 } while (!(skip & ~SKIPCONT));
8785 evalfor(union node *n, int flags)
8787 struct arglist arglist;
8790 struct stackmark smark;
8793 setstackmark(&smark);
8794 arglist.list = NULL;
8795 arglist.lastp = &arglist.list;
8796 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8797 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8799 *arglist.lastp = NULL;
8803 for (sp = arglist.list; sp; sp = sp->next) {
8804 setvar0(n->nfor.var, sp->text);
8805 status = evaltree(n->nfor.body, flags);
8806 if (skiploop() & ~SKIPCONT)
8810 popstackmark(&smark);
8816 evalcase(union node *n, int flags)
8820 struct arglist arglist;
8821 struct stackmark smark;
8824 setstackmark(&smark);
8825 arglist.list = NULL;
8826 arglist.lastp = &arglist.list;
8827 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8828 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8829 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8830 if (casematch(patp, arglist.list->text)) {
8831 /* Ensure body is non-empty as otherwise
8832 * EV_EXIT may prevent us from setting the
8835 if (evalskip == 0 && cp->nclist.body) {
8836 status = evaltree(cp->nclist.body, flags);
8843 popstackmark(&smark);
8849 * Kick off a subshell to evaluate a tree.
8852 evalsubshell(union node *n, int flags)
8855 int backgnd = (n->type == NBACKGND);
8858 expredir(n->nredir.redirect);
8859 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8862 jp = makejob(/*n,*/ 1);
8863 if (forkshell(jp, n, backgnd) == 0) {
8868 flags &= ~EV_TESTED;
8870 redirect(n->nredir.redirect, 0);
8871 evaltreenr(n->nredir.n, flags);
8877 status = waitforjob(jp);
8883 * Compute the names of the files in a redirection list.
8885 static void fixredir(union node *, const char *, int);
8887 expredir(union node *n)
8891 for (redir = n; redir; redir = redir->nfile.next) {
8895 fn.lastp = &fn.list;
8896 switch (redir->type) {
8900 #if BASH_REDIR_OUTPUT
8905 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8906 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8907 #if BASH_REDIR_OUTPUT
8911 // By the design of stack allocator, the loop of this kind:
8912 // while true; do while true; do break; done </dev/null; done
8913 // will look like a memory leak: ash plans to free expfname's
8914 // of "/dev/null" as soon as it finishes running the loop
8915 // (in this case, never).
8916 // This "fix" is wrong:
8917 if (redir->nfile.expfname)
8918 stunalloc(redir->nfile.expfname);
8919 // It results in corrupted state of stacked allocations.
8921 redir->nfile.expfname = fn.list->text;
8924 case NTOFD: /* >& */
8925 if (redir->ndup.vname) {
8926 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8927 if (fn.list == NULL)
8928 ash_msg_and_raise_error("redir error");
8929 #if BASH_REDIR_OUTPUT
8930 //FIXME: we used expandarg with different args!
8931 if (!isdigit_str9(fn.list->text)) {
8932 /* >&file, not >&fd */
8933 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8934 ash_msg_and_raise_error("redir error");
8936 goto store_expfname;
8939 fixredir(redir, fn.list->text, 1);
8947 * Evaluate a pipeline. All the processes in the pipeline are children
8948 * of the process creating the pipeline. (This differs from some versions
8949 * of the shell, which make the last process in a pipeline the parent
8953 evalpipe(union node *n, int flags)
8956 struct nodelist *lp;
8962 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8964 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8968 jp = makejob(/*n,*/ pipelen);
8970 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8974 if (pipe(pip) < 0) {
8976 ash_msg_and_raise_error("pipe call failed");
8979 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8993 evaltreenr(lp->n, flags);
9000 /* Don't want to trigger debugging */
9004 if (n->npipe.pipe_backgnd == 0) {
9005 status = waitforjob(jp);
9006 TRACE(("evalpipe: job done exit status %d\n", status));
9014 * Controls whether the shell is interactive or not.
9017 setinteractive(int on)
9019 static smallint is_interactive;
9021 if (++on == is_interactive)
9023 is_interactive = on;
9027 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9028 if (is_interactive > 1) {
9029 /* Looks like they want an interactive shell */
9030 static smallint did_banner;
9033 /* note: ash and hush share this string */
9034 out1fmt("\n\n%s %s\n"
9035 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9038 "built-in shell (ash)"
9052 setinteractive(iflag);
9054 #if ENABLE_FEATURE_EDITING_VI
9056 line_input_state->flags |= VI_MODE;
9058 line_input_state->flags &= ~VI_MODE;
9060 viflag = 0; /* forcibly keep the option off */
9064 static struct localvar *localvars;
9067 * Called after a function returns.
9068 * Interrupts must be off.
9073 struct localvar *lvp;
9076 while ((lvp = localvars) != NULL) {
9077 localvars = lvp->next;
9079 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9080 if (vp == NULL) { /* $- saved */
9081 memcpy(optlist, lvp->text, sizeof(optlist));
9082 free((char*)lvp->text);
9084 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
9085 unsetvar(vp->var_text);
9088 vp->var_func(var_end(lvp->text));
9089 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9090 free((char*)vp->var_text);
9091 vp->flags = lvp->flags;
9092 vp->var_text = lvp->text;
9099 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9101 volatile struct shparam saveparam;
9102 struct localvar *volatile savelocalvars;
9103 struct jmploc *volatile savehandler;
9104 struct jmploc jmploc;
9107 saveparam = shellparam;
9108 savelocalvars = localvars;
9109 savehandler = exception_handler;
9110 e = setjmp(jmploc.loc);
9115 exception_handler = &jmploc;
9117 shellparam.malloced = 0;
9121 shellparam.nparam = argc - 1;
9122 shellparam.p = argv + 1;
9123 #if ENABLE_ASH_GETOPTS
9124 shellparam.optind = 1;
9125 shellparam.optoff = -1;
9127 evaltree(func->n.narg.next, flags & EV_TESTED);
9133 localvars = savelocalvars;
9134 freeparam(&shellparam);
9135 shellparam = saveparam;
9136 exception_handler = savehandler;
9138 evalskip &= ~SKIPFUNC;
9143 * Make a variable a local variable. When a variable is made local, it's
9144 * value and flags are saved in a localvar structure. The saved values
9145 * will be restored when the shell function returns. We handle the name
9146 * "-" as a special case: it makes changes to "set +-options" local
9147 * (options will be restored on return from the function).
9152 struct localvar *lvp;
9155 char *eq = strchr(name, '=');
9158 /* Cater for duplicate "local". Examples:
9159 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9160 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9164 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9168 * it's a duplicate "local VAR" declaration, do nothing
9175 lvp = ckzalloc(sizeof(*lvp));
9176 if (LONE_DASH(name)) {
9178 p = ckmalloc(sizeof(optlist));
9179 lvp->text = memcpy(p, optlist, sizeof(optlist));
9182 vpp = hashvar(name);
9183 vp = *findvar(vpp, name);
9185 /* variable did not exist yet */
9187 setvareq(name, VSTRFIXED);
9189 setvar(name, NULL, VSTRFIXED);
9190 vp = *vpp; /* the new variable */
9191 lvp->flags = VUNSET;
9193 lvp->text = vp->var_text;
9194 lvp->flags = vp->flags;
9195 /* make sure neither "struct var" nor string gets freed
9196 * during (un)setting:
9198 vp->flags |= VSTRFIXED|VTEXTFIXED;
9202 /* "local VAR" unsets VAR: */
9203 setvar0(name, NULL);
9207 lvp->next = localvars;
9214 * The "local" command.
9216 static int FAST_FUNC
9217 localcmd(int argc UNUSED_PARAM, char **argv)
9222 ash_msg_and_raise_error("not in a function");
9225 while ((name = *argv++) != NULL) {
9231 static int FAST_FUNC
9232 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9237 static int FAST_FUNC
9238 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9243 static int FAST_FUNC
9244 execcmd(int argc UNUSED_PARAM, char **argv)
9247 iflag = 0; /* exit on error */
9250 /* We should set up signals for "exec CMD"
9251 * the same way as for "CMD" without "exec".
9252 * But optschanged->setinteractive->setsignal
9253 * still thought we are a root shell. Therefore, for example,
9254 * SIGQUIT is still set to IGN. Fix it:
9258 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9259 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9260 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9262 shellexec(argv + 1, pathval(), 0);
9269 * The return command.
9271 static int FAST_FUNC
9272 returncmd(int argc UNUSED_PARAM, char **argv)
9275 * If called outside a function, do what ksh does;
9276 * skip the rest of the file.
9278 evalskip = SKIPFUNC;
9279 return argv[1] ? number(argv[1]) : exitstatus;
9282 /* Forward declarations for builtintab[] */
9283 static int breakcmd(int, char **) FAST_FUNC;
9284 static int dotcmd(int, char **) FAST_FUNC;
9285 static int evalcmd(int, char **, int) FAST_FUNC;
9286 static int exitcmd(int, char **) FAST_FUNC;
9287 static int exportcmd(int, char **) FAST_FUNC;
9288 #if ENABLE_ASH_GETOPTS
9289 static int getoptscmd(int, char **) FAST_FUNC;
9292 static int helpcmd(int, char **) FAST_FUNC;
9295 static int historycmd(int, char **) FAST_FUNC;
9297 #if ENABLE_FEATURE_SH_MATH
9298 static int letcmd(int, char **) FAST_FUNC;
9300 static int readcmd(int, char **) FAST_FUNC;
9301 static int setcmd(int, char **) FAST_FUNC;
9302 static int shiftcmd(int, char **) FAST_FUNC;
9303 static int timescmd(int, char **) FAST_FUNC;
9304 static int trapcmd(int, char **) FAST_FUNC;
9305 static int umaskcmd(int, char **) FAST_FUNC;
9306 static int unsetcmd(int, char **) FAST_FUNC;
9307 static int ulimitcmd(int, char **) FAST_FUNC;
9309 #define BUILTIN_NOSPEC "0"
9310 #define BUILTIN_SPECIAL "1"
9311 #define BUILTIN_REGULAR "2"
9312 #define BUILTIN_SPEC_REG "3"
9313 #define BUILTIN_ASSIGN "4"
9314 #define BUILTIN_SPEC_ASSG "5"
9315 #define BUILTIN_REG_ASSG "6"
9316 #define BUILTIN_SPEC_REG_ASSG "7"
9318 /* Stubs for calling non-FAST_FUNC's */
9320 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9322 #if ENABLE_ASH_PRINTF
9323 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9325 #if ENABLE_ASH_TEST || BASH_TEST2
9326 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9329 /* Keep these in proper order since it is searched via bsearch() */
9330 static const struct builtincmd builtintab[] = {
9331 { BUILTIN_SPEC_REG "." , dotcmd },
9332 { BUILTIN_SPEC_REG ":" , truecmd },
9334 { BUILTIN_REGULAR "[" , testcmd },
9337 { BUILTIN_REGULAR "[[" , testcmd },
9339 #if ENABLE_ASH_ALIAS
9340 { BUILTIN_REG_ASSG "alias" , aliascmd },
9343 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9345 { BUILTIN_SPEC_REG "break" , breakcmd },
9346 { BUILTIN_REGULAR "cd" , cdcmd },
9347 { BUILTIN_NOSPEC "chdir" , cdcmd },
9348 #if ENABLE_ASH_CMDCMD
9349 { BUILTIN_REGULAR "command" , commandcmd },
9351 { BUILTIN_SPEC_REG "continue", breakcmd },
9353 { BUILTIN_REGULAR "echo" , echocmd },
9355 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9356 { BUILTIN_SPEC_REG "exec" , execcmd },
9357 { BUILTIN_SPEC_REG "exit" , exitcmd },
9358 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9359 { BUILTIN_REGULAR "false" , falsecmd },
9361 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9363 #if ENABLE_ASH_GETOPTS
9364 { BUILTIN_REGULAR "getopts" , getoptscmd },
9366 { BUILTIN_NOSPEC "hash" , hashcmd },
9368 { BUILTIN_NOSPEC "help" , helpcmd },
9371 { BUILTIN_NOSPEC "history" , historycmd },
9374 { BUILTIN_REGULAR "jobs" , jobscmd },
9375 { BUILTIN_REGULAR "kill" , killcmd },
9377 #if ENABLE_FEATURE_SH_MATH
9378 { BUILTIN_NOSPEC "let" , letcmd },
9380 { BUILTIN_ASSIGN "local" , localcmd },
9381 #if ENABLE_ASH_PRINTF
9382 { BUILTIN_REGULAR "printf" , printfcmd },
9384 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9385 { BUILTIN_REGULAR "read" , readcmd },
9386 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9387 { BUILTIN_SPEC_REG "return" , returncmd },
9388 { BUILTIN_SPEC_REG "set" , setcmd },
9389 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9391 { BUILTIN_SPEC_REG "source" , dotcmd },
9394 { BUILTIN_REGULAR "test" , testcmd },
9396 { BUILTIN_SPEC_REG "times" , timescmd },
9397 { BUILTIN_SPEC_REG "trap" , trapcmd },
9398 { BUILTIN_REGULAR "true" , truecmd },
9399 { BUILTIN_NOSPEC "type" , typecmd },
9400 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9401 { BUILTIN_REGULAR "umask" , umaskcmd },
9402 #if ENABLE_ASH_ALIAS
9403 { BUILTIN_REGULAR "unalias" , unaliascmd },
9405 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9406 { BUILTIN_REGULAR "wait" , waitcmd },
9409 /* Should match the above table! */
9410 #define COMMANDCMD (builtintab + \
9412 /* [ */ 1 * ENABLE_ASH_TEST + \
9413 /* [[ */ 1 * BASH_TEST2 + \
9414 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9415 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9416 /* break cd cddir */ 3)
9417 #define EVALCMD (COMMANDCMD + \
9418 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9419 /* continue */ 1 + \
9420 /* echo */ 1 * ENABLE_ASH_ECHO + \
9422 #define EXECCMD (EVALCMD + \
9426 * Search the table of builtin commands.
9429 pstrcmp1(const void *a, const void *b)
9431 return strcmp((char*)a, *(char**)b + 1);
9433 static struct builtincmd *
9434 find_builtin(const char *name)
9436 struct builtincmd *bp;
9439 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9446 * Execute a simple command.
9449 isassignment(const char *p)
9451 const char *q = endofname(p);
9456 static int FAST_FUNC
9457 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9459 /* Preserve exitstatus of a previous possible redirection
9460 * as POSIX mandates */
9461 return back_exitstatus;
9464 evalcommand(union node *cmd, int flags)
9466 static const struct builtincmd null_bltin = {
9467 "\0\0", bltincmd /* why three NULs? */
9469 struct stackmark smark;
9471 struct arglist arglist;
9472 struct arglist varlist;
9475 const struct strlist *sp;
9476 struct cmdentry cmdentry;
9483 struct builtincmd *bcmd;
9484 smallint cmd_is_exec;
9485 smallint pseudovarflag = 0;
9487 /* First expand the arguments. */
9488 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9489 setstackmark(&smark);
9490 back_exitstatus = 0;
9492 cmdentry.cmdtype = CMDBUILTIN;
9493 cmdentry.u.cmd = &null_bltin;
9494 varlist.lastp = &varlist.list;
9495 *varlist.lastp = NULL;
9496 arglist.lastp = &arglist.list;
9497 *arglist.lastp = NULL;
9500 if (cmd->ncmd.args) {
9501 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9502 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9505 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9506 struct strlist **spp;
9508 spp = arglist.lastp;
9509 if (pseudovarflag && isassignment(argp->narg.text))
9510 expandarg(argp, &arglist, EXP_VARTILDE);
9512 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9514 for (sp = *spp; sp; sp = sp->next)
9518 /* Reserve one extra spot at the front for shellexec. */
9519 nargv = stalloc(sizeof(char *) * (argc + 2));
9521 for (sp = arglist.list; sp; sp = sp->next) {
9522 TRACE(("evalcommand arg: %s\n", sp->text));
9523 *nargv++ = sp->text;
9528 if (iflag && funcnest == 0 && argc > 0)
9529 lastarg = nargv[-1];
9532 expredir(cmd->ncmd.redirect);
9533 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9535 path = vpath.var_text;
9536 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9537 struct strlist **spp;
9540 spp = varlist.lastp;
9541 expandarg(argp, &varlist, EXP_VARTILDE);
9544 * Modify the command lookup path, if a PATH= assignment
9548 if (varcmp(p, path) == 0)
9552 /* Print the command if xflag is set. */
9555 const char *p = " %s" + 1;
9557 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9559 for (n = 0; n < 2; n++) {
9561 fdprintf(preverrout_fd, p, sp->text);
9567 safe_write(preverrout_fd, "\n", 1);
9573 /* Now locate the command. */
9575 int cmd_flag = DO_ERR;
9576 #if ENABLE_ASH_CMDCMD
9577 const char *oldpath = path + 5;
9581 find_command(argv[0], &cmdentry, cmd_flag, path);
9582 if (cmdentry.cmdtype == CMDUNKNOWN) {
9583 flush_stdout_stderr();
9588 /* implement bltin and command here */
9589 if (cmdentry.cmdtype != CMDBUILTIN)
9592 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9593 if (cmdentry.u.cmd == EXECCMD)
9595 #if ENABLE_ASH_CMDCMD
9596 if (cmdentry.u.cmd == COMMANDCMD) {
9598 nargv = parse_command_args(argv, &path);
9601 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9602 * nargv => "PROG". path is updated if -p.
9604 argc -= nargv - argv;
9606 cmd_flag |= DO_NOFUNC;
9615 exitstatus = status;
9617 /* We have a redirection error. */
9619 raise_exception(EXERROR);
9624 /* Execute the command. */
9625 switch (cmdentry.cmdtype) {
9628 #if ENABLE_FEATURE_SH_NOFORK
9629 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9630 * around run_nofork_applet() call.
9631 * (2) Should this check also be done in forkshell()?
9632 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9634 /* find_command() encodes applet_no as (-2 - applet_no) */
9635 int applet_no = (- cmdentry.u.index - 2);
9636 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9637 listsetvar(varlist.list, VEXPORT|VSTACK);
9638 /* run <applet>_main() */
9639 status = run_nofork_applet(applet_no, argv);
9643 /* Can we avoid forking off? For example, very last command
9644 * in a script or a subshell does not need forking,
9645 * we can just exec it.
9647 if (!(flags & EV_EXIT) || may_have_traps) {
9648 /* No, forking off a child is necessary */
9650 jp = makejob(/*cmd,*/ 1);
9651 if (forkshell(jp, cmd, FORK_FG) != 0) {
9653 status = waitforjob(jp);
9655 TRACE(("forked child exited with %d\n", status));
9660 /* fall through to exec'ing external program */
9662 listsetvar(varlist.list, VEXPORT|VSTACK);
9663 shellexec(argv, path, cmdentry.u.index);
9667 cmdenviron = varlist.list;
9669 struct strlist *list = cmdenviron;
9671 if (spclbltin > 0 || argc == 0) {
9673 if (cmd_is_exec && argc > 1)
9676 listsetvar(list, i);
9678 /* Tight loop with builtins only:
9679 * "while kill -0 $child; do true; done"
9680 * will never exit even if $child died, unless we do this
9681 * to reap the zombie and make kill detect that it's gone: */
9682 dowait(DOWAIT_NONBLOCK, NULL);
9684 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9685 if (exception_type == EXERROR && spclbltin <= 0) {
9690 longjmp(exception_handler->loc, 1);
9695 listsetvar(varlist.list, 0);
9696 /* See above for the rationale */
9697 dowait(DOWAIT_NONBLOCK, NULL);
9698 if (evalfun(cmdentry.u.func, argc, argv, flags))
9701 status = exitstatus;
9706 if (cmd->ncmd.redirect)
9707 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9709 /* dsl: I think this is intended to be used to support
9710 * '_' in 'vi' command mode during line editing...
9711 * However I implemented that within libedit itself.
9713 setvar0("_", lastarg);
9715 popstackmark(&smark);
9721 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9723 char *volatile savecmdname;
9724 struct jmploc *volatile savehandler;
9725 struct jmploc jmploc;
9729 savecmdname = commandname;
9730 savehandler = exception_handler;
9731 i = setjmp(jmploc.loc);
9734 exception_handler = &jmploc;
9735 commandname = argv[0];
9737 optptr = NULL; /* initialize nextopt */
9739 status = evalcmd(argc, argv, flags);
9741 status = (*cmd->builtin)(argc, argv);
9742 flush_stdout_stderr();
9743 status |= ferror(stdout);
9744 exitstatus = status;
9747 commandname = savecmdname;
9748 exception_handler = savehandler;
9754 goodname(const char *p)
9756 return endofname(p)[0] == '\0';
9761 * Search for a command. This is called before we fork so that the
9762 * location of the command will be available in the parent as well as
9763 * the child. The check for "goodname" is an overly conservative
9764 * check that the name will not be subject to expansion.
9767 prehash(union node *n)
9769 struct cmdentry entry;
9771 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9772 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9776 /* ============ Builtin commands
9778 * Builtin commands whose functions are closely tied to evaluation
9779 * are implemented here.
9783 * Handle break and continue commands. Break, continue, and return are
9784 * all handled by setting the evalskip flag. The evaluation routines
9785 * above all check this flag, and if it is set they start skipping
9786 * commands rather than executing them. The variable skipcount is
9787 * the number of loops to break/continue, or the number of function
9788 * levels to return. (The latter is always 1.) It should probably
9789 * be an error to break out of more loops than exist, but it isn't
9790 * in the standard shell so we don't make it one here.
9792 static int FAST_FUNC
9793 breakcmd(int argc UNUSED_PARAM, char **argv)
9795 int n = argv[1] ? number(argv[1]) : 1;
9798 ash_msg_and_raise_error(msg_illnum, argv[1]);
9802 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9810 * This implements the input routines used by the parser.
9814 INPUT_PUSH_FILE = 1,
9815 INPUT_NOFILE_OK = 2,
9818 static smallint checkkwd;
9819 /* values of checkkwd variable */
9820 #define CHKALIAS 0x1
9825 * Push a string back onto the input at this current parsefile level.
9826 * We handle aliases this way.
9828 #if !ENABLE_ASH_ALIAS
9829 #define pushstring(s, ap) pushstring(s)
9832 pushstring(char *s, struct alias *ap)
9839 if (g_parsefile->strpush) {
9840 sp = ckzalloc(sizeof(*sp));
9841 sp->prev = g_parsefile->strpush;
9843 sp = &(g_parsefile->basestrpush);
9845 g_parsefile->strpush = sp;
9846 sp->prev_string = g_parsefile->next_to_pgetc;
9847 sp->prev_left_in_line = g_parsefile->left_in_line;
9848 sp->unget = g_parsefile->unget;
9849 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9850 #if ENABLE_ASH_ALIAS
9853 ap->flag |= ALIASINUSE;
9857 g_parsefile->next_to_pgetc = s;
9858 g_parsefile->left_in_line = len;
9859 g_parsefile->unget = 0;
9866 struct strpush *sp = g_parsefile->strpush;
9869 #if ENABLE_ASH_ALIAS
9871 if (g_parsefile->next_to_pgetc[-1] == ' '
9872 || g_parsefile->next_to_pgetc[-1] == '\t'
9874 checkkwd |= CHKALIAS;
9876 if (sp->string != sp->ap->val) {
9879 sp->ap->flag &= ~ALIASINUSE;
9880 if (sp->ap->flag & ALIASDEAD) {
9881 unalias(sp->ap->name);
9885 g_parsefile->next_to_pgetc = sp->prev_string;
9886 g_parsefile->left_in_line = sp->prev_left_in_line;
9887 g_parsefile->unget = sp->unget;
9888 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
9889 g_parsefile->strpush = sp->prev;
9890 if (sp != &(g_parsefile->basestrpush))
9899 char *buf = g_parsefile->buf;
9901 g_parsefile->next_to_pgetc = buf;
9902 #if ENABLE_FEATURE_EDITING
9904 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9905 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9908 # if ENABLE_ASH_IDLE_TIMEOUT
9910 const char *tmout_var = lookupvar("TMOUT");
9912 timeout = atoi(tmout_var) * 1000;
9918 # if ENABLE_FEATURE_TAB_COMPLETION
9919 line_input_state->path_lookup = pathval();
9921 reinit_unicode_for_ash();
9922 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9924 /* ^C pressed, "convert" to SIGINT */
9925 write(STDOUT_FILENO, "^C", 2);
9932 exitstatus = 128 + SIGINT;
9938 /* Ctrl+D pressed */
9941 # if ENABLE_ASH_IDLE_TIMEOUT
9942 else if (errno == EAGAIN && timeout > 0) {
9943 puts("\007timed out waiting for input: auto-logout");
9950 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9953 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9955 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9956 int flags = fcntl(0, F_GETFL);
9957 if (flags >= 0 && (flags & O_NONBLOCK)) {
9958 flags &= ~O_NONBLOCK;
9959 if (fcntl(0, F_SETFL, flags) >= 0) {
9960 out2str("sh: turning off NDELAY mode\n");
9971 * Refill the input buffer and return the next input character:
9973 * 1) If a string was pushed back on the input, pop it;
9974 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9975 * or we are reading from a string so we can't refill the buffer,
9977 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9978 * 4) Process input up to the next newline, deleting nul characters.
9980 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9981 #define pgetc_debug(...) ((void)0)
9982 static int pgetc(void);
9989 if (g_parsefile->strpush) {
9990 #if ENABLE_ASH_ALIAS
9991 if (g_parsefile->left_in_line == -1
9992 && g_parsefile->strpush->ap
9993 && g_parsefile->next_to_pgetc[-1] != ' '
9994 && g_parsefile->next_to_pgetc[-1] != '\t'
9996 pgetc_debug("preadbuffer PEOA");
10003 /* on both branches above g_parsefile->left_in_line < 0.
10004 * "pgetc" needs refilling.
10007 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
10008 * pungetc() may increment it a few times.
10009 * Assuming it won't increment it to less than -90.
10011 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
10012 pgetc_debug("preadbuffer PEOF1");
10013 /* even in failure keep left_in_line and next_to_pgetc
10014 * in lock step, for correct multi-layer pungetc.
10015 * left_in_line was decremented before preadbuffer(),
10016 * must inc next_to_pgetc: */
10017 g_parsefile->next_to_pgetc++;
10021 more = g_parsefile->left_in_buffer;
10023 flush_stdout_stderr();
10027 /* don't try reading again */
10028 g_parsefile->left_in_line = -99;
10029 pgetc_debug("preadbuffer PEOF2");
10030 g_parsefile->next_to_pgetc++;
10035 /* Find out where's the end of line.
10036 * Set g_parsefile->left_in_line
10037 * and g_parsefile->left_in_buffer acordingly.
10038 * NUL chars are deleted.
10040 q = g_parsefile->next_to_pgetc;
10048 memmove(q, q + 1, more);
10052 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10058 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10059 if (g_parsefile->left_in_line < 0)
10064 g_parsefile->left_in_buffer = more;
10069 out2str(g_parsefile->next_to_pgetc);
10073 pgetc_debug("preadbuffer at %d:%p'%s'",
10074 g_parsefile->left_in_line,
10075 g_parsefile->next_to_pgetc,
10076 g_parsefile->next_to_pgetc);
10077 return (unsigned char)*g_parsefile->next_to_pgetc++;
10083 g_parsefile->linno++;
10084 setprompt_if(doprompt, 2);
10089 g_parsefile->linno++;
10090 needprompt = doprompt;
10098 pgetc_debug("pgetc at %d:%p'%s'",
10099 g_parsefile->left_in_line,
10100 g_parsefile->next_to_pgetc,
10101 g_parsefile->next_to_pgetc);
10102 if (g_parsefile->unget)
10103 return g_parsefile->lastc[--g_parsefile->unget];
10105 if (--g_parsefile->left_in_line >= 0)
10106 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10110 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10111 g_parsefile->lastc[0] = c;
10116 #if ENABLE_ASH_ALIAS
10118 pgetc_without_PEOA(void)
10122 pgetc_debug("pgetc at %d:%p'%s'",
10123 g_parsefile->left_in_line,
10124 g_parsefile->next_to_pgetc,
10125 g_parsefile->next_to_pgetc);
10127 } while (c == PEOA);
10131 # define pgetc_without_PEOA() pgetc()
10135 * Read a line from the script.
10138 pfgets(char *line, int len)
10144 while (--nleft > 0) {
10145 c = pgetc_without_PEOA();
10160 * Undo a call to pgetc. Only two characters may be pushed back.
10161 * PEOF may be pushed back.
10166 g_parsefile->unget++;
10169 /* This one eats backslash+newline */
10175 while ((c = pgetc()) == '\\') {
10176 if (pgetc() != '\n') {
10188 * To handle the "." command, a stack of input files is used. Pushfile
10189 * adds a new entry to the stack and popfile restores the previous level.
10194 struct parsefile *pf;
10196 pf = ckzalloc(sizeof(*pf));
10197 pf->prev = g_parsefile;
10199 /*pf->strpush = NULL; - ckzalloc did it */
10200 /*pf->basestrpush.prev = NULL;*/
10208 struct parsefile *pf = g_parsefile;
10214 if (pf->pf_fd >= 0)
10217 while (pf->strpush)
10219 g_parsefile = pf->prev;
10225 * Return to top level.
10230 while (g_parsefile != &basepf)
10235 * Close the file(s) that the shell is reading commands from. Called
10236 * after a fork is done.
10242 if (g_parsefile->pf_fd > 0) {
10243 close(g_parsefile->pf_fd);
10244 g_parsefile->pf_fd = 0;
10249 * Like setinputfile, but takes an open file descriptor. Call this with
10253 setinputfd(int fd, int push)
10257 g_parsefile->buf = NULL;
10259 g_parsefile->pf_fd = fd;
10260 if (g_parsefile->buf == NULL)
10261 g_parsefile->buf = ckmalloc(IBUFSIZ);
10262 g_parsefile->left_in_buffer = 0;
10263 g_parsefile->left_in_line = 0;
10264 g_parsefile->linno = 1;
10268 * Set the input to take input from a file. If push is set, push the
10269 * old input onto the stack first.
10272 setinputfile(const char *fname, int flags)
10277 fd = open(fname, O_RDONLY);
10279 if (flags & INPUT_NOFILE_OK)
10282 ash_msg_and_raise_error("can't open '%s'", fname);
10287 close_on_exec_on(fd);
10288 setinputfd(fd, flags & INPUT_PUSH_FILE);
10295 * Like setinputfile, but takes input from a string.
10298 setinputstring(char *string)
10302 g_parsefile->next_to_pgetc = string;
10303 g_parsefile->left_in_line = strlen(string);
10304 g_parsefile->buf = NULL;
10305 g_parsefile->linno = 1;
10311 * Routines to check for mail.
10314 #if ENABLE_ASH_MAIL
10316 /* Hash of mtimes of mailboxes */
10317 static unsigned mailtime_hash;
10318 /* Set if MAIL or MAILPATH is changed. */
10319 static smallint mail_var_path_changed;
10322 * Print appropriate message(s) if mail has arrived.
10323 * If mail_var_path_changed is set,
10324 * then the value of MAIL has mail_var_path_changed,
10325 * so we just update the values.
10334 struct stackmark smark;
10337 setstackmark(&smark);
10338 mpath = mpathset() ? mpathval() : mailval();
10341 p = path_advance(&mpath, nullstr);
10346 for (q = p; *q; q++)
10352 q[-1] = '\0'; /* delete trailing '/' */
10353 if (stat(p, &statb) < 0) {
10356 /* Very simplistic "hash": just a sum of all mtimes */
10357 new_hash += (unsigned)statb.st_mtime;
10359 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10360 if (mailtime_hash != 0)
10361 out2str("you have mail\n");
10362 mailtime_hash = new_hash;
10364 mail_var_path_changed = 0;
10365 popstackmark(&smark);
10368 static void FAST_FUNC
10369 changemail(const char *val UNUSED_PARAM)
10371 mail_var_path_changed = 1;
10374 #endif /* ASH_MAIL */
10377 /* ============ ??? */
10380 * Set the shell parameters.
10383 setparam(char **argv)
10389 for (nparam = 0; argv[nparam]; nparam++)
10391 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10393 *ap++ = ckstrdup(*argv++);
10396 freeparam(&shellparam);
10397 shellparam.malloced = 1;
10398 shellparam.nparam = nparam;
10399 shellparam.p = newparam;
10400 #if ENABLE_ASH_GETOPTS
10401 shellparam.optind = 1;
10402 shellparam.optoff = -1;
10407 * Process shell options. The global variable argptr contains a pointer
10408 * to the argument list; we advance it past the options.
10410 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10411 * For a non-interactive shell, an error condition encountered
10412 * by a special built-in ... shall cause the shell to write a diagnostic message
10413 * to standard error and exit as shown in the following table:
10414 * Error Special Built-In
10416 * Utility syntax error (option or operand error) Shall exit
10418 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10419 * we see that bash does not do that (set "finishes" with error code 1 instead,
10420 * and shell continues), and people rely on this behavior!
10422 * set -o barfoo 2>/dev/null
10425 * Oh well. Let's mimic that.
10428 plus_minus_o(char *name, int val)
10433 for (i = 0; i < NOPTS; i++) {
10434 if (strcmp(name, optnames(i)) == 0) {
10439 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10442 for (i = 0; i < NOPTS; i++) {
10444 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10446 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10452 setoption(int flag, int val)
10456 for (i = 0; i < NOPTS; i++) {
10457 if (optletters(i) == flag) {
10462 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10466 options(int cmdline)
10474 while ((p = *argptr) != NULL) {
10476 if (c != '-' && c != '+')
10479 val = 0; /* val = 0 if c == '+' */
10482 if (p[0] == '\0' || LONE_DASH(p)) {
10484 /* "-" means turn off -x and -v */
10487 /* "--" means reset params */
10488 else if (*argptr == NULL)
10491 break; /* "-" or "--" terminates options */
10494 /* first char was + or - */
10495 while ((c = *p++) != '\0') {
10496 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10497 if (c == 'c' && cmdline) {
10498 minusc = p; /* command is after shell args */
10499 } else if (c == 'o') {
10500 if (plus_minus_o(*argptr, val)) {
10501 /* it already printed err message */
10502 return 1; /* error */
10506 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10508 /* bash does not accept +-login, we also won't */
10509 } else if (cmdline && val && (c == '-')) { /* long options */
10510 if (strcmp(p, "login") == 0)
10522 * The shift builtin command.
10524 static int FAST_FUNC
10525 shiftcmd(int argc UNUSED_PARAM, char **argv)
10532 n = number(argv[1]);
10533 if (n > shellparam.nparam)
10534 n = 0; /* bash compat, was = shellparam.nparam; */
10536 shellparam.nparam -= n;
10537 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10538 if (shellparam.malloced)
10541 ap2 = shellparam.p;
10542 while ((*ap2++ = *ap1++) != NULL)
10544 #if ENABLE_ASH_GETOPTS
10545 shellparam.optind = 1;
10546 shellparam.optoff = -1;
10553 * POSIX requires that 'set' (but not export or readonly) output the
10554 * variables in lexicographic order - by the locale's collating order (sigh).
10555 * Maybe we could keep them in an ordered balanced binary tree
10556 * instead of hashed lists.
10557 * For now just roll 'em through qsort for printing...
10560 showvars(const char *sep_prefix, int on, int off)
10563 char **ep, **epend;
10565 ep = listvars(on, off, &epend);
10566 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10568 sep = *sep_prefix ? " " : sep_prefix;
10570 for (; ep < epend; ep++) {
10574 p = strchrnul(*ep, '=');
10577 q = single_quote(++p);
10578 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10584 * The set command builtin.
10586 static int FAST_FUNC
10587 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10592 return showvars(nullstr, 0, VUNSET);
10595 retval = options(/*cmdline:*/ 0);
10596 if (retval == 0) { /* if no parse error... */
10598 if (*argptr != NULL) {
10606 #if ENABLE_ASH_RANDOM_SUPPORT
10607 static void FAST_FUNC
10608 change_random(const char *value)
10612 if (value == NULL) {
10613 /* "get", generate */
10614 t = next_random(&random_gen);
10615 /* set without recursion */
10616 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10617 vrandom.flags &= ~VNOFUNC;
10620 t = strtoul(value, NULL, 10);
10621 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10626 #if ENABLE_ASH_GETOPTS
10628 getopts(char *optstr, char *optvar, char **optfirst)
10635 int ind = shellparam.optind;
10636 int off = shellparam.optoff;
10640 shellparam.optind = -1;
10641 optnext = optfirst + ind - 1;
10643 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10646 p = optnext[-1] + off;
10647 if (p == NULL || *p == '\0') {
10648 /* Current word is done, advance */
10650 if (p == NULL || *p != '-' || *++p == '\0') {
10657 if (LONE_DASH(p)) /* check for "--" */
10662 for (q = optstr; *q != c;) {
10664 if (optstr[0] == ':') {
10666 /*sbuf[1] = '\0'; - already is */
10667 setvar0("OPTARG", sbuf);
10669 fprintf(stderr, "Illegal option -%c\n", c);
10670 unsetvar("OPTARG");
10680 if (*p == '\0' && (p = *optnext) == NULL) {
10681 if (optstr[0] == ':') {
10683 /*sbuf[1] = '\0'; - already is */
10684 setvar0("OPTARG", sbuf);
10687 fprintf(stderr, "No arg for -%c option\n", c);
10688 unsetvar("OPTARG");
10696 setvar0("OPTARG", p);
10699 setvar0("OPTARG", nullstr);
10701 ind = optnext - optfirst + 1;
10702 setvar("OPTIND", itoa(ind), VNOFUNC);
10704 /*sbuf[1] = '\0'; - already is */
10705 setvar0(optvar, sbuf);
10707 shellparam.optoff = p ? p - *(optnext - 1) : -1;
10708 shellparam.optind = ind;
10714 * The getopts builtin. Shellparam.optnext points to the next argument
10715 * to be processed. Shellparam.optptr points to the next character to
10716 * be processed in the current argument. If shellparam.optnext is NULL,
10717 * then it's the first time getopts has been called.
10719 static int FAST_FUNC
10720 getoptscmd(int argc, char **argv)
10725 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10727 optbase = shellparam.p;
10728 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
10729 shellparam.optind = 1;
10730 shellparam.optoff = -1;
10733 optbase = &argv[3];
10734 if ((unsigned)shellparam.optind > argc - 2) {
10735 shellparam.optind = 1;
10736 shellparam.optoff = -1;
10740 return getopts(argv[1], argv[2], optbase);
10742 #endif /* ASH_GETOPTS */
10745 /* ============ Shell parser */
10748 struct heredoc *next; /* next here document in list */
10749 union node *here; /* redirection node */
10750 char *eofmark; /* string indicating end of input */
10751 smallint striptabs; /* if set, strip leading tabs */
10754 static smallint tokpushback; /* last token pushed back */
10755 static smallint quoteflag; /* set if (part of) last token was quoted */
10756 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10757 static struct heredoc *heredoclist; /* list of here documents to read */
10758 static char *wordtext; /* text of last word returned by readtoken */
10759 static struct nodelist *backquotelist;
10760 static union node *redirnode;
10761 static struct heredoc *heredoc;
10763 static const char *
10764 tokname(char *buf, int tok)
10767 return tokname_array[tok];
10768 sprintf(buf, "\"%s\"", tokname_array[tok]);
10772 /* raise_error_unexpected_syntax:
10773 * Called when an unexpected token is read during the parse. The argument
10774 * is the token that is expected, or -1 if more than one type of token can
10775 * occur at this point.
10777 static void raise_error_unexpected_syntax(int) NORETURN;
10779 raise_error_unexpected_syntax(int token)
10785 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10787 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10788 raise_error_syntax(msg);
10792 #define EOFMARKLEN 79
10794 /* parsing is heavily cross-recursive, need these forward decls */
10795 static union node *andor(void);
10796 static union node *pipeline(void);
10797 static union node *parse_command(void);
10798 static void parseheredoc(void);
10799 static int peektoken(void);
10800 static int readtoken(void);
10802 static union node *
10805 union node *n1, *n2, *n3;
10810 switch (peektoken()) {
10818 if (!n1 && (nlflag & 1))
10824 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10825 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
10831 if (tok == TBACKGND) {
10832 if (n2->type == NPIPE) {
10833 n2->npipe.pipe_backgnd = 1;
10835 if (n2->type != NREDIR) {
10836 n3 = stzalloc(sizeof(struct nredir));
10838 /*n3->nredir.redirect = NULL; - stzalloc did it */
10841 n2->type = NBACKGND;
10847 n3 = stzalloc(sizeof(struct nbinary));
10849 n3->nbinary.ch1 = n1;
10850 n3->nbinary.ch2 = n2;
10863 raise_error_unexpected_syntax(-1);
10870 static union node *
10873 union node *n1, *n2, *n3;
10881 } else if (t == TOR) {
10887 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10889 n3 = stzalloc(sizeof(struct nbinary));
10891 n3->nbinary.ch1 = n1;
10892 n3->nbinary.ch2 = n2;
10897 static union node *
10900 union node *n1, *n2, *pipenode;
10901 struct nodelist *lp, *prev;
10905 TRACE(("pipeline: entered\n"));
10906 if (readtoken() == TNOT) {
10908 checkkwd = CHKKWD | CHKALIAS;
10911 n1 = parse_command();
10912 if (readtoken() == TPIPE) {
10913 pipenode = stzalloc(sizeof(struct npipe));
10914 pipenode->type = NPIPE;
10915 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10916 lp = stzalloc(sizeof(struct nodelist));
10917 pipenode->npipe.cmdlist = lp;
10921 lp = stzalloc(sizeof(struct nodelist));
10922 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10923 lp->n = parse_command();
10925 } while (readtoken() == TPIPE);
10931 n2 = stzalloc(sizeof(struct nnot));
10939 static union node *
10944 n = stzalloc(sizeof(struct narg));
10946 /*n->narg.next = NULL; - stzalloc did it */
10947 n->narg.text = wordtext;
10948 n->narg.backquote = backquotelist;
10953 fixredir(union node *n, const char *text, int err)
10957 TRACE(("Fix redir %s %d\n", text, err));
10959 n->ndup.vname = NULL;
10961 fd = bb_strtou(text, NULL, 10);
10962 if (!errno && fd >= 0)
10963 n->ndup.dupfd = fd;
10964 else if (LONE_DASH(text))
10965 n->ndup.dupfd = -1;
10968 raise_error_syntax("bad fd number");
10969 n->ndup.vname = makename();
10974 * Returns true if the text contains nothing to expand (no dollar signs
10978 noexpand(const char *text)
10982 while ((c = *text++) != '\0') {
10983 if (c == CTLQUOTEMARK)
10987 else if (SIT(c, BASESYNTAX) == CCTL)
10996 union node *n = redirnode;
10998 if (readtoken() != TWORD)
10999 raise_error_unexpected_syntax(-1);
11000 if (n->type == NHERE) {
11001 struct heredoc *here = heredoc;
11005 if (quoteflag == 0)
11007 TRACE(("Here document %d\n", n->type));
11008 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
11009 raise_error_syntax("illegal eof marker for << redirection");
11010 rmescapes(wordtext, 0);
11011 here->eofmark = wordtext;
11013 if (heredoclist == NULL)
11014 heredoclist = here;
11016 for (p = heredoclist; p->next; p = p->next)
11020 } else if (n->type == NTOFD || n->type == NFROMFD) {
11021 fixredir(n, wordtext, 0);
11023 n->nfile.fname = makename();
11027 static union node *
11030 union node *args, **app;
11031 union node *n = NULL;
11032 union node *vars, **vpp;
11033 union node **rpp, *redir;
11036 smallint double_brackets_flag = 0;
11038 IF_BASH_FUNCTION(smallint function_flag = 0;)
11047 savecheckkwd = CHKALIAS;
11050 checkkwd = savecheckkwd;
11055 if (peektoken() != TWORD)
11056 raise_error_unexpected_syntax(TWORD);
11061 case TAND: /* "&&" */
11062 case TOR: /* "||" */
11063 if (!double_brackets_flag) {
11067 wordtext = (char *) (t == TAND ? "-a" : "-o");
11070 n = stzalloc(sizeof(struct narg));
11072 /*n->narg.next = NULL; - stzalloc did it */
11073 n->narg.text = wordtext;
11075 if (strcmp("[[", wordtext) == 0)
11076 double_brackets_flag = 1;
11077 else if (strcmp("]]", wordtext) == 0)
11078 double_brackets_flag = 0;
11080 n->narg.backquote = backquotelist;
11081 if (savecheckkwd && isassignment(wordtext)) {
11083 vpp = &n->narg.next;
11086 app = &n->narg.next;
11090 if (function_flag) {
11091 checkkwd = CHKNL | CHKKWD;
11092 switch (peektoken()) {
11104 if (strcmp("[[", wordtext) == 0)
11108 raise_error_unexpected_syntax(-1);
11114 *rpp = n = redirnode;
11115 rpp = &n->nfile.next;
11116 parsefname(); /* read name of redirection file */
11119 IF_BASH_FUNCTION(do_func:)
11120 if (args && app == &args->narg.next
11123 struct builtincmd *bcmd;
11126 /* We have a function */
11127 if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
11128 raise_error_unexpected_syntax(TRP);
11129 name = n->narg.text;
11130 if (!goodname(name)
11131 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11133 raise_error_syntax("bad function name");
11136 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11137 n->narg.next = parse_command();
11140 IF_BASH_FUNCTION(function_flag = 0;)
11151 n = stzalloc(sizeof(struct ncmd));
11153 n->ncmd.args = args;
11154 n->ncmd.assign = vars;
11155 n->ncmd.redirect = redir;
11159 static union node *
11160 parse_command(void)
11162 union node *n1, *n2;
11163 union node *ap, **app;
11164 union node *cp, **cpp;
11165 union node *redir, **rpp;
11172 switch (readtoken()) {
11174 raise_error_unexpected_syntax(-1);
11177 n1 = stzalloc(sizeof(struct nif));
11179 n1->nif.test = list(0);
11180 if (readtoken() != TTHEN)
11181 raise_error_unexpected_syntax(TTHEN);
11182 n1->nif.ifpart = list(0);
11184 while (readtoken() == TELIF) {
11185 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11186 n2 = n2->nif.elsepart;
11188 n2->nif.test = list(0);
11189 if (readtoken() != TTHEN)
11190 raise_error_unexpected_syntax(TTHEN);
11191 n2->nif.ifpart = list(0);
11193 if (lasttoken == TELSE)
11194 n2->nif.elsepart = list(0);
11196 n2->nif.elsepart = NULL;
11204 n1 = stzalloc(sizeof(struct nbinary));
11205 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11206 n1->nbinary.ch1 = list(0);
11209 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11210 got == TWORD ? wordtext : ""));
11211 raise_error_unexpected_syntax(TDO);
11213 n1->nbinary.ch2 = list(0);
11218 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11219 raise_error_syntax("bad for loop variable");
11220 n1 = stzalloc(sizeof(struct nfor));
11222 n1->nfor.var = wordtext;
11223 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11224 if (readtoken() == TIN) {
11226 while (readtoken() == TWORD) {
11227 n2 = stzalloc(sizeof(struct narg));
11229 /*n2->narg.next = NULL; - stzalloc did it */
11230 n2->narg.text = wordtext;
11231 n2->narg.backquote = backquotelist;
11233 app = &n2->narg.next;
11236 n1->nfor.args = ap;
11237 if (lasttoken != TNL && lasttoken != TSEMI)
11238 raise_error_unexpected_syntax(-1);
11240 n2 = stzalloc(sizeof(struct narg));
11242 /*n2->narg.next = NULL; - stzalloc did it */
11243 n2->narg.text = (char *)dolatstr;
11244 /*n2->narg.backquote = NULL;*/
11245 n1->nfor.args = n2;
11247 * Newline or semicolon here is optional (but note
11248 * that the original Bourne shell only allowed NL).
11250 if (lasttoken != TSEMI)
11253 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11254 if (readtoken() != TDO)
11255 raise_error_unexpected_syntax(TDO);
11256 n1->nfor.body = list(0);
11260 n1 = stzalloc(sizeof(struct ncase));
11262 if (readtoken() != TWORD)
11263 raise_error_unexpected_syntax(TWORD);
11264 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11266 /*n2->narg.next = NULL; - stzalloc did it */
11267 n2->narg.text = wordtext;
11268 n2->narg.backquote = backquotelist;
11269 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11270 if (readtoken() != TIN)
11271 raise_error_unexpected_syntax(TIN);
11272 cpp = &n1->ncase.cases;
11274 checkkwd = CHKNL | CHKKWD;
11276 while (t != TESAC) {
11277 if (lasttoken == TLP)
11279 *cpp = cp = stzalloc(sizeof(struct nclist));
11281 app = &cp->nclist.pattern;
11283 *app = ap = stzalloc(sizeof(struct narg));
11285 /*ap->narg.next = NULL; - stzalloc did it */
11286 ap->narg.text = wordtext;
11287 ap->narg.backquote = backquotelist;
11288 if (readtoken() != TPIPE)
11290 app = &ap->narg.next;
11293 //ap->narg.next = NULL;
11294 if (lasttoken != TRP)
11295 raise_error_unexpected_syntax(TRP);
11296 cp->nclist.body = list(2);
11298 cpp = &cp->nclist.next;
11300 checkkwd = CHKNL | CHKKWD;
11304 raise_error_unexpected_syntax(TENDCASE);
11311 n1 = stzalloc(sizeof(struct nredir));
11312 n1->type = NSUBSHELL;
11313 n1->nredir.n = list(0);
11314 /*n1->nredir.redirect = NULL; - stzalloc did it */
11321 IF_BASH_FUNCTION(case TFUNCTION:)
11325 return simplecmd();
11328 if (readtoken() != t)
11329 raise_error_unexpected_syntax(t);
11332 /* Now check for redirection which may follow command */
11333 checkkwd = CHKKWD | CHKALIAS;
11335 while (readtoken() == TREDIR) {
11336 *rpp = n2 = redirnode;
11337 rpp = &n2->nfile.next;
11343 if (n1->type != NSUBSHELL) {
11344 n2 = stzalloc(sizeof(struct nredir));
11349 n1->nredir.redirect = redir;
11354 #if BASH_DOLLAR_SQUOTE
11356 decode_dollar_squote(void)
11358 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11364 p = strchr(C_escapes, c);
11369 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11373 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11375 } else if (c == 'x') { /* \xHH */
11379 } while (isxdigit(c) && --cnt);
11381 if (cnt == 3) { /* \x but next char is "bad" */
11385 } else { /* simple seq like \\ or \t */
11390 c = bb_process_escape_sequence((void*)&p);
11391 } else { /* unrecognized "\z": print both chars unless ' or " */
11392 if (c != '\'' && c != '"') {
11394 c |= 0x100; /* "please encode \, then me" */
11402 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11403 * is not NULL, read a here document. In the latter case, eofmark is the
11404 * word which marks the end of the document and striptabs is true if
11405 * leading tabs should be stripped from the document. The argument c
11406 * is the first character of the input token or document.
11408 * Because C does not have internal subroutines, I have simulated them
11409 * using goto's to implement the subroutine linkage. The following macros
11410 * will run code that appears at the end of readtoken1.
11412 #define CHECKEND() {goto checkend; checkend_return:;}
11413 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11414 #define PARSESUB() {goto parsesub; parsesub_return:;}
11415 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11416 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11417 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11419 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11421 /* NB: syntax parameter fits into smallint */
11422 /* c parameter is an unsigned char or PEOF or PEOA */
11425 char line[EOFMARKLEN + 1];
11426 struct nodelist *bqlist;
11430 IF_FEATURE_SH_MATH(smallint prevsyntax;) /* syntax before arithmetic */
11431 #if ENABLE_ASH_EXPAND_PRMT
11432 smallint pssyntax; /* we are expanding a prompt string */
11434 int varnest; /* levels of variables expansion */
11435 IF_FEATURE_SH_MATH(int arinest;) /* levels of arithmetic expansion */
11436 IF_FEATURE_SH_MATH(int parenlevel;) /* levels of parens in arithmetic */
11437 int dqvarnest; /* levels of variables expansion within double quotes */
11439 IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
11441 startlinno = g_parsefile->linno;
11444 IF_FEATURE_SH_MATH(prevsyntax = 0;)
11445 #if ENABLE_ASH_EXPAND_PRMT
11446 pssyntax = (syntax == PSSYNTAX);
11450 dblquote = (syntax == DQSYNTAX);
11452 IF_FEATURE_SH_MATH(arinest = 0;)
11453 IF_FEATURE_SH_MATH(parenlevel = 0;)
11456 STARTSTACKSTR(out);
11458 /* For each line, until end of word */
11459 CHECKEND(); /* set c to PEOF if at end of here document */
11460 for (;;) { /* until end of line or end of word */
11461 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11462 switch (SIT(c, syntax)) {
11463 case CNL: /* '\n' */
11464 if (syntax == BASESYNTAX)
11465 goto endword; /* exit outer loop */
11469 goto loop; /* continue outer loop */
11474 #if BASH_DOLLAR_SQUOTE
11475 if (c == '\\' && bash_dollar_squote) {
11476 c = decode_dollar_squote();
11478 /* skip $'\000', $'\x00' (like bash) */
11482 /* Unknown escape. Encode as '\z' */
11483 c = (unsigned char)c;
11484 if (eofmark == NULL || dblquote)
11485 USTPUTC(CTLESC, out);
11486 USTPUTC('\\', out);
11490 if (eofmark == NULL || dblquote)
11491 USTPUTC(CTLESC, out);
11494 case CBACK: /* backslash */
11495 c = pgetc_without_PEOA();
11497 USTPUTC(CTLESC, out);
11498 USTPUTC('\\', out);
11500 } else if (c == '\n') {
11503 #if ENABLE_ASH_EXPAND_PRMT
11504 if (c == '$' && pssyntax) {
11505 USTPUTC(CTLESC, out);
11506 USTPUTC('\\', out);
11509 /* Backslash is retained if we are in "str" and next char isn't special */
11514 && (c != '"' || eofmark != NULL)
11516 USTPUTC('\\', out);
11518 USTPUTC(CTLESC, out);
11526 if (eofmark == NULL) {
11527 USTPUTC(CTLQUOTEMARK, out);
11535 IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
11536 if (eofmark != NULL && varnest == 0) {
11539 if (dqvarnest == 0) {
11540 syntax = BASESYNTAX;
11547 case CVAR: /* '$' */
11548 PARSESUB(); /* parse substitution */
11550 case CENDVAR: /* '}' */
11553 if (dqvarnest > 0) {
11560 #if ENABLE_FEATURE_SH_MATH
11561 case CLP: /* '(' in arithmetic */
11565 case CRP: /* ')' in arithmetic */
11566 if (parenlevel > 0) {
11569 if (pgetc_eatbnl() == ')') {
11571 if (--arinest == 0) {
11572 syntax = prevsyntax;
11576 * unbalanced parens
11577 * (don't 2nd guess - no error)
11585 case CBQUOTE: /* '`' */
11589 goto endword; /* exit outer loop */
11593 if (varnest == 0) {
11594 #if BASH_REDIR_OUTPUT
11596 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11597 if (pgetc() == '>')
11598 c = 0x100 + '>'; /* flag &> */
11602 goto endword; /* exit outer loop */
11604 IF_ASH_ALIAS(if (c != PEOA))
11611 #if ENABLE_FEATURE_SH_MATH
11612 if (syntax == ARISYNTAX)
11613 raise_error_syntax("missing '))'");
11615 if (syntax != BASESYNTAX && eofmark == NULL)
11616 raise_error_syntax("unterminated quoted string");
11617 if (varnest != 0) {
11618 startlinno = g_parsefile->linno;
11620 raise_error_syntax("missing '}'");
11622 USTPUTC('\0', out);
11623 len = out - (char *)stackblock();
11624 out = stackblock();
11625 if (eofmark == NULL) {
11626 if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
11629 if (isdigit_str9(out)) {
11630 PARSEREDIR(); /* passed as params: out, c */
11631 lasttoken = TREDIR;
11634 /* else: non-number X seen, interpret it
11635 * as "NNNX>file" = "NNNX >file" */
11639 quoteflag = quotef;
11640 backquotelist = bqlist;
11641 grabstackblock(len);
11645 /* end of readtoken routine */
11648 * Check to see whether we are at the end of the here document. When this
11649 * is called, c is set to the first character of the next input line. If
11650 * we are at the end of the here document, this routine sets the c to PEOF.
11654 #if ENABLE_ASH_ALIAS
11656 c = pgetc_without_PEOA();
11659 while (c == '\t') {
11660 c = pgetc_without_PEOA();
11663 if (c == *eofmark) {
11664 if (pfgets(line, sizeof(line)) != NULL) {
11669 for (q = eofmark + 1;; p++, q++) {
11673 if (!*q || cc != *q)
11680 pushstring(line, NULL);
11685 goto checkend_return;
11689 * Parse a redirection operator. The variable "out" points to a string
11690 * specifying the fd to be redirected. The variable "c" contains the
11691 * first character of the redirection operator.
11694 /* out is already checked to be a valid number or "" */
11695 int fd = (*out == '\0' ? -1 : atoi(out));
11698 np = stzalloc(sizeof(struct nfile));
11703 np->type = NAPPEND;
11705 np->type = NCLOBBER;
11708 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11714 #if BASH_REDIR_OUTPUT
11715 else if (c == 0x100 + '>') { /* this flags &> redirection */
11717 pgetc(); /* this is '>', no need to check */
11721 else { /* c == '<' */
11722 /*np->nfile.fd = 0; - stzalloc did it */
11726 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11727 np = stzalloc(sizeof(struct nhere));
11728 /*np->nfile.fd = 0; - stzalloc did it */
11731 heredoc = stzalloc(sizeof(struct heredoc));
11732 heredoc->here = np;
11735 heredoc->striptabs = 1;
11737 /*heredoc->striptabs = 0; - stzalloc did it */
11743 np->type = NFROMFD;
11747 np->type = NFROMTO;
11759 goto parseredir_return;
11763 * Parse a substitution. At this point, we have read the dollar sign
11764 * and nothing else.
11767 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11768 * (assuming ascii char codes, as the original implementation did) */
11769 #define is_special(c) \
11770 (((unsigned)(c) - 33 < 32) \
11771 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11773 unsigned char subtype;
11776 c = pgetc_eatbnl();
11777 if (c > 255 /* PEOA or PEOF */
11778 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11780 #if BASH_DOLLAR_SQUOTE
11781 if (syntax != DQSYNTAX && c == '\'')
11782 bash_dollar_squote = 1;
11787 } else if (c == '(') {
11788 /* $(command) or $((arith)) */
11789 if (pgetc_eatbnl() == '(') {
11790 #if ENABLE_FEATURE_SH_MATH
11793 raise_error_syntax("you disabled math support for $((arith)) syntax");
11800 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11801 USTPUTC(CTLVAR, out);
11802 typeloc = out - (char *)stackblock();
11804 subtype = VSNORMAL;
11806 c = pgetc_eatbnl();
11811 /* $[{[#]]NAME[}] */
11814 c = pgetc_eatbnl();
11815 } while (is_in_name(c));
11816 } else if (isdigit(c)) {
11817 /* $[{[#]]NUM[}] */
11820 c = pgetc_eatbnl();
11821 } while (isdigit(c));
11822 } else if (is_special(c)) {
11823 /* $[{[#]]<specialchar>[}] */
11826 c = pgetc_eatbnl();
11827 if (!subtype && cc == '#') {
11828 subtype = VSLENGTH;
11829 if (c == '_' || isalnum(c))
11832 c = pgetc_eatbnl();
11833 if (cc == '}' || c != '}') {
11844 if (c != '}' && subtype == VSLENGTH) {
11845 /* ${#VAR didn't end with } */
11849 if (subtype == 0) {
11850 static const char types[] ALIGN1 = "}-+?=";
11851 /* ${VAR...} but not $VAR or ${#VAR} */
11852 /* c == first char after VAR */
11855 c = pgetc_eatbnl();
11857 /* This check is only needed to not misinterpret
11858 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11861 if (!strchr(types, c)) {
11862 subtype = VSSUBSTR;
11864 break; /* "goto badsub" is bigger (!) */
11870 const char *p = strchr(types, c);
11873 subtype |= p - types + VSNORMAL;
11879 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11880 c = pgetc_eatbnl();
11886 #if BASH_PATTERN_SUBST
11888 /* ${v/[/]pattern/repl} */
11889 //TODO: encode pattern and repl separately.
11890 // Currently ${v/$var_with_slash/repl} is horribly broken
11891 subtype = VSREPLACE;
11892 c = pgetc_eatbnl();
11895 subtype++; /* VSREPLACEALL */
11903 ((unsigned char *)stackblock())[typeloc] = subtype;
11904 if (subtype != VSNORMAL) {
11911 goto parsesub_return;
11915 * Called to parse command substitutions. Newstyle is set if the command
11916 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11917 * list of commands (passed by reference), and savelen is the number of
11918 * characters on the top of the stack which must be preserved.
11921 struct nodelist **nlpp;
11925 smallint saveprompt = 0;
11928 savelen = out - (char *)stackblock();
11931 * FIXME: this can allocate very large block on stack and SEGV.
11933 * echo "..<100kbytes>..`true` $(true) `true` ..."
11934 * allocates 100kb for every command subst. With about
11935 * a hundred command substitutions stack overflows.
11936 * With larger prepended string, SEGV happens sooner.
11938 str = alloca(savelen);
11939 memcpy(str, stackblock(), savelen);
11943 /* We must read until the closing backquote, giving special
11944 * treatment to some slashes, and then push the string and
11945 * reread it as input, interpreting it normally.
11951 STARTSTACKSTR(pout);
11955 setprompt_if(needprompt, 2);
11966 * If eating a newline, avoid putting
11967 * the newline into the new character
11968 * stream (via the STPUTC after the
11973 if (pc != '\\' && pc != '`' && pc != '$'
11974 && (!dblquote || pc != '"')
11976 STPUTC('\\', pout);
11978 if (pc <= 255 /* not PEOA or PEOF */) {
11984 IF_ASH_ALIAS(case PEOA:)
11985 startlinno = g_parsefile->linno;
11986 raise_error_syntax("EOF in backquote substitution");
11998 STPUTC('\0', pout);
11999 psavelen = pout - (char *)stackblock();
12000 if (psavelen > 0) {
12001 pstr = grabstackstr(pout);
12002 setinputstring(pstr);
12007 nlpp = &(*nlpp)->next;
12008 *nlpp = stzalloc(sizeof(**nlpp));
12009 /* (*nlpp)->next = NULL; - stzalloc did it */
12012 saveprompt = doprompt;
12019 doprompt = saveprompt;
12020 else if (readtoken() != TRP)
12021 raise_error_unexpected_syntax(TRP);
12026 * Start reading from old file again, ignoring any pushed back
12027 * tokens left from the backquote parsing
12032 while (stackblocksize() <= savelen)
12034 STARTSTACKSTR(out);
12036 memcpy(out, str, savelen);
12037 STADJUST(savelen, out);
12039 USTPUTC(CTLBACKQ, out);
12041 goto parsebackq_oldreturn;
12042 goto parsebackq_newreturn;
12045 #if ENABLE_FEATURE_SH_MATH
12047 * Parse an arithmetic expansion (indicate start of one and set state)
12050 if (++arinest == 1) {
12051 prevsyntax = syntax;
12052 syntax = ARISYNTAX;
12054 USTPUTC(CTLARI, out);
12055 goto parsearith_return;
12058 } /* end of readtoken */
12061 * Read the next input token.
12062 * If the token is a word, we set backquotelist to the list of cmds in
12063 * backquotes. We set quoteflag to true if any part of the word was
12065 * If the token is TREDIR, then we set redirnode to a structure containing
12067 * In all cases, the variable startlinno is set to the number of the line
12068 * on which the token starts.
12070 * [Change comment: here documents and internal procedures]
12071 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12072 * word parsing code into a separate routine. In this case, readtoken
12073 * doesn't need to have any internal procedures, but parseword does.
12074 * We could also make parseoperator in essence the main routine, and
12075 * have parseword (readtoken1?) handle both words and redirection.]
12077 #define NEW_xxreadtoken
12078 #ifdef NEW_xxreadtoken
12079 /* singles must be first! */
12080 static const char xxreadtoken_chars[7] ALIGN1 = {
12081 '\n', '(', ')', /* singles */
12082 '&', '|', ';', /* doubles */
12086 #define xxreadtoken_singles 3
12087 #define xxreadtoken_doubles 3
12089 static const char xxreadtoken_tokens[] ALIGN1 = {
12090 TNL, TLP, TRP, /* only single occurrence allowed */
12091 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12092 TEOF, /* corresponds to trailing nul */
12093 TAND, TOR, TENDCASE /* if double occurrence */
12105 setprompt_if(needprompt, 2);
12106 startlinno = g_parsefile->linno;
12107 for (;;) { /* until token or start of word found */
12109 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12113 while ((c = pgetc()) != '\n' && c != PEOF)
12116 } else if (c == '\\') {
12117 if (pgetc() != '\n') {
12119 break; /* return readtoken1(...) */
12125 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12131 p = strchr(xxreadtoken_chars, c);
12133 break; /* return readtoken1(...) */
12135 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12137 if (cc == c) { /* double occurrence? */
12138 p += xxreadtoken_doubles + 1;
12141 #if BASH_REDIR_OUTPUT
12142 if (c == '&' && cc == '>') /* &> */
12143 break; /* return readtoken1(...) */
12148 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12153 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12155 #else /* old xxreadtoken */
12156 #define RETURN(token) return lasttoken = token
12166 setprompt_if(needprompt, 2);
12167 startlinno = g_parsefile->linno;
12168 for (;;) { /* until token or start of word found */
12171 case ' ': case '\t':
12172 IF_ASH_ALIAS(case PEOA:)
12175 while ((c = pgetc()) != '\n' && c != PEOF)
12180 if (pgetc() == '\n') {
12192 if (pgetc() == '&')
12197 if (pgetc() == '|')
12202 if (pgetc() == ';')
12215 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12218 #endif /* old xxreadtoken */
12224 int kwd = checkkwd;
12226 smallint alreadyseen = tokpushback;
12229 #if ENABLE_ASH_ALIAS
12245 if (t != TWORD || quoteflag) {
12250 * check for keywords
12252 if (kwd & CHKKWD) {
12253 const char *const *pp;
12255 pp = findkwd(wordtext);
12257 lasttoken = t = pp - tokname_array;
12258 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12263 if (checkkwd & CHKALIAS) {
12264 #if ENABLE_ASH_ALIAS
12266 ap = lookupalias(wordtext, 1);
12269 pushstring(ap->val, ap);
12279 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12281 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12297 * Read and parse a command. Returns NODE_EOF on end of file.
12298 * (NULL is a valid parse tree indicating a blank line.)
12300 static union node *
12301 parsecmd(int interact)
12306 doprompt = interact;
12307 setprompt_if(doprompt, doprompt);
12313 * Input any here documents.
12318 struct heredoc *here;
12321 here = heredoclist;
12322 heredoclist = NULL;
12325 setprompt_if(needprompt, 2);
12326 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12327 here->eofmark, here->striptabs);
12328 n = stzalloc(sizeof(struct narg));
12329 n->narg.type = NARG;
12330 /*n->narg.next = NULL; - stzalloc did it */
12331 n->narg.text = wordtext;
12332 n->narg.backquote = backquotelist;
12333 here->here->nhere.doc = n;
12340 * called by editline -- any expansions to the prompt should be added here.
12342 #if ENABLE_ASH_EXPAND_PRMT
12343 static const char *
12344 expandstr(const char *ps)
12349 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12350 * and token processing _can_ alter it (delete NULs etc). */
12351 setinputstring((char *)ps);
12353 saveprompt = doprompt;
12355 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12356 doprompt = saveprompt;
12360 n.narg.type = NARG;
12361 n.narg.next = NULL;
12362 n.narg.text = wordtext;
12363 n.narg.backquote = backquotelist;
12365 expandarg(&n, NULL, EXP_QUOTED);
12366 return stackblock();
12371 * Execute a command or commands contained in a string.
12374 evalstring(char *s, int flags)
12376 struct jmploc *volatile savehandler;
12377 struct jmploc jmploc;
12381 struct stackmark smark;
12386 setstackmark(&smark);
12389 /* On exception inside execution loop, we must popfile().
12390 * Try interactively:
12392 * command eval "a=b" # throws "is read only" error
12393 * "command BLTIN" is not supposed to abort (even in non-interactive use).
12394 * But if we skip popfile(), we hit EOF in eval's string, and exit.
12396 savehandler = exception_handler;
12397 ex = setjmp(jmploc.loc);
12400 exception_handler = &jmploc;
12402 while ((n = parsecmd(0)) != NODE_EOF) {
12405 i = evaltree(n, flags);
12408 popstackmark(&smark);
12413 popstackmark(&smark);
12417 exception_handler = savehandler;
12419 longjmp(exception_handler->loc, ex);
12425 * The eval command.
12427 static int FAST_FUNC
12428 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12437 STARTSTACKSTR(concat);
12439 concat = stack_putstr(p, concat);
12443 STPUTC(' ', concat);
12445 STPUTC('\0', concat);
12446 p = grabstackstr(concat);
12448 return evalstring(p, flags & EV_TESTED);
12454 * Read and execute commands.
12455 * "Top" is nonzero for the top level command loop;
12456 * it turns on prompting if the shell is interactive.
12462 struct stackmark smark;
12467 TRACE(("cmdloop(%d) called\n", top));
12471 setstackmark(&smark);
12474 showjobs(SHOW_CHANGED|SHOW_STDERR);
12477 if (iflag && top) {
12481 n = parsecmd(inter);
12483 if (DEBUG > 2 && debug && (n != NODE_EOF))
12486 if (n == NODE_EOF) {
12487 if (!top || numeof >= 50)
12489 if (!stoppedjobs()) {
12492 out2str("\nUse \"exit\" to leave shell.\n");
12495 } else if (nflag == 0) {
12498 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12501 i = evaltree(n, 0);
12505 popstackmark(&smark);
12509 evalskip &= ~SKIPFUNC;
12517 * Take commands from a file. To be compatible we should do a path
12518 * search for the file, which is necessary to find sub-commands.
12521 find_dot_file(char *name)
12524 const char *path = pathval();
12527 /* don't try this for absolute or relative paths */
12528 if (strchr(name, '/'))
12531 while ((fullname = path_advance(&path, name)) != NULL) {
12532 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12534 * Don't bother freeing here, since it will
12535 * be freed by the caller.
12539 if (fullname != name)
12540 stunalloc(fullname);
12543 /* not found in the PATH */
12544 ash_msg_and_raise_error("%s: not found", name);
12548 static int FAST_FUNC
12549 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12551 /* "false; . empty_file; echo $?" should print 0, not 1: */
12555 char *args_need_save;
12556 struct strlist *sp;
12557 volatile struct shparam saveparam;
12559 for (sp = cmdenviron; sp; sp = sp->next)
12560 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12562 nextopt(nullstr); /* handle possible "--" */
12566 /* bash says: "bash: .: filename argument required" */
12567 return 2; /* bash compat */
12570 /* This aborts if file isn't found, which is POSIXly correct.
12571 * bash returns exitcode 1 instead.
12573 fullname = find_dot_file(argv[0]);
12575 args_need_save = argv[0];
12576 if (args_need_save) { /* . FILE ARGS, ARGS exist */
12578 saveparam = shellparam;
12579 shellparam.malloced = 0;
12583 shellparam.nparam = argc;
12584 shellparam.p = argv;
12587 /* This aborts if file can't be opened, which is POSIXly correct.
12588 * bash returns exitcode 1 instead.
12590 setinputfile(fullname, INPUT_PUSH_FILE);
12591 commandname = fullname;
12592 status = cmdloop(0);
12595 if (args_need_save) {
12596 freeparam(&shellparam);
12597 shellparam = saveparam;
12603 static int FAST_FUNC
12604 exitcmd(int argc UNUSED_PARAM, char **argv)
12609 exitstatus = number(argv[1]);
12610 raise_exception(EXEXIT);
12615 * Read a file containing shell functions.
12618 readcmdfile(char *name)
12620 setinputfile(name, INPUT_PUSH_FILE);
12626 /* ============ find_command inplementation */
12629 * Resolve a command name. If you change this routine, you may have to
12630 * change the shellexec routine as well.
12633 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12635 struct tblentry *cmdp;
12642 struct builtincmd *bcmd;
12644 /* If name contains a slash, don't use PATH or hash table */
12645 if (strchr(name, '/') != NULL) {
12646 entry->u.index = -1;
12647 if (act & DO_ABS) {
12648 while (stat(name, &statb) < 0) {
12650 if (errno == EINTR)
12653 entry->cmdtype = CMDUNKNOWN;
12657 entry->cmdtype = CMDNORMAL;
12661 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12663 updatetbl = (path == pathval());
12666 if (strstr(path, "%builtin") != NULL)
12667 act |= DO_ALTBLTIN;
12670 /* If name is in the table, check answer will be ok */
12671 cmdp = cmdlookup(name, 0);
12672 if (cmdp != NULL) {
12675 switch (cmdp->cmdtype) {
12693 } else if (cmdp->rehash == 0)
12694 /* if not invalidated by cd, we're done */
12698 /* If %builtin not in path, check for builtin next */
12699 bcmd = find_builtin(name);
12701 if (IS_BUILTIN_REGULAR(bcmd))
12702 goto builtin_success;
12703 if (act & DO_ALTPATH) {
12704 if (!(act & DO_ALTBLTIN))
12705 goto builtin_success;
12706 } else if (builtinloc <= 0) {
12707 goto builtin_success;
12711 #if ENABLE_FEATURE_SH_STANDALONE
12713 int applet_no = find_applet_by_name(name);
12714 if (applet_no >= 0) {
12715 entry->cmdtype = CMDNORMAL;
12716 entry->u.index = -2 - applet_no;
12722 /* We have to search path. */
12723 prev = -1; /* where to start */
12724 if (cmdp && cmdp->rehash) { /* doing a rehash */
12725 if (cmdp->cmdtype == CMDBUILTIN)
12728 prev = cmdp->param.index;
12734 while ((fullname = path_advance(&path, name)) != NULL) {
12735 stunalloc(fullname);
12736 /* NB: code below will still use fullname
12737 * despite it being "unallocated" */
12740 if (prefix(pathopt, "builtin")) {
12742 goto builtin_success;
12745 if ((act & DO_NOFUNC)
12746 || !prefix(pathopt, "func")
12747 ) { /* ignore unimplemented options */
12751 /* if rehash, don't redo absolute path names */
12752 if (fullname[0] == '/' && idx <= prev) {
12755 TRACE(("searchexec \"%s\": no change\n", name));
12758 while (stat(fullname, &statb) < 0) {
12760 if (errno == EINTR)
12763 if (errno != ENOENT && errno != ENOTDIR)
12767 e = EACCES; /* if we fail, this will be the error */
12768 if (!S_ISREG(statb.st_mode))
12770 if (pathopt) { /* this is a %func directory */
12771 stalloc(strlen(fullname) + 1);
12772 /* NB: stalloc will return space pointed by fullname
12773 * (because we don't have any intervening allocations
12774 * between stunalloc above and this stalloc) */
12775 readcmdfile(fullname);
12776 cmdp = cmdlookup(name, 0);
12777 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12778 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12779 stunalloc(fullname);
12782 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12784 entry->cmdtype = CMDNORMAL;
12785 entry->u.index = idx;
12789 cmdp = cmdlookup(name, 1);
12790 cmdp->cmdtype = CMDNORMAL;
12791 cmdp->param.index = idx;
12796 /* We failed. If there was an entry for this command, delete it */
12797 if (cmdp && updatetbl)
12798 delete_cmd_entry();
12800 ash_msg("%s: %s", name, errmsg(e, "not found"));
12801 entry->cmdtype = CMDUNKNOWN;
12806 entry->cmdtype = CMDBUILTIN;
12807 entry->u.cmd = bcmd;
12811 cmdp = cmdlookup(name, 1);
12812 cmdp->cmdtype = CMDBUILTIN;
12813 cmdp->param.cmd = bcmd;
12817 entry->cmdtype = cmdp->cmdtype;
12818 entry->u = cmdp->param;
12823 * The trap builtin.
12825 static int FAST_FUNC
12826 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12830 int signo, exitcode;
12835 for (signo = 0; signo < NSIG; signo++) {
12836 char *tr = trap_ptr[signo];
12838 /* note: bash adds "SIG", but only if invoked
12839 * as "bash". If called as "sh", or if set -o posix,
12840 * then it prints short signal names.
12841 * We are printing short names: */
12842 out1fmt("trap -- %s %s\n",
12844 get_signame(signo));
12845 /* trap_ptr != trap only if we are in special-cased `trap` code.
12846 * In this case, we will exit very soon, no need to free(). */
12847 /* if (trap_ptr != trap && tp[0]) */
12852 if (trap_ptr != trap) {
12865 signo = get_signum(*ap);
12867 /* Mimic bash message exactly */
12868 ash_msg("%s: invalid signal specification", *ap);
12874 if (LONE_DASH(action))
12877 if (action[0]) /* not NULL and not "" and not "-" */
12878 may_have_traps = 1;
12879 action = ckstrdup(action);
12883 trap[signo] = action;
12894 /* ============ Builtins */
12896 #if ENABLE_ASH_HELP
12897 static int FAST_FUNC
12898 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12904 "Built-in commands:\n"
12905 "------------------\n");
12906 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12907 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12908 builtintab[i].name + 1);
12914 # if ENABLE_FEATURE_SH_STANDALONE
12916 const char *a = applet_names;
12918 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12923 while (*a++ != '\0')
12928 newline_and_flush(stdout);
12929 return EXIT_SUCCESS;
12934 static int FAST_FUNC
12935 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12937 show_history(line_input_state);
12938 return EXIT_SUCCESS;
12943 * The export and readonly commands.
12945 static int FAST_FUNC
12946 exportcmd(int argc UNUSED_PARAM, char **argv)
12956 /* "readonly" in bash accepts, but ignores -n.
12957 * We do the same: it saves a conditional in nextopt's param.
12960 while ((opt = nextopt("np")) != '\0') {
12962 flag_off = VEXPORT;
12965 if (argv[0][0] == 'r') {
12967 flag_off = 0; /* readonly ignores -n */
12969 flag_off = ~flag_off;
12971 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12977 p = strchr(name, '=');
12981 vp = *findvar(hashvar(name), name);
12983 vp->flags = ((vp->flags | flag) & flag_off);
12987 setvar(name, p, (flag & flag_off));
12988 } while ((name = *++aptr) != NULL);
12993 /* No arguments. Show the list of exported or readonly vars.
12996 showvars(argv[0], flag, 0);
13001 * Delete a function if it exists.
13004 unsetfunc(const char *name)
13006 struct tblentry *cmdp;
13008 cmdp = cmdlookup(name, 0);
13009 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
13010 delete_cmd_entry();
13014 * The unset builtin command. We unset the function before we unset the
13015 * variable to allow a function to be unset when there is a readonly variable
13016 * with the same name.
13018 static int FAST_FUNC
13019 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13026 while ((i = nextopt("vf")) != 0) {
13030 for (ap = argptr; *ap; ap++) {
13043 static const unsigned char timescmd_str[] ALIGN1 = {
13044 ' ', offsetof(struct tms, tms_utime),
13045 '\n', offsetof(struct tms, tms_stime),
13046 ' ', offsetof(struct tms, tms_cutime),
13047 '\n', offsetof(struct tms, tms_cstime),
13050 static int FAST_FUNC
13051 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13053 unsigned long clk_tck, s, t;
13054 const unsigned char *p;
13057 clk_tck = bb_clk_tck();
13062 t = *(clock_t *)(((char *) &buf) + p[1]);
13065 out1fmt("%lum%lu.%03lus%c",
13067 (t * 1000) / clk_tck,
13075 #if ENABLE_FEATURE_SH_MATH
13077 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13078 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13080 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13082 static int FAST_FUNC
13083 letcmd(int argc UNUSED_PARAM, char **argv)
13089 ash_msg_and_raise_error("expression expected");
13091 i = ash_arith(*argv);
13099 * The read builtin. Options:
13100 * -r Do not interpret '\' specially
13101 * -s Turn off echo (tty only)
13102 * -n NCHARS Read NCHARS max
13103 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13104 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13105 * -u FD Read from given FD instead of fd 0
13106 * This uses unbuffered input, which may be avoidable in some cases.
13107 * TODO: bash also has:
13108 * -a ARRAY Read into array[0],[1],etc
13109 * -d DELIM End on DELIM char, not newline
13110 * -e Use line editing (tty only)
13112 static int FAST_FUNC
13113 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13115 char *opt_n = NULL;
13116 char *opt_p = NULL;
13117 char *opt_t = NULL;
13118 char *opt_u = NULL;
13119 int read_flags = 0;
13123 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13132 read_flags |= BUILTIN_READ_SILENT;
13138 read_flags |= BUILTIN_READ_RAW;
13148 /* "read -s" needs to save/restore termios, can't allow ^C
13149 * to jump out of it.
13152 r = shell_builtin_read(setvar0,
13154 bltinlookup("IFS"), /* can be NULL */
13163 if ((uintptr_t)r > 1)
13164 ash_msg_and_raise_error(r);
13166 return (uintptr_t)r;
13169 static int FAST_FUNC
13170 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13172 static const char permuser[3] ALIGN1 = "ogu";
13175 int symbolic_mode = 0;
13177 while (nextopt("S") != '\0') {
13186 if (*argptr == NULL) {
13187 if (symbolic_mode) {
13188 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13195 *p++ = permuser[i];
13197 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13198 if (!(mask & 0400)) *p++ = 'r';
13199 if (!(mask & 0200)) *p++ = 'w';
13200 if (!(mask & 0100)) *p++ = 'x';
13208 out1fmt("%04o\n", mask);
13211 char *modestr = *argptr;
13212 /* numeric umasks are taken as-is */
13213 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13214 if (!isdigit(modestr[0]))
13216 mask = bb_parse_mode(modestr, mask);
13217 if ((unsigned)mask > 0777) {
13218 ash_msg_and_raise_error("illegal mode: %s", modestr);
13220 if (!isdigit(modestr[0]))
13227 static int FAST_FUNC
13228 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13230 return shell_builtin_ulimit(argv);
13233 /* ============ main() and helpers */
13236 * Called to exit the shell.
13245 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13246 save_history(line_input_state);
13248 status = exitstatus;
13249 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13250 if (setjmp(loc.loc)) {
13251 if (exception_type == EXEXIT)
13252 status = exitstatus;
13255 exception_handler = &loc;
13261 /*free(p); - we'll exit soon */
13264 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13265 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13268 flush_stdout_stderr();
13276 /* we will never free this */
13277 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13279 sigmode[SIGCHLD - 1] = S_DFL;
13280 setsignal(SIGCHLD);
13282 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13283 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13285 signal(SIGHUP, SIG_DFL);
13290 struct stat st1, st2;
13293 for (envp = environ; envp && *envp; envp++) {
13294 p = endofname(*envp);
13295 if (p != *envp && *p == '=') {
13296 setvareq(*envp, VEXPORT|VTEXTFIXED);
13300 setvareq((char*)defoptindvar, VTEXTFIXED);
13302 setvar0("PPID", utoa(getppid()));
13304 p = lookupvar("SHLVL");
13305 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13307 #if BASH_HOSTNAME_VAR
13308 if (!lookupvar("HOSTNAME")) {
13309 struct utsname uts;
13311 setvar0("HOSTNAME", uts.nodename);
13314 p = lookupvar("PWD");
13316 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13317 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13327 //usage:#define ash_trivial_usage
13328 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13329 //usage:#define ash_full_usage "\n\n"
13330 //usage: "Unix shell interpreter"
13333 * Process the shell command line arguments.
13336 procargs(char **argv)
13339 const char *xminusc;
13344 /* if (xargv[0]) - mmm, this is always true! */
13346 for (i = 0; i < NOPTS; i++)
13349 if (options(/*cmdline:*/ 1)) {
13350 /* it already printed err message */
13351 raise_exception(EXERROR);
13355 if (*xargv == NULL) {
13357 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13360 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13364 for (i = 0; i < NOPTS; i++)
13365 if (optlist[i] == 2)
13370 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13375 } else if (!sflag) {
13376 setinputfile(*xargv, 0);
13379 commandname = arg0;
13382 shellparam.p = xargv;
13383 #if ENABLE_ASH_GETOPTS
13384 shellparam.optind = 1;
13385 shellparam.optoff = -1;
13387 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13389 shellparam.nparam++;
13396 * Read /etc/profile, ~/.profile, $ENV.
13399 read_profile(const char *name)
13401 name = expandstr(name);
13402 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13409 * This routine is called when an error or an interrupt occurs in an
13410 * interactive shell and control is returned to the main command loop.
13411 * (In dash, this function is auto-generated by build machinery).
13420 /* from expand.c: */
13423 /* from input.c: */
13424 g_parsefile->left_in_buffer = 0;
13425 g_parsefile->left_in_line = 0; /* clear input buffer */
13428 /* from redir.c: */
13430 popredir(/*drop:*/ 0, /*restore:*/ 0);
13434 static short profile_buf[16384];
13435 extern int etext();
13439 * Main routine. We initialize things, parse the arguments, execute
13440 * profiles if we're a login shell, and then call cmdloop to execute
13441 * commands. The setjmp call sets up the location to jump to when an
13442 * exception occurs. When an exception occurs the variable "state"
13443 * is used to figure out how far we had gotten.
13445 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13446 int ash_main(int argc UNUSED_PARAM, char **argv)
13448 volatile smallint state;
13449 struct jmploc jmploc;
13450 struct stackmark smark;
13452 /* Initialize global data */
13456 #if ENABLE_ASH_ALIAS
13462 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13465 #if ENABLE_FEATURE_EDITING
13466 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13469 if (setjmp(jmploc.loc)) {
13475 e = exception_type;
13477 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13481 newline_and_flush(stderr);
13484 popstackmark(&smark);
13485 FORCE_INT_ON; /* enable interrupts */
13494 exception_handler = &jmploc;
13495 rootpid = getpid();
13498 setstackmark(&smark);
13501 TRACE(("Shell args: "));
13502 trace_puts_args(argv);
13505 if (argv[0] && argv[0][0] == '-')
13511 read_profile("/etc/profile");
13514 hp = lookupvar("HOME");
13516 read_profile("$HOME/.profile");
13522 getuid() == geteuid() && getgid() == getegid() &&
13526 const char *shinit = lookupvar("ENV");
13527 if (shinit != NULL && *shinit != '\0')
13528 read_profile(shinit);
13530 popstackmark(&smark);
13534 /* evalstring pushes parsefile stack.
13535 * Ensure we don't falsely claim that 0 (stdin)
13536 * is one of stacked source fds.
13537 * Testcase: ash -c 'exec 1>&0' must not complain. */
13538 // if (!sflag) g_parsefile->pf_fd = -1;
13539 // ^^ not necessary since now we special-case fd 0
13540 // in is_hidden_fd() to not be considered "hidden fd"
13541 evalstring(minusc, 0);
13544 if (sflag || minusc == NULL) {
13545 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13547 const char *hp = lookupvar("HISTFILE");
13549 hp = lookupvar("HOME");
13551 hp = concat_path_file(hp, ".ash_history");
13552 setvar0("HISTFILE", hp);
13554 hp = lookupvar("HISTFILE");
13558 line_input_state->hist_file = hp;
13559 # if ENABLE_FEATURE_SH_HISTFILESIZE
13560 hp = lookupvar("HISTFILESIZE");
13561 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13565 state4: /* XXX ??? - why isn't this before the "if" statement */
13573 extern void _mcleanup(void);
13577 TRACE(("End of main reached\n"));
13584 * Copyright (c) 1989, 1991, 1993, 1994
13585 * The Regents of the University of California. All rights reserved.
13587 * This code is derived from software contributed to Berkeley by
13588 * Kenneth Almquist.
13590 * Redistribution and use in source and binary forms, with or without
13591 * modification, are permitted provided that the following conditions
13593 * 1. Redistributions of source code must retain the above copyright
13594 * notice, this list of conditions and the following disclaimer.
13595 * 2. Redistributions in binary form must reproduce the above copyright
13596 * notice, this list of conditions and the following disclaimer in the
13597 * documentation and/or other materials provided with the distribution.
13598 * 3. Neither the name of the University nor the names of its contributors
13599 * may be used to endorse or promote products derived from this software
13600 * without specific prior written permission.
13602 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13603 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13604 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13605 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13606 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13607 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13608 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13609 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13610 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13611 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF