1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
19 //config: bool "ash (77 kb)"
21 //config: depends on !NOMMU
23 //config: The most complete and most pedantically correct shell included with
24 //config: busybox. This shell is actually a derivative of the Debian 'dash'
25 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
26 //config: (written by Kenneth Almquist) from NetBSD.
28 //config:# ash options
29 //config:# note: Don't remove !NOMMU part in the next line; it would break
30 //config:# menuconfig's indenting.
31 //config:if !NOMMU && (ASH || SH_IS_ASH || BASH_IS_ASH)
33 //config:config ASH_OPTIMIZE_FOR_SIZE
34 //config: bool "Optimize for size instead of speed"
36 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
38 //config:config ASH_INTERNAL_GLOB
39 //config: bool "Use internal glob() implementation"
40 //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
41 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
43 //config: Do not use glob() function from libc, use internal implementation.
44 //config: Use this if you are getting "glob.h: No such file or directory"
45 //config: or similar build errors.
46 //config: Note that as of now (2017-01), uclibc and musl glob() both have bugs
47 //config: which would break ash if you select N here.
49 //config:config ASH_BASH_COMPAT
50 //config: bool "bash-compatible extensions"
52 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
54 //config:config ASH_JOB_CONTROL
55 //config: bool "Job control"
57 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
59 //config:config ASH_ALIAS
60 //config: bool "Alias support"
62 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
64 //config:config ASH_RANDOM_SUPPORT
65 //config: bool "Pseudorandom generator and $RANDOM variable"
67 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
69 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
70 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
71 //config: You can reset the generator by using a specified start value.
72 //config: After "unset RANDOM" the generator will switch off and this
73 //config: variable will no longer have special treatment.
75 //config:config ASH_EXPAND_PRMT
76 //config: bool "Expand prompt string"
78 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
80 //config: $PS# may contain volatile content, such as backquote commands.
81 //config: This option recreates the prompt string from the environment
82 //config: variable each time it is displayed.
84 //config:config ASH_IDLE_TIMEOUT
85 //config: bool "Idle timeout variable $TMOUT"
87 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
89 //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
91 //config:config ASH_MAIL
92 //config: bool "Check for new mail in interactive shell"
94 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
96 //config: Enable "check for new mail" function:
97 //config: if set, $MAIL file and $MAILPATH list of files
98 //config: are checked for mtime changes, and "you have mail"
99 //config: message is printed if change is detected.
101 //config:config ASH_ECHO
102 //config: bool "echo builtin"
104 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
106 //config:config ASH_PRINTF
107 //config: bool "printf builtin"
109 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
111 //config:config ASH_TEST
112 //config: bool "test builtin"
114 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
116 //config:config ASH_HELP
117 //config: bool "help builtin"
119 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
121 //config:config ASH_GETOPTS
122 //config: bool "getopts builtin"
124 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
126 //config:config ASH_CMDCMD
127 //config: bool "command builtin"
129 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
131 //config: Enable support for the 'command' builtin, which allows
132 //config: you to run the specified command or builtin,
133 //config: even when there is a function with the same name.
135 //config:endif # ash options
137 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
138 // APPLET_ODDNAME:name main location suid_type help
139 //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
140 //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
142 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
143 //kbuild:lib-$(CONFIG_SH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
144 //kbuild:lib-$(CONFIG_BASH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
145 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
148 * DEBUG=1 to compile in debugging ('set -o debug' turns on)
149 * DEBUG=2 to compile in and turn on debugging.
150 * When debugging is on ("set -o debug" was executed, or DEBUG=2),
151 * debugging info is written to ./trace, quit signal generates core dump.
154 /* Tweak debug output verbosity here */
158 #define DEBUG_INTONOFF 0
162 #define JOBS ENABLE_ASH_JOB_CONTROL
166 #include <sys/times.h>
167 #include <sys/utsname.h> /* for setting $HOSTNAME */
168 #include "busybox.h" /* for applet_names */
170 /* So far, all bash compat is controlled by one config option */
171 /* Separate defines document which part of code implements what */
172 /* function keyword */
173 #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
174 #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
176 #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
177 #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
179 #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
180 #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
181 #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
182 #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
183 #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
184 #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
186 #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
187 #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
188 #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
189 #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
190 #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
192 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
193 /* Bionic at least up to version 24 has no glob() */
194 # undef ENABLE_ASH_INTERNAL_GLOB
195 # define ENABLE_ASH_INTERNAL_GLOB 1
198 #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
199 # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
200 # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
201 # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
202 # error glob() should unbackslash them and match. uClibc does not unbackslash,
203 # error fails to match dirname, subsequently not expanding <pattern> in it.
205 // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
206 // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
209 #if !ENABLE_ASH_INTERNAL_GLOB
214 #include "shell_common.h"
215 #if ENABLE_FEATURE_SH_MATH
218 #if ENABLE_ASH_RANDOM_SUPPORT
221 # define CLEAR_RANDOM_T(rnd) ((void)0)
224 #include "NUM_APPLETS.h"
226 /* STANDALONE does not make sense, and won't compile */
227 # undef CONFIG_FEATURE_SH_STANDALONE
228 # undef ENABLE_FEATURE_SH_STANDALONE
229 # undef IF_FEATURE_SH_STANDALONE
230 # undef IF_NOT_FEATURE_SH_STANDALONE
231 # define ENABLE_FEATURE_SH_STANDALONE 0
232 # define IF_FEATURE_SH_STANDALONE(...)
233 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
237 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
241 # error "Do not even bother, ash will not run on NOMMU machine"
245 /* ============ Hash table sizes. Configurable. */
249 #define CMDTABLESIZE 31 /* should be prime */
252 /* ============ Shell options */
254 static const char *const optletters_optnames[] = {
278 #define optletters(n) optletters_optnames[n][0]
279 #define optnames(n) (optletters_optnames[n] + 1)
281 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
284 /* ============ Misc data */
286 #define msg_illnum "Illegal number: %s"
289 * We enclose jmp_buf in a structure so that we can declare pointers to
290 * jump locations. The global variable handler contains the location to
291 * jump to when an exception occurs, and the global variable exception_type
292 * contains a code identifying the exception. To implement nested
293 * exception handlers, the user should save the value of handler on entry
294 * to an inner scope, set handler to point to a jmploc structure for the
295 * inner scope, and restore handler on exit from the scope.
301 struct globals_misc {
302 uint8_t exitstatus; /* exit status of last command */
303 uint8_t back_exitstatus;/* exit status of backquoted command */
304 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
305 int rootpid; /* pid of main shell */
306 /* shell level: 0 for the main shell, 1 for its children, and so on */
308 #define rootshell (!shlvl)
309 char *minusc; /* argument to -c option */
311 char *curdir; // = nullstr; /* current working directory */
312 char *physdir; // = nullstr; /* physical working directory */
314 char *arg0; /* value of $0 */
316 struct jmploc *exception_handler;
318 volatile int suppress_int; /* counter */
319 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
320 volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
321 volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
322 smallint exception_type; /* kind of exception (0..5) */
324 #define EXINT 0 /* SIGINT received */
325 #define EXERROR 1 /* a generic error */
326 #define EXEXIT 4 /* exit the shell */
329 char nullstr[1]; /* zero length string */
332 #define eflag optlist[0]
333 #define fflag optlist[1]
334 #define Iflag optlist[2]
335 #define iflag optlist[3]
336 #define mflag optlist[4]
337 #define nflag optlist[5]
338 #define sflag optlist[6]
339 #define xflag optlist[7]
340 #define vflag optlist[8]
341 #define Cflag optlist[9]
342 #define aflag optlist[10]
343 #define bflag optlist[11]
344 #define uflag optlist[12]
345 #define viflag optlist[13]
347 # define pipefail optlist[14]
352 # define nolog optlist[14 + BASH_PIPEFAIL]
353 # define debug optlist[15 + BASH_PIPEFAIL]
356 /* trap handler commands */
358 * Sigmode records the current value of the signal handlers for the various
359 * modes. A value of zero means that the current handler is not known.
360 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
362 char sigmode[NSIG - 1];
363 #define S_DFL 1 /* default signal handling (SIG_DFL) */
364 #define S_CATCH 2 /* signal is caught */
365 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
366 #define S_HARD_IGN 4 /* signal is ignored permanently */
368 /* indicates specified signal received */
369 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
370 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
372 char **trap_ptr; /* used only by "trap hack" */
374 /* Rarely referenced stuff */
375 #if ENABLE_ASH_RANDOM_SUPPORT
378 pid_t backgndpid; /* pid of last background process */
380 extern struct globals_misc *const ash_ptr_to_globals_misc;
381 #define G_misc (*ash_ptr_to_globals_misc)
382 #define exitstatus (G_misc.exitstatus )
383 #define back_exitstatus (G_misc.back_exitstatus )
384 #define job_warning (G_misc.job_warning)
385 #define rootpid (G_misc.rootpid )
386 #define shlvl (G_misc.shlvl )
387 #define minusc (G_misc.minusc )
388 #define curdir (G_misc.curdir )
389 #define physdir (G_misc.physdir )
390 #define arg0 (G_misc.arg0 )
391 #define exception_handler (G_misc.exception_handler)
392 #define exception_type (G_misc.exception_type )
393 #define suppress_int (G_misc.suppress_int )
394 #define pending_int (G_misc.pending_int )
395 #define got_sigchld (G_misc.got_sigchld )
396 #define pending_sig (G_misc.pending_sig )
397 #define isloginsh (G_misc.isloginsh )
398 #define nullstr (G_misc.nullstr )
399 #define optlist (G_misc.optlist )
400 #define sigmode (G_misc.sigmode )
401 #define gotsig (G_misc.gotsig )
402 #define may_have_traps (G_misc.may_have_traps )
403 #define trap (G_misc.trap )
404 #define trap_ptr (G_misc.trap_ptr )
405 #define random_gen (G_misc.random_gen )
406 #define backgndpid (G_misc.backgndpid )
407 #define INIT_G_misc() do { \
408 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
416 /* ============ DEBUG */
418 static void trace_printf(const char *fmt, ...);
419 static void trace_vprintf(const char *fmt, va_list va);
420 # define TRACE(param) trace_printf param
421 # define TRACEV(param) trace_vprintf param
422 # define close(fd) do { \
424 if (close(dfd) < 0) \
425 bb_error_msg("bug on %d: closing %d(0x%x)", \
426 __LINE__, dfd, dfd); \
429 # define TRACE(param)
430 # define TRACEV(param)
434 /* ============ Utility functions */
435 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
436 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
439 isdigit_str9(const char *str)
441 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
442 while (--maxlen && isdigit(*str))
444 return (*str == '\0');
448 var_end(const char *var)
457 /* ============ Interrupts / exceptions */
459 static void exitshell(void) NORETURN;
462 * These macros allow the user to suspend the handling of interrupt signals
463 * over a period of time. This is similar to SIGHOLD or to sigblock, but
464 * much more efficient and portable. (But hacking the kernel is so much
465 * more fun than worrying about efficiency and portability. :-))
468 # define INT_OFF do { \
469 TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
474 # define INT_OFF do { \
481 * Called to raise an exception. Since C doesn't include exceptions, we
482 * just do a longjmp to the exception handler. The type of exception is
483 * stored in the global variable "exception_type".
485 static void raise_exception(int) NORETURN;
487 raise_exception(int e)
490 if (exception_handler == NULL)
495 longjmp(exception_handler->loc, 1);
498 #define raise_exception(e) do { \
499 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
500 raise_exception(e); \
505 * Called when a SIGINT is received. (If the user specifies
506 * that SIGINT is to be trapped or ignored using the trap builtin, then
507 * this routine is not called.) Suppressint is nonzero when interrupts
508 * are held using the INT_OFF macro. (The test for iflag is just
509 * defensive programming.)
511 static void raise_interrupt(void) NORETURN;
513 raise_interrupt(void)
516 /* Signal is not automatically unmasked after it is raised,
517 * do it ourself - unmask all signals */
518 sigprocmask_allsigs(SIG_UNBLOCK);
519 /* pending_sig = 0; - now done in signal_handler() */
521 if (!(rootshell && iflag)) {
522 /* Kill ourself with SIGINT */
523 signal(SIGINT, SIG_DFL);
526 /* bash: ^C even on empty command line sets $? */
527 exitstatus = SIGINT + 128;
528 raise_exception(EXINT);
532 #define raise_interrupt() do { \
533 TRACE(("raising interrupt on line %d\n", __LINE__)); \
538 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
542 if (--suppress_int == 0 && pending_int) {
547 # define INT_ON do { \
548 TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
552 # define INT_ON int_on()
554 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
562 #define FORCE_INT_ON force_int_on()
564 #define SAVE_INT(v) ((v) = suppress_int)
566 #define RESTORE_INT(v) do { \
568 suppress_int = (v); \
569 if (suppress_int == 0 && pending_int) \
574 /* ============ Stdout/stderr output */
577 outstr(const char *p, FILE *file)
585 flush_stdout_stderr(void)
592 /* Was called outcslow(c,FILE*), but c was always '\n' */
594 newline_and_flush(FILE *dest)
602 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
604 out1fmt(const char *fmt, ...)
611 r = vprintf(fmt, ap);
617 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
619 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
626 ret = vsnprintf(outbuf, length, fmt, ap);
633 out1str(const char *p)
639 out2str(const char *p)
642 flush_stdout_stderr();
646 /* ============ Parser structures */
648 /* control characters in argument strings */
649 #define CTL_FIRST CTLESC
650 #define CTLESC ((unsigned char)'\201') /* escape next character */
651 #define CTLVAR ((unsigned char)'\202') /* variable defn */
652 #define CTLENDVAR ((unsigned char)'\203')
653 #define CTLBACKQ ((unsigned char)'\204')
654 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
655 #define CTLENDARI ((unsigned char)'\207')
656 #define CTLQUOTEMARK ((unsigned char)'\210')
657 #define CTL_LAST CTLQUOTEMARK
659 /* variable substitution byte (follows CTLVAR) */
660 #define VSTYPE 0x0f /* type of variable substitution */
661 #define VSNUL 0x10 /* colon--treat the empty string as unset */
663 /* values of VSTYPE field */
664 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
665 #define VSMINUS 0x2 /* ${var-text} */
666 #define VSPLUS 0x3 /* ${var+text} */
667 #define VSQUESTION 0x4 /* ${var?message} */
668 #define VSASSIGN 0x5 /* ${var=text} */
669 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
670 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
671 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
672 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
673 #define VSLENGTH 0xa /* ${#var} */
675 #define VSSUBSTR 0xc /* ${var:position:length} */
677 #if BASH_PATTERN_SUBST
678 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
679 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
682 static const char dolatstr[] ALIGN1 = {
683 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
685 #define DOLATSTRLEN 6
704 #if BASH_REDIR_OUTPUT
721 smallint type; /* Nxxxx */
724 union node *redirect;
729 smallint pipe_backgnd;
730 struct nodelist *cmdlist;
736 union node *redirect;
749 union node *elsepart;
776 struct nodelist *backquote;
779 /* nfile and ndup layout must match!
780 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
781 * that it is actually NTO2 (>&file), and change its type.
798 char *_unused_expfname;
817 struct nredir nredir;
818 struct nbinary nbinary;
822 struct nclist nclist;
831 * NODE_EOF is returned by parsecmd when it encounters an end of file.
832 * It must be distinct from NULL.
834 #define NODE_EOF ((union node *) -1L)
837 struct nodelist *next;
850 freefunc(struct funcnode *f)
852 if (f && --f->count < 0)
857 /* ============ Debugging output */
861 static FILE *tracefile;
864 trace_printf(const char *fmt, ...)
871 fprintf(tracefile, "%u ", (int) time(NULL));
873 fprintf(tracefile, "[%u] ", (int) getpid());
875 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
877 vfprintf(tracefile, fmt, va);
882 trace_vprintf(const char *fmt, va_list va)
886 vfprintf(tracefile, fmt, va);
887 fprintf(tracefile, "\n");
891 trace_puts(const char *s)
899 trace_puts_quoted(char *s)
906 putc('"', tracefile);
907 for (p = s; *p; p++) {
908 switch ((unsigned char)*p) {
909 case '\n': c = 'n'; goto backslash;
910 case '\t': c = 't'; goto backslash;
911 case '\r': c = 'r'; goto backslash;
912 case '\"': c = '\"'; goto backslash;
913 case '\\': c = '\\'; goto backslash;
914 case CTLESC: c = 'e'; goto backslash;
915 case CTLVAR: c = 'v'; goto backslash;
916 case CTLBACKQ: c = 'q'; goto backslash;
918 putc('\\', tracefile);
922 if (*p >= ' ' && *p <= '~')
925 putc('\\', tracefile);
926 putc((*p >> 6) & 03, tracefile);
927 putc((*p >> 3) & 07, tracefile);
928 putc(*p & 07, tracefile);
933 putc('"', tracefile);
937 trace_puts_args(char **ap)
944 trace_puts_quoted(*ap);
946 putc('\n', tracefile);
949 putc(' ', tracefile);
964 /* leave open because libedit might be using it */
967 strcpy(s, "./trace");
969 if (!freopen(s, "a", tracefile)) {
970 fprintf(stderr, "Can't re-open %s\n", s);
975 tracefile = fopen(s, "a");
976 if (tracefile == NULL) {
977 fprintf(stderr, "Can't open %s\n", s);
983 flags = fcntl(fileno(tracefile), F_GETFL);
985 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
987 setlinebuf(tracefile);
988 fputs("\nTracing started.\n", tracefile);
992 indent(int amount, char *pfx, FILE *fp)
996 for (i = 0; i < amount; i++) {
997 if (pfx && i == amount - 1)
1003 /* little circular references here... */
1004 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
1007 sharg(union node *arg, FILE *fp)
1010 struct nodelist *bqlist;
1011 unsigned char subtype;
1013 if (arg->type != NARG) {
1014 out1fmt("<node type %d>\n", arg->type);
1017 bqlist = arg->narg.backquote;
1018 for (p = arg->narg.text; *p; p++) {
1019 switch ((unsigned char)*p) {
1028 if (subtype == VSLENGTH)
1036 if (subtype & VSNUL)
1039 switch (subtype & VSTYPE) {
1065 case VSTRIMRIGHTMAX:
1072 out1fmt("<subtype %d>", subtype);
1081 shtree(bqlist->n, -1, NULL, fp);
1092 shcmd(union node *cmd, FILE *fp)
1100 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1106 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1110 switch (np->nfile.type) {
1111 case NTO: s = ">>"+1; dftfd = 1; break;
1112 case NCLOBBER: s = ">|"; dftfd = 1; break;
1113 case NAPPEND: s = ">>"; dftfd = 1; break;
1114 #if BASH_REDIR_OUTPUT
1117 case NTOFD: s = ">&"; dftfd = 1; break;
1118 case NFROM: s = "<"; break;
1119 case NFROMFD: s = "<&"; break;
1120 case NFROMTO: s = "<>"; break;
1121 default: s = "*error*"; break;
1123 if (np->nfile.fd != dftfd)
1124 fprintf(fp, "%d", np->nfile.fd);
1126 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1127 fprintf(fp, "%d", np->ndup.dupfd);
1129 sharg(np->nfile.fname, fp);
1136 shtree(union node *n, int ind, char *pfx, FILE *fp)
1138 struct nodelist *lp;
1144 indent(ind, pfx, fp);
1146 if (n == NODE_EOF) {
1161 shtree(n->nbinary.ch1, ind, NULL, fp);
1164 shtree(n->nbinary.ch2, ind, NULL, fp);
1172 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1173 shtree(lp->n, 0, NULL, fp);
1177 if (n->npipe.pipe_backgnd)
1183 fprintf(fp, "<node type %d>", n->type);
1191 showtree(union node *n)
1193 trace_puts("showtree called\n");
1194 shtree(n, 1, NULL, stderr);
1200 /* ============ Parser data */
1203 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1206 struct strlist *next;
1213 struct strpush *prev; /* preceding string on stack */
1215 int prev_left_in_line;
1216 #if ENABLE_ASH_ALIAS
1217 struct alias *ap; /* if push was associated with an alias */
1219 char *string; /* remember the string since it may change */
1221 /* Remember last two characters for pungetc. */
1224 /* Number of outstanding calls to pungetc. */
1229 struct parsefile *prev; /* preceding file on stack */
1230 int linno; /* current line */
1231 int pf_fd; /* file descriptor (or -1 if string) */
1232 int left_in_line; /* number of chars left in this line */
1233 int left_in_buffer; /* number of chars left in this buffer past the line */
1234 char *next_to_pgetc; /* next char in buffer */
1235 char *buf; /* input buffer */
1236 struct strpush *strpush; /* for pushing strings at this level */
1237 struct strpush basestrpush; /* so pushing one is fast */
1239 /* Remember last two characters for pungetc. */
1242 /* Number of outstanding calls to pungetc. */
1246 static struct parsefile basepf; /* top level input file */
1247 static struct parsefile *g_parsefile = &basepf; /* current input file */
1248 static int startlinno; /* line # where last token started */
1249 static char *commandname; /* currently executing command */
1250 static struct strlist *cmdenviron; /* environment for builtin command */
1253 /* ============ Message printing */
1256 ash_vmsg(const char *msg, va_list ap)
1258 fprintf(stderr, "%s: ", arg0);
1260 if (strcmp(arg0, commandname))
1261 fprintf(stderr, "%s: ", commandname);
1262 if (!iflag || g_parsefile->pf_fd > 0)
1263 fprintf(stderr, "line %d: ", startlinno);
1265 vfprintf(stderr, msg, ap);
1266 newline_and_flush(stderr);
1270 * Exverror is called to raise the error exception. If the second argument
1271 * is not NULL then error prints an error message using printf style
1272 * formatting. It then raises the error exception.
1274 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1276 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1280 TRACE(("ash_vmsg_and_raise(%d):", cond));
1283 TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
1288 flush_stdout_stderr();
1289 raise_exception(cond);
1293 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1295 ash_msg_and_raise_error(const char *msg, ...)
1302 ash_vmsg_and_raise(EXERROR, msg, ap);
1307 static void raise_error_syntax(const char *) NORETURN;
1309 raise_error_syntax(const char *msg)
1311 ash_msg_and_raise_error("syntax error: %s", msg);
1315 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1317 ash_msg_and_raise(int cond, const char *msg, ...)
1322 ash_vmsg_and_raise(cond, msg, ap);
1328 * error/warning routines for external builtins
1331 ash_msg(const char *fmt, ...)
1341 * Return a string describing an error. The returned string may be a
1342 * pointer to a static buffer that will be overwritten on the next call.
1343 * Action describes the operation that got the error.
1346 errmsg(int e, const char *em)
1348 if (e == ENOENT || e == ENOTDIR) {
1355 /* ============ Memory allocation */
1358 /* I consider these wrappers nearly useless:
1359 * ok, they return you to nearest exception handler, but
1360 * how much memory do you leak in the process, making
1361 * memory starvation worse?
1364 ckrealloc(void * p, size_t nbytes)
1366 p = realloc(p, nbytes);
1368 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1373 ckmalloc(size_t nbytes)
1375 return ckrealloc(NULL, nbytes);
1379 ckzalloc(size_t nbytes)
1381 return memset(ckmalloc(nbytes), 0, nbytes);
1385 ckstrdup(const char *s)
1387 char *p = strdup(s);
1389 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1393 /* Using bbox equivalents. They exit if out of memory */
1394 # define ckrealloc xrealloc
1395 # define ckmalloc xmalloc
1396 # define ckzalloc xzalloc
1397 # define ckstrdup xstrdup
1401 * It appears that grabstackstr() will barf with such alignments
1402 * because stalloc() will return a string allocated in a new stackblock.
1404 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1406 /* Most machines require the value returned from malloc to be aligned
1407 * in some way. The following macro will get this right
1408 * on many machines. */
1409 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1410 /* Minimum size of a block */
1411 MINSIZE = SHELL_ALIGN(504),
1414 struct stack_block {
1415 struct stack_block *prev;
1416 char space[MINSIZE];
1420 struct stack_block *stackp;
1426 struct globals_memstack {
1427 struct stack_block *g_stackp; // = &stackbase;
1428 char *g_stacknxt; // = stackbase.space;
1429 char *sstrend; // = stackbase.space + MINSIZE;
1430 size_t g_stacknleft; // = MINSIZE;
1431 struct stack_block stackbase;
1433 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1434 #define G_memstack (*ash_ptr_to_globals_memstack)
1435 #define g_stackp (G_memstack.g_stackp )
1436 #define g_stacknxt (G_memstack.g_stacknxt )
1437 #define sstrend (G_memstack.sstrend )
1438 #define g_stacknleft (G_memstack.g_stacknleft)
1439 #define stackbase (G_memstack.stackbase )
1440 #define INIT_G_memstack() do { \
1441 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1443 g_stackp = &stackbase; \
1444 g_stacknxt = stackbase.space; \
1445 g_stacknleft = MINSIZE; \
1446 sstrend = stackbase.space + MINSIZE; \
1450 #define stackblock() ((void *)g_stacknxt)
1451 #define stackblocksize() g_stacknleft
1454 * Parse trees for commands are allocated in lifo order, so we use a stack
1455 * to make this more efficient, and also to avoid all sorts of exception
1456 * handling code to handle interrupts in the middle of a parse.
1458 * The size 504 was chosen because the Ultrix malloc handles that size
1462 stalloc(size_t nbytes)
1467 aligned = SHELL_ALIGN(nbytes);
1468 if (aligned > g_stacknleft) {
1471 struct stack_block *sp;
1473 blocksize = aligned;
1474 if (blocksize < MINSIZE)
1475 blocksize = MINSIZE;
1476 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1477 if (len < blocksize)
1478 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1481 sp->prev = g_stackp;
1482 g_stacknxt = sp->space;
1483 g_stacknleft = blocksize;
1484 sstrend = g_stacknxt + blocksize;
1489 g_stacknxt += aligned;
1490 g_stacknleft -= aligned;
1495 stzalloc(size_t nbytes)
1497 return memset(stalloc(nbytes), 0, nbytes);
1504 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1505 write(STDERR_FILENO, "stunalloc\n", 10);
1509 g_stacknleft += g_stacknxt - (char *)p;
1514 * Like strdup but works with the ash stack.
1517 sstrdup(const char *p)
1519 size_t len = strlen(p) + 1;
1520 return memcpy(stalloc(len), p, len);
1524 grabstackblock(size_t len)
1530 pushstackmark(struct stackmark *mark, size_t len)
1532 mark->stackp = g_stackp;
1533 mark->stacknxt = g_stacknxt;
1534 mark->stacknleft = g_stacknleft;
1535 grabstackblock(len);
1539 setstackmark(struct stackmark *mark)
1541 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1545 popstackmark(struct stackmark *mark)
1547 struct stack_block *sp;
1553 while (g_stackp != mark->stackp) {
1555 g_stackp = sp->prev;
1558 g_stacknxt = mark->stacknxt;
1559 g_stacknleft = mark->stacknleft;
1560 sstrend = mark->stacknxt + mark->stacknleft;
1565 * When the parser reads in a string, it wants to stick the string on the
1566 * stack and only adjust the stack pointer when it knows how big the
1567 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1568 * of space on top of the stack and stackblocklen returns the length of
1569 * this block. Growstackblock will grow this space by at least one byte,
1570 * possibly moving it (like realloc). Grabstackblock actually allocates the
1571 * part of the block that has been used.
1574 growstackblock(void)
1578 newlen = g_stacknleft * 2;
1579 if (newlen < g_stacknleft)
1580 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1584 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1585 struct stack_block *sp;
1586 struct stack_block *prevstackp;
1591 prevstackp = sp->prev;
1592 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1593 sp = ckrealloc(sp, grosslen);
1594 sp->prev = prevstackp;
1596 g_stacknxt = sp->space;
1597 g_stacknleft = newlen;
1598 sstrend = sp->space + newlen;
1601 char *oldspace = g_stacknxt;
1602 size_t oldlen = g_stacknleft;
1603 char *p = stalloc(newlen);
1605 /* free the space we just allocated */
1606 g_stacknxt = memcpy(p, oldspace, oldlen);
1607 g_stacknleft += newlen;
1612 * The following routines are somewhat easier to use than the above.
1613 * The user declares a variable of type STACKSTR, which may be declared
1614 * to be a register. The macro STARTSTACKSTR initializes things. Then
1615 * the user uses the macro STPUTC to add characters to the string. In
1616 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1617 * grown as necessary. When the user is done, she can just leave the
1618 * string there and refer to it using stackblock(). Or she can allocate
1619 * the space for it using grabstackstr(). If it is necessary to allow
1620 * someone else to use the stack temporarily and then continue to grow
1621 * the string, the user should use grabstack to allocate the space, and
1622 * then call ungrabstr(p) to return to the previous mode of operation.
1624 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1625 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1626 * is space for at least one character.
1631 size_t len = stackblocksize();
1633 return (char *)stackblock() + len;
1637 * Called from CHECKSTRSPACE.
1640 makestrspace(size_t newlen, char *p)
1642 size_t len = p - g_stacknxt;
1648 size = stackblocksize();
1650 if (nleft >= newlen)
1654 return (char *)stackblock() + len;
1658 stack_nputstr(const char *s, size_t n, char *p)
1660 p = makestrspace(n, p);
1661 p = (char *)mempcpy(p, s, n);
1666 stack_putstr(const char *s, char *p)
1668 return stack_nputstr(s, strlen(s), p);
1672 _STPUTC(int c, char *p)
1680 #define STARTSTACKSTR(p) ((p) = stackblock())
1681 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1682 #define CHECKSTRSPACE(n, p) do { \
1685 size_t m = sstrend - q; \
1687 (p) = makestrspace(l, q); \
1689 #define USTPUTC(c, p) (*(p)++ = (c))
1690 #define STACKSTRNUL(p) do { \
1691 if ((p) == sstrend) \
1692 (p) = growstackstr(); \
1695 #define STUNPUTC(p) (--(p))
1696 #define STTOPC(p) ((p)[-1])
1697 #define STADJUST(amount, p) ((p) += (amount))
1699 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1700 #define ungrabstackstr(s, p) stunalloc(s)
1701 #define stackstrend() ((void *)sstrend)
1704 /* ============ String helpers */
1707 * prefix -- see if pfx is a prefix of string.
1710 prefix(const char *string, const char *pfx)
1713 if (*pfx++ != *string++)
1716 return (char *) string;
1720 * Check for a valid number. This should be elsewhere.
1723 is_number(const char *p)
1728 } while (*++p != '\0');
1733 * Convert a string of digits to an integer, printing an error message on
1737 number(const char *s)
1740 ash_msg_and_raise_error(msg_illnum, s);
1745 * Produce a single quoted string suitable as input to the shell.
1746 * The return string is allocated on the stack.
1749 single_quote(const char *s)
1759 len = strchrnul(s, '\'') - s;
1761 q = p = makestrspace(len + 3, p);
1764 q = (char *)mempcpy(q, s, len);
1773 do len++; while (*++s == '\'');
1775 q = p = makestrspace(len + 3, p);
1778 q = (char *)mempcpy(q, s - len, len);
1786 return stackblock();
1790 * Produce a possibly single quoted string suitable as input to the shell.
1791 * If quoting was done, the return string is allocated on the stack,
1792 * otherwise a pointer to the original string is returned.
1795 maybe_single_quote(const char *s)
1800 /* Assuming ACSII */
1801 /* quote ctrl_chars space !"#$%&'()* */
1805 if (*p >= ';' && *p <= '?')
1814 /* quote {|}~ DEL and high bytes */
1817 /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
1818 /* TODO: maybe avoid quoting % */
1824 return single_quote(s);
1828 /* ============ nextopt */
1830 static char **argptr; /* argument list for builtin commands */
1831 static char *optionarg; /* set by nextopt (like getopt) */
1832 static char *optptr; /* used by nextopt */
1835 * XXX - should get rid of. Have all builtins use getopt(3).
1836 * The library getopt must have the BSD extension static variable
1837 * "optreset", otherwise it can't be used within the shell safely.
1839 * Standard option processing (a la getopt) for builtin routines.
1840 * The only argument that is passed to nextopt is the option string;
1841 * the other arguments are unnecessary. It returns the character,
1842 * or '\0' on end of input.
1845 nextopt(const char *optstring)
1852 if (p == NULL || *p == '\0') {
1853 /* We ate entire "-param", take next one */
1859 if (*++p == '\0') /* just "-" ? */
1862 if (LONE_DASH(p)) /* "--" ? */
1864 /* p => next "-param" */
1866 /* p => some option char in the middle of a "-param" */
1868 for (q = optstring; *q != c;) {
1870 ash_msg_and_raise_error("illegal option -%c", c);
1878 ash_msg_and_raise_error("no arg for -%c option", c);
1888 /* ============ Shell variables */
1891 * The parsefile structure pointed to by the global variable parsefile
1892 * contains information about the current file being read.
1895 int nparam; /* # of positional parameters (without $0) */
1896 #if ENABLE_ASH_GETOPTS
1897 int optind; /* next parameter to be processed by getopts */
1898 int optoff; /* used by getopts */
1900 unsigned char malloced; /* if parameter list dynamically allocated */
1901 char **p; /* parameter list */
1905 * Free the list of positional parameters.
1908 freeparam(volatile struct shparam *param)
1910 if (param->malloced) {
1912 ap = ap1 = param->p;
1919 #if ENABLE_ASH_GETOPTS
1920 static void FAST_FUNC getoptsreset(const char *value);
1924 struct var *next; /* next entry in hash list */
1925 int flags; /* flags are defined above */
1926 const char *var_text; /* name=value */
1927 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1928 /* the variable gets set/unset */
1932 struct localvar *next; /* next local variable in list */
1933 struct var *vp; /* the variable that was made local */
1934 int flags; /* saved flags */
1935 const char *text; /* saved text */
1939 #define VEXPORT 0x01 /* variable is exported */
1940 #define VREADONLY 0x02 /* variable cannot be modified */
1941 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1942 #define VTEXTFIXED 0x08 /* text is statically allocated */
1943 #define VSTACK 0x10 /* text is allocated on the stack */
1944 #define VUNSET 0x20 /* the variable is not set */
1945 #define VNOFUNC 0x40 /* don't call the callback function */
1946 #define VNOSET 0x80 /* do not set variable - just readonly test */
1947 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1948 #if ENABLE_ASH_RANDOM_SUPPORT
1949 # define VDYNAMIC 0x200 /* dynamic variable */
1955 /* Need to be before varinit_data[] */
1956 #if ENABLE_LOCALE_SUPPORT
1957 static void FAST_FUNC
1958 change_lc_all(const char *value)
1960 if (value && *value != '\0')
1961 setlocale(LC_ALL, value);
1963 static void FAST_FUNC
1964 change_lc_ctype(const char *value)
1966 if (value && *value != '\0')
1967 setlocale(LC_CTYPE, value);
1971 static void chkmail(void);
1972 static void changemail(const char *var_value) FAST_FUNC;
1974 # define chkmail() ((void)0)
1976 static void changepath(const char *) FAST_FUNC;
1977 #if ENABLE_ASH_RANDOM_SUPPORT
1978 static void change_random(const char *) FAST_FUNC;
1981 static const struct {
1983 const char *var_text;
1984 void (*var_func)(const char *) FAST_FUNC;
1985 } varinit_data[] = {
1987 * Note: VEXPORT would not work correctly here for NOFORK applets:
1988 * some environment strings may be constant.
1990 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1992 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1993 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1995 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1996 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1997 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1998 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1999 #if ENABLE_ASH_GETOPTS
2000 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
2002 #if ENABLE_ASH_RANDOM_SUPPORT
2003 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
2005 #if ENABLE_LOCALE_SUPPORT
2006 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
2007 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
2009 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
2010 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
2016 struct globals_var {
2017 struct shparam shellparam; /* $@ current positional parameters */
2018 struct redirtab *redirlist;
2019 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
2020 struct var *vartab[VTABSIZE];
2021 struct var varinit[ARRAY_SIZE(varinit_data)];
2023 extern struct globals_var *const ash_ptr_to_globals_var;
2024 #define G_var (*ash_ptr_to_globals_var)
2025 #define shellparam (G_var.shellparam )
2026 //#define redirlist (G_var.redirlist )
2027 #define preverrout_fd (G_var.preverrout_fd)
2028 #define vartab (G_var.vartab )
2029 #define varinit (G_var.varinit )
2030 #define INIT_G_var() do { \
2032 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
2034 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
2035 varinit[i].flags = varinit_data[i].flags; \
2036 varinit[i].var_text = varinit_data[i].var_text; \
2037 varinit[i].var_func = varinit_data[i].var_func; \
2041 #define vifs varinit[0]
2043 # define vmail (&vifs)[1]
2044 # define vmpath (&vmail)[1]
2045 # define vpath (&vmpath)[1]
2047 # define vpath (&vifs)[1]
2049 #define vps1 (&vpath)[1]
2050 #define vps2 (&vps1)[1]
2051 #define vps4 (&vps2)[1]
2052 #if ENABLE_ASH_GETOPTS
2053 # define voptind (&vps4)[1]
2054 # if ENABLE_ASH_RANDOM_SUPPORT
2055 # define vrandom (&voptind)[1]
2058 # if ENABLE_ASH_RANDOM_SUPPORT
2059 # define vrandom (&vps4)[1]
2064 * The following macros access the values of the above variables.
2065 * They have to skip over the name. They return the null string
2066 * for unset variables.
2068 #define ifsval() (vifs.var_text + 4)
2069 #define ifsset() ((vifs.flags & VUNSET) == 0)
2071 # define mailval() (vmail.var_text + 5)
2072 # define mpathval() (vmpath.var_text + 9)
2073 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2075 #define pathval() (vpath.var_text + 5)
2076 #define ps1val() (vps1.var_text + 4)
2077 #define ps2val() (vps2.var_text + 4)
2078 #define ps4val() (vps4.var_text + 4)
2079 #if ENABLE_ASH_GETOPTS
2080 # define optindval() (voptind.var_text + 7)
2083 #if ENABLE_ASH_GETOPTS
2084 static void FAST_FUNC
2085 getoptsreset(const char *value)
2087 shellparam.optind = number(value) ?: 1;
2088 shellparam.optoff = -1;
2093 * Compares two strings up to the first = or '\0'. The first
2094 * string must be terminated by '='; the second may be terminated by
2095 * either '=' or '\0'.
2098 varcmp(const char *p, const char *q)
2102 while ((c = *p) == (d = *q)) {
2103 if (c == '\0' || c == '=')
2117 * Find the appropriate entry in the hash table from the name.
2119 static struct var **
2120 hashvar(const char *p)
2124 hashval = ((unsigned char) *p) << 4;
2125 while (*p && *p != '=')
2126 hashval += (unsigned char) *p++;
2127 return &vartab[hashval % VTABSIZE];
2131 vpcmp(const void *a, const void *b)
2133 return varcmp(*(const char **)a, *(const char **)b);
2137 * This routine initializes the builtin variables.
2147 * PS1 depends on uid
2149 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2150 vps1.var_text = "PS1=\\w \\$ ";
2153 vps1.var_text = "PS1=# ";
2156 end = vp + ARRAY_SIZE(varinit);
2158 vpp = hashvar(vp->var_text);
2161 } while (++vp < end);
2164 static struct var **
2165 findvar(struct var **vpp, const char *name)
2167 for (; *vpp; vpp = &(*vpp)->next) {
2168 if (varcmp((*vpp)->var_text, name) == 0) {
2176 * Find the value of a variable. Returns NULL if not set.
2178 static const char* FAST_FUNC
2179 lookupvar(const char *name)
2183 v = *findvar(hashvar(name), name);
2185 #if ENABLE_ASH_RANDOM_SUPPORT
2187 * Dynamic variables are implemented roughly the same way they are
2188 * in bash. Namely, they're "special" so long as they aren't unset.
2189 * As soon as they're unset, they're no longer dynamic, and dynamic
2190 * lookup will no longer happen at that point. -- PFM.
2192 if (v->flags & VDYNAMIC)
2195 if (!(v->flags & VUNSET))
2196 return var_end(v->var_text);
2201 #if ENABLE_UNICODE_SUPPORT
2203 reinit_unicode_for_ash(void)
2205 /* Unicode support should be activated even if LANG is set
2206 * _during_ shell execution, not only if it was set when
2207 * shell was started. Therefore, re-check LANG every time:
2209 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2210 || ENABLE_UNICODE_USING_LOCALE
2212 const char *s = lookupvar("LC_ALL");
2213 if (!s) s = lookupvar("LC_CTYPE");
2214 if (!s) s = lookupvar("LANG");
2219 # define reinit_unicode_for_ash() ((void)0)
2223 * Search the environment of a builtin command.
2226 bltinlookup(const char *name)
2230 for (sp = cmdenviron; sp; sp = sp->next) {
2231 if (varcmp(sp->text, name) == 0)
2232 return var_end(sp->text);
2234 return lookupvar(name);
2238 * Same as setvar except that the variable and value are passed in
2239 * the first argument as name=value. Since the first argument will
2240 * be actually stored in the table, it should not be a string that
2242 * Called with interrupts off.
2245 setvareq(char *s, int flags)
2247 struct var *vp, **vpp;
2250 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2251 vp = *findvar(vpp, s);
2253 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2256 if (flags & VNOSAVE)
2260 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2266 if (vp->var_func && !(flags & VNOFUNC))
2267 vp->var_func(var_end(s));
2269 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2270 free((char*)vp->var_text);
2272 if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
2276 if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
2281 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2283 /* variable s is not found */
2286 if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
2288 vp = ckzalloc(sizeof(*vp));
2290 /*vp->func = NULL; - ckzalloc did it */
2293 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2300 * Set the value of a variable. The flags argument is ored with the
2301 * flags of the variable. If val is NULL, the variable is unset.
2304 setvar(const char *name, const char *val, int flags)
2312 q = endofname(name);
2313 p = strchrnul(q, '=');
2315 if (!namelen || p != q)
2316 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2321 vallen = strlen(val);
2325 nameeq = ckmalloc(namelen + vallen + 2);
2326 p = mempcpy(nameeq, name, namelen);
2329 p = mempcpy(p, val, vallen);
2332 setvareq(nameeq, flags | VNOSAVE);
2336 static void FAST_FUNC
2337 setvar0(const char *name, const char *val)
2339 setvar(name, val, 0);
2343 * Unset the specified variable.
2346 unsetvar(const char *s)
2352 * Process a linked list of variable assignments.
2355 listsetvar(struct strlist *list_set_var, int flags)
2357 struct strlist *lp = list_set_var;
2363 setvareq(lp->text, flags);
2370 * Generate a list of variables satisfying the given conditions.
2373 listvars(int on, int off, char ***end)
2384 for (vp = *vpp; vp; vp = vp->next) {
2385 if ((vp->flags & mask) == on) {
2386 if (ep == stackstrend())
2387 ep = growstackstr();
2388 *ep++ = (char*)vp->var_text;
2391 } while (++vpp < vartab + VTABSIZE);
2392 if (ep == stackstrend())
2393 ep = growstackstr();
2397 return grabstackstr(ep);
2401 /* ============ Path search helper
2403 * The variable path (passed by reference) should be set to the start
2404 * of the path before the first call; path_advance will update
2405 * this value as it proceeds. Successive calls to path_advance will return
2406 * the possible path expansions in sequence. If an option (indicated by
2407 * a percent sign) appears in the path entry then the global variable
2408 * pathopt will be set to point to it; otherwise pathopt will be set to
2411 static const char *pathopt; /* set by path_advance */
2414 path_advance(const char **path, const char *name)
2424 for (p = start; *p && *p != ':' && *p != '%'; p++)
2426 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2427 while (stackblocksize() < len)
2431 q = mempcpy(q, start, p - start);
2438 while (*p && *p != ':')
2445 return stalloc(len);
2449 /* ============ Prompt */
2451 static smallint doprompt; /* if set, prompt the user */
2452 static smallint needprompt; /* true if interactive and at start of line */
2454 #if ENABLE_FEATURE_EDITING
2455 static line_input_t *line_input_state;
2456 static const char *cmdedit_prompt;
2458 putprompt(const char *s)
2460 if (ENABLE_ASH_EXPAND_PRMT) {
2461 free((char*)cmdedit_prompt);
2462 cmdedit_prompt = ckstrdup(s);
2469 putprompt(const char *s)
2475 /* expandstr() needs parsing machinery, so it is far away ahead... */
2476 static const char *expandstr(const char *ps);
2479 setprompt_if(smallint do_set, int whichprompt)
2482 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2489 switch (whichprompt) {
2499 #if ENABLE_ASH_EXPAND_PRMT
2500 pushstackmark(&smark, stackblocksize());
2501 putprompt(expandstr(prompt));
2502 popstackmark(&smark);
2509 /* ============ The cd and pwd commands */
2511 #define CD_PHYSICAL 1
2521 while ((i = nextopt("LP")) != '\0') {
2523 flags ^= CD_PHYSICAL;
2532 * Update curdir (the name of the current directory) in response to a
2536 updatepwd(const char *dir)
2543 cdcomppath = sstrdup(dir);
2546 if (curdir == nullstr)
2548 new = stack_putstr(curdir, new);
2550 new = makestrspace(strlen(dir) + 2, new);
2551 lim = (char *)stackblock() + 1;
2555 if (new > lim && *lim == '/')
2560 if (dir[1] == '/' && dir[2] != '/') {
2566 p = strtok(cdcomppath, "/");
2570 if (p[1] == '.' && p[2] == '\0') {
2582 new = stack_putstr(p, new);
2585 p = strtok(NULL, "/");
2590 return stackblock();
2594 * Find out what the current directory is. If we already know the current
2595 * directory, this routine returns immediately.
2600 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2601 return dir ? dir : nullstr;
2605 setpwd(const char *val, int setold)
2609 oldcur = dir = curdir;
2612 setvar("OLDPWD", oldcur, VEXPORT);
2615 if (physdir != nullstr) {
2616 if (physdir != oldcur)
2620 if (oldcur == val || !val) {
2626 dir = ckstrdup(val);
2627 if (oldcur != dir && oldcur != nullstr) {
2632 setvar("PWD", dir, VEXPORT);
2635 static void hashcd(void);
2638 * Actually do the chdir. We also call hashcd to let other routines
2639 * know that the current directory has changed.
2642 docd(const char *dest, int flags)
2644 const char *dir = NULL;
2647 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2650 if (!(flags & CD_PHYSICAL)) {
2651 dir = updatepwd(dest);
2665 static int FAST_FUNC
2666 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2678 dest = bltinlookup("HOME");
2679 else if (LONE_DASH(dest)) {
2680 dest = bltinlookup("OLDPWD");
2702 path = bltinlookup("CDPATH");
2705 p = path_advance(&path, dest);
2706 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2710 if (!docd(p, flags))
2721 ash_msg_and_raise_error("can't cd to %s", dest);
2724 if (flags & CD_PRINT)
2725 out1fmt("%s\n", curdir);
2729 static int FAST_FUNC
2730 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2733 const char *dir = curdir;
2737 if (physdir == nullstr)
2741 out1fmt("%s\n", dir);
2746 /* ============ ... */
2749 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2751 /* Syntax classes */
2752 #define CWORD 0 /* character is nothing special */
2753 #define CNL 1 /* newline character */
2754 #define CBACK 2 /* a backslash character */
2755 #define CSQUOTE 3 /* single quote */
2756 #define CDQUOTE 4 /* double quote */
2757 #define CENDQUOTE 5 /* a terminating quote */
2758 #define CBQUOTE 6 /* backwards single quote */
2759 #define CVAR 7 /* a dollar sign */
2760 #define CENDVAR 8 /* a '}' character */
2761 #define CLP 9 /* a left paren in arithmetic */
2762 #define CRP 10 /* a right paren in arithmetic */
2763 #define CENDFILE 11 /* end of file */
2764 #define CCTL 12 /* like CWORD, except it must be escaped */
2765 #define CSPCL 13 /* these terminate a word */
2766 #define CIGN 14 /* character should be ignored */
2769 #if ENABLE_ASH_ALIAS
2773 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2775 #if ENABLE_FEATURE_SH_MATH
2776 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2778 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2780 static const uint16_t S_I_T[] ALIGN2 = {
2781 #if ENABLE_ASH_ALIAS
2782 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2784 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2785 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2786 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2787 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2788 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2789 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2790 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2791 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2792 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2793 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2794 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2795 #if !USE_SIT_FUNCTION
2796 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2797 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2798 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2802 /* Constants below must match table above */
2804 #if ENABLE_ASH_ALIAS
2805 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2807 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2808 CNL_CNL_CNL_CNL , /* 2 */
2809 CWORD_CCTL_CCTL_CWORD , /* 3 */
2810 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2811 CVAR_CVAR_CWORD_CVAR , /* 5 */
2812 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2813 CSPCL_CWORD_CWORD_CLP , /* 7 */
2814 CSPCL_CWORD_CWORD_CRP , /* 8 */
2815 CBACK_CBACK_CCTL_CBACK , /* 9 */
2816 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2817 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2818 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2819 CWORD_CWORD_CWORD_CWORD , /* 13 */
2820 CCTL_CCTL_CCTL_CCTL , /* 14 */
2823 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2824 * caller must ensure proper cast on it if c is *char_ptr!
2826 /* Values for syntax param */
2827 #define BASESYNTAX 0 /* not in quotes */
2828 #define DQSYNTAX 1 /* in double quotes */
2829 #define SQSYNTAX 2 /* in single quotes */
2830 #define ARISYNTAX 3 /* in arithmetic */
2831 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2833 #if USE_SIT_FUNCTION
2836 SIT(int c, int syntax)
2838 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2839 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2841 * This causes '/' to be prepended with CTLESC in dquoted string,
2842 * making "./file"* treated incorrectly because we feed
2843 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2844 * The "homegrown" glob implementation is okay with that,
2845 * but glibc one isn't. With '/' always treated as CWORD,
2848 # if ENABLE_ASH_ALIAS
2849 static const uint8_t syntax_index_table[] ALIGN1 = {
2850 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2851 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2852 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2856 static const uint8_t syntax_index_table[] ALIGN1 = {
2857 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2858 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2859 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2868 # if ENABLE_ASH_ALIAS
2874 /* Cast is purely for paranoia here,
2875 * just in case someone passed signed char to us */
2876 if ((unsigned char)c >= CTL_FIRST
2877 && (unsigned char)c <= CTL_LAST
2881 s = strchrnul(spec_symbls, c);
2884 indx = syntax_index_table[s - spec_symbls];
2886 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2889 #else /* !USE_SIT_FUNCTION */
2891 static const uint8_t syntax_index_table[] ALIGN1 = {
2892 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2893 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2903 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2904 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2926 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2927 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2928 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2930 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2932 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2933 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2934 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2935 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2936 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2938 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2939 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2940 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2941 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2953 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2954 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2955 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2956 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2957 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2958 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2986 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2987 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2988 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2991 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3006 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3007 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3008 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3009 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3010 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3011 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3012 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3013 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3014 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3015 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3016 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3017 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3018 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3019 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3020 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3021 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3022 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3024 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3025 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3026 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3027 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3028 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3029 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3030 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3031 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3120 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3121 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3122 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3123 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3124 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3125 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3126 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3127 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3128 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3129 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3130 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3131 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3132 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3133 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3134 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3135 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3136 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3137 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3138 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3139 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3140 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3141 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3142 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3143 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3144 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3145 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3146 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3147 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3148 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3149 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3150 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3151 # if ENABLE_ASH_ALIAS
3152 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3157 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3158 #else /* debug version, caught one signed char bug */
3159 # define SIT(c, syntax) \
3161 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3162 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3163 if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
3164 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3165 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3169 #endif /* !USE_SIT_FUNCTION */
3172 /* ============ Alias handling */
3174 #if ENABLE_ASH_ALIAS
3176 #define ALIASINUSE 1
3187 static struct alias **atab; // [ATABSIZE];
3188 #define INIT_G_alias() do { \
3189 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3193 static struct alias **
3194 __lookupalias(const char *name)
3196 unsigned int hashval;
3203 ch = (unsigned char)*p;
3207 ch = (unsigned char)*++p;
3209 app = &atab[hashval % ATABSIZE];
3211 for (; *app; app = &(*app)->next) {
3212 if (strcmp(name, (*app)->name) == 0) {
3220 static struct alias *
3221 lookupalias(const char *name, int check)
3223 struct alias *ap = *__lookupalias(name);
3225 if (check && ap && (ap->flag & ALIASINUSE))
3230 static struct alias *
3231 freealias(struct alias *ap)
3235 if (ap->flag & ALIASINUSE) {
3236 ap->flag |= ALIASDEAD;
3248 setalias(const char *name, const char *val)
3250 struct alias *ap, **app;
3252 app = __lookupalias(name);
3256 if (!(ap->flag & ALIASINUSE)) {
3259 ap->val = ckstrdup(val);
3260 ap->flag &= ~ALIASDEAD;
3263 ap = ckzalloc(sizeof(struct alias));
3264 ap->name = ckstrdup(name);
3265 ap->val = ckstrdup(val);
3266 /*ap->flag = 0; - ckzalloc did it */
3267 /*ap->next = NULL;*/
3274 unalias(const char *name)
3278 app = __lookupalias(name);
3282 *app = freealias(*app);
3293 struct alias *ap, **app;
3297 for (i = 0; i < ATABSIZE; i++) {
3299 for (ap = *app; ap; ap = *app) {
3300 *app = freealias(*app);
3310 printalias(const struct alias *ap)
3312 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3316 * TODO - sort output
3318 static int FAST_FUNC
3319 aliascmd(int argc UNUSED_PARAM, char **argv)
3328 for (i = 0; i < ATABSIZE; i++) {
3329 for (ap = atab[i]; ap; ap = ap->next) {
3335 while ((n = *++argv) != NULL) {
3336 v = strchr(n+1, '=');
3337 if (v == NULL) { /* n+1: funny ksh stuff */
3338 ap = *__lookupalias(n);
3340 fprintf(stderr, "%s: %s not found\n", "alias", n);
3353 static int FAST_FUNC
3354 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3358 while (nextopt("a") != '\0') {
3362 for (i = 0; *argptr; argptr++) {
3363 if (unalias(*argptr)) {
3364 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3372 #endif /* ASH_ALIAS */
3375 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3378 #define FORK_NOJOB 2
3380 /* mode flags for showjob(s) */
3381 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3382 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3383 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3384 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3387 * A job structure contains information about a job. A job is either a
3388 * single process or a set of processes contained in a pipeline. In the
3389 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3393 pid_t ps_pid; /* process id */
3394 int ps_status; /* last process status from wait() */
3395 char *ps_cmd; /* text of command being run */
3399 struct procstat ps0; /* status of process */
3400 struct procstat *ps; /* status or processes when more than one */
3402 int stopstatus; /* status of a stopped job */
3404 unsigned nprocs; /* number of processes */
3406 #define JOBRUNNING 0 /* at least one proc running */
3407 #define JOBSTOPPED 1 /* all procs are stopped */
3408 #define JOBDONE 2 /* all procs are completed */
3412 sigint: 1, /* job was killed by SIGINT */
3413 jobctl: 1, /* job running under job control */
3415 waited: 1, /* true if this entry has been waited for */
3416 used: 1, /* true if this entry is in used */
3417 changed: 1; /* true if status has changed */
3418 struct job *prev_job; /* previous job */
3421 static struct job *makejob(/*union node *,*/ int);
3422 static int forkshell(struct job *, union node *, int);
3423 static int waitforjob(struct job *);
3426 enum { doing_jobctl = 0 };
3427 #define setjobctl(on) do {} while (0)
3429 static smallint doing_jobctl; //references:8
3430 static void setjobctl(int);
3437 ignoresig(int signo)
3439 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3440 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3441 /* No, need to do it */
3442 signal(signo, SIG_IGN);
3444 sigmode[signo - 1] = S_HARD_IGN;
3448 * Only one usage site - in setsignal()
3451 signal_handler(int signo)
3453 if (signo == SIGCHLD) {
3459 gotsig[signo - 1] = 1;
3460 pending_sig = signo;
3462 if (signo == SIGINT && !trap[SIGINT]) {
3463 if (!suppress_int) {
3465 raise_interrupt(); /* does not return */
3472 * Set the signal handler for the specified signal. The routine figures
3473 * out what it should be set to.
3476 setsignal(int signo)
3479 char cur_act, new_act;
3480 struct sigaction act;
3484 if (t != NULL) { /* trap for this sig is set */
3486 if (t[0] == '\0') /* trap is "": ignore this sig */
3490 if (rootshell && new_act == S_DFL) {
3493 if (iflag || minusc || sflag == 0)
3502 * "In all cases, bash ignores SIGQUIT. Non-builtin
3503 * commands run by bash have signal handlers
3504 * set to the values inherited by the shell
3505 * from its parent". */
3521 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3522 //whereas we have to restore it to what shell got on entry
3523 //from the parent. See comment above
3525 if (signo == SIGCHLD)
3528 t = &sigmode[signo - 1];
3531 /* current setting is not yet known */
3532 if (sigaction(signo, NULL, &act)) {
3533 /* pretend it worked; maybe we should give a warning,
3534 * but other shells don't. We don't alter sigmode,
3535 * so we retry every time.
3536 * btw, in Linux it never fails. --vda */
3539 if (act.sa_handler == SIG_IGN) {
3540 cur_act = S_HARD_IGN;
3542 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3544 cur_act = S_IGN; /* don't hard ignore these */
3548 if (cur_act == S_HARD_IGN || cur_act == new_act)
3551 act.sa_handler = SIG_DFL;
3554 act.sa_handler = signal_handler;
3557 act.sa_handler = SIG_IGN;
3561 /* flags and mask matter only if !DFL and !IGN, but we do it
3562 * for all cases for more deterministic behavior:
3565 sigfillset(&act.sa_mask);
3567 sigaction_set(signo, &act);
3572 /* mode flags for set_curjob */
3573 #define CUR_DELETE 2
3574 #define CUR_RUNNING 1
3575 #define CUR_STOPPED 0
3578 /* pgrp of shell on invocation */
3579 static int initialpgrp; //references:2
3580 static int ttyfd = -1; //5
3583 static struct job *jobtab; //5
3585 static unsigned njobs; //4
3587 static struct job *curjob; //lots
3588 /* number of presumed living untracked jobs */
3589 static int jobless; //4
3592 /* Bash has a feature: it restores termios after a successful wait for
3593 * a foreground job which had at least one stopped or sigkilled member.
3594 * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
3595 * properly restoring tty state. Should we do this too?
3596 * A reproducer: ^Z an interactive python:
3599 * Python 2.7.12 (...)
3601 * { python leaves tty in -icanon -echo state. We do survive that... }
3602 * [1]+ Stopped python
3603 * { ...however, next program (python #2) does not survive it well: }
3605 * Python 2.7.12 (...)
3606 * >>> Traceback (most recent call last):
3607 * { above, I typed "qwerty<CR>", but -echo state is still in effect }
3608 * File "<stdin>", line 1, in <module>
3609 * NameError: name 'qwerty' is not defined
3611 * The implementation below is modeled on bash code and seems to work.
3612 * However, I'm not sure we should do this. For one: what if I'd fg
3613 * the stopped python instead? It'll be confused by "restored" tty state.
3615 static struct termios shell_tty_info;
3619 if (rootshell && ttyfd >= 0)
3620 tcgetattr(ttyfd, &shell_tty_info);
3625 /* if (rootshell) - caller ensures this */
3627 tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
3630 job_signal_status(struct job *jp)
3634 struct procstat *ps = jp->ps;
3635 for (i = 0; i < jp->nprocs; i++) {
3636 status = ps[i].ps_status;
3637 if (WIFSIGNALED(status) || WIFSTOPPED(status))
3643 restore_tty_if_stopped_or_signaled(struct job *jp)
3645 //TODO: check what happens if we come from waitforjob() in expbackq()
3647 int s = job_signal_status(jp);
3648 if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
3653 # define get_tty_state() ((void)0)
3654 # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
3658 set_curjob(struct job *jp, unsigned mode)
3661 struct job **jpp, **curp;
3663 /* first remove from list */
3664 jpp = curp = &curjob;
3669 jpp = &jp1->prev_job;
3671 *jpp = jp1->prev_job;
3673 /* Then re-insert in correct position */
3681 /* job being deleted */
3684 /* newly created job or backgrounded job,
3685 * put after all stopped jobs.
3690 if (!jp1 || jp1->state != JOBSTOPPED)
3693 jpp = &jp1->prev_job;
3699 /* newly stopped job - becomes curjob */
3700 jp->prev_job = *jpp;
3708 jobno(const struct job *jp)
3710 return jp - jobtab + 1;
3715 * Convert a job name to a job structure.
3718 #define getjob(name, getctl) getjob(name)
3721 getjob(const char *name, int getctl)
3725 const char *err_msg = "%s: no such job";
3729 char *(*match)(const char *, const char *);
3744 if (c == '+' || c == '%') {
3746 err_msg = "No current job";
3752 err_msg = "No previous job";
3762 if (num > 0 && num <= njobs) {
3763 jp = jobtab + num - 1;
3778 if (match(jp->ps[0].ps_cmd, p)) {
3782 err_msg = "%s: ambiguous";
3792 err_msg = "job %s not created under job control";
3793 if (getctl && jp->jobctl == 0)
3798 ash_msg_and_raise_error(err_msg, name);
3802 * Mark a job structure as unused.
3805 freejob(struct job *jp)
3807 struct procstat *ps;
3811 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3812 if (ps->ps_cmd != nullstr)
3815 if (jp->ps != &jp->ps0)
3818 set_curjob(jp, CUR_DELETE);
3824 xtcsetpgrp(int fd, pid_t pgrp)
3826 if (tcsetpgrp(fd, pgrp))
3827 ash_msg_and_raise_error("can't set tty process group (%m)");
3831 * Turn job control on and off.
3833 * Note: This code assumes that the third arg to ioctl is a character
3834 * pointer, which is true on Berkeley systems but not System V. Since
3835 * System V doesn't have job control yet, this isn't a problem now.
3837 * Called with interrupts off.
3845 if (on == doing_jobctl || rootshell == 0)
3849 ofd = fd = open(_PATH_TTY, O_RDWR);
3851 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3852 * That sometimes helps to acquire controlling tty.
3853 * Obviously, a workaround for bugs when someone
3854 * failed to provide a controlling tty to bash! :) */
3860 /* fd is a tty at this point */
3861 fd = fcntl(fd, F_DUPFD, 10);
3862 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
3865 goto out; /* F_DUPFD failed */
3866 close_on_exec_on(fd);
3867 while (1) { /* while we are in the background */
3868 pgrp = tcgetpgrp(fd);
3871 ash_msg("can't access tty; job control turned off");
3875 if (pgrp == getpgrp())
3886 xtcsetpgrp(fd, pgrp);
3888 /* turning job control off */
3891 /* was xtcsetpgrp, but this can make exiting ash
3892 * loop forever if pty is already deleted */
3893 tcsetpgrp(fd, pgrp);
3907 static int FAST_FUNC
3908 killcmd(int argc, char **argv)
3910 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3913 if (argv[i][0] == '%') {
3915 * "kill %N" - job kill
3916 * Converting to pgrp / pid kill
3922 jp = getjob(argv[i], 0);
3924 * In jobs started under job control, we signal
3925 * entire process group by kill -PGRP_ID.
3926 * This happens, f.e., in interactive shell.
3928 * Otherwise, we signal each child via
3929 * kill PID1 PID2 PID3.
3931 * sh -c 'sleep 1|sleep 1 & kill %1'
3932 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3933 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3935 n = jp->nprocs; /* can't be 0 (I hope) */
3938 dst = alloca(n * sizeof(int)*4);
3940 for (j = 0; j < n; j++) {
3941 struct procstat *ps = &jp->ps[j];
3942 /* Skip non-running and not-stopped members
3943 * (i.e. dead members) of the job
3945 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3948 * kill_main has matching code to expect
3949 * leading space. Needed to not confuse
3950 * negative pids with "kill -SIGNAL_NO" syntax
3952 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3956 } while (argv[++i]);
3958 return kill_main(argc, argv);
3962 showpipe(struct job *jp /*, FILE *out*/)
3964 struct procstat *ps;
3965 struct procstat *psend;
3967 psend = jp->ps + jp->nprocs;
3968 for (ps = jp->ps + 1; ps < psend; ps++)
3969 printf(" | %s", ps->ps_cmd);
3970 newline_and_flush(stdout);
3971 flush_stdout_stderr();
3976 restartjob(struct job *jp, int mode)
3978 struct procstat *ps;
3984 if (jp->state == JOBDONE)
3986 jp->state = JOBRUNNING;
3987 pgid = jp->ps[0].ps_pid;
3988 if (mode == FORK_FG) {
3990 xtcsetpgrp(ttyfd, pgid);
3992 killpg(pgid, SIGCONT);
3996 if (WIFSTOPPED(ps->ps_status)) {
4002 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
4007 static int FAST_FUNC
4008 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
4014 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
4018 jp = getjob(*argv, 1);
4019 if (mode == FORK_BG) {
4020 set_curjob(jp, CUR_RUNNING);
4021 printf("[%d] ", jobno(jp));
4023 out1str(jp->ps[0].ps_cmd);
4024 showpipe(jp /*, stdout*/);
4025 retval = restartjob(jp, mode);
4026 } while (*argv && *++argv);
4032 sprint_status48(char *s, int status, int sigonly)
4038 if (!WIFEXITED(status)) {
4040 if (WIFSTOPPED(status))
4041 st = WSTOPSIG(status);
4044 st = WTERMSIG(status);
4046 if (st == SIGINT || st == SIGPIPE)
4049 if (WIFSTOPPED(status))
4054 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
4055 col = fmtstr(s, 32, strsignal(st));
4056 if (WCOREDUMP(status)) {
4057 strcpy(s + col, " (core dumped)");
4058 col += sizeof(" (core dumped)")-1;
4060 } else if (!sigonly) {
4061 st = WEXITSTATUS(status);
4062 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
4069 wait_block_or_sig(int *status)
4076 /* Poll all children for changes in their state */
4078 /* if job control is active, accept stopped processes too */
4079 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
4081 break; /* Error (e.g. EINTR, ECHILD) or pid */
4083 /* Children exist, but none are ready. Sleep until interesting signal */
4086 sigprocmask(SIG_SETMASK, &mask, &mask);
4087 while (!got_sigchld && !pending_sig)
4089 sigprocmask(SIG_SETMASK, &mask, NULL);
4090 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
4091 while (!got_sigchld && !pending_sig)
4095 /* If it was SIGCHLD, poll children again */
4096 } while (got_sigchld);
4101 #define DOWAIT_NONBLOCK 0
4102 #define DOWAIT_BLOCK 1
4103 #define DOWAIT_BLOCK_OR_SIG 2
4106 dowait(int block, struct job *job)
4111 struct job *thisjob = NULL;
4113 TRACE(("dowait(0x%x) called\n", block));
4115 /* It's wrong to call waitpid() outside of INT_OFF region:
4116 * signal can arrive just after syscall return and handler can
4117 * longjmp away, losing stop/exit notification processing.
4118 * Thus, for "jobs" builtin, and for waiting for a fg job,
4119 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4121 * However, for "wait" builtin it is wrong to simply call waitpid()
4122 * in INT_OFF region: "wait" needs to wait for any running job
4123 * to change state, but should exit on any trap too.
4124 * In INT_OFF region, a signal just before syscall entry can set
4125 * pending_sig variables, but we can't check them, and we would
4126 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4128 * Because of this, we run inside INT_OFF, but use a special routine
4129 * which combines waitpid() and sigsuspend().
4130 * This is the reason why we need to have a handler for SIGCHLD:
4131 * SIG_DFL handler does not wake sigsuspend().
4134 if (block == DOWAIT_BLOCK_OR_SIG) {
4135 pid = wait_block_or_sig(&status);
4138 if (block == DOWAIT_NONBLOCK)
4139 wait_flags = WNOHANG;
4140 /* if job control is active, accept stopped processes too */
4142 wait_flags |= WUNTRACED;
4143 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4144 pid = waitpid(-1, &status, wait_flags);
4146 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4147 pid, status, errno, strerror(errno)));
4152 for (jp = curjob; jp; jp = jp->prev_job) {
4154 struct procstat *ps;
4155 struct procstat *psend;
4156 if (jp->state == JOBDONE)
4160 psend = ps + jp->nprocs;
4162 if (ps->ps_pid == pid) {
4163 TRACE(("Job %d: changing status of proc %d "
4164 "from 0x%x to 0x%x\n",
4165 jobno(jp), pid, ps->ps_status, status));
4166 ps->ps_status = status;
4169 if (ps->ps_status == -1)
4170 jobstate = JOBRUNNING;
4172 if (jobstate == JOBRUNNING)
4174 if (WIFSTOPPED(ps->ps_status)) {
4175 jp->stopstatus = ps->ps_status;
4176 jobstate = JOBSTOPPED;
4179 } while (++ps < psend);
4183 /* Found the job where one of its processes changed its state.
4184 * Is there at least one live and running process in this job? */
4185 if (jobstate != JOBRUNNING) {
4186 /* No. All live processes in the job are stopped
4187 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4189 thisjob->changed = 1;
4190 if (thisjob->state != jobstate) {
4191 TRACE(("Job %d: changing state from %d to %d\n",
4192 jobno(thisjob), thisjob->state, jobstate));
4193 thisjob->state = jobstate;
4195 if (jobstate == JOBSTOPPED)
4196 set_curjob(thisjob, CUR_STOPPED);
4202 /* The process wasn't found in job list */
4204 if (!WIFSTOPPED(status))
4210 if (thisjob && thisjob == job) {
4214 len = sprint_status48(s, status, 1);
4226 showjob(struct job *jp, int mode)
4228 struct procstat *ps;
4229 struct procstat *psend;
4232 char s[16 + 16 + 48];
4233 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4237 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4238 /* just output process (group) id of pipeline */
4239 fprintf(out, "%d\n", ps->ps_pid);
4243 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4248 else if (curjob && jp == curjob->prev_job)
4251 if (mode & SHOW_PIDS)
4252 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4254 psend = ps + jp->nprocs;
4256 if (jp->state == JOBRUNNING) {
4257 strcpy(s + col, "Running");
4258 col += sizeof("Running") - 1;
4260 int status = psend[-1].ps_status;
4261 if (jp->state == JOBSTOPPED)
4262 status = jp->stopstatus;
4263 col += sprint_status48(s + col, status, 0);
4265 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4267 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4268 * or prints several "PID | <cmdN>" lines,
4269 * depending on SHOW_PIDS bit.
4270 * We do not print status of individual processes
4271 * between PID and <cmdN>. bash does it, but not very well:
4272 * first line shows overall job status, not process status,
4273 * making it impossible to know 1st process status.
4277 /* for each process */
4280 if (mode & SHOW_PIDS)
4281 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4283 fprintf(out, "%s%*c%s%s",
4285 33 - col >= 0 ? 33 - col : 0, ' ',
4286 ps == jp->ps ? "" : "| ",
4289 } while (++ps != psend);
4290 newline_and_flush(out);
4294 if (jp->state == JOBDONE) {
4295 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4301 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4302 * statuses have changed since the last call to showjobs.
4309 TRACE(("showjobs(0x%x) called\n", mode));
4311 /* Handle all finished jobs */
4312 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4315 for (jp = curjob; jp; jp = jp->prev_job) {
4316 if (!(mode & SHOW_CHANGED) || jp->changed) {
4322 static int FAST_FUNC
4323 jobscmd(int argc UNUSED_PARAM, char **argv)
4328 while ((m = nextopt("lp")) != '\0') {
4332 mode |= SHOW_ONLY_PGID;
4338 showjob(getjob(*argv, 0), mode);
4348 /* Called only on finished or stopped jobs (no members are running) */
4350 getstatus(struct job *job)
4354 struct procstat *ps;
4356 /* Fetch last member's status */
4357 ps = job->ps + job->nprocs - 1;
4358 status = ps->ps_status;
4360 /* "set -o pipefail" mode: use last _nonzero_ status */
4361 while (status == 0 && --ps >= job->ps)
4362 status = ps->ps_status;
4365 retval = WEXITSTATUS(status);
4366 if (!WIFEXITED(status)) {
4368 retval = WSTOPSIG(status);
4369 if (!WIFSTOPPED(status))
4372 /* XXX: limits number of signals */
4373 retval = WTERMSIG(status);
4375 if (retval == SIGINT)
4381 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4382 jobno(job), job->nprocs, status, retval));
4386 static int FAST_FUNC
4387 waitcmd(int argc UNUSED_PARAM, char **argv)
4398 /* wait for all jobs */
4402 if (!jp) /* no running procs */
4404 if (jp->state == JOBRUNNING)
4410 * "When bash is waiting for an asynchronous command via
4411 * the wait builtin, the reception of a signal for which a trap
4412 * has been set will cause the wait builtin to return immediately
4413 * with an exit status greater than 128, immediately after which
4414 * the trap is executed."
4416 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4417 /* if child sends us a signal *and immediately exits*,
4418 * dowait() returns pid > 0. Check this case,
4419 * not "if (dowait() < 0)"!
4428 if (**argv != '%') {
4429 pid_t pid = number(*argv);
4434 if (job->ps[job->nprocs - 1].ps_pid == pid)
4436 job = job->prev_job;
4439 job = getjob(*argv, 0);
4441 /* loop until process terminated or stopped */
4442 while (job->state == JOBRUNNING) {
4443 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4448 retval = getstatus(job);
4455 retval = 128 + pending_sig;
4464 struct job *jp, *jq;
4466 len = njobs * sizeof(*jp);
4468 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4470 offset = (char *)jp - (char *)jq;
4472 /* Relocate pointers */
4475 jq = (struct job *)((char *)jq + l);
4479 #define joff(p) ((struct job *)((char *)(p) + l))
4480 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4481 if (joff(jp)->ps == &jq->ps0)
4482 jmove(joff(jp)->ps);
4483 if (joff(jp)->prev_job)
4484 jmove(joff(jp)->prev_job);
4494 jp = (struct job *)((char *)jp + len);
4498 } while (--jq >= jp);
4503 * Return a new job structure.
4504 * Called with interrupts off.
4507 makejob(/*union node *node,*/ int nprocs)
4512 for (i = njobs, jp = jobtab; ; jp++) {
4519 if (jp->state != JOBDONE || !jp->waited)
4528 memset(jp, 0, sizeof(*jp));
4530 /* jp->jobctl is a bitfield.
4531 * "jp->jobctl |= doing_jobctl" likely to give awful code */
4535 jp->prev_job = curjob;
4540 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4542 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4549 * Return a string identifying a command (to be printed by the
4552 static char *cmdnextc;
4555 cmdputs(const char *s)
4557 static const char vstype[VSTYPE + 1][3] = {
4558 "", "}", "-", "+", "?", "=",
4559 "%", "%%", "#", "##"
4560 IF_BASH_SUBSTR(, ":")
4561 IF_BASH_PATTERN_SUBST(, "/", "//")
4564 const char *p, *str;
4568 unsigned char subtype = 0;
4572 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4574 while ((c = *p++) != '\0') {
4582 if ((subtype & VSTYPE) == VSLENGTH)
4588 str = "\"}" + !(quoted & 1);
4595 #if ENABLE_FEATURE_SH_MATH
4610 if ((subtype & VSTYPE) != VSNORMAL)
4612 str = vstype[subtype & VSTYPE];
4613 if (subtype & VSNUL)
4622 /* These can only happen inside quotes */
4635 while ((c = *str++) != '\0') {
4638 } /* while *p++ not NUL */
4641 USTPUTC('"', nextc);
4647 /* cmdtxt() and cmdlist() call each other */
4648 static void cmdtxt(union node *n);
4651 cmdlist(union node *np, int sep)
4653 for (; np; np = np->narg.next) {
4657 if (sep && np->narg.next)
4663 cmdtxt(union node *n)
4666 struct nodelist *lp;
4677 lp = n->npipe.cmdlist;
4695 cmdtxt(n->nbinary.ch1);
4711 cmdtxt(n->nif.test);
4713 if (n->nif.elsepart) {
4714 cmdtxt(n->nif.ifpart);
4716 n = n->nif.elsepart;
4734 cmdtxt(n->nbinary.ch1);
4744 cmdputs(n->nfor.var);
4746 cmdlist(n->nfor.args, 1);
4751 cmdputs(n->narg.text);
4755 cmdlist(n->ncmd.args, 1);
4756 cmdlist(n->ncmd.redirect, 0);
4769 cmdputs(n->ncase.expr->narg.text);
4771 for (np = n->ncase.cases; np; np = np->nclist.next) {
4772 cmdtxt(np->nclist.pattern);
4774 cmdtxt(np->nclist.body);
4788 #if BASH_REDIR_OUTPUT
4803 cmdputs(utoa(n->nfile.fd));
4805 if (n->type == NTOFD || n->type == NFROMFD) {
4806 cmdputs(utoa(n->ndup.dupfd));
4815 commandtext(union node *n)
4819 STARTSTACKSTR(cmdnextc);
4821 name = stackblock();
4822 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4823 return ckstrdup(name);
4828 * Fork off a subshell. If we are doing job control, give the subshell its
4829 * own process group. Jp is a job structure that the job is to be added to.
4830 * N is the command that will be evaluated by the child. Both jp and n may
4831 * be NULL. The mode parameter can be one of the following:
4832 * FORK_FG - Fork off a foreground process.
4833 * FORK_BG - Fork off a background process.
4834 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4835 * process group even if job control is on.
4837 * When job control is turned off, background processes have their standard
4838 * input redirected to /dev/null (except for the second and later processes
4841 * Called with interrupts off.
4844 * Clear traps on a fork.
4852 for (tp = trap; tp < &trap[NSIG]; tp++) {
4853 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4854 if (trap_ptr == trap)
4856 /* else: it "belongs" to trap_ptr vector, don't free */
4858 if ((tp - trap) != 0)
4859 setsignal(tp - trap);
4866 /* Lives far away from here, needed for forkchild */
4867 static void closescript(void);
4869 /* Called after fork(), in child */
4870 /* jp and n are NULL when called by openhere() for heredoc support */
4871 static NOINLINE void
4872 forkchild(struct job *jp, union node *n, int mode)
4876 TRACE(("Child shell %d\n", getpid()));
4880 /* man bash: "Non-builtin commands run by bash have signal handlers
4881 * set to the values inherited by the shell from its parent".
4882 * Do we do it correctly? */
4886 if (mode == FORK_NOJOB /* is it `xxx` ? */
4887 && n && n->type == NCMD /* is it single cmd? */
4888 /* && n->ncmd.args->type == NARG - always true? */
4889 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4890 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4891 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4893 TRACE(("Trap hack\n"));
4894 /* Awful hack for `trap` or $(trap).
4896 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4897 * contains an example where "trap" is executed in a subshell:
4899 * save_traps=$(trap)
4901 * eval "$save_traps"
4903 * Standard does not say that "trap" in subshell shall print
4904 * parent shell's traps. It only says that its output
4905 * must have suitable form, but then, in the above example
4906 * (which is not supposed to be normative), it implies that.
4908 * bash (and probably other shell) does implement it
4909 * (traps are reset to defaults, but "trap" still shows them),
4910 * but as a result, "trap" logic is hopelessly messed up:
4913 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4914 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4915 * # true | trap <--- trap is in subshell - no output (ditto)
4916 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4917 * trap -- 'echo Ho' SIGWINCH
4918 * # echo `(trap)` <--- in subshell in subshell - output
4919 * trap -- 'echo Ho' SIGWINCH
4920 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4921 * trap -- 'echo Ho' SIGWINCH
4923 * The rules when to forget and when to not forget traps
4924 * get really complex and nonsensical.
4926 * Our solution: ONLY bare $(trap) or `trap` is special.
4928 /* Save trap handler strings for trap builtin to print */
4929 trap_ptr = xmemdup(trap, sizeof(trap));
4930 /* Fall through into clearing traps */
4934 /* do job control only in root shell */
4936 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4939 if (jp->nprocs == 0)
4942 pgrp = jp->ps[0].ps_pid;
4943 /* this can fail because we are doing it in the parent also */
4945 if (mode == FORK_FG)
4946 xtcsetpgrp(ttyfd, pgrp);
4951 if (mode == FORK_BG) {
4952 /* man bash: "When job control is not in effect,
4953 * asynchronous commands ignore SIGINT and SIGQUIT" */
4956 if (jp->nprocs == 0) {
4958 if (open(bb_dev_null, O_RDONLY) != 0)
4959 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4963 if (iflag) { /* why if iflag only? */
4968 * "In all cases, bash ignores SIGQUIT. Non-builtin
4969 * commands run by bash have signal handlers
4970 * set to the values inherited by the shell
4972 * Take care of the second rule: */
4976 if (n && n->type == NCMD
4977 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4979 TRACE(("Job hack\n"));
4980 /* "jobs": we do not want to clear job list for it,
4981 * instead we remove only _its_ own_ job from job list.
4982 * This makes "jobs .... | cat" more useful.
4988 for (jp = curjob; jp; jp = jp->prev_job)
4993 /* Called after fork(), in parent */
4995 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4998 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
5000 TRACE(("In parent shell: child = %d\n", pid));
5002 /* jp is NULL when called by openhere() for heredoc support */
5003 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
5009 if (mode != FORK_NOJOB && jp->jobctl) {
5012 if (jp->nprocs == 0)
5015 pgrp = jp->ps[0].ps_pid;
5016 /* This can fail because we are doing it in the child also */
5020 if (mode == FORK_BG) {
5021 backgndpid = pid; /* set $! */
5022 set_curjob(jp, CUR_RUNNING);
5025 struct procstat *ps = &jp->ps[jp->nprocs++];
5028 ps->ps_cmd = nullstr;
5030 if (doing_jobctl && n)
5031 ps->ps_cmd = commandtext(n);
5036 /* jp and n are NULL when called by openhere() for heredoc support */
5038 forkshell(struct job *jp, union node *n, int mode)
5042 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
5045 TRACE(("Fork failed, errno=%d", errno));
5048 ash_msg_and_raise_error("can't fork");
5051 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
5052 forkchild(jp, n, mode);
5054 forkparent(jp, n, mode, pid);
5060 * Wait for job to finish.
5062 * Under job control we have the problem that while a child process
5063 * is running interrupts generated by the user are sent to the child
5064 * but not to the shell. This means that an infinite loop started by
5065 * an interactive user may be hard to kill. With job control turned off,
5066 * an interactive user may place an interactive program inside a loop.
5067 * If the interactive program catches interrupts, the user doesn't want
5068 * these interrupts to also abort the loop. The approach we take here
5069 * is to have the shell ignore interrupt signals while waiting for a
5070 * foreground process to terminate, and then send itself an interrupt
5071 * signal if the child process was terminated by an interrupt signal.
5072 * Unfortunately, some programs want to do a bit of cleanup and then
5073 * exit on interrupt; unless these processes terminate themselves by
5074 * sending a signal to themselves (instead of calling exit) they will
5075 * confuse this approach.
5077 * Called with interrupts off.
5080 waitforjob(struct job *jp)
5084 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
5087 while (jp->state == JOBRUNNING) {
5088 /* In non-interactive shells, we _can_ get
5089 * a keyboard signal here and be EINTRed,
5090 * but we just loop back, waiting for command to complete.
5093 * "If bash is waiting for a command to complete and receives
5094 * a signal for which a trap has been set, the trap
5095 * will not be executed until the command completes."
5097 * Reality is that even if trap is not set, bash
5098 * will not act on the signal until command completes.
5099 * Try this. sleep5intoff.c:
5100 * #include <signal.h>
5101 * #include <unistd.h>
5104 * sigemptyset(&set);
5105 * sigaddset(&set, SIGINT);
5106 * sigaddset(&set, SIGQUIT);
5107 * sigprocmask(SIG_BLOCK, &set, NULL);
5111 * $ bash -c './sleep5intoff; echo hi'
5112 * ^C^C^C^C <--- pressing ^C once a second
5114 * $ bash -c './sleep5intoff; echo hi'
5115 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5118 dowait(DOWAIT_BLOCK, jp);
5125 xtcsetpgrp(ttyfd, rootpid);
5126 restore_tty_if_stopped_or_signaled(jp);
5129 * This is truly gross.
5130 * If we're doing job control, then we did a TIOCSPGRP which
5131 * caused us (the shell) to no longer be in the controlling
5132 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5133 * intuit from the subprocess exit status whether a SIGINT
5134 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5136 if (jp->sigint) /* TODO: do the same with all signals */
5137 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5139 if (jp->state == JOBDONE)
5146 * return 1 if there are stopped jobs, otherwise 0
5158 if (jp && jp->state == JOBSTOPPED) {
5159 out2str("You have stopped jobs.\n");
5169 * Code for dealing with input/output redirection.
5174 #define EMPTY -2 /* marks an unused slot in redirtab */
5175 #define CLOSED -3 /* marks a slot of previously-closed fd */
5178 * Handle here documents. Normally we fork off a process to write the
5179 * data to a pipe. If the document is short, we can stuff the data in
5180 * the pipe without forking.
5182 /* openhere needs this forward reference */
5183 static void expandhere(union node *arg, int fd);
5185 openhere(union node *redir)
5191 ash_msg_and_raise_error("pipe call failed");
5192 if (redir->type == NHERE) {
5193 len = strlen(redir->nhere.doc->narg.text);
5194 if (len <= PIPE_BUF) {
5195 full_write(pip[1], redir->nhere.doc->narg.text, len);
5199 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5202 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5203 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5204 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5205 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5206 signal(SIGPIPE, SIG_DFL);
5207 if (redir->type == NHERE)
5208 full_write(pip[1], redir->nhere.doc->narg.text, len);
5210 expandhere(redir->nhere.doc, pip[1]);
5211 _exit(EXIT_SUCCESS);
5219 openredirect(union node *redir)
5225 switch (redir->nfile.type) {
5226 /* Can't happen, our single caller does this itself */
5232 return openhere(redir);
5235 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5236 * allocated space. Do it only when we know it is safe.
5238 fname = redir->nfile.expfname;
5240 switch (redir->nfile.type) {
5246 f = open(fname, O_RDONLY);
5251 f = open(fname, O_RDWR|O_CREAT, 0666);
5256 #if BASH_REDIR_OUTPUT
5259 /* Take care of noclobber mode. */
5261 if (stat(fname, &sb) < 0) {
5262 f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5265 } else if (!S_ISREG(sb.st_mode)) {
5266 f = open(fname, O_WRONLY, 0666);
5269 if (fstat(f, &sb) < 0 && S_ISREG(sb.st_mode)) {
5282 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5287 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5295 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5297 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5301 * Copy a file descriptor to be >= 10. Throws exception on error.
5309 newfd = fcntl(from, F_DUPFD, 10);
5310 err = newfd < 0 ? errno : 0;
5313 ash_msg_and_raise_error("%d: %m", from);
5315 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5321 dup2_or_raise(int from, int to)
5325 newfd = (from != to) ? dup2(from, to) : to;
5327 /* Happens when source fd is not open: try "echo >&99" */
5328 ash_msg_and_raise_error("%d: %m", from);
5333 /* Struct def and variable are moved down to the first usage site */
5338 struct redirtab *next;
5340 struct two_fd_t two_fd[];
5342 #define redirlist (G_var.redirlist)
5344 COPYFD_RESTORE = (int)~(INT_MAX),
5348 need_to_remember(struct redirtab *rp, int fd)
5352 if (!rp) /* remembering was not requested */
5355 for (i = 0; i < rp->pair_count; i++) {
5356 if (rp->two_fd[i].orig == fd) {
5357 /* already remembered */
5364 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5366 is_hidden_fd(struct redirtab *rp, int fd)
5369 struct parsefile *pf;
5373 /* Check open scripts' fds */
5376 /* We skip pf_fd == 0 case because of the following case:
5377 * $ ash # running ash interactively
5379 * and in script.sh: "exec 9>&0".
5380 * Even though top-level pf_fd _is_ 0,
5381 * it's still ok to use it: "read" builtin uses it,
5382 * why should we cripple "exec" builtin?
5384 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5392 /* Check saved fds of redirects */
5393 fd |= COPYFD_RESTORE;
5394 for (i = 0; i < rp->pair_count; i++) {
5395 if (rp->two_fd[i].copy == fd) {
5403 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5404 * old file descriptors are stashed away so that the redirection can be
5405 * undone by calling popredir.
5407 /* flags passed to redirect */
5408 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5409 #define REDIR_SAVEFD2 03 /* set preverrout */
5411 redirect(union node *redir, int flags)
5413 struct redirtab *sv;
5418 int copied_fd2 = -1;
5427 if (flags & REDIR_PUSH) {
5428 union node *tmp = redir;
5431 #if BASH_REDIR_OUTPUT
5432 if (tmp->nfile.type == NTO2)
5435 tmp = tmp->nfile.next;
5437 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5438 sv->next = redirlist;
5439 sv->pair_count = sv_pos;
5441 while (sv_pos > 0) {
5443 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5449 fd = redir->nfile.fd;
5450 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5451 right_fd = redir->ndup.dupfd;
5452 //bb_error_msg("doing %d > %d", fd, right_fd);
5453 /* redirect from/to same file descriptor? */
5456 /* "echo >&10" and 10 is a fd opened to a sh script? */
5457 if (is_hidden_fd(sv, right_fd)) {
5458 errno = EBADF; /* as if it is closed */
5459 ash_msg_and_raise_error("%d: %m", right_fd);
5463 newfd = openredirect(redir); /* always >= 0 */
5465 /* Descriptor wasn't open before redirect.
5466 * Mark it for close in the future */
5467 if (need_to_remember(sv, fd)) {
5468 goto remember_to_close;
5473 #if BASH_REDIR_OUTPUT
5476 if (need_to_remember(sv, fd)) {
5477 /* Copy old descriptor */
5478 /* Careful to not accidentally "save"
5479 * to the same fd as right side fd in N>&M */
5480 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5481 #if defined(F_DUPFD_CLOEXEC)
5482 i = fcntl(fd, F_DUPFD_CLOEXEC, minfd);
5484 i = fcntl(fd, F_DUPFD, minfd);
5489 /* Strange error (e.g. "too many files" EMFILE?) */
5493 ash_msg_and_raise_error("%d: %m", fd);
5496 /* EBADF: it is not open - good, remember to close it */
5499 } else { /* fd is open, save its copy */
5500 #if !defined(F_DUPFD_CLOEXEC)
5501 fcntl(i, F_SETFD, FD_CLOEXEC);
5503 /* "exec fd>&-" should not close fds
5504 * which point to script file(s).
5505 * Force them to be restored afterwards */
5506 if (is_hidden_fd(sv, fd))
5507 i |= COPYFD_RESTORE;
5511 sv->two_fd[sv_pos].orig = fd;
5512 sv->two_fd[sv_pos].copy = i;
5516 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5517 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5518 /* Don't want to trigger debugging */
5522 dup2_or_raise(redir->ndup.dupfd, fd);
5524 } else if (fd != newfd) { /* move newfd to fd */
5525 dup2_or_raise(newfd, fd);
5526 #if BASH_REDIR_OUTPUT
5527 if (!(redir->nfile.type == NTO2 && fd == 2))
5531 #if BASH_REDIR_OUTPUT
5532 if (redir->nfile.type == NTO2 && fd == 1) {
5533 /* We already redirected it to fd 1, now copy it to 2 */
5539 } while ((redir = redir->nfile.next) != NULL);
5542 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5543 preverrout_fd = copied_fd2;
5547 * Undo the effects of the last redirection.
5550 popredir(int drop, int restore)
5552 struct redirtab *rp;
5555 if (redirlist == NULL)
5559 for (i = 0; i < rp->pair_count; i++) {
5560 int fd = rp->two_fd[i].orig;
5561 int copy = rp->two_fd[i].copy;
5562 if (copy == CLOSED) {
5567 if (copy != EMPTY) {
5568 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5569 copy &= ~COPYFD_RESTORE;
5571 dup2_or_raise(copy, fd);
5573 close(copy & ~COPYFD_RESTORE);
5576 redirlist = rp->next;
5582 * Undo all redirections. Called on error or interrupt.
5586 redirectsafe(union node *redir, int flags)
5589 volatile int saveint;
5590 struct jmploc *volatile savehandler = exception_handler;
5591 struct jmploc jmploc;
5594 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5595 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5597 exception_handler = &jmploc;
5598 redirect(redir, flags);
5600 exception_handler = savehandler;
5601 if (err && exception_type != EXERROR)
5602 longjmp(exception_handler->loc, 1);
5603 RESTORE_INT(saveint);
5608 /* ============ Routines to expand arguments to commands
5610 * We have to deal with backquotes, shell variables, and file metacharacters.
5613 #if ENABLE_FEATURE_SH_MATH
5615 ash_arith(const char *s)
5617 arith_state_t math_state;
5620 math_state.lookupvar = lookupvar;
5621 math_state.setvar = setvar0;
5622 //math_state.endofname = endofname;
5625 result = arith(&math_state, s);
5626 if (math_state.errmsg)
5627 ash_msg_and_raise_error(math_state.errmsg);
5637 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5638 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5639 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5640 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5641 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5642 * POSIX says for this case:
5643 * Pathname expansion shall not be performed on the word by a
5644 * non-interactive shell; an interactive shell may perform it, but shall
5645 * do so only when the expansion would result in one word.
5646 * Currently, our code complies to the above rule by never globbing
5647 * redirection filenames.
5648 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5649 * (this means that on a typical Linux distro, bash almost always
5650 * performs globbing, and thus diverges from what we do).
5652 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5653 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5654 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5655 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5656 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5660 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5661 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5662 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5663 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5664 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5666 /* Add CTLESC when necessary. */
5667 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT)
5668 /* Do not skip NUL characters. */
5669 #define QUOTES_KEEPNUL EXP_TILDE
5672 * Structure specifying which parts of the string should be searched
5673 * for IFS characters.
5676 struct ifsregion *next; /* next region in list */
5677 int begoff; /* offset of start of region */
5678 int endoff; /* offset of end of region */
5679 int nulonly; /* search for nul bytes only */
5683 struct strlist *list;
5684 struct strlist **lastp;
5687 /* output of current string */
5688 static char *expdest;
5689 /* list of back quote expressions */
5690 static struct nodelist *argbackq;
5691 /* first struct in list of ifs regions */
5692 static struct ifsregion ifsfirst;
5693 /* last struct in list */
5694 static struct ifsregion *ifslastp;
5695 /* holds expanded arg list */
5696 static struct arglist exparg;
5701 #if !ENABLE_FEATURE_SH_MATH
5702 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5703 typedef long arith_t;
5704 # define ARITH_FMT "%ld"
5711 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5712 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5713 STADJUST(len, expdest);
5718 * Break the argument string into pieces based upon IFS and add the
5719 * strings to the argument list. The regions of the string to be
5720 * searched for IFS characters have been stored by recordregion.
5723 ifsbreakup(char *string, struct arglist *arglist)
5725 struct ifsregion *ifsp;
5730 const char *ifs, *realifs;
5735 if (ifslastp != NULL) {
5738 realifs = ifsset() ? ifsval() : defifs;
5741 p = string + ifsp->begoff;
5742 nulonly = ifsp->nulonly;
5743 ifs = nulonly ? nullstr : realifs;
5745 while (p < string + ifsp->endoff) {
5747 if ((unsigned char)*p == CTLESC)
5749 if (!strchr(ifs, *p)) {
5754 ifsspc = (strchr(defifs, *p) != NULL);
5755 /* Ignore IFS whitespace at start */
5756 if (q == start && ifsspc) {
5762 sp = stzalloc(sizeof(*sp));
5764 *arglist->lastp = sp;
5765 arglist->lastp = &sp->next;
5769 if (p >= string + ifsp->endoff) {
5773 if ((unsigned char)*p == CTLESC)
5775 if (strchr(ifs, *p) == NULL) {
5779 if (strchr(defifs, *p) == NULL) {
5794 } while (ifsp != NULL);
5803 sp = stzalloc(sizeof(*sp));
5805 *arglist->lastp = sp;
5806 arglist->lastp = &sp->next;
5812 struct ifsregion *p = ifsfirst.next;
5819 struct ifsregion *ifsp;
5824 ifsfirst.next = NULL;
5831 esclen(const char *start, const char *p)
5835 while (p > start && (unsigned char)*--p == CTLESC) {
5842 * Remove any CTLESC characters from a string.
5845 rmescapes(char *str, int flag)
5847 static const char qchars[] ALIGN1 = {
5848 IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
5852 unsigned protect_against_glob;
5854 IF_BASH_PATTERN_SUBST(unsigned slash = flag & RMESCAPE_SLASH;)
5856 p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash));
5862 if (flag & RMESCAPE_ALLOC) {
5863 size_t len = p - str;
5864 size_t fulllen = len + strlen(p) + 1;
5866 if (flag & RMESCAPE_GROW) {
5867 int strloc = str - (char *)stackblock();
5868 r = makestrspace(fulllen, expdest);
5869 /* p and str may be invalidated by makestrspace */
5870 str = (char *)stackblock() + strloc;
5872 } else if (flag & RMESCAPE_HEAP) {
5873 r = ckmalloc(fulllen);
5875 r = stalloc(fulllen);
5879 q = (char *)mempcpy(q, str, len);
5884 globbing = flag & RMESCAPE_GLOB;
5885 protect_against_glob = globbing;
5887 if ((unsigned char)*p == CTLQUOTEMARK) {
5888 // Note: both inquotes and protect_against_glob only affect whether
5889 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5890 inquotes = ~inquotes;
5892 protect_against_glob = globbing;
5895 if ((unsigned char)*p == CTLESC) {
5899 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5901 if (protect_against_glob) {
5903 * We used to trust glob() and fnmatch() to eat
5904 * superfluous escapes (\z where z has no
5905 * special meaning anyway). But this causes
5906 * bugs such as string of one greek letter rho
5907 * (unicode-encoded as two bytes "cf,81")
5908 * getting encoded as "cf,CTLESC,81"
5909 * and here, converted to "cf,\,81" -
5910 * which does not go well with some flavors
5911 * of fnmatch() in unicode locales
5912 * (for example, glibc <= 2.22).
5914 * Lets add "\" only on the chars which need it.
5915 * Testcases for less obvious chars are shown.
5920 || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
5921 || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
5922 || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
5923 || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
5924 /* Some libc support [^negate], that's why "^" also needs love */
5925 || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
5930 } else if (*p == '\\' && !inquotes) {
5931 /* naked back slash */
5932 protect_against_glob = 0;
5935 #if BASH_PATTERN_SUBST
5936 else if (*p == '/' && slash) {
5937 /* stop handling globbing and mark location of slash */
5938 globbing = slash = 0;
5942 protect_against_glob = globbing;
5947 if (flag & RMESCAPE_GROW) {
5949 STADJUST(q - r + 1, expdest);
5953 #define pmatch(a, b) !fnmatch((a), (b), 0)
5956 * Prepare a pattern for a expmeta (internal glob(3)) call.
5958 * Returns an stalloced string.
5961 preglob(const char *pattern, int flag)
5963 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5967 * Put a string on the stack.
5970 memtodest(const char *p, size_t len, int syntax, int quotes)
5977 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5980 unsigned char c = *p++;
5982 if (quotes & QUOTES_ESC) {
5983 int n = SIT(c, syntax);
5985 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
5992 } else if (!(quotes & QUOTES_KEEPNUL))
6001 strtodest(const char *p, int syntax, int quotes)
6003 size_t len = strlen(p);
6004 memtodest(p, len, syntax, quotes);
6009 * Record the fact that we have to scan this region of the
6010 * string for IFS characters.
6013 recordregion(int start, int end, int nulonly)
6015 struct ifsregion *ifsp;
6017 if (ifslastp == NULL) {
6021 ifsp = ckzalloc(sizeof(*ifsp));
6022 /*ifsp->next = NULL; - ckzalloc did it */
6023 ifslastp->next = ifsp;
6027 ifslastp->begoff = start;
6028 ifslastp->endoff = end;
6029 ifslastp->nulonly = nulonly;
6033 removerecordregions(int endoff)
6035 if (ifslastp == NULL)
6038 if (ifsfirst.endoff > endoff) {
6039 while (ifsfirst.next) {
6040 struct ifsregion *ifsp;
6042 ifsp = ifsfirst.next->next;
6043 free(ifsfirst.next);
6044 ifsfirst.next = ifsp;
6047 if (ifsfirst.begoff > endoff) {
6050 ifslastp = &ifsfirst;
6051 ifsfirst.endoff = endoff;
6056 ifslastp = &ifsfirst;
6057 while (ifslastp->next && ifslastp->next->begoff < endoff)
6058 ifslastp = ifslastp->next;
6059 while (ifslastp->next) {
6060 struct ifsregion *ifsp;
6062 ifsp = ifslastp->next->next;
6063 free(ifslastp->next);
6064 ifslastp->next = ifsp;
6067 if (ifslastp->endoff > endoff)
6068 ifslastp->endoff = endoff;
6072 exptilde(char *startp, char *p, int flags)
6078 int quotes = flags & QUOTES_ESC;
6082 while ((c = *++p) != '\0') {
6089 if (flags & EXP_VARTILDE)
6099 if (*name == '\0') {
6100 home = lookupvar("HOME");
6102 pw = getpwnam(name);
6107 if (!home || !*home)
6110 strtodest(home, SQSYNTAX, quotes);
6118 * Execute a command inside back quotes. If it's a builtin command, we
6119 * want to save its output in a block obtained from malloc. Otherwise
6120 * we fork off a subprocess and get the output of the command via a pipe.
6121 * Should be called with interrupts off.
6123 struct backcmd { /* result of evalbackcmd */
6124 int fd; /* file descriptor to read from */
6125 int nleft; /* number of chars in buffer */
6126 char *buf; /* buffer */
6127 struct job *jp; /* job structure for command */
6130 /* These forward decls are needed to use "eval" code for backticks handling: */
6131 #define EV_EXIT 01 /* exit after evaluating tree */
6132 static int evaltree(union node *, int);
6134 static void FAST_FUNC
6135 evalbackcmd(union node *n, struct backcmd *result)
6149 ash_msg_and_raise_error("pipe call failed");
6150 jp = makejob(/*n,*/ 1);
6151 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6157 dup2_or_raise(pip[1], 1);
6160 /* TODO: eflag clearing makes the following not abort:
6161 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6162 * which is what bash does (unless it is in POSIX mode).
6163 * dash deleted "eflag = 0" line in the commit
6164 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6165 * [EVAL] Don't clear eflag in evalbackcmd
6166 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6170 evaltree(n, EV_EXIT); /* actually evaltreenr... */
6175 result->fd = pip[0];
6179 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6180 result->fd, result->buf, result->nleft, result->jp));
6184 * Expand stuff in backwards quotes.
6187 expbackq(union node *cmd, int flag)
6195 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6196 struct stackmark smark;
6199 startloc = expdest - (char *)stackblock();
6200 pushstackmark(&smark, startloc);
6201 evalbackcmd(cmd, &in);
6202 popstackmark(&smark);
6209 memtodest(p, i, syntax, flag & QUOTES_ESC);
6213 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6214 TRACE(("expbackq: read returns %d\n", i));
6223 back_exitstatus = waitforjob(in.jp);
6227 /* Eat all trailing newlines */
6229 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6233 if (!(flag & EXP_QUOTED))
6234 recordregion(startloc, dest - (char *)stackblock(), 0);
6235 TRACE(("evalbackq: size:%d:'%.*s'\n",
6236 (int)((dest - (char *)stackblock()) - startloc),
6237 (int)((dest - (char *)stackblock()) - startloc),
6238 stackblock() + startloc));
6241 #if ENABLE_FEATURE_SH_MATH
6243 * Expand arithmetic expression. Backup to start of expression,
6244 * evaluate, place result in (backed up) result, adjust string position.
6256 * This routine is slightly over-complicated for
6257 * efficiency. Next we scan backwards looking for the
6258 * start of arithmetic.
6260 start = stackblock();
6267 while ((unsigned char)*p != CTLARI) {
6271 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6276 esc = esclen(start, p);
6286 removerecordregions(begoff);
6290 if (flag & QUOTES_ESC)
6291 rmescapes(p + 1, 0);
6293 len = cvtnum(ash_arith(p + 1));
6295 if (!(flag & EXP_QUOTED))
6296 recordregion(begoff, begoff + len, 0);
6300 /* argstr needs it */
6301 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6304 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6305 * characters to allow for further processing. Otherwise treat
6306 * $@ like $* since no splitting will be performed.
6308 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6309 * over shell variables. Needed for "A=a B=$A; echo $B" case - we use it
6310 * for correct expansion of "B=$A" word.
6313 argstr(char *p, int flags, struct strlist *var_str_list)
6315 static const char spclchars[] ALIGN1 = {
6323 #if ENABLE_FEATURE_SH_MATH
6328 const char *reject = spclchars;
6329 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6334 if (!(flags & EXP_VARTILDE)) {
6336 } else if (flags & EXP_VARTILDE2) {
6341 if (flags & EXP_TILDE) {
6344 flags &= ~EXP_TILDE;
6348 p = exptilde(p, q, flags);
6351 startloc = expdest - (char *)stackblock();
6355 length += strcspn(p + length, reject);
6359 IF_FEATURE_SH_MATH(|| c == CTLENDARI)
6361 /* c == '=' || c == ':' || c == CTLENDARI */
6367 expdest = stack_nputstr(p, length, expdest);
6368 newloc = expdest - (char *)stackblock();
6369 if (breakall && !inquotes && newloc > startloc) {
6370 recordregion(startloc, newloc, 0);
6381 if (flags & EXP_VARTILDE2) {
6385 flags |= EXP_VARTILDE2;
6390 * sort of a hack - expand tildes in variable
6391 * assignments (after the first '=' and after ':'s).
6400 case CTLENDVAR: /* ??? */
6403 inquotes ^= EXP_QUOTED;
6404 /* "$@" syntax adherence hack */
6405 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6406 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6410 if (flags & QUOTES_ESC) {
6421 * Quoted parameter expansion pattern: remove quote
6422 * unless inside inner quotes or we have a literal
6425 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6426 EXP_QPAT && *p != '\\')
6431 TRACE(("argstr: evalvar('%s')\n", p));
6432 p = evalvar(p, flags | inquotes, var_str_list);
6433 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6436 expbackq(argbackq->n, flags | inquotes);
6437 argbackq = argbackq->next;
6439 #if ENABLE_FEATURE_SH_MATH
6442 expari(flags | inquotes);
6451 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6452 char *pattern, int quotes, int zero)
6461 const char *s = loc2;
6468 match = pmatch(pattern, s);
6473 if (quotes && (unsigned char)*loc == CTLESC)
6482 scanright(char *startp, char *rmesc, char *rmescend,
6483 char *pattern, int quotes, int match_at_start)
6485 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6486 int try2optimize = match_at_start;
6492 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6493 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6494 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6496 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6497 * and on each iteration they go back two/one char until they reach the beginning.
6498 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6500 /* TODO: document in what other circumstances we are called. */
6502 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6505 const char *s = loc2;
6506 if (match_at_start) {
6510 match = pmatch(pattern, s);
6511 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6515 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6517 /* Maybe we can optimize this:
6518 * if pattern ends with unescaped *, we can avoid checking
6519 * shorter strings: if "foo*" doesn't match "raw_value_of_v",
6520 * it won't match truncated "raw_value_of_" strings too.
6522 unsigned plen = strlen(pattern);
6523 /* Does it end with "*"? */
6524 if (plen != 0 && pattern[--plen] == '*') {
6525 /* "xxxx*" is not escaped */
6526 /* "xxx\*" is escaped */
6527 /* "xx\\*" is not escaped */
6528 /* "x\\\*" is escaped */
6530 while (plen != 0 && pattern[--plen] == '\\')
6533 break; /* ends with unescaped "*" */
6541 esc = esclen(startp, loc);
6552 static void varunset(const char *, const char *, const char *, int) NORETURN;
6554 varunset(const char *end, const char *var, const char *umsg, int varflags)
6560 msg = "parameter not set";
6562 if ((unsigned char)*end == CTLENDVAR) {
6563 if (varflags & VSNUL)
6569 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6573 subevalvar(char *p, char *varname, int strloc, int subtype,
6574 int startloc, int varflags, int flag, struct strlist *var_str_list)
6576 struct nodelist *saveargbackq = argbackq;
6577 int quotes = flag & QUOTES_ESC;
6580 char *rmesc, *rmescend;
6582 int amount, resetloc;
6583 IF_BASH_PATTERN_SUBST(int workloc;)
6584 IF_BASH_PATTERN_SUBST(char *repl = NULL;)
6586 char *(*scan)(char*, char*, char*, char*, int, int);
6588 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6589 // p, varname, strloc, subtype, startloc, varflags, quotes);
6591 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6592 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6594 STPUTC('\0', expdest);
6595 argbackq = saveargbackq;
6596 startp = (char *)stackblock() + startloc;
6600 setvar0(varname, startp);
6601 amount = startp - expdest;
6602 STADJUST(amount, expdest);
6606 varunset(p, varname, startp, varflags);
6611 int pos, len, orig_len;
6614 loc = str = stackblock() + strloc;
6616 # if !ENABLE_FEATURE_SH_MATH
6617 # define ash_arith number
6619 /* Read POS in ${var:POS:LEN} */
6620 colon = strchr(loc, ':');
6621 if (colon) *colon = '\0';
6622 pos = ash_arith(loc);
6623 if (colon) *colon = ':';
6625 /* Read LEN in ${var:POS:LEN} */
6626 len = str - startp - 1;
6627 /* *loc != '\0', guaranteed by parser */
6631 /* Adjust the length by the number of escapes */
6632 for (ptr = startp; ptr < (str - 1); ptr++) {
6633 if ((unsigned char)*ptr == CTLESC) {
6640 if (*loc++ == ':') {
6642 len = ash_arith(loc);
6644 /* Skip POS in ${var:POS:LEN} */
6646 while (*loc && *loc != ':') {
6649 if (*loc++ == ':') {
6650 len = ash_arith(loc);
6656 /* ${VAR:$((-n)):l} starts n chars from the end */
6657 pos = orig_len + pos;
6659 if ((unsigned)pos >= orig_len) {
6660 /* apart from obvious ${VAR:999999:l},
6661 * covers ${VAR:$((-9999999)):l} - result is ""
6668 /* ${VAR:N:-M} sets LEN to strlen()-M */
6669 len = (orig_len - pos) + len;
6671 if ((unsigned)len > (orig_len - pos))
6672 len = orig_len - pos;
6674 for (str = startp; pos; str++, pos--) {
6675 if (quotes && (unsigned char)*str == CTLESC)
6678 for (loc = startp; len; len--) {
6679 if (quotes && (unsigned char)*str == CTLESC)
6684 amount = loc - expdest;
6685 STADJUST(amount, expdest);
6688 #endif /* BASH_SUBSTR */
6691 resetloc = expdest - (char *)stackblock();
6693 #if BASH_PATTERN_SUBST
6694 /* We'll comeback here if we grow the stack while handling
6695 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6696 * stack will need rebasing, and we'll need to remove our work
6702 amount = expdest - ((char *)stackblock() + resetloc);
6703 STADJUST(-amount, expdest);
6704 startp = (char *)stackblock() + startloc;
6707 rmescend = (char *)stackblock() + strloc;
6709 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6710 if (rmesc != startp) {
6712 startp = (char *)stackblock() + startloc;
6716 str = (char *)stackblock() + strloc;
6718 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6719 * The result is a_\_z_c (not a\_\_z_c)!
6721 * The search pattern and replace string treat backslashes differently!
6722 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6723 * and string. It's only used on the first call.
6725 preglob(str, IF_BASH_PATTERN_SUBST(
6726 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6727 RMESCAPE_SLASH : ) 0);
6729 #if BASH_PATTERN_SUBST
6730 workloc = expdest - (char *)stackblock();
6731 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6736 repl = strchr(str, CTLESC);
6742 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6744 /* If there's no pattern to match, return the expansion unmolested */
6753 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6754 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6756 /* No match, advance */
6757 char *restart_detect = stackblock();
6759 STPUTC(*idx, expdest);
6760 if (quotes && (unsigned char)*idx == CTLESC) {
6763 STPUTC(*idx, expdest);
6765 if (stackblock() != restart_detect)
6770 /* continue; - prone to quadratic behavior, smarter code: */
6773 if (str[0] == '*') {
6774 /* Pattern is "*foo". If "*foo" does not match "long_string",
6775 * it would never match "ong_string" etc, no point in trying.
6782 if (subtype == VSREPLACEALL) {
6784 if (quotes && (unsigned char)*idx == CTLESC)
6793 //bb_error_msg("repl:'%s'", repl);
6794 for (loc = (char*)repl; *loc; loc++) {
6795 char *restart_detect = stackblock();
6796 if (quotes && *loc == '\\') {
6797 STPUTC(CTLESC, expdest);
6800 STPUTC(*loc, expdest);
6801 if (stackblock() != restart_detect)
6806 if (subtype == VSREPLACE) {
6807 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6809 char *restart_detect = stackblock();
6810 STPUTC(*idx, expdest);
6811 if (stackblock() != restart_detect)
6820 /* We've put the replaced text into a buffer at workloc, now
6821 * move it to the right place and adjust the stack.
6823 STPUTC('\0', expdest);
6824 startp = (char *)stackblock() + startloc;
6825 memmove(startp, (char *)stackblock() + workloc, len + 1);
6826 //bb_error_msg("startp:'%s'", startp);
6827 amount = expdest - (startp + len);
6828 STADJUST(-amount, expdest);
6831 #endif /* BASH_PATTERN_SUBST */
6833 subtype -= VSTRIMRIGHT;
6835 if (subtype < 0 || subtype > 7)
6838 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6839 zero = subtype >> 1;
6840 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6841 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6843 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6846 memmove(startp, loc, str - loc);
6847 loc = startp + (str - loc) - 1;
6850 amount = loc - expdest;
6851 STADJUST(amount, expdest);
6857 * Add the value of a specialized variable to the stack string.
6858 * name parameter (examples):
6859 * ash -c 'echo $1' name:'1='
6860 * ash -c 'echo $qwe' name:'qwe='
6861 * ash -c 'echo $$' name:'$='
6862 * ash -c 'echo ${$}' name:'$='
6863 * ash -c 'echo ${$##q}' name:'$=q'
6864 * ash -c 'echo ${#$}' name:'$='
6865 * note: examples with bad shell syntax:
6866 * ash -c 'echo ${#$1}' name:'$=1'
6867 * ash -c 'echo ${#1#}' name:'1=#'
6869 static NOINLINE ssize_t
6870 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list, int *quotedp)
6877 int quoted = *quotedp;
6878 int subtype = varflags & VSTYPE;
6879 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6880 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6883 sep = (flags & EXP_FULL) << CHAR_BIT;
6884 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6894 num = shellparam.nparam;
6902 goto check_1char_name;
6904 expdest = makestrspace(NOPTS, expdest);
6905 for (i = NOPTS - 1; i >= 0; i--) {
6907 USTPUTC(optletters(i), expdest);
6913 /* handles cases similar to ${#$1} */
6914 if (name[2] != '\0')
6915 raise_error_syntax("bad substitution");
6928 sep |= ifsset() ? ifsval()[0] : ' ';
6935 while ((p = *ap++) != NULL) {
6936 len += strtodest(p, syntax, quotes);
6940 memtodest(&sepc, 1, syntax, quotes);
6955 num = atoi(name); /* number(name) fails on ${N#str} etc */
6956 if (num < 0 || num > shellparam.nparam)
6958 p = num ? shellparam.p[num - 1] : arg0;
6961 /* NB: name has form "VAR=..." */
6963 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6964 * which should be considered before we check variables. */
6966 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6970 str = var_str_list->text;
6971 eq = strchr(str, '=');
6972 if (!eq) /* stop at first non-assignment */
6975 if (name_len == (unsigned)(eq - str)
6976 && strncmp(str, name, name_len) == 0
6979 /* goto value; - WRONG! */
6980 /* think "A=1 A=2 B=$A" */
6982 var_str_list = var_str_list->next;
6983 } while (var_str_list);
6987 p = lookupvar(name);
6992 len = strtodest(p, syntax, quotes);
6993 #if ENABLE_UNICODE_SUPPORT
6994 if (subtype == VSLENGTH && len > 0) {
6995 reinit_unicode_for_ash();
6996 if (unicode_status == UNICODE_ON) {
6997 STADJUST(-len, expdest);
6999 len = unicode_strlen(p);
7007 STADJUST(-len, expdest);
7012 * Expand a variable, and return a pointer to the next character in the
7016 evalvar(char *p, int flag, struct strlist *var_str_list)
7027 varflags = (unsigned char) *p++;
7028 subtype = varflags & VSTYPE;
7031 raise_error_syntax("bad substitution");
7033 quoted = flag & EXP_QUOTED;
7035 easy = (!quoted || (*var == '@' && shellparam.nparam));
7036 startloc = expdest - (char *)stackblock();
7037 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
7040 varlen = varvalue(var, varflags, flag, var_str_list, "ed);
7041 if (varflags & VSNUL)
7044 if (subtype == VSPLUS) {
7045 varlen = -1 - varlen;
7049 if (subtype == VSMINUS) {
7054 flag | EXP_TILDE | EXP_WORD,
7062 if (subtype == VSASSIGN || subtype == VSQUESTION) {
7066 subevalvar(p, var, 0, subtype, startloc, varflags,
7067 flag & ~QUOTES_ESC, var_str_list);
7070 * Remove any recorded regions beyond
7073 removerecordregions(startloc);
7077 if (varlen < 0 && uflag)
7078 varunset(p, var, 0, 0);
7080 if (subtype == VSLENGTH) {
7081 cvtnum(varlen > 0 ? varlen : 0);
7085 if (subtype == VSNORMAL) {
7089 recordregion(startloc, expdest - (char *)stackblock(), quoted);
7098 case VSTRIMRIGHTMAX:
7102 #if BASH_PATTERN_SUBST
7114 * Terminate the string and start recording the pattern
7117 STPUTC('\0', expdest);
7118 patloc = expdest - (char *)stackblock();
7119 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7120 startloc, varflags, flag, var_str_list)) {
7121 int amount = expdest - (
7122 (char *)stackblock() + patloc - 1
7124 STADJUST(-amount, expdest);
7126 /* Remove any recorded regions beyond start of variable */
7127 removerecordregions(startloc);
7132 if (subtype != VSNORMAL) { /* skip to end of alternative */
7135 unsigned char c = *p++;
7138 else if (c == CTLBACKQ) {
7140 argbackq = argbackq->next;
7141 } else if (c == CTLVAR) {
7142 if ((*p++ & VSTYPE) != VSNORMAL)
7144 } else if (c == CTLENDVAR) {
7154 * Add a file name to the list.
7157 addfname(const char *name)
7161 sp = stzalloc(sizeof(*sp));
7162 sp->text = sstrdup(name);
7164 exparg.lastp = &sp->next;
7167 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7169 hasmeta(const char *p)
7171 static const char chars[] ALIGN1 = {
7172 '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
7176 p = strpbrk(p, chars);
7179 switch ((unsigned char) *p) {
7183 if (*p == CTLQUOTEMARK)
7187 if (*p == '\0') /* huh? */
7198 if (!strchr(p + 1, ']')) {
7199 /* It's not a properly closed [] pattern,
7200 * but other metas may follow. Continue checking.
7201 * my[file* _is_ globbed by bash
7202 * and matches filenames like "my[file1".
7218 /* If we want to use glob() from libc... */
7219 #if !ENABLE_ASH_INTERNAL_GLOB
7221 /* Add the result of glob() to the list */
7223 addglob(const glob_t *pglob)
7225 char **p = pglob->gl_pathv;
7232 expandmeta(struct strlist *str /*, int flag*/)
7234 /* TODO - EXP_REDIR */
7244 if (!hasmeta(str->text))
7248 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7249 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7250 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7252 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7253 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7254 // Which means you need to unescape the string, right? Not so fast:
7255 // if there _is_ a file named "file\?" (with backslash), it is returned
7256 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7257 // You DON'T KNOW by looking at the result whether you need to unescape it.
7259 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7260 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7261 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7262 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7263 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7264 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7265 i = glob(p, 0, NULL, &pglob);
7266 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7271 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7272 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7273 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7285 *exparg.lastp = str;
7286 rmescapes(str->text, 0);
7287 exparg.lastp = &str->next;
7289 default: /* GLOB_NOSPACE */
7292 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7299 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7302 * Do metacharacter (i.e. *, ?, [...]) expansion.
7305 expmeta(char *expdir, char *enddir, char *name)
7321 for (p = name; esc = 0, *p; p += esc + 1) {
7322 if (*p == '*' || *p == '?')
7324 else if (*p == '[') {
7331 if (*q == '/' || *q == '\0')
7341 if (p[esc] == '/') {
7344 start = p + esc + 1;
7348 if (metaflag == 0) { /* we've reached the end of the file name */
7349 if (enddir != expdir)
7357 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7368 } while (p < start);
7370 if (enddir == expdir) {
7372 } else if (enddir == expdir + 1 && *expdir == '/') {
7381 if (enddir != expdir)
7383 if (*endname == 0) {
7396 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7397 if (dp->d_name[0] == '.' && !matchdot)
7399 if (pmatch(start, dp->d_name)) {
7401 strcpy(enddir, dp->d_name);
7404 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7407 expmeta(expdir, p, endname);
7413 endname[-esc - 1] = esc ? '\\' : '/';
7416 static struct strlist *
7417 msort(struct strlist *list, int len)
7419 struct strlist *p, *q = NULL;
7420 struct strlist **lpp;
7428 for (n = half; --n >= 0;) {
7432 q->next = NULL; /* terminate first half of list */
7433 q = msort(list, half); /* sort first half of list */
7434 p = msort(p, len - half); /* sort second half */
7437 #if ENABLE_LOCALE_SUPPORT
7438 if (strcoll(p->text, q->text) < 0)
7440 if (strcmp(p->text, q->text) < 0)
7464 * Sort the results of file name expansion. It calculates the number of
7465 * strings to sort and then calls msort (short for merge sort) to do the
7468 static struct strlist *
7469 expsort(struct strlist *str)
7475 for (sp = str; sp; sp = sp->next)
7477 return msort(str, len);
7481 expandmeta(struct strlist *str /*, int flag*/)
7483 /* TODO - EXP_REDIR */
7487 struct strlist **savelastp;
7493 if (!hasmeta(str->text))
7495 savelastp = exparg.lastp;
7498 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7500 int i = strlen(str->text);
7501 //BUGGY estimation of how long expanded name can be
7502 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7504 expmeta(expdir, expdir, p);
7509 if (exparg.lastp == savelastp) {
7514 *exparg.lastp = str;
7515 rmescapes(str->text, 0);
7516 exparg.lastp = &str->next;
7518 *exparg.lastp = NULL;
7519 *savelastp = sp = expsort(*savelastp);
7520 while (sp->next != NULL)
7522 exparg.lastp = &sp->next;
7527 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7530 * Perform variable substitution and command substitution on an argument,
7531 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7532 * perform splitting and file name expansion. When arglist is NULL, perform
7533 * here document expansion.
7536 expandarg(union node *arg, struct arglist *arglist, int flag)
7541 argbackq = arg->narg.backquote;
7542 STARTSTACKSTR(expdest);
7543 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7544 argstr(arg->narg.text, flag,
7545 /* var_str_list: */ arglist ? arglist->list : NULL);
7546 p = _STPUTC('\0', expdest);
7548 if (arglist == NULL) {
7549 /* here document expanded */
7552 p = grabstackstr(p);
7553 TRACE(("expandarg: p:'%s'\n", p));
7554 exparg.lastp = &exparg.list;
7558 if (flag & EXP_FULL) {
7559 ifsbreakup(p, &exparg);
7560 *exparg.lastp = NULL;
7561 exparg.lastp = &exparg.list;
7562 expandmeta(exparg.list /*, flag*/);
7564 sp = stzalloc(sizeof(*sp));
7567 exparg.lastp = &sp->next;
7569 *exparg.lastp = NULL;
7571 *arglist->lastp = exparg.list;
7572 arglist->lastp = exparg.lastp;
7580 * Expand shell variables and backquotes inside a here document.
7583 expandhere(union node *arg, int fd)
7585 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7586 full_write(fd, stackblock(), expdest - (char *)stackblock());
7590 * Returns true if the pattern matches the string.
7593 patmatch(char *pattern, const char *string)
7595 char *p = preglob(pattern, 0);
7596 //bb_error_msg("fnmatch(pattern:'%s',str:'%s')", p, string);
7597 return pmatch(p, string);
7601 * See if a pattern matches in a case statement.
7604 casematch(union node *pattern, char *val)
7606 struct stackmark smark;
7609 setstackmark(&smark);
7610 argbackq = pattern->narg.backquote;
7611 STARTSTACKSTR(expdest);
7612 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7613 /* var_str_list: */ NULL);
7614 STACKSTRNUL(expdest);
7616 result = patmatch(stackblock(), val);
7617 popstackmark(&smark);
7622 /* ============ find_command */
7626 int (*builtin)(int, char **) FAST_FUNC;
7627 /* unsigned flags; */
7629 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7630 /* "regular" builtins always take precedence over commands,
7631 * regardless of PATH=....%builtin... position */
7632 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7633 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7636 smallint cmdtype; /* CMDxxx */
7639 /* index >= 0 for commands without path (slashes) */
7640 /* (TODO: what exactly does the value mean? PATH position?) */
7641 /* index == -1 for commands with slashes */
7642 /* index == (-2 - applet_no) for NOFORK applets */
7643 const struct builtincmd *cmd;
7644 struct funcnode *func;
7647 /* values of cmdtype */
7648 #define CMDUNKNOWN -1 /* no entry in table for command */
7649 #define CMDNORMAL 0 /* command is an executable program */
7650 #define CMDFUNCTION 1 /* command is a shell function */
7651 #define CMDBUILTIN 2 /* command is a shell builtin */
7653 /* action to find_command() */
7654 #define DO_ERR 0x01 /* prints errors */
7655 #define DO_ABS 0x02 /* checks absolute paths */
7656 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7657 #define DO_ALTPATH 0x08 /* using alternate path */
7658 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7660 static void find_command(char *, struct cmdentry *, int, const char *);
7663 /* ============ Hashing commands */
7666 * When commands are first encountered, they are entered in a hash table.
7667 * This ensures that a full path search will not have to be done for them
7668 * on each invocation.
7670 * We should investigate converting to a linear search, even though that
7671 * would make the command name "hash" a misnomer.
7675 struct tblentry *next; /* next entry in hash chain */
7676 union param param; /* definition of builtin function */
7677 smallint cmdtype; /* CMDxxx */
7678 char rehash; /* if set, cd done since entry created */
7679 char cmdname[1]; /* name of command */
7682 static struct tblentry **cmdtable;
7683 #define INIT_G_cmdtable() do { \
7684 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7687 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7691 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7693 #if ENABLE_FEATURE_SH_STANDALONE
7694 if (applet_no >= 0) {
7695 if (APPLET_IS_NOEXEC(applet_no)) {
7699 run_applet_no_and_exit(applet_no, cmd, argv);
7701 /* re-exec ourselves with the new arguments */
7702 execve(bb_busybox_exec_path, argv, envp);
7703 /* If they called chroot or otherwise made the binary no longer
7704 * executable, fall through */
7711 execve(cmd, argv, envp);
7712 } while (errno == EINTR);
7714 execve(cmd, argv, envp);
7716 if (cmd != (char*) bb_busybox_exec_path && errno == ENOEXEC) {
7717 /* Run "cmd" as a shell script:
7718 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7719 * "If the execve() function fails with ENOEXEC, the shell
7720 * shall execute a command equivalent to having a shell invoked
7721 * with the command name as its first operand,
7722 * with any remaining arguments passed to the new shell"
7724 * That is, do not use $SHELL, user's shell, or /bin/sh;
7725 * just call ourselves.
7727 * Note that bash reads ~80 chars of the file, and if it sees
7728 * a zero byte before it sees newline, it doesn't try to
7729 * interpret it, but fails with "cannot execute binary file"
7730 * message and exit code 126. For one, this prevents attempts
7731 * to interpret foreign ELF binaries as shell scripts.
7734 cmd = (char*) bb_busybox_exec_path;
7735 /* NB: this is only possible because all callers of shellexec()
7736 * ensure that the argv[-1] slot exists!
7739 argv[0] = (char*) "ash";
7745 * Exec a program. Never returns. If you change this routine, you may
7746 * have to change the find_command routine as well.
7747 * argv[-1] must exist and be writable! See tryexec() for why.
7749 static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
7750 static void shellexec(char *prog, char **argv, const char *path, int idx)
7756 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7758 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7759 if (strchr(prog, '/') != NULL
7760 #if ENABLE_FEATURE_SH_STANDALONE
7761 || (applet_no = find_applet_by_name(prog)) >= 0
7764 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
7765 if (applet_no >= 0) {
7766 /* We tried execing ourself, but it didn't work.
7767 * Maybe /proc/self/exe doesn't exist?
7776 while ((cmdname = path_advance(&path, prog)) != NULL) {
7777 if (--idx < 0 && pathopt == NULL) {
7778 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7779 if (errno != ENOENT && errno != ENOTDIR)
7786 /* Map to POSIX errors */
7798 exitstatus = exerrno;
7799 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7800 prog, e, suppress_int));
7801 ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
7806 printentry(struct tblentry *cmdp)
7812 idx = cmdp->param.index;
7815 name = path_advance(&path, cmdp->cmdname);
7817 } while (--idx >= 0);
7818 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7822 * Clear out command entries. The argument specifies the first entry in
7823 * PATH which has changed.
7826 clearcmdentry(int firstchange)
7828 struct tblentry **tblp;
7829 struct tblentry **pp;
7830 struct tblentry *cmdp;
7833 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7835 while ((cmdp = *pp) != NULL) {
7836 if ((cmdp->cmdtype == CMDNORMAL &&
7837 cmdp->param.index >= firstchange)
7838 || (cmdp->cmdtype == CMDBUILTIN &&
7839 builtinloc >= firstchange)
7852 * Locate a command in the command hash table. If "add" is nonzero,
7853 * add the command to the table if it is not already present. The
7854 * variable "lastcmdentry" is set to point to the address of the link
7855 * pointing to the entry, so that delete_cmd_entry can delete the
7858 * Interrupts must be off if called with add != 0.
7860 static struct tblentry **lastcmdentry;
7862 static struct tblentry *
7863 cmdlookup(const char *name, int add)
7865 unsigned int hashval;
7867 struct tblentry *cmdp;
7868 struct tblentry **pp;
7871 hashval = (unsigned char)*p << 4;
7873 hashval += (unsigned char)*p++;
7875 pp = &cmdtable[hashval % CMDTABLESIZE];
7876 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7877 if (strcmp(cmdp->cmdname, name) == 0)
7881 if (add && cmdp == NULL) {
7882 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7884 /* + 1 - already done because
7885 * tblentry::cmdname is char[1] */);
7886 /*cmdp->next = NULL; - ckzalloc did it */
7887 cmdp->cmdtype = CMDUNKNOWN;
7888 strcpy(cmdp->cmdname, name);
7895 * Delete the command entry returned on the last lookup.
7898 delete_cmd_entry(void)
7900 struct tblentry *cmdp;
7903 cmdp = *lastcmdentry;
7904 *lastcmdentry = cmdp->next;
7905 if (cmdp->cmdtype == CMDFUNCTION)
7906 freefunc(cmdp->param.func);
7912 * Add a new command entry, replacing any existing command entry for
7913 * the same name - except special builtins.
7916 addcmdentry(char *name, struct cmdentry *entry)
7918 struct tblentry *cmdp;
7920 cmdp = cmdlookup(name, 1);
7921 if (cmdp->cmdtype == CMDFUNCTION) {
7922 freefunc(cmdp->param.func);
7924 cmdp->cmdtype = entry->cmdtype;
7925 cmdp->param = entry->u;
7929 static int FAST_FUNC
7930 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7932 struct tblentry **pp;
7933 struct tblentry *cmdp;
7935 struct cmdentry entry;
7938 if (nextopt("r") != '\0') {
7943 if (*argptr == NULL) {
7944 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7945 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7946 if (cmdp->cmdtype == CMDNORMAL)
7954 while ((name = *argptr) != NULL) {
7955 cmdp = cmdlookup(name, 0);
7957 && (cmdp->cmdtype == CMDNORMAL
7958 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7962 find_command(name, &entry, DO_ERR, pathval());
7963 if (entry.cmdtype == CMDUNKNOWN)
7971 * Called when a cd is done. Marks all commands so the next time they
7972 * are executed they will be rehashed.
7977 struct tblentry **pp;
7978 struct tblentry *cmdp;
7980 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7981 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7982 if (cmdp->cmdtype == CMDNORMAL
7983 || (cmdp->cmdtype == CMDBUILTIN
7984 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7994 * Fix command hash table when PATH changed.
7995 * Called before PATH is changed. The argument is the new value of PATH;
7996 * pathval() still returns the old value at this point.
7997 * Called with interrupts off.
7999 static void FAST_FUNC
8000 changepath(const char *new)
8008 firstchange = 9999; /* assume no change */
8014 if ((*old == '\0' && *new == ':')
8015 || (*old == ':' && *new == '\0')
8019 old = new; /* ignore subsequent differences */
8023 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
8030 if (builtinloc < 0 && idx_bltin >= 0)
8031 builtinloc = idx_bltin; /* zap builtins */
8032 if (builtinloc >= 0 && idx_bltin < 0)
8034 clearcmdentry(firstchange);
8035 builtinloc = idx_bltin;
8071 typedef smallint token_id_t;
8073 /* Nth bit indicates if token marks the end of a list */
8076 /* 0 */ | (1u << TEOF)
8077 /* 1 */ | (0u << TNL)
8078 /* 2 */ | (0u << TREDIR)
8079 /* 3 */ | (0u << TWORD)
8080 /* 4 */ | (0u << TSEMI)
8081 /* 5 */ | (0u << TBACKGND)
8082 /* 6 */ | (0u << TAND)
8083 /* 7 */ | (0u << TOR)
8084 /* 8 */ | (0u << TPIPE)
8085 /* 9 */ | (0u << TLP)
8086 /* 10 */ | (1u << TRP)
8087 /* 11 */ | (1u << TENDCASE)
8088 /* 12 */ | (1u << TENDBQUOTE)
8089 /* 13 */ | (0u << TNOT)
8090 /* 14 */ | (0u << TCASE)
8091 /* 15 */ | (1u << TDO)
8092 /* 16 */ | (1u << TDONE)
8093 /* 17 */ | (1u << TELIF)
8094 /* 18 */ | (1u << TELSE)
8095 /* 19 */ | (1u << TESAC)
8096 /* 20 */ | (1u << TFI)
8097 /* 21 */ | (0u << TFOR)
8099 /* 22 */ | (0u << TFUNCTION)
8101 /* 23 */ | (0u << TIF)
8102 /* 24 */ | (0u << TIN)
8103 /* 25 */ | (1u << TTHEN)
8104 /* 26 */ | (0u << TUNTIL)
8105 /* 27 */ | (0u << TWHILE)
8106 /* 28 */ | (0u << TBEGIN)
8107 /* 29 */ | (1u << TEND)
8108 , /* thus far 29 bits used */
8111 static const char *const tokname_array[] = {
8125 #define KWDOFFSET 13
8126 /* the following are keywords */
8148 /* Wrapper around strcmp for qsort/bsearch/... */
8150 pstrcmp(const void *a, const void *b)
8152 return strcmp((char*)a, *(char**)b);
8155 static const char *const *
8156 findkwd(const char *s)
8158 return bsearch(s, tokname_array + KWDOFFSET,
8159 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8160 sizeof(tokname_array[0]), pstrcmp);
8164 * Locate and print what a word is...
8167 describe_command(char *command, const char *path, int describe_command_verbose)
8169 struct cmdentry entry;
8170 #if ENABLE_ASH_ALIAS
8171 const struct alias *ap;
8174 path = path ? path : pathval();
8176 if (describe_command_verbose) {
8180 /* First look at the keywords */
8181 if (findkwd(command)) {
8182 out1str(describe_command_verbose ? " is a shell keyword" : command);
8186 #if ENABLE_ASH_ALIAS
8187 /* Then look at the aliases */
8188 ap = lookupalias(command, 0);
8190 if (!describe_command_verbose) {
8195 out1fmt(" is an alias for %s", ap->val);
8200 find_command(command, &entry, DO_ABS, path);
8202 switch (entry.cmdtype) {
8204 int j = entry.u.index;
8210 p = path_advance(&path, command);
8214 if (describe_command_verbose) {
8215 out1fmt(" is %s", p);
8223 if (describe_command_verbose) {
8224 out1str(" is a shell function");
8231 if (describe_command_verbose) {
8232 out1fmt(" is a %sshell builtin",
8233 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8234 "special " : nullstr
8242 if (describe_command_verbose) {
8243 out1str(": not found\n");
8252 static int FAST_FUNC
8253 typecmd(int argc UNUSED_PARAM, char **argv)
8259 /* type -p ... ? (we don't bother checking for 'p') */
8260 if (argv[1] && argv[1][0] == '-') {
8265 err |= describe_command(argv[i++], NULL, verbose);
8270 #if ENABLE_ASH_CMDCMD
8271 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8273 parse_command_args(char **argv, const char **path)
8286 if (c == '-' && !*cp) {
8294 *path = bb_default_path;
8297 /* run 'typecmd' for other options */
8306 static int FAST_FUNC
8307 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8315 const char *path = NULL;
8317 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8318 * never reaches this function.
8321 while ((c = nextopt("pvV")) != '\0')
8323 verify |= VERIFY_VERBOSE;
8325 /*verify |= VERIFY_BRIEF*/;
8331 path = bb_default_path;
8333 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8335 if (/*verify && */ cmd)
8336 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8343 /*static int funcblocksize; // size of structures in function */
8344 /*static int funcstringsize; // size of strings in node */
8345 static void *funcblock; /* block to allocate function from */
8346 static char *funcstring_end; /* end of block to allocate strings from */
8348 /* flags in argument to evaltree */
8349 #define EV_EXIT 01 /* exit after evaluating tree */
8350 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8352 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8353 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8354 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8355 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8356 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8357 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8358 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8359 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8360 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8361 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8362 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8363 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8364 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8365 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8366 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8367 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8368 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8369 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8370 #if BASH_REDIR_OUTPUT
8371 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8373 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8374 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8375 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8376 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8377 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8378 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8379 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8380 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8381 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8384 static int calcsize(int funcblocksize, union node *n);
8387 sizenodelist(int funcblocksize, struct nodelist *lp)
8390 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8391 funcblocksize = calcsize(funcblocksize, lp->n);
8394 return funcblocksize;
8398 calcsize(int funcblocksize, union node *n)
8401 return funcblocksize;
8402 funcblocksize += nodesize[n->type];
8405 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8406 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8407 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8410 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8415 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8416 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8423 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8424 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8427 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8428 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8429 funcblocksize = calcsize(funcblocksize, n->nif.test);
8432 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8433 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8434 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8437 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8438 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8441 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8442 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8443 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8447 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8448 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8449 funcblocksize = calcsize(funcblocksize, n->narg.next);
8452 #if BASH_REDIR_OUTPUT
8459 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8460 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8464 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8465 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8469 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8470 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8473 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8476 return funcblocksize;
8480 nodeckstrdup(char *s)
8482 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8483 return strcpy(funcstring_end, s);
8486 static union node *copynode(union node *);
8488 static struct nodelist *
8489 copynodelist(struct nodelist *lp)
8491 struct nodelist *start;
8492 struct nodelist **lpp;
8497 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8498 (*lpp)->n = copynode(lp->n);
8500 lpp = &(*lpp)->next;
8507 copynode(union node *n)
8514 funcblock = (char *) funcblock + nodesize[n->type];
8518 new->ncmd.redirect = copynode(n->ncmd.redirect);
8519 new->ncmd.args = copynode(n->ncmd.args);
8520 new->ncmd.assign = copynode(n->ncmd.assign);
8523 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8524 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8529 new->nredir.redirect = copynode(n->nredir.redirect);
8530 new->nredir.n = copynode(n->nredir.n);
8537 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8538 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8541 new->nif.elsepart = copynode(n->nif.elsepart);
8542 new->nif.ifpart = copynode(n->nif.ifpart);
8543 new->nif.test = copynode(n->nif.test);
8546 new->nfor.var = nodeckstrdup(n->nfor.var);
8547 new->nfor.body = copynode(n->nfor.body);
8548 new->nfor.args = copynode(n->nfor.args);
8551 new->ncase.cases = copynode(n->ncase.cases);
8552 new->ncase.expr = copynode(n->ncase.expr);
8555 new->nclist.body = copynode(n->nclist.body);
8556 new->nclist.pattern = copynode(n->nclist.pattern);
8557 new->nclist.next = copynode(n->nclist.next);
8561 new->narg.backquote = copynodelist(n->narg.backquote);
8562 new->narg.text = nodeckstrdup(n->narg.text);
8563 new->narg.next = copynode(n->narg.next);
8566 #if BASH_REDIR_OUTPUT
8573 new->nfile.fname = copynode(n->nfile.fname);
8574 new->nfile.fd = n->nfile.fd;
8575 new->nfile.next = copynode(n->nfile.next);
8579 new->ndup.vname = copynode(n->ndup.vname);
8580 new->ndup.dupfd = n->ndup.dupfd;
8581 new->ndup.fd = n->ndup.fd;
8582 new->ndup.next = copynode(n->ndup.next);
8586 new->nhere.doc = copynode(n->nhere.doc);
8587 new->nhere.fd = n->nhere.fd;
8588 new->nhere.next = copynode(n->nhere.next);
8591 new->nnot.com = copynode(n->nnot.com);
8594 new->type = n->type;
8599 * Make a copy of a parse tree.
8601 static struct funcnode *
8602 copyfunc(union node *n)
8607 /*funcstringsize = 0;*/
8608 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8609 f = ckzalloc(blocksize /* + funcstringsize */);
8610 funcblock = (char *) f + offsetof(struct funcnode, n);
8611 funcstring_end = (char *) f + blocksize;
8613 /* f->count = 0; - ckzalloc did it */
8618 * Define a shell function.
8621 defun(union node *func)
8623 struct cmdentry entry;
8626 entry.cmdtype = CMDFUNCTION;
8627 entry.u.func = copyfunc(func);
8628 addcmdentry(func->narg.text, &entry);
8632 /* Reasons for skipping commands (see comment on breakcmd routine) */
8633 #define SKIPBREAK (1 << 0)
8634 #define SKIPCONT (1 << 1)
8635 #define SKIPFUNC (1 << 2)
8636 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8637 static int skipcount; /* number of levels to skip */
8638 static int funcnest; /* depth of function calls */
8639 static int loopnest; /* current loop nesting level */
8641 /* Forward decl way out to parsing code - dotrap needs it */
8642 static int evalstring(char *s, int flags);
8644 /* Called to execute a trap.
8645 * Single callsite - at the end of evaltree().
8646 * If we return non-zero, evaltree raises EXEXIT exception.
8648 * Perhaps we should avoid entering new trap handlers
8649 * while we are executing a trap handler. [is it a TODO?]
8656 uint8_t last_status;
8661 last_status = exitstatus;
8665 TRACE(("dotrap entered\n"));
8666 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8678 /* non-trapped SIGINT is handled separately by raise_interrupt,
8679 * don't upset it by resetting gotsig[SIGINT-1] */
8680 if (sig == SIGINT && !p)
8683 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8689 exitstatus = last_status;
8690 TRACE(("dotrap returns\n"));
8693 /* forward declarations - evaluation is fairly recursive business... */
8694 static int evalloop(union node *, int);
8695 static int evalfor(union node *, int);
8696 static int evalcase(union node *, int);
8697 static int evalsubshell(union node *, int);
8698 static void expredir(union node *);
8699 static int evalpipe(union node *, int);
8700 static int evalcommand(union node *, int);
8701 static int evalbltin(const struct builtincmd *, int, char **, int);
8702 static void prehash(union node *);
8705 * Evaluate a parse tree. The value is left in the global variable
8709 evaltree(union node *n, int flags)
8712 int (*evalfn)(union node *, int);
8716 TRACE(("evaltree(NULL) called\n"));
8719 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8726 out1fmt("Node type = %d\n", n->type);
8731 status = !evaltree(n->nnot.com, EV_TESTED);
8734 expredir(n->nredir.redirect);
8735 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8737 status = evaltree(n->nredir.n, flags & EV_TESTED);
8739 if (n->nredir.redirect)
8740 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8743 evalfn = evalcommand;
8745 if (eflag && !(flags & EV_TESTED))
8757 evalfn = evalsubshell;
8770 #error NAND + 1 != NOR
8772 #if NOR + 1 != NSEMI
8773 #error NOR + 1 != NSEMI
8775 unsigned is_or = n->type - NAND;
8778 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8780 if ((!status) == is_or || evalskip)
8786 status = evalfn(n, flags);
8790 status = evaltree(n->nif.test, EV_TESTED);
8797 if (n->nif.elsepart) {
8798 n = n->nif.elsepart;
8805 /* Not necessary. To test it:
8806 * "false; f() { qwerty; }; echo $?" should print 0.
8810 exitstatus = status;
8814 /* Order of checks below is important:
8815 * signal handlers trigger before exit caused by "set -e".
8819 if (checkexit & status)
8820 raise_exception(EXEXIT);
8821 if (flags & EV_EXIT)
8822 raise_exception(EXEXIT);
8824 TRACE(("leaving evaltree (no interrupts)\n"));
8828 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8831 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8836 int skip = evalskip;
8843 if (--skipcount <= 0) {
8854 evalloop(union node *n, int flags)
8865 i = evaltree(n->nbinary.ch1, EV_TESTED);
8867 if (skip == SKIPFUNC)
8871 if (n->type != NWHILE)
8875 status = evaltree(n->nbinary.ch2, flags);
8877 } while (!(skip & ~SKIPCONT));
8884 evalfor(union node *n, int flags)
8886 struct arglist arglist;
8889 struct stackmark smark;
8892 setstackmark(&smark);
8893 arglist.list = NULL;
8894 arglist.lastp = &arglist.list;
8895 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8896 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8898 *arglist.lastp = NULL;
8902 for (sp = arglist.list; sp; sp = sp->next) {
8903 setvar0(n->nfor.var, sp->text);
8904 status = evaltree(n->nfor.body, flags);
8905 if (skiploop() & ~SKIPCONT)
8909 popstackmark(&smark);
8915 evalcase(union node *n, int flags)
8919 struct arglist arglist;
8920 struct stackmark smark;
8923 setstackmark(&smark);
8924 arglist.list = NULL;
8925 arglist.lastp = &arglist.list;
8926 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8927 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8928 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8929 if (casematch(patp, arglist.list->text)) {
8930 /* Ensure body is non-empty as otherwise
8931 * EV_EXIT may prevent us from setting the
8934 if (evalskip == 0 && cp->nclist.body) {
8935 status = evaltree(cp->nclist.body, flags);
8942 popstackmark(&smark);
8948 * Kick off a subshell to evaluate a tree.
8951 evalsubshell(union node *n, int flags)
8954 int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
8957 expredir(n->nredir.redirect);
8958 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8961 if (backgnd == FORK_FG)
8963 jp = makejob(/*n,*/ 1);
8964 if (forkshell(jp, n, backgnd) == 0) {
8969 flags &= ~EV_TESTED;
8971 redirect(n->nredir.redirect, 0);
8972 evaltreenr(n->nredir.n, flags);
8977 if (backgnd == FORK_FG)
8978 status = waitforjob(jp);
8984 * Compute the names of the files in a redirection list.
8986 static void fixredir(union node *, const char *, int);
8988 expredir(union node *n)
8992 for (redir = n; redir; redir = redir->nfile.next) {
8996 fn.lastp = &fn.list;
8997 switch (redir->type) {
9001 #if BASH_REDIR_OUTPUT
9006 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
9007 TRACE(("expredir expanded to '%s'\n", fn.list->text));
9008 #if BASH_REDIR_OUTPUT
9012 // By the design of stack allocator, the loop of this kind:
9013 // while true; do while true; do break; done </dev/null; done
9014 // will look like a memory leak: ash plans to free expfname's
9015 // of "/dev/null" as soon as it finishes running the loop
9016 // (in this case, never).
9017 // This "fix" is wrong:
9018 if (redir->nfile.expfname)
9019 stunalloc(redir->nfile.expfname);
9020 // It results in corrupted state of stacked allocations.
9022 redir->nfile.expfname = fn.list->text;
9025 case NTOFD: /* >& */
9026 if (redir->ndup.vname) {
9027 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
9028 if (fn.list == NULL)
9029 ash_msg_and_raise_error("redir error");
9030 #if BASH_REDIR_OUTPUT
9031 //FIXME: we used expandarg with different args!
9032 if (!isdigit_str9(fn.list->text)) {
9033 /* >&file, not >&fd */
9034 if (redir->nfile.fd != 1) /* 123>&file - BAD */
9035 ash_msg_and_raise_error("redir error");
9037 goto store_expfname;
9040 fixredir(redir, fn.list->text, 1);
9048 * Evaluate a pipeline. All the processes in the pipeline are children
9049 * of the process creating the pipeline. (This differs from some versions
9050 * of the shell, which make the last process in a pipeline the parent
9054 evalpipe(union node *n, int flags)
9057 struct nodelist *lp;
9063 TRACE(("evalpipe(0x%lx) called\n", (long)n));
9065 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
9069 if (n->npipe.pipe_backgnd == 0)
9071 jp = makejob(/*n,*/ pipelen);
9073 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
9077 if (pipe(pip) < 0) {
9079 ash_msg_and_raise_error("pipe call failed");
9082 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
9096 evaltreenr(lp->n, flags);
9103 /* Don't want to trigger debugging */
9107 if (n->npipe.pipe_backgnd == 0) {
9108 status = waitforjob(jp);
9109 TRACE(("evalpipe: job done exit status %d\n", status));
9117 * Controls whether the shell is interactive or not.
9120 setinteractive(int on)
9122 static smallint is_interactive;
9124 if (++on == is_interactive)
9126 is_interactive = on;
9130 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9131 if (is_interactive > 1) {
9132 /* Looks like they want an interactive shell */
9133 static smallint did_banner;
9136 /* note: ash and hush share this string */
9137 out1fmt("\n\n%s %s\n"
9138 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9141 "built-in shell (ash)"
9155 setinteractive(iflag);
9157 #if ENABLE_FEATURE_EDITING_VI
9159 line_input_state->flags |= VI_MODE;
9161 line_input_state->flags &= ~VI_MODE;
9163 viflag = 0; /* forcibly keep the option off */
9167 static struct localvar *localvars;
9170 * Called after a function returns.
9171 * Interrupts must be off.
9176 struct localvar *lvp;
9179 while ((lvp = localvars) != NULL) {
9180 localvars = lvp->next;
9182 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9183 if (vp == NULL) { /* $- saved */
9184 memcpy(optlist, lvp->text, sizeof(optlist));
9185 free((char*)lvp->text);
9187 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
9188 unsetvar(vp->var_text);
9191 vp->var_func(var_end(lvp->text));
9192 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9193 free((char*)vp->var_text);
9194 vp->flags = lvp->flags;
9195 vp->var_text = lvp->text;
9202 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9204 volatile struct shparam saveparam;
9205 struct localvar *volatile savelocalvars;
9206 struct jmploc *volatile savehandler;
9207 struct jmploc jmploc;
9210 saveparam = shellparam;
9211 savelocalvars = localvars;
9212 savehandler = exception_handler;
9213 e = setjmp(jmploc.loc);
9218 exception_handler = &jmploc;
9220 shellparam.malloced = 0;
9224 shellparam.nparam = argc - 1;
9225 shellparam.p = argv + 1;
9226 #if ENABLE_ASH_GETOPTS
9227 shellparam.optind = 1;
9228 shellparam.optoff = -1;
9230 evaltree(func->n.narg.next, flags & EV_TESTED);
9236 localvars = savelocalvars;
9237 freeparam(&shellparam);
9238 shellparam = saveparam;
9239 exception_handler = savehandler;
9241 evalskip &= ~SKIPFUNC;
9246 * Make a variable a local variable. When a variable is made local, it's
9247 * value and flags are saved in a localvar structure. The saved values
9248 * will be restored when the shell function returns. We handle the name
9249 * "-" as a special case: it makes changes to "set +-options" local
9250 * (options will be restored on return from the function).
9255 struct localvar *lvp;
9258 char *eq = strchr(name, '=');
9261 /* Cater for duplicate "local". Examples:
9262 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9263 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9267 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9271 * it's a duplicate "local VAR" declaration, do nothing
9278 lvp = ckzalloc(sizeof(*lvp));
9279 if (LONE_DASH(name)) {
9281 p = ckmalloc(sizeof(optlist));
9282 lvp->text = memcpy(p, optlist, sizeof(optlist));
9285 vpp = hashvar(name);
9286 vp = *findvar(vpp, name);
9288 /* variable did not exist yet */
9290 setvareq(name, VSTRFIXED);
9292 setvar(name, NULL, VSTRFIXED);
9293 vp = *vpp; /* the new variable */
9294 lvp->flags = VUNSET;
9296 lvp->text = vp->var_text;
9297 lvp->flags = vp->flags;
9298 /* make sure neither "struct var" nor string gets freed
9299 * during (un)setting:
9301 vp->flags |= VSTRFIXED|VTEXTFIXED;
9305 /* "local VAR" unsets VAR: */
9306 setvar0(name, NULL);
9310 lvp->next = localvars;
9317 * The "local" command.
9319 static int FAST_FUNC
9320 localcmd(int argc UNUSED_PARAM, char **argv)
9325 ash_msg_and_raise_error("not in a function");
9328 while ((name = *argv++) != NULL) {
9334 static int FAST_FUNC
9335 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9340 static int FAST_FUNC
9341 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9346 static int FAST_FUNC
9347 execcmd(int argc UNUSED_PARAM, char **argv)
9350 while (nextopt("a:") != '\0')
9351 /* nextopt() sets optionarg to "-a ARGV0" */;
9357 iflag = 0; /* exit on error */
9360 /* We should set up signals for "exec CMD"
9361 * the same way as for "CMD" without "exec".
9362 * But optschanged->setinteractive->setsignal
9363 * still thought we are a root shell. Therefore, for example,
9364 * SIGQUIT is still set to IGN. Fix it:
9368 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9369 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9370 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9374 argv[0] = optionarg;
9375 shellexec(prog, argv, pathval(), 0);
9382 * The return command.
9384 static int FAST_FUNC
9385 returncmd(int argc UNUSED_PARAM, char **argv)
9388 * If called outside a function, do what ksh does;
9389 * skip the rest of the file.
9391 evalskip = SKIPFUNC;
9392 return argv[1] ? number(argv[1]) : exitstatus;
9395 /* Forward declarations for builtintab[] */
9396 static int breakcmd(int, char **) FAST_FUNC;
9397 static int dotcmd(int, char **) FAST_FUNC;
9398 static int evalcmd(int, char **, int) FAST_FUNC;
9399 static int exitcmd(int, char **) FAST_FUNC;
9400 static int exportcmd(int, char **) FAST_FUNC;
9401 #if ENABLE_ASH_GETOPTS
9402 static int getoptscmd(int, char **) FAST_FUNC;
9405 static int helpcmd(int, char **) FAST_FUNC;
9408 static int historycmd(int, char **) FAST_FUNC;
9410 #if ENABLE_FEATURE_SH_MATH
9411 static int letcmd(int, char **) FAST_FUNC;
9413 static int readcmd(int, char **) FAST_FUNC;
9414 static int setcmd(int, char **) FAST_FUNC;
9415 static int shiftcmd(int, char **) FAST_FUNC;
9416 static int timescmd(int, char **) FAST_FUNC;
9417 static int trapcmd(int, char **) FAST_FUNC;
9418 static int umaskcmd(int, char **) FAST_FUNC;
9419 static int unsetcmd(int, char **) FAST_FUNC;
9420 static int ulimitcmd(int, char **) FAST_FUNC;
9422 #define BUILTIN_NOSPEC "0"
9423 #define BUILTIN_SPECIAL "1"
9424 #define BUILTIN_REGULAR "2"
9425 #define BUILTIN_SPEC_REG "3"
9426 #define BUILTIN_ASSIGN "4"
9427 #define BUILTIN_SPEC_ASSG "5"
9428 #define BUILTIN_REG_ASSG "6"
9429 #define BUILTIN_SPEC_REG_ASSG "7"
9431 /* Stubs for calling non-FAST_FUNC's */
9433 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9435 #if ENABLE_ASH_PRINTF
9436 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9438 #if ENABLE_ASH_TEST || BASH_TEST2
9439 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9442 /* Keep these in proper order since it is searched via bsearch() */
9443 static const struct builtincmd builtintab[] = {
9444 { BUILTIN_SPEC_REG "." , dotcmd },
9445 { BUILTIN_SPEC_REG ":" , truecmd },
9447 { BUILTIN_REGULAR "[" , testcmd },
9450 { BUILTIN_REGULAR "[[" , testcmd },
9452 #if ENABLE_ASH_ALIAS
9453 { BUILTIN_REG_ASSG "alias" , aliascmd },
9456 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9458 { BUILTIN_SPEC_REG "break" , breakcmd },
9459 { BUILTIN_REGULAR "cd" , cdcmd },
9460 { BUILTIN_NOSPEC "chdir" , cdcmd },
9461 #if ENABLE_ASH_CMDCMD
9462 { BUILTIN_REGULAR "command" , commandcmd },
9464 { BUILTIN_SPEC_REG "continue", breakcmd },
9466 { BUILTIN_REGULAR "echo" , echocmd },
9468 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9469 { BUILTIN_SPEC_REG "exec" , execcmd },
9470 { BUILTIN_SPEC_REG "exit" , exitcmd },
9471 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9472 { BUILTIN_REGULAR "false" , falsecmd },
9474 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9476 #if ENABLE_ASH_GETOPTS
9477 { BUILTIN_REGULAR "getopts" , getoptscmd },
9479 { BUILTIN_NOSPEC "hash" , hashcmd },
9481 { BUILTIN_NOSPEC "help" , helpcmd },
9484 { BUILTIN_NOSPEC "history" , historycmd },
9487 { BUILTIN_REGULAR "jobs" , jobscmd },
9488 { BUILTIN_REGULAR "kill" , killcmd },
9490 #if ENABLE_FEATURE_SH_MATH
9491 { BUILTIN_NOSPEC "let" , letcmd },
9493 { BUILTIN_ASSIGN "local" , localcmd },
9494 #if ENABLE_ASH_PRINTF
9495 { BUILTIN_REGULAR "printf" , printfcmd },
9497 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9498 { BUILTIN_REGULAR "read" , readcmd },
9499 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9500 { BUILTIN_SPEC_REG "return" , returncmd },
9501 { BUILTIN_SPEC_REG "set" , setcmd },
9502 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9504 { BUILTIN_SPEC_REG "source" , dotcmd },
9507 { BUILTIN_REGULAR "test" , testcmd },
9509 { BUILTIN_SPEC_REG "times" , timescmd },
9510 { BUILTIN_SPEC_REG "trap" , trapcmd },
9511 { BUILTIN_REGULAR "true" , truecmd },
9512 { BUILTIN_NOSPEC "type" , typecmd },
9513 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9514 { BUILTIN_REGULAR "umask" , umaskcmd },
9515 #if ENABLE_ASH_ALIAS
9516 { BUILTIN_REGULAR "unalias" , unaliascmd },
9518 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9519 { BUILTIN_REGULAR "wait" , waitcmd },
9522 /* Should match the above table! */
9523 #define COMMANDCMD (builtintab + \
9525 /* [ */ 1 * ENABLE_ASH_TEST + \
9526 /* [[ */ 1 * BASH_TEST2 + \
9527 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9528 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9529 /* break cd cddir */ 3)
9530 #define EVALCMD (COMMANDCMD + \
9531 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9532 /* continue */ 1 + \
9533 /* echo */ 1 * ENABLE_ASH_ECHO + \
9535 #define EXECCMD (EVALCMD + \
9539 * Search the table of builtin commands.
9542 pstrcmp1(const void *a, const void *b)
9544 return strcmp((char*)a, *(char**)b + 1);
9546 static struct builtincmd *
9547 find_builtin(const char *name)
9549 struct builtincmd *bp;
9552 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9559 * Execute a simple command.
9562 isassignment(const char *p)
9564 const char *q = endofname(p);
9569 static int FAST_FUNC
9570 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9572 /* Preserve exitstatus of a previous possible redirection
9573 * as POSIX mandates */
9574 return back_exitstatus;
9577 evalcommand(union node *cmd, int flags)
9579 static const struct builtincmd null_bltin = {
9580 "\0\0", bltincmd /* why three NULs? */
9582 struct stackmark smark;
9584 struct arglist arglist;
9585 struct arglist varlist;
9588 const struct strlist *sp;
9589 struct cmdentry cmdentry;
9596 struct builtincmd *bcmd;
9597 smallint cmd_is_exec;
9598 smallint pseudovarflag = 0;
9600 /* First expand the arguments. */
9601 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9602 setstackmark(&smark);
9603 back_exitstatus = 0;
9605 cmdentry.cmdtype = CMDBUILTIN;
9606 cmdentry.u.cmd = &null_bltin;
9607 varlist.lastp = &varlist.list;
9608 *varlist.lastp = NULL;
9609 arglist.lastp = &arglist.list;
9610 *arglist.lastp = NULL;
9613 if (cmd->ncmd.args) {
9614 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9615 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9618 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9619 struct strlist **spp;
9621 spp = arglist.lastp;
9622 if (pseudovarflag && isassignment(argp->narg.text))
9623 expandarg(argp, &arglist, EXP_VARTILDE);
9625 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9627 for (sp = *spp; sp; sp = sp->next)
9631 /* Reserve one extra spot at the front for shellexec. */
9632 nargv = stalloc(sizeof(char *) * (argc + 2));
9634 for (sp = arglist.list; sp; sp = sp->next) {
9635 TRACE(("evalcommand arg: %s\n", sp->text));
9636 *nargv++ = sp->text;
9641 if (iflag && funcnest == 0 && argc > 0)
9642 lastarg = nargv[-1];
9645 expredir(cmd->ncmd.redirect);
9646 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9648 path = vpath.var_text;
9649 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9650 struct strlist **spp;
9653 spp = varlist.lastp;
9654 expandarg(argp, &varlist, EXP_VARTILDE);
9657 * Modify the command lookup path, if a PATH= assignment
9661 if (varcmp(p, path) == 0)
9665 /* Print the command if xflag is set. */
9667 const char *pfx = "";
9669 fdprintf(preverrout_fd, "%s", expandstr(ps4val()));
9673 char *varval = sp->text;
9674 char *eq = strchrnul(varval, '=');
9677 fdprintf(preverrout_fd, "%s%.*s%s",
9679 (int)(eq - varval), varval,
9680 maybe_single_quote(eq)
9688 fdprintf(preverrout_fd, "%s%s",
9690 /* always quote if matches reserved word: */
9692 ? single_quote(sp->text)
9693 : maybe_single_quote(sp->text)
9698 safe_write(preverrout_fd, "\n", 1);
9704 /* Now locate the command. */
9706 int cmd_flag = DO_ERR;
9707 #if ENABLE_ASH_CMDCMD
9708 const char *oldpath = path + 5;
9712 find_command(argv[0], &cmdentry, cmd_flag, path);
9713 if (cmdentry.cmdtype == CMDUNKNOWN) {
9714 flush_stdout_stderr();
9719 /* implement bltin and command here */
9720 if (cmdentry.cmdtype != CMDBUILTIN)
9723 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9724 if (cmdentry.u.cmd == EXECCMD)
9726 #if ENABLE_ASH_CMDCMD
9727 if (cmdentry.u.cmd == COMMANDCMD) {
9729 nargv = parse_command_args(argv, &path);
9732 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9733 * nargv => "PROG". path is updated if -p.
9735 argc -= nargv - argv;
9737 cmd_flag |= DO_NOFUNC;
9746 exitstatus = status;
9748 /* We have a redirection error. */
9750 raise_exception(EXERROR);
9755 /* Execute the command. */
9756 switch (cmdentry.cmdtype) {
9759 #if ENABLE_FEATURE_SH_NOFORK
9760 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9761 * around run_nofork_applet() call.
9762 * (2) Should this check also be done in forkshell()?
9763 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9765 /* find_command() encodes applet_no as (-2 - applet_no) */
9766 int applet_no = (- cmdentry.u.index - 2);
9767 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9768 listsetvar(varlist.list, VEXPORT|VSTACK);
9769 /* run <applet>_main() */
9770 status = run_nofork_applet(applet_no, argv);
9774 /* Can we avoid forking off? For example, very last command
9775 * in a script or a subshell does not need forking,
9776 * we can just exec it.
9778 if (!(flags & EV_EXIT) || may_have_traps) {
9779 /* No, forking off a child is necessary */
9782 jp = makejob(/*cmd,*/ 1);
9783 if (forkshell(jp, cmd, FORK_FG) != 0) {
9785 status = waitforjob(jp);
9787 TRACE(("forked child exited with %d\n", status));
9792 /* fall through to exec'ing external program */
9794 listsetvar(varlist.list, VEXPORT|VSTACK);
9795 shellexec(argv[0], argv, path, cmdentry.u.index);
9799 cmdenviron = varlist.list;
9801 struct strlist *list = cmdenviron;
9803 if (spclbltin > 0 || argc == 0) {
9805 if (cmd_is_exec && argc > 1)
9808 listsetvar(list, i);
9810 /* Tight loop with builtins only:
9811 * "while kill -0 $child; do true; done"
9812 * will never exit even if $child died, unless we do this
9813 * to reap the zombie and make kill detect that it's gone: */
9814 dowait(DOWAIT_NONBLOCK, NULL);
9816 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9817 if (exception_type == EXERROR && spclbltin <= 0) {
9822 longjmp(exception_handler->loc, 1);
9827 listsetvar(varlist.list, 0);
9828 /* See above for the rationale */
9829 dowait(DOWAIT_NONBLOCK, NULL);
9830 if (evalfun(cmdentry.u.func, argc, argv, flags))
9833 status = exitstatus;
9838 if (cmd->ncmd.redirect)
9839 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9841 /* dsl: I think this is intended to be used to support
9842 * '_' in 'vi' command mode during line editing...
9843 * However I implemented that within libedit itself.
9845 setvar0("_", lastarg);
9847 popstackmark(&smark);
9853 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9855 char *volatile savecmdname;
9856 struct jmploc *volatile savehandler;
9857 struct jmploc jmploc;
9861 savecmdname = commandname;
9862 savehandler = exception_handler;
9863 i = setjmp(jmploc.loc);
9866 exception_handler = &jmploc;
9867 commandname = argv[0];
9869 optptr = NULL; /* initialize nextopt */
9871 status = evalcmd(argc, argv, flags);
9873 status = (*cmd->builtin)(argc, argv);
9874 flush_stdout_stderr();
9875 status |= ferror(stdout);
9876 exitstatus = status;
9879 commandname = savecmdname;
9880 exception_handler = savehandler;
9886 goodname(const char *p)
9888 return endofname(p)[0] == '\0';
9893 * Search for a command. This is called before we fork so that the
9894 * location of the command will be available in the parent as well as
9895 * the child. The check for "goodname" is an overly conservative
9896 * check that the name will not be subject to expansion.
9899 prehash(union node *n)
9901 struct cmdentry entry;
9903 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9904 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9908 /* ============ Builtin commands
9910 * Builtin commands whose functions are closely tied to evaluation
9911 * are implemented here.
9915 * Handle break and continue commands. Break, continue, and return are
9916 * all handled by setting the evalskip flag. The evaluation routines
9917 * above all check this flag, and if it is set they start skipping
9918 * commands rather than executing them. The variable skipcount is
9919 * the number of loops to break/continue, or the number of function
9920 * levels to return. (The latter is always 1.) It should probably
9921 * be an error to break out of more loops than exist, but it isn't
9922 * in the standard shell so we don't make it one here.
9924 static int FAST_FUNC
9925 breakcmd(int argc UNUSED_PARAM, char **argv)
9927 int n = argv[1] ? number(argv[1]) : 1;
9930 ash_msg_and_raise_error(msg_illnum, argv[1]);
9934 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9942 * This implements the input routines used by the parser.
9946 INPUT_PUSH_FILE = 1,
9947 INPUT_NOFILE_OK = 2,
9950 static smallint checkkwd;
9951 /* values of checkkwd variable */
9952 #define CHKALIAS 0x1
9957 * Push a string back onto the input at this current parsefile level.
9958 * We handle aliases this way.
9960 #if !ENABLE_ASH_ALIAS
9961 #define pushstring(s, ap) pushstring(s)
9964 pushstring(char *s, struct alias *ap)
9971 if (g_parsefile->strpush) {
9972 sp = ckzalloc(sizeof(*sp));
9973 sp->prev = g_parsefile->strpush;
9975 sp = &(g_parsefile->basestrpush);
9977 g_parsefile->strpush = sp;
9978 sp->prev_string = g_parsefile->next_to_pgetc;
9979 sp->prev_left_in_line = g_parsefile->left_in_line;
9980 sp->unget = g_parsefile->unget;
9981 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9982 #if ENABLE_ASH_ALIAS
9985 ap->flag |= ALIASINUSE;
9989 g_parsefile->next_to_pgetc = s;
9990 g_parsefile->left_in_line = len;
9991 g_parsefile->unget = 0;
9998 struct strpush *sp = g_parsefile->strpush;
10001 #if ENABLE_ASH_ALIAS
10003 if (g_parsefile->next_to_pgetc[-1] == ' '
10004 || g_parsefile->next_to_pgetc[-1] == '\t'
10006 checkkwd |= CHKALIAS;
10008 if (sp->string != sp->ap->val) {
10011 sp->ap->flag &= ~ALIASINUSE;
10012 if (sp->ap->flag & ALIASDEAD) {
10013 unalias(sp->ap->name);
10017 g_parsefile->next_to_pgetc = sp->prev_string;
10018 g_parsefile->left_in_line = sp->prev_left_in_line;
10019 g_parsefile->unget = sp->unget;
10020 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
10021 g_parsefile->strpush = sp->prev;
10022 if (sp != &(g_parsefile->basestrpush))
10031 char *buf = g_parsefile->buf;
10033 g_parsefile->next_to_pgetc = buf;
10034 #if ENABLE_FEATURE_EDITING
10036 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
10037 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10040 # if ENABLE_ASH_IDLE_TIMEOUT
10042 const char *tmout_var = lookupvar("TMOUT");
10044 timeout = atoi(tmout_var) * 1000;
10050 # if ENABLE_FEATURE_TAB_COMPLETION
10051 line_input_state->path_lookup = pathval();
10053 reinit_unicode_for_ash();
10054 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
10056 /* ^C pressed, "convert" to SIGINT */
10057 write(STDOUT_FILENO, "^C", 2);
10058 if (trap[SIGINT]) {
10064 exitstatus = 128 + SIGINT;
10070 /* Ctrl+D pressed */
10073 # if ENABLE_ASH_IDLE_TIMEOUT
10074 else if (errno == EAGAIN && timeout > 0) {
10075 puts("\007timed out waiting for input: auto-logout");
10082 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10085 #if 0 /* disabled: nonblock_immune_read() handles this problem */
10087 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
10088 int flags = fcntl(0, F_GETFL);
10089 if (flags >= 0 && (flags & O_NONBLOCK)) {
10090 flags &= ~O_NONBLOCK;
10091 if (fcntl(0, F_SETFL, flags) >= 0) {
10092 out2str("sh: turning off NDELAY mode\n");
10103 * Refill the input buffer and return the next input character:
10105 * 1) If a string was pushed back on the input, pop it;
10106 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
10107 * or we are reading from a string so we can't refill the buffer,
10109 * 3) If there is more stuff in this buffer, use it else call read to fill it.
10110 * 4) Process input up to the next newline, deleting nul characters.
10112 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
10113 #define pgetc_debug(...) ((void)0)
10114 static int pgetc(void);
10121 if (g_parsefile->strpush) {
10122 #if ENABLE_ASH_ALIAS
10123 if (g_parsefile->left_in_line == -1
10124 && g_parsefile->strpush->ap
10125 && g_parsefile->next_to_pgetc[-1] != ' '
10126 && g_parsefile->next_to_pgetc[-1] != '\t'
10128 pgetc_debug("preadbuffer PEOA");
10135 /* on both branches above g_parsefile->left_in_line < 0.
10136 * "pgetc" needs refilling.
10139 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
10140 * pungetc() may increment it a few times.
10141 * Assuming it won't increment it to less than -90.
10143 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
10144 pgetc_debug("preadbuffer PEOF1");
10145 /* even in failure keep left_in_line and next_to_pgetc
10146 * in lock step, for correct multi-layer pungetc.
10147 * left_in_line was decremented before preadbuffer(),
10148 * must inc next_to_pgetc: */
10149 g_parsefile->next_to_pgetc++;
10153 more = g_parsefile->left_in_buffer;
10155 flush_stdout_stderr();
10159 /* don't try reading again */
10160 g_parsefile->left_in_line = -99;
10161 pgetc_debug("preadbuffer PEOF2");
10162 g_parsefile->next_to_pgetc++;
10167 /* Find out where's the end of line.
10168 * Set g_parsefile->left_in_line
10169 * and g_parsefile->left_in_buffer acordingly.
10170 * NUL chars are deleted.
10172 q = g_parsefile->next_to_pgetc;
10180 memmove(q, q + 1, more);
10184 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10190 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10191 if (g_parsefile->left_in_line < 0)
10196 g_parsefile->left_in_buffer = more;
10201 out2str(g_parsefile->next_to_pgetc);
10205 pgetc_debug("preadbuffer at %d:%p'%s'",
10206 g_parsefile->left_in_line,
10207 g_parsefile->next_to_pgetc,
10208 g_parsefile->next_to_pgetc);
10209 return (unsigned char)*g_parsefile->next_to_pgetc++;
10215 g_parsefile->linno++;
10216 setprompt_if(doprompt, 2);
10221 g_parsefile->linno++;
10222 needprompt = doprompt;
10230 pgetc_debug("pgetc at %d:%p'%s'",
10231 g_parsefile->left_in_line,
10232 g_parsefile->next_to_pgetc,
10233 g_parsefile->next_to_pgetc);
10234 if (g_parsefile->unget)
10235 return g_parsefile->lastc[--g_parsefile->unget];
10237 if (--g_parsefile->left_in_line >= 0)
10238 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10242 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10243 g_parsefile->lastc[0] = c;
10248 #if ENABLE_ASH_ALIAS
10250 pgetc_without_PEOA(void)
10254 pgetc_debug("pgetc at %d:%p'%s'",
10255 g_parsefile->left_in_line,
10256 g_parsefile->next_to_pgetc,
10257 g_parsefile->next_to_pgetc);
10259 } while (c == PEOA);
10263 # define pgetc_without_PEOA() pgetc()
10267 * Read a line from the script.
10270 pfgets(char *line, int len)
10276 while (--nleft > 0) {
10277 c = pgetc_without_PEOA();
10292 * Undo a call to pgetc. Only two characters may be pushed back.
10293 * PEOF may be pushed back.
10298 g_parsefile->unget++;
10301 /* This one eats backslash+newline */
10307 while ((c = pgetc()) == '\\') {
10308 if (pgetc() != '\n') {
10320 * To handle the "." command, a stack of input files is used. Pushfile
10321 * adds a new entry to the stack and popfile restores the previous level.
10326 struct parsefile *pf;
10328 pf = ckzalloc(sizeof(*pf));
10329 pf->prev = g_parsefile;
10331 /*pf->strpush = NULL; - ckzalloc did it */
10332 /*pf->basestrpush.prev = NULL;*/
10340 struct parsefile *pf = g_parsefile;
10346 if (pf->pf_fd >= 0)
10349 while (pf->strpush)
10351 g_parsefile = pf->prev;
10357 * Return to top level.
10362 while (g_parsefile != &basepf)
10367 * Close the file(s) that the shell is reading commands from. Called
10368 * after a fork is done.
10374 if (g_parsefile->pf_fd > 0) {
10375 close(g_parsefile->pf_fd);
10376 g_parsefile->pf_fd = 0;
10381 * Like setinputfile, but takes an open file descriptor. Call this with
10385 setinputfd(int fd, int push)
10389 g_parsefile->buf = NULL;
10391 g_parsefile->pf_fd = fd;
10392 if (g_parsefile->buf == NULL)
10393 g_parsefile->buf = ckmalloc(IBUFSIZ);
10394 g_parsefile->left_in_buffer = 0;
10395 g_parsefile->left_in_line = 0;
10396 g_parsefile->linno = 1;
10400 * Set the input to take input from a file. If push is set, push the
10401 * old input onto the stack first.
10404 setinputfile(const char *fname, int flags)
10409 fd = open(fname, O_RDONLY);
10411 if (flags & INPUT_NOFILE_OK)
10414 ash_msg_and_raise_error("can't open '%s'", fname);
10419 close_on_exec_on(fd);
10420 setinputfd(fd, flags & INPUT_PUSH_FILE);
10427 * Like setinputfile, but takes input from a string.
10430 setinputstring(char *string)
10434 g_parsefile->next_to_pgetc = string;
10435 g_parsefile->left_in_line = strlen(string);
10436 g_parsefile->buf = NULL;
10437 g_parsefile->linno = 1;
10443 * Routines to check for mail.
10446 #if ENABLE_ASH_MAIL
10448 /* Hash of mtimes of mailboxes */
10449 static unsigned mailtime_hash;
10450 /* Set if MAIL or MAILPATH is changed. */
10451 static smallint mail_var_path_changed;
10454 * Print appropriate message(s) if mail has arrived.
10455 * If mail_var_path_changed is set,
10456 * then the value of MAIL has mail_var_path_changed,
10457 * so we just update the values.
10466 struct stackmark smark;
10469 setstackmark(&smark);
10470 mpath = mpathset() ? mpathval() : mailval();
10473 p = path_advance(&mpath, nullstr);
10478 for (q = p; *q; q++)
10484 q[-1] = '\0'; /* delete trailing '/' */
10485 if (stat(p, &statb) < 0) {
10488 /* Very simplistic "hash": just a sum of all mtimes */
10489 new_hash += (unsigned)statb.st_mtime;
10491 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10492 if (mailtime_hash != 0)
10493 out2str("you have mail\n");
10494 mailtime_hash = new_hash;
10496 mail_var_path_changed = 0;
10497 popstackmark(&smark);
10500 static void FAST_FUNC
10501 changemail(const char *val UNUSED_PARAM)
10503 mail_var_path_changed = 1;
10506 #endif /* ASH_MAIL */
10509 /* ============ ??? */
10512 * Set the shell parameters.
10515 setparam(char **argv)
10521 for (nparam = 0; argv[nparam]; nparam++)
10523 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10525 *ap++ = ckstrdup(*argv++);
10528 freeparam(&shellparam);
10529 shellparam.malloced = 1;
10530 shellparam.nparam = nparam;
10531 shellparam.p = newparam;
10532 #if ENABLE_ASH_GETOPTS
10533 shellparam.optind = 1;
10534 shellparam.optoff = -1;
10539 * Process shell options. The global variable argptr contains a pointer
10540 * to the argument list; we advance it past the options.
10542 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10543 * For a non-interactive shell, an error condition encountered
10544 * by a special built-in ... shall cause the shell to write a diagnostic message
10545 * to standard error and exit as shown in the following table:
10546 * Error Special Built-In
10548 * Utility syntax error (option or operand error) Shall exit
10550 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10551 * we see that bash does not do that (set "finishes" with error code 1 instead,
10552 * and shell continues), and people rely on this behavior!
10554 * set -o barfoo 2>/dev/null
10557 * Oh well. Let's mimic that.
10560 plus_minus_o(char *name, int val)
10565 for (i = 0; i < NOPTS; i++) {
10566 if (strcmp(name, optnames(i)) == 0) {
10571 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10574 for (i = 0; i < NOPTS; i++) {
10576 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10578 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10584 setoption(int flag, int val)
10588 for (i = 0; i < NOPTS; i++) {
10589 if (optletters(i) == flag) {
10594 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10598 options(int cmdline)
10606 while ((p = *argptr) != NULL) {
10608 if (c != '-' && c != '+')
10611 val = 0; /* val = 0 if c == '+' */
10614 if (p[0] == '\0' || LONE_DASH(p)) {
10616 /* "-" means turn off -x and -v */
10619 /* "--" means reset params */
10620 else if (*argptr == NULL)
10623 break; /* "-" or "--" terminates options */
10626 /* first char was + or - */
10627 while ((c = *p++) != '\0') {
10628 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10629 if (c == 'c' && cmdline) {
10630 minusc = p; /* command is after shell args */
10631 } else if (c == 'o') {
10632 if (plus_minus_o(*argptr, val)) {
10633 /* it already printed err message */
10634 return 1; /* error */
10638 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10640 /* bash does not accept +-login, we also won't */
10641 } else if (cmdline && val && (c == '-')) { /* long options */
10642 if (strcmp(p, "login") == 0)
10654 * The shift builtin command.
10656 static int FAST_FUNC
10657 shiftcmd(int argc UNUSED_PARAM, char **argv)
10664 n = number(argv[1]);
10665 if (n > shellparam.nparam)
10666 n = 0; /* bash compat, was = shellparam.nparam; */
10668 shellparam.nparam -= n;
10669 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10670 if (shellparam.malloced)
10673 ap2 = shellparam.p;
10674 while ((*ap2++ = *ap1++) != NULL)
10676 #if ENABLE_ASH_GETOPTS
10677 shellparam.optind = 1;
10678 shellparam.optoff = -1;
10685 * POSIX requires that 'set' (but not export or readonly) output the
10686 * variables in lexicographic order - by the locale's collating order (sigh).
10687 * Maybe we could keep them in an ordered balanced binary tree
10688 * instead of hashed lists.
10689 * For now just roll 'em through qsort for printing...
10692 showvars(const char *sep_prefix, int on, int off)
10695 char **ep, **epend;
10697 ep = listvars(on, off, &epend);
10698 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10700 sep = *sep_prefix ? " " : sep_prefix;
10702 for (; ep < epend; ep++) {
10706 p = strchrnul(*ep, '=');
10709 q = single_quote(++p);
10710 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10716 * The set command builtin.
10718 static int FAST_FUNC
10719 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10724 return showvars(nullstr, 0, VUNSET);
10727 retval = options(/*cmdline:*/ 0);
10728 if (retval == 0) { /* if no parse error... */
10730 if (*argptr != NULL) {
10738 #if ENABLE_ASH_RANDOM_SUPPORT
10739 static void FAST_FUNC
10740 change_random(const char *value)
10744 if (value == NULL) {
10745 /* "get", generate */
10746 t = next_random(&random_gen);
10747 /* set without recursion */
10748 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10749 vrandom.flags &= ~VNOFUNC;
10752 t = strtoul(value, NULL, 10);
10753 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10758 #if ENABLE_ASH_GETOPTS
10760 getopts(char *optstr, char *optvar, char **optfirst)
10767 int ind = shellparam.optind;
10768 int off = shellparam.optoff;
10772 shellparam.optind = -1;
10773 optnext = optfirst + ind - 1;
10775 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10778 p = optnext[-1] + off;
10779 if (p == NULL || *p == '\0') {
10780 /* Current word is done, advance */
10782 if (p == NULL || *p != '-' || *++p == '\0') {
10789 if (LONE_DASH(p)) /* check for "--" */
10794 for (q = optstr; *q != c;) {
10796 if (optstr[0] == ':') {
10798 /*sbuf[1] = '\0'; - already is */
10799 setvar0("OPTARG", sbuf);
10801 fprintf(stderr, "Illegal option -%c\n", c);
10802 unsetvar("OPTARG");
10812 if (*p == '\0' && (p = *optnext) == NULL) {
10813 if (optstr[0] == ':') {
10815 /*sbuf[1] = '\0'; - already is */
10816 setvar0("OPTARG", sbuf);
10819 fprintf(stderr, "No arg for -%c option\n", c);
10820 unsetvar("OPTARG");
10828 setvar0("OPTARG", p);
10831 setvar0("OPTARG", nullstr);
10833 ind = optnext - optfirst + 1;
10834 setvar("OPTIND", itoa(ind), VNOFUNC);
10836 /*sbuf[1] = '\0'; - already is */
10837 setvar0(optvar, sbuf);
10839 shellparam.optoff = p ? p - *(optnext - 1) : -1;
10840 shellparam.optind = ind;
10846 * The getopts builtin. Shellparam.optnext points to the next argument
10847 * to be processed. Shellparam.optptr points to the next character to
10848 * be processed in the current argument. If shellparam.optnext is NULL,
10849 * then it's the first time getopts has been called.
10851 static int FAST_FUNC
10852 getoptscmd(int argc, char **argv)
10857 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10859 optbase = shellparam.p;
10860 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
10861 shellparam.optind = 1;
10862 shellparam.optoff = -1;
10865 optbase = &argv[3];
10866 if ((unsigned)shellparam.optind > argc - 2) {
10867 shellparam.optind = 1;
10868 shellparam.optoff = -1;
10872 return getopts(argv[1], argv[2], optbase);
10874 #endif /* ASH_GETOPTS */
10877 /* ============ Shell parser */
10880 struct heredoc *next; /* next here document in list */
10881 union node *here; /* redirection node */
10882 char *eofmark; /* string indicating end of input */
10883 smallint striptabs; /* if set, strip leading tabs */
10886 static smallint tokpushback; /* last token pushed back */
10887 static smallint quoteflag; /* set if (part of) last token was quoted */
10888 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10889 static struct heredoc *heredoclist; /* list of here documents to read */
10890 static char *wordtext; /* text of last word returned by readtoken */
10891 static struct nodelist *backquotelist;
10892 static union node *redirnode;
10893 static struct heredoc *heredoc;
10895 static const char *
10896 tokname(char *buf, int tok)
10899 return tokname_array[tok];
10900 sprintf(buf, "\"%s\"", tokname_array[tok]);
10904 /* raise_error_unexpected_syntax:
10905 * Called when an unexpected token is read during the parse. The argument
10906 * is the token that is expected, or -1 if more than one type of token can
10907 * occur at this point.
10909 static void raise_error_unexpected_syntax(int) NORETURN;
10911 raise_error_unexpected_syntax(int token)
10917 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10919 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10920 raise_error_syntax(msg);
10924 #define EOFMARKLEN 79
10926 /* parsing is heavily cross-recursive, need these forward decls */
10927 static union node *andor(void);
10928 static union node *pipeline(void);
10929 static union node *parse_command(void);
10930 static void parseheredoc(void);
10931 static int peektoken(void);
10932 static int readtoken(void);
10934 static union node *
10937 union node *n1, *n2, *n3;
10942 switch (peektoken()) {
10950 if (!n1 && (nlflag & 1))
10956 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10957 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
10963 if (tok == TBACKGND) {
10964 if (n2->type == NPIPE) {
10965 n2->npipe.pipe_backgnd = 1;
10967 if (n2->type != NREDIR) {
10968 n3 = stzalloc(sizeof(struct nredir));
10970 /*n3->nredir.redirect = NULL; - stzalloc did it */
10973 n2->type = NBACKGND;
10979 n3 = stzalloc(sizeof(struct nbinary));
10981 n3->nbinary.ch1 = n1;
10982 n3->nbinary.ch2 = n2;
10995 raise_error_unexpected_syntax(-1);
11002 static union node *
11005 union node *n1, *n2, *n3;
11013 } else if (t == TOR) {
11019 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11021 n3 = stzalloc(sizeof(struct nbinary));
11023 n3->nbinary.ch1 = n1;
11024 n3->nbinary.ch2 = n2;
11029 static union node *
11032 union node *n1, *n2, *pipenode;
11033 struct nodelist *lp, *prev;
11037 TRACE(("pipeline: entered\n"));
11038 if (readtoken() == TNOT) {
11040 checkkwd = CHKKWD | CHKALIAS;
11043 n1 = parse_command();
11044 if (readtoken() == TPIPE) {
11045 pipenode = stzalloc(sizeof(struct npipe));
11046 pipenode->type = NPIPE;
11047 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
11048 lp = stzalloc(sizeof(struct nodelist));
11049 pipenode->npipe.cmdlist = lp;
11053 lp = stzalloc(sizeof(struct nodelist));
11054 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11055 lp->n = parse_command();
11057 } while (readtoken() == TPIPE);
11063 n2 = stzalloc(sizeof(struct nnot));
11071 static union node *
11076 n = stzalloc(sizeof(struct narg));
11078 /*n->narg.next = NULL; - stzalloc did it */
11079 n->narg.text = wordtext;
11080 n->narg.backquote = backquotelist;
11085 fixredir(union node *n, const char *text, int err)
11089 TRACE(("Fix redir %s %d\n", text, err));
11091 n->ndup.vname = NULL;
11093 fd = bb_strtou(text, NULL, 10);
11094 if (!errno && fd >= 0)
11095 n->ndup.dupfd = fd;
11096 else if (LONE_DASH(text))
11097 n->ndup.dupfd = -1;
11100 raise_error_syntax("bad fd number");
11101 n->ndup.vname = makename();
11106 * Returns true if the text contains nothing to expand (no dollar signs
11110 noexpand(const char *text)
11114 while ((c = *text++) != '\0') {
11115 if (c == CTLQUOTEMARK)
11119 else if (SIT(c, BASESYNTAX) == CCTL)
11128 union node *n = redirnode;
11130 if (readtoken() != TWORD)
11131 raise_error_unexpected_syntax(-1);
11132 if (n->type == NHERE) {
11133 struct heredoc *here = heredoc;
11137 if (quoteflag == 0)
11139 TRACE(("Here document %d\n", n->type));
11140 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
11141 raise_error_syntax("illegal eof marker for << redirection");
11142 rmescapes(wordtext, 0);
11143 here->eofmark = wordtext;
11145 if (heredoclist == NULL)
11146 heredoclist = here;
11148 for (p = heredoclist; p->next; p = p->next)
11152 } else if (n->type == NTOFD || n->type == NFROMFD) {
11153 fixredir(n, wordtext, 0);
11155 n->nfile.fname = makename();
11159 static union node *
11162 union node *args, **app;
11163 union node *n = NULL;
11164 union node *vars, **vpp;
11165 union node **rpp, *redir;
11168 smallint double_brackets_flag = 0;
11170 IF_BASH_FUNCTION(smallint function_flag = 0;)
11179 savecheckkwd = CHKALIAS;
11182 checkkwd = savecheckkwd;
11187 if (peektoken() != TWORD)
11188 raise_error_unexpected_syntax(TWORD);
11193 case TAND: /* "&&" */
11194 case TOR: /* "||" */
11195 if (!double_brackets_flag) {
11199 wordtext = (char *) (t == TAND ? "-a" : "-o");
11202 n = stzalloc(sizeof(struct narg));
11204 /*n->narg.next = NULL; - stzalloc did it */
11205 n->narg.text = wordtext;
11207 if (strcmp("[[", wordtext) == 0)
11208 double_brackets_flag = 1;
11209 else if (strcmp("]]", wordtext) == 0)
11210 double_brackets_flag = 0;
11212 n->narg.backquote = backquotelist;
11213 if (savecheckkwd && isassignment(wordtext)) {
11215 vpp = &n->narg.next;
11218 app = &n->narg.next;
11222 if (function_flag) {
11223 checkkwd = CHKNL | CHKKWD;
11224 switch (peektoken()) {
11236 if (strcmp("[[", wordtext) == 0)
11240 raise_error_unexpected_syntax(-1);
11246 *rpp = n = redirnode;
11247 rpp = &n->nfile.next;
11248 parsefname(); /* read name of redirection file */
11251 IF_BASH_FUNCTION(do_func:)
11252 if (args && app == &args->narg.next
11255 struct builtincmd *bcmd;
11258 /* We have a function */
11259 if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
11260 raise_error_unexpected_syntax(TRP);
11261 name = n->narg.text;
11262 if (!goodname(name)
11263 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11265 raise_error_syntax("bad function name");
11268 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11269 n->narg.next = parse_command();
11272 IF_BASH_FUNCTION(function_flag = 0;)
11283 n = stzalloc(sizeof(struct ncmd));
11285 n->ncmd.args = args;
11286 n->ncmd.assign = vars;
11287 n->ncmd.redirect = redir;
11291 static union node *
11292 parse_command(void)
11294 union node *n1, *n2;
11295 union node *ap, **app;
11296 union node *cp, **cpp;
11297 union node *redir, **rpp;
11304 switch (readtoken()) {
11306 raise_error_unexpected_syntax(-1);
11309 n1 = stzalloc(sizeof(struct nif));
11311 n1->nif.test = list(0);
11312 if (readtoken() != TTHEN)
11313 raise_error_unexpected_syntax(TTHEN);
11314 n1->nif.ifpart = list(0);
11316 while (readtoken() == TELIF) {
11317 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11318 n2 = n2->nif.elsepart;
11320 n2->nif.test = list(0);
11321 if (readtoken() != TTHEN)
11322 raise_error_unexpected_syntax(TTHEN);
11323 n2->nif.ifpart = list(0);
11325 if (lasttoken == TELSE)
11326 n2->nif.elsepart = list(0);
11328 n2->nif.elsepart = NULL;
11336 n1 = stzalloc(sizeof(struct nbinary));
11337 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11338 n1->nbinary.ch1 = list(0);
11341 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11342 got == TWORD ? wordtext : ""));
11343 raise_error_unexpected_syntax(TDO);
11345 n1->nbinary.ch2 = list(0);
11350 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11351 raise_error_syntax("bad for loop variable");
11352 n1 = stzalloc(sizeof(struct nfor));
11354 n1->nfor.var = wordtext;
11355 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11356 if (readtoken() == TIN) {
11358 while (readtoken() == TWORD) {
11359 n2 = stzalloc(sizeof(struct narg));
11361 /*n2->narg.next = NULL; - stzalloc did it */
11362 n2->narg.text = wordtext;
11363 n2->narg.backquote = backquotelist;
11365 app = &n2->narg.next;
11368 n1->nfor.args = ap;
11369 if (lasttoken != TNL && lasttoken != TSEMI)
11370 raise_error_unexpected_syntax(-1);
11372 n2 = stzalloc(sizeof(struct narg));
11374 /*n2->narg.next = NULL; - stzalloc did it */
11375 n2->narg.text = (char *)dolatstr;
11376 /*n2->narg.backquote = NULL;*/
11377 n1->nfor.args = n2;
11379 * Newline or semicolon here is optional (but note
11380 * that the original Bourne shell only allowed NL).
11382 if (lasttoken != TSEMI)
11385 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11386 if (readtoken() != TDO)
11387 raise_error_unexpected_syntax(TDO);
11388 n1->nfor.body = list(0);
11392 n1 = stzalloc(sizeof(struct ncase));
11394 if (readtoken() != TWORD)
11395 raise_error_unexpected_syntax(TWORD);
11396 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11398 /*n2->narg.next = NULL; - stzalloc did it */
11399 n2->narg.text = wordtext;
11400 n2->narg.backquote = backquotelist;
11401 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11402 if (readtoken() != TIN)
11403 raise_error_unexpected_syntax(TIN);
11404 cpp = &n1->ncase.cases;
11406 checkkwd = CHKNL | CHKKWD;
11408 while (t != TESAC) {
11409 if (lasttoken == TLP)
11411 *cpp = cp = stzalloc(sizeof(struct nclist));
11413 app = &cp->nclist.pattern;
11415 *app = ap = stzalloc(sizeof(struct narg));
11417 /*ap->narg.next = NULL; - stzalloc did it */
11418 ap->narg.text = wordtext;
11419 ap->narg.backquote = backquotelist;
11420 if (readtoken() != TPIPE)
11422 app = &ap->narg.next;
11425 //ap->narg.next = NULL;
11426 if (lasttoken != TRP)
11427 raise_error_unexpected_syntax(TRP);
11428 cp->nclist.body = list(2);
11430 cpp = &cp->nclist.next;
11432 checkkwd = CHKNL | CHKKWD;
11436 raise_error_unexpected_syntax(TENDCASE);
11443 n1 = stzalloc(sizeof(struct nredir));
11444 n1->type = NSUBSHELL;
11445 n1->nredir.n = list(0);
11446 /*n1->nredir.redirect = NULL; - stzalloc did it */
11453 IF_BASH_FUNCTION(case TFUNCTION:)
11457 return simplecmd();
11460 if (readtoken() != t)
11461 raise_error_unexpected_syntax(t);
11464 /* Now check for redirection which may follow command */
11465 checkkwd = CHKKWD | CHKALIAS;
11467 while (readtoken() == TREDIR) {
11468 *rpp = n2 = redirnode;
11469 rpp = &n2->nfile.next;
11475 if (n1->type != NSUBSHELL) {
11476 n2 = stzalloc(sizeof(struct nredir));
11481 n1->nredir.redirect = redir;
11486 #if BASH_DOLLAR_SQUOTE
11488 decode_dollar_squote(void)
11490 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11496 p = strchr(C_escapes, c);
11501 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11505 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11507 } else if (c == 'x') { /* \xHH */
11511 } while (isxdigit(c) && --cnt);
11513 if (cnt == 3) { /* \x but next char is "bad" */
11517 } else { /* simple seq like \\ or \t */
11522 c = bb_process_escape_sequence((void*)&p);
11523 } else { /* unrecognized "\z": print both chars unless ' or " */
11524 if (c != '\'' && c != '"') {
11526 c |= 0x100; /* "please encode \, then me" */
11534 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11535 * is not NULL, read a here document. In the latter case, eofmark is the
11536 * word which marks the end of the document and striptabs is true if
11537 * leading tabs should be stripped from the document. The argument c
11538 * is the first character of the input token or document.
11540 * Because C does not have internal subroutines, I have simulated them
11541 * using goto's to implement the subroutine linkage. The following macros
11542 * will run code that appears at the end of readtoken1.
11544 #define CHECKEND() {goto checkend; checkend_return:;}
11545 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11546 #define PARSESUB() {goto parsesub; parsesub_return:;}
11547 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11548 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11549 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11551 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11553 /* NB: syntax parameter fits into smallint */
11554 /* c parameter is an unsigned char or PEOF or PEOA */
11557 char line[EOFMARKLEN + 1];
11558 struct nodelist *bqlist;
11562 IF_FEATURE_SH_MATH(smallint prevsyntax;) /* syntax before arithmetic */
11563 smallint pssyntax; /* we are expanding a prompt string */
11564 int varnest; /* levels of variables expansion */
11565 IF_FEATURE_SH_MATH(int arinest;) /* levels of arithmetic expansion */
11566 IF_FEATURE_SH_MATH(int parenlevel;) /* levels of parens in arithmetic */
11567 int dqvarnest; /* levels of variables expansion within double quotes */
11569 IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
11571 startlinno = g_parsefile->linno;
11574 IF_FEATURE_SH_MATH(prevsyntax = 0;)
11575 pssyntax = (syntax == PSSYNTAX);
11578 dblquote = (syntax == DQSYNTAX);
11580 IF_FEATURE_SH_MATH(arinest = 0;)
11581 IF_FEATURE_SH_MATH(parenlevel = 0;)
11584 STARTSTACKSTR(out);
11586 /* For each line, until end of word */
11587 CHECKEND(); /* set c to PEOF if at end of here document */
11588 for (;;) { /* until end of line or end of word */
11589 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11590 switch (SIT(c, syntax)) {
11591 case CNL: /* '\n' */
11592 if (syntax == BASESYNTAX)
11593 goto endword; /* exit outer loop */
11597 goto loop; /* continue outer loop */
11602 #if BASH_DOLLAR_SQUOTE
11603 if (c == '\\' && bash_dollar_squote) {
11604 c = decode_dollar_squote();
11606 /* skip $'\000', $'\x00' (like bash) */
11610 /* Unknown escape. Encode as '\z' */
11611 c = (unsigned char)c;
11612 if (eofmark == NULL || dblquote)
11613 USTPUTC(CTLESC, out);
11614 USTPUTC('\\', out);
11618 if (eofmark == NULL || dblquote)
11619 USTPUTC(CTLESC, out);
11622 case CBACK: /* backslash */
11623 c = pgetc_without_PEOA();
11625 USTPUTC(CTLESC, out);
11626 USTPUTC('\\', out);
11628 } else if (c == '\n') {
11631 if (c == '$' && pssyntax) {
11632 USTPUTC(CTLESC, out);
11633 USTPUTC('\\', out);
11635 /* Backslash is retained if we are in "str" and next char isn't special */
11640 && (c != '"' || eofmark != NULL)
11642 USTPUTC('\\', out);
11644 USTPUTC(CTLESC, out);
11652 if (eofmark == NULL) {
11653 USTPUTC(CTLQUOTEMARK, out);
11661 IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
11662 if (eofmark != NULL && varnest == 0) {
11665 if (dqvarnest == 0) {
11666 syntax = BASESYNTAX;
11673 case CVAR: /* '$' */
11674 PARSESUB(); /* parse substitution */
11676 case CENDVAR: /* '}' */
11679 if (dqvarnest > 0) {
11686 #if ENABLE_FEATURE_SH_MATH
11687 case CLP: /* '(' in arithmetic */
11691 case CRP: /* ')' in arithmetic */
11692 if (parenlevel > 0) {
11695 if (pgetc_eatbnl() == ')') {
11697 if (--arinest == 0) {
11698 syntax = prevsyntax;
11702 * unbalanced parens
11703 * (don't 2nd guess - no error)
11711 case CBQUOTE: /* '`' */
11715 goto endword; /* exit outer loop */
11719 if (varnest == 0) {
11720 #if BASH_REDIR_OUTPUT
11722 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11723 if (pgetc() == '>')
11724 c = 0x100 + '>'; /* flag &> */
11728 goto endword; /* exit outer loop */
11730 IF_ASH_ALIAS(if (c != PEOA))
11737 #if ENABLE_FEATURE_SH_MATH
11738 if (syntax == ARISYNTAX)
11739 raise_error_syntax("missing '))'");
11741 if (syntax != BASESYNTAX && eofmark == NULL)
11742 raise_error_syntax("unterminated quoted string");
11743 if (varnest != 0) {
11744 startlinno = g_parsefile->linno;
11746 raise_error_syntax("missing '}'");
11748 USTPUTC('\0', out);
11749 len = out - (char *)stackblock();
11750 out = stackblock();
11751 if (eofmark == NULL) {
11752 if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
11755 if (isdigit_str9(out)) {
11756 PARSEREDIR(); /* passed as params: out, c */
11757 lasttoken = TREDIR;
11760 /* else: non-number X seen, interpret it
11761 * as "NNNX>file" = "NNNX >file" */
11765 quoteflag = quotef;
11766 backquotelist = bqlist;
11767 grabstackblock(len);
11771 /* end of readtoken routine */
11774 * Check to see whether we are at the end of the here document. When this
11775 * is called, c is set to the first character of the next input line. If
11776 * we are at the end of the here document, this routine sets the c to PEOF.
11780 #if ENABLE_ASH_ALIAS
11782 c = pgetc_without_PEOA();
11785 while (c == '\t') {
11786 c = pgetc_without_PEOA();
11789 if (c == *eofmark) {
11790 if (pfgets(line, sizeof(line)) != NULL) {
11795 for (q = eofmark + 1;; p++, q++) {
11799 if (!*q || cc != *q)
11806 pushstring(line, NULL);
11811 goto checkend_return;
11815 * Parse a redirection operator. The variable "out" points to a string
11816 * specifying the fd to be redirected. The variable "c" contains the
11817 * first character of the redirection operator.
11820 /* out is already checked to be a valid number or "" */
11821 int fd = (*out == '\0' ? -1 : atoi(out));
11824 np = stzalloc(sizeof(struct nfile));
11829 np->type = NAPPEND;
11831 np->type = NCLOBBER;
11834 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11840 #if BASH_REDIR_OUTPUT
11841 else if (c == 0x100 + '>') { /* this flags &> redirection */
11843 pgetc(); /* this is '>', no need to check */
11847 else { /* c == '<' */
11848 /*np->nfile.fd = 0; - stzalloc did it */
11852 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11853 np = stzalloc(sizeof(struct nhere));
11854 /*np->nfile.fd = 0; - stzalloc did it */
11857 heredoc = stzalloc(sizeof(struct heredoc));
11858 heredoc->here = np;
11861 heredoc->striptabs = 1;
11863 /*heredoc->striptabs = 0; - stzalloc did it */
11869 np->type = NFROMFD;
11873 np->type = NFROMTO;
11885 goto parseredir_return;
11889 * Parse a substitution. At this point, we have read the dollar sign
11890 * and nothing else.
11893 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11894 * (assuming ascii char codes, as the original implementation did) */
11895 #define is_special(c) \
11896 (((unsigned)(c) - 33 < 32) \
11897 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11899 unsigned char subtype;
11902 c = pgetc_eatbnl();
11903 if (c > 255 /* PEOA or PEOF */
11904 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11906 #if BASH_DOLLAR_SQUOTE
11907 if (syntax != DQSYNTAX && c == '\'')
11908 bash_dollar_squote = 1;
11913 } else if (c == '(') {
11914 /* $(command) or $((arith)) */
11915 if (pgetc_eatbnl() == '(') {
11916 #if ENABLE_FEATURE_SH_MATH
11919 raise_error_syntax("support for $((arith)) is disabled");
11926 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11927 USTPUTC(CTLVAR, out);
11928 typeloc = out - (char *)stackblock();
11930 subtype = VSNORMAL;
11932 c = pgetc_eatbnl();
11937 /* $[{[#]]NAME[}] */
11940 c = pgetc_eatbnl();
11941 } while (is_in_name(c));
11942 } else if (isdigit(c)) {
11943 /* $[{[#]]NUM[}] */
11946 c = pgetc_eatbnl();
11947 } while (isdigit(c));
11948 } else if (is_special(c)) {
11949 /* $[{[#]]<specialchar>[}] */
11952 c = pgetc_eatbnl();
11953 if (!subtype && cc == '#') {
11954 subtype = VSLENGTH;
11955 if (c == '_' || isalnum(c))
11958 c = pgetc_eatbnl();
11959 if (cc == '}' || c != '}') {
11970 if (c != '}' && subtype == VSLENGTH) {
11971 /* ${#VAR didn't end with } */
11975 if (subtype == 0) {
11976 static const char types[] ALIGN1 = "}-+?=";
11977 /* ${VAR...} but not $VAR or ${#VAR} */
11978 /* c == first char after VAR */
11981 c = pgetc_eatbnl();
11983 /* This check is only needed to not misinterpret
11984 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11987 if (!strchr(types, c)) {
11988 subtype = VSSUBSTR;
11990 break; /* "goto badsub" is bigger (!) */
11996 const char *p = strchr(types, c);
11999 subtype |= p - types + VSNORMAL;
12005 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
12006 c = pgetc_eatbnl();
12012 #if BASH_PATTERN_SUBST
12014 /* ${v/[/]pattern/repl} */
12015 //TODO: encode pattern and repl separately.
12016 // Currently ${v/$var_with_slash/repl} is horribly broken
12017 subtype = VSREPLACE;
12018 c = pgetc_eatbnl();
12021 subtype++; /* VSREPLACEALL */
12029 ((unsigned char *)stackblock())[typeloc] = subtype;
12030 if (subtype != VSNORMAL) {
12037 goto parsesub_return;
12041 * Called to parse command substitutions. Newstyle is set if the command
12042 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
12043 * list of commands (passed by reference), and savelen is the number of
12044 * characters on the top of the stack which must be preserved.
12047 struct nodelist **nlpp;
12051 smallint saveprompt = 0;
12054 savelen = out - (char *)stackblock();
12057 * FIXME: this can allocate very large block on stack and SEGV.
12059 * echo "..<100kbytes>..`true` $(true) `true` ..."
12060 * allocates 100kb for every command subst. With about
12061 * a hundred command substitutions stack overflows.
12062 * With larger prepended string, SEGV happens sooner.
12064 str = alloca(savelen);
12065 memcpy(str, stackblock(), savelen);
12069 /* We must read until the closing backquote, giving special
12070 * treatment to some slashes, and then push the string and
12071 * reread it as input, interpreting it normally.
12077 STARTSTACKSTR(pout);
12081 setprompt_if(needprompt, 2);
12092 * If eating a newline, avoid putting
12093 * the newline into the new character
12094 * stream (via the STPUTC after the
12099 if (pc != '\\' && pc != '`' && pc != '$'
12100 && (!dblquote || pc != '"')
12102 STPUTC('\\', pout);
12104 if (pc <= 255 /* not PEOA or PEOF */) {
12110 IF_ASH_ALIAS(case PEOA:)
12111 startlinno = g_parsefile->linno;
12112 raise_error_syntax("EOF in backquote substitution");
12124 STPUTC('\0', pout);
12125 psavelen = pout - (char *)stackblock();
12126 if (psavelen > 0) {
12127 pstr = grabstackstr(pout);
12128 setinputstring(pstr);
12133 nlpp = &(*nlpp)->next;
12134 *nlpp = stzalloc(sizeof(**nlpp));
12135 /* (*nlpp)->next = NULL; - stzalloc did it */
12138 saveprompt = doprompt;
12145 doprompt = saveprompt;
12146 else if (readtoken() != TRP)
12147 raise_error_unexpected_syntax(TRP);
12152 * Start reading from old file again, ignoring any pushed back
12153 * tokens left from the backquote parsing
12158 while (stackblocksize() <= savelen)
12160 STARTSTACKSTR(out);
12162 memcpy(out, str, savelen);
12163 STADJUST(savelen, out);
12165 USTPUTC(CTLBACKQ, out);
12167 goto parsebackq_oldreturn;
12168 goto parsebackq_newreturn;
12171 #if ENABLE_FEATURE_SH_MATH
12173 * Parse an arithmetic expansion (indicate start of one and set state)
12176 if (++arinest == 1) {
12177 prevsyntax = syntax;
12178 syntax = ARISYNTAX;
12180 USTPUTC(CTLARI, out);
12181 goto parsearith_return;
12184 } /* end of readtoken */
12187 * Read the next input token.
12188 * If the token is a word, we set backquotelist to the list of cmds in
12189 * backquotes. We set quoteflag to true if any part of the word was
12191 * If the token is TREDIR, then we set redirnode to a structure containing
12193 * In all cases, the variable startlinno is set to the number of the line
12194 * on which the token starts.
12196 * [Change comment: here documents and internal procedures]
12197 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12198 * word parsing code into a separate routine. In this case, readtoken
12199 * doesn't need to have any internal procedures, but parseword does.
12200 * We could also make parseoperator in essence the main routine, and
12201 * have parseword (readtoken1?) handle both words and redirection.]
12203 #define NEW_xxreadtoken
12204 #ifdef NEW_xxreadtoken
12205 /* singles must be first! */
12206 static const char xxreadtoken_chars[7] ALIGN1 = {
12207 '\n', '(', ')', /* singles */
12208 '&', '|', ';', /* doubles */
12212 #define xxreadtoken_singles 3
12213 #define xxreadtoken_doubles 3
12215 static const char xxreadtoken_tokens[] ALIGN1 = {
12216 TNL, TLP, TRP, /* only single occurrence allowed */
12217 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12218 TEOF, /* corresponds to trailing nul */
12219 TAND, TOR, TENDCASE /* if double occurrence */
12231 setprompt_if(needprompt, 2);
12232 startlinno = g_parsefile->linno;
12233 for (;;) { /* until token or start of word found */
12235 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12239 while ((c = pgetc()) != '\n' && c != PEOF)
12242 } else if (c == '\\') {
12243 if (pgetc() != '\n') {
12245 break; /* return readtoken1(...) */
12251 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12257 p = strchr(xxreadtoken_chars, c);
12259 break; /* return readtoken1(...) */
12261 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12263 if (cc == c) { /* double occurrence? */
12264 p += xxreadtoken_doubles + 1;
12267 #if BASH_REDIR_OUTPUT
12268 if (c == '&' && cc == '>') /* &> */
12269 break; /* return readtoken1(...) */
12274 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12279 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12281 #else /* old xxreadtoken */
12282 #define RETURN(token) return lasttoken = token
12292 setprompt_if(needprompt, 2);
12293 startlinno = g_parsefile->linno;
12294 for (;;) { /* until token or start of word found */
12297 case ' ': case '\t':
12298 IF_ASH_ALIAS(case PEOA:)
12301 while ((c = pgetc()) != '\n' && c != PEOF)
12306 if (pgetc() == '\n') {
12318 if (pgetc() == '&')
12323 if (pgetc() == '|')
12328 if (pgetc() == ';')
12341 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12344 #endif /* old xxreadtoken */
12350 int kwd = checkkwd;
12352 smallint alreadyseen = tokpushback;
12355 #if ENABLE_ASH_ALIAS
12371 if (t != TWORD || quoteflag) {
12376 * check for keywords
12378 if (kwd & CHKKWD) {
12379 const char *const *pp;
12381 pp = findkwd(wordtext);
12383 lasttoken = t = pp - tokname_array;
12384 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12389 if (checkkwd & CHKALIAS) {
12390 #if ENABLE_ASH_ALIAS
12392 ap = lookupalias(wordtext, 1);
12395 pushstring(ap->val, ap);
12405 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12407 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12423 * Read and parse a command. Returns NODE_EOF on end of file.
12424 * (NULL is a valid parse tree indicating a blank line.)
12426 static union node *
12427 parsecmd(int interact)
12432 doprompt = interact;
12433 setprompt_if(doprompt, doprompt);
12439 * Input any here documents.
12444 struct heredoc *here;
12447 here = heredoclist;
12448 heredoclist = NULL;
12451 setprompt_if(needprompt, 2);
12452 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12453 here->eofmark, here->striptabs);
12454 n = stzalloc(sizeof(struct narg));
12455 n->narg.type = NARG;
12456 /*n->narg.next = NULL; - stzalloc did it */
12457 n->narg.text = wordtext;
12458 n->narg.backquote = backquotelist;
12459 here->here->nhere.doc = n;
12466 * called by editline -- any expansions to the prompt should be added here.
12468 static const char *
12469 expandstr(const char *ps)
12474 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12475 * and token processing _can_ alter it (delete NULs etc). */
12476 setinputstring((char *)ps);
12478 saveprompt = doprompt;
12480 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12481 doprompt = saveprompt;
12485 n.narg.type = NARG;
12486 n.narg.next = NULL;
12487 n.narg.text = wordtext;
12488 n.narg.backquote = backquotelist;
12490 expandarg(&n, NULL, EXP_QUOTED);
12491 return stackblock();
12495 * Execute a command or commands contained in a string.
12498 evalstring(char *s, int flags)
12500 struct jmploc *volatile savehandler;
12501 struct jmploc jmploc;
12505 struct stackmark smark;
12510 setstackmark(&smark);
12513 /* On exception inside execution loop, we must popfile().
12514 * Try interactively:
12516 * command eval "a=b" # throws "is read only" error
12517 * "command BLTIN" is not supposed to abort (even in non-interactive use).
12518 * But if we skip popfile(), we hit EOF in eval's string, and exit.
12520 savehandler = exception_handler;
12521 ex = setjmp(jmploc.loc);
12524 exception_handler = &jmploc;
12526 while ((n = parsecmd(0)) != NODE_EOF) {
12529 i = evaltree(n, flags);
12532 popstackmark(&smark);
12537 popstackmark(&smark);
12541 exception_handler = savehandler;
12543 longjmp(exception_handler->loc, ex);
12549 * The eval command.
12551 static int FAST_FUNC
12552 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12561 STARTSTACKSTR(concat);
12563 concat = stack_putstr(p, concat);
12567 STPUTC(' ', concat);
12569 STPUTC('\0', concat);
12570 p = grabstackstr(concat);
12572 return evalstring(p, flags & EV_TESTED);
12578 * Read and execute commands.
12579 * "Top" is nonzero for the top level command loop;
12580 * it turns on prompting if the shell is interactive.
12586 struct stackmark smark;
12591 TRACE(("cmdloop(%d) called\n", top));
12595 setstackmark(&smark);
12598 showjobs(SHOW_CHANGED|SHOW_STDERR);
12601 if (iflag && top) {
12605 n = parsecmd(inter);
12607 if (DEBUG > 2 && debug && (n != NODE_EOF))
12610 if (n == NODE_EOF) {
12611 if (!top || numeof >= 50)
12613 if (!stoppedjobs()) {
12616 out2str("\nUse \"exit\" to leave shell.\n");
12619 } else if (nflag == 0) {
12622 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12625 i = evaltree(n, 0);
12629 popstackmark(&smark);
12633 evalskip &= ~SKIPFUNC;
12641 * Take commands from a file. To be compatible we should do a path
12642 * search for the file, which is necessary to find sub-commands.
12645 find_dot_file(char *name)
12648 const char *path = pathval();
12651 /* don't try this for absolute or relative paths */
12652 if (strchr(name, '/'))
12655 while ((fullname = path_advance(&path, name)) != NULL) {
12656 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12658 * Don't bother freeing here, since it will
12659 * be freed by the caller.
12663 if (fullname != name)
12664 stunalloc(fullname);
12667 /* not found in the PATH */
12668 ash_msg_and_raise_error("%s: not found", name);
12672 static int FAST_FUNC
12673 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12675 /* "false; . empty_file; echo $?" should print 0, not 1: */
12679 char *args_need_save;
12680 struct strlist *sp;
12681 volatile struct shparam saveparam;
12683 for (sp = cmdenviron; sp; sp = sp->next)
12684 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12686 nextopt(nullstr); /* handle possible "--" */
12690 /* bash says: "bash: .: filename argument required" */
12691 return 2; /* bash compat */
12694 /* This aborts if file isn't found, which is POSIXly correct.
12695 * bash returns exitcode 1 instead.
12697 fullname = find_dot_file(argv[0]);
12699 args_need_save = argv[0];
12700 if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
12702 saveparam = shellparam;
12703 shellparam.malloced = 0;
12707 shellparam.nparam = argc;
12708 shellparam.p = argv;
12711 /* This aborts if file can't be opened, which is POSIXly correct.
12712 * bash returns exitcode 1 instead.
12714 setinputfile(fullname, INPUT_PUSH_FILE);
12715 commandname = fullname;
12716 status = cmdloop(0);
12719 if (args_need_save) {
12720 freeparam(&shellparam);
12721 shellparam = saveparam;
12727 static int FAST_FUNC
12728 exitcmd(int argc UNUSED_PARAM, char **argv)
12733 exitstatus = number(argv[1]);
12734 raise_exception(EXEXIT);
12739 * Read a file containing shell functions.
12742 readcmdfile(char *name)
12744 setinputfile(name, INPUT_PUSH_FILE);
12750 /* ============ find_command inplementation */
12753 * Resolve a command name. If you change this routine, you may have to
12754 * change the shellexec routine as well.
12757 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12759 struct tblentry *cmdp;
12766 struct builtincmd *bcmd;
12768 /* If name contains a slash, don't use PATH or hash table */
12769 if (strchr(name, '/') != NULL) {
12770 entry->u.index = -1;
12771 if (act & DO_ABS) {
12772 while (stat(name, &statb) < 0) {
12774 if (errno == EINTR)
12777 entry->cmdtype = CMDUNKNOWN;
12781 entry->cmdtype = CMDNORMAL;
12785 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12787 updatetbl = (path == pathval());
12790 if (strstr(path, "%builtin") != NULL)
12791 act |= DO_ALTBLTIN;
12794 /* If name is in the table, check answer will be ok */
12795 cmdp = cmdlookup(name, 0);
12796 if (cmdp != NULL) {
12799 switch (cmdp->cmdtype) {
12817 } else if (cmdp->rehash == 0)
12818 /* if not invalidated by cd, we're done */
12822 /* If %builtin not in path, check for builtin next */
12823 bcmd = find_builtin(name);
12825 if (IS_BUILTIN_REGULAR(bcmd))
12826 goto builtin_success;
12827 if (act & DO_ALTPATH) {
12828 if (!(act & DO_ALTBLTIN))
12829 goto builtin_success;
12830 } else if (builtinloc <= 0) {
12831 goto builtin_success;
12835 #if ENABLE_FEATURE_SH_STANDALONE
12837 int applet_no = find_applet_by_name(name);
12838 if (applet_no >= 0) {
12839 entry->cmdtype = CMDNORMAL;
12840 entry->u.index = -2 - applet_no;
12846 /* We have to search path. */
12847 prev = -1; /* where to start */
12848 if (cmdp && cmdp->rehash) { /* doing a rehash */
12849 if (cmdp->cmdtype == CMDBUILTIN)
12852 prev = cmdp->param.index;
12858 while ((fullname = path_advance(&path, name)) != NULL) {
12859 stunalloc(fullname);
12860 /* NB: code below will still use fullname
12861 * despite it being "unallocated" */
12864 if (prefix(pathopt, "builtin")) {
12866 goto builtin_success;
12869 if ((act & DO_NOFUNC)
12870 || !prefix(pathopt, "func")
12871 ) { /* ignore unimplemented options */
12875 /* if rehash, don't redo absolute path names */
12876 if (fullname[0] == '/' && idx <= prev) {
12879 TRACE(("searchexec \"%s\": no change\n", name));
12882 while (stat(fullname, &statb) < 0) {
12884 if (errno == EINTR)
12887 if (errno != ENOENT && errno != ENOTDIR)
12891 e = EACCES; /* if we fail, this will be the error */
12892 if (!S_ISREG(statb.st_mode))
12894 if (pathopt) { /* this is a %func directory */
12895 stalloc(strlen(fullname) + 1);
12896 /* NB: stalloc will return space pointed by fullname
12897 * (because we don't have any intervening allocations
12898 * between stunalloc above and this stalloc) */
12899 readcmdfile(fullname);
12900 cmdp = cmdlookup(name, 0);
12901 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12902 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12903 stunalloc(fullname);
12906 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12908 entry->cmdtype = CMDNORMAL;
12909 entry->u.index = idx;
12913 cmdp = cmdlookup(name, 1);
12914 cmdp->cmdtype = CMDNORMAL;
12915 cmdp->param.index = idx;
12920 /* We failed. If there was an entry for this command, delete it */
12921 if (cmdp && updatetbl)
12922 delete_cmd_entry();
12924 ash_msg("%s: %s", name, errmsg(e, "not found"));
12925 entry->cmdtype = CMDUNKNOWN;
12930 entry->cmdtype = CMDBUILTIN;
12931 entry->u.cmd = bcmd;
12935 cmdp = cmdlookup(name, 1);
12936 cmdp->cmdtype = CMDBUILTIN;
12937 cmdp->param.cmd = bcmd;
12941 entry->cmdtype = cmdp->cmdtype;
12942 entry->u = cmdp->param;
12947 * The trap builtin.
12949 static int FAST_FUNC
12950 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12954 int signo, exitcode;
12959 for (signo = 0; signo < NSIG; signo++) {
12960 char *tr = trap_ptr[signo];
12962 /* note: bash adds "SIG", but only if invoked
12963 * as "bash". If called as "sh", or if set -o posix,
12964 * then it prints short signal names.
12965 * We are printing short names: */
12966 out1fmt("trap -- %s %s\n",
12968 get_signame(signo));
12969 /* trap_ptr != trap only if we are in special-cased `trap` code.
12970 * In this case, we will exit very soon, no need to free(). */
12971 /* if (trap_ptr != trap && tp[0]) */
12976 if (trap_ptr != trap) {
12989 signo = get_signum(*ap);
12990 if (signo < 0 || signo >= NSIG) {
12991 /* Mimic bash message exactly */
12992 ash_msg("%s: invalid signal specification", *ap);
12998 if (LONE_DASH(action))
13001 if (action[0]) /* not NULL and not "" and not "-" */
13002 may_have_traps = 1;
13003 action = ckstrdup(action);
13007 trap[signo] = action;
13018 /* ============ Builtins */
13020 #if ENABLE_ASH_HELP
13021 static int FAST_FUNC
13022 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13028 "Built-in commands:\n"
13029 "------------------\n");
13030 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
13031 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
13032 builtintab[i].name + 1);
13038 # if ENABLE_FEATURE_SH_STANDALONE
13040 const char *a = applet_names;
13042 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
13047 while (*a++ != '\0')
13052 newline_and_flush(stdout);
13053 return EXIT_SUCCESS;
13058 static int FAST_FUNC
13059 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13061 show_history(line_input_state);
13062 return EXIT_SUCCESS;
13067 * The export and readonly commands.
13069 static int FAST_FUNC
13070 exportcmd(int argc UNUSED_PARAM, char **argv)
13080 /* "readonly" in bash accepts, but ignores -n.
13081 * We do the same: it saves a conditional in nextopt's param.
13084 while ((opt = nextopt("np")) != '\0') {
13086 flag_off = VEXPORT;
13089 if (argv[0][0] == 'r') {
13091 flag_off = 0; /* readonly ignores -n */
13093 flag_off = ~flag_off;
13095 /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
13101 p = strchr(name, '=');
13105 vp = *findvar(hashvar(name), name);
13107 vp->flags = ((vp->flags | flag) & flag_off);
13111 setvar(name, p, (flag & flag_off));
13112 } while ((name = *++aptr) != NULL);
13117 /* No arguments. Show the list of exported or readonly vars.
13120 showvars(argv[0], flag, 0);
13125 * Delete a function if it exists.
13128 unsetfunc(const char *name)
13130 struct tblentry *cmdp;
13132 cmdp = cmdlookup(name, 0);
13133 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
13134 delete_cmd_entry();
13138 * The unset builtin command. We unset the function before we unset the
13139 * variable to allow a function to be unset when there is a readonly variable
13140 * with the same name.
13142 static int FAST_FUNC
13143 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13149 while ((i = nextopt("vf")) != 0) {
13153 for (ap = argptr; *ap; ap++) {
13164 static const unsigned char timescmd_str[] ALIGN1 = {
13165 ' ', offsetof(struct tms, tms_utime),
13166 '\n', offsetof(struct tms, tms_stime),
13167 ' ', offsetof(struct tms, tms_cutime),
13168 '\n', offsetof(struct tms, tms_cstime),
13171 static int FAST_FUNC
13172 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13174 unsigned long clk_tck, s, t;
13175 const unsigned char *p;
13178 clk_tck = bb_clk_tck();
13183 t = *(clock_t *)(((char *) &buf) + p[1]);
13186 out1fmt("%lum%lu.%03lus%c",
13188 (t * 1000) / clk_tck,
13196 #if ENABLE_FEATURE_SH_MATH
13198 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13199 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13201 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13203 static int FAST_FUNC
13204 letcmd(int argc UNUSED_PARAM, char **argv)
13210 ash_msg_and_raise_error("expression expected");
13212 i = ash_arith(*argv);
13220 * The read builtin. Options:
13221 * -r Do not interpret '\' specially
13222 * -s Turn off echo (tty only)
13223 * -n NCHARS Read NCHARS max
13224 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13225 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13226 * -u FD Read from given FD instead of fd 0
13227 * This uses unbuffered input, which may be avoidable in some cases.
13228 * TODO: bash also has:
13229 * -a ARRAY Read into array[0],[1],etc
13230 * -d DELIM End on DELIM char, not newline
13231 * -e Use line editing (tty only)
13233 static int FAST_FUNC
13234 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13236 char *opt_n = NULL;
13237 char *opt_p = NULL;
13238 char *opt_t = NULL;
13239 char *opt_u = NULL;
13240 int read_flags = 0;
13244 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13253 read_flags |= BUILTIN_READ_SILENT;
13259 read_flags |= BUILTIN_READ_RAW;
13269 /* "read -s" needs to save/restore termios, can't allow ^C
13270 * to jump out of it.
13274 r = shell_builtin_read(setvar0,
13276 bltinlookup("IFS"), /* can be NULL */
13285 if ((uintptr_t)r == 1 && errno == EINTR) {
13286 /* to get SIGCHLD: sleep 1 & read x; echo $x */
13287 if (pending_sig == 0)
13291 if ((uintptr_t)r > 1)
13292 ash_msg_and_raise_error(r);
13294 return (uintptr_t)r;
13297 static int FAST_FUNC
13298 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13300 static const char permuser[3] ALIGN1 = "ogu";
13303 int symbolic_mode = 0;
13305 while (nextopt("S") != '\0') {
13314 if (*argptr == NULL) {
13315 if (symbolic_mode) {
13316 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13323 *p++ = permuser[i];
13325 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13326 if (!(mask & 0400)) *p++ = 'r';
13327 if (!(mask & 0200)) *p++ = 'w';
13328 if (!(mask & 0100)) *p++ = 'x';
13336 out1fmt("%04o\n", mask);
13339 char *modestr = *argptr;
13340 /* numeric umasks are taken as-is */
13341 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13342 if (!isdigit(modestr[0]))
13344 mask = bb_parse_mode(modestr, mask);
13345 if ((unsigned)mask > 0777) {
13346 ash_msg_and_raise_error("illegal mode: %s", modestr);
13348 if (!isdigit(modestr[0]))
13355 static int FAST_FUNC
13356 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13358 return shell_builtin_ulimit(argv);
13361 /* ============ main() and helpers */
13364 * Called to exit the shell.
13373 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13374 save_history(line_input_state);
13376 status = exitstatus;
13377 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13378 if (setjmp(loc.loc)) {
13379 if (exception_type == EXEXIT)
13380 status = exitstatus;
13383 exception_handler = &loc;
13389 /*free(p); - we'll exit soon */
13392 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13393 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13396 flush_stdout_stderr();
13404 /* we will never free this */
13405 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13407 sigmode[SIGCHLD - 1] = S_DFL;
13408 setsignal(SIGCHLD);
13410 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13411 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13413 signal(SIGHUP, SIG_DFL);
13418 struct stat st1, st2;
13421 for (envp = environ; envp && *envp; envp++) {
13422 p = endofname(*envp);
13423 if (p != *envp && *p == '=') {
13424 setvareq(*envp, VEXPORT|VTEXTFIXED);
13428 setvareq((char*)defoptindvar, VTEXTFIXED);
13430 setvar0("PPID", utoa(getppid()));
13432 p = lookupvar("SHLVL");
13433 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13435 #if BASH_HOSTNAME_VAR
13436 if (!lookupvar("HOSTNAME")) {
13437 struct utsname uts;
13439 setvar0("HOSTNAME", uts.nodename);
13442 p = lookupvar("PWD");
13444 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13445 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13455 //usage:#define ash_trivial_usage
13456 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13457 //usage:#define ash_full_usage "\n\n"
13458 //usage: "Unix shell interpreter"
13461 * Process the shell command line arguments.
13464 procargs(char **argv)
13467 const char *xminusc;
13472 /* if (xargv[0]) - mmm, this is always true! */
13474 for (i = 0; i < NOPTS; i++)
13477 if (options(/*cmdline:*/ 1)) {
13478 /* it already printed err message */
13479 raise_exception(EXERROR);
13483 if (*xargv == NULL) {
13485 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13488 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13492 for (i = 0; i < NOPTS; i++)
13493 if (optlist[i] == 2)
13498 /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
13503 } else if (!sflag) {
13504 setinputfile(*xargv, 0);
13507 commandname = arg0;
13510 shellparam.p = xargv;
13511 #if ENABLE_ASH_GETOPTS
13512 shellparam.optind = 1;
13513 shellparam.optoff = -1;
13515 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13517 shellparam.nparam++;
13524 * Read /etc/profile, ~/.profile, $ENV.
13527 read_profile(const char *name)
13529 name = expandstr(name);
13530 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13537 * This routine is called when an error or an interrupt occurs in an
13538 * interactive shell and control is returned to the main command loop.
13539 * (In dash, this function is auto-generated by build machinery).
13548 /* from expand.c: */
13551 /* from input.c: */
13552 g_parsefile->left_in_buffer = 0;
13553 g_parsefile->left_in_line = 0; /* clear input buffer */
13556 /* from redir.c: */
13558 popredir(/*drop:*/ 0, /*restore:*/ 0);
13562 static short profile_buf[16384];
13563 extern int etext();
13567 * Main routine. We initialize things, parse the arguments, execute
13568 * profiles if we're a login shell, and then call cmdloop to execute
13569 * commands. The setjmp call sets up the location to jump to when an
13570 * exception occurs. When an exception occurs the variable "state"
13571 * is used to figure out how far we had gotten.
13573 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13574 int ash_main(int argc UNUSED_PARAM, char **argv)
13576 volatile smallint state;
13577 struct jmploc jmploc;
13578 struct stackmark smark;
13580 /* Initialize global data */
13584 #if ENABLE_ASH_ALIAS
13590 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13593 #if ENABLE_FEATURE_EDITING
13594 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13597 if (setjmp(jmploc.loc)) {
13603 e = exception_type;
13605 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13609 newline_and_flush(stderr);
13612 popstackmark(&smark);
13613 FORCE_INT_ON; /* enable interrupts */
13622 exception_handler = &jmploc;
13623 rootpid = getpid();
13626 setstackmark(&smark);
13629 TRACE(("Shell args: "));
13630 trace_puts_args(argv);
13633 if (argv[0] && argv[0][0] == '-')
13639 read_profile("/etc/profile");
13642 hp = lookupvar("HOME");
13644 read_profile("$HOME/.profile");
13650 getuid() == geteuid() && getgid() == getegid() &&
13654 const char *shinit = lookupvar("ENV");
13655 if (shinit != NULL && *shinit != '\0')
13656 read_profile(shinit);
13658 popstackmark(&smark);
13662 /* evalstring pushes parsefile stack.
13663 * Ensure we don't falsely claim that 0 (stdin)
13664 * is one of stacked source fds.
13665 * Testcase: ash -c 'exec 1>&0' must not complain. */
13666 // if (!sflag) g_parsefile->pf_fd = -1;
13667 // ^^ not necessary since now we special-case fd 0
13668 // in is_hidden_fd() to not be considered "hidden fd"
13669 evalstring(minusc, 0);
13672 if (sflag || minusc == NULL) {
13673 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13675 const char *hp = lookupvar("HISTFILE");
13677 hp = lookupvar("HOME");
13680 hp = concat_path_file(hp, ".ash_history");
13681 setvar0("HISTFILE", hp);
13684 hp = lookupvar("HISTFILE");
13688 line_input_state->hist_file = hp;
13689 # if ENABLE_FEATURE_SH_HISTFILESIZE
13690 hp = lookupvar("HISTFILESIZE");
13691 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13695 state4: /* XXX ??? - why isn't this before the "if" statement */
13703 extern void _mcleanup(void);
13707 TRACE(("End of main reached\n"));
13714 * Copyright (c) 1989, 1991, 1993, 1994
13715 * The Regents of the University of California. All rights reserved.
13717 * This code is derived from software contributed to Berkeley by
13718 * Kenneth Almquist.
13720 * Redistribution and use in source and binary forms, with or without
13721 * modification, are permitted provided that the following conditions
13723 * 1. Redistributions of source code must retain the above copyright
13724 * notice, this list of conditions and the following disclaimer.
13725 * 2. Redistributions in binary form must reproduce the above copyright
13726 * notice, this list of conditions and the following disclaimer in the
13727 * documentation and/or other materials provided with the distribution.
13728 * 3. Neither the name of the University nor the names of its contributors
13729 * may be used to endorse or promote products derived from this software
13730 * without specific prior written permission.
13732 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13733 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13734 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13735 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13736 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13737 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13738 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13739 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13740 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13741 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF