1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
21 //config: depends on !NOMMU
23 //config: Tha 'ash' shell adds about 60k in the default configuration and is
24 //config: the most complete and most pedantically correct shell included with
25 //config: busybox. This shell is actually a derivative of the Debian 'dash'
26 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
27 //config: (written by Kenneth Almquist) from NetBSD.
29 //config:config ASH_OPTIMIZE_FOR_SIZE
30 //config: bool "Optimize for size instead of speed"
32 //config: depends on ASH
34 //config: Compile ash for reduced size at the price of speed.
36 //config:config ASH_INTERNAL_GLOB
37 //config: bool "Use internal glob() implementation"
38 //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
39 //config: depends on ASH
41 //config: Do not use glob() function from libc, use internal implementation.
42 //config: Use this if you are getting "glob.h: No such file or directory"
43 //config: or similar build errors.
45 //config:config ASH_RANDOM_SUPPORT
46 //config: bool "Pseudorandom generator and $RANDOM variable"
48 //config: depends on ASH
50 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
51 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
52 //config: You can reset the generator by using a specified start value.
53 //config: After "unset RANDOM" the generator will switch off and this
54 //config: variable will no longer have special treatment.
56 //config:config ASH_EXPAND_PRMT
57 //config: bool "Expand prompt string"
59 //config: depends on ASH
61 //config: "PS#" may contain volatile content, such as backquote commands.
62 //config: This option recreates the prompt string from the environment
63 //config: variable each time it is displayed.
65 //config:config ASH_BASH_COMPAT
66 //config: bool "bash-compatible extensions"
68 //config: depends on ASH
70 //config: Enable bash-compatible extensions.
72 //config:config ASH_IDLE_TIMEOUT
73 //config: bool "Idle timeout variable"
75 //config: depends on ASH
77 //config: Enables bash-like auto-logout after $TMOUT seconds of idle time.
79 //config:config ASH_JOB_CONTROL
80 //config: bool "Job control"
82 //config: depends on ASH
84 //config: Enable job control in the ash shell.
86 //config:config ASH_ALIAS
87 //config: bool "Alias support"
89 //config: depends on ASH
91 //config: Enable alias support in the ash shell.
93 //config:config ASH_GETOPTS
94 //config: bool "Builtin getopt to parse positional parameters"
96 //config: depends on ASH
98 //config: Enable support for getopts builtin in ash.
100 //config:config ASH_BUILTIN_ECHO
101 //config: bool "Builtin version of 'echo'"
103 //config: depends on ASH
105 //config: Enable support for echo builtin in ash.
107 //config:config ASH_BUILTIN_PRINTF
108 //config: bool "Builtin version of 'printf'"
110 //config: depends on ASH
112 //config: Enable support for printf builtin in ash.
114 //config:config ASH_BUILTIN_TEST
115 //config: bool "Builtin version of 'test'"
117 //config: depends on ASH
119 //config: Enable support for test builtin in ash.
121 //config:config ASH_HELP
122 //config: bool "help builtin"
124 //config: depends on ASH
126 //config: Enable help builtin in ash.
128 //config:config ASH_CMDCMD
129 //config: bool "'command' command to override shell builtins"
131 //config: depends on ASH
133 //config: Enable support for the ash 'command' builtin, which allows
134 //config: you to run the specified command with the specified arguments,
135 //config: even when there is an ash builtin command with the same name.
137 //config:config ASH_MAIL
138 //config: bool "Check for new mail on interactive shells"
140 //config: depends on ASH
142 //config: Enable "check for new mail" function in the ash shell.
144 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
145 //applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, sh))
146 //applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, bash))
148 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
149 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
152 * The following should be set to reflect the type of system you have:
153 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
154 * define SYSV if you are running under System V.
155 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
156 * define DEBUG=2 to compile in and turn on debugging.
158 * When debugging is on (DEBUG is 1 and "set -o debug" was executed),
159 * debugging info will be written to ./trace and a quit signal
160 * will generate a core dump.
163 /* Tweak debug output verbosity here */
167 #define DEBUG_INTONOFF 0
171 #define JOBS ENABLE_ASH_JOB_CONTROL
175 #include <sys/times.h>
176 #include <sys/utsname.h> /* for setting $HOSTNAME */
178 #include "busybox.h" /* for applet_names */
180 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
181 /* Bionic at least up to version 24 has no glob() */
182 # undef ENABLE_ASH_INTERNAL_GLOB
183 # define ENABLE_ASH_INTERNAL_GLOB 1
186 #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
187 # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
188 # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
189 # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
190 # error glob() should unbackslash them and match. uClibc does not unbackslash,
191 # error fails to match dirname, subsequently not expanding <pattern> in it.
193 // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
194 // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
197 #if !ENABLE_ASH_INTERNAL_GLOB
202 #include "shell_common.h"
203 #if ENABLE_SH_MATH_SUPPORT
206 #if ENABLE_ASH_RANDOM_SUPPORT
209 # define CLEAR_RANDOM_T(rnd) ((void)0)
212 #include "NUM_APPLETS.h"
214 /* STANDALONE does not make sense, and won't compile */
215 # undef CONFIG_FEATURE_SH_STANDALONE
216 # undef ENABLE_FEATURE_SH_STANDALONE
217 # undef IF_FEATURE_SH_STANDALONE
218 # undef IF_NOT_FEATURE_SH_STANDALONE
219 # define ENABLE_FEATURE_SH_STANDALONE 0
220 # define IF_FEATURE_SH_STANDALONE(...)
221 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
225 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
229 # error "Do not even bother, ash will not run on NOMMU machine"
233 /* ============ Hash table sizes. Configurable. */
237 #define CMDTABLESIZE 31 /* should be prime */
240 /* ============ Shell options */
242 static const char *const optletters_optnames[] = {
257 #if ENABLE_ASH_BASH_COMPAT
266 #define optletters(n) optletters_optnames[n][0]
267 #define optnames(n) (optletters_optnames[n] + 1)
269 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
272 /* ============ Misc data */
274 #define msg_illnum "Illegal number: %s"
277 * We enclose jmp_buf in a structure so that we can declare pointers to
278 * jump locations. The global variable handler contains the location to
279 * jump to when an exception occurs, and the global variable exception_type
280 * contains a code identifying the exception. To implement nested
281 * exception handlers, the user should save the value of handler on entry
282 * to an inner scope, set handler to point to a jmploc structure for the
283 * inner scope, and restore handler on exit from the scope.
289 struct globals_misc {
290 uint8_t exitstatus; /* exit status of last command */
291 uint8_t back_exitstatus;/* exit status of backquoted command */
292 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
293 int rootpid; /* pid of main shell */
294 /* shell level: 0 for the main shell, 1 for its children, and so on */
296 #define rootshell (!shlvl)
297 char *minusc; /* argument to -c option */
299 char *curdir; // = nullstr; /* current working directory */
300 char *physdir; // = nullstr; /* physical working directory */
302 char *arg0; /* value of $0 */
304 struct jmploc *exception_handler;
306 volatile int suppress_int; /* counter */
307 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
308 volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
309 volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
310 smallint exception_type; /* kind of exception (0..5) */
312 #define EXINT 0 /* SIGINT received */
313 #define EXERROR 1 /* a generic error */
314 #define EXEXIT 4 /* exit the shell */
317 char nullstr[1]; /* zero length string */
320 #define eflag optlist[0]
321 #define fflag optlist[1]
322 #define Iflag optlist[2]
323 #define iflag optlist[3]
324 #define mflag optlist[4]
325 #define nflag optlist[5]
326 #define sflag optlist[6]
327 #define xflag optlist[7]
328 #define vflag optlist[8]
329 #define Cflag optlist[9]
330 #define aflag optlist[10]
331 #define bflag optlist[11]
332 #define uflag optlist[12]
333 #define viflag optlist[13]
334 #if ENABLE_ASH_BASH_COMPAT
335 # define pipefail optlist[14]
340 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
341 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
344 /* trap handler commands */
346 * Sigmode records the current value of the signal handlers for the various
347 * modes. A value of zero means that the current handler is not known.
348 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
350 char sigmode[NSIG - 1];
351 #define S_DFL 1 /* default signal handling (SIG_DFL) */
352 #define S_CATCH 2 /* signal is caught */
353 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
354 #define S_HARD_IGN 4 /* signal is ignored permanently */
356 /* indicates specified signal received */
357 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
358 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
360 char **trap_ptr; /* used only by "trap hack" */
362 /* Rarely referenced stuff */
363 #if ENABLE_ASH_RANDOM_SUPPORT
366 pid_t backgndpid; /* pid of last background process */
368 extern struct globals_misc *const ash_ptr_to_globals_misc;
369 #define G_misc (*ash_ptr_to_globals_misc)
370 #define exitstatus (G_misc.exitstatus )
371 #define back_exitstatus (G_misc.back_exitstatus )
372 #define job_warning (G_misc.job_warning)
373 #define rootpid (G_misc.rootpid )
374 #define shlvl (G_misc.shlvl )
375 #define minusc (G_misc.minusc )
376 #define curdir (G_misc.curdir )
377 #define physdir (G_misc.physdir )
378 #define arg0 (G_misc.arg0 )
379 #define exception_handler (G_misc.exception_handler)
380 #define exception_type (G_misc.exception_type )
381 #define suppress_int (G_misc.suppress_int )
382 #define pending_int (G_misc.pending_int )
383 #define got_sigchld (G_misc.got_sigchld )
384 #define pending_sig (G_misc.pending_sig )
385 #define isloginsh (G_misc.isloginsh )
386 #define nullstr (G_misc.nullstr )
387 #define optlist (G_misc.optlist )
388 #define sigmode (G_misc.sigmode )
389 #define gotsig (G_misc.gotsig )
390 #define may_have_traps (G_misc.may_have_traps )
391 #define trap (G_misc.trap )
392 #define trap_ptr (G_misc.trap_ptr )
393 #define random_gen (G_misc.random_gen )
394 #define backgndpid (G_misc.backgndpid )
395 #define INIT_G_misc() do { \
396 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
404 /* ============ DEBUG */
406 static void trace_printf(const char *fmt, ...);
407 static void trace_vprintf(const char *fmt, va_list va);
408 # define TRACE(param) trace_printf param
409 # define TRACEV(param) trace_vprintf param
410 # define close(fd) do { \
412 if (close(dfd) < 0) \
413 bb_error_msg("bug on %d: closing %d(0x%x)", \
414 __LINE__, dfd, dfd); \
417 # define TRACE(param)
418 # define TRACEV(param)
422 /* ============ Utility functions */
423 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
424 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
427 isdigit_str9(const char *str)
429 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
430 while (--maxlen && isdigit(*str))
432 return (*str == '\0');
436 var_end(const char *var)
445 /* ============ Interrupts / exceptions */
447 static void exitshell(void) NORETURN;
450 * These macros allow the user to suspend the handling of interrupt signals
451 * over a period of time. This is similar to SIGHOLD or to sigblock, but
452 * much more efficient and portable. (But hacking the kernel is so much
453 * more fun than worrying about efficiency and portability. :-))
456 # define INT_OFF do { \
457 TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
462 # define INT_OFF do { \
469 * Called to raise an exception. Since C doesn't include exceptions, we
470 * just do a longjmp to the exception handler. The type of exception is
471 * stored in the global variable "exception_type".
473 static void raise_exception(int) NORETURN;
475 raise_exception(int e)
478 if (exception_handler == NULL)
483 longjmp(exception_handler->loc, 1);
486 #define raise_exception(e) do { \
487 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
488 raise_exception(e); \
493 * Called when a SIGINT is received. (If the user specifies
494 * that SIGINT is to be trapped or ignored using the trap builtin, then
495 * this routine is not called.) Suppressint is nonzero when interrupts
496 * are held using the INT_OFF macro. (The test for iflag is just
497 * defensive programming.)
499 static void raise_interrupt(void) NORETURN;
501 raise_interrupt(void)
504 /* Signal is not automatically unmasked after it is raised,
505 * do it ourself - unmask all signals */
506 sigprocmask_allsigs(SIG_UNBLOCK);
507 /* pending_sig = 0; - now done in signal_handler() */
509 if (!(rootshell && iflag)) {
510 /* Kill ourself with SIGINT */
511 signal(SIGINT, SIG_DFL);
514 /* bash: ^C even on empty command line sets $? */
515 exitstatus = SIGINT + 128;
516 raise_exception(EXINT);
520 #define raise_interrupt() do { \
521 TRACE(("raising interrupt on line %d\n", __LINE__)); \
526 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
530 if (--suppress_int == 0 && pending_int) {
535 # define INT_ON do { \
536 TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
540 # define INT_ON int_on()
542 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
550 #define FORCE_INT_ON force_int_on()
552 #define SAVE_INT(v) ((v) = suppress_int)
554 #define RESTORE_INT(v) do { \
556 suppress_int = (v); \
557 if (suppress_int == 0 && pending_int) \
562 /* ============ Stdout/stderr output */
565 outstr(const char *p, FILE *file)
573 flush_stdout_stderr(void)
580 /* Was called outcslow(c,FILE*), but c was always '\n' */
582 newline_and_flush(FILE *dest)
590 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
592 out1fmt(const char *fmt, ...)
599 r = vprintf(fmt, ap);
605 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
607 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
614 ret = vsnprintf(outbuf, length, fmt, ap);
621 out1str(const char *p)
627 out2str(const char *p)
630 flush_stdout_stderr();
634 /* ============ Parser structures */
636 /* control characters in argument strings */
637 #define CTL_FIRST CTLESC
638 #define CTLESC ((unsigned char)'\201') /* escape next character */
639 #define CTLVAR ((unsigned char)'\202') /* variable defn */
640 #define CTLENDVAR ((unsigned char)'\203')
641 #define CTLBACKQ ((unsigned char)'\204')
642 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
643 #define CTLENDARI ((unsigned char)'\207')
644 #define CTLQUOTEMARK ((unsigned char)'\210')
645 #define CTL_LAST CTLQUOTEMARK
647 /* variable substitution byte (follows CTLVAR) */
648 #define VSTYPE 0x0f /* type of variable substitution */
649 #define VSNUL 0x10 /* colon--treat the empty string as unset */
651 /* values of VSTYPE field */
652 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
653 #define VSMINUS 0x2 /* ${var-text} */
654 #define VSPLUS 0x3 /* ${var+text} */
655 #define VSQUESTION 0x4 /* ${var?message} */
656 #define VSASSIGN 0x5 /* ${var=text} */
657 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
658 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
659 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
660 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
661 #define VSLENGTH 0xa /* ${#var} */
662 #if ENABLE_ASH_BASH_COMPAT
663 #define VSSUBSTR 0xc /* ${var:position:length} */
664 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
665 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
668 static const char dolatstr[] ALIGN1 = {
669 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
671 #define DOLATSTRLEN 6
690 #if ENABLE_ASH_BASH_COMPAT
707 smallint type; /* Nxxxx */
710 union node *redirect;
715 smallint pipe_backgnd;
716 struct nodelist *cmdlist;
722 union node *redirect;
735 union node *elsepart;
762 struct nodelist *backquote;
765 /* nfile and ndup layout must match!
766 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
767 * that it is actually NTO2 (>&file), and change its type.
784 char *_unused_expfname;
803 struct nredir nredir;
804 struct nbinary nbinary;
808 struct nclist nclist;
817 * NODE_EOF is returned by parsecmd when it encounters an end of file.
818 * It must be distinct from NULL.
820 #define NODE_EOF ((union node *) -1L)
823 struct nodelist *next;
836 freefunc(struct funcnode *f)
838 if (f && --f->count < 0)
843 /* ============ Debugging output */
847 static FILE *tracefile;
850 trace_printf(const char *fmt, ...)
857 fprintf(tracefile, "%u ", (int) time(NULL));
859 fprintf(tracefile, "[%u] ", (int) getpid());
861 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
863 vfprintf(tracefile, fmt, va);
868 trace_vprintf(const char *fmt, va_list va)
872 vfprintf(tracefile, fmt, va);
873 fprintf(tracefile, "\n");
877 trace_puts(const char *s)
885 trace_puts_quoted(char *s)
892 putc('"', tracefile);
893 for (p = s; *p; p++) {
894 switch ((unsigned char)*p) {
895 case '\n': c = 'n'; goto backslash;
896 case '\t': c = 't'; goto backslash;
897 case '\r': c = 'r'; goto backslash;
898 case '\"': c = '\"'; goto backslash;
899 case '\\': c = '\\'; goto backslash;
900 case CTLESC: c = 'e'; goto backslash;
901 case CTLVAR: c = 'v'; goto backslash;
902 case CTLBACKQ: c = 'q'; goto backslash;
904 putc('\\', tracefile);
908 if (*p >= ' ' && *p <= '~')
911 putc('\\', tracefile);
912 putc((*p >> 6) & 03, tracefile);
913 putc((*p >> 3) & 07, tracefile);
914 putc(*p & 07, tracefile);
919 putc('"', tracefile);
923 trace_puts_args(char **ap)
930 trace_puts_quoted(*ap);
932 putc('\n', tracefile);
935 putc(' ', tracefile);
950 /* leave open because libedit might be using it */
953 strcpy(s, "./trace");
955 if (!freopen(s, "a", tracefile)) {
956 fprintf(stderr, "Can't re-open %s\n", s);
961 tracefile = fopen(s, "a");
962 if (tracefile == NULL) {
963 fprintf(stderr, "Can't open %s\n", s);
969 flags = fcntl(fileno(tracefile), F_GETFL);
971 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
973 setlinebuf(tracefile);
974 fputs("\nTracing started.\n", tracefile);
978 indent(int amount, char *pfx, FILE *fp)
982 for (i = 0; i < amount; i++) {
983 if (pfx && i == amount - 1)
989 /* little circular references here... */
990 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
993 sharg(union node *arg, FILE *fp)
996 struct nodelist *bqlist;
997 unsigned char subtype;
999 if (arg->type != NARG) {
1000 out1fmt("<node type %d>\n", arg->type);
1003 bqlist = arg->narg.backquote;
1004 for (p = arg->narg.text; *p; p++) {
1005 switch ((unsigned char)*p) {
1014 if (subtype == VSLENGTH)
1022 if (subtype & VSNUL)
1025 switch (subtype & VSTYPE) {
1051 case VSTRIMRIGHTMAX:
1058 out1fmt("<subtype %d>", subtype);
1067 shtree(bqlist->n, -1, NULL, fp);
1078 shcmd(union node *cmd, FILE *fp)
1086 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1092 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1096 switch (np->nfile.type) {
1097 case NTO: s = ">>"+1; dftfd = 1; break;
1098 case NCLOBBER: s = ">|"; dftfd = 1; break;
1099 case NAPPEND: s = ">>"; dftfd = 1; break;
1100 #if ENABLE_ASH_BASH_COMPAT
1103 case NTOFD: s = ">&"; dftfd = 1; break;
1104 case NFROM: s = "<"; break;
1105 case NFROMFD: s = "<&"; break;
1106 case NFROMTO: s = "<>"; break;
1107 default: s = "*error*"; break;
1109 if (np->nfile.fd != dftfd)
1110 fprintf(fp, "%d", np->nfile.fd);
1112 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1113 fprintf(fp, "%d", np->ndup.dupfd);
1115 sharg(np->nfile.fname, fp);
1122 shtree(union node *n, int ind, char *pfx, FILE *fp)
1124 struct nodelist *lp;
1130 indent(ind, pfx, fp);
1132 if (n == NODE_EOF) {
1147 shtree(n->nbinary.ch1, ind, NULL, fp);
1150 shtree(n->nbinary.ch2, ind, NULL, fp);
1158 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1159 shtree(lp->n, 0, NULL, fp);
1163 if (n->npipe.pipe_backgnd)
1169 fprintf(fp, "<node type %d>", n->type);
1177 showtree(union node *n)
1179 trace_puts("showtree called\n");
1180 shtree(n, 1, NULL, stderr);
1186 /* ============ Parser data */
1189 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1192 struct strlist *next;
1199 struct strpush *prev; /* preceding string on stack */
1201 int prev_left_in_line;
1202 #if ENABLE_ASH_ALIAS
1203 struct alias *ap; /* if push was associated with an alias */
1205 char *string; /* remember the string since it may change */
1207 /* Remember last two characters for pungetc. */
1210 /* Number of outstanding calls to pungetc. */
1215 struct parsefile *prev; /* preceding file on stack */
1216 int linno; /* current line */
1217 int pf_fd; /* file descriptor (or -1 if string) */
1218 int left_in_line; /* number of chars left in this line */
1219 int left_in_buffer; /* number of chars left in this buffer past the line */
1220 char *next_to_pgetc; /* next char in buffer */
1221 char *buf; /* input buffer */
1222 struct strpush *strpush; /* for pushing strings at this level */
1223 struct strpush basestrpush; /* so pushing one is fast */
1225 /* Remember last two characters for pungetc. */
1228 /* Number of outstanding calls to pungetc. */
1232 static struct parsefile basepf; /* top level input file */
1233 static struct parsefile *g_parsefile = &basepf; /* current input file */
1234 static int startlinno; /* line # where last token started */
1235 static char *commandname; /* currently executing command */
1236 static struct strlist *cmdenviron; /* environment for builtin command */
1239 /* ============ Message printing */
1242 ash_vmsg(const char *msg, va_list ap)
1244 fprintf(stderr, "%s: ", arg0);
1246 if (strcmp(arg0, commandname))
1247 fprintf(stderr, "%s: ", commandname);
1248 if (!iflag || g_parsefile->pf_fd > 0)
1249 fprintf(stderr, "line %d: ", startlinno);
1251 vfprintf(stderr, msg, ap);
1252 newline_and_flush(stderr);
1256 * Exverror is called to raise the error exception. If the second argument
1257 * is not NULL then error prints an error message using printf style
1258 * formatting. It then raises the error exception.
1260 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1262 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1266 TRACE(("ash_vmsg_and_raise(%d):", cond));
1269 TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
1274 flush_stdout_stderr();
1275 raise_exception(cond);
1279 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1281 ash_msg_and_raise_error(const char *msg, ...)
1286 ash_vmsg_and_raise(EXERROR, msg, ap);
1291 static void raise_error_syntax(const char *) NORETURN;
1293 raise_error_syntax(const char *msg)
1295 ash_msg_and_raise_error("syntax error: %s", msg);
1299 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1301 ash_msg_and_raise(int cond, const char *msg, ...)
1306 ash_vmsg_and_raise(cond, msg, ap);
1312 * error/warning routines for external builtins
1315 ash_msg(const char *fmt, ...)
1325 * Return a string describing an error. The returned string may be a
1326 * pointer to a static buffer that will be overwritten on the next call.
1327 * Action describes the operation that got the error.
1330 errmsg(int e, const char *em)
1332 if (e == ENOENT || e == ENOTDIR) {
1339 /* ============ Memory allocation */
1342 /* I consider these wrappers nearly useless:
1343 * ok, they return you to nearest exception handler, but
1344 * how much memory do you leak in the process, making
1345 * memory starvation worse?
1348 ckrealloc(void * p, size_t nbytes)
1350 p = realloc(p, nbytes);
1352 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1357 ckmalloc(size_t nbytes)
1359 return ckrealloc(NULL, nbytes);
1363 ckzalloc(size_t nbytes)
1365 return memset(ckmalloc(nbytes), 0, nbytes);
1369 ckstrdup(const char *s)
1371 char *p = strdup(s);
1373 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1377 /* Using bbox equivalents. They exit if out of memory */
1378 # define ckrealloc xrealloc
1379 # define ckmalloc xmalloc
1380 # define ckzalloc xzalloc
1381 # define ckstrdup xstrdup
1385 * It appears that grabstackstr() will barf with such alignments
1386 * because stalloc() will return a string allocated in a new stackblock.
1388 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1390 /* Most machines require the value returned from malloc to be aligned
1391 * in some way. The following macro will get this right
1392 * on many machines. */
1393 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1394 /* Minimum size of a block */
1395 MINSIZE = SHELL_ALIGN(504),
1398 struct stack_block {
1399 struct stack_block *prev;
1400 char space[MINSIZE];
1404 struct stack_block *stackp;
1410 struct globals_memstack {
1411 struct stack_block *g_stackp; // = &stackbase;
1412 char *g_stacknxt; // = stackbase.space;
1413 char *sstrend; // = stackbase.space + MINSIZE;
1414 size_t g_stacknleft; // = MINSIZE;
1415 struct stack_block stackbase;
1417 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1418 #define G_memstack (*ash_ptr_to_globals_memstack)
1419 #define g_stackp (G_memstack.g_stackp )
1420 #define g_stacknxt (G_memstack.g_stacknxt )
1421 #define sstrend (G_memstack.sstrend )
1422 #define g_stacknleft (G_memstack.g_stacknleft)
1423 #define stackbase (G_memstack.stackbase )
1424 #define INIT_G_memstack() do { \
1425 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1427 g_stackp = &stackbase; \
1428 g_stacknxt = stackbase.space; \
1429 g_stacknleft = MINSIZE; \
1430 sstrend = stackbase.space + MINSIZE; \
1434 #define stackblock() ((void *)g_stacknxt)
1435 #define stackblocksize() g_stacknleft
1438 * Parse trees for commands are allocated in lifo order, so we use a stack
1439 * to make this more efficient, and also to avoid all sorts of exception
1440 * handling code to handle interrupts in the middle of a parse.
1442 * The size 504 was chosen because the Ultrix malloc handles that size
1446 stalloc(size_t nbytes)
1451 aligned = SHELL_ALIGN(nbytes);
1452 if (aligned > g_stacknleft) {
1455 struct stack_block *sp;
1457 blocksize = aligned;
1458 if (blocksize < MINSIZE)
1459 blocksize = MINSIZE;
1460 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1461 if (len < blocksize)
1462 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1465 sp->prev = g_stackp;
1466 g_stacknxt = sp->space;
1467 g_stacknleft = blocksize;
1468 sstrend = g_stacknxt + blocksize;
1473 g_stacknxt += aligned;
1474 g_stacknleft -= aligned;
1479 stzalloc(size_t nbytes)
1481 return memset(stalloc(nbytes), 0, nbytes);
1488 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1489 write(STDERR_FILENO, "stunalloc\n", 10);
1493 g_stacknleft += g_stacknxt - (char *)p;
1498 * Like strdup but works with the ash stack.
1501 sstrdup(const char *p)
1503 size_t len = strlen(p) + 1;
1504 return memcpy(stalloc(len), p, len);
1508 grabstackblock(size_t len)
1514 pushstackmark(struct stackmark *mark, size_t len)
1516 mark->stackp = g_stackp;
1517 mark->stacknxt = g_stacknxt;
1518 mark->stacknleft = g_stacknleft;
1519 grabstackblock(len);
1523 setstackmark(struct stackmark *mark)
1525 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1529 popstackmark(struct stackmark *mark)
1531 struct stack_block *sp;
1537 while (g_stackp != mark->stackp) {
1539 g_stackp = sp->prev;
1542 g_stacknxt = mark->stacknxt;
1543 g_stacknleft = mark->stacknleft;
1544 sstrend = mark->stacknxt + mark->stacknleft;
1549 * When the parser reads in a string, it wants to stick the string on the
1550 * stack and only adjust the stack pointer when it knows how big the
1551 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1552 * of space on top of the stack and stackblocklen returns the length of
1553 * this block. Growstackblock will grow this space by at least one byte,
1554 * possibly moving it (like realloc). Grabstackblock actually allocates the
1555 * part of the block that has been used.
1558 growstackblock(void)
1562 newlen = g_stacknleft * 2;
1563 if (newlen < g_stacknleft)
1564 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1568 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1569 struct stack_block *sp;
1570 struct stack_block *prevstackp;
1575 prevstackp = sp->prev;
1576 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1577 sp = ckrealloc(sp, grosslen);
1578 sp->prev = prevstackp;
1580 g_stacknxt = sp->space;
1581 g_stacknleft = newlen;
1582 sstrend = sp->space + newlen;
1585 char *oldspace = g_stacknxt;
1586 size_t oldlen = g_stacknleft;
1587 char *p = stalloc(newlen);
1589 /* free the space we just allocated */
1590 g_stacknxt = memcpy(p, oldspace, oldlen);
1591 g_stacknleft += newlen;
1596 * The following routines are somewhat easier to use than the above.
1597 * The user declares a variable of type STACKSTR, which may be declared
1598 * to be a register. The macro STARTSTACKSTR initializes things. Then
1599 * the user uses the macro STPUTC to add characters to the string. In
1600 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1601 * grown as necessary. When the user is done, she can just leave the
1602 * string there and refer to it using stackblock(). Or she can allocate
1603 * the space for it using grabstackstr(). If it is necessary to allow
1604 * someone else to use the stack temporarily and then continue to grow
1605 * the string, the user should use grabstack to allocate the space, and
1606 * then call ungrabstr(p) to return to the previous mode of operation.
1608 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1609 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1610 * is space for at least one character.
1615 size_t len = stackblocksize();
1617 return (char *)stackblock() + len;
1621 * Called from CHECKSTRSPACE.
1624 makestrspace(size_t newlen, char *p)
1626 size_t len = p - g_stacknxt;
1632 size = stackblocksize();
1634 if (nleft >= newlen)
1638 return (char *)stackblock() + len;
1642 stack_nputstr(const char *s, size_t n, char *p)
1644 p = makestrspace(n, p);
1645 p = (char *)memcpy(p, s, n) + n;
1650 stack_putstr(const char *s, char *p)
1652 return stack_nputstr(s, strlen(s), p);
1656 _STPUTC(int c, char *p)
1664 #define STARTSTACKSTR(p) ((p) = stackblock())
1665 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1666 #define CHECKSTRSPACE(n, p) do { \
1669 size_t m = sstrend - q; \
1671 (p) = makestrspace(l, q); \
1673 #define USTPUTC(c, p) (*(p)++ = (c))
1674 #define STACKSTRNUL(p) do { \
1675 if ((p) == sstrend) \
1676 (p) = growstackstr(); \
1679 #define STUNPUTC(p) (--(p))
1680 #define STTOPC(p) ((p)[-1])
1681 #define STADJUST(amount, p) ((p) += (amount))
1683 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1684 #define ungrabstackstr(s, p) stunalloc(s)
1685 #define stackstrend() ((void *)sstrend)
1688 /* ============ String helpers */
1691 * prefix -- see if pfx is a prefix of string.
1694 prefix(const char *string, const char *pfx)
1697 if (*pfx++ != *string++)
1700 return (char *) string;
1704 * Check for a valid number. This should be elsewhere.
1707 is_number(const char *p)
1712 } while (*++p != '\0');
1717 * Convert a string of digits to an integer, printing an error message on
1721 number(const char *s)
1724 ash_msg_and_raise_error(msg_illnum, s);
1729 * Produce a possibly single quoted string suitable as input to the shell.
1730 * The return string is allocated on the stack.
1733 single_quote(const char *s)
1743 len = strchrnul(s, '\'') - s;
1745 q = p = makestrspace(len + 3, p);
1748 q = (char *)memcpy(q, s, len) + len;
1757 do len++; while (*++s == '\'');
1759 q = p = makestrspace(len + 3, p);
1762 q = (char *)memcpy(q, s - len, len) + len;
1770 return stackblock();
1774 /* ============ nextopt */
1776 static char **argptr; /* argument list for builtin commands */
1777 static char *optionarg; /* set by nextopt (like getopt) */
1778 static char *optptr; /* used by nextopt */
1781 * XXX - should get rid of. Have all builtins use getopt(3).
1782 * The library getopt must have the BSD extension static variable
1783 * "optreset", otherwise it can't be used within the shell safely.
1785 * Standard option processing (a la getopt) for builtin routines.
1786 * The only argument that is passed to nextopt is the option string;
1787 * the other arguments are unnecessary. It returns the character,
1788 * or '\0' on end of input.
1791 nextopt(const char *optstring)
1798 if (p == NULL || *p == '\0') {
1799 /* We ate entire "-param", take next one */
1805 if (*++p == '\0') /* just "-" ? */
1808 if (LONE_DASH(p)) /* "--" ? */
1810 /* p => next "-param" */
1812 /* p => some option char in the middle of a "-param" */
1814 for (q = optstring; *q != c;) {
1816 ash_msg_and_raise_error("illegal option -%c", c);
1824 ash_msg_and_raise_error("no arg for -%c option", c);
1834 /* ============ Shell variables */
1837 * The parsefile structure pointed to by the global variable parsefile
1838 * contains information about the current file being read.
1841 int nparam; /* # of positional parameters (without $0) */
1842 #if ENABLE_ASH_GETOPTS
1843 int optind; /* next parameter to be processed by getopts */
1844 int optoff; /* used by getopts */
1846 unsigned char malloced; /* if parameter list dynamically allocated */
1847 char **p; /* parameter list */
1851 * Free the list of positional parameters.
1854 freeparam(volatile struct shparam *param)
1856 if (param->malloced) {
1858 ap = ap1 = param->p;
1865 #if ENABLE_ASH_GETOPTS
1866 static void FAST_FUNC getoptsreset(const char *value);
1870 struct var *next; /* next entry in hash list */
1871 int flags; /* flags are defined above */
1872 const char *var_text; /* name=value */
1873 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1874 /* the variable gets set/unset */
1878 struct localvar *next; /* next local variable in list */
1879 struct var *vp; /* the variable that was made local */
1880 int flags; /* saved flags */
1881 const char *text; /* saved text */
1885 #define VEXPORT 0x01 /* variable is exported */
1886 #define VREADONLY 0x02 /* variable cannot be modified */
1887 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1888 #define VTEXTFIXED 0x08 /* text is statically allocated */
1889 #define VSTACK 0x10 /* text is allocated on the stack */
1890 #define VUNSET 0x20 /* the variable is not set */
1891 #define VNOFUNC 0x40 /* don't call the callback function */
1892 #define VNOSET 0x80 /* do not set variable - just readonly test */
1893 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1894 #if ENABLE_ASH_RANDOM_SUPPORT
1895 # define VDYNAMIC 0x200 /* dynamic variable */
1901 /* Need to be before varinit_data[] */
1902 #if ENABLE_LOCALE_SUPPORT
1903 static void FAST_FUNC
1904 change_lc_all(const char *value)
1906 if (value && *value != '\0')
1907 setlocale(LC_ALL, value);
1909 static void FAST_FUNC
1910 change_lc_ctype(const char *value)
1912 if (value && *value != '\0')
1913 setlocale(LC_CTYPE, value);
1917 static void chkmail(void);
1918 static void changemail(const char *var_value) FAST_FUNC;
1920 # define chkmail() ((void)0)
1922 static void changepath(const char *) FAST_FUNC;
1923 #if ENABLE_ASH_RANDOM_SUPPORT
1924 static void change_random(const char *) FAST_FUNC;
1927 static const struct {
1929 const char *var_text;
1930 void (*var_func)(const char *) FAST_FUNC;
1931 } varinit_data[] = {
1933 * Note: VEXPORT would not work correctly here for NOFORK applets:
1934 * some environment strings may be constant.
1936 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1938 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1939 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1941 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1942 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1943 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1944 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1945 #if ENABLE_ASH_GETOPTS
1946 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
1948 #if ENABLE_ASH_RANDOM_SUPPORT
1949 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1951 #if ENABLE_LOCALE_SUPPORT
1952 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1953 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1955 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1956 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1962 struct globals_var {
1963 struct shparam shellparam; /* $@ current positional parameters */
1964 struct redirtab *redirlist;
1965 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1966 struct var *vartab[VTABSIZE];
1967 struct var varinit[ARRAY_SIZE(varinit_data)];
1969 extern struct globals_var *const ash_ptr_to_globals_var;
1970 #define G_var (*ash_ptr_to_globals_var)
1971 #define shellparam (G_var.shellparam )
1972 //#define redirlist (G_var.redirlist )
1973 #define preverrout_fd (G_var.preverrout_fd)
1974 #define vartab (G_var.vartab )
1975 #define varinit (G_var.varinit )
1976 #define INIT_G_var() do { \
1978 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1980 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1981 varinit[i].flags = varinit_data[i].flags; \
1982 varinit[i].var_text = varinit_data[i].var_text; \
1983 varinit[i].var_func = varinit_data[i].var_func; \
1987 #define vifs varinit[0]
1989 # define vmail (&vifs)[1]
1990 # define vmpath (&vmail)[1]
1991 # define vpath (&vmpath)[1]
1993 # define vpath (&vifs)[1]
1995 #define vps1 (&vpath)[1]
1996 #define vps2 (&vps1)[1]
1997 #define vps4 (&vps2)[1]
1998 #if ENABLE_ASH_GETOPTS
1999 # define voptind (&vps4)[1]
2000 # if ENABLE_ASH_RANDOM_SUPPORT
2001 # define vrandom (&voptind)[1]
2004 # if ENABLE_ASH_RANDOM_SUPPORT
2005 # define vrandom (&vps4)[1]
2010 * The following macros access the values of the above variables.
2011 * They have to skip over the name. They return the null string
2012 * for unset variables.
2014 #define ifsval() (vifs.var_text + 4)
2015 #define ifsset() ((vifs.flags & VUNSET) == 0)
2017 # define mailval() (vmail.var_text + 5)
2018 # define mpathval() (vmpath.var_text + 9)
2019 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2021 #define pathval() (vpath.var_text + 5)
2022 #define ps1val() (vps1.var_text + 4)
2023 #define ps2val() (vps2.var_text + 4)
2024 #define ps4val() (vps4.var_text + 4)
2025 #if ENABLE_ASH_GETOPTS
2026 # define optindval() (voptind.var_text + 7)
2029 #if ENABLE_ASH_GETOPTS
2030 static void FAST_FUNC
2031 getoptsreset(const char *value)
2033 shellparam.optind = number(value) ?: 1;
2034 shellparam.optoff = -1;
2039 * Compares two strings up to the first = or '\0'. The first
2040 * string must be terminated by '='; the second may be terminated by
2041 * either '=' or '\0'.
2044 varcmp(const char *p, const char *q)
2048 while ((c = *p) == (d = *q)) {
2049 if (c == '\0' || c == '=')
2063 * Find the appropriate entry in the hash table from the name.
2065 static struct var **
2066 hashvar(const char *p)
2070 hashval = ((unsigned char) *p) << 4;
2071 while (*p && *p != '=')
2072 hashval += (unsigned char) *p++;
2073 return &vartab[hashval % VTABSIZE];
2077 vpcmp(const void *a, const void *b)
2079 return varcmp(*(const char **)a, *(const char **)b);
2083 * This routine initializes the builtin variables.
2093 * PS1 depends on uid
2095 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2096 vps1.var_text = "PS1=\\w \\$ ";
2099 vps1.var_text = "PS1=# ";
2102 end = vp + ARRAY_SIZE(varinit);
2104 vpp = hashvar(vp->var_text);
2107 } while (++vp < end);
2110 static struct var **
2111 findvar(struct var **vpp, const char *name)
2113 for (; *vpp; vpp = &(*vpp)->next) {
2114 if (varcmp((*vpp)->var_text, name) == 0) {
2122 * Find the value of a variable. Returns NULL if not set.
2124 static const char* FAST_FUNC
2125 lookupvar(const char *name)
2129 v = *findvar(hashvar(name), name);
2131 #if ENABLE_ASH_RANDOM_SUPPORT
2133 * Dynamic variables are implemented roughly the same way they are
2134 * in bash. Namely, they're "special" so long as they aren't unset.
2135 * As soon as they're unset, they're no longer dynamic, and dynamic
2136 * lookup will no longer happen at that point. -- PFM.
2138 if (v->flags & VDYNAMIC)
2141 if (!(v->flags & VUNSET))
2142 return var_end(v->var_text);
2148 reinit_unicode_for_ash(void)
2150 /* Unicode support should be activated even if LANG is set
2151 * _during_ shell execution, not only if it was set when
2152 * shell was started. Therefore, re-check LANG every time:
2154 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2155 || ENABLE_UNICODE_USING_LOCALE
2157 const char *s = lookupvar("LC_ALL");
2158 if (!s) s = lookupvar("LC_CTYPE");
2159 if (!s) s = lookupvar("LANG");
2165 * Search the environment of a builtin command.
2168 bltinlookup(const char *name)
2172 for (sp = cmdenviron; sp; sp = sp->next) {
2173 if (varcmp(sp->text, name) == 0)
2174 return var_end(sp->text);
2176 return lookupvar(name);
2180 * Same as setvar except that the variable and value are passed in
2181 * the first argument as name=value. Since the first argument will
2182 * be actually stored in the table, it should not be a string that
2184 * Called with interrupts off.
2187 setvareq(char *s, int flags)
2189 struct var *vp, **vpp;
2192 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2193 vp = *findvar(vpp, s);
2195 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2198 if (flags & VNOSAVE)
2202 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2208 if (vp->var_func && !(flags & VNOFUNC))
2209 vp->var_func(var_end(s));
2211 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2212 free((char*)vp->var_text);
2214 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2216 /* variable s is not found */
2219 vp = ckzalloc(sizeof(*vp));
2221 /*vp->func = NULL; - ckzalloc did it */
2224 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2231 * Set the value of a variable. The flags argument is ored with the
2232 * flags of the variable. If val is NULL, the variable is unset.
2235 setvar(const char *name, const char *val, int flags)
2243 q = endofname(name);
2244 p = strchrnul(q, '=');
2246 if (!namelen || p != q)
2247 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2252 vallen = strlen(val);
2256 nameeq = ckmalloc(namelen + vallen + 2);
2257 p = memcpy(nameeq, name, namelen) + namelen;
2260 p = memcpy(p, val, vallen) + vallen;
2263 setvareq(nameeq, flags | VNOSAVE);
2267 static void FAST_FUNC
2268 setvar0(const char *name, const char *val)
2270 setvar(name, val, 0);
2274 * Unset the specified variable.
2277 unsetvar(const char *s)
2283 vpp = findvar(hashvar(s), s);
2287 int flags = vp->flags;
2290 if (flags & VREADONLY)
2292 #if ENABLE_ASH_RANDOM_SUPPORT
2293 vp->flags &= ~VDYNAMIC;
2297 if ((flags & VSTRFIXED) == 0) {
2299 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2300 free((char*)vp->var_text);
2306 vp->flags &= ~VEXPORT;
2316 * Process a linked list of variable assignments.
2319 listsetvar(struct strlist *list_set_var, int flags)
2321 struct strlist *lp = list_set_var;
2327 setvareq(lp->text, flags);
2334 * Generate a list of variables satisfying the given conditions.
2337 listvars(int on, int off, char ***end)
2348 for (vp = *vpp; vp; vp = vp->next) {
2349 if ((vp->flags & mask) == on) {
2350 if (ep == stackstrend())
2351 ep = growstackstr();
2352 *ep++ = (char*)vp->var_text;
2355 } while (++vpp < vartab + VTABSIZE);
2356 if (ep == stackstrend())
2357 ep = growstackstr();
2361 return grabstackstr(ep);
2365 /* ============ Path search helper
2367 * The variable path (passed by reference) should be set to the start
2368 * of the path before the first call; path_advance will update
2369 * this value as it proceeds. Successive calls to path_advance will return
2370 * the possible path expansions in sequence. If an option (indicated by
2371 * a percent sign) appears in the path entry then the global variable
2372 * pathopt will be set to point to it; otherwise pathopt will be set to
2375 static const char *pathopt; /* set by path_advance */
2378 path_advance(const char **path, const char *name)
2388 for (p = start; *p && *p != ':' && *p != '%'; p++)
2390 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2391 while (stackblocksize() < len)
2395 memcpy(q, start, p - start);
2403 while (*p && *p != ':')
2410 return stalloc(len);
2414 /* ============ Prompt */
2416 static smallint doprompt; /* if set, prompt the user */
2417 static smallint needprompt; /* true if interactive and at start of line */
2419 #if ENABLE_FEATURE_EDITING
2420 static line_input_t *line_input_state;
2421 static const char *cmdedit_prompt;
2423 putprompt(const char *s)
2425 if (ENABLE_ASH_EXPAND_PRMT) {
2426 free((char*)cmdedit_prompt);
2427 cmdedit_prompt = ckstrdup(s);
2434 putprompt(const char *s)
2440 #if ENABLE_ASH_EXPAND_PRMT
2441 /* expandstr() needs parsing machinery, so it is far away ahead... */
2442 static const char *expandstr(const char *ps);
2444 #define expandstr(s) s
2448 setprompt_if(smallint do_set, int whichprompt)
2451 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2458 switch (whichprompt) {
2468 #if ENABLE_ASH_EXPAND_PRMT
2469 pushstackmark(&smark, stackblocksize());
2471 putprompt(expandstr(prompt));
2472 #if ENABLE_ASH_EXPAND_PRMT
2473 popstackmark(&smark);
2478 /* ============ The cd and pwd commands */
2480 #define CD_PHYSICAL 1
2490 while ((i = nextopt("LP")) != '\0') {
2492 flags ^= CD_PHYSICAL;
2501 * Update curdir (the name of the current directory) in response to a
2505 updatepwd(const char *dir)
2512 cdcomppath = sstrdup(dir);
2515 if (curdir == nullstr)
2517 new = stack_putstr(curdir, new);
2519 new = makestrspace(strlen(dir) + 2, new);
2520 lim = (char *)stackblock() + 1;
2524 if (new > lim && *lim == '/')
2529 if (dir[1] == '/' && dir[2] != '/') {
2535 p = strtok(cdcomppath, "/");
2539 if (p[1] == '.' && p[2] == '\0') {
2551 new = stack_putstr(p, new);
2554 p = strtok(NULL, "/");
2559 return stackblock();
2563 * Find out what the current directory is. If we already know the current
2564 * directory, this routine returns immediately.
2569 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2570 return dir ? dir : nullstr;
2574 setpwd(const char *val, int setold)
2578 oldcur = dir = curdir;
2581 setvar("OLDPWD", oldcur, VEXPORT);
2584 if (physdir != nullstr) {
2585 if (physdir != oldcur)
2589 if (oldcur == val || !val) {
2595 dir = ckstrdup(val);
2596 if (oldcur != dir && oldcur != nullstr) {
2601 setvar("PWD", dir, VEXPORT);
2604 static void hashcd(void);
2607 * Actually do the chdir. We also call hashcd to let other routines
2608 * know that the current directory has changed.
2611 docd(const char *dest, int flags)
2613 const char *dir = NULL;
2616 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2619 if (!(flags & CD_PHYSICAL)) {
2620 dir = updatepwd(dest);
2634 static int FAST_FUNC
2635 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2647 dest = bltinlookup("HOME");
2648 else if (LONE_DASH(dest)) {
2649 dest = bltinlookup("OLDPWD");
2671 path = bltinlookup("CDPATH");
2674 p = path_advance(&path, dest);
2675 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2679 if (!docd(p, flags))
2690 ash_msg_and_raise_error("can't cd to %s", dest);
2693 if (flags & CD_PRINT)
2694 out1fmt("%s\n", curdir);
2698 static int FAST_FUNC
2699 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2702 const char *dir = curdir;
2706 if (physdir == nullstr)
2710 out1fmt("%s\n", dir);
2715 /* ============ ... */
2718 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2720 /* Syntax classes */
2721 #define CWORD 0 /* character is nothing special */
2722 #define CNL 1 /* newline character */
2723 #define CBACK 2 /* a backslash character */
2724 #define CSQUOTE 3 /* single quote */
2725 #define CDQUOTE 4 /* double quote */
2726 #define CENDQUOTE 5 /* a terminating quote */
2727 #define CBQUOTE 6 /* backwards single quote */
2728 #define CVAR 7 /* a dollar sign */
2729 #define CENDVAR 8 /* a '}' character */
2730 #define CLP 9 /* a left paren in arithmetic */
2731 #define CRP 10 /* a right paren in arithmetic */
2732 #define CENDFILE 11 /* end of file */
2733 #define CCTL 12 /* like CWORD, except it must be escaped */
2734 #define CSPCL 13 /* these terminate a word */
2735 #define CIGN 14 /* character should be ignored */
2738 #if ENABLE_ASH_ALIAS
2742 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2744 #if ENABLE_SH_MATH_SUPPORT
2745 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2747 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2749 static const uint16_t S_I_T[] ALIGN2 = {
2750 #if ENABLE_ASH_ALIAS
2751 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2753 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2754 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2755 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2756 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2757 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2758 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2759 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2760 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2761 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2762 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2763 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2764 #if !USE_SIT_FUNCTION
2765 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2766 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2767 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2771 /* Constants below must match table above */
2773 #if ENABLE_ASH_ALIAS
2774 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2776 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2777 CNL_CNL_CNL_CNL , /* 2 */
2778 CWORD_CCTL_CCTL_CWORD , /* 3 */
2779 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2780 CVAR_CVAR_CWORD_CVAR , /* 5 */
2781 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2782 CSPCL_CWORD_CWORD_CLP , /* 7 */
2783 CSPCL_CWORD_CWORD_CRP , /* 8 */
2784 CBACK_CBACK_CCTL_CBACK , /* 9 */
2785 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2786 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2787 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2788 CWORD_CWORD_CWORD_CWORD , /* 13 */
2789 CCTL_CCTL_CCTL_CCTL , /* 14 */
2792 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2793 * caller must ensure proper cast on it if c is *char_ptr!
2795 /* Values for syntax param */
2796 #define BASESYNTAX 0 /* not in quotes */
2797 #define DQSYNTAX 1 /* in double quotes */
2798 #define SQSYNTAX 2 /* in single quotes */
2799 #define ARISYNTAX 3 /* in arithmetic */
2800 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2802 #if USE_SIT_FUNCTION
2805 SIT(int c, int syntax)
2807 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2808 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2810 * This causes '/' to be prepended with CTLESC in dquoted string,
2811 * making "./file"* treated incorrectly because we feed
2812 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2813 * The "homegrown" glob implementation is okay with that,
2814 * but glibc one isn't. With '/' always treated as CWORD,
2817 # if ENABLE_ASH_ALIAS
2818 static const uint8_t syntax_index_table[] ALIGN1 = {
2819 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2820 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2821 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2825 static const uint8_t syntax_index_table[] ALIGN1 = {
2826 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2827 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2828 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2837 # if ENABLE_ASH_ALIAS
2843 /* Cast is purely for paranoia here,
2844 * just in case someone passed signed char to us */
2845 if ((unsigned char)c >= CTL_FIRST
2846 && (unsigned char)c <= CTL_LAST
2850 s = strchrnul(spec_symbls, c);
2853 indx = syntax_index_table[s - spec_symbls];
2855 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2858 #else /* !USE_SIT_FUNCTION */
2860 static const uint8_t syntax_index_table[] ALIGN1 = {
2861 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2862 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2872 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2873 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2895 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2896 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2897 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2898 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2899 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2900 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2901 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2902 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2903 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2904 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2905 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2906 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2907 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2908 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2909 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2910 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2911 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2912 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2913 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2916 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2918 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2922 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2923 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2924 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2925 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2926 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2927 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2955 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2956 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2957 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2960 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2988 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2989 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2990 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2991 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2992 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2993 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2994 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2995 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2996 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2997 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2998 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2999 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3000 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3001 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3002 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3119 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3120 # if ENABLE_ASH_ALIAS
3121 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3126 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3127 #else /* debug version, caught one signed char bug */
3128 # define SIT(c, syntax) \
3130 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3131 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3132 if ((syntax) < 0 || (syntax) > (2 + ENABLE_SH_MATH_SUPPORT)) \
3133 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3134 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3138 #endif /* !USE_SIT_FUNCTION */
3141 /* ============ Alias handling */
3143 #if ENABLE_ASH_ALIAS
3145 #define ALIASINUSE 1
3156 static struct alias **atab; // [ATABSIZE];
3157 #define INIT_G_alias() do { \
3158 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3162 static struct alias **
3163 __lookupalias(const char *name)
3165 unsigned int hashval;
3172 ch = (unsigned char)*p;
3176 ch = (unsigned char)*++p;
3178 app = &atab[hashval % ATABSIZE];
3180 for (; *app; app = &(*app)->next) {
3181 if (strcmp(name, (*app)->name) == 0) {
3189 static struct alias *
3190 lookupalias(const char *name, int check)
3192 struct alias *ap = *__lookupalias(name);
3194 if (check && ap && (ap->flag & ALIASINUSE))
3199 static struct alias *
3200 freealias(struct alias *ap)
3204 if (ap->flag & ALIASINUSE) {
3205 ap->flag |= ALIASDEAD;
3217 setalias(const char *name, const char *val)
3219 struct alias *ap, **app;
3221 app = __lookupalias(name);
3225 if (!(ap->flag & ALIASINUSE)) {
3228 ap->val = ckstrdup(val);
3229 ap->flag &= ~ALIASDEAD;
3232 ap = ckzalloc(sizeof(struct alias));
3233 ap->name = ckstrdup(name);
3234 ap->val = ckstrdup(val);
3235 /*ap->flag = 0; - ckzalloc did it */
3236 /*ap->next = NULL;*/
3243 unalias(const char *name)
3247 app = __lookupalias(name);
3251 *app = freealias(*app);
3262 struct alias *ap, **app;
3266 for (i = 0; i < ATABSIZE; i++) {
3268 for (ap = *app; ap; ap = *app) {
3269 *app = freealias(*app);
3279 printalias(const struct alias *ap)
3281 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3285 * TODO - sort output
3287 static int FAST_FUNC
3288 aliascmd(int argc UNUSED_PARAM, char **argv)
3297 for (i = 0; i < ATABSIZE; i++) {
3298 for (ap = atab[i]; ap; ap = ap->next) {
3304 while ((n = *++argv) != NULL) {
3305 v = strchr(n+1, '=');
3306 if (v == NULL) { /* n+1: funny ksh stuff */
3307 ap = *__lookupalias(n);
3309 fprintf(stderr, "%s: %s not found\n", "alias", n);
3322 static int FAST_FUNC
3323 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3327 while ((i = nextopt("a")) != '\0') {
3333 for (i = 0; *argptr; argptr++) {
3334 if (unalias(*argptr)) {
3335 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3343 #endif /* ASH_ALIAS */
3346 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3349 #define FORK_NOJOB 2
3351 /* mode flags for showjob(s) */
3352 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3353 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3354 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3355 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3358 * A job structure contains information about a job. A job is either a
3359 * single process or a set of processes contained in a pipeline. In the
3360 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3364 pid_t ps_pid; /* process id */
3365 int ps_status; /* last process status from wait() */
3366 char *ps_cmd; /* text of command being run */
3370 struct procstat ps0; /* status of process */
3371 struct procstat *ps; /* status or processes when more than one */
3373 int stopstatus; /* status of a stopped job */
3376 nprocs: 16, /* number of processes */
3378 #define JOBRUNNING 0 /* at least one proc running */
3379 #define JOBSTOPPED 1 /* all procs are stopped */
3380 #define JOBDONE 2 /* all procs are completed */
3382 sigint: 1, /* job was killed by SIGINT */
3383 jobctl: 1, /* job running under job control */
3385 waited: 1, /* true if this entry has been waited for */
3386 used: 1, /* true if this entry is in used */
3387 changed: 1; /* true if status has changed */
3388 struct job *prev_job; /* previous job */
3391 static struct job *makejob(/*union node *,*/ int);
3392 static int forkshell(struct job *, union node *, int);
3393 static int waitforjob(struct job *);
3396 enum { doing_jobctl = 0 };
3397 #define setjobctl(on) do {} while (0)
3399 static smallint doing_jobctl; //references:8
3400 static void setjobctl(int);
3407 ignoresig(int signo)
3409 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3410 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3411 /* No, need to do it */
3412 signal(signo, SIG_IGN);
3414 sigmode[signo - 1] = S_HARD_IGN;
3418 * Only one usage site - in setsignal()
3421 signal_handler(int signo)
3423 if (signo == SIGCHLD) {
3429 gotsig[signo - 1] = 1;
3430 pending_sig = signo;
3432 if (signo == SIGINT && !trap[SIGINT]) {
3433 if (!suppress_int) {
3435 raise_interrupt(); /* does not return */
3442 * Set the signal handler for the specified signal. The routine figures
3443 * out what it should be set to.
3446 setsignal(int signo)
3449 char cur_act, new_act;
3450 struct sigaction act;
3454 if (t != NULL) { /* trap for this sig is set */
3456 if (t[0] == '\0') /* trap is "": ignore this sig */
3460 if (rootshell && new_act == S_DFL) {
3463 if (iflag || minusc || sflag == 0)
3472 * "In all cases, bash ignores SIGQUIT. Non-builtin
3473 * commands run by bash have signal handlers
3474 * set to the values inherited by the shell
3475 * from its parent". */
3491 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3492 //whereas we have to restore it to what shell got on entry
3493 //from the parent. See comment above
3495 if (signo == SIGCHLD)
3498 t = &sigmode[signo - 1];
3501 /* current setting is not yet known */
3502 if (sigaction(signo, NULL, &act)) {
3503 /* pretend it worked; maybe we should give a warning,
3504 * but other shells don't. We don't alter sigmode,
3505 * so we retry every time.
3506 * btw, in Linux it never fails. --vda */
3509 if (act.sa_handler == SIG_IGN) {
3510 cur_act = S_HARD_IGN;
3512 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3514 cur_act = S_IGN; /* don't hard ignore these */
3518 if (cur_act == S_HARD_IGN || cur_act == new_act)
3521 act.sa_handler = SIG_DFL;
3524 act.sa_handler = signal_handler;
3527 act.sa_handler = SIG_IGN;
3531 /* flags and mask matter only if !DFL and !IGN, but we do it
3532 * for all cases for more deterministic behavior:
3535 sigfillset(&act.sa_mask);
3537 sigaction_set(signo, &act);
3542 /* mode flags for set_curjob */
3543 #define CUR_DELETE 2
3544 #define CUR_RUNNING 1
3545 #define CUR_STOPPED 0
3548 /* pgrp of shell on invocation */
3549 static int initialpgrp; //references:2
3550 static int ttyfd = -1; //5
3553 static struct job *jobtab; //5
3555 static unsigned njobs; //4
3557 static struct job *curjob; //lots
3558 /* number of presumed living untracked jobs */
3559 static int jobless; //4
3562 set_curjob(struct job *jp, unsigned mode)
3565 struct job **jpp, **curp;
3567 /* first remove from list */
3568 jpp = curp = &curjob;
3573 jpp = &jp1->prev_job;
3575 *jpp = jp1->prev_job;
3577 /* Then re-insert in correct position */
3585 /* job being deleted */
3588 /* newly created job or backgrounded job,
3589 * put after all stopped jobs.
3594 if (!jp1 || jp1->state != JOBSTOPPED)
3597 jpp = &jp1->prev_job;
3603 /* newly stopped job - becomes curjob */
3604 jp->prev_job = *jpp;
3612 jobno(const struct job *jp)
3614 return jp - jobtab + 1;
3619 * Convert a job name to a job structure.
3622 #define getjob(name, getctl) getjob(name)
3625 getjob(const char *name, int getctl)
3629 const char *err_msg = "%s: no such job";
3633 char *(*match)(const char *, const char *);
3648 if (c == '+' || c == '%') {
3650 err_msg = "No current job";
3656 err_msg = "No previous job";
3666 if (num > 0 && num <= njobs) {
3667 jp = jobtab + num - 1;
3682 if (match(jp->ps[0].ps_cmd, p)) {
3686 err_msg = "%s: ambiguous";
3696 err_msg = "job %s not created under job control";
3697 if (getctl && jp->jobctl == 0)
3702 ash_msg_and_raise_error(err_msg, name);
3706 * Mark a job structure as unused.
3709 freejob(struct job *jp)
3711 struct procstat *ps;
3715 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3716 if (ps->ps_cmd != nullstr)
3719 if (jp->ps != &jp->ps0)
3722 set_curjob(jp, CUR_DELETE);
3728 xtcsetpgrp(int fd, pid_t pgrp)
3730 if (tcsetpgrp(fd, pgrp))
3731 ash_msg_and_raise_error("can't set tty process group (%m)");
3735 * Turn job control on and off.
3737 * Note: This code assumes that the third arg to ioctl is a character
3738 * pointer, which is true on Berkeley systems but not System V. Since
3739 * System V doesn't have job control yet, this isn't a problem now.
3741 * Called with interrupts off.
3749 if (on == doing_jobctl || rootshell == 0)
3753 ofd = fd = open(_PATH_TTY, O_RDWR);
3755 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3756 * That sometimes helps to acquire controlling tty.
3757 * Obviously, a workaround for bugs when someone
3758 * failed to provide a controlling tty to bash! :) */
3764 /* fd is a tty at this point */
3765 fd = fcntl(fd, F_DUPFD, 10);
3766 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, dont */
3769 goto out; /* F_DUPFD failed */
3770 close_on_exec_on(fd);
3771 while (1) { /* while we are in the background */
3772 pgrp = tcgetpgrp(fd);
3775 ash_msg("can't access tty; job control turned off");
3779 if (pgrp == getpgrp())
3790 xtcsetpgrp(fd, pgrp);
3792 /* turning job control off */
3795 /* was xtcsetpgrp, but this can make exiting ash
3796 * loop forever if pty is already deleted */
3797 tcsetpgrp(fd, pgrp);
3811 static int FAST_FUNC
3812 killcmd(int argc, char **argv)
3814 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3817 if (argv[i][0] == '%') {
3819 * "kill %N" - job kill
3820 * Converting to pgrp / pid kill
3826 jp = getjob(argv[i], 0);
3828 * In jobs started under job control, we signal
3829 * entire process group by kill -PGRP_ID.
3830 * This happens, f.e., in interactive shell.
3832 * Otherwise, we signal each child via
3833 * kill PID1 PID2 PID3.
3835 * sh -c 'sleep 1|sleep 1 & kill %1'
3836 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3837 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3839 n = jp->nprocs; /* can't be 0 (I hope) */
3842 dst = alloca(n * sizeof(int)*4);
3844 for (j = 0; j < n; j++) {
3845 struct procstat *ps = &jp->ps[j];
3846 /* Skip non-running and not-stopped members
3847 * (i.e. dead members) of the job
3849 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3852 * kill_main has matching code to expect
3853 * leading space. Needed to not confuse
3854 * negative pids with "kill -SIGNAL_NO" syntax
3856 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3860 } while (argv[++i]);
3862 return kill_main(argc, argv);
3866 showpipe(struct job *jp /*, FILE *out*/)
3868 struct procstat *ps;
3869 struct procstat *psend;
3871 psend = jp->ps + jp->nprocs;
3872 for (ps = jp->ps + 1; ps < psend; ps++)
3873 printf(" | %s", ps->ps_cmd);
3874 newline_and_flush(stdout);
3875 flush_stdout_stderr();
3880 restartjob(struct job *jp, int mode)
3882 struct procstat *ps;
3888 if (jp->state == JOBDONE)
3890 jp->state = JOBRUNNING;
3891 pgid = jp->ps[0].ps_pid;
3892 if (mode == FORK_FG)
3893 xtcsetpgrp(ttyfd, pgid);
3894 killpg(pgid, SIGCONT);
3898 if (WIFSTOPPED(ps->ps_status)) {
3904 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3909 static int FAST_FUNC
3910 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3916 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3920 jp = getjob(*argv, 1);
3921 if (mode == FORK_BG) {
3922 set_curjob(jp, CUR_RUNNING);
3923 printf("[%d] ", jobno(jp));
3925 out1str(jp->ps[0].ps_cmd);
3926 showpipe(jp /*, stdout*/);
3927 retval = restartjob(jp, mode);
3928 } while (*argv && *++argv);
3934 sprint_status48(char *s, int status, int sigonly)
3940 if (!WIFEXITED(status)) {
3941 if (JOBS && WIFSTOPPED(status))
3942 st = WSTOPSIG(status);
3944 st = WTERMSIG(status);
3946 if (st == SIGINT || st == SIGPIPE)
3948 if (JOBS && WIFSTOPPED(status))
3952 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3953 col = fmtstr(s, 32, strsignal(st));
3954 if (WCOREDUMP(status)) {
3955 strcpy(s + col, " (core dumped)");
3956 col += sizeof(" (core dumped)")-1;
3958 } else if (!sigonly) {
3959 st = WEXITSTATUS(status);
3960 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
3967 wait_block_or_sig(int *status)
3974 /* Poll all children for changes in their state */
3976 /* if job control is active, accept stopped processes too */
3977 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
3979 break; /* Error (e.g. EINTR, ECHILD) or pid */
3981 /* Children exist, but none are ready. Sleep until interesting signal */
3984 sigprocmask(SIG_SETMASK, &mask, &mask);
3985 while (!got_sigchld && !pending_sig)
3987 sigprocmask(SIG_SETMASK, &mask, NULL);
3988 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
3989 while (!got_sigchld && !pending_sig)
3993 /* If it was SIGCHLD, poll children again */
3994 } while (got_sigchld);
3999 #define DOWAIT_NONBLOCK 0
4000 #define DOWAIT_BLOCK 1
4001 #define DOWAIT_BLOCK_OR_SIG 2
4004 dowait(int block, struct job *job)
4009 struct job *thisjob = NULL;
4011 TRACE(("dowait(0x%x) called\n", block));
4013 /* It's wrong to call waitpid() outside of INT_OFF region:
4014 * signal can arrive just after syscall return and handler can
4015 * longjmp away, losing stop/exit notification processing.
4016 * Thus, for "jobs" builtin, and for waiting for a fg job,
4017 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4019 * However, for "wait" builtin it is wrong to simply call waitpid()
4020 * in INT_OFF region: "wait" needs to wait for any running job
4021 * to change state, but should exit on any trap too.
4022 * In INT_OFF region, a signal just before syscall entry can set
4023 * pending_sig variables, but we can't check them, and we would
4024 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4026 * Because of this, we run inside INT_OFF, but use a special routine
4027 * which combines waitpid() and sigsuspend().
4028 * This is the reason why we need to have a handler for SIGCHLD:
4029 * SIG_DFL handler does not wake sigsuspend().
4032 if (block == DOWAIT_BLOCK_OR_SIG) {
4033 pid = wait_block_or_sig(&status);
4036 if (block == DOWAIT_NONBLOCK)
4037 wait_flags = WNOHANG;
4038 /* if job control is active, accept stopped processes too */
4040 wait_flags |= WUNTRACED;
4041 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4042 pid = waitpid(-1, &status, wait_flags);
4044 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4045 pid, status, errno, strerror(errno)));
4050 for (jp = curjob; jp; jp = jp->prev_job) {
4052 struct procstat *ps;
4053 struct procstat *psend;
4054 if (jp->state == JOBDONE)
4058 psend = ps + jp->nprocs;
4060 if (ps->ps_pid == pid) {
4061 TRACE(("Job %d: changing status of proc %d "
4062 "from 0x%x to 0x%x\n",
4063 jobno(jp), pid, ps->ps_status, status));
4064 ps->ps_status = status;
4067 if (ps->ps_status == -1)
4068 jobstate = JOBRUNNING;
4070 if (jobstate == JOBRUNNING)
4072 if (WIFSTOPPED(ps->ps_status)) {
4073 jp->stopstatus = ps->ps_status;
4074 jobstate = JOBSTOPPED;
4077 } while (++ps < psend);
4081 /* Found the job where one of its processes changed its state.
4082 * Is there at least one live and running process in this job? */
4083 if (jobstate != JOBRUNNING) {
4084 /* No. All live processes in the job are stopped
4085 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4087 thisjob->changed = 1;
4088 if (thisjob->state != jobstate) {
4089 TRACE(("Job %d: changing state from %d to %d\n",
4090 jobno(thisjob), thisjob->state, jobstate));
4091 thisjob->state = jobstate;
4093 if (jobstate == JOBSTOPPED)
4094 set_curjob(thisjob, CUR_STOPPED);
4100 /* The process wasn't found in job list */
4101 if (JOBS && !WIFSTOPPED(status))
4106 if (thisjob && thisjob == job) {
4110 len = sprint_status48(s, status, 1);
4122 showjob(struct job *jp, int mode)
4124 struct procstat *ps;
4125 struct procstat *psend;
4128 char s[16 + 16 + 48];
4129 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4133 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4134 /* just output process (group) id of pipeline */
4135 fprintf(out, "%d\n", ps->ps_pid);
4139 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4144 else if (curjob && jp == curjob->prev_job)
4147 if (mode & SHOW_PIDS)
4148 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4150 psend = ps + jp->nprocs;
4152 if (jp->state == JOBRUNNING) {
4153 strcpy(s + col, "Running");
4154 col += sizeof("Running") - 1;
4156 int status = psend[-1].ps_status;
4157 if (jp->state == JOBSTOPPED)
4158 status = jp->stopstatus;
4159 col += sprint_status48(s + col, status, 0);
4161 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4163 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4164 * or prints several "PID | <cmdN>" lines,
4165 * depending on SHOW_PIDS bit.
4166 * We do not print status of individual processes
4167 * between PID and <cmdN>. bash does it, but not very well:
4168 * first line shows overall job status, not process status,
4169 * making it impossible to know 1st process status.
4173 /* for each process */
4176 if (mode & SHOW_PIDS)
4177 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4179 fprintf(out, "%s%*c%s%s",
4181 33 - col >= 0 ? 33 - col : 0, ' ',
4182 ps == jp->ps ? "" : "| ",
4185 } while (++ps != psend);
4186 newline_and_flush(out);
4190 if (jp->state == JOBDONE) {
4191 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4197 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4198 * statuses have changed since the last call to showjobs.
4205 TRACE(("showjobs(0x%x) called\n", mode));
4207 /* Handle all finished jobs */
4208 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4211 for (jp = curjob; jp; jp = jp->prev_job) {
4212 if (!(mode & SHOW_CHANGED) || jp->changed) {
4218 static int FAST_FUNC
4219 jobscmd(int argc UNUSED_PARAM, char **argv)
4224 while ((m = nextopt("lp")) != '\0') {
4228 mode |= SHOW_ONLY_PGID;
4234 showjob(getjob(*argv, 0), mode);
4244 /* Called only on finished or stopped jobs (no members are running) */
4246 getstatus(struct job *job)
4250 struct procstat *ps;
4252 /* Fetch last member's status */
4253 ps = job->ps + job->nprocs - 1;
4254 status = ps->ps_status;
4256 /* "set -o pipefail" mode: use last _nonzero_ status */
4257 while (status == 0 && --ps >= job->ps)
4258 status = ps->ps_status;
4261 retval = WEXITSTATUS(status);
4262 if (!WIFEXITED(status)) {
4264 retval = WSTOPSIG(status);
4265 if (!WIFSTOPPED(status))
4268 /* XXX: limits number of signals */
4269 retval = WTERMSIG(status);
4271 if (retval == SIGINT)
4277 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4278 jobno(job), job->nprocs, status, retval));
4282 static int FAST_FUNC
4283 waitcmd(int argc UNUSED_PARAM, char **argv)
4294 /* wait for all jobs */
4298 if (!jp) /* no running procs */
4300 if (jp->state == JOBRUNNING)
4306 * "When bash is waiting for an asynchronous command via
4307 * the wait builtin, the reception of a signal for which a trap
4308 * has been set will cause the wait builtin to return immediately
4309 * with an exit status greater than 128, immediately after which
4310 * the trap is executed."
4312 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4313 /* if child sends us a signal *and immediately exits*,
4314 * dowait() returns pid > 0. Check this case,
4315 * not "if (dowait() < 0)"!
4324 if (**argv != '%') {
4325 pid_t pid = number(*argv);
4330 if (job->ps[job->nprocs - 1].ps_pid == pid)
4332 job = job->prev_job;
4335 job = getjob(*argv, 0);
4337 /* loop until process terminated or stopped */
4338 while (job->state == JOBRUNNING) {
4339 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4344 retval = getstatus(job);
4351 retval = 128 + pending_sig;
4360 struct job *jp, *jq;
4362 len = njobs * sizeof(*jp);
4364 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4366 offset = (char *)jp - (char *)jq;
4368 /* Relocate pointers */
4371 jq = (struct job *)((char *)jq + l);
4375 #define joff(p) ((struct job *)((char *)(p) + l))
4376 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4377 if (joff(jp)->ps == &jq->ps0)
4378 jmove(joff(jp)->ps);
4379 if (joff(jp)->prev_job)
4380 jmove(joff(jp)->prev_job);
4390 jp = (struct job *)((char *)jp + len);
4394 } while (--jq >= jp);
4399 * Return a new job structure.
4400 * Called with interrupts off.
4403 makejob(/*union node *node,*/ int nprocs)
4408 for (i = njobs, jp = jobtab; ; jp++) {
4415 if (jp->state != JOBDONE || !jp->waited)
4424 memset(jp, 0, sizeof(*jp));
4426 /* jp->jobctl is a bitfield.
4427 * "jp->jobctl |= jobctl" likely to give awful code */
4431 jp->prev_job = curjob;
4436 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4438 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4445 * Return a string identifying a command (to be printed by the
4448 static char *cmdnextc;
4451 cmdputs(const char *s)
4453 static const char vstype[VSTYPE + 1][3] = {
4454 "", "}", "-", "+", "?", "=",
4455 "%", "%%", "#", "##"
4456 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4459 const char *p, *str;
4463 unsigned char subtype = 0;
4467 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4469 while ((c = *p++) != '\0') {
4477 if ((subtype & VSTYPE) == VSLENGTH)
4483 str = "\"}" + !(quoted & 1);
4490 #if ENABLE_SH_MATH_SUPPORT
4505 if ((subtype & VSTYPE) != VSNORMAL)
4507 str = vstype[subtype & VSTYPE];
4508 if (subtype & VSNUL)
4517 /* These can only happen inside quotes */
4530 while ((c = *str++) != '\0') {
4533 } /* while *p++ not NUL */
4536 USTPUTC('"', nextc);
4542 /* cmdtxt() and cmdlist() call each other */
4543 static void cmdtxt(union node *n);
4546 cmdlist(union node *np, int sep)
4548 for (; np; np = np->narg.next) {
4552 if (sep && np->narg.next)
4558 cmdtxt(union node *n)
4561 struct nodelist *lp;
4572 lp = n->npipe.cmdlist;
4590 cmdtxt(n->nbinary.ch1);
4606 cmdtxt(n->nif.test);
4608 if (n->nif.elsepart) {
4609 cmdtxt(n->nif.ifpart);
4611 n = n->nif.elsepart;
4629 cmdtxt(n->nbinary.ch1);
4639 cmdputs(n->nfor.var);
4641 cmdlist(n->nfor.args, 1);
4646 cmdputs(n->narg.text);
4650 cmdlist(n->ncmd.args, 1);
4651 cmdlist(n->ncmd.redirect, 0);
4664 cmdputs(n->ncase.expr->narg.text);
4666 for (np = n->ncase.cases; np; np = np->nclist.next) {
4667 cmdtxt(np->nclist.pattern);
4669 cmdtxt(np->nclist.body);
4683 #if ENABLE_ASH_BASH_COMPAT
4698 cmdputs(utoa(n->nfile.fd));
4700 if (n->type == NTOFD || n->type == NFROMFD) {
4701 cmdputs(utoa(n->ndup.dupfd));
4710 commandtext(union node *n)
4714 STARTSTACKSTR(cmdnextc);
4716 name = stackblock();
4717 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4718 return ckstrdup(name);
4723 * Fork off a subshell. If we are doing job control, give the subshell its
4724 * own process group. Jp is a job structure that the job is to be added to.
4725 * N is the command that will be evaluated by the child. Both jp and n may
4726 * be NULL. The mode parameter can be one of the following:
4727 * FORK_FG - Fork off a foreground process.
4728 * FORK_BG - Fork off a background process.
4729 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4730 * process group even if job control is on.
4732 * When job control is turned off, background processes have their standard
4733 * input redirected to /dev/null (except for the second and later processes
4736 * Called with interrupts off.
4739 * Clear traps on a fork.
4747 for (tp = trap; tp < &trap[NSIG]; tp++) {
4748 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4749 if (trap_ptr == trap)
4751 /* else: it "belongs" to trap_ptr vector, don't free */
4753 if ((tp - trap) != 0)
4754 setsignal(tp - trap);
4761 /* Lives far away from here, needed for forkchild */
4762 static void closescript(void);
4764 /* Called after fork(), in child */
4765 /* jp and n are NULL when called by openhere() for heredoc support */
4766 static NOINLINE void
4767 forkchild(struct job *jp, union node *n, int mode)
4771 TRACE(("Child shell %d\n", getpid()));
4775 /* man bash: "Non-builtin commands run by bash have signal handlers
4776 * set to the values inherited by the shell from its parent".
4777 * Do we do it correctly? */
4781 if (mode == FORK_NOJOB /* is it `xxx` ? */
4782 && n && n->type == NCMD /* is it single cmd? */
4783 /* && n->ncmd.args->type == NARG - always true? */
4784 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4785 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4786 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4788 TRACE(("Trap hack\n"));
4789 /* Awful hack for `trap` or $(trap).
4791 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4792 * contains an example where "trap" is executed in a subshell:
4794 * save_traps=$(trap)
4796 * eval "$save_traps"
4798 * Standard does not say that "trap" in subshell shall print
4799 * parent shell's traps. It only says that its output
4800 * must have suitable form, but then, in the above example
4801 * (which is not supposed to be normative), it implies that.
4803 * bash (and probably other shell) does implement it
4804 * (traps are reset to defaults, but "trap" still shows them),
4805 * but as a result, "trap" logic is hopelessly messed up:
4808 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4809 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4810 * # true | trap <--- trap is in subshell - no output (ditto)
4811 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4812 * trap -- 'echo Ho' SIGWINCH
4813 * # echo `(trap)` <--- in subshell in subshell - output
4814 * trap -- 'echo Ho' SIGWINCH
4815 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4816 * trap -- 'echo Ho' SIGWINCH
4818 * The rules when to forget and when to not forget traps
4819 * get really complex and nonsensical.
4821 * Our solution: ONLY bare $(trap) or `trap` is special.
4823 /* Save trap handler strings for trap builtin to print */
4824 trap_ptr = xmemdup(trap, sizeof(trap));
4825 /* Fall through into clearing traps */
4829 /* do job control only in root shell */
4831 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4834 if (jp->nprocs == 0)
4837 pgrp = jp->ps[0].ps_pid;
4838 /* this can fail because we are doing it in the parent also */
4840 if (mode == FORK_FG)
4841 xtcsetpgrp(ttyfd, pgrp);
4846 if (mode == FORK_BG) {
4847 /* man bash: "When job control is not in effect,
4848 * asynchronous commands ignore SIGINT and SIGQUIT" */
4851 if (jp->nprocs == 0) {
4853 if (open(bb_dev_null, O_RDONLY) != 0)
4854 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4858 if (iflag) { /* why if iflag only? */
4863 * "In all cases, bash ignores SIGQUIT. Non-builtin
4864 * commands run by bash have signal handlers
4865 * set to the values inherited by the shell
4867 * Take care of the second rule: */
4871 if (n && n->type == NCMD
4872 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4874 TRACE(("Job hack\n"));
4875 /* "jobs": we do not want to clear job list for it,
4876 * instead we remove only _its_ own_ job from job list.
4877 * This makes "jobs .... | cat" more useful.
4883 for (jp = curjob; jp; jp = jp->prev_job)
4888 /* Called after fork(), in parent */
4890 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4893 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4895 TRACE(("In parent shell: child = %d\n", pid));
4897 /* jp is NULL when called by openhere() for heredoc support */
4898 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4904 if (mode != FORK_NOJOB && jp->jobctl) {
4907 if (jp->nprocs == 0)
4910 pgrp = jp->ps[0].ps_pid;
4911 /* This can fail because we are doing it in the child also */
4915 if (mode == FORK_BG) {
4916 backgndpid = pid; /* set $! */
4917 set_curjob(jp, CUR_RUNNING);
4920 struct procstat *ps = &jp->ps[jp->nprocs++];
4923 ps->ps_cmd = nullstr;
4925 if (doing_jobctl && n)
4926 ps->ps_cmd = commandtext(n);
4931 /* jp and n are NULL when called by openhere() for heredoc support */
4933 forkshell(struct job *jp, union node *n, int mode)
4937 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4940 TRACE(("Fork failed, errno=%d", errno));
4943 ash_msg_and_raise_error("can't fork");
4946 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4947 forkchild(jp, n, mode);
4949 forkparent(jp, n, mode, pid);
4955 * Wait for job to finish.
4957 * Under job control we have the problem that while a child process
4958 * is running interrupts generated by the user are sent to the child
4959 * but not to the shell. This means that an infinite loop started by
4960 * an interactive user may be hard to kill. With job control turned off,
4961 * an interactive user may place an interactive program inside a loop.
4962 * If the interactive program catches interrupts, the user doesn't want
4963 * these interrupts to also abort the loop. The approach we take here
4964 * is to have the shell ignore interrupt signals while waiting for a
4965 * foreground process to terminate, and then send itself an interrupt
4966 * signal if the child process was terminated by an interrupt signal.
4967 * Unfortunately, some programs want to do a bit of cleanup and then
4968 * exit on interrupt; unless these processes terminate themselves by
4969 * sending a signal to themselves (instead of calling exit) they will
4970 * confuse this approach.
4972 * Called with interrupts off.
4975 waitforjob(struct job *jp)
4979 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4982 while (jp->state == JOBRUNNING) {
4983 /* In non-interactive shells, we _can_ get
4984 * a keyboard signal here and be EINTRed,
4985 * but we just loop back, waiting for command to complete.
4988 * "If bash is waiting for a command to complete and receives
4989 * a signal for which a trap has been set, the trap
4990 * will not be executed until the command completes."
4992 * Reality is that even if trap is not set, bash
4993 * will not act on the signal until command completes.
4994 * Try this. sleep5intoff.c:
4995 * #include <signal.h>
4996 * #include <unistd.h>
4999 * sigemptyset(&set);
5000 * sigaddset(&set, SIGINT);
5001 * sigaddset(&set, SIGQUIT);
5002 * sigprocmask(SIG_BLOCK, &set, NULL);
5006 * $ bash -c './sleep5intoff; echo hi'
5007 * ^C^C^C^C <--- pressing ^C once a second
5009 * $ bash -c './sleep5intoff; echo hi'
5010 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5013 dowait(DOWAIT_BLOCK, jp);
5020 xtcsetpgrp(ttyfd, rootpid);
5022 * This is truly gross.
5023 * If we're doing job control, then we did a TIOCSPGRP which
5024 * caused us (the shell) to no longer be in the controlling
5025 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5026 * intuit from the subprocess exit status whether a SIGINT
5027 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5029 if (jp->sigint) /* TODO: do the same with all signals */
5030 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5032 if (jp->state == JOBDONE)
5039 * return 1 if there are stopped jobs, otherwise 0
5051 if (jp && jp->state == JOBSTOPPED) {
5052 out2str("You have stopped jobs.\n");
5062 * Code for dealing with input/output redirection.
5067 #define EMPTY -2 /* marks an unused slot in redirtab */
5068 #define CLOSED -3 /* marks a slot of previously-closed fd */
5071 * Open a file in noclobber mode.
5072 * The code was copied from bash.
5075 noclobberopen(const char *fname)
5078 struct stat finfo, finfo2;
5081 * If the file exists and is a regular file, return an error
5084 r = stat(fname, &finfo);
5085 if (r == 0 && S_ISREG(finfo.st_mode)) {
5091 * If the file was not present (r != 0), make sure we open it
5092 * exclusively so that if it is created before we open it, our open
5093 * will fail. Make sure that we do not truncate an existing file.
5094 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5095 * file was not a regular file, we leave O_EXCL off.
5098 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5099 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5101 /* If the open failed, return the file descriptor right away. */
5106 * OK, the open succeeded, but the file may have been changed from a
5107 * non-regular file to a regular file between the stat and the open.
5108 * We are assuming that the O_EXCL open handles the case where FILENAME
5109 * did not exist and is symlinked to an existing file between the stat
5114 * If we can open it and fstat the file descriptor, and neither check
5115 * revealed that it was a regular file, and the file has not been
5116 * replaced, return the file descriptor.
5118 if (fstat(fd, &finfo2) == 0
5119 && !S_ISREG(finfo2.st_mode)
5120 && finfo.st_dev == finfo2.st_dev
5121 && finfo.st_ino == finfo2.st_ino
5126 /* The file has been replaced. badness. */
5133 * Handle here documents. Normally we fork off a process to write the
5134 * data to a pipe. If the document is short, we can stuff the data in
5135 * the pipe without forking.
5137 /* openhere needs this forward reference */
5138 static void expandhere(union node *arg, int fd);
5140 openhere(union node *redir)
5146 ash_msg_and_raise_error("pipe call failed");
5147 if (redir->type == NHERE) {
5148 len = strlen(redir->nhere.doc->narg.text);
5149 if (len <= PIPE_BUF) {
5150 full_write(pip[1], redir->nhere.doc->narg.text, len);
5154 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5157 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5158 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5159 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5160 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5161 signal(SIGPIPE, SIG_DFL);
5162 if (redir->type == NHERE)
5163 full_write(pip[1], redir->nhere.doc->narg.text, len);
5165 expandhere(redir->nhere.doc, pip[1]);
5166 _exit(EXIT_SUCCESS);
5174 openredirect(union node *redir)
5179 switch (redir->nfile.type) {
5180 /* Can't happen, our single caller does this itself */
5186 return openhere(redir);
5189 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5190 * allocated space. Do it only when we know it is safe.
5192 fname = redir->nfile.expfname;
5194 switch (redir->nfile.type) {
5200 f = open(fname, O_RDONLY);
5205 f = open(fname, O_RDWR|O_CREAT, 0666);
5210 #if ENABLE_ASH_BASH_COMPAT
5213 /* Take care of noclobber mode. */
5215 f = noclobberopen(fname);
5222 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5227 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5235 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5237 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5241 * Copy a file descriptor to be >= 10. Throws exception on error.
5249 newfd = fcntl(from, F_DUPFD, 10);
5250 err = newfd < 0 ? errno : 0;
5253 ash_msg_and_raise_error("%d: %m", from);
5255 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5261 dup2_or_raise(int from, int to)
5265 newfd = (from != to) ? dup2(from, to) : to;
5267 /* Happens when source fd is not open: try "echo >&99" */
5268 ash_msg_and_raise_error("%d: %m", from);
5273 /* Struct def and variable are moved down to the first usage site */
5278 struct redirtab *next;
5280 struct two_fd_t two_fd[];
5282 #define redirlist (G_var.redirlist)
5284 COPYFD_RESTORE = (int)~(INT_MAX),
5288 need_to_remember(struct redirtab *rp, int fd)
5292 if (!rp) /* remembering was not requested */
5295 for (i = 0; i < rp->pair_count; i++) {
5296 if (rp->two_fd[i].orig == fd) {
5297 /* already remembered */
5304 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5306 is_hidden_fd(struct redirtab *rp, int fd)
5309 struct parsefile *pf;
5313 /* Check open scripts' fds */
5316 /* We skip pf_fd == 0 case because of the following case:
5317 * $ ash # running ash interactively
5319 * and in script.sh: "exec 9>&0".
5320 * Even though top-level pf_fd _is_ 0,
5321 * it's still ok to use it: "read" builtin uses it,
5322 * why should we cripple "exec" builtin?
5324 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5332 /* Check saved fds of redirects */
5333 fd |= COPYFD_RESTORE;
5334 for (i = 0; i < rp->pair_count; i++) {
5335 if (rp->two_fd[i].copy == fd) {
5343 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5344 * old file descriptors are stashed away so that the redirection can be
5345 * undone by calling popredir.
5347 /* flags passed to redirect */
5348 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5349 #define REDIR_SAVEFD2 03 /* set preverrout */
5351 redirect(union node *redir, int flags)
5353 struct redirtab *sv;
5358 int copied_fd2 = -1;
5367 if (flags & REDIR_PUSH) {
5368 union node *tmp = redir;
5371 #if ENABLE_ASH_BASH_COMPAT
5372 if (tmp->nfile.type == NTO2)
5375 tmp = tmp->nfile.next;
5377 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5378 sv->next = redirlist;
5379 sv->pair_count = sv_pos;
5381 while (sv_pos > 0) {
5383 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5389 fd = redir->nfile.fd;
5390 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5391 right_fd = redir->ndup.dupfd;
5392 //bb_error_msg("doing %d > %d", fd, right_fd);
5393 /* redirect from/to same file descriptor? */
5396 /* "echo >&10" and 10 is a fd opened to a sh script? */
5397 if (is_hidden_fd(sv, right_fd)) {
5398 errno = EBADF; /* as if it is closed */
5399 ash_msg_and_raise_error("%d: %m", right_fd);
5403 newfd = openredirect(redir); /* always >= 0 */
5405 /* Descriptor wasn't open before redirect.
5406 * Mark it for close in the future */
5407 if (need_to_remember(sv, fd)) {
5408 goto remember_to_close;
5413 #if ENABLE_ASH_BASH_COMPAT
5416 if (need_to_remember(sv, fd)) {
5417 /* Copy old descriptor */
5418 /* Careful to not accidentally "save"
5419 * to the same fd as right side fd in N>&M */
5420 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5421 i = fcntl(fd, F_DUPFD, minfd);
5422 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5423 * are closed in popredir() in the child, preventing them from leaking
5424 * into child. (popredir() also cleans up the mess in case of failures)
5429 /* Strange error (e.g. "too many files" EMFILE?) */
5433 ash_msg_and_raise_error("%d: %m", fd);
5436 /* EBADF: it is not open - good, remember to close it */
5439 } else { /* fd is open, save its copy */
5440 /* "exec fd>&-" should not close fds
5441 * which point to script file(s).
5442 * Force them to be restored afterwards */
5443 if (is_hidden_fd(sv, fd))
5444 i |= COPYFD_RESTORE;
5448 sv->two_fd[sv_pos].orig = fd;
5449 sv->two_fd[sv_pos].copy = i;
5453 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5454 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5455 /* Don't want to trigger debugging */
5459 dup2_or_raise(redir->ndup.dupfd, fd);
5461 } else if (fd != newfd) { /* move newfd to fd */
5462 dup2_or_raise(newfd, fd);
5463 #if ENABLE_ASH_BASH_COMPAT
5464 if (!(redir->nfile.type == NTO2 && fd == 2))
5468 #if ENABLE_ASH_BASH_COMPAT
5469 if (redir->nfile.type == NTO2 && fd == 1) {
5470 /* We already redirected it to fd 1, now copy it to 2 */
5476 } while ((redir = redir->nfile.next) != NULL);
5479 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5480 preverrout_fd = copied_fd2;
5484 * Undo the effects of the last redirection.
5487 popredir(int drop, int restore)
5489 struct redirtab *rp;
5492 if (redirlist == NULL)
5496 for (i = 0; i < rp->pair_count; i++) {
5497 int fd = rp->two_fd[i].orig;
5498 int copy = rp->two_fd[i].copy;
5499 if (copy == CLOSED) {
5504 if (copy != EMPTY) {
5505 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5506 copy &= ~COPYFD_RESTORE;
5508 dup2_or_raise(copy, fd);
5510 close(copy & ~COPYFD_RESTORE);
5513 redirlist = rp->next;
5519 * Undo all redirections. Called on error or interrupt.
5523 redirectsafe(union node *redir, int flags)
5526 volatile int saveint;
5527 struct jmploc *volatile savehandler = exception_handler;
5528 struct jmploc jmploc;
5531 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5532 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5534 exception_handler = &jmploc;
5535 redirect(redir, flags);
5537 exception_handler = savehandler;
5538 if (err && exception_type != EXERROR)
5539 longjmp(exception_handler->loc, 1);
5540 RESTORE_INT(saveint);
5545 /* ============ Routines to expand arguments to commands
5547 * We have to deal with backquotes, shell variables, and file metacharacters.
5550 #if ENABLE_SH_MATH_SUPPORT
5552 ash_arith(const char *s)
5554 arith_state_t math_state;
5557 math_state.lookupvar = lookupvar;
5558 math_state.setvar = setvar0;
5559 //math_state.endofname = endofname;
5562 result = arith(&math_state, s);
5563 if (math_state.errmsg)
5564 ash_msg_and_raise_error(math_state.errmsg);
5574 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5575 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5576 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5577 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5578 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5579 * POSIX says for this case:
5580 * Pathname expansion shall not be performed on the word by a
5581 * non-interactive shell; an interactive shell may perform it, but shall
5582 * do so only when the expansion would result in one word.
5583 * Currently, our code complies to the above rule by never globbing
5584 * redirection filenames.
5585 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5586 * (this means that on a typical Linux distro, bash almost always
5587 * performs globbing, and thus diverges from what we do).
5589 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5590 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5591 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5592 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5593 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5597 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5598 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5599 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5600 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5601 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5603 /* Add CTLESC when necessary. */
5604 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5605 /* Do not skip NUL characters. */
5606 #define QUOTES_KEEPNUL EXP_TILDE
5609 * Structure specifying which parts of the string should be searched
5610 * for IFS characters.
5613 struct ifsregion *next; /* next region in list */
5614 int begoff; /* offset of start of region */
5615 int endoff; /* offset of end of region */
5616 int nulonly; /* search for nul bytes only */
5620 struct strlist *list;
5621 struct strlist **lastp;
5624 /* output of current string */
5625 static char *expdest;
5626 /* list of back quote expressions */
5627 static struct nodelist *argbackq;
5628 /* first struct in list of ifs regions */
5629 static struct ifsregion ifsfirst;
5630 /* last struct in list */
5631 static struct ifsregion *ifslastp;
5632 /* holds expanded arg list */
5633 static struct arglist exparg;
5638 #if !ENABLE_SH_MATH_SUPPORT
5639 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5640 typedef long arith_t;
5641 # define ARITH_FMT "%ld"
5648 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5649 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5650 STADJUST(len, expdest);
5655 * Break the argument string into pieces based upon IFS and add the
5656 * strings to the argument list. The regions of the string to be
5657 * searched for IFS characters have been stored by recordregion.
5660 ifsbreakup(char *string, struct arglist *arglist)
5662 struct ifsregion *ifsp;
5667 const char *ifs, *realifs;
5672 if (ifslastp != NULL) {
5675 realifs = ifsset() ? ifsval() : defifs;
5678 p = string + ifsp->begoff;
5679 nulonly = ifsp->nulonly;
5680 ifs = nulonly ? nullstr : realifs;
5682 while (p < string + ifsp->endoff) {
5684 if ((unsigned char)*p == CTLESC)
5686 if (!strchr(ifs, *p)) {
5691 ifsspc = (strchr(defifs, *p) != NULL);
5692 /* Ignore IFS whitespace at start */
5693 if (q == start && ifsspc) {
5699 sp = stzalloc(sizeof(*sp));
5701 *arglist->lastp = sp;
5702 arglist->lastp = &sp->next;
5706 if (p >= string + ifsp->endoff) {
5710 if ((unsigned char)*p == CTLESC)
5712 if (strchr(ifs, *p) == NULL) {
5716 if (strchr(defifs, *p) == NULL) {
5731 } while (ifsp != NULL);
5740 sp = stzalloc(sizeof(*sp));
5742 *arglist->lastp = sp;
5743 arglist->lastp = &sp->next;
5749 struct ifsregion *p = ifsfirst.next;
5756 struct ifsregion *ifsp;
5761 ifsfirst.next = NULL;
5768 esclen(const char *start, const char *p)
5772 while (p > start && (unsigned char)*--p == CTLESC) {
5779 * Remove any CTLESC characters from a string.
5782 rmescapes(char *str, int flag)
5784 static const char qchars[] ALIGN1 = {
5785 IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
5789 unsigned protect_against_glob;
5791 IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
5793 p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
5799 if (flag & RMESCAPE_ALLOC) {
5800 size_t len = p - str;
5801 size_t fulllen = len + strlen(p) + 1;
5803 if (flag & RMESCAPE_GROW) {
5804 int strloc = str - (char *)stackblock();
5805 r = makestrspace(fulllen, expdest);
5806 /* p and str may be invalidated by makestrspace */
5807 str = (char *)stackblock() + strloc;
5809 } else if (flag & RMESCAPE_HEAP) {
5810 r = ckmalloc(fulllen);
5812 r = stalloc(fulllen);
5816 q = (char *)memcpy(q, str, len) + len;
5821 globbing = flag & RMESCAPE_GLOB;
5822 protect_against_glob = globbing;
5824 if ((unsigned char)*p == CTLQUOTEMARK) {
5825 // Note: both inquotes and protect_against_glob only affect whether
5826 inquotes = ~inquotes;
5828 protect_against_glob = globbing;
5831 if ((unsigned char)*p == CTLESC) {
5835 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5837 if (protect_against_glob) {
5840 } else if (*p == '\\' && !inquotes) {
5841 /* naked back slash */
5842 protect_against_glob = 0;
5845 #if ENABLE_ASH_BASH_COMPAT
5846 else if (*p == '/' && slash) {
5847 /* stop handling globbing and mark location of slash */
5848 globbing = slash = 0;
5852 protect_against_glob = globbing;
5857 if (flag & RMESCAPE_GROW) {
5859 STADJUST(q - r + 1, expdest);
5863 #define pmatch(a, b) !fnmatch((a), (b), 0)
5866 * Prepare a pattern for a expmeta (internal glob(3)) call.
5868 * Returns an stalloced string.
5871 preglob(const char *pattern, int flag)
5873 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5877 * Put a string on the stack.
5880 memtodest(const char *p, size_t len, int syntax, int quotes)
5887 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5890 unsigned char c = *p++;
5892 if (quotes & QUOTES_ESC) {
5893 int n = SIT(c, syntax);
5895 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
5902 } else if (!(quotes & QUOTES_KEEPNUL))
5911 strtodest(const char *p, int syntax, int quotes)
5913 size_t len = strlen(p);
5914 memtodest(p, len, syntax, quotes);
5919 * Record the fact that we have to scan this region of the
5920 * string for IFS characters.
5923 recordregion(int start, int end, int nulonly)
5925 struct ifsregion *ifsp;
5927 if (ifslastp == NULL) {
5931 ifsp = ckzalloc(sizeof(*ifsp));
5932 /*ifsp->next = NULL; - ckzalloc did it */
5933 ifslastp->next = ifsp;
5937 ifslastp->begoff = start;
5938 ifslastp->endoff = end;
5939 ifslastp->nulonly = nulonly;
5943 removerecordregions(int endoff)
5945 if (ifslastp == NULL)
5948 if (ifsfirst.endoff > endoff) {
5949 while (ifsfirst.next) {
5950 struct ifsregion *ifsp;
5952 ifsp = ifsfirst.next->next;
5953 free(ifsfirst.next);
5954 ifsfirst.next = ifsp;
5957 if (ifsfirst.begoff > endoff) {
5960 ifslastp = &ifsfirst;
5961 ifsfirst.endoff = endoff;
5966 ifslastp = &ifsfirst;
5967 while (ifslastp->next && ifslastp->next->begoff < endoff)
5968 ifslastp = ifslastp->next;
5969 while (ifslastp->next) {
5970 struct ifsregion *ifsp;
5972 ifsp = ifslastp->next->next;
5973 free(ifslastp->next);
5974 ifslastp->next = ifsp;
5977 if (ifslastp->endoff > endoff)
5978 ifslastp->endoff = endoff;
5982 exptilde(char *startp, char *p, int flags)
5988 int quotes = flags & QUOTES_ESC;
5992 while ((c = *++p) != '\0') {
5999 if (flags & EXP_VARTILDE)
6009 if (*name == '\0') {
6010 home = lookupvar("HOME");
6012 pw = getpwnam(name);
6017 if (!home || !*home)
6020 strtodest(home, SQSYNTAX, quotes);
6028 * Execute a command inside back quotes. If it's a builtin command, we
6029 * want to save its output in a block obtained from malloc. Otherwise
6030 * we fork off a subprocess and get the output of the command via a pipe.
6031 * Should be called with interrupts off.
6033 struct backcmd { /* result of evalbackcmd */
6034 int fd; /* file descriptor to read from */
6035 int nleft; /* number of chars in buffer */
6036 char *buf; /* buffer */
6037 struct job *jp; /* job structure for command */
6040 /* These forward decls are needed to use "eval" code for backticks handling: */
6041 #define EV_EXIT 01 /* exit after evaluating tree */
6042 static int evaltree(union node *, int);
6044 static void FAST_FUNC
6045 evalbackcmd(union node *n, struct backcmd *result)
6059 ash_msg_and_raise_error("pipe call failed");
6060 jp = makejob(/*n,*/ 1);
6061 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6067 dup2_or_raise(pip[1], 1);
6070 /* TODO: eflag clearing makes the following not abort:
6071 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6072 * which is what bash does (unless it is in POSIX mode).
6073 * dash deleted "eflag = 0" line in the commit
6074 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6075 * [EVAL] Don't clear eflag in evalbackcmd
6076 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6080 evaltree(n, EV_EXIT); /* actually evaltreenr... */
6085 result->fd = pip[0];
6089 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6090 result->fd, result->buf, result->nleft, result->jp));
6094 * Expand stuff in backwards quotes.
6097 expbackq(union node *cmd, int flag)
6105 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6106 struct stackmark smark;
6109 startloc = expdest - (char *)stackblock();
6110 pushstackmark(&smark, startloc);
6111 evalbackcmd(cmd, &in);
6112 popstackmark(&smark);
6119 memtodest(p, i, syntax, flag & QUOTES_ESC);
6123 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6124 TRACE(("expbackq: read returns %d\n", i));
6133 back_exitstatus = waitforjob(in.jp);
6137 /* Eat all trailing newlines */
6139 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6143 if (!(flag & EXP_QUOTED))
6144 recordregion(startloc, dest - (char *)stackblock(), 0);
6145 TRACE(("evalbackq: size:%d:'%.*s'\n",
6146 (int)((dest - (char *)stackblock()) - startloc),
6147 (int)((dest - (char *)stackblock()) - startloc),
6148 stackblock() + startloc));
6151 #if ENABLE_SH_MATH_SUPPORT
6153 * Expand arithmetic expression. Backup to start of expression,
6154 * evaluate, place result in (backed up) result, adjust string position.
6166 * This routine is slightly over-complicated for
6167 * efficiency. Next we scan backwards looking for the
6168 * start of arithmetic.
6170 start = stackblock();
6177 while ((unsigned char)*p != CTLARI) {
6181 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6186 esc = esclen(start, p);
6196 removerecordregions(begoff);
6200 if (flag & QUOTES_ESC)
6201 rmescapes(p + 1, 0);
6203 len = cvtnum(ash_arith(p + 1));
6205 if (!(flag & EXP_QUOTED))
6206 recordregion(begoff, begoff + len, 0);
6210 /* argstr needs it */
6211 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6214 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6215 * characters to allow for further processing. Otherwise treat
6216 * $@ like $* since no splitting will be performed.
6218 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6219 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6220 * for correct expansion of "B=$A" word.
6223 argstr(char *p, int flags, struct strlist *var_str_list)
6225 static const char spclchars[] ALIGN1 = {
6233 #if ENABLE_SH_MATH_SUPPORT
6238 const char *reject = spclchars;
6239 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6244 if (!(flags & EXP_VARTILDE)) {
6246 } else if (flags & EXP_VARTILDE2) {
6251 if (flags & EXP_TILDE) {
6254 flags &= ~EXP_TILDE;
6258 p = exptilde(p, q, flags);
6261 startloc = expdest - (char *)stackblock();
6265 length += strcspn(p + length, reject);
6269 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6271 /* c == '=' || c == ':' || c == CTLENDARI */
6277 expdest = stack_nputstr(p, length, expdest);
6278 newloc = expdest - (char *)stackblock();
6279 if (breakall && !inquotes && newloc > startloc) {
6280 recordregion(startloc, newloc, 0);
6291 if (flags & EXP_VARTILDE2) {
6295 flags |= EXP_VARTILDE2;
6300 * sort of a hack - expand tildes in variable
6301 * assignments (after the first '=' and after ':'s).
6310 case CTLENDVAR: /* ??? */
6313 inquotes ^= EXP_QUOTED;
6314 /* "$@" syntax adherence hack */
6315 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6316 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6320 if (flags & QUOTES_ESC) {
6331 * Quoted parameter expansion pattern: remove quote
6332 * unless inside inner quotes or we have a literal
6335 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6336 EXP_QPAT && *p != '\\')
6341 TRACE(("argstr: evalvar('%s')\n", p));
6342 p = evalvar(p, flags | inquotes, var_str_list);
6343 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6346 expbackq(argbackq->n, flags | inquotes);
6347 argbackq = argbackq->next;
6349 #if ENABLE_SH_MATH_SUPPORT
6352 expari(flags | inquotes);
6361 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6362 char *pattern, int quotes, int zero)
6371 const char *s = loc2;
6378 match = pmatch(pattern, s);
6383 if (quotes && (unsigned char)*loc == CTLESC)
6392 scanright(char *startp, char *rmesc, char *rmescend,
6393 char *pattern, int quotes, int match_at_start)
6395 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6396 int try2optimize = match_at_start;
6402 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6403 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6404 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6406 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6407 * and on each iteration they go back two/one char until they reach the beginning.
6408 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6410 /* TODO: document in what other circumstances we are called. */
6412 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6415 const char *s = loc2;
6416 if (match_at_start) {
6420 match = pmatch(pattern, s);
6421 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6425 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6427 /* Maybe we can optimize this:
6428 * if pattern ends with unescaped *, we can avoid checking
6429 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6430 * it wont match truncated "raw_value_of_" strings too.
6432 unsigned plen = strlen(pattern);
6433 /* Does it end with "*"? */
6434 if (plen != 0 && pattern[--plen] == '*') {
6435 /* "xxxx*" is not escaped */
6436 /* "xxx\*" is escaped */
6437 /* "xx\\*" is not escaped */
6438 /* "x\\\*" is escaped */
6440 while (plen != 0 && pattern[--plen] == '\\')
6443 break; /* ends with unescaped "*" */
6451 esc = esclen(startp, loc);
6462 static void varunset(const char *, const char *, const char *, int) NORETURN;
6464 varunset(const char *end, const char *var, const char *umsg, int varflags)
6470 msg = "parameter not set";
6472 if ((unsigned char)*end == CTLENDVAR) {
6473 if (varflags & VSNUL)
6479 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6483 subevalvar(char *p, char *varname, int strloc, int subtype,
6484 int startloc, int varflags, int flag, struct strlist *var_str_list)
6486 struct nodelist *saveargbackq = argbackq;
6487 int quotes = flag & QUOTES_ESC;
6490 char *rmesc, *rmescend;
6492 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6493 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6494 int amount, resetloc;
6495 IF_ASH_BASH_COMPAT(int workloc;)
6497 char *(*scan)(char*, char*, char*, char*, int, int);
6499 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6500 // p, varname, strloc, subtype, startloc, varflags, quotes);
6502 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6503 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6505 STPUTC('\0', expdest);
6506 argbackq = saveargbackq;
6507 startp = (char *)stackblock() + startloc;
6511 setvar0(varname, startp);
6512 amount = startp - expdest;
6513 STADJUST(amount, expdest);
6517 varunset(p, varname, startp, varflags);
6520 #if ENABLE_ASH_BASH_COMPAT
6522 //TODO: support more general format ${v:EXPR:EXPR},
6523 // where EXPR follows $(()) rules
6524 loc = str = stackblock() + strloc;
6525 /* Read POS in ${var:POS:LEN} */
6526 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6527 len = str - startp - 1;
6529 /* *loc != '\0', guaranteed by parser */
6533 /* Adjust the length by the number of escapes */
6534 for (ptr = startp; ptr < (str - 1); ptr++) {
6535 if ((unsigned char)*ptr == CTLESC) {
6543 if (*loc++ == ':') {
6547 /* Skip POS in ${var:POS:LEN} */
6549 while (*loc && *loc != ':') {
6551 * bash complains on: var=qwe; echo ${var:1a:123}
6553 ash_msg_and_raise_error(msg_illnum, str);
6557 if (*loc++ == ':') {
6562 /* ${VAR:$((-n)):l} starts n chars from the end */
6563 pos = orig_len + pos;
6565 if ((unsigned)pos >= orig_len) {
6566 /* apart from obvious ${VAR:999999:l},
6567 * covers ${VAR:$((-9999999)):l} - result is ""
6573 if (len > (orig_len - pos))
6574 len = orig_len - pos;
6576 for (str = startp; pos; str++, pos--) {
6577 if (quotes && (unsigned char)*str == CTLESC)
6580 for (loc = startp; len; len--) {
6581 if (quotes && (unsigned char)*str == CTLESC)
6586 amount = loc - expdest;
6587 STADJUST(amount, expdest);
6592 resetloc = expdest - (char *)stackblock();
6594 /* We'll comeback here if we grow the stack while handling
6595 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6596 * stack will need rebasing, and we'll need to remove our work
6599 IF_ASH_BASH_COMPAT(restart:)
6601 amount = expdest - ((char *)stackblock() + resetloc);
6602 STADJUST(-amount, expdest);
6603 startp = (char *)stackblock() + startloc;
6606 rmescend = (char *)stackblock() + strloc;
6608 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6609 if (rmesc != startp) {
6611 startp = (char *)stackblock() + startloc;
6615 str = (char *)stackblock() + strloc;
6617 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6618 * The result is a_\_z_c (not a\_\_z_c)!
6620 * The search pattern and replace string treat backslashes differently!
6621 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6622 * and string. It's only used on the first call.
6624 preglob(str, IF_ASH_BASH_COMPAT(
6625 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6626 RMESCAPE_SLASH :) 0);
6628 #if ENABLE_ASH_BASH_COMPAT
6629 workloc = expdest - (char *)stackblock();
6630 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6634 repl = strchr(str, CTLESC);
6640 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6642 /* If there's no pattern to match, return the expansion unmolested */
6651 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6652 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6654 /* No match, advance */
6655 char *restart_detect = stackblock();
6657 STPUTC(*idx, expdest);
6658 if (quotes && (unsigned char)*idx == CTLESC) {
6661 STPUTC(*idx, expdest);
6663 if (stackblock() != restart_detect)
6668 /* continue; - prone to quadratic behavior, smarter code: */
6671 if (str[0] == '*') {
6672 /* Pattern is "*foo". If "*foo" does not match "long_string",
6673 * it would never match "ong_string" etc, no point in trying.
6680 if (subtype == VSREPLACEALL) {
6682 if (quotes && (unsigned char)*idx == CTLESC)
6691 //bb_error_msg("repl:'%s'", repl);
6692 for (loc = (char*)repl; *loc; loc++) {
6693 char *restart_detect = stackblock();
6694 if (quotes && *loc == '\\') {
6695 STPUTC(CTLESC, expdest);
6698 STPUTC(*loc, expdest);
6699 if (stackblock() != restart_detect)
6704 if (subtype == VSREPLACE) {
6705 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6707 char *restart_detect = stackblock();
6708 STPUTC(*idx, expdest);
6709 if (stackblock() != restart_detect)
6718 /* We've put the replaced text into a buffer at workloc, now
6719 * move it to the right place and adjust the stack.
6721 STPUTC('\0', expdest);
6722 startp = (char *)stackblock() + startloc;
6723 memmove(startp, (char *)stackblock() + workloc, len + 1);
6724 //bb_error_msg("startp:'%s'", startp);
6725 amount = expdest - (startp + len);
6726 STADJUST(-amount, expdest);
6729 #endif /* ENABLE_ASH_BASH_COMPAT */
6731 subtype -= VSTRIMRIGHT;
6733 if (subtype < 0 || subtype > 7)
6736 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6737 zero = subtype >> 1;
6738 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6739 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6741 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6744 memmove(startp, loc, str - loc);
6745 loc = startp + (str - loc) - 1;
6748 amount = loc - expdest;
6749 STADJUST(amount, expdest);
6755 * Add the value of a specialized variable to the stack string.
6756 * name parameter (examples):
6757 * ash -c 'echo $1' name:'1='
6758 * ash -c 'echo $qwe' name:'qwe='
6759 * ash -c 'echo $$' name:'$='
6760 * ash -c 'echo ${$}' name:'$='
6761 * ash -c 'echo ${$##q}' name:'$=q'
6762 * ash -c 'echo ${#$}' name:'$='
6763 * note: examples with bad shell syntax:
6764 * ash -c 'echo ${#$1}' name:'$=1'
6765 * ash -c 'echo ${#1#}' name:'1=#'
6767 static NOINLINE ssize_t
6768 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list, int *quotedp)
6775 int quoted = *quotedp;
6776 int subtype = varflags & VSTYPE;
6777 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6778 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6781 sep = (flags & EXP_FULL) << CHAR_BIT;
6782 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6792 num = shellparam.nparam;
6800 goto check_1char_name;
6802 expdest = makestrspace(NOPTS, expdest);
6803 for (i = NOPTS - 1; i >= 0; i--) {
6805 USTPUTC(optletters(i), expdest);
6811 /* handles cases similar to ${#$1} */
6812 if (name[2] != '\0')
6813 raise_error_syntax("bad substitution");
6826 sep |= ifsset() ? ifsval()[0] : ' ';
6833 while ((p = *ap++) != NULL) {
6834 len += strtodest(p, syntax, quotes);
6838 memtodest(&sepc, 1, syntax, quotes);
6853 num = atoi(name); /* number(name) fails on ${N#str} etc */
6854 if (num < 0 || num > shellparam.nparam)
6856 p = num ? shellparam.p[num - 1] : arg0;
6859 /* NB: name has form "VAR=..." */
6861 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6862 * which should be considered before we check variables. */
6864 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6868 str = var_str_list->text;
6869 eq = strchr(str, '=');
6870 if (!eq) /* stop at first non-assignment */
6873 if (name_len == (unsigned)(eq - str)
6874 && strncmp(str, name, name_len) == 0
6877 /* goto value; - WRONG! */
6878 /* think "A=1 A=2 B=$A" */
6880 var_str_list = var_str_list->next;
6881 } while (var_str_list);
6885 p = lookupvar(name);
6890 len = strtodest(p, syntax, quotes);
6891 #if ENABLE_UNICODE_SUPPORT
6892 if (subtype == VSLENGTH && len > 0) {
6893 reinit_unicode_for_ash();
6894 if (unicode_status == UNICODE_ON) {
6895 STADJUST(-len, expdest);
6897 len = unicode_strlen(p);
6905 STADJUST(-len, expdest);
6910 * Expand a variable, and return a pointer to the next character in the
6914 evalvar(char *p, int flag, struct strlist *var_str_list)
6925 varflags = (unsigned char) *p++;
6926 subtype = varflags & VSTYPE;
6929 raise_error_syntax("bad substitution");
6931 quoted = flag & EXP_QUOTED;
6933 easy = (!quoted || (*var == '@' && shellparam.nparam));
6934 startloc = expdest - (char *)stackblock();
6935 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6938 varlen = varvalue(var, varflags, flag, var_str_list, "ed);
6939 if (varflags & VSNUL)
6942 if (subtype == VSPLUS) {
6943 varlen = -1 - varlen;
6947 if (subtype == VSMINUS) {
6952 flag | EXP_TILDE | EXP_WORD,
6960 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6964 subevalvar(p, var, 0, subtype, startloc, varflags,
6965 flag & ~QUOTES_ESC, var_str_list);
6968 * Remove any recorded regions beyond
6971 removerecordregions(startloc);
6975 if (varlen < 0 && uflag)
6976 varunset(p, var, 0, 0);
6978 if (subtype == VSLENGTH) {
6979 cvtnum(varlen > 0 ? varlen : 0);
6983 if (subtype == VSNORMAL) {
6987 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6996 case VSTRIMRIGHTMAX:
6997 #if ENABLE_ASH_BASH_COMPAT
7010 * Terminate the string and start recording the pattern
7013 STPUTC('\0', expdest);
7014 patloc = expdest - (char *)stackblock();
7015 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7016 startloc, varflags, flag, var_str_list)) {
7017 int amount = expdest - (
7018 (char *)stackblock() + patloc - 1
7020 STADJUST(-amount, expdest);
7022 /* Remove any recorded regions beyond start of variable */
7023 removerecordregions(startloc);
7028 if (subtype != VSNORMAL) { /* skip to end of alternative */
7031 unsigned char c = *p++;
7034 else if (c == CTLBACKQ) {
7036 argbackq = argbackq->next;
7037 } else if (c == CTLVAR) {
7038 if ((*p++ & VSTYPE) != VSNORMAL)
7040 } else if (c == CTLENDVAR) {
7050 * Add a file name to the list.
7053 addfname(const char *name)
7057 sp = stzalloc(sizeof(*sp));
7058 sp->text = sstrdup(name);
7060 exparg.lastp = &sp->next;
7063 /* If we want to use glob() from libc... */
7064 #if !ENABLE_ASH_INTERNAL_GLOB
7066 /* Add the result of glob() to the list */
7068 addglob(const glob_t *pglob)
7070 char **p = pglob->gl_pathv;
7077 expandmeta(struct strlist *str /*, int flag*/)
7079 /* TODO - EXP_REDIR */
7089 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7104 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7105 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7106 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7108 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7109 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7110 // Which means you need to unescape the string, right? Not so fast:
7111 // if there _is_ a file named "file\?" (with backslash), it is returned
7112 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7113 // You DONT KNOW by looking at the result whether you need to unescape it.
7115 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7116 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7117 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7118 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7119 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7120 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7121 i = glob(p, 0, NULL, &pglob);
7122 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7127 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7128 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7129 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7141 *exparg.lastp = str;
7142 rmescapes(str->text, 0);
7143 exparg.lastp = &str->next;
7145 default: /* GLOB_NOSPACE */
7148 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7155 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7158 * Do metacharacter (i.e. *, ?, [...]) expansion.
7161 expmeta(char *expdir, char *enddir, char *name)
7177 for (p = name; esc = 0, *p; p += esc + 1) {
7178 if (*p == '*' || *p == '?')
7180 else if (*p == '[') {
7187 if (*q == '/' || *q == '\0')
7197 if (p[esc] == '/') {
7200 start = p + esc + 1;
7204 if (metaflag == 0) { /* we've reached the end of the file name */
7205 if (enddir != expdir)
7213 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7224 } while (p < start);
7226 if (enddir == expdir) {
7228 } else if (enddir == expdir + 1 && *expdir == '/') {
7237 if (enddir != expdir)
7239 if (*endname == 0) {
7252 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7253 if (dp->d_name[0] == '.' && !matchdot)
7255 if (pmatch(start, dp->d_name)) {
7257 strcpy(enddir, dp->d_name);
7260 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7263 expmeta(expdir, p, endname);
7269 endname[-esc - 1] = esc ? '\\' : '/';
7272 static struct strlist *
7273 msort(struct strlist *list, int len)
7275 struct strlist *p, *q = NULL;
7276 struct strlist **lpp;
7284 for (n = half; --n >= 0;) {
7288 q->next = NULL; /* terminate first half of list */
7289 q = msort(list, half); /* sort first half of list */
7290 p = msort(p, len - half); /* sort second half */
7293 #if ENABLE_LOCALE_SUPPORT
7294 if (strcoll(p->text, q->text) < 0)
7296 if (strcmp(p->text, q->text) < 0)
7320 * Sort the results of file name expansion. It calculates the number of
7321 * strings to sort and then calls msort (short for merge sort) to do the
7324 static struct strlist *
7325 expsort(struct strlist *str)
7331 for (sp = str; sp; sp = sp->next)
7333 return msort(str, len);
7337 expandmeta(struct strlist *str /*, int flag*/)
7339 static const char metachars[] ALIGN1 = {
7342 /* TODO - EXP_REDIR */
7346 struct strlist **savelastp;
7352 if (!strpbrk(str->text, metachars))
7354 savelastp = exparg.lastp;
7357 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7359 int i = strlen(str->text);
7360 //BUGGY estimation of how long expanded name can be
7361 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7363 expmeta(expdir, expdir, p);
7368 if (exparg.lastp == savelastp) {
7373 *exparg.lastp = str;
7374 rmescapes(str->text, 0);
7375 exparg.lastp = &str->next;
7377 *exparg.lastp = NULL;
7378 *savelastp = sp = expsort(*savelastp);
7379 while (sp->next != NULL)
7381 exparg.lastp = &sp->next;
7386 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7389 * Perform variable substitution and command substitution on an argument,
7390 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7391 * perform splitting and file name expansion. When arglist is NULL, perform
7392 * here document expansion.
7395 expandarg(union node *arg, struct arglist *arglist, int flag)
7400 argbackq = arg->narg.backquote;
7401 STARTSTACKSTR(expdest);
7402 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7403 argstr(arg->narg.text, flag,
7404 /* var_str_list: */ arglist ? arglist->list : NULL);
7405 p = _STPUTC('\0', expdest);
7407 if (arglist == NULL) {
7408 /* here document expanded */
7411 p = grabstackstr(p);
7412 TRACE(("expandarg: p:'%s'\n", p));
7413 exparg.lastp = &exparg.list;
7417 if (flag & EXP_FULL) {
7418 ifsbreakup(p, &exparg);
7419 *exparg.lastp = NULL;
7420 exparg.lastp = &exparg.list;
7421 expandmeta(exparg.list /*, flag*/);
7423 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7425 TRACE(("expandarg: rmescapes:'%s'\n", p));
7427 sp = stzalloc(sizeof(*sp));
7430 exparg.lastp = &sp->next;
7432 *exparg.lastp = NULL;
7434 *arglist->lastp = exparg.list;
7435 arglist->lastp = exparg.lastp;
7443 * Expand shell variables and backquotes inside a here document.
7446 expandhere(union node *arg, int fd)
7448 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7449 full_write(fd, stackblock(), expdest - (char *)stackblock());
7453 * Returns true if the pattern matches the string.
7456 patmatch(char *pattern, const char *string)
7458 return pmatch(preglob(pattern, 0), string);
7462 * See if a pattern matches in a case statement.
7465 casematch(union node *pattern, char *val)
7467 struct stackmark smark;
7470 setstackmark(&smark);
7471 argbackq = pattern->narg.backquote;
7472 STARTSTACKSTR(expdest);
7473 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7474 /* var_str_list: */ NULL);
7475 STACKSTRNUL(expdest);
7477 result = patmatch(stackblock(), val);
7478 popstackmark(&smark);
7483 /* ============ find_command */
7487 int (*builtin)(int, char **) FAST_FUNC;
7488 /* unsigned flags; */
7490 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7491 /* "regular" builtins always take precedence over commands,
7492 * regardless of PATH=....%builtin... position */
7493 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7494 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7497 smallint cmdtype; /* CMDxxx */
7500 /* index >= 0 for commands without path (slashes) */
7501 /* (TODO: what exactly does the value mean? PATH position?) */
7502 /* index == -1 for commands with slashes */
7503 /* index == (-2 - applet_no) for NOFORK applets */
7504 const struct builtincmd *cmd;
7505 struct funcnode *func;
7508 /* values of cmdtype */
7509 #define CMDUNKNOWN -1 /* no entry in table for command */
7510 #define CMDNORMAL 0 /* command is an executable program */
7511 #define CMDFUNCTION 1 /* command is a shell function */
7512 #define CMDBUILTIN 2 /* command is a shell builtin */
7514 /* action to find_command() */
7515 #define DO_ERR 0x01 /* prints errors */
7516 #define DO_ABS 0x02 /* checks absolute paths */
7517 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7518 #define DO_ALTPATH 0x08 /* using alternate path */
7519 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7521 static void find_command(char *, struct cmdentry *, int, const char *);
7524 /* ============ Hashing commands */
7527 * When commands are first encountered, they are entered in a hash table.
7528 * This ensures that a full path search will not have to be done for them
7529 * on each invocation.
7531 * We should investigate converting to a linear search, even though that
7532 * would make the command name "hash" a misnomer.
7536 struct tblentry *next; /* next entry in hash chain */
7537 union param param; /* definition of builtin function */
7538 smallint cmdtype; /* CMDxxx */
7539 char rehash; /* if set, cd done since entry created */
7540 char cmdname[1]; /* name of command */
7543 static struct tblentry **cmdtable;
7544 #define INIT_G_cmdtable() do { \
7545 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7548 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7552 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7554 #if ENABLE_FEATURE_SH_STANDALONE
7555 if (applet_no >= 0) {
7556 if (APPLET_IS_NOEXEC(applet_no)) {
7560 run_applet_no_and_exit(applet_no, argv);
7562 /* re-exec ourselves with the new arguments */
7563 execve(bb_busybox_exec_path, argv, envp);
7564 /* If they called chroot or otherwise made the binary no longer
7565 * executable, fall through */
7572 execve(cmd, argv, envp);
7573 } while (errno == EINTR);
7575 execve(cmd, argv, envp);
7577 if (cmd != (char*) bb_busybox_exec_path && errno == ENOEXEC) {
7578 /* Run "cmd" as a shell script:
7579 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7580 * "If the execve() function fails with ENOEXEC, the shell
7581 * shall execute a command equivalent to having a shell invoked
7582 * with the command name as its first operand,
7583 * with any remaining arguments passed to the new shell"
7585 * That is, do not use $SHELL, user's shell, or /bin/sh;
7586 * just call ourselves.
7588 * Note that bash reads ~80 chars of the file, and if it sees
7589 * a zero byte before it sees newline, it doesn't try to
7590 * interpret it, but fails with "cannot execute binary file"
7591 * message and exit code 126. For one, this prevents attempts
7592 * to interpret foreign ELF binaries as shell scripts.
7595 cmd = (char*) bb_busybox_exec_path;
7596 /* NB: this is only possible because all callers of shellexec()
7597 * ensure that the argv[-1] slot exists!
7600 argv[0] = (char*) "ash";
7606 * Exec a program. Never returns. If you change this routine, you may
7607 * have to change the find_command routine as well.
7608 * argv[-1] must exist and be writable! See tryexec() for why.
7610 static void shellexec(char **, const char *, int) NORETURN;
7612 shellexec(char **argv, const char *path, int idx)
7618 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7620 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7621 if (strchr(argv[0], '/') != NULL
7622 #if ENABLE_FEATURE_SH_STANDALONE
7623 || (applet_no = find_applet_by_name(argv[0])) >= 0
7626 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7627 if (applet_no >= 0) {
7628 /* We tried execing ourself, but it didn't work.
7629 * Maybe /proc/self/exe doesn't exist?
7638 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7639 if (--idx < 0 && pathopt == NULL) {
7640 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7641 if (errno != ENOENT && errno != ENOTDIR)
7648 /* Map to POSIX errors */
7660 exitstatus = exerrno;
7661 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7662 argv[0], e, suppress_int));
7663 ash_msg_and_raise(EXEXIT, "%s: %s", argv[0], errmsg(e, "not found"));
7668 printentry(struct tblentry *cmdp)
7674 idx = cmdp->param.index;
7677 name = path_advance(&path, cmdp->cmdname);
7679 } while (--idx >= 0);
7680 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7684 * Clear out command entries. The argument specifies the first entry in
7685 * PATH which has changed.
7688 clearcmdentry(int firstchange)
7690 struct tblentry **tblp;
7691 struct tblentry **pp;
7692 struct tblentry *cmdp;
7695 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7697 while ((cmdp = *pp) != NULL) {
7698 if ((cmdp->cmdtype == CMDNORMAL &&
7699 cmdp->param.index >= firstchange)
7700 || (cmdp->cmdtype == CMDBUILTIN &&
7701 builtinloc >= firstchange)
7714 * Locate a command in the command hash table. If "add" is nonzero,
7715 * add the command to the table if it is not already present. The
7716 * variable "lastcmdentry" is set to point to the address of the link
7717 * pointing to the entry, so that delete_cmd_entry can delete the
7720 * Interrupts must be off if called with add != 0.
7722 static struct tblentry **lastcmdentry;
7724 static struct tblentry *
7725 cmdlookup(const char *name, int add)
7727 unsigned int hashval;
7729 struct tblentry *cmdp;
7730 struct tblentry **pp;
7733 hashval = (unsigned char)*p << 4;
7735 hashval += (unsigned char)*p++;
7737 pp = &cmdtable[hashval % CMDTABLESIZE];
7738 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7739 if (strcmp(cmdp->cmdname, name) == 0)
7743 if (add && cmdp == NULL) {
7744 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7746 /* + 1 - already done because
7747 * tblentry::cmdname is char[1] */);
7748 /*cmdp->next = NULL; - ckzalloc did it */
7749 cmdp->cmdtype = CMDUNKNOWN;
7750 strcpy(cmdp->cmdname, name);
7757 * Delete the command entry returned on the last lookup.
7760 delete_cmd_entry(void)
7762 struct tblentry *cmdp;
7765 cmdp = *lastcmdentry;
7766 *lastcmdentry = cmdp->next;
7767 if (cmdp->cmdtype == CMDFUNCTION)
7768 freefunc(cmdp->param.func);
7774 * Add a new command entry, replacing any existing command entry for
7775 * the same name - except special builtins.
7778 addcmdentry(char *name, struct cmdentry *entry)
7780 struct tblentry *cmdp;
7782 cmdp = cmdlookup(name, 1);
7783 if (cmdp->cmdtype == CMDFUNCTION) {
7784 freefunc(cmdp->param.func);
7786 cmdp->cmdtype = entry->cmdtype;
7787 cmdp->param = entry->u;
7791 static int FAST_FUNC
7792 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7794 struct tblentry **pp;
7795 struct tblentry *cmdp;
7797 struct cmdentry entry;
7800 if (nextopt("r") != '\0') {
7805 if (*argptr == NULL) {
7806 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7807 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7808 if (cmdp->cmdtype == CMDNORMAL)
7816 while ((name = *argptr) != NULL) {
7817 cmdp = cmdlookup(name, 0);
7819 && (cmdp->cmdtype == CMDNORMAL
7820 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7824 find_command(name, &entry, DO_ERR, pathval());
7825 if (entry.cmdtype == CMDUNKNOWN)
7833 * Called when a cd is done. Marks all commands so the next time they
7834 * are executed they will be rehashed.
7839 struct tblentry **pp;
7840 struct tblentry *cmdp;
7842 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7843 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7844 if (cmdp->cmdtype == CMDNORMAL
7845 || (cmdp->cmdtype == CMDBUILTIN
7846 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7856 * Fix command hash table when PATH changed.
7857 * Called before PATH is changed. The argument is the new value of PATH;
7858 * pathval() still returns the old value at this point.
7859 * Called with interrupts off.
7861 static void FAST_FUNC
7862 changepath(const char *new)
7870 firstchange = 9999; /* assume no change */
7876 if ((*old == '\0' && *new == ':')
7877 || (*old == ':' && *new == '\0')
7881 old = new; /* ignore subsequent differences */
7885 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7892 if (builtinloc < 0 && idx_bltin >= 0)
7893 builtinloc = idx_bltin; /* zap builtins */
7894 if (builtinloc >= 0 && idx_bltin < 0)
7896 clearcmdentry(firstchange);
7897 builtinloc = idx_bltin;
7922 #if ENABLE_ASH_BASH_COMPAT
7933 typedef smallint token_id_t;
7935 /* Nth bit indicates if token marks the end of a list */
7938 /* 0 */ | (1u << TEOF)
7939 /* 1 */ | (0u << TNL)
7940 /* 2 */ | (0u << TREDIR)
7941 /* 3 */ | (0u << TWORD)
7942 /* 4 */ | (0u << TSEMI)
7943 /* 5 */ | (0u << TBACKGND)
7944 /* 6 */ | (0u << TAND)
7945 /* 7 */ | (0u << TOR)
7946 /* 8 */ | (0u << TPIPE)
7947 /* 9 */ | (0u << TLP)
7948 /* 10 */ | (1u << TRP)
7949 /* 11 */ | (1u << TENDCASE)
7950 /* 12 */ | (1u << TENDBQUOTE)
7951 /* 13 */ | (0u << TNOT)
7952 /* 14 */ | (0u << TCASE)
7953 /* 15 */ | (1u << TDO)
7954 /* 16 */ | (1u << TDONE)
7955 /* 17 */ | (1u << TELIF)
7956 /* 18 */ | (1u << TELSE)
7957 /* 19 */ | (1u << TESAC)
7958 /* 20 */ | (1u << TFI)
7959 /* 21 */ | (0u << TFOR)
7960 #if ENABLE_ASH_BASH_COMPAT
7961 /* 22 */ | (0u << TFUNCTION)
7963 /* 23 */ | (0u << TIF)
7964 /* 24 */ | (0u << TIN)
7965 /* 25 */ | (1u << TTHEN)
7966 /* 26 */ | (0u << TUNTIL)
7967 /* 27 */ | (0u << TWHILE)
7968 /* 28 */ | (0u << TBEGIN)
7969 /* 29 */ | (1u << TEND)
7970 , /* thus far 29 bits used */
7973 static const char *const tokname_array[] = {
7987 #define KWDOFFSET 13
7988 /* the following are keywords */
7998 #if ENABLE_ASH_BASH_COMPAT
8010 /* Wrapper around strcmp for qsort/bsearch/... */
8012 pstrcmp(const void *a, const void *b)
8014 return strcmp((char*)a, *(char**)b);
8017 static const char *const *
8018 findkwd(const char *s)
8020 return bsearch(s, tokname_array + KWDOFFSET,
8021 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8022 sizeof(tokname_array[0]), pstrcmp);
8026 * Locate and print what a word is...
8029 describe_command(char *command, const char *path, int describe_command_verbose)
8031 struct cmdentry entry;
8032 struct tblentry *cmdp;
8033 #if ENABLE_ASH_ALIAS
8034 const struct alias *ap;
8037 path = path ? path : pathval();
8039 if (describe_command_verbose) {
8043 /* First look at the keywords */
8044 if (findkwd(command)) {
8045 out1str(describe_command_verbose ? " is a shell keyword" : command);
8049 #if ENABLE_ASH_ALIAS
8050 /* Then look at the aliases */
8051 ap = lookupalias(command, 0);
8053 if (!describe_command_verbose) {
8058 out1fmt(" is an alias for %s", ap->val);
8062 /* Then check if it is a tracked alias */
8063 cmdp = cmdlookup(command, 0);
8065 entry.cmdtype = cmdp->cmdtype;
8066 entry.u = cmdp->param;
8068 /* Finally use brute force */
8069 find_command(command, &entry, DO_ABS, path);
8072 switch (entry.cmdtype) {
8074 int j = entry.u.index;
8080 p = path_advance(&path, command);
8084 if (describe_command_verbose) {
8086 (cmdp ? " a tracked alias for" : nullstr), p
8095 if (describe_command_verbose) {
8096 out1str(" is a shell function");
8103 if (describe_command_verbose) {
8104 out1fmt(" is a %sshell builtin",
8105 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8106 "special " : nullstr
8114 if (describe_command_verbose) {
8115 out1str(": not found\n");
8124 static int FAST_FUNC
8125 typecmd(int argc UNUSED_PARAM, char **argv)
8131 /* type -p ... ? (we don't bother checking for 'p') */
8132 if (argv[1] && argv[1][0] == '-') {
8137 err |= describe_command(argv[i++], NULL, verbose);
8142 #if ENABLE_ASH_CMDCMD
8143 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8145 parse_command_args(char **argv, const char **path)
8158 if (c == '-' && !*cp) {
8166 *path = bb_default_path;
8169 /* run 'typecmd' for other options */
8178 static int FAST_FUNC
8179 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8187 const char *path = NULL;
8189 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8190 * never reaches this function.
8193 while ((c = nextopt("pvV")) != '\0')
8195 verify |= VERIFY_VERBOSE;
8197 /*verify |= VERIFY_BRIEF*/;
8203 path = bb_default_path;
8205 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8207 if (/*verify && */ cmd)
8208 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8215 /*static int funcblocksize; // size of structures in function */
8216 /*static int funcstringsize; // size of strings in node */
8217 static void *funcblock; /* block to allocate function from */
8218 static char *funcstring_end; /* end of block to allocate strings from */
8220 /* flags in argument to evaltree */
8221 #define EV_EXIT 01 /* exit after evaluating tree */
8222 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8224 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8225 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8226 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8227 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8228 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8229 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8230 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8231 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8232 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8233 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8234 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8235 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8236 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8237 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8238 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8239 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8240 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8241 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8242 #if ENABLE_ASH_BASH_COMPAT
8243 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8245 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8246 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8247 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8248 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8249 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8250 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8251 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8252 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8253 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8256 static int calcsize(int funcblocksize, union node *n);
8259 sizenodelist(int funcblocksize, struct nodelist *lp)
8262 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8263 funcblocksize = calcsize(funcblocksize, lp->n);
8266 return funcblocksize;
8270 calcsize(int funcblocksize, union node *n)
8273 return funcblocksize;
8274 funcblocksize += nodesize[n->type];
8277 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8278 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8279 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8282 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8287 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8288 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8295 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8296 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8299 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8300 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8301 funcblocksize = calcsize(funcblocksize, n->nif.test);
8304 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8305 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8306 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8309 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8310 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8313 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8314 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8315 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8319 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8320 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8321 funcblocksize = calcsize(funcblocksize, n->narg.next);
8324 #if ENABLE_ASH_BASH_COMPAT
8331 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8332 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8336 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8337 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8341 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8342 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8345 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8348 return funcblocksize;
8352 nodeckstrdup(char *s)
8354 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8355 return strcpy(funcstring_end, s);
8358 static union node *copynode(union node *);
8360 static struct nodelist *
8361 copynodelist(struct nodelist *lp)
8363 struct nodelist *start;
8364 struct nodelist **lpp;
8369 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8370 (*lpp)->n = copynode(lp->n);
8372 lpp = &(*lpp)->next;
8379 copynode(union node *n)
8386 funcblock = (char *) funcblock + nodesize[n->type];
8390 new->ncmd.redirect = copynode(n->ncmd.redirect);
8391 new->ncmd.args = copynode(n->ncmd.args);
8392 new->ncmd.assign = copynode(n->ncmd.assign);
8395 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8396 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8401 new->nredir.redirect = copynode(n->nredir.redirect);
8402 new->nredir.n = copynode(n->nredir.n);
8409 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8410 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8413 new->nif.elsepart = copynode(n->nif.elsepart);
8414 new->nif.ifpart = copynode(n->nif.ifpart);
8415 new->nif.test = copynode(n->nif.test);
8418 new->nfor.var = nodeckstrdup(n->nfor.var);
8419 new->nfor.body = copynode(n->nfor.body);
8420 new->nfor.args = copynode(n->nfor.args);
8423 new->ncase.cases = copynode(n->ncase.cases);
8424 new->ncase.expr = copynode(n->ncase.expr);
8427 new->nclist.body = copynode(n->nclist.body);
8428 new->nclist.pattern = copynode(n->nclist.pattern);
8429 new->nclist.next = copynode(n->nclist.next);
8433 new->narg.backquote = copynodelist(n->narg.backquote);
8434 new->narg.text = nodeckstrdup(n->narg.text);
8435 new->narg.next = copynode(n->narg.next);
8438 #if ENABLE_ASH_BASH_COMPAT
8445 new->nfile.fname = copynode(n->nfile.fname);
8446 new->nfile.fd = n->nfile.fd;
8447 new->nfile.next = copynode(n->nfile.next);
8451 new->ndup.vname = copynode(n->ndup.vname);
8452 new->ndup.dupfd = n->ndup.dupfd;
8453 new->ndup.fd = n->ndup.fd;
8454 new->ndup.next = copynode(n->ndup.next);
8458 new->nhere.doc = copynode(n->nhere.doc);
8459 new->nhere.fd = n->nhere.fd;
8460 new->nhere.next = copynode(n->nhere.next);
8463 new->nnot.com = copynode(n->nnot.com);
8466 new->type = n->type;
8471 * Make a copy of a parse tree.
8473 static struct funcnode *
8474 copyfunc(union node *n)
8479 /*funcstringsize = 0;*/
8480 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8481 f = ckzalloc(blocksize /* + funcstringsize */);
8482 funcblock = (char *) f + offsetof(struct funcnode, n);
8483 funcstring_end = (char *) f + blocksize;
8485 /* f->count = 0; - ckzalloc did it */
8490 * Define a shell function.
8493 defun(union node *func)
8495 struct cmdentry entry;
8498 entry.cmdtype = CMDFUNCTION;
8499 entry.u.func = copyfunc(func);
8500 addcmdentry(func->narg.text, &entry);
8504 /* Reasons for skipping commands (see comment on breakcmd routine) */
8505 #define SKIPBREAK (1 << 0)
8506 #define SKIPCONT (1 << 1)
8507 #define SKIPFUNC (1 << 2)
8508 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8509 static int skipcount; /* number of levels to skip */
8510 static int funcnest; /* depth of function calls */
8511 static int loopnest; /* current loop nesting level */
8513 /* Forward decl way out to parsing code - dotrap needs it */
8514 static int evalstring(char *s, int flags);
8516 /* Called to execute a trap.
8517 * Single callsite - at the end of evaltree().
8518 * If we return non-zero, evaltree raises EXEXIT exception.
8520 * Perhaps we should avoid entering new trap handlers
8521 * while we are executing a trap handler. [is it a TODO?]
8528 uint8_t last_status;
8533 last_status = exitstatus;
8537 TRACE(("dotrap entered\n"));
8538 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8550 /* non-trapped SIGINT is handled separately by raise_interrupt,
8551 * don't upset it by resetting gotsig[SIGINT-1] */
8552 if (sig == SIGINT && !p)
8555 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8561 exitstatus = last_status;
8562 TRACE(("dotrap returns\n"));
8565 /* forward declarations - evaluation is fairly recursive business... */
8566 static int evalloop(union node *, int);
8567 static int evalfor(union node *, int);
8568 static int evalcase(union node *, int);
8569 static int evalsubshell(union node *, int);
8570 static void expredir(union node *);
8571 static int evalpipe(union node *, int);
8572 static int evalcommand(union node *, int);
8573 static int evalbltin(const struct builtincmd *, int, char **, int);
8574 static void prehash(union node *);
8577 * Evaluate a parse tree. The value is left in the global variable
8581 evaltree(union node *n, int flags)
8584 int (*evalfn)(union node *, int);
8588 TRACE(("evaltree(NULL) called\n"));
8591 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8598 out1fmt("Node type = %d\n", n->type);
8603 status = !evaltree(n->nnot.com, EV_TESTED);
8606 expredir(n->nredir.redirect);
8607 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8609 status = evaltree(n->nredir.n, flags & EV_TESTED);
8611 if (n->nredir.redirect)
8612 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8615 evalfn = evalcommand;
8617 if (eflag && !(flags & EV_TESTED))
8629 evalfn = evalsubshell;
8642 #error NAND + 1 != NOR
8644 #if NOR + 1 != NSEMI
8645 #error NOR + 1 != NSEMI
8647 unsigned is_or = n->type - NAND;
8650 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8652 if ((!status) == is_or || evalskip)
8658 status = evalfn(n, flags);
8662 status = evaltree(n->nif.test, EV_TESTED);
8669 if (n->nif.elsepart) {
8670 n = n->nif.elsepart;
8677 /* Not necessary. To test it:
8678 * "false; f() { qwerty; }; echo $?" should print 0.
8682 exitstatus = status;
8686 /* Order of checks below is important:
8687 * signal handlers trigger before exit caused by "set -e".
8691 if (checkexit & status)
8692 raise_exception(EXEXIT);
8693 if (flags & EV_EXIT)
8694 raise_exception(EXEXIT);
8696 TRACE(("leaving evaltree (no interrupts)\n"));
8700 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8703 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8708 int skip = evalskip;
8715 if (--skipcount <= 0) {
8726 evalloop(union node *n, int flags)
8737 i = evaltree(n->nbinary.ch1, EV_TESTED);
8739 if (skip == SKIPFUNC)
8743 if (n->type != NWHILE)
8747 status = evaltree(n->nbinary.ch2, flags);
8749 } while (!(skip & ~SKIPCONT));
8756 evalfor(union node *n, int flags)
8758 struct arglist arglist;
8761 struct stackmark smark;
8764 setstackmark(&smark);
8765 arglist.list = NULL;
8766 arglist.lastp = &arglist.list;
8767 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8768 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8770 *arglist.lastp = NULL;
8774 for (sp = arglist.list; sp; sp = sp->next) {
8775 setvar0(n->nfor.var, sp->text);
8776 status = evaltree(n->nfor.body, flags);
8777 if (skiploop() & ~SKIPCONT)
8781 popstackmark(&smark);
8787 evalcase(union node *n, int flags)
8791 struct arglist arglist;
8792 struct stackmark smark;
8795 setstackmark(&smark);
8796 arglist.list = NULL;
8797 arglist.lastp = &arglist.list;
8798 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8799 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8800 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8801 if (casematch(patp, arglist.list->text)) {
8802 /* Ensure body is non-empty as otherwise
8803 * EV_EXIT may prevent us from setting the
8806 if (evalskip == 0 && cp->nclist.body) {
8807 status = evaltree(cp->nclist.body, flags);
8814 popstackmark(&smark);
8820 * Kick off a subshell to evaluate a tree.
8823 evalsubshell(union node *n, int flags)
8826 int backgnd = (n->type == NBACKGND);
8829 expredir(n->nredir.redirect);
8830 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8833 jp = makejob(/*n,*/ 1);
8834 if (forkshell(jp, n, backgnd) == 0) {
8839 flags &= ~EV_TESTED;
8841 redirect(n->nredir.redirect, 0);
8842 evaltreenr(n->nredir.n, flags);
8848 status = waitforjob(jp);
8854 * Compute the names of the files in a redirection list.
8856 static void fixredir(union node *, const char *, int);
8858 expredir(union node *n)
8862 for (redir = n; redir; redir = redir->nfile.next) {
8866 fn.lastp = &fn.list;
8867 switch (redir->type) {
8871 #if ENABLE_ASH_BASH_COMPAT
8876 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8877 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8878 #if ENABLE_ASH_BASH_COMPAT
8882 // By the design of stack allocator, the loop of this kind:
8883 // while true; do while true; do break; done </dev/null; done
8884 // will look like a memory leak: ash plans to free expfname's
8885 // of "/dev/null" as soon as it finishes running the loop
8886 // (in this case, never).
8887 // This "fix" is wrong:
8888 if (redir->nfile.expfname)
8889 stunalloc(redir->nfile.expfname);
8890 // It results in corrupted state of stacked allocations.
8892 redir->nfile.expfname = fn.list->text;
8895 case NTOFD: /* >& */
8896 if (redir->ndup.vname) {
8897 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8898 if (fn.list == NULL)
8899 ash_msg_and_raise_error("redir error");
8900 #if ENABLE_ASH_BASH_COMPAT
8901 //FIXME: we used expandarg with different args!
8902 if (!isdigit_str9(fn.list->text)) {
8903 /* >&file, not >&fd */
8904 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8905 ash_msg_and_raise_error("redir error");
8907 goto store_expfname;
8910 fixredir(redir, fn.list->text, 1);
8918 * Evaluate a pipeline. All the processes in the pipeline are children
8919 * of the process creating the pipeline. (This differs from some versions
8920 * of the shell, which make the last process in a pipeline the parent
8924 evalpipe(union node *n, int flags)
8927 struct nodelist *lp;
8933 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8935 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8939 jp = makejob(/*n,*/ pipelen);
8941 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8945 if (pipe(pip) < 0) {
8947 ash_msg_and_raise_error("pipe call failed");
8950 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8964 evaltreenr(lp->n, flags);
8971 /* Don't want to trigger debugging */
8975 if (n->npipe.pipe_backgnd == 0) {
8976 status = waitforjob(jp);
8977 TRACE(("evalpipe: job done exit status %d\n", status));
8985 * Controls whether the shell is interactive or not.
8988 setinteractive(int on)
8990 static smallint is_interactive;
8992 if (++on == is_interactive)
8994 is_interactive = on;
8998 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8999 if (is_interactive > 1) {
9000 /* Looks like they want an interactive shell */
9001 static smallint did_banner;
9004 /* note: ash and hush share this string */
9005 out1fmt("\n\n%s %s\n"
9006 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9009 "built-in shell (ash)"
9023 setinteractive(iflag);
9025 #if ENABLE_FEATURE_EDITING_VI
9027 line_input_state->flags |= VI_MODE;
9029 line_input_state->flags &= ~VI_MODE;
9031 viflag = 0; /* forcibly keep the option off */
9035 static struct localvar *localvars;
9038 * Called after a function returns.
9039 * Interrupts must be off.
9044 struct localvar *lvp;
9047 while ((lvp = localvars) != NULL) {
9048 localvars = lvp->next;
9050 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9051 if (vp == NULL) { /* $- saved */
9052 memcpy(optlist, lvp->text, sizeof(optlist));
9053 free((char*)lvp->text);
9055 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
9056 unsetvar(vp->var_text);
9059 vp->var_func(var_end(lvp->text));
9060 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9061 free((char*)vp->var_text);
9062 vp->flags = lvp->flags;
9063 vp->var_text = lvp->text;
9070 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9072 volatile struct shparam saveparam;
9073 struct localvar *volatile savelocalvars;
9074 struct jmploc *volatile savehandler;
9075 struct jmploc jmploc;
9078 saveparam = shellparam;
9079 savelocalvars = localvars;
9080 savehandler = exception_handler;
9081 e = setjmp(jmploc.loc);
9086 exception_handler = &jmploc;
9088 shellparam.malloced = 0;
9092 shellparam.nparam = argc - 1;
9093 shellparam.p = argv + 1;
9094 #if ENABLE_ASH_GETOPTS
9095 shellparam.optind = 1;
9096 shellparam.optoff = -1;
9098 evaltree(func->n.narg.next, flags & EV_TESTED);
9104 localvars = savelocalvars;
9105 freeparam(&shellparam);
9106 shellparam = saveparam;
9107 exception_handler = savehandler;
9109 evalskip &= ~SKIPFUNC;
9114 * Make a variable a local variable. When a variable is made local, it's
9115 * value and flags are saved in a localvar structure. The saved values
9116 * will be restored when the shell function returns. We handle the name
9117 * "-" as a special case: it makes changes to "set +-options" local
9118 * (options will be restored on return from the function).
9123 struct localvar *lvp;
9126 char *eq = strchr(name, '=');
9129 /* Cater for duplicate "local". Examples:
9130 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9131 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9135 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9139 * it's a duplicate "local VAR" declaration, do nothing
9146 lvp = ckzalloc(sizeof(*lvp));
9147 if (LONE_DASH(name)) {
9149 p = ckmalloc(sizeof(optlist));
9150 lvp->text = memcpy(p, optlist, sizeof(optlist));
9153 vpp = hashvar(name);
9154 vp = *findvar(vpp, name);
9156 /* variable did not exist yet */
9158 setvareq(name, VSTRFIXED);
9160 setvar(name, NULL, VSTRFIXED);
9161 vp = *vpp; /* the new variable */
9162 lvp->flags = VUNSET;
9164 lvp->text = vp->var_text;
9165 lvp->flags = vp->flags;
9166 /* make sure neither "struct var" nor string gets freed
9167 * during (un)setting:
9169 vp->flags |= VSTRFIXED|VTEXTFIXED;
9173 /* "local VAR" unsets VAR: */
9174 setvar0(name, NULL);
9178 lvp->next = localvars;
9185 * The "local" command.
9187 static int FAST_FUNC
9188 localcmd(int argc UNUSED_PARAM, char **argv)
9193 ash_msg_and_raise_error("not in a function");
9196 while ((name = *argv++) != NULL) {
9202 static int FAST_FUNC
9203 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9208 static int FAST_FUNC
9209 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9214 static int FAST_FUNC
9215 execcmd(int argc UNUSED_PARAM, char **argv)
9218 iflag = 0; /* exit on error */
9221 /* We should set up signals for "exec CMD"
9222 * the same way as for "CMD" without "exec".
9223 * But optschanged->setinteractive->setsignal
9224 * still thought we are a root shell. Therefore, for example,
9225 * SIGQUIT is still set to IGN. Fix it:
9229 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9230 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9231 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9233 shellexec(argv + 1, pathval(), 0);
9240 * The return command.
9242 static int FAST_FUNC
9243 returncmd(int argc UNUSED_PARAM, char **argv)
9246 * If called outside a function, do what ksh does;
9247 * skip the rest of the file.
9249 evalskip = SKIPFUNC;
9250 return argv[1] ? number(argv[1]) : exitstatus;
9253 /* Forward declarations for builtintab[] */
9254 static int breakcmd(int, char **) FAST_FUNC;
9255 static int dotcmd(int, char **) FAST_FUNC;
9256 static int evalcmd(int, char **, int) FAST_FUNC;
9257 static int exitcmd(int, char **) FAST_FUNC;
9258 static int exportcmd(int, char **) FAST_FUNC;
9259 #if ENABLE_ASH_GETOPTS
9260 static int getoptscmd(int, char **) FAST_FUNC;
9263 static int helpcmd(int, char **) FAST_FUNC;
9266 static int historycmd(int, char **) FAST_FUNC;
9268 #if ENABLE_SH_MATH_SUPPORT
9269 static int letcmd(int, char **) FAST_FUNC;
9271 static int readcmd(int, char **) FAST_FUNC;
9272 static int setcmd(int, char **) FAST_FUNC;
9273 static int shiftcmd(int, char **) FAST_FUNC;
9274 static int timescmd(int, char **) FAST_FUNC;
9275 static int trapcmd(int, char **) FAST_FUNC;
9276 static int umaskcmd(int, char **) FAST_FUNC;
9277 static int unsetcmd(int, char **) FAST_FUNC;
9278 static int ulimitcmd(int, char **) FAST_FUNC;
9280 #define BUILTIN_NOSPEC "0"
9281 #define BUILTIN_SPECIAL "1"
9282 #define BUILTIN_REGULAR "2"
9283 #define BUILTIN_SPEC_REG "3"
9284 #define BUILTIN_ASSIGN "4"
9285 #define BUILTIN_SPEC_ASSG "5"
9286 #define BUILTIN_REG_ASSG "6"
9287 #define BUILTIN_SPEC_REG_ASSG "7"
9289 /* Stubs for calling non-FAST_FUNC's */
9290 #if ENABLE_ASH_BUILTIN_ECHO
9291 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9293 #if ENABLE_ASH_BUILTIN_PRINTF
9294 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9296 #if ENABLE_ASH_BUILTIN_TEST
9297 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9300 /* Keep these in proper order since it is searched via bsearch() */
9301 static const struct builtincmd builtintab[] = {
9302 { BUILTIN_SPEC_REG "." , dotcmd },
9303 { BUILTIN_SPEC_REG ":" , truecmd },
9304 #if ENABLE_ASH_BUILTIN_TEST
9305 { BUILTIN_REGULAR "[" , testcmd },
9306 # if ENABLE_ASH_BASH_COMPAT
9307 { BUILTIN_REGULAR "[[" , testcmd },
9310 #if ENABLE_ASH_ALIAS
9311 { BUILTIN_REG_ASSG "alias" , aliascmd },
9314 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9316 { BUILTIN_SPEC_REG "break" , breakcmd },
9317 { BUILTIN_REGULAR "cd" , cdcmd },
9318 { BUILTIN_NOSPEC "chdir" , cdcmd },
9319 #if ENABLE_ASH_CMDCMD
9320 { BUILTIN_REGULAR "command" , commandcmd },
9322 { BUILTIN_SPEC_REG "continue", breakcmd },
9323 #if ENABLE_ASH_BUILTIN_ECHO
9324 { BUILTIN_REGULAR "echo" , echocmd },
9326 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9327 { BUILTIN_SPEC_REG "exec" , execcmd },
9328 { BUILTIN_SPEC_REG "exit" , exitcmd },
9329 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9330 { BUILTIN_REGULAR "false" , falsecmd },
9332 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9334 #if ENABLE_ASH_GETOPTS
9335 { BUILTIN_REGULAR "getopts" , getoptscmd },
9337 { BUILTIN_NOSPEC "hash" , hashcmd },
9339 { BUILTIN_NOSPEC "help" , helpcmd },
9342 { BUILTIN_NOSPEC "history" , historycmd },
9345 { BUILTIN_REGULAR "jobs" , jobscmd },
9346 { BUILTIN_REGULAR "kill" , killcmd },
9348 #if ENABLE_SH_MATH_SUPPORT
9349 { BUILTIN_NOSPEC "let" , letcmd },
9351 { BUILTIN_ASSIGN "local" , localcmd },
9352 #if ENABLE_ASH_BUILTIN_PRINTF
9353 { BUILTIN_REGULAR "printf" , printfcmd },
9355 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9356 { BUILTIN_REGULAR "read" , readcmd },
9357 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9358 { BUILTIN_SPEC_REG "return" , returncmd },
9359 { BUILTIN_SPEC_REG "set" , setcmd },
9360 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9361 #if ENABLE_ASH_BASH_COMPAT
9362 { BUILTIN_SPEC_REG "source" , dotcmd },
9364 #if ENABLE_ASH_BUILTIN_TEST
9365 { BUILTIN_REGULAR "test" , testcmd },
9367 { BUILTIN_SPEC_REG "times" , timescmd },
9368 { BUILTIN_SPEC_REG "trap" , trapcmd },
9369 { BUILTIN_REGULAR "true" , truecmd },
9370 { BUILTIN_NOSPEC "type" , typecmd },
9371 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9372 { BUILTIN_REGULAR "umask" , umaskcmd },
9373 #if ENABLE_ASH_ALIAS
9374 { BUILTIN_REGULAR "unalias" , unaliascmd },
9376 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9377 { BUILTIN_REGULAR "wait" , waitcmd },
9380 /* Should match the above table! */
9381 #define COMMANDCMD (builtintab + \
9383 /* [ */ 1 * ENABLE_ASH_BUILTIN_TEST + \
9384 /* [[ */ 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9385 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9386 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9387 /* break cd cddir */ 3)
9388 #define EVALCMD (COMMANDCMD + \
9389 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9390 /* continue */ 1 + \
9391 /* echo */ 1 * ENABLE_ASH_BUILTIN_ECHO + \
9393 #define EXECCMD (EVALCMD + \
9397 * Search the table of builtin commands.
9400 pstrcmp1(const void *a, const void *b)
9402 return strcmp((char*)a, *(char**)b + 1);
9404 static struct builtincmd *
9405 find_builtin(const char *name)
9407 struct builtincmd *bp;
9410 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9417 * Execute a simple command.
9420 isassignment(const char *p)
9422 const char *q = endofname(p);
9427 static int FAST_FUNC
9428 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9430 /* Preserve exitstatus of a previous possible redirection
9431 * as POSIX mandates */
9432 return back_exitstatus;
9435 evalcommand(union node *cmd, int flags)
9437 static const struct builtincmd null_bltin = {
9438 "\0\0", bltincmd /* why three NULs? */
9440 struct stackmark smark;
9442 struct arglist arglist;
9443 struct arglist varlist;
9446 const struct strlist *sp;
9447 struct cmdentry cmdentry;
9454 struct builtincmd *bcmd;
9455 smallint cmd_is_exec;
9456 smallint pseudovarflag = 0;
9458 /* First expand the arguments. */
9459 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9460 setstackmark(&smark);
9461 back_exitstatus = 0;
9463 cmdentry.cmdtype = CMDBUILTIN;
9464 cmdentry.u.cmd = &null_bltin;
9465 varlist.lastp = &varlist.list;
9466 *varlist.lastp = NULL;
9467 arglist.lastp = &arglist.list;
9468 *arglist.lastp = NULL;
9471 if (cmd->ncmd.args) {
9472 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9473 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9476 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9477 struct strlist **spp;
9479 spp = arglist.lastp;
9480 if (pseudovarflag && isassignment(argp->narg.text))
9481 expandarg(argp, &arglist, EXP_VARTILDE);
9483 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9485 for (sp = *spp; sp; sp = sp->next)
9489 /* Reserve one extra spot at the front for shellexec. */
9490 nargv = stalloc(sizeof(char *) * (argc + 2));
9492 for (sp = arglist.list; sp; sp = sp->next) {
9493 TRACE(("evalcommand arg: %s\n", sp->text));
9494 *nargv++ = sp->text;
9499 if (iflag && funcnest == 0 && argc > 0)
9500 lastarg = nargv[-1];
9503 expredir(cmd->ncmd.redirect);
9504 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9506 path = vpath.var_text;
9507 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9508 struct strlist **spp;
9511 spp = varlist.lastp;
9512 expandarg(argp, &varlist, EXP_VARTILDE);
9515 * Modify the command lookup path, if a PATH= assignment
9519 if (varcmp(p, path) == 0)
9523 /* Print the command if xflag is set. */
9526 const char *p = " %s" + 1;
9528 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9530 for (n = 0; n < 2; n++) {
9532 fdprintf(preverrout_fd, p, sp->text);
9538 safe_write(preverrout_fd, "\n", 1);
9544 /* Now locate the command. */
9546 int cmd_flag = DO_ERR;
9547 #if ENABLE_ASH_CMDCMD
9548 const char *oldpath = path + 5;
9552 find_command(argv[0], &cmdentry, cmd_flag, path);
9553 if (cmdentry.cmdtype == CMDUNKNOWN) {
9554 flush_stdout_stderr();
9559 /* implement bltin and command here */
9560 if (cmdentry.cmdtype != CMDBUILTIN)
9563 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9564 if (cmdentry.u.cmd == EXECCMD)
9566 #if ENABLE_ASH_CMDCMD
9567 if (cmdentry.u.cmd == COMMANDCMD) {
9569 nargv = parse_command_args(argv, &path);
9572 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9573 * nargv => "PROG". path is updated if -p.
9575 argc -= nargv - argv;
9577 cmd_flag |= DO_NOFUNC;
9585 /* We have a redirection error. */
9587 raise_exception(EXERROR);
9589 exitstatus = status;
9593 /* Execute the command. */
9594 switch (cmdentry.cmdtype) {
9597 #if ENABLE_FEATURE_SH_NOFORK
9598 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9599 * around run_nofork_applet() call.
9600 * (2) Should this check also be done in forkshell()?
9601 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9603 /* find_command() encodes applet_no as (-2 - applet_no) */
9604 int applet_no = (- cmdentry.u.index - 2);
9605 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9606 listsetvar(varlist.list, VEXPORT|VSTACK);
9607 /* run <applet>_main() */
9608 status = run_nofork_applet(applet_no, argv);
9612 /* Can we avoid forking off? For example, very last command
9613 * in a script or a subshell does not need forking,
9614 * we can just exec it.
9616 if (!(flags & EV_EXIT) || may_have_traps) {
9617 /* No, forking off a child is necessary */
9619 jp = makejob(/*cmd,*/ 1);
9620 if (forkshell(jp, cmd, FORK_FG) != 0) {
9622 status = waitforjob(jp);
9624 TRACE(("forked child exited with %d\n", status));
9629 /* fall through to exec'ing external program */
9631 listsetvar(varlist.list, VEXPORT|VSTACK);
9632 shellexec(argv, path, cmdentry.u.index);
9636 cmdenviron = varlist.list;
9638 struct strlist *list = cmdenviron;
9640 if (spclbltin > 0 || argc == 0) {
9642 if (cmd_is_exec && argc > 1)
9645 listsetvar(list, i);
9647 /* Tight loop with builtins only:
9648 * "while kill -0 $child; do true; done"
9649 * will never exit even if $child died, unless we do this
9650 * to reap the zombie and make kill detect that it's gone: */
9651 dowait(DOWAIT_NONBLOCK, NULL);
9653 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9654 if (exception_type == EXERROR && spclbltin <= 0) {
9659 longjmp(exception_handler->loc, 1);
9664 listsetvar(varlist.list, 0);
9665 /* See above for the rationale */
9666 dowait(DOWAIT_NONBLOCK, NULL);
9667 if (evalfun(cmdentry.u.func, argc, argv, flags))
9670 status = exitstatus;
9675 if (cmd->ncmd.redirect)
9676 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9678 /* dsl: I think this is intended to be used to support
9679 * '_' in 'vi' command mode during line editing...
9680 * However I implemented that within libedit itself.
9682 setvar0("_", lastarg);
9684 popstackmark(&smark);
9690 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9692 char *volatile savecmdname;
9693 struct jmploc *volatile savehandler;
9694 struct jmploc jmploc;
9698 savecmdname = commandname;
9699 savehandler = exception_handler;
9700 i = setjmp(jmploc.loc);
9703 exception_handler = &jmploc;
9704 commandname = argv[0];
9706 optptr = NULL; /* initialize nextopt */
9708 status = evalcmd(argc, argv, flags);
9710 status = (*cmd->builtin)(argc, argv);
9711 flush_stdout_stderr();
9712 status |= ferror(stdout);
9713 exitstatus = status;
9716 commandname = savecmdname;
9717 exception_handler = savehandler;
9723 goodname(const char *p)
9725 return endofname(p)[0] == '\0';
9730 * Search for a command. This is called before we fork so that the
9731 * location of the command will be available in the parent as well as
9732 * the child. The check for "goodname" is an overly conservative
9733 * check that the name will not be subject to expansion.
9736 prehash(union node *n)
9738 struct cmdentry entry;
9740 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9741 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9745 /* ============ Builtin commands
9747 * Builtin commands whose functions are closely tied to evaluation
9748 * are implemented here.
9752 * Handle break and continue commands. Break, continue, and return are
9753 * all handled by setting the evalskip flag. The evaluation routines
9754 * above all check this flag, and if it is set they start skipping
9755 * commands rather than executing them. The variable skipcount is
9756 * the number of loops to break/continue, or the number of function
9757 * levels to return. (The latter is always 1.) It should probably
9758 * be an error to break out of more loops than exist, but it isn't
9759 * in the standard shell so we don't make it one here.
9761 static int FAST_FUNC
9762 breakcmd(int argc UNUSED_PARAM, char **argv)
9764 int n = argv[1] ? number(argv[1]) : 1;
9767 ash_msg_and_raise_error(msg_illnum, argv[1]);
9771 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9779 * This implements the input routines used by the parser.
9783 INPUT_PUSH_FILE = 1,
9784 INPUT_NOFILE_OK = 2,
9787 static smallint checkkwd;
9788 /* values of checkkwd variable */
9789 #define CHKALIAS 0x1
9794 * Push a string back onto the input at this current parsefile level.
9795 * We handle aliases this way.
9797 #if !ENABLE_ASH_ALIAS
9798 #define pushstring(s, ap) pushstring(s)
9801 pushstring(char *s, struct alias *ap)
9808 if (g_parsefile->strpush) {
9809 sp = ckzalloc(sizeof(*sp));
9810 sp->prev = g_parsefile->strpush;
9812 sp = &(g_parsefile->basestrpush);
9814 g_parsefile->strpush = sp;
9815 sp->prev_string = g_parsefile->next_to_pgetc;
9816 sp->prev_left_in_line = g_parsefile->left_in_line;
9817 sp->unget = g_parsefile->unget;
9818 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9819 #if ENABLE_ASH_ALIAS
9822 ap->flag |= ALIASINUSE;
9826 g_parsefile->next_to_pgetc = s;
9827 g_parsefile->left_in_line = len;
9828 g_parsefile->unget = 0;
9835 struct strpush *sp = g_parsefile->strpush;
9838 #if ENABLE_ASH_ALIAS
9840 if (g_parsefile->next_to_pgetc[-1] == ' '
9841 || g_parsefile->next_to_pgetc[-1] == '\t'
9843 checkkwd |= CHKALIAS;
9845 if (sp->string != sp->ap->val) {
9848 sp->ap->flag &= ~ALIASINUSE;
9849 if (sp->ap->flag & ALIASDEAD) {
9850 unalias(sp->ap->name);
9854 g_parsefile->next_to_pgetc = sp->prev_string;
9855 g_parsefile->left_in_line = sp->prev_left_in_line;
9856 g_parsefile->unget = sp->unget;
9857 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
9858 g_parsefile->strpush = sp->prev;
9859 if (sp != &(g_parsefile->basestrpush))
9868 char *buf = g_parsefile->buf;
9870 g_parsefile->next_to_pgetc = buf;
9871 #if ENABLE_FEATURE_EDITING
9873 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9874 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9877 # if ENABLE_ASH_IDLE_TIMEOUT
9879 const char *tmout_var = lookupvar("TMOUT");
9881 timeout = atoi(tmout_var) * 1000;
9887 # if ENABLE_FEATURE_TAB_COMPLETION
9888 line_input_state->path_lookup = pathval();
9890 reinit_unicode_for_ash();
9891 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9893 /* ^C pressed, "convert" to SIGINT */
9894 write(STDOUT_FILENO, "^C", 2);
9901 exitstatus = 128 + SIGINT;
9907 /* Ctrl+D pressed */
9910 # if ENABLE_ASH_IDLE_TIMEOUT
9911 else if (errno == EAGAIN && timeout > 0) {
9912 puts("\007timed out waiting for input: auto-logout");
9919 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9922 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9924 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9925 int flags = fcntl(0, F_GETFL);
9926 if (flags >= 0 && (flags & O_NONBLOCK)) {
9927 flags &= ~O_NONBLOCK;
9928 if (fcntl(0, F_SETFL, flags) >= 0) {
9929 out2str("sh: turning off NDELAY mode\n");
9940 * Refill the input buffer and return the next input character:
9942 * 1) If a string was pushed back on the input, pop it;
9943 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9944 * or we are reading from a string so we can't refill the buffer,
9946 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9947 * 4) Process input up to the next newline, deleting nul characters.
9949 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9950 #define pgetc_debug(...) ((void)0)
9951 static int pgetc(void);
9958 if (g_parsefile->strpush) {
9959 #if ENABLE_ASH_ALIAS
9960 if (g_parsefile->left_in_line == -1
9961 && g_parsefile->strpush->ap
9962 && g_parsefile->next_to_pgetc[-1] != ' '
9963 && g_parsefile->next_to_pgetc[-1] != '\t'
9965 pgetc_debug("preadbuffer PEOA");
9972 /* on both branches above g_parsefile->left_in_line < 0.
9973 * "pgetc" needs refilling.
9976 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9977 * pungetc() may increment it a few times.
9978 * Assuming it won't increment it to less than -90.
9980 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9981 pgetc_debug("preadbuffer PEOF1");
9982 /* even in failure keep left_in_line and next_to_pgetc
9983 * in lock step, for correct multi-layer pungetc.
9984 * left_in_line was decremented before preadbuffer(),
9985 * must inc next_to_pgetc: */
9986 g_parsefile->next_to_pgetc++;
9990 more = g_parsefile->left_in_buffer;
9992 flush_stdout_stderr();
9996 /* don't try reading again */
9997 g_parsefile->left_in_line = -99;
9998 pgetc_debug("preadbuffer PEOF2");
9999 g_parsefile->next_to_pgetc++;
10004 /* Find out where's the end of line.
10005 * Set g_parsefile->left_in_line
10006 * and g_parsefile->left_in_buffer acordingly.
10007 * NUL chars are deleted.
10009 q = g_parsefile->next_to_pgetc;
10017 memmove(q, q + 1, more);
10021 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10027 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10028 if (g_parsefile->left_in_line < 0)
10033 g_parsefile->left_in_buffer = more;
10038 out2str(g_parsefile->next_to_pgetc);
10042 pgetc_debug("preadbuffer at %d:%p'%s'",
10043 g_parsefile->left_in_line,
10044 g_parsefile->next_to_pgetc,
10045 g_parsefile->next_to_pgetc);
10046 return (unsigned char)*g_parsefile->next_to_pgetc++;
10052 g_parsefile->linno++;
10053 setprompt_if(doprompt, 2);
10058 g_parsefile->linno++;
10059 needprompt = doprompt;
10067 pgetc_debug("pgetc at %d:%p'%s'",
10068 g_parsefile->left_in_line,
10069 g_parsefile->next_to_pgetc,
10070 g_parsefile->next_to_pgetc);
10071 if (g_parsefile->unget)
10072 return g_parsefile->lastc[--g_parsefile->unget];
10074 if (--g_parsefile->left_in_line >= 0)
10075 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10079 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10080 g_parsefile->lastc[0] = c;
10085 #if ENABLE_ASH_ALIAS
10087 pgetc_without_PEOA(void)
10091 pgetc_debug("pgetc at %d:%p'%s'",
10092 g_parsefile->left_in_line,
10093 g_parsefile->next_to_pgetc,
10094 g_parsefile->next_to_pgetc);
10096 } while (c == PEOA);
10100 # define pgetc_without_PEOA() pgetc()
10104 * Read a line from the script.
10107 pfgets(char *line, int len)
10113 while (--nleft > 0) {
10114 c = pgetc_without_PEOA();
10129 * Undo a call to pgetc. Only two characters may be pushed back.
10130 * PEOF may be pushed back.
10135 g_parsefile->unget++;
10138 /* This one eats backslash+newline */
10144 while ((c = pgetc()) == '\\') {
10145 if (pgetc() != '\n') {
10157 * To handle the "." command, a stack of input files is used. Pushfile
10158 * adds a new entry to the stack and popfile restores the previous level.
10163 struct parsefile *pf;
10165 pf = ckzalloc(sizeof(*pf));
10166 pf->prev = g_parsefile;
10168 /*pf->strpush = NULL; - ckzalloc did it */
10169 /*pf->basestrpush.prev = NULL;*/
10177 struct parsefile *pf = g_parsefile;
10183 if (pf->pf_fd >= 0)
10186 while (pf->strpush)
10188 g_parsefile = pf->prev;
10194 * Return to top level.
10199 while (g_parsefile != &basepf)
10204 * Close the file(s) that the shell is reading commands from. Called
10205 * after a fork is done.
10211 if (g_parsefile->pf_fd > 0) {
10212 close(g_parsefile->pf_fd);
10213 g_parsefile->pf_fd = 0;
10218 * Like setinputfile, but takes an open file descriptor. Call this with
10222 setinputfd(int fd, int push)
10226 g_parsefile->buf = NULL;
10228 g_parsefile->pf_fd = fd;
10229 if (g_parsefile->buf == NULL)
10230 g_parsefile->buf = ckmalloc(IBUFSIZ);
10231 g_parsefile->left_in_buffer = 0;
10232 g_parsefile->left_in_line = 0;
10233 g_parsefile->linno = 1;
10237 * Set the input to take input from a file. If push is set, push the
10238 * old input onto the stack first.
10241 setinputfile(const char *fname, int flags)
10246 fd = open(fname, O_RDONLY);
10248 if (flags & INPUT_NOFILE_OK)
10251 ash_msg_and_raise_error("can't open '%s'", fname);
10256 close_on_exec_on(fd);
10257 setinputfd(fd, flags & INPUT_PUSH_FILE);
10264 * Like setinputfile, but takes input from a string.
10267 setinputstring(char *string)
10271 g_parsefile->next_to_pgetc = string;
10272 g_parsefile->left_in_line = strlen(string);
10273 g_parsefile->buf = NULL;
10274 g_parsefile->linno = 1;
10280 * Routines to check for mail.
10283 #if ENABLE_ASH_MAIL
10285 /* Hash of mtimes of mailboxes */
10286 static unsigned mailtime_hash;
10287 /* Set if MAIL or MAILPATH is changed. */
10288 static smallint mail_var_path_changed;
10291 * Print appropriate message(s) if mail has arrived.
10292 * If mail_var_path_changed is set,
10293 * then the value of MAIL has mail_var_path_changed,
10294 * so we just update the values.
10303 struct stackmark smark;
10306 setstackmark(&smark);
10307 mpath = mpathset() ? mpathval() : mailval();
10310 p = path_advance(&mpath, nullstr);
10315 for (q = p; *q; q++)
10321 q[-1] = '\0'; /* delete trailing '/' */
10322 if (stat(p, &statb) < 0) {
10325 /* Very simplistic "hash": just a sum of all mtimes */
10326 new_hash += (unsigned)statb.st_mtime;
10328 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10329 if (mailtime_hash != 0)
10330 out2str("you have mail\n");
10331 mailtime_hash = new_hash;
10333 mail_var_path_changed = 0;
10334 popstackmark(&smark);
10337 static void FAST_FUNC
10338 changemail(const char *val UNUSED_PARAM)
10340 mail_var_path_changed = 1;
10343 #endif /* ASH_MAIL */
10346 /* ============ ??? */
10349 * Set the shell parameters.
10352 setparam(char **argv)
10358 for (nparam = 0; argv[nparam]; nparam++)
10360 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10362 *ap++ = ckstrdup(*argv++);
10365 freeparam(&shellparam);
10366 shellparam.malloced = 1;
10367 shellparam.nparam = nparam;
10368 shellparam.p = newparam;
10369 #if ENABLE_ASH_GETOPTS
10370 shellparam.optind = 1;
10371 shellparam.optoff = -1;
10376 * Process shell options. The global variable argptr contains a pointer
10377 * to the argument list; we advance it past the options.
10379 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10380 * For a non-interactive shell, an error condition encountered
10381 * by a special built-in ... shall cause the shell to write a diagnostic message
10382 * to standard error and exit as shown in the following table:
10383 * Error Special Built-In
10385 * Utility syntax error (option or operand error) Shall exit
10387 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10388 * we see that bash does not do that (set "finishes" with error code 1 instead,
10389 * and shell continues), and people rely on this behavior!
10391 * set -o barfoo 2>/dev/null
10394 * Oh well. Let's mimic that.
10397 plus_minus_o(char *name, int val)
10402 for (i = 0; i < NOPTS; i++) {
10403 if (strcmp(name, optnames(i)) == 0) {
10408 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10411 for (i = 0; i < NOPTS; i++) {
10413 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10415 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10421 setoption(int flag, int val)
10425 for (i = 0; i < NOPTS; i++) {
10426 if (optletters(i) == flag) {
10431 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10435 options(int cmdline)
10443 while ((p = *argptr) != NULL) {
10445 if (c != '-' && c != '+')
10448 val = 0; /* val = 0 if c == '+' */
10451 if (p[0] == '\0' || LONE_DASH(p)) {
10453 /* "-" means turn off -x and -v */
10456 /* "--" means reset params */
10457 else if (*argptr == NULL)
10460 break; /* "-" or "--" terminates options */
10463 /* first char was + or - */
10464 while ((c = *p++) != '\0') {
10465 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10466 if (c == 'c' && cmdline) {
10467 minusc = p; /* command is after shell args */
10468 } else if (c == 'o') {
10469 if (plus_minus_o(*argptr, val)) {
10470 /* it already printed err message */
10471 return 1; /* error */
10475 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10477 /* bash does not accept +-login, we also won't */
10478 } else if (cmdline && val && (c == '-')) { /* long options */
10479 if (strcmp(p, "login") == 0)
10491 * The shift builtin command.
10493 static int FAST_FUNC
10494 shiftcmd(int argc UNUSED_PARAM, char **argv)
10501 n = number(argv[1]);
10502 if (n > shellparam.nparam)
10503 n = 0; /* bash compat, was = shellparam.nparam; */
10505 shellparam.nparam -= n;
10506 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10507 if (shellparam.malloced)
10510 ap2 = shellparam.p;
10511 while ((*ap2++ = *ap1++) != NULL)
10513 #if ENABLE_ASH_GETOPTS
10514 shellparam.optind = 1;
10515 shellparam.optoff = -1;
10522 * POSIX requires that 'set' (but not export or readonly) output the
10523 * variables in lexicographic order - by the locale's collating order (sigh).
10524 * Maybe we could keep them in an ordered balanced binary tree
10525 * instead of hashed lists.
10526 * For now just roll 'em through qsort for printing...
10529 showvars(const char *sep_prefix, int on, int off)
10532 char **ep, **epend;
10534 ep = listvars(on, off, &epend);
10535 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10537 sep = *sep_prefix ? " " : sep_prefix;
10539 for (; ep < epend; ep++) {
10543 p = strchrnul(*ep, '=');
10546 q = single_quote(++p);
10547 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10553 * The set command builtin.
10555 static int FAST_FUNC
10556 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10561 return showvars(nullstr, 0, VUNSET);
10564 retval = options(/*cmdline:*/ 0);
10565 if (retval == 0) { /* if no parse error... */
10567 if (*argptr != NULL) {
10575 #if ENABLE_ASH_RANDOM_SUPPORT
10576 static void FAST_FUNC
10577 change_random(const char *value)
10581 if (value == NULL) {
10582 /* "get", generate */
10583 t = next_random(&random_gen);
10584 /* set without recursion */
10585 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10586 vrandom.flags &= ~VNOFUNC;
10589 t = strtoul(value, NULL, 10);
10590 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10595 #if ENABLE_ASH_GETOPTS
10597 getopts(char *optstr, char *optvar, char **optfirst)
10604 int ind = shellparam.optind;
10605 int off = shellparam.optoff;
10609 shellparam.optind = -1;
10610 optnext = optfirst + ind - 1;
10612 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10615 p = optnext[-1] + off;
10616 if (p == NULL || *p == '\0') {
10617 /* Current word is done, advance */
10619 if (p == NULL || *p != '-' || *++p == '\0') {
10626 if (LONE_DASH(p)) /* check for "--" */
10631 for (q = optstr; *q != c;) {
10633 if (optstr[0] == ':') {
10635 /*sbuf[1] = '\0'; - already is */
10636 setvar0("OPTARG", sbuf);
10638 fprintf(stderr, "Illegal option -%c\n", c);
10639 unsetvar("OPTARG");
10649 if (*p == '\0' && (p = *optnext) == NULL) {
10650 if (optstr[0] == ':') {
10652 /*sbuf[1] = '\0'; - already is */
10653 setvar0("OPTARG", sbuf);
10656 fprintf(stderr, "No arg for -%c option\n", c);
10657 unsetvar("OPTARG");
10665 setvar0("OPTARG", p);
10668 setvar0("OPTARG", nullstr);
10670 ind = optnext - optfirst + 1;
10671 setvar("OPTIND", itoa(ind), VNOFUNC);
10673 /*sbuf[1] = '\0'; - already is */
10674 setvar0(optvar, sbuf);
10676 shellparam.optoff = p ? p - *(optnext - 1) : -1;
10677 shellparam.optind = ind;
10683 * The getopts builtin. Shellparam.optnext points to the next argument
10684 * to be processed. Shellparam.optptr points to the next character to
10685 * be processed in the current argument. If shellparam.optnext is NULL,
10686 * then it's the first time getopts has been called.
10688 static int FAST_FUNC
10689 getoptscmd(int argc, char **argv)
10694 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10696 optbase = shellparam.p;
10697 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
10698 shellparam.optind = 1;
10699 shellparam.optoff = -1;
10702 optbase = &argv[3];
10703 if ((unsigned)shellparam.optind > argc - 2) {
10704 shellparam.optind = 1;
10705 shellparam.optoff = -1;
10709 return getopts(argv[1], argv[2], optbase);
10711 #endif /* ASH_GETOPTS */
10714 /* ============ Shell parser */
10717 struct heredoc *next; /* next here document in list */
10718 union node *here; /* redirection node */
10719 char *eofmark; /* string indicating end of input */
10720 smallint striptabs; /* if set, strip leading tabs */
10723 static smallint tokpushback; /* last token pushed back */
10724 static smallint quoteflag; /* set if (part of) last token was quoted */
10725 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10726 static struct heredoc *heredoclist; /* list of here documents to read */
10727 static char *wordtext; /* text of last word returned by readtoken */
10728 static struct nodelist *backquotelist;
10729 static union node *redirnode;
10730 static struct heredoc *heredoc;
10732 static const char *
10733 tokname(char *buf, int tok)
10736 return tokname_array[tok];
10737 sprintf(buf, "\"%s\"", tokname_array[tok]);
10741 /* raise_error_unexpected_syntax:
10742 * Called when an unexpected token is read during the parse. The argument
10743 * is the token that is expected, or -1 if more than one type of token can
10744 * occur at this point.
10746 static void raise_error_unexpected_syntax(int) NORETURN;
10748 raise_error_unexpected_syntax(int token)
10754 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10756 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10757 raise_error_syntax(msg);
10761 #define EOFMARKLEN 79
10763 /* parsing is heavily cross-recursive, need these forward decls */
10764 static union node *andor(void);
10765 static union node *pipeline(void);
10766 static union node *parse_command(void);
10767 static void parseheredoc(void);
10768 static int peektoken(void);
10769 static int readtoken(void);
10771 static union node *
10774 union node *n1, *n2, *n3;
10779 switch (peektoken()) {
10787 if (!n1 && (nlflag & 1))
10793 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10794 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
10800 if (tok == TBACKGND) {
10801 if (n2->type == NPIPE) {
10802 n2->npipe.pipe_backgnd = 1;
10804 if (n2->type != NREDIR) {
10805 n3 = stzalloc(sizeof(struct nredir));
10807 /*n3->nredir.redirect = NULL; - stzalloc did it */
10810 n2->type = NBACKGND;
10816 n3 = stzalloc(sizeof(struct nbinary));
10818 n3->nbinary.ch1 = n1;
10819 n3->nbinary.ch2 = n2;
10832 raise_error_unexpected_syntax(-1);
10839 static union node *
10842 union node *n1, *n2, *n3;
10850 } else if (t == TOR) {
10856 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10858 n3 = stzalloc(sizeof(struct nbinary));
10860 n3->nbinary.ch1 = n1;
10861 n3->nbinary.ch2 = n2;
10866 static union node *
10869 union node *n1, *n2, *pipenode;
10870 struct nodelist *lp, *prev;
10874 TRACE(("pipeline: entered\n"));
10875 if (readtoken() == TNOT) {
10877 checkkwd = CHKKWD | CHKALIAS;
10880 n1 = parse_command();
10881 if (readtoken() == TPIPE) {
10882 pipenode = stzalloc(sizeof(struct npipe));
10883 pipenode->type = NPIPE;
10884 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10885 lp = stzalloc(sizeof(struct nodelist));
10886 pipenode->npipe.cmdlist = lp;
10890 lp = stzalloc(sizeof(struct nodelist));
10891 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10892 lp->n = parse_command();
10894 } while (readtoken() == TPIPE);
10900 n2 = stzalloc(sizeof(struct nnot));
10908 static union node *
10913 n = stzalloc(sizeof(struct narg));
10915 /*n->narg.next = NULL; - stzalloc did it */
10916 n->narg.text = wordtext;
10917 n->narg.backquote = backquotelist;
10922 fixredir(union node *n, const char *text, int err)
10926 TRACE(("Fix redir %s %d\n", text, err));
10928 n->ndup.vname = NULL;
10930 fd = bb_strtou(text, NULL, 10);
10931 if (!errno && fd >= 0)
10932 n->ndup.dupfd = fd;
10933 else if (LONE_DASH(text))
10934 n->ndup.dupfd = -1;
10937 raise_error_syntax("bad fd number");
10938 n->ndup.vname = makename();
10943 * Returns true if the text contains nothing to expand (no dollar signs
10947 noexpand(const char *text)
10951 while ((c = *text++) != '\0') {
10952 if (c == CTLQUOTEMARK)
10956 else if (SIT(c, BASESYNTAX) == CCTL)
10965 union node *n = redirnode;
10967 if (readtoken() != TWORD)
10968 raise_error_unexpected_syntax(-1);
10969 if (n->type == NHERE) {
10970 struct heredoc *here = heredoc;
10974 if (quoteflag == 0)
10976 TRACE(("Here document %d\n", n->type));
10977 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10978 raise_error_syntax("illegal eof marker for << redirection");
10979 rmescapes(wordtext, 0);
10980 here->eofmark = wordtext;
10982 if (heredoclist == NULL)
10983 heredoclist = here;
10985 for (p = heredoclist; p->next; p = p->next)
10989 } else if (n->type == NTOFD || n->type == NFROMFD) {
10990 fixredir(n, wordtext, 0);
10992 n->nfile.fname = makename();
10996 static union node *
10999 union node *args, **app;
11000 union node *n = NULL;
11001 union node *vars, **vpp;
11002 union node **rpp, *redir;
11004 #if ENABLE_ASH_BASH_COMPAT
11005 smallint double_brackets_flag = 0;
11006 smallint function_flag = 0;
11016 savecheckkwd = CHKALIAS;
11019 checkkwd = savecheckkwd;
11022 #if ENABLE_ASH_BASH_COMPAT
11024 if (peektoken() != TWORD)
11025 raise_error_unexpected_syntax(TWORD);
11028 case TAND: /* "&&" */
11029 case TOR: /* "||" */
11030 if (!double_brackets_flag) {
11034 wordtext = (char *) (t == TAND ? "-a" : "-o");
11037 n = stzalloc(sizeof(struct narg));
11039 /*n->narg.next = NULL; - stzalloc did it */
11040 n->narg.text = wordtext;
11041 #if ENABLE_ASH_BASH_COMPAT
11042 if (strcmp("[[", wordtext) == 0)
11043 double_brackets_flag = 1;
11044 else if (strcmp("]]", wordtext) == 0)
11045 double_brackets_flag = 0;
11047 n->narg.backquote = backquotelist;
11048 if (savecheckkwd && isassignment(wordtext)) {
11050 vpp = &n->narg.next;
11053 app = &n->narg.next;
11056 #if ENABLE_ASH_BASH_COMPAT
11057 if (function_flag) {
11058 checkkwd = CHKNL | CHKKWD;
11059 switch (peektoken()) {
11071 if (strcmp("[[", wordtext) == 0)
11075 raise_error_unexpected_syntax(-1);
11081 *rpp = n = redirnode;
11082 rpp = &n->nfile.next;
11083 parsefname(); /* read name of redirection file */
11086 IF_ASH_BASH_COMPAT(do_func:)
11087 if (args && app == &args->narg.next
11090 struct builtincmd *bcmd;
11093 /* We have a function */
11094 if (IF_ASH_BASH_COMPAT(!function_flag &&) readtoken() != TRP)
11095 raise_error_unexpected_syntax(TRP);
11096 name = n->narg.text;
11097 if (!goodname(name)
11098 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11100 raise_error_syntax("bad function name");
11103 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11104 n->narg.next = parse_command();
11107 IF_ASH_BASH_COMPAT(function_flag = 0;)
11118 n = stzalloc(sizeof(struct ncmd));
11120 n->ncmd.args = args;
11121 n->ncmd.assign = vars;
11122 n->ncmd.redirect = redir;
11126 static union node *
11127 parse_command(void)
11129 union node *n1, *n2;
11130 union node *ap, **app;
11131 union node *cp, **cpp;
11132 union node *redir, **rpp;
11139 switch (readtoken()) {
11141 raise_error_unexpected_syntax(-1);
11144 n1 = stzalloc(sizeof(struct nif));
11146 n1->nif.test = list(0);
11147 if (readtoken() != TTHEN)
11148 raise_error_unexpected_syntax(TTHEN);
11149 n1->nif.ifpart = list(0);
11151 while (readtoken() == TELIF) {
11152 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11153 n2 = n2->nif.elsepart;
11155 n2->nif.test = list(0);
11156 if (readtoken() != TTHEN)
11157 raise_error_unexpected_syntax(TTHEN);
11158 n2->nif.ifpart = list(0);
11160 if (lasttoken == TELSE)
11161 n2->nif.elsepart = list(0);
11163 n2->nif.elsepart = NULL;
11171 n1 = stzalloc(sizeof(struct nbinary));
11172 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11173 n1->nbinary.ch1 = list(0);
11176 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11177 got == TWORD ? wordtext : ""));
11178 raise_error_unexpected_syntax(TDO);
11180 n1->nbinary.ch2 = list(0);
11185 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11186 raise_error_syntax("bad for loop variable");
11187 n1 = stzalloc(sizeof(struct nfor));
11189 n1->nfor.var = wordtext;
11190 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11191 if (readtoken() == TIN) {
11193 while (readtoken() == TWORD) {
11194 n2 = stzalloc(sizeof(struct narg));
11196 /*n2->narg.next = NULL; - stzalloc did it */
11197 n2->narg.text = wordtext;
11198 n2->narg.backquote = backquotelist;
11200 app = &n2->narg.next;
11203 n1->nfor.args = ap;
11204 if (lasttoken != TNL && lasttoken != TSEMI)
11205 raise_error_unexpected_syntax(-1);
11207 n2 = stzalloc(sizeof(struct narg));
11209 /*n2->narg.next = NULL; - stzalloc did it */
11210 n2->narg.text = (char *)dolatstr;
11211 /*n2->narg.backquote = NULL;*/
11212 n1->nfor.args = n2;
11214 * Newline or semicolon here is optional (but note
11215 * that the original Bourne shell only allowed NL).
11217 if (lasttoken != TSEMI)
11220 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11221 if (readtoken() != TDO)
11222 raise_error_unexpected_syntax(TDO);
11223 n1->nfor.body = list(0);
11227 n1 = stzalloc(sizeof(struct ncase));
11229 if (readtoken() != TWORD)
11230 raise_error_unexpected_syntax(TWORD);
11231 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11233 /*n2->narg.next = NULL; - stzalloc did it */
11234 n2->narg.text = wordtext;
11235 n2->narg.backquote = backquotelist;
11236 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11237 if (readtoken() != TIN)
11238 raise_error_unexpected_syntax(TIN);
11239 cpp = &n1->ncase.cases;
11241 checkkwd = CHKNL | CHKKWD;
11243 while (t != TESAC) {
11244 if (lasttoken == TLP)
11246 *cpp = cp = stzalloc(sizeof(struct nclist));
11248 app = &cp->nclist.pattern;
11250 *app = ap = stzalloc(sizeof(struct narg));
11252 /*ap->narg.next = NULL; - stzalloc did it */
11253 ap->narg.text = wordtext;
11254 ap->narg.backquote = backquotelist;
11255 if (readtoken() != TPIPE)
11257 app = &ap->narg.next;
11260 //ap->narg.next = NULL;
11261 if (lasttoken != TRP)
11262 raise_error_unexpected_syntax(TRP);
11263 cp->nclist.body = list(2);
11265 cpp = &cp->nclist.next;
11267 checkkwd = CHKNL | CHKKWD;
11271 raise_error_unexpected_syntax(TENDCASE);
11278 n1 = stzalloc(sizeof(struct nredir));
11279 n1->type = NSUBSHELL;
11280 n1->nredir.n = list(0);
11281 /*n1->nredir.redirect = NULL; - stzalloc did it */
11288 IF_ASH_BASH_COMPAT(case TFUNCTION:)
11292 return simplecmd();
11295 if (readtoken() != t)
11296 raise_error_unexpected_syntax(t);
11299 /* Now check for redirection which may follow command */
11300 checkkwd = CHKKWD | CHKALIAS;
11302 while (readtoken() == TREDIR) {
11303 *rpp = n2 = redirnode;
11304 rpp = &n2->nfile.next;
11310 if (n1->type != NSUBSHELL) {
11311 n2 = stzalloc(sizeof(struct nredir));
11316 n1->nredir.redirect = redir;
11321 #if ENABLE_ASH_BASH_COMPAT
11323 decode_dollar_squote(void)
11325 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11331 p = strchr(C_escapes, c);
11336 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11340 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11342 } else if (c == 'x') { /* \xHH */
11346 } while (isxdigit(c) && --cnt);
11348 if (cnt == 3) { /* \x but next char is "bad" */
11352 } else { /* simple seq like \\ or \t */
11357 c = bb_process_escape_sequence((void*)&p);
11358 } else { /* unrecognized "\z": print both chars unless ' or " */
11359 if (c != '\'' && c != '"') {
11361 c |= 0x100; /* "please encode \, then me" */
11369 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11370 * is not NULL, read a here document. In the latter case, eofmark is the
11371 * word which marks the end of the document and striptabs is true if
11372 * leading tabs should be stripped from the document. The argument c
11373 * is the first character of the input token or document.
11375 * Because C does not have internal subroutines, I have simulated them
11376 * using goto's to implement the subroutine linkage. The following macros
11377 * will run code that appears at the end of readtoken1.
11379 #define CHECKEND() {goto checkend; checkend_return:;}
11380 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11381 #define PARSESUB() {goto parsesub; parsesub_return:;}
11382 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11383 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11384 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11386 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11388 /* NB: syntax parameter fits into smallint */
11389 /* c parameter is an unsigned char or PEOF or PEOA */
11392 char line[EOFMARKLEN + 1];
11393 struct nodelist *bqlist;
11397 IF_SH_MATH_SUPPORT(smallint prevsyntax;) /* syntax before arithmetic */
11398 #if ENABLE_ASH_EXPAND_PRMT
11399 smallint pssyntax; /* we are expanding a prompt string */
11401 int varnest; /* levels of variables expansion */
11402 IF_SH_MATH_SUPPORT(int arinest;) /* levels of arithmetic expansion */
11403 IF_SH_MATH_SUPPORT(int parenlevel;) /* levels of parens in arithmetic */
11404 int dqvarnest; /* levels of variables expansion within double quotes */
11406 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11408 startlinno = g_parsefile->linno;
11411 IF_SH_MATH_SUPPORT(prevsyntax = 0;)
11412 #if ENABLE_ASH_EXPAND_PRMT
11413 pssyntax = (syntax == PSSYNTAX);
11417 dblquote = (syntax == DQSYNTAX);
11419 IF_SH_MATH_SUPPORT(arinest = 0;)
11420 IF_SH_MATH_SUPPORT(parenlevel = 0;)
11423 STARTSTACKSTR(out);
11425 /* For each line, until end of word */
11426 CHECKEND(); /* set c to PEOF if at end of here document */
11427 for (;;) { /* until end of line or end of word */
11428 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11429 switch (SIT(c, syntax)) {
11430 case CNL: /* '\n' */
11431 if (syntax == BASESYNTAX)
11432 goto endword; /* exit outer loop */
11436 goto loop; /* continue outer loop */
11441 #if ENABLE_ASH_BASH_COMPAT
11442 if (c == '\\' && bash_dollar_squote) {
11443 c = decode_dollar_squote();
11445 /* skip $'\000', $'\x00' (like bash) */
11449 /* Unknown escape. Encode as '\z' */
11450 c = (unsigned char)c;
11451 if (eofmark == NULL || dblquote)
11452 USTPUTC(CTLESC, out);
11453 USTPUTC('\\', out);
11457 if (eofmark == NULL || dblquote)
11458 USTPUTC(CTLESC, out);
11461 case CBACK: /* backslash */
11462 c = pgetc_without_PEOA();
11464 USTPUTC(CTLESC, out);
11465 USTPUTC('\\', out);
11467 } else if (c == '\n') {
11470 #if ENABLE_ASH_EXPAND_PRMT
11471 if (c == '$' && pssyntax) {
11472 USTPUTC(CTLESC, out);
11473 USTPUTC('\\', out);
11476 /* Backslash is retained if we are in "str" and next char isn't special */
11481 && (c != '"' || eofmark != NULL)
11483 USTPUTC('\\', out);
11485 USTPUTC(CTLESC, out);
11493 if (eofmark == NULL) {
11494 USTPUTC(CTLQUOTEMARK, out);
11502 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11503 if (eofmark != NULL && varnest == 0) {
11506 if (dqvarnest == 0) {
11507 syntax = BASESYNTAX;
11514 case CVAR: /* '$' */
11515 PARSESUB(); /* parse substitution */
11517 case CENDVAR: /* '}' */
11520 if (dqvarnest > 0) {
11527 #if ENABLE_SH_MATH_SUPPORT
11528 case CLP: /* '(' in arithmetic */
11532 case CRP: /* ')' in arithmetic */
11533 if (parenlevel > 0) {
11536 if (pgetc_eatbnl() == ')') {
11538 if (--arinest == 0) {
11539 syntax = prevsyntax;
11543 * unbalanced parens
11544 * (don't 2nd guess - no error)
11552 case CBQUOTE: /* '`' */
11556 goto endword; /* exit outer loop */
11560 if (varnest == 0) {
11561 #if ENABLE_ASH_BASH_COMPAT
11563 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11564 if (pgetc() == '>')
11565 c = 0x100 + '>'; /* flag &> */
11569 goto endword; /* exit outer loop */
11571 IF_ASH_ALIAS(if (c != PEOA))
11578 #if ENABLE_SH_MATH_SUPPORT
11579 if (syntax == ARISYNTAX)
11580 raise_error_syntax("missing '))'");
11582 if (syntax != BASESYNTAX && eofmark == NULL)
11583 raise_error_syntax("unterminated quoted string");
11584 if (varnest != 0) {
11585 startlinno = g_parsefile->linno;
11587 raise_error_syntax("missing '}'");
11589 USTPUTC('\0', out);
11590 len = out - (char *)stackblock();
11591 out = stackblock();
11592 if (eofmark == NULL) {
11593 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11596 if (isdigit_str9(out)) {
11597 PARSEREDIR(); /* passed as params: out, c */
11598 lasttoken = TREDIR;
11601 /* else: non-number X seen, interpret it
11602 * as "NNNX>file" = "NNNX >file" */
11606 quoteflag = quotef;
11607 backquotelist = bqlist;
11608 grabstackblock(len);
11612 /* end of readtoken routine */
11615 * Check to see whether we are at the end of the here document. When this
11616 * is called, c is set to the first character of the next input line. If
11617 * we are at the end of the here document, this routine sets the c to PEOF.
11621 #if ENABLE_ASH_ALIAS
11623 c = pgetc_without_PEOA();
11626 while (c == '\t') {
11627 c = pgetc_without_PEOA();
11630 if (c == *eofmark) {
11631 if (pfgets(line, sizeof(line)) != NULL) {
11636 for (q = eofmark + 1;; p++, q++) {
11640 if (!*q || cc != *q)
11647 pushstring(line, NULL);
11652 goto checkend_return;
11656 * Parse a redirection operator. The variable "out" points to a string
11657 * specifying the fd to be redirected. The variable "c" contains the
11658 * first character of the redirection operator.
11661 /* out is already checked to be a valid number or "" */
11662 int fd = (*out == '\0' ? -1 : atoi(out));
11665 np = stzalloc(sizeof(struct nfile));
11670 np->type = NAPPEND;
11672 np->type = NCLOBBER;
11675 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11681 #if ENABLE_ASH_BASH_COMPAT
11682 else if (c == 0x100 + '>') { /* this flags &> redirection */
11684 pgetc(); /* this is '>', no need to check */
11688 else { /* c == '<' */
11689 /*np->nfile.fd = 0; - stzalloc did it */
11693 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11694 np = stzalloc(sizeof(struct nhere));
11695 /*np->nfile.fd = 0; - stzalloc did it */
11698 heredoc = stzalloc(sizeof(struct heredoc));
11699 heredoc->here = np;
11702 heredoc->striptabs = 1;
11704 /*heredoc->striptabs = 0; - stzalloc did it */
11710 np->type = NFROMFD;
11714 np->type = NFROMTO;
11726 goto parseredir_return;
11730 * Parse a substitution. At this point, we have read the dollar sign
11731 * and nothing else.
11734 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11735 * (assuming ascii char codes, as the original implementation did) */
11736 #define is_special(c) \
11737 (((unsigned)(c) - 33 < 32) \
11738 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11740 unsigned char subtype;
11743 c = pgetc_eatbnl();
11744 if (c > 255 /* PEOA or PEOF */
11745 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11747 #if ENABLE_ASH_BASH_COMPAT
11748 if (syntax != DQSYNTAX && c == '\'')
11749 bash_dollar_squote = 1;
11754 } else if (c == '(') {
11755 /* $(command) or $((arith)) */
11756 if (pgetc_eatbnl() == '(') {
11757 #if ENABLE_SH_MATH_SUPPORT
11760 raise_error_syntax("you disabled math support for $((arith)) syntax");
11767 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11768 USTPUTC(CTLVAR, out);
11769 typeloc = out - (char *)stackblock();
11771 subtype = VSNORMAL;
11773 c = pgetc_eatbnl();
11778 /* $[{[#]]NAME[}] */
11781 c = pgetc_eatbnl();
11782 } while (is_in_name(c));
11783 } else if (isdigit(c)) {
11784 /* $[{[#]]NUM[}] */
11787 c = pgetc_eatbnl();
11788 } while (isdigit(c));
11789 } else if (is_special(c)) {
11790 /* $[{[#]]<specialchar>[}] */
11793 c = pgetc_eatbnl();
11794 if (!subtype && cc == '#') {
11795 subtype = VSLENGTH;
11796 if (c == '_' || isalnum(c))
11799 c = pgetc_eatbnl();
11800 if (cc == '}' || c != '}') {
11811 if (c != '}' && subtype == VSLENGTH) {
11812 /* ${#VAR didn't end with } */
11816 if (subtype == 0) {
11817 static const char types[] ALIGN1 = "}-+?=";
11818 /* ${VAR...} but not $VAR or ${#VAR} */
11819 /* c == first char after VAR */
11822 c = pgetc_eatbnl();
11823 #if ENABLE_ASH_BASH_COMPAT
11824 /* This check is only needed to not misinterpret
11825 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11828 if (!strchr(types, c)) {
11829 subtype = VSSUBSTR;
11831 break; /* "goto badsub" is bigger (!) */
11837 const char *p = strchr(types, c);
11840 subtype |= p - types + VSNORMAL;
11846 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11847 c = pgetc_eatbnl();
11853 #if ENABLE_ASH_BASH_COMPAT
11855 /* ${v/[/]pattern/repl} */
11856 //TODO: encode pattern and repl separately.
11857 // Currently ${v/$var_with_slash/repl} is horribly broken
11858 subtype = VSREPLACE;
11859 c = pgetc_eatbnl();
11862 subtype++; /* VSREPLACEALL */
11870 ((unsigned char *)stackblock())[typeloc] = subtype;
11871 if (subtype != VSNORMAL) {
11878 goto parsesub_return;
11882 * Called to parse command substitutions. Newstyle is set if the command
11883 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11884 * list of commands (passed by reference), and savelen is the number of
11885 * characters on the top of the stack which must be preserved.
11888 struct nodelist **nlpp;
11892 smallint saveprompt = 0;
11895 savelen = out - (char *)stackblock();
11898 * FIXME: this can allocate very large block on stack and SEGV.
11900 * echo "..<100kbytes>..`true` $(true) `true` ..."
11901 * allocates 100kb for every command subst. With about
11902 * a hundred command substitutions stack overflows.
11903 * With larger prepended string, SEGV happens sooner.
11905 str = alloca(savelen);
11906 memcpy(str, stackblock(), savelen);
11910 /* We must read until the closing backquote, giving special
11911 * treatment to some slashes, and then push the string and
11912 * reread it as input, interpreting it normally.
11918 STARTSTACKSTR(pout);
11922 setprompt_if(needprompt, 2);
11933 * If eating a newline, avoid putting
11934 * the newline into the new character
11935 * stream (via the STPUTC after the
11940 if (pc != '\\' && pc != '`' && pc != '$'
11941 && (!dblquote || pc != '"')
11943 STPUTC('\\', pout);
11945 if (pc <= 255 /* not PEOA or PEOF */) {
11951 IF_ASH_ALIAS(case PEOA:)
11952 startlinno = g_parsefile->linno;
11953 raise_error_syntax("EOF in backquote substitution");
11965 STPUTC('\0', pout);
11966 psavelen = pout - (char *)stackblock();
11967 if (psavelen > 0) {
11968 pstr = grabstackstr(pout);
11969 setinputstring(pstr);
11974 nlpp = &(*nlpp)->next;
11975 *nlpp = stzalloc(sizeof(**nlpp));
11976 /* (*nlpp)->next = NULL; - stzalloc did it */
11979 saveprompt = doprompt;
11986 doprompt = saveprompt;
11987 else if (readtoken() != TRP)
11988 raise_error_unexpected_syntax(TRP);
11993 * Start reading from old file again, ignoring any pushed back
11994 * tokens left from the backquote parsing
11999 while (stackblocksize() <= savelen)
12001 STARTSTACKSTR(out);
12003 memcpy(out, str, savelen);
12004 STADJUST(savelen, out);
12006 USTPUTC(CTLBACKQ, out);
12008 goto parsebackq_oldreturn;
12009 goto parsebackq_newreturn;
12012 #if ENABLE_SH_MATH_SUPPORT
12014 * Parse an arithmetic expansion (indicate start of one and set state)
12017 if (++arinest == 1) {
12018 prevsyntax = syntax;
12019 syntax = ARISYNTAX;
12021 USTPUTC(CTLARI, out);
12022 goto parsearith_return;
12025 } /* end of readtoken */
12028 * Read the next input token.
12029 * If the token is a word, we set backquotelist to the list of cmds in
12030 * backquotes. We set quoteflag to true if any part of the word was
12032 * If the token is TREDIR, then we set redirnode to a structure containing
12034 * In all cases, the variable startlinno is set to the number of the line
12035 * on which the token starts.
12037 * [Change comment: here documents and internal procedures]
12038 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12039 * word parsing code into a separate routine. In this case, readtoken
12040 * doesn't need to have any internal procedures, but parseword does.
12041 * We could also make parseoperator in essence the main routine, and
12042 * have parseword (readtoken1?) handle both words and redirection.]
12044 #define NEW_xxreadtoken
12045 #ifdef NEW_xxreadtoken
12046 /* singles must be first! */
12047 static const char xxreadtoken_chars[7] ALIGN1 = {
12048 '\n', '(', ')', /* singles */
12049 '&', '|', ';', /* doubles */
12053 #define xxreadtoken_singles 3
12054 #define xxreadtoken_doubles 3
12056 static const char xxreadtoken_tokens[] ALIGN1 = {
12057 TNL, TLP, TRP, /* only single occurrence allowed */
12058 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12059 TEOF, /* corresponds to trailing nul */
12060 TAND, TOR, TENDCASE /* if double occurrence */
12072 setprompt_if(needprompt, 2);
12073 startlinno = g_parsefile->linno;
12074 for (;;) { /* until token or start of word found */
12076 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12080 while ((c = pgetc()) != '\n' && c != PEOF)
12083 } else if (c == '\\') {
12084 if (pgetc() != '\n') {
12086 break; /* return readtoken1(...) */
12092 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12098 p = strchr(xxreadtoken_chars, c);
12100 break; /* return readtoken1(...) */
12102 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12104 if (cc == c) { /* double occurrence? */
12105 p += xxreadtoken_doubles + 1;
12108 #if ENABLE_ASH_BASH_COMPAT
12109 if (c == '&' && cc == '>') /* &> */
12110 break; /* return readtoken1(...) */
12115 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12120 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12122 #else /* old xxreadtoken */
12123 #define RETURN(token) return lasttoken = token
12133 setprompt_if(needprompt, 2);
12134 startlinno = g_parsefile->linno;
12135 for (;;) { /* until token or start of word found */
12138 case ' ': case '\t':
12139 IF_ASH_ALIAS(case PEOA:)
12142 while ((c = pgetc()) != '\n' && c != PEOF)
12147 if (pgetc() == '\n') {
12159 if (pgetc() == '&')
12164 if (pgetc() == '|')
12169 if (pgetc() == ';')
12182 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12185 #endif /* old xxreadtoken */
12191 int kwd = checkkwd;
12193 smallint alreadyseen = tokpushback;
12196 #if ENABLE_ASH_ALIAS
12212 if (t != TWORD || quoteflag) {
12217 * check for keywords
12219 if (kwd & CHKKWD) {
12220 const char *const *pp;
12222 pp = findkwd(wordtext);
12224 lasttoken = t = pp - tokname_array;
12225 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12230 if (checkkwd & CHKALIAS) {
12231 #if ENABLE_ASH_ALIAS
12233 ap = lookupalias(wordtext, 1);
12236 pushstring(ap->val, ap);
12246 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12248 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12264 * Read and parse a command. Returns NODE_EOF on end of file.
12265 * (NULL is a valid parse tree indicating a blank line.)
12267 static union node *
12268 parsecmd(int interact)
12273 doprompt = interact;
12274 setprompt_if(doprompt, doprompt);
12280 * Input any here documents.
12285 struct heredoc *here;
12288 here = heredoclist;
12289 heredoclist = NULL;
12292 setprompt_if(needprompt, 2);
12293 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12294 here->eofmark, here->striptabs);
12295 n = stzalloc(sizeof(struct narg));
12296 n->narg.type = NARG;
12297 /*n->narg.next = NULL; - stzalloc did it */
12298 n->narg.text = wordtext;
12299 n->narg.backquote = backquotelist;
12300 here->here->nhere.doc = n;
12307 * called by editline -- any expansions to the prompt should be added here.
12309 #if ENABLE_ASH_EXPAND_PRMT
12310 static const char *
12311 expandstr(const char *ps)
12316 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12317 * and token processing _can_ alter it (delete NULs etc). */
12318 setinputstring((char *)ps);
12320 saveprompt = doprompt;
12322 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12323 doprompt = saveprompt;
12327 n.narg.type = NARG;
12328 n.narg.next = NULL;
12329 n.narg.text = wordtext;
12330 n.narg.backquote = backquotelist;
12332 expandarg(&n, NULL, EXP_QUOTED);
12333 return stackblock();
12338 * Execute a command or commands contained in a string.
12341 evalstring(char *s, int flags)
12343 struct jmploc *volatile savehandler;
12344 struct jmploc jmploc;
12348 struct stackmark smark;
12353 setstackmark(&smark);
12356 /* On exception inside execution loop, we must popfile().
12357 * Try interactively:
12359 * command eval "a=b" # throws "is read only" error
12360 * "command BLTIN" is not supposed to abort (even in non-interactive use).
12361 * But if we skip popfile(), we hit EOF in eval's string, and exit.
12363 savehandler = exception_handler;
12364 ex = setjmp(jmploc.loc);
12367 exception_handler = &jmploc;
12369 while ((n = parsecmd(0)) != NODE_EOF) {
12372 i = evaltree(n, flags);
12375 popstackmark(&smark);
12380 popstackmark(&smark);
12384 exception_handler = savehandler;
12386 longjmp(exception_handler->loc, ex);
12392 * The eval command.
12394 static int FAST_FUNC
12395 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12404 STARTSTACKSTR(concat);
12406 concat = stack_putstr(p, concat);
12410 STPUTC(' ', concat);
12412 STPUTC('\0', concat);
12413 p = grabstackstr(concat);
12415 return evalstring(p, flags & EV_TESTED);
12421 * Read and execute commands.
12422 * "Top" is nonzero for the top level command loop;
12423 * it turns on prompting if the shell is interactive.
12429 struct stackmark smark;
12434 TRACE(("cmdloop(%d) called\n", top));
12438 setstackmark(&smark);
12441 showjobs(SHOW_CHANGED|SHOW_STDERR);
12444 if (iflag && top) {
12448 n = parsecmd(inter);
12450 if (DEBUG > 2 && debug && (n != NODE_EOF))
12453 if (n == NODE_EOF) {
12454 if (!top || numeof >= 50)
12456 if (!stoppedjobs()) {
12459 out2str("\nUse \"exit\" to leave shell.\n");
12462 } else if (nflag == 0) {
12465 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12468 i = evaltree(n, 0);
12472 popstackmark(&smark);
12476 evalskip &= ~SKIPFUNC;
12484 * Take commands from a file. To be compatible we should do a path
12485 * search for the file, which is necessary to find sub-commands.
12488 find_dot_file(char *name)
12491 const char *path = pathval();
12494 /* don't try this for absolute or relative paths */
12495 if (strchr(name, '/'))
12498 /* IIRC standards do not say whether . is to be searched.
12499 * And it is even smaller this way, making it unconditional for now:
12501 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12506 while ((fullname = path_advance(&path, name)) != NULL) {
12508 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12510 * Don't bother freeing here, since it will
12511 * be freed by the caller.
12515 if (fullname != name)
12516 stunalloc(fullname);
12519 /* not found in the PATH */
12520 ash_msg_and_raise_error("%s: not found", name);
12524 static int FAST_FUNC
12525 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12527 /* "false; . empty_file; echo $?" should print 0, not 1: */
12531 struct strlist *sp;
12532 volatile struct shparam saveparam;
12534 for (sp = cmdenviron; sp; sp = sp->next)
12535 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12537 nextopt(nullstr); /* handle possible "--" */
12541 /* bash says: "bash: .: filename argument required" */
12542 return 2; /* bash compat */
12545 /* This aborts if file isn't found, which is POSIXly correct.
12546 * bash returns exitcode 1 instead.
12548 fullname = find_dot_file(argv[0]);
12550 if (argv[0]) { /* . FILE ARGS, ARGS exist */
12552 saveparam = shellparam;
12553 shellparam.malloced = 0;
12557 shellparam.nparam = argc;
12558 shellparam.p = argv;
12561 /* This aborts if file can't be opened, which is POSIXly correct.
12562 * bash returns exitcode 1 instead.
12564 setinputfile(fullname, INPUT_PUSH_FILE);
12565 commandname = fullname;
12566 status = cmdloop(0);
12570 freeparam(&shellparam);
12571 shellparam = saveparam;
12577 static int FAST_FUNC
12578 exitcmd(int argc UNUSED_PARAM, char **argv)
12583 exitstatus = number(argv[1]);
12584 raise_exception(EXEXIT);
12589 * Read a file containing shell functions.
12592 readcmdfile(char *name)
12594 setinputfile(name, INPUT_PUSH_FILE);
12600 /* ============ find_command inplementation */
12603 * Resolve a command name. If you change this routine, you may have to
12604 * change the shellexec routine as well.
12607 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12609 struct tblentry *cmdp;
12616 struct builtincmd *bcmd;
12618 /* If name contains a slash, don't use PATH or hash table */
12619 if (strchr(name, '/') != NULL) {
12620 entry->u.index = -1;
12621 if (act & DO_ABS) {
12622 while (stat(name, &statb) < 0) {
12624 if (errno == EINTR)
12627 entry->cmdtype = CMDUNKNOWN;
12631 entry->cmdtype = CMDNORMAL;
12635 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12637 updatetbl = (path == pathval());
12640 if (strstr(path, "%builtin") != NULL)
12641 act |= DO_ALTBLTIN;
12644 /* If name is in the table, check answer will be ok */
12645 cmdp = cmdlookup(name, 0);
12646 if (cmdp != NULL) {
12649 switch (cmdp->cmdtype) {
12667 } else if (cmdp->rehash == 0)
12668 /* if not invalidated by cd, we're done */
12672 /* If %builtin not in path, check for builtin next */
12673 bcmd = find_builtin(name);
12675 if (IS_BUILTIN_REGULAR(bcmd))
12676 goto builtin_success;
12677 if (act & DO_ALTPATH) {
12678 if (!(act & DO_ALTBLTIN))
12679 goto builtin_success;
12680 } else if (builtinloc <= 0) {
12681 goto builtin_success;
12685 #if ENABLE_FEATURE_SH_STANDALONE
12687 int applet_no = find_applet_by_name(name);
12688 if (applet_no >= 0) {
12689 entry->cmdtype = CMDNORMAL;
12690 entry->u.index = -2 - applet_no;
12696 /* We have to search path. */
12697 prev = -1; /* where to start */
12698 if (cmdp && cmdp->rehash) { /* doing a rehash */
12699 if (cmdp->cmdtype == CMDBUILTIN)
12702 prev = cmdp->param.index;
12708 while ((fullname = path_advance(&path, name)) != NULL) {
12709 stunalloc(fullname);
12710 /* NB: code below will still use fullname
12711 * despite it being "unallocated" */
12714 if (prefix(pathopt, "builtin")) {
12716 goto builtin_success;
12719 if ((act & DO_NOFUNC)
12720 || !prefix(pathopt, "func")
12721 ) { /* ignore unimplemented options */
12725 /* if rehash, don't redo absolute path names */
12726 if (fullname[0] == '/' && idx <= prev) {
12729 TRACE(("searchexec \"%s\": no change\n", name));
12732 while (stat(fullname, &statb) < 0) {
12734 if (errno == EINTR)
12737 if (errno != ENOENT && errno != ENOTDIR)
12741 e = EACCES; /* if we fail, this will be the error */
12742 if (!S_ISREG(statb.st_mode))
12744 if (pathopt) { /* this is a %func directory */
12745 stalloc(strlen(fullname) + 1);
12746 /* NB: stalloc will return space pointed by fullname
12747 * (because we don't have any intervening allocations
12748 * between stunalloc above and this stalloc) */
12749 readcmdfile(fullname);
12750 cmdp = cmdlookup(name, 0);
12751 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12752 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12753 stunalloc(fullname);
12756 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12758 entry->cmdtype = CMDNORMAL;
12759 entry->u.index = idx;
12763 cmdp = cmdlookup(name, 1);
12764 cmdp->cmdtype = CMDNORMAL;
12765 cmdp->param.index = idx;
12770 /* We failed. If there was an entry for this command, delete it */
12771 if (cmdp && updatetbl)
12772 delete_cmd_entry();
12774 ash_msg("%s: %s", name, errmsg(e, "not found"));
12775 entry->cmdtype = CMDUNKNOWN;
12780 entry->cmdtype = CMDBUILTIN;
12781 entry->u.cmd = bcmd;
12785 cmdp = cmdlookup(name, 1);
12786 cmdp->cmdtype = CMDBUILTIN;
12787 cmdp->param.cmd = bcmd;
12791 entry->cmdtype = cmdp->cmdtype;
12792 entry->u = cmdp->param;
12797 * The trap builtin.
12799 static int FAST_FUNC
12800 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12804 int signo, exitcode;
12809 for (signo = 0; signo < NSIG; signo++) {
12810 char *tr = trap_ptr[signo];
12812 /* note: bash adds "SIG", but only if invoked
12813 * as "bash". If called as "sh", or if set -o posix,
12814 * then it prints short signal names.
12815 * We are printing short names: */
12816 out1fmt("trap -- %s %s\n",
12818 get_signame(signo));
12819 /* trap_ptr != trap only if we are in special-cased `trap` code.
12820 * In this case, we will exit very soon, no need to free(). */
12821 /* if (trap_ptr != trap && tp[0]) */
12826 if (trap_ptr != trap) {
12839 signo = get_signum(*ap);
12841 /* Mimic bash message exactly */
12842 ash_msg("%s: invalid signal specification", *ap);
12848 if (LONE_DASH(action))
12851 if (action[0]) /* not NULL and not "" and not "-" */
12852 may_have_traps = 1;
12853 action = ckstrdup(action);
12857 trap[signo] = action;
12868 /* ============ Builtins */
12870 #if ENABLE_ASH_HELP
12871 static int FAST_FUNC
12872 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12878 "Built-in commands:\n"
12879 "------------------\n");
12880 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12881 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12882 builtintab[i].name + 1);
12888 # if ENABLE_FEATURE_SH_STANDALONE
12890 const char *a = applet_names;
12892 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12897 while (*a++ != '\0')
12902 newline_and_flush(stdout);
12903 return EXIT_SUCCESS;
12908 static int FAST_FUNC
12909 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12911 show_history(line_input_state);
12912 return EXIT_SUCCESS;
12917 * The export and readonly commands.
12919 static int FAST_FUNC
12920 exportcmd(int argc UNUSED_PARAM, char **argv)
12930 /* "readonly" in bash accepts, but ignores -n.
12931 * We do the same: it saves a conditional in nextopt's param.
12934 while ((opt = nextopt("np")) != '\0') {
12936 flag_off = VEXPORT;
12939 if (argv[0][0] == 'r') {
12941 flag_off = 0; /* readonly ignores -n */
12943 flag_off = ~flag_off;
12945 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12951 p = strchr(name, '=');
12955 vp = *findvar(hashvar(name), name);
12957 vp->flags = ((vp->flags | flag) & flag_off);
12961 setvar(name, p, (flag & flag_off));
12962 } while ((name = *++aptr) != NULL);
12967 /* No arguments. Show the list of exported or readonly vars.
12970 showvars(argv[0], flag, 0);
12975 * Delete a function if it exists.
12978 unsetfunc(const char *name)
12980 struct tblentry *cmdp;
12982 cmdp = cmdlookup(name, 0);
12983 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12984 delete_cmd_entry();
12988 * The unset builtin command. We unset the function before we unset the
12989 * variable to allow a function to be unset when there is a readonly variable
12990 * with the same name.
12992 static int FAST_FUNC
12993 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13000 while ((i = nextopt("vf")) != 0) {
13004 for (ap = argptr; *ap; ap++) {
13017 static const unsigned char timescmd_str[] ALIGN1 = {
13018 ' ', offsetof(struct tms, tms_utime),
13019 '\n', offsetof(struct tms, tms_stime),
13020 ' ', offsetof(struct tms, tms_cutime),
13021 '\n', offsetof(struct tms, tms_cstime),
13024 static int FAST_FUNC
13025 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13027 unsigned long clk_tck, s, t;
13028 const unsigned char *p;
13031 clk_tck = bb_clk_tck();
13036 t = *(clock_t *)(((char *) &buf) + p[1]);
13039 out1fmt("%lum%lu.%03lus%c",
13041 (t * 1000) / clk_tck,
13049 #if ENABLE_SH_MATH_SUPPORT
13051 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13052 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13054 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13056 static int FAST_FUNC
13057 letcmd(int argc UNUSED_PARAM, char **argv)
13063 ash_msg_and_raise_error("expression expected");
13065 i = ash_arith(*argv);
13073 * The read builtin. Options:
13074 * -r Do not interpret '\' specially
13075 * -s Turn off echo (tty only)
13076 * -n NCHARS Read NCHARS max
13077 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13078 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13079 * -u FD Read from given FD instead of fd 0
13080 * This uses unbuffered input, which may be avoidable in some cases.
13081 * TODO: bash also has:
13082 * -a ARRAY Read into array[0],[1],etc
13083 * -d DELIM End on DELIM char, not newline
13084 * -e Use line editing (tty only)
13086 static int FAST_FUNC
13087 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13089 char *opt_n = NULL;
13090 char *opt_p = NULL;
13091 char *opt_t = NULL;
13092 char *opt_u = NULL;
13093 int read_flags = 0;
13097 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13106 read_flags |= BUILTIN_READ_SILENT;
13112 read_flags |= BUILTIN_READ_RAW;
13122 /* "read -s" needs to save/restore termios, can't allow ^C
13123 * to jump out of it.
13126 r = shell_builtin_read(setvar0,
13128 bltinlookup("IFS"), /* can be NULL */
13137 if ((uintptr_t)r > 1)
13138 ash_msg_and_raise_error(r);
13140 return (uintptr_t)r;
13143 static int FAST_FUNC
13144 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13146 static const char permuser[3] ALIGN1 = "ogu";
13149 int symbolic_mode = 0;
13151 while (nextopt("S") != '\0') {
13160 if (*argptr == NULL) {
13161 if (symbolic_mode) {
13162 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13169 *p++ = permuser[i];
13171 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13172 if (!(mask & 0400)) *p++ = 'r';
13173 if (!(mask & 0200)) *p++ = 'w';
13174 if (!(mask & 0100)) *p++ = 'x';
13182 out1fmt("%04o\n", mask);
13185 char *modestr = *argptr;
13186 /* numeric umasks are taken as-is */
13187 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13188 if (!isdigit(modestr[0]))
13190 mask = bb_parse_mode(modestr, mask);
13191 if ((unsigned)mask > 0777) {
13192 ash_msg_and_raise_error("illegal mode: %s", modestr);
13194 if (!isdigit(modestr[0]))
13201 static int FAST_FUNC
13202 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13204 return shell_builtin_ulimit(argv);
13207 /* ============ main() and helpers */
13210 * Called to exit the shell.
13219 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13220 save_history(line_input_state);
13222 status = exitstatus;
13223 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13224 if (setjmp(loc.loc)) {
13225 if (exception_type == EXEXIT)
13226 status = exitstatus;
13229 exception_handler = &loc;
13235 /*free(p); - we'll exit soon */
13238 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13239 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13242 flush_stdout_stderr();
13250 /* we will never free this */
13251 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13253 sigmode[SIGCHLD - 1] = S_DFL;
13254 setsignal(SIGCHLD);
13256 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13257 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13259 signal(SIGHUP, SIG_DFL);
13264 struct stat st1, st2;
13267 for (envp = environ; envp && *envp; envp++) {
13268 p = endofname(*envp);
13269 if (p != *envp && *p == '=') {
13270 setvareq(*envp, VEXPORT|VTEXTFIXED);
13274 setvareq((char*)defoptindvar, VTEXTFIXED);
13276 setvar0("PPID", utoa(getppid()));
13277 #if ENABLE_ASH_BASH_COMPAT
13278 p = lookupvar("SHLVL");
13279 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13280 if (!lookupvar("HOSTNAME")) {
13281 struct utsname uts;
13283 setvar0("HOSTNAME", uts.nodename);
13286 p = lookupvar("PWD");
13288 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13289 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13299 //usage:#define ash_trivial_usage
13300 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13301 //usage:#define ash_full_usage "\n\n"
13302 //usage: "Unix shell interpreter"
13304 //usage:#if ENABLE_FEATURE_SH_IS_ASH
13305 //usage:# define sh_trivial_usage ash_trivial_usage
13306 //usage:# define sh_full_usage ash_full_usage
13308 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
13309 //usage:# define bash_trivial_usage ash_trivial_usage
13310 //usage:# define bash_full_usage ash_full_usage
13314 * Process the shell command line arguments.
13317 procargs(char **argv)
13320 const char *xminusc;
13325 /* if (xargv[0]) - mmm, this is always true! */
13327 for (i = 0; i < NOPTS; i++)
13330 if (options(/*cmdline:*/ 1)) {
13331 /* it already printed err message */
13332 raise_exception(EXERROR);
13336 if (*xargv == NULL) {
13338 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13341 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13345 for (i = 0; i < NOPTS; i++)
13346 if (optlist[i] == 2)
13351 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13356 } else if (!sflag) {
13357 setinputfile(*xargv, 0);
13360 commandname = arg0;
13363 shellparam.p = xargv;
13364 #if ENABLE_ASH_GETOPTS
13365 shellparam.optind = 1;
13366 shellparam.optoff = -1;
13368 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13370 shellparam.nparam++;
13377 * Read /etc/profile, ~/.profile, $ENV.
13380 read_profile(const char *name)
13382 name = expandstr(name);
13383 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13390 * This routine is called when an error or an interrupt occurs in an
13391 * interactive shell and control is returned to the main command loop.
13392 * (In dash, this function is auto-generated by build machinery).
13401 /* from expand.c: */
13404 /* from input.c: */
13405 g_parsefile->left_in_buffer = 0;
13406 g_parsefile->left_in_line = 0; /* clear input buffer */
13409 /* from redir.c: */
13411 popredir(/*drop:*/ 0, /*restore:*/ 0);
13415 static short profile_buf[16384];
13416 extern int etext();
13420 * Main routine. We initialize things, parse the arguments, execute
13421 * profiles if we're a login shell, and then call cmdloop to execute
13422 * commands. The setjmp call sets up the location to jump to when an
13423 * exception occurs. When an exception occurs the variable "state"
13424 * is used to figure out how far we had gotten.
13426 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13427 int ash_main(int argc UNUSED_PARAM, char **argv)
13429 volatile smallint state;
13430 struct jmploc jmploc;
13431 struct stackmark smark;
13433 /* Initialize global data */
13437 #if ENABLE_ASH_ALIAS
13443 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13446 #if ENABLE_FEATURE_EDITING
13447 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13450 if (setjmp(jmploc.loc)) {
13456 e = exception_type;
13458 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13462 newline_and_flush(stderr);
13465 popstackmark(&smark);
13466 FORCE_INT_ON; /* enable interrupts */
13475 exception_handler = &jmploc;
13476 rootpid = getpid();
13479 setstackmark(&smark);
13482 TRACE(("Shell args: "));
13483 trace_puts_args(argv);
13486 if (argv[0] && argv[0][0] == '-')
13492 read_profile("/etc/profile");
13495 hp = lookupvar("HOME");
13497 read_profile("$HOME/.profile");
13503 getuid() == geteuid() && getgid() == getegid() &&
13507 const char *shinit = lookupvar("ENV");
13508 if (shinit != NULL && *shinit != '\0')
13509 read_profile(shinit);
13511 popstackmark(&smark);
13515 /* evalstring pushes parsefile stack.
13516 * Ensure we don't falsely claim that 0 (stdin)
13517 * is one of stacked source fds.
13518 * Testcase: ash -c 'exec 1>&0' must not complain. */
13519 // if (!sflag) g_parsefile->pf_fd = -1;
13520 // ^^ not necessary since now we special-case fd 0
13521 // in is_hidden_fd() to not be considered "hidden fd"
13522 evalstring(minusc, 0);
13525 if (sflag || minusc == NULL) {
13526 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13528 const char *hp = lookupvar("HISTFILE");
13530 hp = lookupvar("HOME");
13532 hp = concat_path_file(hp, ".ash_history");
13533 setvar0("HISTFILE", hp);
13535 hp = lookupvar("HISTFILE");
13539 line_input_state->hist_file = hp;
13540 # if ENABLE_FEATURE_SH_HISTFILESIZE
13541 hp = lookupvar("HISTFILESIZE");
13542 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13546 state4: /* XXX ??? - why isn't this before the "if" statement */
13554 extern void _mcleanup(void);
13558 TRACE(("End of main reached\n"));
13565 * Copyright (c) 1989, 1991, 1993, 1994
13566 * The Regents of the University of California. All rights reserved.
13568 * This code is derived from software contributed to Berkeley by
13569 * Kenneth Almquist.
13571 * Redistribution and use in source and binary forms, with or without
13572 * modification, are permitted provided that the following conditions
13574 * 1. Redistributions of source code must retain the above copyright
13575 * notice, this list of conditions and the following disclaimer.
13576 * 2. Redistributions in binary form must reproduce the above copyright
13577 * notice, this list of conditions and the following disclaimer in the
13578 * documentation and/or other materials provided with the distribution.
13579 * 3. Neither the name of the University nor the names of its contributors
13580 * may be used to endorse or promote products derived from this software
13581 * without specific prior written permission.
13583 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13584 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13585 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13586 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13587 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13588 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13589 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13590 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13591 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13592 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF