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.
20 * The following should be set to reflect the type of system you have:
21 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22 * define SYSV if you are running under System V.
23 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24 * define DEBUG=2 to compile in and turn on debugging.
26 * When debugging is on (DEBUG is 1 and "set -o debug" was executed),
27 * debugging info will be written to ./trace and a quit signal
28 * will generate a core dump.
31 /* Tweak debug output verbosity here */
38 #define JOBS ENABLE_ASH_JOB_CONTROL
42 #include <sys/times.h>
43 #include <sys/utsname.h> /* for setting $HOSTNAME */
45 #include "busybox.h" /* for applet_names */
47 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
48 /* Bionic at least up to version 24 has no glob() */
49 # undef ENABLE_ASH_INTERNAL_GLOB
50 # define ENABLE_ASH_INTERNAL_GLOB 1
53 #if !ENABLE_ASH_INTERNAL_GLOB
58 #include "shell_common.h"
59 #if ENABLE_SH_MATH_SUPPORT
62 #if ENABLE_ASH_RANDOM_SUPPORT
65 # define CLEAR_RANDOM_T(rnd) ((void)0)
68 #include "NUM_APPLETS.h"
70 /* STANDALONE does not make sense, and won't compile */
71 # undef CONFIG_FEATURE_SH_STANDALONE
72 # undef ENABLE_FEATURE_SH_STANDALONE
73 # undef IF_FEATURE_SH_STANDALONE
74 # undef IF_NOT_FEATURE_SH_STANDALONE
75 # define ENABLE_FEATURE_SH_STANDALONE 0
76 # define IF_FEATURE_SH_STANDALONE(...)
77 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
81 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
85 # error "Do not even bother, ash will not run on NOMMU machine"
91 //config: depends on !NOMMU
93 //config: Tha 'ash' shell adds about 60k in the default configuration and is
94 //config: the most complete and most pedantically correct shell included with
95 //config: busybox. This shell is actually a derivative of the Debian 'dash'
96 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
97 //config: (written by Kenneth Almquist) from NetBSD.
99 //config:config ASH_OPTIMIZE_FOR_SIZE
100 //config: bool "Optimize for size instead of speed"
102 //config: depends on ASH
104 //config: Compile ash for reduced size at the price of speed.
106 //config:config ASH_INTERNAL_GLOB
107 //config: bool "Use internal glob() implementation"
109 //config: depends on ASH
111 //config: Do not use glob() function from libc, use internal implementation.
112 //config: Use this if you are getting "glob.h: No such file or directory"
113 //config: or similar build errors.
115 //config:config ASH_RANDOM_SUPPORT
116 //config: bool "Pseudorandom generator and $RANDOM variable"
118 //config: depends on ASH
120 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
121 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
122 //config: You can reset the generator by using a specified start value.
123 //config: After "unset RANDOM" the generator will switch off and this
124 //config: variable will no longer have special treatment.
126 //config:config ASH_EXPAND_PRMT
127 //config: bool "Expand prompt string"
129 //config: depends on ASH
131 //config: "PS#" may contain volatile content, such as backquote commands.
132 //config: This option recreates the prompt string from the environment
133 //config: variable each time it is displayed.
135 //config:config ASH_BASH_COMPAT
136 //config: bool "bash-compatible extensions"
138 //config: depends on ASH
140 //config: Enable bash-compatible extensions.
142 //config:config ASH_IDLE_TIMEOUT
143 //config: bool "Idle timeout variable"
145 //config: depends on ASH
147 //config: Enables bash-like auto-logout after $TMOUT seconds of idle time.
149 //config:config ASH_JOB_CONTROL
150 //config: bool "Job control"
152 //config: depends on ASH
154 //config: Enable job control in the ash shell.
156 //config:config ASH_ALIAS
157 //config: bool "Alias support"
159 //config: depends on ASH
161 //config: Enable alias support in the ash shell.
163 //config:config ASH_GETOPTS
164 //config: bool "Builtin getopt to parse positional parameters"
166 //config: depends on ASH
168 //config: Enable support for getopts builtin in ash.
170 //config:config ASH_BUILTIN_ECHO
171 //config: bool "Builtin version of 'echo'"
173 //config: depends on ASH
175 //config: Enable support for echo builtin in ash.
177 //config:config ASH_BUILTIN_PRINTF
178 //config: bool "Builtin version of 'printf'"
180 //config: depends on ASH
182 //config: Enable support for printf builtin in ash.
184 //config:config ASH_BUILTIN_TEST
185 //config: bool "Builtin version of 'test'"
187 //config: depends on ASH
189 //config: Enable support for test builtin in ash.
191 //config:config ASH_HELP
192 //config: bool "help builtin"
194 //config: depends on ASH
196 //config: Enable help builtin in ash.
198 //config:config ASH_CMDCMD
199 //config: bool "'command' command to override shell builtins"
201 //config: depends on ASH
203 //config: Enable support for the ash 'command' builtin, which allows
204 //config: you to run the specified command with the specified arguments,
205 //config: even when there is an ash builtin command with the same name.
207 //config:config ASH_MAIL
208 //config: bool "Check for new mail on interactive shells"
210 //config: depends on ASH
212 //config: Enable "check for new mail" function in the ash shell.
215 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
216 //applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, sh))
217 //applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, bash))
219 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
220 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
223 /* ============ Hash table sizes. Configurable. */
227 #define CMDTABLESIZE 31 /* should be prime */
230 /* ============ Shell options */
232 static const char *const optletters_optnames[] = {
247 #if ENABLE_ASH_BASH_COMPAT
256 #define optletters(n) optletters_optnames[n][0]
257 #define optnames(n) (optletters_optnames[n] + 1)
259 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
262 /* ============ Misc data */
264 #define msg_illnum "Illegal number: %s"
267 * We enclose jmp_buf in a structure so that we can declare pointers to
268 * jump locations. The global variable handler contains the location to
269 * jump to when an exception occurs, and the global variable exception_type
270 * contains a code identifying the exception. To implement nested
271 * exception handlers, the user should save the value of handler on entry
272 * to an inner scope, set handler to point to a jmploc structure for the
273 * inner scope, and restore handler on exit from the scope.
279 struct globals_misc {
280 uint8_t exitstatus; /* exit status of last command */
281 uint8_t back_exitstatus;/* exit status of backquoted command */
282 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
283 int rootpid; /* pid of main shell */
284 /* shell level: 0 for the main shell, 1 for its children, and so on */
286 #define rootshell (!shlvl)
287 char *minusc; /* argument to -c option */
289 char *curdir; // = nullstr; /* current working directory */
290 char *physdir; // = nullstr; /* physical working directory */
292 char *arg0; /* value of $0 */
294 struct jmploc *exception_handler;
296 volatile int suppress_int; /* counter */
297 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
298 volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
299 volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
300 smallint exception_type; /* kind of exception (0..5) */
302 #define EXINT 0 /* SIGINT received */
303 #define EXERROR 1 /* a generic error */
304 #define EXEXIT 4 /* exit the shell */
307 char nullstr[1]; /* zero length string */
310 #define eflag optlist[0]
311 #define fflag optlist[1]
312 #define Iflag optlist[2]
313 #define iflag optlist[3]
314 #define mflag optlist[4]
315 #define nflag optlist[5]
316 #define sflag optlist[6]
317 #define xflag optlist[7]
318 #define vflag optlist[8]
319 #define Cflag optlist[9]
320 #define aflag optlist[10]
321 #define bflag optlist[11]
322 #define uflag optlist[12]
323 #define viflag optlist[13]
324 #if ENABLE_ASH_BASH_COMPAT
325 # define pipefail optlist[14]
330 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
331 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
334 /* trap handler commands */
336 * Sigmode records the current value of the signal handlers for the various
337 * modes. A value of zero means that the current handler is not known.
338 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
340 char sigmode[NSIG - 1];
341 #define S_DFL 1 /* default signal handling (SIG_DFL) */
342 #define S_CATCH 2 /* signal is caught */
343 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
344 #define S_HARD_IGN 4 /* signal is ignored permanently */
346 /* indicates specified signal received */
347 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
348 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
350 char **trap_ptr; /* used only by "trap hack" */
352 /* Rarely referenced stuff */
353 #if ENABLE_ASH_RANDOM_SUPPORT
356 pid_t backgndpid; /* pid of last background process */
358 extern struct globals_misc *const ash_ptr_to_globals_misc;
359 #define G_misc (*ash_ptr_to_globals_misc)
360 #define exitstatus (G_misc.exitstatus )
361 #define back_exitstatus (G_misc.back_exitstatus )
362 #define job_warning (G_misc.job_warning)
363 #define rootpid (G_misc.rootpid )
364 #define shlvl (G_misc.shlvl )
365 #define minusc (G_misc.minusc )
366 #define curdir (G_misc.curdir )
367 #define physdir (G_misc.physdir )
368 #define arg0 (G_misc.arg0 )
369 #define exception_handler (G_misc.exception_handler)
370 #define exception_type (G_misc.exception_type )
371 #define suppress_int (G_misc.suppress_int )
372 #define pending_int (G_misc.pending_int )
373 #define got_sigchld (G_misc.got_sigchld )
374 #define pending_sig (G_misc.pending_sig )
375 #define isloginsh (G_misc.isloginsh )
376 #define nullstr (G_misc.nullstr )
377 #define optlist (G_misc.optlist )
378 #define sigmode (G_misc.sigmode )
379 #define gotsig (G_misc.gotsig )
380 #define may_have_traps (G_misc.may_have_traps )
381 #define trap (G_misc.trap )
382 #define trap_ptr (G_misc.trap_ptr )
383 #define random_gen (G_misc.random_gen )
384 #define backgndpid (G_misc.backgndpid )
385 #define INIT_G_misc() do { \
386 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
394 /* ============ DEBUG */
396 static void trace_printf(const char *fmt, ...);
397 static void trace_vprintf(const char *fmt, va_list va);
398 # define TRACE(param) trace_printf param
399 # define TRACEV(param) trace_vprintf param
400 # define close(fd) do { \
402 if (close(dfd) < 0) \
403 bb_error_msg("bug on %d: closing %d(0x%x)", \
404 __LINE__, dfd, dfd); \
407 # define TRACE(param)
408 # define TRACEV(param)
412 /* ============ Utility functions */
413 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
414 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
417 isdigit_str9(const char *str)
419 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
420 while (--maxlen && isdigit(*str))
422 return (*str == '\0');
426 var_end(const char *var)
435 /* ============ Interrupts / exceptions */
437 static void exitshell(void) NORETURN;
440 * These macros allow the user to suspend the handling of interrupt signals
441 * over a period of time. This is similar to SIGHOLD or to sigblock, but
442 * much more efficient and portable. (But hacking the kernel is so much
443 * more fun than worrying about efficiency and portability. :-))
445 #define INT_OFF do { \
451 * Called to raise an exception. Since C doesn't include exceptions, we
452 * just do a longjmp to the exception handler. The type of exception is
453 * stored in the global variable "exception_type".
455 static void raise_exception(int) NORETURN;
457 raise_exception(int e)
460 if (exception_handler == NULL)
465 longjmp(exception_handler->loc, 1);
468 #define raise_exception(e) do { \
469 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
470 raise_exception(e); \
475 * Called when a SIGINT is received. (If the user specifies
476 * that SIGINT is to be trapped or ignored using the trap builtin, then
477 * this routine is not called.) Suppressint is nonzero when interrupts
478 * are held using the INT_OFF macro. (The test for iflag is just
479 * defensive programming.)
481 static void raise_interrupt(void) NORETURN;
483 raise_interrupt(void)
486 /* Signal is not automatically unmasked after it is raised,
487 * do it ourself - unmask all signals */
488 sigprocmask_allsigs(SIG_UNBLOCK);
489 /* pending_sig = 0; - now done in signal_handler() */
491 if (!(rootshell && iflag)) {
492 /* Kill ourself with SIGINT */
493 signal(SIGINT, SIG_DFL);
496 /* bash: ^C even on empty command line sets $? */
497 exitstatus = SIGINT + 128;
498 raise_exception(EXINT);
502 #define raise_interrupt() do { \
503 TRACE(("raising interrupt on line %d\n", __LINE__)); \
508 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
512 if (--suppress_int == 0 && pending_int) {
516 #define INT_ON int_on()
517 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
525 #define FORCE_INT_ON force_int_on()
527 #define SAVE_INT(v) ((v) = suppress_int)
529 #define RESTORE_INT(v) do { \
531 suppress_int = (v); \
532 if (suppress_int == 0 && pending_int) \
537 /* ============ Stdout/stderr output */
540 outstr(const char *p, FILE *file)
548 flush_stdout_stderr(void)
555 /* Was called outcslow(c,FILE*), but c was always '\n' */
557 newline_and_flush(FILE *dest)
565 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
567 out1fmt(const char *fmt, ...)
574 r = vprintf(fmt, ap);
580 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
582 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
589 ret = vsnprintf(outbuf, length, fmt, ap);
596 out1str(const char *p)
602 out2str(const char *p)
605 flush_stdout_stderr();
609 /* ============ Parser structures */
611 /* control characters in argument strings */
612 #define CTL_FIRST CTLESC
613 #define CTLESC ((unsigned char)'\201') /* escape next character */
614 #define CTLVAR ((unsigned char)'\202') /* variable defn */
615 #define CTLENDVAR ((unsigned char)'\203')
616 #define CTLBACKQ ((unsigned char)'\204')
617 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
618 #define CTLENDARI ((unsigned char)'\207')
619 #define CTLQUOTEMARK ((unsigned char)'\210')
620 #define CTL_LAST CTLQUOTEMARK
622 /* variable substitution byte (follows CTLVAR) */
623 #define VSTYPE 0x0f /* type of variable substitution */
624 #define VSNUL 0x10 /* colon--treat the empty string as unset */
626 /* values of VSTYPE field */
627 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
628 #define VSMINUS 0x2 /* ${var-text} */
629 #define VSPLUS 0x3 /* ${var+text} */
630 #define VSQUESTION 0x4 /* ${var?message} */
631 #define VSASSIGN 0x5 /* ${var=text} */
632 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
633 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
634 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
635 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
636 #define VSLENGTH 0xa /* ${#var} */
637 #if ENABLE_ASH_BASH_COMPAT
638 #define VSSUBSTR 0xc /* ${var:position:length} */
639 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
640 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
643 static const char dolatstr[] ALIGN1 = {
644 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
646 #define DOLATSTRLEN 6
665 #if ENABLE_ASH_BASH_COMPAT
682 smallint type; /* Nxxxx */
685 union node *redirect;
690 smallint pipe_backgnd;
691 struct nodelist *cmdlist;
697 union node *redirect;
710 union node *elsepart;
737 struct nodelist *backquote;
740 /* nfile and ndup layout must match!
741 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
742 * that it is actually NTO2 (>&file), and change its type.
759 char *_unused_expfname;
778 struct nredir nredir;
779 struct nbinary nbinary;
783 struct nclist nclist;
792 * NODE_EOF is returned by parsecmd when it encounters an end of file.
793 * It must be distinct from NULL.
795 #define NODE_EOF ((union node *) -1L)
798 struct nodelist *next;
811 freefunc(struct funcnode *f)
813 if (f && --f->count < 0)
818 /* ============ Debugging output */
822 static FILE *tracefile;
825 trace_printf(const char *fmt, ...)
832 fprintf(tracefile, "%u ", (int) time(NULL));
834 fprintf(tracefile, "[%u] ", (int) getpid());
836 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
838 vfprintf(tracefile, fmt, va);
843 trace_vprintf(const char *fmt, va_list va)
847 vfprintf(tracefile, fmt, va);
848 fprintf(tracefile, "\n");
852 trace_puts(const char *s)
860 trace_puts_quoted(char *s)
867 putc('"', tracefile);
868 for (p = s; *p; p++) {
869 switch ((unsigned char)*p) {
870 case '\n': c = 'n'; goto backslash;
871 case '\t': c = 't'; goto backslash;
872 case '\r': c = 'r'; goto backslash;
873 case '\"': c = '\"'; goto backslash;
874 case '\\': c = '\\'; goto backslash;
875 case CTLESC: c = 'e'; goto backslash;
876 case CTLVAR: c = 'v'; goto backslash;
877 case CTLBACKQ: c = 'q'; goto backslash;
879 putc('\\', tracefile);
883 if (*p >= ' ' && *p <= '~')
886 putc('\\', tracefile);
887 putc((*p >> 6) & 03, tracefile);
888 putc((*p >> 3) & 07, tracefile);
889 putc(*p & 07, tracefile);
894 putc('"', tracefile);
898 trace_puts_args(char **ap)
905 trace_puts_quoted(*ap);
907 putc('\n', tracefile);
910 putc(' ', tracefile);
925 /* leave open because libedit might be using it */
928 strcpy(s, "./trace");
930 if (!freopen(s, "a", tracefile)) {
931 fprintf(stderr, "Can't re-open %s\n", s);
936 tracefile = fopen(s, "a");
937 if (tracefile == NULL) {
938 fprintf(stderr, "Can't open %s\n", s);
944 flags = fcntl(fileno(tracefile), F_GETFL);
946 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
948 setlinebuf(tracefile);
949 fputs("\nTracing started.\n", tracefile);
953 indent(int amount, char *pfx, FILE *fp)
957 for (i = 0; i < amount; i++) {
958 if (pfx && i == amount - 1)
964 /* little circular references here... */
965 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
968 sharg(union node *arg, FILE *fp)
971 struct nodelist *bqlist;
972 unsigned char subtype;
974 if (arg->type != NARG) {
975 out1fmt("<node type %d>\n", arg->type);
978 bqlist = arg->narg.backquote;
979 for (p = arg->narg.text; *p; p++) {
980 switch ((unsigned char)*p) {
989 if (subtype == VSLENGTH)
1000 switch (subtype & VSTYPE) {
1026 case VSTRIMRIGHTMAX:
1033 out1fmt("<subtype %d>", subtype);
1042 shtree(bqlist->n, -1, NULL, fp);
1053 shcmd(union node *cmd, FILE *fp)
1061 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1067 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1071 switch (np->nfile.type) {
1072 case NTO: s = ">>"+1; dftfd = 1; break;
1073 case NCLOBBER: s = ">|"; dftfd = 1; break;
1074 case NAPPEND: s = ">>"; dftfd = 1; break;
1075 #if ENABLE_ASH_BASH_COMPAT
1078 case NTOFD: s = ">&"; dftfd = 1; break;
1079 case NFROM: s = "<"; break;
1080 case NFROMFD: s = "<&"; break;
1081 case NFROMTO: s = "<>"; break;
1082 default: s = "*error*"; break;
1084 if (np->nfile.fd != dftfd)
1085 fprintf(fp, "%d", np->nfile.fd);
1087 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1088 fprintf(fp, "%d", np->ndup.dupfd);
1090 sharg(np->nfile.fname, fp);
1097 shtree(union node *n, int ind, char *pfx, FILE *fp)
1099 struct nodelist *lp;
1105 indent(ind, pfx, fp);
1107 if (n == NODE_EOF) {
1122 shtree(n->nbinary.ch1, ind, NULL, fp);
1125 shtree(n->nbinary.ch2, ind, NULL, fp);
1133 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1134 shtree(lp->n, 0, NULL, fp);
1138 if (n->npipe.pipe_backgnd)
1144 fprintf(fp, "<node type %d>", n->type);
1152 showtree(union node *n)
1154 trace_puts("showtree called\n");
1155 shtree(n, 1, NULL, stderr);
1161 /* ============ Parser data */
1164 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1167 struct strlist *next;
1174 struct strpush *prev; /* preceding string on stack */
1176 int prev_left_in_line;
1177 #if ENABLE_ASH_ALIAS
1178 struct alias *ap; /* if push was associated with an alias */
1180 char *string; /* remember the string since it may change */
1182 /* Remember last two characters for pungetc. */
1185 /* Number of outstanding calls to pungetc. */
1190 struct parsefile *prev; /* preceding file on stack */
1191 int linno; /* current line */
1192 int pf_fd; /* file descriptor (or -1 if string) */
1193 int left_in_line; /* number of chars left in this line */
1194 int left_in_buffer; /* number of chars left in this buffer past the line */
1195 char *next_to_pgetc; /* next char in buffer */
1196 char *buf; /* input buffer */
1197 struct strpush *strpush; /* for pushing strings at this level */
1198 struct strpush basestrpush; /* so pushing one is fast */
1200 /* Remember last two characters for pungetc. */
1203 /* Number of outstanding calls to pungetc. */
1207 static struct parsefile basepf; /* top level input file */
1208 static struct parsefile *g_parsefile = &basepf; /* current input file */
1209 static int startlinno; /* line # where last token started */
1210 static char *commandname; /* currently executing command */
1211 static struct strlist *cmdenviron; /* environment for builtin command */
1214 /* ============ Message printing */
1217 ash_vmsg(const char *msg, va_list ap)
1219 fprintf(stderr, "%s: ", arg0);
1221 if (strcmp(arg0, commandname))
1222 fprintf(stderr, "%s: ", commandname);
1223 if (!iflag || g_parsefile->pf_fd > 0)
1224 fprintf(stderr, "line %d: ", startlinno);
1226 vfprintf(stderr, msg, ap);
1227 newline_and_flush(stderr);
1231 * Exverror is called to raise the error exception. If the second argument
1232 * is not NULL then error prints an error message using printf style
1233 * formatting. It then raises the error exception.
1235 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1237 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1241 TRACE(("ash_vmsg_and_raise(%d):", cond));
1244 TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
1249 flush_stdout_stderr();
1250 raise_exception(cond);
1254 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1256 ash_msg_and_raise_error(const char *msg, ...)
1261 ash_vmsg_and_raise(EXERROR, msg, ap);
1266 static void raise_error_syntax(const char *) NORETURN;
1268 raise_error_syntax(const char *msg)
1270 ash_msg_and_raise_error("syntax error: %s", msg);
1274 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1276 ash_msg_and_raise(int cond, const char *msg, ...)
1281 ash_vmsg_and_raise(cond, msg, ap);
1287 * error/warning routines for external builtins
1290 ash_msg(const char *fmt, ...)
1300 * Return a string describing an error. The returned string may be a
1301 * pointer to a static buffer that will be overwritten on the next call.
1302 * Action describes the operation that got the error.
1305 errmsg(int e, const char *em)
1307 if (e == ENOENT || e == ENOTDIR) {
1314 /* ============ Memory allocation */
1317 /* I consider these wrappers nearly useless:
1318 * ok, they return you to nearest exception handler, but
1319 * how much memory do you leak in the process, making
1320 * memory starvation worse?
1323 ckrealloc(void * p, size_t nbytes)
1325 p = realloc(p, nbytes);
1327 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1332 ckmalloc(size_t nbytes)
1334 return ckrealloc(NULL, nbytes);
1338 ckzalloc(size_t nbytes)
1340 return memset(ckmalloc(nbytes), 0, nbytes);
1344 ckstrdup(const char *s)
1346 char *p = strdup(s);
1348 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1352 /* Using bbox equivalents. They exit if out of memory */
1353 # define ckrealloc xrealloc
1354 # define ckmalloc xmalloc
1355 # define ckzalloc xzalloc
1356 # define ckstrdup xstrdup
1360 * It appears that grabstackstr() will barf with such alignments
1361 * because stalloc() will return a string allocated in a new stackblock.
1363 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1365 /* Most machines require the value returned from malloc to be aligned
1366 * in some way. The following macro will get this right
1367 * on many machines. */
1368 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1369 /* Minimum size of a block */
1370 MINSIZE = SHELL_ALIGN(504),
1373 struct stack_block {
1374 struct stack_block *prev;
1375 char space[MINSIZE];
1379 struct stack_block *stackp;
1385 struct globals_memstack {
1386 struct stack_block *g_stackp; // = &stackbase;
1387 char *g_stacknxt; // = stackbase.space;
1388 char *sstrend; // = stackbase.space + MINSIZE;
1389 size_t g_stacknleft; // = MINSIZE;
1390 struct stack_block stackbase;
1392 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1393 #define G_memstack (*ash_ptr_to_globals_memstack)
1394 #define g_stackp (G_memstack.g_stackp )
1395 #define g_stacknxt (G_memstack.g_stacknxt )
1396 #define sstrend (G_memstack.sstrend )
1397 #define g_stacknleft (G_memstack.g_stacknleft)
1398 #define stackbase (G_memstack.stackbase )
1399 #define INIT_G_memstack() do { \
1400 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1402 g_stackp = &stackbase; \
1403 g_stacknxt = stackbase.space; \
1404 g_stacknleft = MINSIZE; \
1405 sstrend = stackbase.space + MINSIZE; \
1409 #define stackblock() ((void *)g_stacknxt)
1410 #define stackblocksize() g_stacknleft
1413 * Parse trees for commands are allocated in lifo order, so we use a stack
1414 * to make this more efficient, and also to avoid all sorts of exception
1415 * handling code to handle interrupts in the middle of a parse.
1417 * The size 504 was chosen because the Ultrix malloc handles that size
1421 stalloc(size_t nbytes)
1426 aligned = SHELL_ALIGN(nbytes);
1427 if (aligned > g_stacknleft) {
1430 struct stack_block *sp;
1432 blocksize = aligned;
1433 if (blocksize < MINSIZE)
1434 blocksize = MINSIZE;
1435 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1436 if (len < blocksize)
1437 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1440 sp->prev = g_stackp;
1441 g_stacknxt = sp->space;
1442 g_stacknleft = blocksize;
1443 sstrend = g_stacknxt + blocksize;
1448 g_stacknxt += aligned;
1449 g_stacknleft -= aligned;
1454 stzalloc(size_t nbytes)
1456 return memset(stalloc(nbytes), 0, nbytes);
1463 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1464 write(STDERR_FILENO, "stunalloc\n", 10);
1468 g_stacknleft += g_stacknxt - (char *)p;
1473 * Like strdup but works with the ash stack.
1476 sstrdup(const char *p)
1478 size_t len = strlen(p) + 1;
1479 return memcpy(stalloc(len), p, len);
1483 grabstackblock(size_t len)
1489 pushstackmark(struct stackmark *mark, size_t len)
1491 mark->stackp = g_stackp;
1492 mark->stacknxt = g_stacknxt;
1493 mark->stacknleft = g_stacknleft;
1494 grabstackblock(len);
1498 setstackmark(struct stackmark *mark)
1500 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1504 popstackmark(struct stackmark *mark)
1506 struct stack_block *sp;
1512 while (g_stackp != mark->stackp) {
1514 g_stackp = sp->prev;
1517 g_stacknxt = mark->stacknxt;
1518 g_stacknleft = mark->stacknleft;
1519 sstrend = mark->stacknxt + mark->stacknleft;
1524 * When the parser reads in a string, it wants to stick the string on the
1525 * stack and only adjust the stack pointer when it knows how big the
1526 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1527 * of space on top of the stack and stackblocklen returns the length of
1528 * this block. Growstackblock will grow this space by at least one byte,
1529 * possibly moving it (like realloc). Grabstackblock actually allocates the
1530 * part of the block that has been used.
1533 growstackblock(void)
1537 newlen = g_stacknleft * 2;
1538 if (newlen < g_stacknleft)
1539 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1543 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1544 struct stack_block *sp;
1545 struct stack_block *prevstackp;
1550 prevstackp = sp->prev;
1551 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1552 sp = ckrealloc(sp, grosslen);
1553 sp->prev = prevstackp;
1555 g_stacknxt = sp->space;
1556 g_stacknleft = newlen;
1557 sstrend = sp->space + newlen;
1560 char *oldspace = g_stacknxt;
1561 size_t oldlen = g_stacknleft;
1562 char *p = stalloc(newlen);
1564 /* free the space we just allocated */
1565 g_stacknxt = memcpy(p, oldspace, oldlen);
1566 g_stacknleft += newlen;
1571 * The following routines are somewhat easier to use than the above.
1572 * The user declares a variable of type STACKSTR, which may be declared
1573 * to be a register. The macro STARTSTACKSTR initializes things. Then
1574 * the user uses the macro STPUTC to add characters to the string. In
1575 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1576 * grown as necessary. When the user is done, she can just leave the
1577 * string there and refer to it using stackblock(). Or she can allocate
1578 * the space for it using grabstackstr(). If it is necessary to allow
1579 * someone else to use the stack temporarily and then continue to grow
1580 * the string, the user should use grabstack to allocate the space, and
1581 * then call ungrabstr(p) to return to the previous mode of operation.
1583 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1584 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1585 * is space for at least one character.
1590 size_t len = stackblocksize();
1592 return (char *)stackblock() + len;
1596 * Called from CHECKSTRSPACE.
1599 makestrspace(size_t newlen, char *p)
1601 size_t len = p - g_stacknxt;
1607 size = stackblocksize();
1609 if (nleft >= newlen)
1613 return (char *)stackblock() + len;
1617 stack_nputstr(const char *s, size_t n, char *p)
1619 p = makestrspace(n, p);
1620 p = (char *)memcpy(p, s, n) + n;
1625 stack_putstr(const char *s, char *p)
1627 return stack_nputstr(s, strlen(s), p);
1631 _STPUTC(int c, char *p)
1639 #define STARTSTACKSTR(p) ((p) = stackblock())
1640 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1641 #define CHECKSTRSPACE(n, p) do { \
1644 size_t m = sstrend - q; \
1646 (p) = makestrspace(l, q); \
1648 #define USTPUTC(c, p) (*(p)++ = (c))
1649 #define STACKSTRNUL(p) do { \
1650 if ((p) == sstrend) \
1651 (p) = growstackstr(); \
1654 #define STUNPUTC(p) (--(p))
1655 #define STTOPC(p) ((p)[-1])
1656 #define STADJUST(amount, p) ((p) += (amount))
1658 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1659 #define ungrabstackstr(s, p) stunalloc(s)
1660 #define stackstrend() ((void *)sstrend)
1663 /* ============ String helpers */
1666 * prefix -- see if pfx is a prefix of string.
1669 prefix(const char *string, const char *pfx)
1672 if (*pfx++ != *string++)
1675 return (char *) string;
1679 * Check for a valid number. This should be elsewhere.
1682 is_number(const char *p)
1687 } while (*++p != '\0');
1692 * Convert a string of digits to an integer, printing an error message on
1696 number(const char *s)
1699 ash_msg_and_raise_error(msg_illnum, s);
1704 * Produce a possibly single quoted string suitable as input to the shell.
1705 * The return string is allocated on the stack.
1708 single_quote(const char *s)
1718 len = strchrnul(s, '\'') - s;
1720 q = p = makestrspace(len + 3, p);
1723 q = (char *)memcpy(q, s, len) + len;
1732 do len++; while (*++s == '\'');
1734 q = p = makestrspace(len + 3, p);
1737 q = (char *)memcpy(q, s - len, len) + len;
1745 return stackblock();
1749 /* ============ nextopt */
1751 static char **argptr; /* argument list for builtin commands */
1752 static char *optionarg; /* set by nextopt (like getopt) */
1753 static char *optptr; /* used by nextopt */
1756 * XXX - should get rid of. Have all builtins use getopt(3).
1757 * The library getopt must have the BSD extension static variable
1758 * "optreset", otherwise it can't be used within the shell safely.
1760 * Standard option processing (a la getopt) for builtin routines.
1761 * The only argument that is passed to nextopt is the option string;
1762 * the other arguments are unnecessary. It returns the character,
1763 * or '\0' on end of input.
1766 nextopt(const char *optstring)
1773 if (p == NULL || *p == '\0') {
1774 /* We ate entire "-param", take next one */
1780 if (*++p == '\0') /* just "-" ? */
1783 if (LONE_DASH(p)) /* "--" ? */
1785 /* p => next "-param" */
1787 /* p => some option char in the middle of a "-param" */
1789 for (q = optstring; *q != c;) {
1791 ash_msg_and_raise_error("illegal option -%c", c);
1799 ash_msg_and_raise_error("no arg for -%c option", c);
1809 /* ============ Shell variables */
1812 * The parsefile structure pointed to by the global variable parsefile
1813 * contains information about the current file being read.
1816 int nparam; /* # of positional parameters (without $0) */
1817 #if ENABLE_ASH_GETOPTS
1818 int optind; /* next parameter to be processed by getopts */
1819 int optoff; /* used by getopts */
1821 unsigned char malloced; /* if parameter list dynamically allocated */
1822 char **p; /* parameter list */
1826 * Free the list of positional parameters.
1829 freeparam(volatile struct shparam *param)
1831 if (param->malloced) {
1833 ap = ap1 = param->p;
1840 #if ENABLE_ASH_GETOPTS
1841 static void FAST_FUNC getoptsreset(const char *value);
1845 struct var *next; /* next entry in hash list */
1846 int flags; /* flags are defined above */
1847 const char *var_text; /* name=value */
1848 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1849 /* the variable gets set/unset */
1853 struct localvar *next; /* next local variable in list */
1854 struct var *vp; /* the variable that was made local */
1855 int flags; /* saved flags */
1856 const char *text; /* saved text */
1860 #define VEXPORT 0x01 /* variable is exported */
1861 #define VREADONLY 0x02 /* variable cannot be modified */
1862 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1863 #define VTEXTFIXED 0x08 /* text is statically allocated */
1864 #define VSTACK 0x10 /* text is allocated on the stack */
1865 #define VUNSET 0x20 /* the variable is not set */
1866 #define VNOFUNC 0x40 /* don't call the callback function */
1867 #define VNOSET 0x80 /* do not set variable - just readonly test */
1868 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1869 #if ENABLE_ASH_RANDOM_SUPPORT
1870 # define VDYNAMIC 0x200 /* dynamic variable */
1876 /* Need to be before varinit_data[] */
1877 #if ENABLE_LOCALE_SUPPORT
1878 static void FAST_FUNC
1879 change_lc_all(const char *value)
1881 if (value && *value != '\0')
1882 setlocale(LC_ALL, value);
1884 static void FAST_FUNC
1885 change_lc_ctype(const char *value)
1887 if (value && *value != '\0')
1888 setlocale(LC_CTYPE, value);
1892 static void chkmail(void);
1893 static void changemail(const char *var_value) FAST_FUNC;
1895 # define chkmail() ((void)0)
1897 static void changepath(const char *) FAST_FUNC;
1898 #if ENABLE_ASH_RANDOM_SUPPORT
1899 static void change_random(const char *) FAST_FUNC;
1902 static const struct {
1904 const char *var_text;
1905 void (*var_func)(const char *) FAST_FUNC;
1906 } varinit_data[] = {
1908 * Note: VEXPORT would not work correctly here for NOFORK applets:
1909 * some environment strings may be constant.
1911 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1913 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1914 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1916 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1917 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1918 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1919 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1920 #if ENABLE_ASH_GETOPTS
1921 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
1923 #if ENABLE_ASH_RANDOM_SUPPORT
1924 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1926 #if ENABLE_LOCALE_SUPPORT
1927 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1928 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1930 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1931 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1937 struct globals_var {
1938 struct shparam shellparam; /* $@ current positional parameters */
1939 struct redirtab *redirlist;
1940 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1941 struct var *vartab[VTABSIZE];
1942 struct var varinit[ARRAY_SIZE(varinit_data)];
1944 extern struct globals_var *const ash_ptr_to_globals_var;
1945 #define G_var (*ash_ptr_to_globals_var)
1946 #define shellparam (G_var.shellparam )
1947 //#define redirlist (G_var.redirlist )
1948 #define preverrout_fd (G_var.preverrout_fd)
1949 #define vartab (G_var.vartab )
1950 #define varinit (G_var.varinit )
1951 #define INIT_G_var() do { \
1953 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1955 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1956 varinit[i].flags = varinit_data[i].flags; \
1957 varinit[i].var_text = varinit_data[i].var_text; \
1958 varinit[i].var_func = varinit_data[i].var_func; \
1962 #define vifs varinit[0]
1964 # define vmail (&vifs)[1]
1965 # define vmpath (&vmail)[1]
1966 # define vpath (&vmpath)[1]
1968 # define vpath (&vifs)[1]
1970 #define vps1 (&vpath)[1]
1971 #define vps2 (&vps1)[1]
1972 #define vps4 (&vps2)[1]
1973 #if ENABLE_ASH_GETOPTS
1974 # define voptind (&vps4)[1]
1975 # if ENABLE_ASH_RANDOM_SUPPORT
1976 # define vrandom (&voptind)[1]
1979 # if ENABLE_ASH_RANDOM_SUPPORT
1980 # define vrandom (&vps4)[1]
1985 * The following macros access the values of the above variables.
1986 * They have to skip over the name. They return the null string
1987 * for unset variables.
1989 #define ifsval() (vifs.var_text + 4)
1990 #define ifsset() ((vifs.flags & VUNSET) == 0)
1992 # define mailval() (vmail.var_text + 5)
1993 # define mpathval() (vmpath.var_text + 9)
1994 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1996 #define pathval() (vpath.var_text + 5)
1997 #define ps1val() (vps1.var_text + 4)
1998 #define ps2val() (vps2.var_text + 4)
1999 #define ps4val() (vps4.var_text + 4)
2000 #if ENABLE_ASH_GETOPTS
2001 # define optindval() (voptind.var_text + 7)
2004 #if ENABLE_ASH_GETOPTS
2005 static void FAST_FUNC
2006 getoptsreset(const char *value)
2008 shellparam.optind = number(value) ?: 1;
2009 shellparam.optoff = -1;
2014 * Compares two strings up to the first = or '\0'. The first
2015 * string must be terminated by '='; the second may be terminated by
2016 * either '=' or '\0'.
2019 varcmp(const char *p, const char *q)
2023 while ((c = *p) == (d = *q)) {
2024 if (c == '\0' || c == '=')
2038 * Find the appropriate entry in the hash table from the name.
2040 static struct var **
2041 hashvar(const char *p)
2045 hashval = ((unsigned char) *p) << 4;
2046 while (*p && *p != '=')
2047 hashval += (unsigned char) *p++;
2048 return &vartab[hashval % VTABSIZE];
2052 vpcmp(const void *a, const void *b)
2054 return varcmp(*(const char **)a, *(const char **)b);
2058 * This routine initializes the builtin variables.
2068 * PS1 depends on uid
2070 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2071 vps1.var_text = "PS1=\\w \\$ ";
2074 vps1.var_text = "PS1=# ";
2077 end = vp + ARRAY_SIZE(varinit);
2079 vpp = hashvar(vp->var_text);
2082 } while (++vp < end);
2085 static struct var **
2086 findvar(struct var **vpp, const char *name)
2088 for (; *vpp; vpp = &(*vpp)->next) {
2089 if (varcmp((*vpp)->var_text, name) == 0) {
2097 * Find the value of a variable. Returns NULL if not set.
2099 static const char* FAST_FUNC
2100 lookupvar(const char *name)
2104 v = *findvar(hashvar(name), name);
2106 #if ENABLE_ASH_RANDOM_SUPPORT
2108 * Dynamic variables are implemented roughly the same way they are
2109 * in bash. Namely, they're "special" so long as they aren't unset.
2110 * As soon as they're unset, they're no longer dynamic, and dynamic
2111 * lookup will no longer happen at that point. -- PFM.
2113 if (v->flags & VDYNAMIC)
2116 if (!(v->flags & VUNSET))
2117 return var_end(v->var_text);
2123 reinit_unicode_for_ash(void)
2125 /* Unicode support should be activated even if LANG is set
2126 * _during_ shell execution, not only if it was set when
2127 * shell was started. Therefore, re-check LANG every time:
2129 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2130 || ENABLE_UNICODE_USING_LOCALE
2132 const char *s = lookupvar("LC_ALL");
2133 if (!s) s = lookupvar("LC_CTYPE");
2134 if (!s) s = lookupvar("LANG");
2140 * Search the environment of a builtin command.
2143 bltinlookup(const char *name)
2147 for (sp = cmdenviron; sp; sp = sp->next) {
2148 if (varcmp(sp->text, name) == 0)
2149 return var_end(sp->text);
2151 return lookupvar(name);
2155 * Same as setvar except that the variable and value are passed in
2156 * the first argument as name=value. Since the first argument will
2157 * be actually stored in the table, it should not be a string that
2159 * Called with interrupts off.
2162 setvareq(char *s, int flags)
2164 struct var *vp, **vpp;
2167 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2168 vp = *findvar(vpp, s);
2170 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2173 if (flags & VNOSAVE)
2177 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2183 if (vp->var_func && !(flags & VNOFUNC))
2184 vp->var_func(var_end(s));
2186 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2187 free((char*)vp->var_text);
2189 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2191 /* variable s is not found */
2194 vp = ckzalloc(sizeof(*vp));
2196 /*vp->func = NULL; - ckzalloc did it */
2199 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2206 * Set the value of a variable. The flags argument is ored with the
2207 * flags of the variable. If val is NULL, the variable is unset.
2210 setvar(const char *name, const char *val, int flags)
2218 q = endofname(name);
2219 p = strchrnul(q, '=');
2221 if (!namelen || p != q)
2222 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2227 vallen = strlen(val);
2231 nameeq = ckmalloc(namelen + vallen + 2);
2232 p = memcpy(nameeq, name, namelen) + namelen;
2235 p = memcpy(p, val, vallen) + vallen;
2238 setvareq(nameeq, flags | VNOSAVE);
2242 static void FAST_FUNC
2243 setvar0(const char *name, const char *val)
2245 setvar(name, val, 0);
2249 * Unset the specified variable.
2252 unsetvar(const char *s)
2258 vpp = findvar(hashvar(s), s);
2262 int flags = vp->flags;
2265 if (flags & VREADONLY)
2267 #if ENABLE_ASH_RANDOM_SUPPORT
2268 vp->flags &= ~VDYNAMIC;
2272 if ((flags & VSTRFIXED) == 0) {
2274 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2275 free((char*)vp->var_text);
2281 vp->flags &= ~VEXPORT;
2291 * Process a linked list of variable assignments.
2294 listsetvar(struct strlist *list_set_var, int flags)
2296 struct strlist *lp = list_set_var;
2302 setvareq(lp->text, flags);
2309 * Generate a list of variables satisfying the given conditions.
2312 listvars(int on, int off, char ***end)
2323 for (vp = *vpp; vp; vp = vp->next) {
2324 if ((vp->flags & mask) == on) {
2325 if (ep == stackstrend())
2326 ep = growstackstr();
2327 *ep++ = (char*)vp->var_text;
2330 } while (++vpp < vartab + VTABSIZE);
2331 if (ep == stackstrend())
2332 ep = growstackstr();
2336 return grabstackstr(ep);
2340 /* ============ Path search helper
2342 * The variable path (passed by reference) should be set to the start
2343 * of the path before the first call; path_advance will update
2344 * this value as it proceeds. Successive calls to path_advance will return
2345 * the possible path expansions in sequence. If an option (indicated by
2346 * a percent sign) appears in the path entry then the global variable
2347 * pathopt will be set to point to it; otherwise pathopt will be set to
2350 static const char *pathopt; /* set by path_advance */
2353 path_advance(const char **path, const char *name)
2363 for (p = start; *p && *p != ':' && *p != '%'; p++)
2365 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2366 while (stackblocksize() < len)
2370 memcpy(q, start, p - start);
2378 while (*p && *p != ':')
2385 return stalloc(len);
2389 /* ============ Prompt */
2391 static smallint doprompt; /* if set, prompt the user */
2392 static smallint needprompt; /* true if interactive and at start of line */
2394 #if ENABLE_FEATURE_EDITING
2395 static line_input_t *line_input_state;
2396 static const char *cmdedit_prompt;
2398 putprompt(const char *s)
2400 if (ENABLE_ASH_EXPAND_PRMT) {
2401 free((char*)cmdedit_prompt);
2402 cmdedit_prompt = ckstrdup(s);
2409 putprompt(const char *s)
2415 #if ENABLE_ASH_EXPAND_PRMT
2416 /* expandstr() needs parsing machinery, so it is far away ahead... */
2417 static const char *expandstr(const char *ps);
2419 #define expandstr(s) s
2423 setprompt_if(smallint do_set, int whichprompt)
2426 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2433 switch (whichprompt) {
2443 #if ENABLE_ASH_EXPAND_PRMT
2444 pushstackmark(&smark, stackblocksize());
2446 putprompt(expandstr(prompt));
2447 #if ENABLE_ASH_EXPAND_PRMT
2448 popstackmark(&smark);
2453 /* ============ The cd and pwd commands */
2455 #define CD_PHYSICAL 1
2465 while ((i = nextopt("LP")) != '\0') {
2467 flags ^= CD_PHYSICAL;
2476 * Update curdir (the name of the current directory) in response to a
2480 updatepwd(const char *dir)
2487 cdcomppath = sstrdup(dir);
2490 if (curdir == nullstr)
2492 new = stack_putstr(curdir, new);
2494 new = makestrspace(strlen(dir) + 2, new);
2495 lim = (char *)stackblock() + 1;
2499 if (new > lim && *lim == '/')
2504 if (dir[1] == '/' && dir[2] != '/') {
2510 p = strtok(cdcomppath, "/");
2514 if (p[1] == '.' && p[2] == '\0') {
2526 new = stack_putstr(p, new);
2529 p = strtok(NULL, "/");
2534 return stackblock();
2538 * Find out what the current directory is. If we already know the current
2539 * directory, this routine returns immediately.
2544 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2545 return dir ? dir : nullstr;
2549 setpwd(const char *val, int setold)
2553 oldcur = dir = curdir;
2556 setvar("OLDPWD", oldcur, VEXPORT);
2559 if (physdir != nullstr) {
2560 if (physdir != oldcur)
2564 if (oldcur == val || !val) {
2570 dir = ckstrdup(val);
2571 if (oldcur != dir && oldcur != nullstr) {
2576 setvar("PWD", dir, VEXPORT);
2579 static void hashcd(void);
2582 * Actually do the chdir. We also call hashcd to let other routines
2583 * know that the current directory has changed.
2586 docd(const char *dest, int flags)
2588 const char *dir = NULL;
2591 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2594 if (!(flags & CD_PHYSICAL)) {
2595 dir = updatepwd(dest);
2609 static int FAST_FUNC
2610 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2622 dest = bltinlookup("HOME");
2623 else if (LONE_DASH(dest)) {
2624 dest = bltinlookup("OLDPWD");
2646 path = bltinlookup("CDPATH");
2649 p = path_advance(&path, dest);
2650 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2654 if (!docd(p, flags))
2665 ash_msg_and_raise_error("can't cd to %s", dest);
2668 if (flags & CD_PRINT)
2669 out1fmt("%s\n", curdir);
2673 static int FAST_FUNC
2674 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2677 const char *dir = curdir;
2681 if (physdir == nullstr)
2685 out1fmt("%s\n", dir);
2690 /* ============ ... */
2693 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2695 /* Syntax classes */
2696 #define CWORD 0 /* character is nothing special */
2697 #define CNL 1 /* newline character */
2698 #define CBACK 2 /* a backslash character */
2699 #define CSQUOTE 3 /* single quote */
2700 #define CDQUOTE 4 /* double quote */
2701 #define CENDQUOTE 5 /* a terminating quote */
2702 #define CBQUOTE 6 /* backwards single quote */
2703 #define CVAR 7 /* a dollar sign */
2704 #define CENDVAR 8 /* a '}' character */
2705 #define CLP 9 /* a left paren in arithmetic */
2706 #define CRP 10 /* a right paren in arithmetic */
2707 #define CENDFILE 11 /* end of file */
2708 #define CCTL 12 /* like CWORD, except it must be escaped */
2709 #define CSPCL 13 /* these terminate a word */
2710 #define CIGN 14 /* character should be ignored */
2713 #if ENABLE_ASH_ALIAS
2717 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2719 #if ENABLE_SH_MATH_SUPPORT
2720 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2722 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2724 static const uint16_t S_I_T[] ALIGN2 = {
2725 #if ENABLE_ASH_ALIAS
2726 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2728 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2729 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2730 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2731 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2732 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2733 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2734 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2735 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2736 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2737 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2738 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2739 #if !USE_SIT_FUNCTION
2740 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2741 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2742 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2746 /* Constants below must match table above */
2748 #if ENABLE_ASH_ALIAS
2749 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2751 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2752 CNL_CNL_CNL_CNL , /* 2 */
2753 CWORD_CCTL_CCTL_CWORD , /* 3 */
2754 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2755 CVAR_CVAR_CWORD_CVAR , /* 5 */
2756 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2757 CSPCL_CWORD_CWORD_CLP , /* 7 */
2758 CSPCL_CWORD_CWORD_CRP , /* 8 */
2759 CBACK_CBACK_CCTL_CBACK , /* 9 */
2760 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2761 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2762 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2763 CWORD_CWORD_CWORD_CWORD , /* 13 */
2764 CCTL_CCTL_CCTL_CCTL , /* 14 */
2767 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2768 * caller must ensure proper cast on it if c is *char_ptr!
2770 /* Values for syntax param */
2771 #define BASESYNTAX 0 /* not in quotes */
2772 #define DQSYNTAX 1 /* in double quotes */
2773 #define SQSYNTAX 2 /* in single quotes */
2774 #define ARISYNTAX 3 /* in arithmetic */
2775 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2777 #if USE_SIT_FUNCTION
2780 SIT(int c, int syntax)
2782 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2783 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2785 * This causes '/' to be prepended with CTLESC in dquoted string,
2786 * making "./file"* treated incorrectly because we feed
2787 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2788 * The "homegrown" glob implementation is okay with that,
2789 * but glibc one isn't. With '/' always treated as CWORD,
2792 # if ENABLE_ASH_ALIAS
2793 static const uint8_t syntax_index_table[] ALIGN1 = {
2794 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2795 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2796 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2800 static const uint8_t syntax_index_table[] ALIGN1 = {
2801 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2802 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2803 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2812 # if ENABLE_ASH_ALIAS
2818 /* Cast is purely for paranoia here,
2819 * just in case someone passed signed char to us */
2820 if ((unsigned char)c >= CTL_FIRST
2821 && (unsigned char)c <= CTL_LAST
2825 s = strchrnul(spec_symbls, c);
2828 indx = syntax_index_table[s - spec_symbls];
2830 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2833 #else /* !USE_SIT_FUNCTION */
2835 static const uint8_t syntax_index_table[] ALIGN1 = {
2836 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2837 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2838 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2839 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2840 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2841 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2842 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2847 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2848 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2870 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2871 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2872 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2873 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2874 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2875 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2876 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2877 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2878 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2879 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2880 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2881 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2882 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2883 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2884 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2885 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2886 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2887 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2888 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2889 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2890 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2891 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2892 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2893 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2894 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2895 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2896 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2897 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2898 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2899 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2900 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2901 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2902 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2903 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2904 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2905 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2906 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2907 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2908 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2909 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2910 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2911 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2912 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2913 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2916 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2918 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2930 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2931 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2932 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2935 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2963 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2964 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2965 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2966 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2968 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2969 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2970 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2971 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2972 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2973 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2974 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2975 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2979 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2981 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2983 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2984 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2985 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2986 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2987 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2988 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2989 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2990 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2991 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2992 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2993 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2994 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2995 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2996 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2997 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2998 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2999 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3000 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3001 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3002 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3094 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3095 # if ENABLE_ASH_ALIAS
3096 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3100 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3102 #endif /* !USE_SIT_FUNCTION */
3105 /* ============ Alias handling */
3107 #if ENABLE_ASH_ALIAS
3109 #define ALIASINUSE 1
3120 static struct alias **atab; // [ATABSIZE];
3121 #define INIT_G_alias() do { \
3122 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3126 static struct alias **
3127 __lookupalias(const char *name)
3129 unsigned int hashval;
3136 ch = (unsigned char)*p;
3140 ch = (unsigned char)*++p;
3142 app = &atab[hashval % ATABSIZE];
3144 for (; *app; app = &(*app)->next) {
3145 if (strcmp(name, (*app)->name) == 0) {
3153 static struct alias *
3154 lookupalias(const char *name, int check)
3156 struct alias *ap = *__lookupalias(name);
3158 if (check && ap && (ap->flag & ALIASINUSE))
3163 static struct alias *
3164 freealias(struct alias *ap)
3168 if (ap->flag & ALIASINUSE) {
3169 ap->flag |= ALIASDEAD;
3181 setalias(const char *name, const char *val)
3183 struct alias *ap, **app;
3185 app = __lookupalias(name);
3189 if (!(ap->flag & ALIASINUSE)) {
3192 ap->val = ckstrdup(val);
3193 ap->flag &= ~ALIASDEAD;
3196 ap = ckzalloc(sizeof(struct alias));
3197 ap->name = ckstrdup(name);
3198 ap->val = ckstrdup(val);
3199 /*ap->flag = 0; - ckzalloc did it */
3200 /*ap->next = NULL;*/
3207 unalias(const char *name)
3211 app = __lookupalias(name);
3215 *app = freealias(*app);
3226 struct alias *ap, **app;
3230 for (i = 0; i < ATABSIZE; i++) {
3232 for (ap = *app; ap; ap = *app) {
3233 *app = freealias(*app);
3243 printalias(const struct alias *ap)
3245 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3249 * TODO - sort output
3251 static int FAST_FUNC
3252 aliascmd(int argc UNUSED_PARAM, char **argv)
3261 for (i = 0; i < ATABSIZE; i++) {
3262 for (ap = atab[i]; ap; ap = ap->next) {
3268 while ((n = *++argv) != NULL) {
3269 v = strchr(n+1, '=');
3270 if (v == NULL) { /* n+1: funny ksh stuff */
3271 ap = *__lookupalias(n);
3273 fprintf(stderr, "%s: %s not found\n", "alias", n);
3286 static int FAST_FUNC
3287 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3291 while ((i = nextopt("a")) != '\0') {
3297 for (i = 0; *argptr; argptr++) {
3298 if (unalias(*argptr)) {
3299 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3307 #endif /* ASH_ALIAS */
3310 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3313 #define FORK_NOJOB 2
3315 /* mode flags for showjob(s) */
3316 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3317 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3318 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3319 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3322 * A job structure contains information about a job. A job is either a
3323 * single process or a set of processes contained in a pipeline. In the
3324 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3328 pid_t ps_pid; /* process id */
3329 int ps_status; /* last process status from wait() */
3330 char *ps_cmd; /* text of command being run */
3334 struct procstat ps0; /* status of process */
3335 struct procstat *ps; /* status or processes when more than one */
3337 int stopstatus; /* status of a stopped job */
3340 nprocs: 16, /* number of processes */
3342 #define JOBRUNNING 0 /* at least one proc running */
3343 #define JOBSTOPPED 1 /* all procs are stopped */
3344 #define JOBDONE 2 /* all procs are completed */
3346 sigint: 1, /* job was killed by SIGINT */
3347 jobctl: 1, /* job running under job control */
3349 waited: 1, /* true if this entry has been waited for */
3350 used: 1, /* true if this entry is in used */
3351 changed: 1; /* true if status has changed */
3352 struct job *prev_job; /* previous job */
3355 static struct job *makejob(/*union node *,*/ int);
3356 static int forkshell(struct job *, union node *, int);
3357 static int waitforjob(struct job *);
3360 enum { doing_jobctl = 0 };
3361 #define setjobctl(on) do {} while (0)
3363 static smallint doing_jobctl; //references:8
3364 static void setjobctl(int);
3371 ignoresig(int signo)
3373 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3374 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3375 /* No, need to do it */
3376 signal(signo, SIG_IGN);
3378 sigmode[signo - 1] = S_HARD_IGN;
3382 * Only one usage site - in setsignal()
3385 signal_handler(int signo)
3387 if (signo == SIGCHLD) {
3393 gotsig[signo - 1] = 1;
3394 pending_sig = signo;
3396 if (signo == SIGINT && !trap[SIGINT]) {
3397 if (!suppress_int) {
3399 raise_interrupt(); /* does not return */
3406 * Set the signal handler for the specified signal. The routine figures
3407 * out what it should be set to.
3410 setsignal(int signo)
3413 char cur_act, new_act;
3414 struct sigaction act;
3418 if (t != NULL) { /* trap for this sig is set */
3420 if (t[0] == '\0') /* trap is "": ignore this sig */
3424 if (rootshell && new_act == S_DFL) {
3427 if (iflag || minusc || sflag == 0)
3436 * "In all cases, bash ignores SIGQUIT. Non-builtin
3437 * commands run by bash have signal handlers
3438 * set to the values inherited by the shell
3439 * from its parent". */
3455 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3456 //whereas we have to restore it to what shell got on entry
3457 //from the parent. See comment above
3459 if (signo == SIGCHLD)
3462 t = &sigmode[signo - 1];
3465 /* current setting is not yet known */
3466 if (sigaction(signo, NULL, &act)) {
3467 /* pretend it worked; maybe we should give a warning,
3468 * but other shells don't. We don't alter sigmode,
3469 * so we retry every time.
3470 * btw, in Linux it never fails. --vda */
3473 if (act.sa_handler == SIG_IGN) {
3474 cur_act = S_HARD_IGN;
3476 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3478 cur_act = S_IGN; /* don't hard ignore these */
3482 if (cur_act == S_HARD_IGN || cur_act == new_act)
3485 act.sa_handler = SIG_DFL;
3488 act.sa_handler = signal_handler;
3491 act.sa_handler = SIG_IGN;
3495 /* flags and mask matter only if !DFL and !IGN, but we do it
3496 * for all cases for more deterministic behavior:
3499 sigfillset(&act.sa_mask);
3501 sigaction_set(signo, &act);
3506 /* mode flags for set_curjob */
3507 #define CUR_DELETE 2
3508 #define CUR_RUNNING 1
3509 #define CUR_STOPPED 0
3512 /* pgrp of shell on invocation */
3513 static int initialpgrp; //references:2
3514 static int ttyfd = -1; //5
3517 static struct job *jobtab; //5
3519 static unsigned njobs; //4
3521 static struct job *curjob; //lots
3522 /* number of presumed living untracked jobs */
3523 static int jobless; //4
3526 set_curjob(struct job *jp, unsigned mode)
3529 struct job **jpp, **curp;
3531 /* first remove from list */
3532 jpp = curp = &curjob;
3537 jpp = &jp1->prev_job;
3539 *jpp = jp1->prev_job;
3541 /* Then re-insert in correct position */
3549 /* job being deleted */
3552 /* newly created job or backgrounded job,
3553 * put after all stopped jobs.
3558 if (!jp1 || jp1->state != JOBSTOPPED)
3561 jpp = &jp1->prev_job;
3567 /* newly stopped job - becomes curjob */
3568 jp->prev_job = *jpp;
3576 jobno(const struct job *jp)
3578 return jp - jobtab + 1;
3583 * Convert a job name to a job structure.
3586 #define getjob(name, getctl) getjob(name)
3589 getjob(const char *name, int getctl)
3593 const char *err_msg = "%s: no such job";
3597 char *(*match)(const char *, const char *);
3612 if (c == '+' || c == '%') {
3614 err_msg = "No current job";
3620 err_msg = "No previous job";
3630 if (num > 0 && num <= njobs) {
3631 jp = jobtab + num - 1;
3646 if (match(jp->ps[0].ps_cmd, p)) {
3650 err_msg = "%s: ambiguous";
3660 err_msg = "job %s not created under job control";
3661 if (getctl && jp->jobctl == 0)
3666 ash_msg_and_raise_error(err_msg, name);
3670 * Mark a job structure as unused.
3673 freejob(struct job *jp)
3675 struct procstat *ps;
3679 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3680 if (ps->ps_cmd != nullstr)
3683 if (jp->ps != &jp->ps0)
3686 set_curjob(jp, CUR_DELETE);
3692 xtcsetpgrp(int fd, pid_t pgrp)
3694 if (tcsetpgrp(fd, pgrp))
3695 ash_msg_and_raise_error("can't set tty process group (%m)");
3699 * Turn job control on and off.
3701 * Note: This code assumes that the third arg to ioctl is a character
3702 * pointer, which is true on Berkeley systems but not System V. Since
3703 * System V doesn't have job control yet, this isn't a problem now.
3705 * Called with interrupts off.
3713 if (on == doing_jobctl || rootshell == 0)
3717 ofd = fd = open(_PATH_TTY, O_RDWR);
3719 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3720 * That sometimes helps to acquire controlling tty.
3721 * Obviously, a workaround for bugs when someone
3722 * failed to provide a controlling tty to bash! :) */
3728 /* fd is a tty at this point */
3729 fd = fcntl(fd, F_DUPFD, 10);
3730 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, dont */
3733 goto out; /* F_DUPFD failed */
3734 close_on_exec_on(fd);
3735 while (1) { /* while we are in the background */
3736 pgrp = tcgetpgrp(fd);
3739 ash_msg("can't access tty; job control turned off");
3743 if (pgrp == getpgrp())
3754 xtcsetpgrp(fd, pgrp);
3756 /* turning job control off */
3759 /* was xtcsetpgrp, but this can make exiting ash
3760 * loop forever if pty is already deleted */
3761 tcsetpgrp(fd, pgrp);
3775 static int FAST_FUNC
3776 killcmd(int argc, char **argv)
3778 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3781 if (argv[i][0] == '%') {
3783 * "kill %N" - job kill
3784 * Converting to pgrp / pid kill
3790 jp = getjob(argv[i], 0);
3792 * In jobs started under job control, we signal
3793 * entire process group by kill -PGRP_ID.
3794 * This happens, f.e., in interactive shell.
3796 * Otherwise, we signal each child via
3797 * kill PID1 PID2 PID3.
3799 * sh -c 'sleep 1|sleep 1 & kill %1'
3800 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3801 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3803 n = jp->nprocs; /* can't be 0 (I hope) */
3806 dst = alloca(n * sizeof(int)*4);
3808 for (j = 0; j < n; j++) {
3809 struct procstat *ps = &jp->ps[j];
3810 /* Skip non-running and not-stopped members
3811 * (i.e. dead members) of the job
3813 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3816 * kill_main has matching code to expect
3817 * leading space. Needed to not confuse
3818 * negative pids with "kill -SIGNAL_NO" syntax
3820 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3824 } while (argv[++i]);
3826 return kill_main(argc, argv);
3830 showpipe(struct job *jp /*, FILE *out*/)
3832 struct procstat *ps;
3833 struct procstat *psend;
3835 psend = jp->ps + jp->nprocs;
3836 for (ps = jp->ps + 1; ps < psend; ps++)
3837 printf(" | %s", ps->ps_cmd);
3838 newline_and_flush(stdout);
3839 flush_stdout_stderr();
3844 restartjob(struct job *jp, int mode)
3846 struct procstat *ps;
3852 if (jp->state == JOBDONE)
3854 jp->state = JOBRUNNING;
3855 pgid = jp->ps[0].ps_pid;
3856 if (mode == FORK_FG)
3857 xtcsetpgrp(ttyfd, pgid);
3858 killpg(pgid, SIGCONT);
3862 if (WIFSTOPPED(ps->ps_status)) {
3868 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3873 static int FAST_FUNC
3874 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3880 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3884 jp = getjob(*argv, 1);
3885 if (mode == FORK_BG) {
3886 set_curjob(jp, CUR_RUNNING);
3887 printf("[%d] ", jobno(jp));
3889 out1str(jp->ps[0].ps_cmd);
3890 showpipe(jp /*, stdout*/);
3891 retval = restartjob(jp, mode);
3892 } while (*argv && *++argv);
3898 sprint_status48(char *s, int status, int sigonly)
3904 if (!WIFEXITED(status)) {
3905 if (JOBS && WIFSTOPPED(status))
3906 st = WSTOPSIG(status);
3908 st = WTERMSIG(status);
3910 if (st == SIGINT || st == SIGPIPE)
3912 if (JOBS && WIFSTOPPED(status))
3916 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3917 col = fmtstr(s, 32, strsignal(st));
3918 if (WCOREDUMP(status)) {
3919 strcpy(s + col, " (core dumped)");
3920 col += sizeof(" (core dumped)")-1;
3922 } else if (!sigonly) {
3923 st = WEXITSTATUS(status);
3924 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
3931 wait_block_or_sig(int *status)
3938 /* Poll all children for changes in their state */
3940 /* if job control is active, accept stopped processes too */
3941 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
3943 break; /* Error (e.g. EINTR, ECHILD) or pid */
3945 /* Children exist, but none are ready. Sleep until interesting signal */
3948 sigprocmask(SIG_SETMASK, &mask, &mask);
3949 while (!got_sigchld && !pending_sig)
3951 sigprocmask(SIG_SETMASK, &mask, NULL);
3952 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
3953 while (!got_sigchld && !pending_sig)
3957 /* If it was SIGCHLD, poll children again */
3958 } while (got_sigchld);
3963 #define DOWAIT_NONBLOCK 0
3964 #define DOWAIT_BLOCK 1
3965 #define DOWAIT_BLOCK_OR_SIG 2
3968 dowait(int block, struct job *job)
3973 struct job *thisjob = NULL;
3975 TRACE(("dowait(0x%x) called\n", block));
3977 /* It's wrong to call waitpid() outside of INT_OFF region:
3978 * signal can arrive just after syscall return and handler can
3979 * longjmp away, losing stop/exit notification processing.
3980 * Thus, for "jobs" builtin, and for waiting for a fg job,
3981 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
3983 * However, for "wait" builtin it is wrong to simply call waitpid()
3984 * in INT_OFF region: "wait" needs to wait for any running job
3985 * to change state, but should exit on any trap too.
3986 * In INT_OFF region, a signal just before syscall entry can set
3987 * pending_sig variables, but we can't check them, and we would
3988 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
3990 * Because of this, we run inside INT_OFF, but use a special routine
3991 * which combines waitpid() and sigsuspend().
3992 * This is the reason why we need to have a handler for SIGCHLD:
3993 * SIG_DFL handler does not wake sigsuspend().
3996 if (block == DOWAIT_BLOCK_OR_SIG) {
3997 pid = wait_block_or_sig(&status);
4000 if (block == DOWAIT_NONBLOCK)
4001 wait_flags = WNOHANG;
4002 /* if job control is active, accept stopped processes too */
4004 wait_flags |= WUNTRACED;
4005 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4006 pid = waitpid(-1, &status, wait_flags);
4008 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4009 pid, status, errno, strerror(errno)));
4014 for (jp = curjob; jp; jp = jp->prev_job) {
4016 struct procstat *ps;
4017 struct procstat *psend;
4018 if (jp->state == JOBDONE)
4022 psend = ps + jp->nprocs;
4024 if (ps->ps_pid == pid) {
4025 TRACE(("Job %d: changing status of proc %d "
4026 "from 0x%x to 0x%x\n",
4027 jobno(jp), pid, ps->ps_status, status));
4028 ps->ps_status = status;
4031 if (ps->ps_status == -1)
4032 jobstate = JOBRUNNING;
4034 if (jobstate == JOBRUNNING)
4036 if (WIFSTOPPED(ps->ps_status)) {
4037 jp->stopstatus = ps->ps_status;
4038 jobstate = JOBSTOPPED;
4041 } while (++ps < psend);
4045 /* Found the job where one of its processes changed its state.
4046 * Is there at least one live and running process in this job? */
4047 if (jobstate != JOBRUNNING) {
4048 /* No. All live processes in the job are stopped
4049 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4051 thisjob->changed = 1;
4052 if (thisjob->state != jobstate) {
4053 TRACE(("Job %d: changing state from %d to %d\n",
4054 jobno(thisjob), thisjob->state, jobstate));
4055 thisjob->state = jobstate;
4057 if (jobstate == JOBSTOPPED)
4058 set_curjob(thisjob, CUR_STOPPED);
4064 /* The process wasn't found in job list */
4065 if (JOBS && !WIFSTOPPED(status))
4070 if (thisjob && thisjob == job) {
4074 len = sprint_status48(s, status, 1);
4086 showjob(struct job *jp, int mode)
4088 struct procstat *ps;
4089 struct procstat *psend;
4092 char s[16 + 16 + 48];
4093 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4097 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4098 /* just output process (group) id of pipeline */
4099 fprintf(out, "%d\n", ps->ps_pid);
4103 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4108 else if (curjob && jp == curjob->prev_job)
4111 if (mode & SHOW_PIDS)
4112 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4114 psend = ps + jp->nprocs;
4116 if (jp->state == JOBRUNNING) {
4117 strcpy(s + col, "Running");
4118 col += sizeof("Running") - 1;
4120 int status = psend[-1].ps_status;
4121 if (jp->state == JOBSTOPPED)
4122 status = jp->stopstatus;
4123 col += sprint_status48(s + col, status, 0);
4125 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4127 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4128 * or prints several "PID | <cmdN>" lines,
4129 * depending on SHOW_PIDS bit.
4130 * We do not print status of individual processes
4131 * between PID and <cmdN>. bash does it, but not very well:
4132 * first line shows overall job status, not process status,
4133 * making it impossible to know 1st process status.
4137 /* for each process */
4140 if (mode & SHOW_PIDS)
4141 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4143 fprintf(out, "%s%*c%s%s",
4145 33 - col >= 0 ? 33 - col : 0, ' ',
4146 ps == jp->ps ? "" : "| ",
4149 } while (++ps != psend);
4150 newline_and_flush(out);
4154 if (jp->state == JOBDONE) {
4155 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4161 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4162 * statuses have changed since the last call to showjobs.
4169 TRACE(("showjobs(0x%x) called\n", mode));
4171 /* Handle all finished jobs */
4172 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4175 for (jp = curjob; jp; jp = jp->prev_job) {
4176 if (!(mode & SHOW_CHANGED) || jp->changed) {
4182 static int FAST_FUNC
4183 jobscmd(int argc UNUSED_PARAM, char **argv)
4188 while ((m = nextopt("lp")) != '\0') {
4192 mode |= SHOW_ONLY_PGID;
4198 showjob(getjob(*argv, 0), mode);
4208 /* Called only on finished or stopped jobs (no members are running) */
4210 getstatus(struct job *job)
4214 struct procstat *ps;
4216 /* Fetch last member's status */
4217 ps = job->ps + job->nprocs - 1;
4218 status = ps->ps_status;
4220 /* "set -o pipefail" mode: use last _nonzero_ status */
4221 while (status == 0 && --ps >= job->ps)
4222 status = ps->ps_status;
4225 retval = WEXITSTATUS(status);
4226 if (!WIFEXITED(status)) {
4228 retval = WSTOPSIG(status);
4229 if (!WIFSTOPPED(status))
4232 /* XXX: limits number of signals */
4233 retval = WTERMSIG(status);
4235 if (retval == SIGINT)
4241 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4242 jobno(job), job->nprocs, status, retval));
4246 static int FAST_FUNC
4247 waitcmd(int argc UNUSED_PARAM, char **argv)
4258 /* wait for all jobs */
4262 if (!jp) /* no running procs */
4264 if (jp->state == JOBRUNNING)
4270 * "When bash is waiting for an asynchronous command via
4271 * the wait builtin, the reception of a signal for which a trap
4272 * has been set will cause the wait builtin to return immediately
4273 * with an exit status greater than 128, immediately after which
4274 * the trap is executed."
4276 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4277 /* if child sends us a signal *and immediately exits*,
4278 * dowait() returns pid > 0. Check this case,
4279 * not "if (dowait() < 0)"!
4288 if (**argv != '%') {
4289 pid_t pid = number(*argv);
4294 if (job->ps[job->nprocs - 1].ps_pid == pid)
4296 job = job->prev_job;
4299 job = getjob(*argv, 0);
4301 /* loop until process terminated or stopped */
4302 while (job->state == JOBRUNNING) {
4303 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4308 retval = getstatus(job);
4315 retval = 128 + pending_sig;
4324 struct job *jp, *jq;
4326 len = njobs * sizeof(*jp);
4328 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4330 offset = (char *)jp - (char *)jq;
4332 /* Relocate pointers */
4335 jq = (struct job *)((char *)jq + l);
4339 #define joff(p) ((struct job *)((char *)(p) + l))
4340 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4341 if (joff(jp)->ps == &jq->ps0)
4342 jmove(joff(jp)->ps);
4343 if (joff(jp)->prev_job)
4344 jmove(joff(jp)->prev_job);
4354 jp = (struct job *)((char *)jp + len);
4358 } while (--jq >= jp);
4363 * Return a new job structure.
4364 * Called with interrupts off.
4367 makejob(/*union node *node,*/ int nprocs)
4372 for (i = njobs, jp = jobtab; ; jp++) {
4379 if (jp->state != JOBDONE || !jp->waited)
4388 memset(jp, 0, sizeof(*jp));
4390 /* jp->jobctl is a bitfield.
4391 * "jp->jobctl |= jobctl" likely to give awful code */
4395 jp->prev_job = curjob;
4400 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4402 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4409 * Return a string identifying a command (to be printed by the
4412 static char *cmdnextc;
4415 cmdputs(const char *s)
4417 static const char vstype[VSTYPE + 1][3] = {
4418 "", "}", "-", "+", "?", "=",
4419 "%", "%%", "#", "##"
4420 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4423 const char *p, *str;
4427 unsigned char subtype = 0;
4431 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4433 while ((c = *p++) != '\0') {
4441 if ((subtype & VSTYPE) == VSLENGTH)
4447 str = "\"}" + !(quoted & 1);
4454 #if ENABLE_SH_MATH_SUPPORT
4469 if ((subtype & VSTYPE) != VSNORMAL)
4471 str = vstype[subtype & VSTYPE];
4472 if (subtype & VSNUL)
4481 /* These can only happen inside quotes */
4494 while ((c = *str++) != '\0') {
4497 } /* while *p++ not NUL */
4500 USTPUTC('"', nextc);
4506 /* cmdtxt() and cmdlist() call each other */
4507 static void cmdtxt(union node *n);
4510 cmdlist(union node *np, int sep)
4512 for (; np; np = np->narg.next) {
4516 if (sep && np->narg.next)
4522 cmdtxt(union node *n)
4525 struct nodelist *lp;
4536 lp = n->npipe.cmdlist;
4554 cmdtxt(n->nbinary.ch1);
4570 cmdtxt(n->nif.test);
4572 if (n->nif.elsepart) {
4573 cmdtxt(n->nif.ifpart);
4575 n = n->nif.elsepart;
4593 cmdtxt(n->nbinary.ch1);
4603 cmdputs(n->nfor.var);
4605 cmdlist(n->nfor.args, 1);
4610 cmdputs(n->narg.text);
4614 cmdlist(n->ncmd.args, 1);
4615 cmdlist(n->ncmd.redirect, 0);
4628 cmdputs(n->ncase.expr->narg.text);
4630 for (np = n->ncase.cases; np; np = np->nclist.next) {
4631 cmdtxt(np->nclist.pattern);
4633 cmdtxt(np->nclist.body);
4647 #if ENABLE_ASH_BASH_COMPAT
4662 cmdputs(utoa(n->nfile.fd));
4664 if (n->type == NTOFD || n->type == NFROMFD) {
4665 cmdputs(utoa(n->ndup.dupfd));
4674 commandtext(union node *n)
4678 STARTSTACKSTR(cmdnextc);
4680 name = stackblock();
4681 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4682 return ckstrdup(name);
4687 * Fork off a subshell. If we are doing job control, give the subshell its
4688 * own process group. Jp is a job structure that the job is to be added to.
4689 * N is the command that will be evaluated by the child. Both jp and n may
4690 * be NULL. The mode parameter can be one of the following:
4691 * FORK_FG - Fork off a foreground process.
4692 * FORK_BG - Fork off a background process.
4693 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4694 * process group even if job control is on.
4696 * When job control is turned off, background processes have their standard
4697 * input redirected to /dev/null (except for the second and later processes
4700 * Called with interrupts off.
4703 * Clear traps on a fork.
4711 for (tp = trap; tp < &trap[NSIG]; tp++) {
4712 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4713 if (trap_ptr == trap)
4715 /* else: it "belongs" to trap_ptr vector, don't free */
4717 if ((tp - trap) != 0)
4718 setsignal(tp - trap);
4725 /* Lives far away from here, needed for forkchild */
4726 static void closescript(void);
4728 /* Called after fork(), in child */
4729 /* jp and n are NULL when called by openhere() for heredoc support */
4730 static NOINLINE void
4731 forkchild(struct job *jp, union node *n, int mode)
4735 TRACE(("Child shell %d\n", getpid()));
4739 /* man bash: "Non-builtin commands run by bash have signal handlers
4740 * set to the values inherited by the shell from its parent".
4741 * Do we do it correctly? */
4745 if (mode == FORK_NOJOB /* is it `xxx` ? */
4746 && n && n->type == NCMD /* is it single cmd? */
4747 /* && n->ncmd.args->type == NARG - always true? */
4748 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4749 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4750 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4752 TRACE(("Trap hack\n"));
4753 /* Awful hack for `trap` or $(trap).
4755 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4756 * contains an example where "trap" is executed in a subshell:
4758 * save_traps=$(trap)
4760 * eval "$save_traps"
4762 * Standard does not say that "trap" in subshell shall print
4763 * parent shell's traps. It only says that its output
4764 * must have suitable form, but then, in the above example
4765 * (which is not supposed to be normative), it implies that.
4767 * bash (and probably other shell) does implement it
4768 * (traps are reset to defaults, but "trap" still shows them),
4769 * but as a result, "trap" logic is hopelessly messed up:
4772 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4773 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4774 * # true | trap <--- trap is in subshell - no output (ditto)
4775 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4776 * trap -- 'echo Ho' SIGWINCH
4777 * # echo `(trap)` <--- in subshell in subshell - output
4778 * trap -- 'echo Ho' SIGWINCH
4779 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4780 * trap -- 'echo Ho' SIGWINCH
4782 * The rules when to forget and when to not forget traps
4783 * get really complex and nonsensical.
4785 * Our solution: ONLY bare $(trap) or `trap` is special.
4787 /* Save trap handler strings for trap builtin to print */
4788 trap_ptr = xmemdup(trap, sizeof(trap));
4789 /* Fall through into clearing traps */
4793 /* do job control only in root shell */
4795 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4798 if (jp->nprocs == 0)
4801 pgrp = jp->ps[0].ps_pid;
4802 /* this can fail because we are doing it in the parent also */
4804 if (mode == FORK_FG)
4805 xtcsetpgrp(ttyfd, pgrp);
4810 if (mode == FORK_BG) {
4811 /* man bash: "When job control is not in effect,
4812 * asynchronous commands ignore SIGINT and SIGQUIT" */
4815 if (jp->nprocs == 0) {
4817 if (open(bb_dev_null, O_RDONLY) != 0)
4818 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4822 if (iflag) { /* why if iflag only? */
4827 * "In all cases, bash ignores SIGQUIT. Non-builtin
4828 * commands run by bash have signal handlers
4829 * set to the values inherited by the shell
4831 * Take care of the second rule: */
4835 if (n && n->type == NCMD
4836 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4838 TRACE(("Job hack\n"));
4839 /* "jobs": we do not want to clear job list for it,
4840 * instead we remove only _its_ own_ job from job list.
4841 * This makes "jobs .... | cat" more useful.
4847 for (jp = curjob; jp; jp = jp->prev_job)
4852 /* Called after fork(), in parent */
4854 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4857 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4859 TRACE(("In parent shell: child = %d\n", pid));
4861 /* jp is NULL when called by openhere() for heredoc support */
4862 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4868 if (mode != FORK_NOJOB && jp->jobctl) {
4871 if (jp->nprocs == 0)
4874 pgrp = jp->ps[0].ps_pid;
4875 /* This can fail because we are doing it in the child also */
4879 if (mode == FORK_BG) {
4880 backgndpid = pid; /* set $! */
4881 set_curjob(jp, CUR_RUNNING);
4884 struct procstat *ps = &jp->ps[jp->nprocs++];
4887 ps->ps_cmd = nullstr;
4889 if (doing_jobctl && n)
4890 ps->ps_cmd = commandtext(n);
4895 /* jp and n are NULL when called by openhere() for heredoc support */
4897 forkshell(struct job *jp, union node *n, int mode)
4901 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4904 TRACE(("Fork failed, errno=%d", errno));
4907 ash_msg_and_raise_error("can't fork");
4910 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4911 forkchild(jp, n, mode);
4913 forkparent(jp, n, mode, pid);
4919 * Wait for job to finish.
4921 * Under job control we have the problem that while a child process
4922 * is running interrupts generated by the user are sent to the child
4923 * but not to the shell. This means that an infinite loop started by
4924 * an interactive user may be hard to kill. With job control turned off,
4925 * an interactive user may place an interactive program inside a loop.
4926 * If the interactive program catches interrupts, the user doesn't want
4927 * these interrupts to also abort the loop. The approach we take here
4928 * is to have the shell ignore interrupt signals while waiting for a
4929 * foreground process to terminate, and then send itself an interrupt
4930 * signal if the child process was terminated by an interrupt signal.
4931 * Unfortunately, some programs want to do a bit of cleanup and then
4932 * exit on interrupt; unless these processes terminate themselves by
4933 * sending a signal to themselves (instead of calling exit) they will
4934 * confuse this approach.
4936 * Called with interrupts off.
4939 waitforjob(struct job *jp)
4943 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4946 while (jp->state == JOBRUNNING) {
4947 /* In non-interactive shells, we _can_ get
4948 * a keyboard signal here and be EINTRed,
4949 * but we just loop back, waiting for command to complete.
4952 * "If bash is waiting for a command to complete and receives
4953 * a signal for which a trap has been set, the trap
4954 * will not be executed until the command completes."
4956 * Reality is that even if trap is not set, bash
4957 * will not act on the signal until command completes.
4958 * Try this. sleep5intoff.c:
4959 * #include <signal.h>
4960 * #include <unistd.h>
4963 * sigemptyset(&set);
4964 * sigaddset(&set, SIGINT);
4965 * sigaddset(&set, SIGQUIT);
4966 * sigprocmask(SIG_BLOCK, &set, NULL);
4970 * $ bash -c './sleep5intoff; echo hi'
4971 * ^C^C^C^C <--- pressing ^C once a second
4973 * $ bash -c './sleep5intoff; echo hi'
4974 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4977 dowait(DOWAIT_BLOCK, jp);
4984 xtcsetpgrp(ttyfd, rootpid);
4986 * This is truly gross.
4987 * If we're doing job control, then we did a TIOCSPGRP which
4988 * caused us (the shell) to no longer be in the controlling
4989 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4990 * intuit from the subprocess exit status whether a SIGINT
4991 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4993 if (jp->sigint) /* TODO: do the same with all signals */
4994 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4996 if (jp->state == JOBDONE)
5003 * return 1 if there are stopped jobs, otherwise 0
5015 if (jp && jp->state == JOBSTOPPED) {
5016 out2str("You have stopped jobs.\n");
5026 * Code for dealing with input/output redirection.
5031 #define EMPTY -2 /* marks an unused slot in redirtab */
5032 #define CLOSED -3 /* marks a slot of previously-closed fd */
5035 * Open a file in noclobber mode.
5036 * The code was copied from bash.
5039 noclobberopen(const char *fname)
5042 struct stat finfo, finfo2;
5045 * If the file exists and is a regular file, return an error
5048 r = stat(fname, &finfo);
5049 if (r == 0 && S_ISREG(finfo.st_mode)) {
5055 * If the file was not present (r != 0), make sure we open it
5056 * exclusively so that if it is created before we open it, our open
5057 * will fail. Make sure that we do not truncate an existing file.
5058 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5059 * file was not a regular file, we leave O_EXCL off.
5062 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5063 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5065 /* If the open failed, return the file descriptor right away. */
5070 * OK, the open succeeded, but the file may have been changed from a
5071 * non-regular file to a regular file between the stat and the open.
5072 * We are assuming that the O_EXCL open handles the case where FILENAME
5073 * did not exist and is symlinked to an existing file between the stat
5078 * If we can open it and fstat the file descriptor, and neither check
5079 * revealed that it was a regular file, and the file has not been
5080 * replaced, return the file descriptor.
5082 if (fstat(fd, &finfo2) == 0
5083 && !S_ISREG(finfo2.st_mode)
5084 && finfo.st_dev == finfo2.st_dev
5085 && finfo.st_ino == finfo2.st_ino
5090 /* The file has been replaced. badness. */
5097 * Handle here documents. Normally we fork off a process to write the
5098 * data to a pipe. If the document is short, we can stuff the data in
5099 * the pipe without forking.
5101 /* openhere needs this forward reference */
5102 static void expandhere(union node *arg, int fd);
5104 openhere(union node *redir)
5110 ash_msg_and_raise_error("pipe call failed");
5111 if (redir->type == NHERE) {
5112 len = strlen(redir->nhere.doc->narg.text);
5113 if (len <= PIPE_BUF) {
5114 full_write(pip[1], redir->nhere.doc->narg.text, len);
5118 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5121 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5122 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5123 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5124 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5125 signal(SIGPIPE, SIG_DFL);
5126 if (redir->type == NHERE)
5127 full_write(pip[1], redir->nhere.doc->narg.text, len);
5129 expandhere(redir->nhere.doc, pip[1]);
5130 _exit(EXIT_SUCCESS);
5138 openredirect(union node *redir)
5143 switch (redir->nfile.type) {
5144 /* Can't happen, our single caller does this itself */
5150 return openhere(redir);
5153 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5154 * allocated space. Do it only when we know it is safe.
5156 fname = redir->nfile.expfname;
5158 switch (redir->nfile.type) {
5164 f = open(fname, O_RDONLY);
5169 f = open(fname, O_RDWR|O_CREAT, 0666);
5174 #if ENABLE_ASH_BASH_COMPAT
5177 /* Take care of noclobber mode. */
5179 f = noclobberopen(fname);
5186 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5191 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5199 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5201 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5205 * Copy a file descriptor to be >= 10. Throws exception on error.
5213 newfd = fcntl(from, F_DUPFD, 10);
5214 err = newfd < 0 ? errno : 0;
5217 ash_msg_and_raise_error("%d: %m", from);
5219 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5225 dup2_or_raise(int from, int to)
5229 newfd = (from != to) ? dup2(from, to) : to;
5231 /* Happens when source fd is not open: try "echo >&99" */
5232 ash_msg_and_raise_error("%d: %m", from);
5237 /* Struct def and variable are moved down to the first usage site */
5242 struct redirtab *next;
5244 struct two_fd_t two_fd[];
5246 #define redirlist (G_var.redirlist)
5248 COPYFD_RESTORE = (int)~(INT_MAX),
5252 need_to_remember(struct redirtab *rp, int fd)
5256 if (!rp) /* remembering was not requested */
5259 for (i = 0; i < rp->pair_count; i++) {
5260 if (rp->two_fd[i].orig == fd) {
5261 /* already remembered */
5268 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5270 is_hidden_fd(struct redirtab *rp, int fd)
5273 struct parsefile *pf;
5277 /* Check open scripts' fds */
5280 /* We skip pf_fd == 0 case because of the following case:
5281 * $ ash # running ash interactively
5283 * and in script.sh: "exec 9>&0".
5284 * Even though top-level pf_fd _is_ 0,
5285 * it's still ok to use it: "read" builtin uses it,
5286 * why should we cripple "exec" builtin?
5288 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5296 /* Check saved fds of redirects */
5297 fd |= COPYFD_RESTORE;
5298 for (i = 0; i < rp->pair_count; i++) {
5299 if (rp->two_fd[i].copy == fd) {
5307 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5308 * old file descriptors are stashed away so that the redirection can be
5309 * undone by calling popredir.
5311 /* flags passed to redirect */
5312 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5313 #define REDIR_SAVEFD2 03 /* set preverrout */
5315 redirect(union node *redir, int flags)
5317 struct redirtab *sv;
5322 int copied_fd2 = -1;
5331 if (flags & REDIR_PUSH) {
5332 union node *tmp = redir;
5335 #if ENABLE_ASH_BASH_COMPAT
5336 if (tmp->nfile.type == NTO2)
5339 tmp = tmp->nfile.next;
5341 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5342 sv->next = redirlist;
5343 sv->pair_count = sv_pos;
5345 while (sv_pos > 0) {
5347 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5353 fd = redir->nfile.fd;
5354 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5355 right_fd = redir->ndup.dupfd;
5356 //bb_error_msg("doing %d > %d", fd, right_fd);
5357 /* redirect from/to same file descriptor? */
5360 /* "echo >&10" and 10 is a fd opened to a sh script? */
5361 if (is_hidden_fd(sv, right_fd)) {
5362 errno = EBADF; /* as if it is closed */
5363 ash_msg_and_raise_error("%d: %m", right_fd);
5367 newfd = openredirect(redir); /* always >= 0 */
5369 /* Descriptor wasn't open before redirect.
5370 * Mark it for close in the future */
5371 if (need_to_remember(sv, fd)) {
5372 goto remember_to_close;
5377 #if ENABLE_ASH_BASH_COMPAT
5380 if (need_to_remember(sv, fd)) {
5381 /* Copy old descriptor */
5382 /* Careful to not accidentally "save"
5383 * to the same fd as right side fd in N>&M */
5384 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5385 i = fcntl(fd, F_DUPFD, minfd);
5386 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5387 * are closed in popredir() in the child, preventing them from leaking
5388 * into child. (popredir() also cleans up the mess in case of failures)
5393 /* Strange error (e.g. "too many files" EMFILE?) */
5397 ash_msg_and_raise_error("%d: %m", fd);
5400 /* EBADF: it is not open - good, remember to close it */
5403 } else { /* fd is open, save its copy */
5404 /* "exec fd>&-" should not close fds
5405 * which point to script file(s).
5406 * Force them to be restored afterwards */
5407 if (is_hidden_fd(sv, fd))
5408 i |= COPYFD_RESTORE;
5412 sv->two_fd[sv_pos].orig = fd;
5413 sv->two_fd[sv_pos].copy = i;
5417 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5418 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5419 /* Don't want to trigger debugging */
5423 dup2_or_raise(redir->ndup.dupfd, fd);
5425 } else if (fd != newfd) { /* move newfd to fd */
5426 dup2_or_raise(newfd, fd);
5427 #if ENABLE_ASH_BASH_COMPAT
5428 if (!(redir->nfile.type == NTO2 && fd == 2))
5432 #if ENABLE_ASH_BASH_COMPAT
5433 if (redir->nfile.type == NTO2 && fd == 1) {
5434 /* We already redirected it to fd 1, now copy it to 2 */
5440 } while ((redir = redir->nfile.next) != NULL);
5443 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5444 preverrout_fd = copied_fd2;
5448 * Undo the effects of the last redirection.
5451 popredir(int drop, int restore)
5453 struct redirtab *rp;
5456 if (redirlist == NULL)
5460 for (i = 0; i < rp->pair_count; i++) {
5461 int fd = rp->two_fd[i].orig;
5462 int copy = rp->two_fd[i].copy;
5463 if (copy == CLOSED) {
5468 if (copy != EMPTY) {
5469 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5470 copy &= ~COPYFD_RESTORE;
5472 dup2_or_raise(copy, fd);
5474 close(copy & ~COPYFD_RESTORE);
5477 redirlist = rp->next;
5483 * Undo all redirections. Called on error or interrupt.
5487 redirectsafe(union node *redir, int flags)
5490 volatile int saveint;
5491 struct jmploc *volatile savehandler = exception_handler;
5492 struct jmploc jmploc;
5495 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5496 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5498 exception_handler = &jmploc;
5499 redirect(redir, flags);
5501 exception_handler = savehandler;
5502 if (err && exception_type != EXERROR)
5503 longjmp(exception_handler->loc, 1);
5504 RESTORE_INT(saveint);
5509 /* ============ Routines to expand arguments to commands
5511 * We have to deal with backquotes, shell variables, and file metacharacters.
5514 #if ENABLE_SH_MATH_SUPPORT
5516 ash_arith(const char *s)
5518 arith_state_t math_state;
5521 math_state.lookupvar = lookupvar;
5522 math_state.setvar = setvar0;
5523 //math_state.endofname = endofname;
5526 result = arith(&math_state, s);
5527 if (math_state.errmsg)
5528 ash_msg_and_raise_error(math_state.errmsg);
5538 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5539 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5540 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5541 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5542 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5543 * POSIX says for this case:
5544 * Pathname expansion shall not be performed on the word by a
5545 * non-interactive shell; an interactive shell may perform it, but shall
5546 * do so only when the expansion would result in one word.
5547 * Currently, our code complies to the above rule by never globbing
5548 * redirection filenames.
5549 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5550 * (this means that on a typical Linux distro, bash almost always
5551 * performs globbing, and thus diverges from what we do).
5553 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5554 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5555 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5556 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5557 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5561 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5562 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5563 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5564 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5565 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5567 /* Add CTLESC when necessary. */
5568 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5569 /* Do not skip NUL characters. */
5570 #define QUOTES_KEEPNUL EXP_TILDE
5573 * Structure specifying which parts of the string should be searched
5574 * for IFS characters.
5577 struct ifsregion *next; /* next region in list */
5578 int begoff; /* offset of start of region */
5579 int endoff; /* offset of end of region */
5580 int nulonly; /* search for nul bytes only */
5584 struct strlist *list;
5585 struct strlist **lastp;
5588 /* output of current string */
5589 static char *expdest;
5590 /* list of back quote expressions */
5591 static struct nodelist *argbackq;
5592 /* first struct in list of ifs regions */
5593 static struct ifsregion ifsfirst;
5594 /* last struct in list */
5595 static struct ifsregion *ifslastp;
5596 /* holds expanded arg list */
5597 static struct arglist exparg;
5602 #if !ENABLE_SH_MATH_SUPPORT
5603 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5604 typedef long arith_t;
5605 # define ARITH_FMT "%ld"
5612 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5613 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5614 STADJUST(len, expdest);
5619 * Break the argument string into pieces based upon IFS and add the
5620 * strings to the argument list. The regions of the string to be
5621 * searched for IFS characters have been stored by recordregion.
5624 ifsbreakup(char *string, struct arglist *arglist)
5626 struct ifsregion *ifsp;
5631 const char *ifs, *realifs;
5636 if (ifslastp != NULL) {
5639 realifs = ifsset() ? ifsval() : defifs;
5642 p = string + ifsp->begoff;
5643 nulonly = ifsp->nulonly;
5644 ifs = nulonly ? nullstr : realifs;
5646 while (p < string + ifsp->endoff) {
5648 if ((unsigned char)*p == CTLESC)
5650 if (!strchr(ifs, *p)) {
5655 ifsspc = (strchr(defifs, *p) != NULL);
5656 /* Ignore IFS whitespace at start */
5657 if (q == start && ifsspc) {
5663 sp = stzalloc(sizeof(*sp));
5665 *arglist->lastp = sp;
5666 arglist->lastp = &sp->next;
5670 if (p >= string + ifsp->endoff) {
5674 if ((unsigned char)*p == CTLESC)
5676 if (strchr(ifs, *p) == NULL) {
5680 if (strchr(defifs, *p) == NULL) {
5695 } while (ifsp != NULL);
5704 sp = stzalloc(sizeof(*sp));
5706 *arglist->lastp = sp;
5707 arglist->lastp = &sp->next;
5713 struct ifsregion *p = ifsfirst.next;
5720 struct ifsregion *ifsp;
5725 ifsfirst.next = NULL;
5732 esclen(const char *start, const char *p)
5736 while (p > start && (unsigned char)*--p == CTLESC) {
5743 * Remove any CTLESC characters from a string.
5746 rmescapes(char *str, int flag)
5748 static const char qchars[] ALIGN1 = {
5749 IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
5753 unsigned protect_against_glob;
5755 IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
5757 p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
5763 if (flag & RMESCAPE_ALLOC) {
5764 size_t len = p - str;
5765 size_t fulllen = len + strlen(p) + 1;
5767 if (flag & RMESCAPE_GROW) {
5768 int strloc = str - (char *)stackblock();
5769 r = makestrspace(fulllen, expdest);
5770 /* p and str may be invalidated by makestrspace */
5771 str = (char *)stackblock() + strloc;
5773 } else if (flag & RMESCAPE_HEAP) {
5774 r = ckmalloc(fulllen);
5776 r = stalloc(fulllen);
5780 q = (char *)memcpy(q, str, len) + len;
5785 globbing = flag & RMESCAPE_GLOB;
5786 protect_against_glob = globbing;
5788 if ((unsigned char)*p == CTLQUOTEMARK) {
5789 // Note: both inquotes and protect_against_glob only affect whether
5790 inquotes = ~inquotes;
5792 protect_against_glob = globbing;
5795 if ((unsigned char)*p == CTLESC) {
5799 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5801 if (protect_against_glob) {
5804 } else if (*p == '\\' && !inquotes) {
5805 /* naked back slash */
5806 protect_against_glob = 0;
5809 #if ENABLE_ASH_BASH_COMPAT
5810 else if (*p == '/' && slash) {
5811 /* stop handling globbing and mark location of slash */
5812 globbing = slash = 0;
5816 protect_against_glob = globbing;
5821 if (flag & RMESCAPE_GROW) {
5823 STADJUST(q - r + 1, expdest);
5827 #define pmatch(a, b) !fnmatch((a), (b), 0)
5830 * Prepare a pattern for a expmeta (internal glob(3)) call.
5832 * Returns an stalloced string.
5835 preglob(const char *pattern, int flag)
5837 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5841 * Put a string on the stack.
5844 memtodest(const char *p, size_t len, int syntax, int quotes)
5851 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5854 unsigned char c = *p++;
5856 int n = SIT(c, syntax);
5857 if ((quotes & QUOTES_ESC)
5859 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
5865 } else if (!(quotes & QUOTES_KEEPNUL))
5874 strtodest(const char *p, int syntax, int quotes)
5876 size_t len = strlen(p);
5877 memtodest(p, len, syntax, quotes);
5882 * Record the fact that we have to scan this region of the
5883 * string for IFS characters.
5886 recordregion(int start, int end, int nulonly)
5888 struct ifsregion *ifsp;
5890 if (ifslastp == NULL) {
5894 ifsp = ckzalloc(sizeof(*ifsp));
5895 /*ifsp->next = NULL; - ckzalloc did it */
5896 ifslastp->next = ifsp;
5900 ifslastp->begoff = start;
5901 ifslastp->endoff = end;
5902 ifslastp->nulonly = nulonly;
5906 removerecordregions(int endoff)
5908 if (ifslastp == NULL)
5911 if (ifsfirst.endoff > endoff) {
5912 while (ifsfirst.next) {
5913 struct ifsregion *ifsp;
5915 ifsp = ifsfirst.next->next;
5916 free(ifsfirst.next);
5917 ifsfirst.next = ifsp;
5920 if (ifsfirst.begoff > endoff) {
5923 ifslastp = &ifsfirst;
5924 ifsfirst.endoff = endoff;
5929 ifslastp = &ifsfirst;
5930 while (ifslastp->next && ifslastp->next->begoff < endoff)
5931 ifslastp = ifslastp->next;
5932 while (ifslastp->next) {
5933 struct ifsregion *ifsp;
5935 ifsp = ifslastp->next->next;
5936 free(ifslastp->next);
5937 ifslastp->next = ifsp;
5940 if (ifslastp->endoff > endoff)
5941 ifslastp->endoff = endoff;
5945 exptilde(char *startp, char *p, int flags)
5951 int quotes = flags & QUOTES_ESC;
5955 while ((c = *++p) != '\0') {
5962 if (flags & EXP_VARTILDE)
5972 if (*name == '\0') {
5973 home = lookupvar("HOME");
5975 pw = getpwnam(name);
5980 if (!home || !*home)
5983 strtodest(home, SQSYNTAX, quotes);
5991 * Execute a command inside back quotes. If it's a builtin command, we
5992 * want to save its output in a block obtained from malloc. Otherwise
5993 * we fork off a subprocess and get the output of the command via a pipe.
5994 * Should be called with interrupts off.
5996 struct backcmd { /* result of evalbackcmd */
5997 int fd; /* file descriptor to read from */
5998 int nleft; /* number of chars in buffer */
5999 char *buf; /* buffer */
6000 struct job *jp; /* job structure for command */
6003 /* These forward decls are needed to use "eval" code for backticks handling: */
6004 #define EV_EXIT 01 /* exit after evaluating tree */
6005 static int evaltree(union node *, int);
6007 static void FAST_FUNC
6008 evalbackcmd(union node *n, struct backcmd *result)
6022 ash_msg_and_raise_error("pipe call failed");
6023 jp = makejob(/*n,*/ 1);
6024 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6030 dup2_or_raise(pip[1], 1);
6033 /* TODO: eflag clearing makes the following not abort:
6034 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6035 * which is what bash does (unless it is in POSIX mode).
6036 * dash deleted "eflag = 0" line in the commit
6037 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6038 * [EVAL] Don't clear eflag in evalbackcmd
6039 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6043 evaltree(n, EV_EXIT); /* actually evaltreenr... */
6048 result->fd = pip[0];
6052 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6053 result->fd, result->buf, result->nleft, result->jp));
6057 * Expand stuff in backwards quotes.
6060 expbackq(union node *cmd, int flag)
6068 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6069 struct stackmark smark;
6072 startloc = expdest - (char *)stackblock();
6073 pushstackmark(&smark, startloc);
6074 evalbackcmd(cmd, &in);
6075 popstackmark(&smark);
6082 memtodest(p, i, syntax, flag & QUOTES_ESC);
6086 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6087 TRACE(("expbackq: read returns %d\n", i));
6096 back_exitstatus = waitforjob(in.jp);
6100 /* Eat all trailing newlines */
6102 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6106 if (!(flag & EXP_QUOTED))
6107 recordregion(startloc, dest - (char *)stackblock(), 0);
6108 TRACE(("evalbackq: size:%d:'%.*s'\n",
6109 (int)((dest - (char *)stackblock()) - startloc),
6110 (int)((dest - (char *)stackblock()) - startloc),
6111 stackblock() + startloc));
6114 #if ENABLE_SH_MATH_SUPPORT
6116 * Expand arithmetic expression. Backup to start of expression,
6117 * evaluate, place result in (backed up) result, adjust string position.
6129 * This routine is slightly over-complicated for
6130 * efficiency. Next we scan backwards looking for the
6131 * start of arithmetic.
6133 start = stackblock();
6140 while ((unsigned char)*p != CTLARI) {
6144 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6149 esc = esclen(start, p);
6159 removerecordregions(begoff);
6163 if (flag & QUOTES_ESC)
6164 rmescapes(p + 1, 0);
6166 len = cvtnum(ash_arith(p + 1));
6168 if (!(flag & EXP_QUOTED))
6169 recordregion(begoff, begoff + len, 0);
6173 /* argstr needs it */
6174 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6177 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6178 * characters to allow for further processing. Otherwise treat
6179 * $@ like $* since no splitting will be performed.
6181 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6182 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6183 * for correct expansion of "B=$A" word.
6186 argstr(char *p, int flags, struct strlist *var_str_list)
6188 static const char spclchars[] ALIGN1 = {
6196 #if ENABLE_SH_MATH_SUPPORT
6201 const char *reject = spclchars;
6202 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6207 if (!(flags & EXP_VARTILDE)) {
6209 } else if (flags & EXP_VARTILDE2) {
6214 if (flags & EXP_TILDE) {
6217 flags &= ~EXP_TILDE;
6221 p = exptilde(p, q, flags);
6224 startloc = expdest - (char *)stackblock();
6228 length += strcspn(p + length, reject);
6232 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6234 /* c == '=' || c == ':' || c == CTLENDARI */
6240 expdest = stack_nputstr(p, length, expdest);
6241 newloc = expdest - (char *)stackblock();
6242 if (breakall && !inquotes && newloc > startloc) {
6243 recordregion(startloc, newloc, 0);
6254 if (flags & EXP_VARTILDE2) {
6258 flags |= EXP_VARTILDE2;
6263 * sort of a hack - expand tildes in variable
6264 * assignments (after the first '=' and after ':'s).
6273 case CTLENDVAR: /* ??? */
6276 inquotes ^= EXP_QUOTED;
6277 /* "$@" syntax adherence hack */
6278 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6279 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6283 if (flags & QUOTES_ESC) {
6294 * Quoted parameter expansion pattern: remove quote
6295 * unless inside inner quotes or we have a literal
6298 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6299 EXP_QPAT && *p != '\\')
6304 TRACE(("argstr: evalvar('%s')\n", p));
6305 p = evalvar(p, flags | inquotes, var_str_list);
6306 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6309 expbackq(argbackq->n, flags | inquotes);
6310 argbackq = argbackq->next;
6312 #if ENABLE_SH_MATH_SUPPORT
6315 expari(flags | inquotes);
6324 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6325 char *pattern, int quotes, int zero)
6334 const char *s = loc2;
6341 match = pmatch(pattern, s);
6346 if (quotes && (unsigned char)*loc == CTLESC)
6355 scanright(char *startp, char *rmesc, char *rmescend,
6356 char *pattern, int quotes, int match_at_start)
6358 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6359 int try2optimize = match_at_start;
6365 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6366 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6367 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6369 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6370 * and on each iteration they go back two/one char until they reach the beginning.
6371 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6373 /* TODO: document in what other circumstances we are called. */
6375 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6378 const char *s = loc2;
6379 if (match_at_start) {
6383 match = pmatch(pattern, s);
6384 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6388 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6390 /* Maybe we can optimize this:
6391 * if pattern ends with unescaped *, we can avoid checking
6392 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6393 * it wont match truncated "raw_value_of_" strings too.
6395 unsigned plen = strlen(pattern);
6396 /* Does it end with "*"? */
6397 if (plen != 0 && pattern[--plen] == '*') {
6398 /* "xxxx*" is not escaped */
6399 /* "xxx\*" is escaped */
6400 /* "xx\\*" is not escaped */
6401 /* "x\\\*" is escaped */
6403 while (plen != 0 && pattern[--plen] == '\\')
6406 break; /* ends with unescaped "*" */
6414 esc = esclen(startp, loc);
6425 static void varunset(const char *, const char *, const char *, int) NORETURN;
6427 varunset(const char *end, const char *var, const char *umsg, int varflags)
6433 msg = "parameter not set";
6435 if ((unsigned char)*end == CTLENDVAR) {
6436 if (varflags & VSNUL)
6442 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6446 subevalvar(char *p, char *varname, int strloc, int subtype,
6447 int startloc, int varflags, int flag, struct strlist *var_str_list)
6449 struct nodelist *saveargbackq = argbackq;
6450 int quotes = flag & QUOTES_ESC;
6453 char *rmesc, *rmescend;
6455 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6456 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6457 int amount, resetloc;
6458 IF_ASH_BASH_COMPAT(int workloc;)
6460 char *(*scan)(char*, char*, char*, char*, int, int);
6462 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6463 // p, varname, strloc, subtype, startloc, varflags, quotes);
6465 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6466 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6468 STPUTC('\0', expdest);
6469 argbackq = saveargbackq;
6470 startp = (char *)stackblock() + startloc;
6474 setvar0(varname, startp);
6475 amount = startp - expdest;
6476 STADJUST(amount, expdest);
6480 varunset(p, varname, startp, varflags);
6483 #if ENABLE_ASH_BASH_COMPAT
6485 //TODO: support more general format ${v:EXPR:EXPR},
6486 // where EXPR follows $(()) rules
6487 loc = str = stackblock() + strloc;
6488 /* Read POS in ${var:POS:LEN} */
6489 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6490 len = str - startp - 1;
6492 /* *loc != '\0', guaranteed by parser */
6496 /* Adjust the length by the number of escapes */
6497 for (ptr = startp; ptr < (str - 1); ptr++) {
6498 if ((unsigned char)*ptr == CTLESC) {
6506 if (*loc++ == ':') {
6510 /* Skip POS in ${var:POS:LEN} */
6512 while (*loc && *loc != ':') {
6514 * bash complains on: var=qwe; echo ${var:1a:123}
6516 ash_msg_and_raise_error(msg_illnum, str);
6520 if (*loc++ == ':') {
6525 /* ${VAR:$((-n)):l} starts n chars from the end */
6526 pos = orig_len + pos;
6528 if ((unsigned)pos >= orig_len) {
6529 /* apart from obvious ${VAR:999999:l},
6530 * covers ${VAR:$((-9999999)):l} - result is ""
6536 if (len > (orig_len - pos))
6537 len = orig_len - pos;
6539 for (str = startp; pos; str++, pos--) {
6540 if (quotes && (unsigned char)*str == CTLESC)
6543 for (loc = startp; len; len--) {
6544 if (quotes && (unsigned char)*str == CTLESC)
6549 amount = loc - expdest;
6550 STADJUST(amount, expdest);
6555 resetloc = expdest - (char *)stackblock();
6557 /* We'll comeback here if we grow the stack while handling
6558 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6559 * stack will need rebasing, and we'll need to remove our work
6562 IF_ASH_BASH_COMPAT(restart:)
6564 amount = expdest - ((char *)stackblock() + resetloc);
6565 STADJUST(-amount, expdest);
6566 startp = (char *)stackblock() + startloc;
6569 rmescend = (char *)stackblock() + strloc;
6571 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6572 if (rmesc != startp) {
6574 startp = (char *)stackblock() + startloc;
6578 str = (char *)stackblock() + strloc;
6580 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6581 * The result is a_\_z_c (not a\_\_z_c)!
6583 * The search pattern and replace string treat backslashes differently!
6584 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6585 * and string. It's only used on the first call.
6587 preglob(str, IF_ASH_BASH_COMPAT(
6588 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6589 RMESCAPE_SLASH :) 0);
6591 #if ENABLE_ASH_BASH_COMPAT
6592 workloc = expdest - (char *)stackblock();
6593 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6597 repl = strchr(str, CTLESC);
6603 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6605 /* If there's no pattern to match, return the expansion unmolested */
6614 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6615 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6617 /* No match, advance */
6618 char *restart_detect = stackblock();
6620 STPUTC(*idx, expdest);
6621 if (quotes && (unsigned char)*idx == CTLESC) {
6624 STPUTC(*idx, expdest);
6626 if (stackblock() != restart_detect)
6631 /* continue; - prone to quadratic behavior, smarter code: */
6634 if (str[0] == '*') {
6635 /* Pattern is "*foo". If "*foo" does not match "long_string",
6636 * it would never match "ong_string" etc, no point in trying.
6643 if (subtype == VSREPLACEALL) {
6645 if (quotes && (unsigned char)*idx == CTLESC)
6654 //bb_error_msg("repl:'%s'", repl);
6655 for (loc = (char*)repl; *loc; loc++) {
6656 char *restart_detect = stackblock();
6657 if (quotes && *loc == '\\') {
6658 STPUTC(CTLESC, expdest);
6661 STPUTC(*loc, expdest);
6662 if (stackblock() != restart_detect)
6667 if (subtype == VSREPLACE) {
6668 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6670 char *restart_detect = stackblock();
6671 STPUTC(*idx, expdest);
6672 if (stackblock() != restart_detect)
6681 /* We've put the replaced text into a buffer at workloc, now
6682 * move it to the right place and adjust the stack.
6684 STPUTC('\0', expdest);
6685 startp = (char *)stackblock() + startloc;
6686 memmove(startp, (char *)stackblock() + workloc, len + 1);
6687 //bb_error_msg("startp:'%s'", startp);
6688 amount = expdest - (startp + len);
6689 STADJUST(-amount, expdest);
6692 #endif /* ENABLE_ASH_BASH_COMPAT */
6694 subtype -= VSTRIMRIGHT;
6696 if (subtype < 0 || subtype > 7)
6699 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6700 zero = subtype >> 1;
6701 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6702 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6704 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6707 memmove(startp, loc, str - loc);
6708 loc = startp + (str - loc) - 1;
6711 amount = loc - expdest;
6712 STADJUST(amount, expdest);
6718 * Add the value of a specialized variable to the stack string.
6719 * name parameter (examples):
6720 * ash -c 'echo $1' name:'1='
6721 * ash -c 'echo $qwe' name:'qwe='
6722 * ash -c 'echo $$' name:'$='
6723 * ash -c 'echo ${$}' name:'$='
6724 * ash -c 'echo ${$##q}' name:'$=q'
6725 * ash -c 'echo ${#$}' name:'$='
6726 * note: examples with bad shell syntax:
6727 * ash -c 'echo ${#$1}' name:'$=1'
6728 * ash -c 'echo ${#1#}' name:'1=#'
6730 static NOINLINE ssize_t
6731 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list, int *quotedp)
6738 int quoted = *quotedp;
6739 int subtype = varflags & VSTYPE;
6740 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6741 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6744 sep = (flags & EXP_FULL) << CHAR_BIT;
6745 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6755 num = shellparam.nparam;
6763 goto check_1char_name;
6765 expdest = makestrspace(NOPTS, expdest);
6766 for (i = NOPTS - 1; i >= 0; i--) {
6768 USTPUTC(optletters(i), expdest);
6774 /* handles cases similar to ${#$1} */
6775 if (name[2] != '\0')
6776 raise_error_syntax("bad substitution");
6789 sep |= ifsset() ? ifsval()[0] : ' ';
6796 while ((p = *ap++) != NULL) {
6797 len += strtodest(p, syntax, quotes);
6801 memtodest(&sepc, 1, syntax, quotes);
6816 num = atoi(name); /* number(name) fails on ${N#str} etc */
6817 if (num < 0 || num > shellparam.nparam)
6819 p = num ? shellparam.p[num - 1] : arg0;
6822 /* NB: name has form "VAR=..." */
6824 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6825 * which should be considered before we check variables. */
6827 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6831 str = var_str_list->text;
6832 eq = strchr(str, '=');
6833 if (!eq) /* stop at first non-assignment */
6836 if (name_len == (unsigned)(eq - str)
6837 && strncmp(str, name, name_len) == 0
6840 /* goto value; - WRONG! */
6841 /* think "A=1 A=2 B=$A" */
6843 var_str_list = var_str_list->next;
6844 } while (var_str_list);
6848 p = lookupvar(name);
6853 len = strtodest(p, syntax, quotes);
6854 #if ENABLE_UNICODE_SUPPORT
6855 if (subtype == VSLENGTH && len > 0) {
6856 reinit_unicode_for_ash();
6857 if (unicode_status == UNICODE_ON) {
6858 STADJUST(-len, expdest);
6860 len = unicode_strlen(p);
6868 STADJUST(-len, expdest);
6873 * Expand a variable, and return a pointer to the next character in the
6877 evalvar(char *p, int flag, struct strlist *var_str_list)
6888 varflags = (unsigned char) *p++;
6889 subtype = varflags & VSTYPE;
6892 raise_error_syntax("bad substitution");
6894 quoted = flag & EXP_QUOTED;
6896 easy = (!quoted || (*var == '@' && shellparam.nparam));
6897 startloc = expdest - (char *)stackblock();
6898 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6901 varlen = varvalue(var, varflags, flag, var_str_list, "ed);
6902 if (varflags & VSNUL)
6905 if (subtype == VSPLUS) {
6906 varlen = -1 - varlen;
6910 if (subtype == VSMINUS) {
6915 flag | EXP_TILDE | EXP_WORD,
6923 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6927 subevalvar(p, var, 0, subtype, startloc, varflags,
6928 flag & ~QUOTES_ESC, var_str_list);
6931 * Remove any recorded regions beyond
6934 removerecordregions(startloc);
6938 if (varlen < 0 && uflag)
6939 varunset(p, var, 0, 0);
6941 if (subtype == VSLENGTH) {
6942 cvtnum(varlen > 0 ? varlen : 0);
6946 if (subtype == VSNORMAL) {
6950 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6959 case VSTRIMRIGHTMAX:
6960 #if ENABLE_ASH_BASH_COMPAT
6973 * Terminate the string and start recording the pattern
6976 STPUTC('\0', expdest);
6977 patloc = expdest - (char *)stackblock();
6978 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6979 startloc, varflags, flag, var_str_list)) {
6980 int amount = expdest - (
6981 (char *)stackblock() + patloc - 1
6983 STADJUST(-amount, expdest);
6985 /* Remove any recorded regions beyond start of variable */
6986 removerecordregions(startloc);
6991 if (subtype != VSNORMAL) { /* skip to end of alternative */
6994 unsigned char c = *p++;
6997 else if (c == CTLBACKQ) {
6999 argbackq = argbackq->next;
7000 } else if (c == CTLVAR) {
7001 if ((*p++ & VSTYPE) != VSNORMAL)
7003 } else if (c == CTLENDVAR) {
7013 * Add a file name to the list.
7016 addfname(const char *name)
7020 sp = stzalloc(sizeof(*sp));
7021 sp->text = sstrdup(name);
7023 exparg.lastp = &sp->next;
7026 /* If we want to use glob() from libc... */
7027 #if !ENABLE_ASH_INTERNAL_GLOB
7029 /* Add the result of glob() to the list */
7031 addglob(const glob_t *pglob)
7033 char **p = pglob->gl_pathv;
7040 expandmeta(struct strlist *str /*, int flag*/)
7042 /* TODO - EXP_REDIR */
7052 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7067 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7068 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7069 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7071 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7072 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7073 // Which means you need to unescape the string, right? Not so fast:
7074 // if there _is_ a file named "file\?" (with backslash), it is returned
7075 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7076 // You DONT KNOW by looking at the result whether you need to unescape it.
7078 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7079 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7080 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7081 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7082 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7083 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7084 i = glob(p, 0, NULL, &pglob);
7085 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7090 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7091 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7092 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7104 *exparg.lastp = str;
7105 rmescapes(str->text, 0);
7106 exparg.lastp = &str->next;
7108 default: /* GLOB_NOSPACE */
7111 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7118 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7121 * Do metacharacter (i.e. *, ?, [...]) expansion.
7124 expmeta(char *expdir, char *enddir, char *name)
7140 for (p = name; esc = 0, *p; p += esc + 1) {
7141 if (*p == '*' || *p == '?')
7143 else if (*p == '[') {
7150 if (*q == '/' || *q == '\0')
7160 if (p[esc] == '/') {
7163 start = p + esc + 1;
7167 if (metaflag == 0) { /* we've reached the end of the file name */
7168 if (enddir != expdir)
7176 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7187 } while (p < start);
7189 if (enddir == expdir) {
7191 } else if (enddir == expdir + 1 && *expdir == '/') {
7200 if (enddir != expdir)
7202 if (*endname == 0) {
7215 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7216 if (dp->d_name[0] == '.' && !matchdot)
7218 if (pmatch(start, dp->d_name)) {
7220 strcpy(enddir, dp->d_name);
7223 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7226 expmeta(expdir, p, endname);
7232 endname[-esc - 1] = esc ? '\\' : '/';
7235 static struct strlist *
7236 msort(struct strlist *list, int len)
7238 struct strlist *p, *q = NULL;
7239 struct strlist **lpp;
7247 for (n = half; --n >= 0;) {
7251 q->next = NULL; /* terminate first half of list */
7252 q = msort(list, half); /* sort first half of list */
7253 p = msort(p, len - half); /* sort second half */
7256 #if ENABLE_LOCALE_SUPPORT
7257 if (strcoll(p->text, q->text) < 0)
7259 if (strcmp(p->text, q->text) < 0)
7283 * Sort the results of file name expansion. It calculates the number of
7284 * strings to sort and then calls msort (short for merge sort) to do the
7287 static struct strlist *
7288 expsort(struct strlist *str)
7294 for (sp = str; sp; sp = sp->next)
7296 return msort(str, len);
7300 expandmeta(struct strlist *str /*, int flag*/)
7302 static const char metachars[] ALIGN1 = {
7305 /* TODO - EXP_REDIR */
7309 struct strlist **savelastp;
7315 if (!strpbrk(str->text, metachars))
7317 savelastp = exparg.lastp;
7320 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7322 int i = strlen(str->text);
7323 //BUGGY estimation of how long expanded name can be
7324 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7326 expmeta(expdir, expdir, p);
7331 if (exparg.lastp == savelastp) {
7336 *exparg.lastp = str;
7337 rmescapes(str->text, 0);
7338 exparg.lastp = &str->next;
7340 *exparg.lastp = NULL;
7341 *savelastp = sp = expsort(*savelastp);
7342 while (sp->next != NULL)
7344 exparg.lastp = &sp->next;
7349 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7352 * Perform variable substitution and command substitution on an argument,
7353 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7354 * perform splitting and file name expansion. When arglist is NULL, perform
7355 * here document expansion.
7358 expandarg(union node *arg, struct arglist *arglist, int flag)
7363 argbackq = arg->narg.backquote;
7364 STARTSTACKSTR(expdest);
7365 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7366 argstr(arg->narg.text, flag,
7367 /* var_str_list: */ arglist ? arglist->list : NULL);
7368 p = _STPUTC('\0', expdest);
7370 if (arglist == NULL) {
7371 /* here document expanded */
7374 p = grabstackstr(p);
7375 TRACE(("expandarg: p:'%s'\n", p));
7376 exparg.lastp = &exparg.list;
7380 if (flag & EXP_FULL) {
7381 ifsbreakup(p, &exparg);
7382 *exparg.lastp = NULL;
7383 exparg.lastp = &exparg.list;
7384 expandmeta(exparg.list /*, flag*/);
7386 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7388 TRACE(("expandarg: rmescapes:'%s'\n", p));
7390 sp = stzalloc(sizeof(*sp));
7393 exparg.lastp = &sp->next;
7395 *exparg.lastp = NULL;
7397 *arglist->lastp = exparg.list;
7398 arglist->lastp = exparg.lastp;
7406 * Expand shell variables and backquotes inside a here document.
7409 expandhere(union node *arg, int fd)
7411 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7412 full_write(fd, stackblock(), expdest - (char *)stackblock());
7416 * Returns true if the pattern matches the string.
7419 patmatch(char *pattern, const char *string)
7421 return pmatch(preglob(pattern, 0), string);
7425 * See if a pattern matches in a case statement.
7428 casematch(union node *pattern, char *val)
7430 struct stackmark smark;
7433 setstackmark(&smark);
7434 argbackq = pattern->narg.backquote;
7435 STARTSTACKSTR(expdest);
7436 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7437 /* var_str_list: */ NULL);
7438 STACKSTRNUL(expdest);
7440 result = patmatch(stackblock(), val);
7441 popstackmark(&smark);
7446 /* ============ find_command */
7450 int (*builtin)(int, char **) FAST_FUNC;
7451 /* unsigned flags; */
7453 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7454 /* "regular" builtins always take precedence over commands,
7455 * regardless of PATH=....%builtin... position */
7456 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7457 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7460 smallint cmdtype; /* CMDxxx */
7463 /* index >= 0 for commands without path (slashes) */
7464 /* (TODO: what exactly does the value mean? PATH position?) */
7465 /* index == -1 for commands with slashes */
7466 /* index == (-2 - applet_no) for NOFORK applets */
7467 const struct builtincmd *cmd;
7468 struct funcnode *func;
7471 /* values of cmdtype */
7472 #define CMDUNKNOWN -1 /* no entry in table for command */
7473 #define CMDNORMAL 0 /* command is an executable program */
7474 #define CMDFUNCTION 1 /* command is a shell function */
7475 #define CMDBUILTIN 2 /* command is a shell builtin */
7477 /* action to find_command() */
7478 #define DO_ERR 0x01 /* prints errors */
7479 #define DO_ABS 0x02 /* checks absolute paths */
7480 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7481 #define DO_ALTPATH 0x08 /* using alternate path */
7482 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7484 static void find_command(char *, struct cmdentry *, int, const char *);
7487 /* ============ Hashing commands */
7490 * When commands are first encountered, they are entered in a hash table.
7491 * This ensures that a full path search will not have to be done for them
7492 * on each invocation.
7494 * We should investigate converting to a linear search, even though that
7495 * would make the command name "hash" a misnomer.
7499 struct tblentry *next; /* next entry in hash chain */
7500 union param param; /* definition of builtin function */
7501 smallint cmdtype; /* CMDxxx */
7502 char rehash; /* if set, cd done since entry created */
7503 char cmdname[1]; /* name of command */
7506 static struct tblentry **cmdtable;
7507 #define INIT_G_cmdtable() do { \
7508 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7511 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7515 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7517 #if ENABLE_FEATURE_SH_STANDALONE
7518 if (applet_no >= 0) {
7519 if (APPLET_IS_NOEXEC(applet_no)) {
7523 run_applet_no_and_exit(applet_no, argv);
7525 /* re-exec ourselves with the new arguments */
7526 execve(bb_busybox_exec_path, argv, envp);
7527 /* If they called chroot or otherwise made the binary no longer
7528 * executable, fall through */
7535 execve(cmd, argv, envp);
7536 } while (errno == EINTR);
7538 execve(cmd, argv, envp);
7540 if (cmd != (char*) bb_busybox_exec_path && errno == ENOEXEC) {
7541 /* Run "cmd" as a shell script:
7542 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7543 * "If the execve() function fails with ENOEXEC, the shell
7544 * shall execute a command equivalent to having a shell invoked
7545 * with the command name as its first operand,
7546 * with any remaining arguments passed to the new shell"
7548 * That is, do not use $SHELL, user's shell, or /bin/sh;
7549 * just call ourselves.
7551 * Note that bash reads ~80 chars of the file, and if it sees
7552 * a zero byte before it sees newline, it doesn't try to
7553 * interpret it, but fails with "cannot execute binary file"
7554 * message and exit code 126. For one, this prevents attempts
7555 * to interpret foreign ELF binaries as shell scripts.
7558 cmd = (char*) bb_busybox_exec_path;
7559 /* NB: this is only possible because all callers of shellexec()
7560 * ensure that the argv[-1] slot exists!
7563 argv[0] = (char*) "ash";
7569 * Exec a program. Never returns. If you change this routine, you may
7570 * have to change the find_command routine as well.
7571 * argv[-1] must exist and be writable! See tryexec() for why.
7573 static void shellexec(char **, const char *, int) NORETURN;
7575 shellexec(char **argv, const char *path, int idx)
7581 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7583 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7584 if (strchr(argv[0], '/') != NULL
7585 #if ENABLE_FEATURE_SH_STANDALONE
7586 || (applet_no = find_applet_by_name(argv[0])) >= 0
7589 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7590 if (applet_no >= 0) {
7591 /* We tried execing ourself, but it didn't work.
7592 * Maybe /proc/self/exe doesn't exist?
7601 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7602 if (--idx < 0 && pathopt == NULL) {
7603 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7604 if (errno != ENOENT && errno != ENOTDIR)
7611 /* Map to POSIX errors */
7623 exitstatus = exerrno;
7624 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7625 argv[0], e, suppress_int));
7626 ash_msg_and_raise(EXEXIT, "%s: %s", argv[0], errmsg(e, "not found"));
7631 printentry(struct tblentry *cmdp)
7637 idx = cmdp->param.index;
7640 name = path_advance(&path, cmdp->cmdname);
7642 } while (--idx >= 0);
7643 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7647 * Clear out command entries. The argument specifies the first entry in
7648 * PATH which has changed.
7651 clearcmdentry(int firstchange)
7653 struct tblentry **tblp;
7654 struct tblentry **pp;
7655 struct tblentry *cmdp;
7658 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7660 while ((cmdp = *pp) != NULL) {
7661 if ((cmdp->cmdtype == CMDNORMAL &&
7662 cmdp->param.index >= firstchange)
7663 || (cmdp->cmdtype == CMDBUILTIN &&
7664 builtinloc >= firstchange)
7677 * Locate a command in the command hash table. If "add" is nonzero,
7678 * add the command to the table if it is not already present. The
7679 * variable "lastcmdentry" is set to point to the address of the link
7680 * pointing to the entry, so that delete_cmd_entry can delete the
7683 * Interrupts must be off if called with add != 0.
7685 static struct tblentry **lastcmdentry;
7687 static struct tblentry *
7688 cmdlookup(const char *name, int add)
7690 unsigned int hashval;
7692 struct tblentry *cmdp;
7693 struct tblentry **pp;
7696 hashval = (unsigned char)*p << 4;
7698 hashval += (unsigned char)*p++;
7700 pp = &cmdtable[hashval % CMDTABLESIZE];
7701 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7702 if (strcmp(cmdp->cmdname, name) == 0)
7706 if (add && cmdp == NULL) {
7707 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7709 /* + 1 - already done because
7710 * tblentry::cmdname is char[1] */);
7711 /*cmdp->next = NULL; - ckzalloc did it */
7712 cmdp->cmdtype = CMDUNKNOWN;
7713 strcpy(cmdp->cmdname, name);
7720 * Delete the command entry returned on the last lookup.
7723 delete_cmd_entry(void)
7725 struct tblentry *cmdp;
7728 cmdp = *lastcmdentry;
7729 *lastcmdentry = cmdp->next;
7730 if (cmdp->cmdtype == CMDFUNCTION)
7731 freefunc(cmdp->param.func);
7737 * Add a new command entry, replacing any existing command entry for
7738 * the same name - except special builtins.
7741 addcmdentry(char *name, struct cmdentry *entry)
7743 struct tblentry *cmdp;
7745 cmdp = cmdlookup(name, 1);
7746 if (cmdp->cmdtype == CMDFUNCTION) {
7747 freefunc(cmdp->param.func);
7749 cmdp->cmdtype = entry->cmdtype;
7750 cmdp->param = entry->u;
7754 static int FAST_FUNC
7755 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7757 struct tblentry **pp;
7758 struct tblentry *cmdp;
7760 struct cmdentry entry;
7763 if (nextopt("r") != '\0') {
7768 if (*argptr == NULL) {
7769 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7770 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7771 if (cmdp->cmdtype == CMDNORMAL)
7779 while ((name = *argptr) != NULL) {
7780 cmdp = cmdlookup(name, 0);
7782 && (cmdp->cmdtype == CMDNORMAL
7783 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7787 find_command(name, &entry, DO_ERR, pathval());
7788 if (entry.cmdtype == CMDUNKNOWN)
7796 * Called when a cd is done. Marks all commands so the next time they
7797 * are executed they will be rehashed.
7802 struct tblentry **pp;
7803 struct tblentry *cmdp;
7805 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7806 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7807 if (cmdp->cmdtype == CMDNORMAL
7808 || (cmdp->cmdtype == CMDBUILTIN
7809 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7819 * Fix command hash table when PATH changed.
7820 * Called before PATH is changed. The argument is the new value of PATH;
7821 * pathval() still returns the old value at this point.
7822 * Called with interrupts off.
7824 static void FAST_FUNC
7825 changepath(const char *new)
7833 firstchange = 9999; /* assume no change */
7839 if ((*old == '\0' && *new == ':')
7840 || (*old == ':' && *new == '\0')
7844 old = new; /* ignore subsequent differences */
7848 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7855 if (builtinloc < 0 && idx_bltin >= 0)
7856 builtinloc = idx_bltin; /* zap builtins */
7857 if (builtinloc >= 0 && idx_bltin < 0)
7859 clearcmdentry(firstchange);
7860 builtinloc = idx_bltin;
7885 #if ENABLE_ASH_BASH_COMPAT
7896 typedef smallint token_id_t;
7898 /* Nth bit indicates if token marks the end of a list */
7901 /* 0 */ | (1u << TEOF)
7902 /* 1 */ | (0u << TNL)
7903 /* 2 */ | (0u << TREDIR)
7904 /* 3 */ | (0u << TWORD)
7905 /* 4 */ | (0u << TSEMI)
7906 /* 5 */ | (0u << TBACKGND)
7907 /* 6 */ | (0u << TAND)
7908 /* 7 */ | (0u << TOR)
7909 /* 8 */ | (0u << TPIPE)
7910 /* 9 */ | (0u << TLP)
7911 /* 10 */ | (1u << TRP)
7912 /* 11 */ | (1u << TENDCASE)
7913 /* 12 */ | (1u << TENDBQUOTE)
7914 /* 13 */ | (0u << TNOT)
7915 /* 14 */ | (0u << TCASE)
7916 /* 15 */ | (1u << TDO)
7917 /* 16 */ | (1u << TDONE)
7918 /* 17 */ | (1u << TELIF)
7919 /* 18 */ | (1u << TELSE)
7920 /* 19 */ | (1u << TESAC)
7921 /* 20 */ | (1u << TFI)
7922 /* 21 */ | (0u << TFOR)
7923 #if ENABLE_ASH_BASH_COMPAT
7924 /* 22 */ | (0u << TFUNCTION)
7926 /* 23 */ | (0u << TIF)
7927 /* 24 */ | (0u << TIN)
7928 /* 25 */ | (1u << TTHEN)
7929 /* 26 */ | (0u << TUNTIL)
7930 /* 27 */ | (0u << TWHILE)
7931 /* 28 */ | (0u << TBEGIN)
7932 /* 29 */ | (1u << TEND)
7933 , /* thus far 29 bits used */
7936 static const char *const tokname_array[] = {
7950 #define KWDOFFSET 13
7951 /* the following are keywords */
7961 #if ENABLE_ASH_BASH_COMPAT
7973 /* Wrapper around strcmp for qsort/bsearch/... */
7975 pstrcmp(const void *a, const void *b)
7977 return strcmp((char*)a, *(char**)b);
7980 static const char *const *
7981 findkwd(const char *s)
7983 return bsearch(s, tokname_array + KWDOFFSET,
7984 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7985 sizeof(tokname_array[0]), pstrcmp);
7989 * Locate and print what a word is...
7992 describe_command(char *command, const char *path, int describe_command_verbose)
7994 struct cmdentry entry;
7995 struct tblentry *cmdp;
7996 #if ENABLE_ASH_ALIAS
7997 const struct alias *ap;
8000 path = path ? path : pathval();
8002 if (describe_command_verbose) {
8006 /* First look at the keywords */
8007 if (findkwd(command)) {
8008 out1str(describe_command_verbose ? " is a shell keyword" : command);
8012 #if ENABLE_ASH_ALIAS
8013 /* Then look at the aliases */
8014 ap = lookupalias(command, 0);
8016 if (!describe_command_verbose) {
8021 out1fmt(" is an alias for %s", ap->val);
8025 /* Then check if it is a tracked alias */
8026 cmdp = cmdlookup(command, 0);
8028 entry.cmdtype = cmdp->cmdtype;
8029 entry.u = cmdp->param;
8031 /* Finally use brute force */
8032 find_command(command, &entry, DO_ABS, path);
8035 switch (entry.cmdtype) {
8037 int j = entry.u.index;
8043 p = path_advance(&path, command);
8047 if (describe_command_verbose) {
8049 (cmdp ? " a tracked alias for" : nullstr), p
8058 if (describe_command_verbose) {
8059 out1str(" is a shell function");
8066 if (describe_command_verbose) {
8067 out1fmt(" is a %sshell builtin",
8068 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8069 "special " : nullstr
8077 if (describe_command_verbose) {
8078 out1str(": not found\n");
8087 static int FAST_FUNC
8088 typecmd(int argc UNUSED_PARAM, char **argv)
8094 /* type -p ... ? (we don't bother checking for 'p') */
8095 if (argv[1] && argv[1][0] == '-') {
8100 err |= describe_command(argv[i++], NULL, verbose);
8105 #if ENABLE_ASH_CMDCMD
8106 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8108 parse_command_args(char **argv, const char **path)
8121 if (c == '-' && !*cp) {
8129 *path = bb_default_path;
8132 /* run 'typecmd' for other options */
8141 static int FAST_FUNC
8142 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8150 const char *path = NULL;
8152 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8153 * never reaches this function.
8156 while ((c = nextopt("pvV")) != '\0')
8158 verify |= VERIFY_VERBOSE;
8160 /*verify |= VERIFY_BRIEF*/;
8166 path = bb_default_path;
8168 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8170 if (/*verify && */ cmd)
8171 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8178 /*static int funcblocksize; // size of structures in function */
8179 /*static int funcstringsize; // size of strings in node */
8180 static void *funcblock; /* block to allocate function from */
8181 static char *funcstring_end; /* end of block to allocate strings from */
8183 /* flags in argument to evaltree */
8184 #define EV_EXIT 01 /* exit after evaluating tree */
8185 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8187 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8188 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8189 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8190 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8191 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8192 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8193 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8194 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8195 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8196 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8197 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8198 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8199 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8200 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8201 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8202 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8203 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8204 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8205 #if ENABLE_ASH_BASH_COMPAT
8206 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8208 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8209 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8210 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8211 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8212 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8213 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8214 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8215 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8216 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8219 static int calcsize(int funcblocksize, union node *n);
8222 sizenodelist(int funcblocksize, struct nodelist *lp)
8225 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8226 funcblocksize = calcsize(funcblocksize, lp->n);
8229 return funcblocksize;
8233 calcsize(int funcblocksize, union node *n)
8236 return funcblocksize;
8237 funcblocksize += nodesize[n->type];
8240 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8241 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8242 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8245 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8250 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8251 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8258 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8259 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8262 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8263 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8264 funcblocksize = calcsize(funcblocksize, n->nif.test);
8267 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8268 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8269 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8272 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8273 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8276 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8277 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8278 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8282 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8283 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8284 funcblocksize = calcsize(funcblocksize, n->narg.next);
8287 #if ENABLE_ASH_BASH_COMPAT
8294 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8295 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8299 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8300 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8304 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8305 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8308 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8311 return funcblocksize;
8315 nodeckstrdup(char *s)
8317 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8318 return strcpy(funcstring_end, s);
8321 static union node *copynode(union node *);
8323 static struct nodelist *
8324 copynodelist(struct nodelist *lp)
8326 struct nodelist *start;
8327 struct nodelist **lpp;
8332 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8333 (*lpp)->n = copynode(lp->n);
8335 lpp = &(*lpp)->next;
8342 copynode(union node *n)
8349 funcblock = (char *) funcblock + nodesize[n->type];
8353 new->ncmd.redirect = copynode(n->ncmd.redirect);
8354 new->ncmd.args = copynode(n->ncmd.args);
8355 new->ncmd.assign = copynode(n->ncmd.assign);
8358 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8359 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8364 new->nredir.redirect = copynode(n->nredir.redirect);
8365 new->nredir.n = copynode(n->nredir.n);
8372 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8373 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8376 new->nif.elsepart = copynode(n->nif.elsepart);
8377 new->nif.ifpart = copynode(n->nif.ifpart);
8378 new->nif.test = copynode(n->nif.test);
8381 new->nfor.var = nodeckstrdup(n->nfor.var);
8382 new->nfor.body = copynode(n->nfor.body);
8383 new->nfor.args = copynode(n->nfor.args);
8386 new->ncase.cases = copynode(n->ncase.cases);
8387 new->ncase.expr = copynode(n->ncase.expr);
8390 new->nclist.body = copynode(n->nclist.body);
8391 new->nclist.pattern = copynode(n->nclist.pattern);
8392 new->nclist.next = copynode(n->nclist.next);
8396 new->narg.backquote = copynodelist(n->narg.backquote);
8397 new->narg.text = nodeckstrdup(n->narg.text);
8398 new->narg.next = copynode(n->narg.next);
8401 #if ENABLE_ASH_BASH_COMPAT
8408 new->nfile.fname = copynode(n->nfile.fname);
8409 new->nfile.fd = n->nfile.fd;
8410 new->nfile.next = copynode(n->nfile.next);
8414 new->ndup.vname = copynode(n->ndup.vname);
8415 new->ndup.dupfd = n->ndup.dupfd;
8416 new->ndup.fd = n->ndup.fd;
8417 new->ndup.next = copynode(n->ndup.next);
8421 new->nhere.doc = copynode(n->nhere.doc);
8422 new->nhere.fd = n->nhere.fd;
8423 new->nhere.next = copynode(n->nhere.next);
8426 new->nnot.com = copynode(n->nnot.com);
8429 new->type = n->type;
8434 * Make a copy of a parse tree.
8436 static struct funcnode *
8437 copyfunc(union node *n)
8442 /*funcstringsize = 0;*/
8443 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8444 f = ckzalloc(blocksize /* + funcstringsize */);
8445 funcblock = (char *) f + offsetof(struct funcnode, n);
8446 funcstring_end = (char *) f + blocksize;
8448 /* f->count = 0; - ckzalloc did it */
8453 * Define a shell function.
8456 defun(union node *func)
8458 struct cmdentry entry;
8461 entry.cmdtype = CMDFUNCTION;
8462 entry.u.func = copyfunc(func);
8463 addcmdentry(func->narg.text, &entry);
8467 /* Reasons for skipping commands (see comment on breakcmd routine) */
8468 #define SKIPBREAK (1 << 0)
8469 #define SKIPCONT (1 << 1)
8470 #define SKIPFUNC (1 << 2)
8471 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8472 static int skipcount; /* number of levels to skip */
8473 static int funcnest; /* depth of function calls */
8474 static int loopnest; /* current loop nesting level */
8476 /* Forward decl way out to parsing code - dotrap needs it */
8477 static int evalstring(char *s, int flags);
8479 /* Called to execute a trap.
8480 * Single callsite - at the end of evaltree().
8481 * If we return non-zero, evaltree raises EXEXIT exception.
8483 * Perhaps we should avoid entering new trap handlers
8484 * while we are executing a trap handler. [is it a TODO?]
8491 uint8_t last_status;
8496 last_status = exitstatus;
8500 TRACE(("dotrap entered\n"));
8501 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8513 /* non-trapped SIGINT is handled separately by raise_interrupt,
8514 * don't upset it by resetting gotsig[SIGINT-1] */
8515 if (sig == SIGINT && !p)
8518 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8524 exitstatus = last_status;
8525 TRACE(("dotrap returns\n"));
8528 /* forward declarations - evaluation is fairly recursive business... */
8529 static int evalloop(union node *, int);
8530 static int evalfor(union node *, int);
8531 static int evalcase(union node *, int);
8532 static int evalsubshell(union node *, int);
8533 static void expredir(union node *);
8534 static int evalpipe(union node *, int);
8535 static int evalcommand(union node *, int);
8536 static int evalbltin(const struct builtincmd *, int, char **, int);
8537 static void prehash(union node *);
8540 * Evaluate a parse tree. The value is left in the global variable
8544 evaltree(union node *n, int flags)
8547 int (*evalfn)(union node *, int);
8551 TRACE(("evaltree(NULL) called\n"));
8554 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8561 out1fmt("Node type = %d\n", n->type);
8566 status = !evaltree(n->nnot.com, EV_TESTED);
8569 expredir(n->nredir.redirect);
8570 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8572 status = evaltree(n->nredir.n, flags & EV_TESTED);
8574 if (n->nredir.redirect)
8575 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8578 evalfn = evalcommand;
8580 if (eflag && !(flags & EV_TESTED))
8592 evalfn = evalsubshell;
8605 #error NAND + 1 != NOR
8607 #if NOR + 1 != NSEMI
8608 #error NOR + 1 != NSEMI
8610 unsigned is_or = n->type - NAND;
8613 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8615 if ((!status) == is_or || evalskip)
8621 status = evalfn(n, flags);
8625 status = evaltree(n->nif.test, EV_TESTED);
8632 if (n->nif.elsepart) {
8633 n = n->nif.elsepart;
8640 /* Not necessary. To test it:
8641 * "false; f() { qwerty; }; echo $?" should print 0.
8645 exitstatus = status;
8649 /* Order of checks below is important:
8650 * signal handlers trigger before exit caused by "set -e".
8654 if (checkexit & status)
8655 raise_exception(EXEXIT);
8656 if (flags & EV_EXIT)
8657 raise_exception(EXEXIT);
8659 TRACE(("leaving evaltree (no interrupts)\n"));
8663 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8666 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8671 int skip = evalskip;
8678 if (--skipcount <= 0) {
8689 evalloop(union node *n, int flags)
8700 i = evaltree(n->nbinary.ch1, EV_TESTED);
8702 if (skip == SKIPFUNC)
8706 if (n->type != NWHILE)
8710 status = evaltree(n->nbinary.ch2, flags);
8712 } while (!(skip & ~SKIPCONT));
8719 evalfor(union node *n, int flags)
8721 struct arglist arglist;
8724 struct stackmark smark;
8727 setstackmark(&smark);
8728 arglist.list = NULL;
8729 arglist.lastp = &arglist.list;
8730 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8731 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8733 *arglist.lastp = NULL;
8737 for (sp = arglist.list; sp; sp = sp->next) {
8738 setvar0(n->nfor.var, sp->text);
8739 status = evaltree(n->nfor.body, flags);
8740 if (skiploop() & ~SKIPCONT)
8744 popstackmark(&smark);
8750 evalcase(union node *n, int flags)
8754 struct arglist arglist;
8755 struct stackmark smark;
8758 setstackmark(&smark);
8759 arglist.list = NULL;
8760 arglist.lastp = &arglist.list;
8761 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8762 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8763 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8764 if (casematch(patp, arglist.list->text)) {
8765 /* Ensure body is non-empty as otherwise
8766 * EV_EXIT may prevent us from setting the
8769 if (evalskip == 0 && cp->nclist.body) {
8770 status = evaltree(cp->nclist.body, flags);
8777 popstackmark(&smark);
8783 * Kick off a subshell to evaluate a tree.
8786 evalsubshell(union node *n, int flags)
8789 int backgnd = (n->type == NBACKGND);
8792 expredir(n->nredir.redirect);
8793 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8796 jp = makejob(/*n,*/ 1);
8797 if (forkshell(jp, n, backgnd) == 0) {
8802 flags &= ~EV_TESTED;
8804 redirect(n->nredir.redirect, 0);
8805 evaltreenr(n->nredir.n, flags);
8811 status = waitforjob(jp);
8817 * Compute the names of the files in a redirection list.
8819 static void fixredir(union node *, const char *, int);
8821 expredir(union node *n)
8825 for (redir = n; redir; redir = redir->nfile.next) {
8829 fn.lastp = &fn.list;
8830 switch (redir->type) {
8834 #if ENABLE_ASH_BASH_COMPAT
8839 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8840 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8841 #if ENABLE_ASH_BASH_COMPAT
8845 // By the design of stack allocator, the loop of this kind:
8846 // while true; do while true; do break; done </dev/null; done
8847 // will look like a memory leak: ash plans to free expfname's
8848 // of "/dev/null" as soon as it finishes running the loop
8849 // (in this case, never).
8850 // This "fix" is wrong:
8851 if (redir->nfile.expfname)
8852 stunalloc(redir->nfile.expfname);
8853 // It results in corrupted state of stacked allocations.
8855 redir->nfile.expfname = fn.list->text;
8858 case NTOFD: /* >& */
8859 if (redir->ndup.vname) {
8860 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8861 if (fn.list == NULL)
8862 ash_msg_and_raise_error("redir error");
8863 #if ENABLE_ASH_BASH_COMPAT
8864 //FIXME: we used expandarg with different args!
8865 if (!isdigit_str9(fn.list->text)) {
8866 /* >&file, not >&fd */
8867 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8868 ash_msg_and_raise_error("redir error");
8870 goto store_expfname;
8873 fixredir(redir, fn.list->text, 1);
8881 * Evaluate a pipeline. All the processes in the pipeline are children
8882 * of the process creating the pipeline. (This differs from some versions
8883 * of the shell, which make the last process in a pipeline the parent
8887 evalpipe(union node *n, int flags)
8890 struct nodelist *lp;
8896 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8898 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8902 jp = makejob(/*n,*/ pipelen);
8904 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8908 if (pipe(pip) < 0) {
8910 ash_msg_and_raise_error("pipe call failed");
8913 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8927 evaltreenr(lp->n, flags);
8934 /* Don't want to trigger debugging */
8938 if (n->npipe.pipe_backgnd == 0) {
8939 status = waitforjob(jp);
8940 TRACE(("evalpipe: job done exit status %d\n", status));
8948 * Controls whether the shell is interactive or not.
8951 setinteractive(int on)
8953 static smallint is_interactive;
8955 if (++on == is_interactive)
8957 is_interactive = on;
8961 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8962 if (is_interactive > 1) {
8963 /* Looks like they want an interactive shell */
8964 static smallint did_banner;
8967 /* note: ash and hush share this string */
8968 out1fmt("\n\n%s %s\n"
8969 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
8972 "built-in shell (ash)"
8986 setinteractive(iflag);
8988 #if ENABLE_FEATURE_EDITING_VI
8990 line_input_state->flags |= VI_MODE;
8992 line_input_state->flags &= ~VI_MODE;
8994 viflag = 0; /* forcibly keep the option off */
8998 static struct localvar *localvars;
9001 * Called after a function returns.
9002 * Interrupts must be off.
9007 struct localvar *lvp;
9010 while ((lvp = localvars) != NULL) {
9011 localvars = lvp->next;
9013 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9014 if (vp == NULL) { /* $- saved */
9015 memcpy(optlist, lvp->text, sizeof(optlist));
9016 free((char*)lvp->text);
9018 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
9019 unsetvar(vp->var_text);
9022 vp->var_func(var_end(lvp->text));
9023 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9024 free((char*)vp->var_text);
9025 vp->flags = lvp->flags;
9026 vp->var_text = lvp->text;
9033 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9035 volatile struct shparam saveparam;
9036 struct localvar *volatile savelocalvars;
9037 struct jmploc *volatile savehandler;
9038 struct jmploc jmploc;
9041 saveparam = shellparam;
9042 savelocalvars = localvars;
9043 savehandler = exception_handler;
9044 e = setjmp(jmploc.loc);
9049 exception_handler = &jmploc;
9051 shellparam.malloced = 0;
9055 shellparam.nparam = argc - 1;
9056 shellparam.p = argv + 1;
9057 #if ENABLE_ASH_GETOPTS
9058 shellparam.optind = 1;
9059 shellparam.optoff = -1;
9061 evaltree(func->n.narg.next, flags & EV_TESTED);
9067 localvars = savelocalvars;
9068 freeparam(&shellparam);
9069 shellparam = saveparam;
9070 exception_handler = savehandler;
9072 evalskip &= ~SKIPFUNC;
9077 * Make a variable a local variable. When a variable is made local, it's
9078 * value and flags are saved in a localvar structure. The saved values
9079 * will be restored when the shell function returns. We handle the name
9080 * "-" as a special case: it makes changes to "set +-options" local
9081 * (options will be restored on return from the function).
9086 struct localvar *lvp;
9089 char *eq = strchr(name, '=');
9092 /* Cater for duplicate "local". Examples:
9093 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9094 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9098 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9102 * it's a duplicate "local VAR" declaration, do nothing
9109 lvp = ckzalloc(sizeof(*lvp));
9110 if (LONE_DASH(name)) {
9112 p = ckmalloc(sizeof(optlist));
9113 lvp->text = memcpy(p, optlist, sizeof(optlist));
9116 vpp = hashvar(name);
9117 vp = *findvar(vpp, name);
9119 /* variable did not exist yet */
9121 setvareq(name, VSTRFIXED);
9123 setvar(name, NULL, VSTRFIXED);
9124 vp = *vpp; /* the new variable */
9125 lvp->flags = VUNSET;
9127 lvp->text = vp->var_text;
9128 lvp->flags = vp->flags;
9129 /* make sure neither "struct var" nor string gets freed
9130 * during (un)setting:
9132 vp->flags |= VSTRFIXED|VTEXTFIXED;
9136 /* "local VAR" unsets VAR: */
9137 setvar0(name, NULL);
9141 lvp->next = localvars;
9147 * The "local" command.
9149 static int FAST_FUNC
9150 localcmd(int argc UNUSED_PARAM, char **argv)
9155 ash_msg_and_raise_error("not in a function");
9158 while ((name = *argv++) != NULL) {
9164 static int FAST_FUNC
9165 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9170 static int FAST_FUNC
9171 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9176 static int FAST_FUNC
9177 execcmd(int argc UNUSED_PARAM, char **argv)
9180 iflag = 0; /* exit on error */
9183 /* We should set up signals for "exec CMD"
9184 * the same way as for "CMD" without "exec".
9185 * But optschanged->setinteractive->setsignal
9186 * still thought we are a root shell. Therefore, for example,
9187 * SIGQUIT is still set to IGN. Fix it:
9191 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9192 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9193 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9195 shellexec(argv + 1, pathval(), 0);
9202 * The return command.
9204 static int FAST_FUNC
9205 returncmd(int argc UNUSED_PARAM, char **argv)
9208 * If called outside a function, do what ksh does;
9209 * skip the rest of the file.
9211 evalskip = SKIPFUNC;
9212 return argv[1] ? number(argv[1]) : exitstatus;
9215 /* Forward declarations for builtintab[] */
9216 static int breakcmd(int, char **) FAST_FUNC;
9217 static int dotcmd(int, char **) FAST_FUNC;
9218 static int evalcmd(int, char **, int) FAST_FUNC;
9219 static int exitcmd(int, char **) FAST_FUNC;
9220 static int exportcmd(int, char **) FAST_FUNC;
9221 #if ENABLE_ASH_GETOPTS
9222 static int getoptscmd(int, char **) FAST_FUNC;
9225 static int helpcmd(int, char **) FAST_FUNC;
9228 static int historycmd(int, char **) FAST_FUNC;
9230 #if ENABLE_SH_MATH_SUPPORT
9231 static int letcmd(int, char **) FAST_FUNC;
9233 static int readcmd(int, char **) FAST_FUNC;
9234 static int setcmd(int, char **) FAST_FUNC;
9235 static int shiftcmd(int, char **) FAST_FUNC;
9236 static int timescmd(int, char **) FAST_FUNC;
9237 static int trapcmd(int, char **) FAST_FUNC;
9238 static int umaskcmd(int, char **) FAST_FUNC;
9239 static int unsetcmd(int, char **) FAST_FUNC;
9240 static int ulimitcmd(int, char **) FAST_FUNC;
9242 #define BUILTIN_NOSPEC "0"
9243 #define BUILTIN_SPECIAL "1"
9244 #define BUILTIN_REGULAR "2"
9245 #define BUILTIN_SPEC_REG "3"
9246 #define BUILTIN_ASSIGN "4"
9247 #define BUILTIN_SPEC_ASSG "5"
9248 #define BUILTIN_REG_ASSG "6"
9249 #define BUILTIN_SPEC_REG_ASSG "7"
9251 /* Stubs for calling non-FAST_FUNC's */
9252 #if ENABLE_ASH_BUILTIN_ECHO
9253 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9255 #if ENABLE_ASH_BUILTIN_PRINTF
9256 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9258 #if ENABLE_ASH_BUILTIN_TEST
9259 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9262 /* Keep these in proper order since it is searched via bsearch() */
9263 static const struct builtincmd builtintab[] = {
9264 { BUILTIN_SPEC_REG "." , dotcmd },
9265 { BUILTIN_SPEC_REG ":" , truecmd },
9266 #if ENABLE_ASH_BUILTIN_TEST
9267 { BUILTIN_REGULAR "[" , testcmd },
9268 #if ENABLE_ASH_BASH_COMPAT
9269 { BUILTIN_REGULAR "[[" , testcmd },
9272 #if ENABLE_ASH_ALIAS
9273 { BUILTIN_REG_ASSG "alias" , aliascmd },
9276 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9278 { BUILTIN_SPEC_REG "break" , breakcmd },
9279 { BUILTIN_REGULAR "cd" , cdcmd },
9280 { BUILTIN_NOSPEC "chdir" , cdcmd },
9281 #if ENABLE_ASH_CMDCMD
9282 { BUILTIN_REGULAR "command" , commandcmd },
9284 { BUILTIN_SPEC_REG "continue", breakcmd },
9285 #if ENABLE_ASH_BUILTIN_ECHO
9286 { BUILTIN_REGULAR "echo" , echocmd },
9288 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9289 { BUILTIN_SPEC_REG "exec" , execcmd },
9290 { BUILTIN_SPEC_REG "exit" , exitcmd },
9291 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9292 { BUILTIN_REGULAR "false" , falsecmd },
9294 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9296 #if ENABLE_ASH_GETOPTS
9297 { BUILTIN_REGULAR "getopts" , getoptscmd },
9299 { BUILTIN_NOSPEC "hash" , hashcmd },
9301 { BUILTIN_NOSPEC "help" , helpcmd },
9304 { BUILTIN_NOSPEC "history" , historycmd },
9307 { BUILTIN_REGULAR "jobs" , jobscmd },
9308 { BUILTIN_REGULAR "kill" , killcmd },
9310 #if ENABLE_SH_MATH_SUPPORT
9311 { BUILTIN_NOSPEC "let" , letcmd },
9313 { BUILTIN_ASSIGN "local" , localcmd },
9314 #if ENABLE_ASH_BUILTIN_PRINTF
9315 { BUILTIN_REGULAR "printf" , printfcmd },
9317 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9318 { BUILTIN_REGULAR "read" , readcmd },
9319 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9320 { BUILTIN_SPEC_REG "return" , returncmd },
9321 { BUILTIN_SPEC_REG "set" , setcmd },
9322 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9323 #if ENABLE_ASH_BASH_COMPAT
9324 { BUILTIN_SPEC_REG "source" , dotcmd },
9326 #if ENABLE_ASH_BUILTIN_TEST
9327 { BUILTIN_REGULAR "test" , testcmd },
9329 { BUILTIN_SPEC_REG "times" , timescmd },
9330 { BUILTIN_SPEC_REG "trap" , trapcmd },
9331 { BUILTIN_REGULAR "true" , truecmd },
9332 { BUILTIN_NOSPEC "type" , typecmd },
9333 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9334 { BUILTIN_REGULAR "umask" , umaskcmd },
9335 #if ENABLE_ASH_ALIAS
9336 { BUILTIN_REGULAR "unalias" , unaliascmd },
9338 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9339 { BUILTIN_REGULAR "wait" , waitcmd },
9342 /* Should match the above table! */
9343 #define COMMANDCMD (builtintab + \
9345 /* [ */ 1 * ENABLE_ASH_BUILTIN_TEST + \
9346 /* [[ */ 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9347 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9348 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9349 /* break cd cddir */ 3)
9350 #define EVALCMD (COMMANDCMD + \
9351 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9352 /* continue */ 1 + \
9353 /* echo */ 1 * ENABLE_ASH_BUILTIN_ECHO + \
9355 #define EXECCMD (EVALCMD + \
9359 * Search the table of builtin commands.
9362 pstrcmp1(const void *a, const void *b)
9364 return strcmp((char*)a, *(char**)b + 1);
9366 static struct builtincmd *
9367 find_builtin(const char *name)
9369 struct builtincmd *bp;
9372 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9379 * Execute a simple command.
9382 isassignment(const char *p)
9384 const char *q = endofname(p);
9389 static int FAST_FUNC
9390 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9392 /* Preserve exitstatus of a previous possible redirection
9393 * as POSIX mandates */
9394 return back_exitstatus;
9397 evalcommand(union node *cmd, int flags)
9399 static const struct builtincmd null_bltin = {
9400 "\0\0", bltincmd /* why three NULs? */
9402 struct stackmark smark;
9404 struct arglist arglist;
9405 struct arglist varlist;
9408 const struct strlist *sp;
9409 struct cmdentry cmdentry;
9416 struct builtincmd *bcmd;
9417 smallint cmd_is_exec;
9418 smallint pseudovarflag = 0;
9420 /* First expand the arguments. */
9421 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9422 setstackmark(&smark);
9423 back_exitstatus = 0;
9425 cmdentry.cmdtype = CMDBUILTIN;
9426 cmdentry.u.cmd = &null_bltin;
9427 varlist.lastp = &varlist.list;
9428 *varlist.lastp = NULL;
9429 arglist.lastp = &arglist.list;
9430 *arglist.lastp = NULL;
9433 if (cmd->ncmd.args) {
9434 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9435 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9438 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9439 struct strlist **spp;
9441 spp = arglist.lastp;
9442 if (pseudovarflag && isassignment(argp->narg.text))
9443 expandarg(argp, &arglist, EXP_VARTILDE);
9445 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9447 for (sp = *spp; sp; sp = sp->next)
9451 /* Reserve one extra spot at the front for shellexec. */
9452 nargv = stalloc(sizeof(char *) * (argc + 2));
9454 for (sp = arglist.list; sp; sp = sp->next) {
9455 TRACE(("evalcommand arg: %s\n", sp->text));
9456 *nargv++ = sp->text;
9461 if (iflag && funcnest == 0 && argc > 0)
9462 lastarg = nargv[-1];
9465 expredir(cmd->ncmd.redirect);
9466 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9468 path = vpath.var_text;
9469 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9470 struct strlist **spp;
9473 spp = varlist.lastp;
9474 expandarg(argp, &varlist, EXP_VARTILDE);
9477 * Modify the command lookup path, if a PATH= assignment
9481 if (varcmp(p, path) == 0)
9485 /* Print the command if xflag is set. */
9488 const char *p = " %s" + 1;
9490 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9492 for (n = 0; n < 2; n++) {
9494 fdprintf(preverrout_fd, p, sp->text);
9500 safe_write(preverrout_fd, "\n", 1);
9506 /* Now locate the command. */
9508 int cmd_flag = DO_ERR;
9509 #if ENABLE_ASH_CMDCMD
9510 const char *oldpath = path + 5;
9514 find_command(argv[0], &cmdentry, cmd_flag, path);
9515 if (cmdentry.cmdtype == CMDUNKNOWN) {
9516 flush_stdout_stderr();
9521 /* implement bltin and command here */
9522 if (cmdentry.cmdtype != CMDBUILTIN)
9525 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9526 if (cmdentry.u.cmd == EXECCMD)
9528 #if ENABLE_ASH_CMDCMD
9529 if (cmdentry.u.cmd == COMMANDCMD) {
9531 nargv = parse_command_args(argv, &path);
9534 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9535 * nargv => "PROG". path is updated if -p.
9537 argc -= nargv - argv;
9539 cmd_flag |= DO_NOFUNC;
9547 /* We have a redirection error. */
9549 raise_exception(EXERROR);
9551 exitstatus = status;
9555 /* Execute the command. */
9556 switch (cmdentry.cmdtype) {
9559 #if ENABLE_FEATURE_SH_NOFORK
9560 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9561 * around run_nofork_applet() call.
9562 * (2) Should this check also be done in forkshell()?
9563 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9565 /* find_command() encodes applet_no as (-2 - applet_no) */
9566 int applet_no = (- cmdentry.u.index - 2);
9567 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9568 listsetvar(varlist.list, VEXPORT|VSTACK);
9569 /* run <applet>_main() */
9570 status = run_nofork_applet(applet_no, argv);
9574 /* Can we avoid forking off? For example, very last command
9575 * in a script or a subshell does not need forking,
9576 * we can just exec it.
9578 if (!(flags & EV_EXIT) || may_have_traps) {
9579 /* No, forking off a child is necessary */
9581 jp = makejob(/*cmd,*/ 1);
9582 if (forkshell(jp, cmd, FORK_FG) != 0) {
9584 status = waitforjob(jp);
9586 TRACE(("forked child exited with %d\n", status));
9591 /* fall through to exec'ing external program */
9593 listsetvar(varlist.list, VEXPORT|VSTACK);
9594 shellexec(argv, path, cmdentry.u.index);
9598 cmdenviron = varlist.list;
9600 struct strlist *list = cmdenviron;
9602 if (spclbltin > 0 || argc == 0) {
9604 if (cmd_is_exec && argc > 1)
9607 listsetvar(list, i);
9609 /* Tight loop with builtins only:
9610 * "while kill -0 $child; do true; done"
9611 * will never exit even if $child died, unless we do this
9612 * to reap the zombie and make kill detect that it's gone: */
9613 dowait(DOWAIT_NONBLOCK, NULL);
9615 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9616 if (exception_type == EXERROR && spclbltin <= 0) {
9621 longjmp(exception_handler->loc, 1);
9626 listsetvar(varlist.list, 0);
9627 /* See above for the rationale */
9628 dowait(DOWAIT_NONBLOCK, NULL);
9629 if (evalfun(cmdentry.u.func, argc, argv, flags))
9632 status = exitstatus;
9637 if (cmd->ncmd.redirect)
9638 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9640 /* dsl: I think this is intended to be used to support
9641 * '_' in 'vi' command mode during line editing...
9642 * However I implemented that within libedit itself.
9644 setvar0("_", lastarg);
9646 popstackmark(&smark);
9652 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9654 char *volatile savecmdname;
9655 struct jmploc *volatile savehandler;
9656 struct jmploc jmploc;
9660 savecmdname = commandname;
9661 savehandler = exception_handler;
9662 i = setjmp(jmploc.loc);
9665 exception_handler = &jmploc;
9666 commandname = argv[0];
9668 optptr = NULL; /* initialize nextopt */
9670 status = evalcmd(argc, argv, flags);
9672 status = (*cmd->builtin)(argc, argv);
9673 flush_stdout_stderr();
9674 status |= ferror(stdout);
9675 exitstatus = status;
9678 commandname = savecmdname;
9679 exception_handler = savehandler;
9685 goodname(const char *p)
9687 return endofname(p)[0] == '\0';
9692 * Search for a command. This is called before we fork so that the
9693 * location of the command will be available in the parent as well as
9694 * the child. The check for "goodname" is an overly conservative
9695 * check that the name will not be subject to expansion.
9698 prehash(union node *n)
9700 struct cmdentry entry;
9702 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9703 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9707 /* ============ Builtin commands
9709 * Builtin commands whose functions are closely tied to evaluation
9710 * are implemented here.
9714 * Handle break and continue commands. Break, continue, and return are
9715 * all handled by setting the evalskip flag. The evaluation routines
9716 * above all check this flag, and if it is set they start skipping
9717 * commands rather than executing them. The variable skipcount is
9718 * the number of loops to break/continue, or the number of function
9719 * levels to return. (The latter is always 1.) It should probably
9720 * be an error to break out of more loops than exist, but it isn't
9721 * in the standard shell so we don't make it one here.
9723 static int FAST_FUNC
9724 breakcmd(int argc UNUSED_PARAM, char **argv)
9726 int n = argv[1] ? number(argv[1]) : 1;
9729 ash_msg_and_raise_error(msg_illnum, argv[1]);
9733 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9741 * This implements the input routines used by the parser.
9745 INPUT_PUSH_FILE = 1,
9746 INPUT_NOFILE_OK = 2,
9749 static smallint checkkwd;
9750 /* values of checkkwd variable */
9751 #define CHKALIAS 0x1
9756 * Push a string back onto the input at this current parsefile level.
9757 * We handle aliases this way.
9759 #if !ENABLE_ASH_ALIAS
9760 #define pushstring(s, ap) pushstring(s)
9763 pushstring(char *s, struct alias *ap)
9770 if (g_parsefile->strpush) {
9771 sp = ckzalloc(sizeof(*sp));
9772 sp->prev = g_parsefile->strpush;
9774 sp = &(g_parsefile->basestrpush);
9776 g_parsefile->strpush = sp;
9777 sp->prev_string = g_parsefile->next_to_pgetc;
9778 sp->prev_left_in_line = g_parsefile->left_in_line;
9779 sp->unget = g_parsefile->unget;
9780 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9781 #if ENABLE_ASH_ALIAS
9784 ap->flag |= ALIASINUSE;
9788 g_parsefile->next_to_pgetc = s;
9789 g_parsefile->left_in_line = len;
9790 g_parsefile->unget = 0;
9797 struct strpush *sp = g_parsefile->strpush;
9800 #if ENABLE_ASH_ALIAS
9802 if (g_parsefile->next_to_pgetc[-1] == ' '
9803 || g_parsefile->next_to_pgetc[-1] == '\t'
9805 checkkwd |= CHKALIAS;
9807 if (sp->string != sp->ap->val) {
9810 sp->ap->flag &= ~ALIASINUSE;
9811 if (sp->ap->flag & ALIASDEAD) {
9812 unalias(sp->ap->name);
9816 g_parsefile->next_to_pgetc = sp->prev_string;
9817 g_parsefile->left_in_line = sp->prev_left_in_line;
9818 g_parsefile->unget = sp->unget;
9819 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
9820 g_parsefile->strpush = sp->prev;
9821 if (sp != &(g_parsefile->basestrpush))
9830 char *buf = g_parsefile->buf;
9832 g_parsefile->next_to_pgetc = buf;
9833 #if ENABLE_FEATURE_EDITING
9835 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9836 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9839 # if ENABLE_ASH_IDLE_TIMEOUT
9841 const char *tmout_var = lookupvar("TMOUT");
9843 timeout = atoi(tmout_var) * 1000;
9849 # if ENABLE_FEATURE_TAB_COMPLETION
9850 line_input_state->path_lookup = pathval();
9852 reinit_unicode_for_ash();
9853 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9855 /* Ctrl+C pressed */
9866 /* Ctrl+D pressed */
9869 # if ENABLE_ASH_IDLE_TIMEOUT
9870 else if (errno == EAGAIN && timeout > 0) {
9871 puts("\007timed out waiting for input: auto-logout");
9878 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9881 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9883 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9884 int flags = fcntl(0, F_GETFL);
9885 if (flags >= 0 && (flags & O_NONBLOCK)) {
9886 flags &= ~O_NONBLOCK;
9887 if (fcntl(0, F_SETFL, flags) >= 0) {
9888 out2str("sh: turning off NDELAY mode\n");
9899 * Refill the input buffer and return the next input character:
9901 * 1) If a string was pushed back on the input, pop it;
9902 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9903 * or we are reading from a string so we can't refill the buffer,
9905 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9906 * 4) Process input up to the next newline, deleting nul characters.
9908 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9909 #define pgetc_debug(...) ((void)0)
9910 static int pgetc(void);
9917 if (g_parsefile->strpush) {
9918 #if ENABLE_ASH_ALIAS
9919 if (g_parsefile->left_in_line == -1
9920 && g_parsefile->strpush->ap
9921 && g_parsefile->next_to_pgetc[-1] != ' '
9922 && g_parsefile->next_to_pgetc[-1] != '\t'
9924 pgetc_debug("preadbuffer PEOA");
9931 /* on both branches above g_parsefile->left_in_line < 0.
9932 * "pgetc" needs refilling.
9935 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9936 * pungetc() may increment it a few times.
9937 * Assuming it won't increment it to less than -90.
9939 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9940 pgetc_debug("preadbuffer PEOF1");
9941 /* even in failure keep left_in_line and next_to_pgetc
9942 * in lock step, for correct multi-layer pungetc.
9943 * left_in_line was decremented before preadbuffer(),
9944 * must inc next_to_pgetc: */
9945 g_parsefile->next_to_pgetc++;
9949 more = g_parsefile->left_in_buffer;
9951 flush_stdout_stderr();
9955 /* don't try reading again */
9956 g_parsefile->left_in_line = -99;
9957 pgetc_debug("preadbuffer PEOF2");
9958 g_parsefile->next_to_pgetc++;
9963 /* Find out where's the end of line.
9964 * Set g_parsefile->left_in_line
9965 * and g_parsefile->left_in_buffer acordingly.
9966 * NUL chars are deleted.
9968 q = g_parsefile->next_to_pgetc;
9976 memmove(q, q + 1, more);
9980 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9986 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9987 if (g_parsefile->left_in_line < 0)
9992 g_parsefile->left_in_buffer = more;
9997 out2str(g_parsefile->next_to_pgetc);
10001 pgetc_debug("preadbuffer at %d:%p'%s'",
10002 g_parsefile->left_in_line,
10003 g_parsefile->next_to_pgetc,
10004 g_parsefile->next_to_pgetc);
10005 return (unsigned char)*g_parsefile->next_to_pgetc++;
10011 g_parsefile->linno++;
10012 setprompt_if(doprompt, 2);
10017 g_parsefile->linno++;
10018 needprompt = doprompt;
10026 pgetc_debug("pgetc at %d:%p'%s'",
10027 g_parsefile->left_in_line,
10028 g_parsefile->next_to_pgetc,
10029 g_parsefile->next_to_pgetc);
10030 if (g_parsefile->unget)
10031 return g_parsefile->lastc[--g_parsefile->unget];
10033 if (--g_parsefile->left_in_line >= 0)
10034 c = (signed char)*g_parsefile->next_to_pgetc++;
10038 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10039 g_parsefile->lastc[0] = c;
10044 #if ENABLE_ASH_ALIAS
10046 pgetc_without_PEOA(void)
10050 pgetc_debug("pgetc at %d:%p'%s'",
10051 g_parsefile->left_in_line,
10052 g_parsefile->next_to_pgetc,
10053 g_parsefile->next_to_pgetc);
10055 } while (c == PEOA);
10059 # define pgetc_without_PEOA() pgetc()
10063 * Read a line from the script.
10066 pfgets(char *line, int len)
10072 while (--nleft > 0) {
10073 c = pgetc_without_PEOA();
10088 * Undo a call to pgetc. Only two characters may be pushed back.
10089 * PEOF may be pushed back.
10094 g_parsefile->unget++;
10097 /* This one eats backslash+newline */
10103 while ((c = pgetc()) == '\\') {
10104 if (pgetc() != '\n') {
10116 * To handle the "." command, a stack of input files is used. Pushfile
10117 * adds a new entry to the stack and popfile restores the previous level.
10122 struct parsefile *pf;
10124 pf = ckzalloc(sizeof(*pf));
10125 pf->prev = g_parsefile;
10127 /*pf->strpush = NULL; - ckzalloc did it */
10128 /*pf->basestrpush.prev = NULL;*/
10136 struct parsefile *pf = g_parsefile;
10142 if (pf->pf_fd >= 0)
10145 while (pf->strpush)
10147 g_parsefile = pf->prev;
10153 * Return to top level.
10158 while (g_parsefile != &basepf)
10163 * Close the file(s) that the shell is reading commands from. Called
10164 * after a fork is done.
10170 if (g_parsefile->pf_fd > 0) {
10171 close(g_parsefile->pf_fd);
10172 g_parsefile->pf_fd = 0;
10177 * Like setinputfile, but takes an open file descriptor. Call this with
10181 setinputfd(int fd, int push)
10185 g_parsefile->buf = NULL;
10187 g_parsefile->pf_fd = fd;
10188 if (g_parsefile->buf == NULL)
10189 g_parsefile->buf = ckmalloc(IBUFSIZ);
10190 g_parsefile->left_in_buffer = 0;
10191 g_parsefile->left_in_line = 0;
10192 g_parsefile->linno = 1;
10196 * Set the input to take input from a file. If push is set, push the
10197 * old input onto the stack first.
10200 setinputfile(const char *fname, int flags)
10205 fd = open(fname, O_RDONLY);
10207 if (flags & INPUT_NOFILE_OK)
10210 ash_msg_and_raise_error("can't open '%s'", fname);
10215 close_on_exec_on(fd);
10216 setinputfd(fd, flags & INPUT_PUSH_FILE);
10223 * Like setinputfile, but takes input from a string.
10226 setinputstring(char *string)
10230 g_parsefile->next_to_pgetc = string;
10231 g_parsefile->left_in_line = strlen(string);
10232 g_parsefile->buf = NULL;
10233 g_parsefile->linno = 1;
10239 * Routines to check for mail.
10242 #if ENABLE_ASH_MAIL
10244 /* Hash of mtimes of mailboxes */
10245 static unsigned mailtime_hash;
10246 /* Set if MAIL or MAILPATH is changed. */
10247 static smallint mail_var_path_changed;
10250 * Print appropriate message(s) if mail has arrived.
10251 * If mail_var_path_changed is set,
10252 * then the value of MAIL has mail_var_path_changed,
10253 * so we just update the values.
10262 struct stackmark smark;
10265 setstackmark(&smark);
10266 mpath = mpathset() ? mpathval() : mailval();
10269 p = path_advance(&mpath, nullstr);
10274 for (q = p; *q; q++)
10280 q[-1] = '\0'; /* delete trailing '/' */
10281 if (stat(p, &statb) < 0) {
10284 /* Very simplistic "hash": just a sum of all mtimes */
10285 new_hash += (unsigned)statb.st_mtime;
10287 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10288 if (mailtime_hash != 0)
10289 out2str("you have mail\n");
10290 mailtime_hash = new_hash;
10292 mail_var_path_changed = 0;
10293 popstackmark(&smark);
10296 static void FAST_FUNC
10297 changemail(const char *val UNUSED_PARAM)
10299 mail_var_path_changed = 1;
10302 #endif /* ASH_MAIL */
10305 /* ============ ??? */
10308 * Set the shell parameters.
10311 setparam(char **argv)
10317 for (nparam = 0; argv[nparam]; nparam++)
10319 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10321 *ap++ = ckstrdup(*argv++);
10324 freeparam(&shellparam);
10325 shellparam.malloced = 1;
10326 shellparam.nparam = nparam;
10327 shellparam.p = newparam;
10328 #if ENABLE_ASH_GETOPTS
10329 shellparam.optind = 1;
10330 shellparam.optoff = -1;
10335 * Process shell options. The global variable argptr contains a pointer
10336 * to the argument list; we advance it past the options.
10338 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10339 * For a non-interactive shell, an error condition encountered
10340 * by a special built-in ... shall cause the shell to write a diagnostic message
10341 * to standard error and exit as shown in the following table:
10342 * Error Special Built-In
10344 * Utility syntax error (option or operand error) Shall exit
10346 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10347 * we see that bash does not do that (set "finishes" with error code 1 instead,
10348 * and shell continues), and people rely on this behavior!
10350 * set -o barfoo 2>/dev/null
10353 * Oh well. Let's mimic that.
10356 plus_minus_o(char *name, int val)
10361 for (i = 0; i < NOPTS; i++) {
10362 if (strcmp(name, optnames(i)) == 0) {
10367 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10370 for (i = 0; i < NOPTS; i++) {
10372 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10374 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10380 setoption(int flag, int val)
10384 for (i = 0; i < NOPTS; i++) {
10385 if (optletters(i) == flag) {
10390 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10394 options(int cmdline)
10402 while ((p = *argptr) != NULL) {
10404 if (c != '-' && c != '+')
10407 val = 0; /* val = 0 if c == '+' */
10410 if (p[0] == '\0' || LONE_DASH(p)) {
10412 /* "-" means turn off -x and -v */
10415 /* "--" means reset params */
10416 else if (*argptr == NULL)
10419 break; /* "-" or "--" terminates options */
10422 /* first char was + or - */
10423 while ((c = *p++) != '\0') {
10424 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10425 if (c == 'c' && cmdline) {
10426 minusc = p; /* command is after shell args */
10427 } else if (c == 'o') {
10428 if (plus_minus_o(*argptr, val)) {
10429 /* it already printed err message */
10430 return 1; /* error */
10434 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10436 /* bash does not accept +-login, we also won't */
10437 } else if (cmdline && val && (c == '-')) { /* long options */
10438 if (strcmp(p, "login") == 0)
10450 * The shift builtin command.
10452 static int FAST_FUNC
10453 shiftcmd(int argc UNUSED_PARAM, char **argv)
10460 n = number(argv[1]);
10461 if (n > shellparam.nparam)
10462 n = 0; /* bash compat, was = shellparam.nparam; */
10464 shellparam.nparam -= n;
10465 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10466 if (shellparam.malloced)
10469 ap2 = shellparam.p;
10470 while ((*ap2++ = *ap1++) != NULL)
10472 #if ENABLE_ASH_GETOPTS
10473 shellparam.optind = 1;
10474 shellparam.optoff = -1;
10481 * POSIX requires that 'set' (but not export or readonly) output the
10482 * variables in lexicographic order - by the locale's collating order (sigh).
10483 * Maybe we could keep them in an ordered balanced binary tree
10484 * instead of hashed lists.
10485 * For now just roll 'em through qsort for printing...
10488 showvars(const char *sep_prefix, int on, int off)
10491 char **ep, **epend;
10493 ep = listvars(on, off, &epend);
10494 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10496 sep = *sep_prefix ? " " : sep_prefix;
10498 for (; ep < epend; ep++) {
10502 p = strchrnul(*ep, '=');
10505 q = single_quote(++p);
10506 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10512 * The set command builtin.
10514 static int FAST_FUNC
10515 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10520 return showvars(nullstr, 0, VUNSET);
10523 retval = options(/*cmdline:*/ 0);
10524 if (retval == 0) { /* if no parse error... */
10526 if (*argptr != NULL) {
10534 #if ENABLE_ASH_RANDOM_SUPPORT
10535 static void FAST_FUNC
10536 change_random(const char *value)
10540 if (value == NULL) {
10541 /* "get", generate */
10542 t = next_random(&random_gen);
10543 /* set without recursion */
10544 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10545 vrandom.flags &= ~VNOFUNC;
10548 t = strtoul(value, NULL, 10);
10549 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10554 #if ENABLE_ASH_GETOPTS
10556 getopts(char *optstr, char *optvar, char **optfirst)
10563 int ind = shellparam.optind;
10564 int off = shellparam.optoff;
10568 shellparam.optind = -1;
10569 optnext = optfirst + ind - 1;
10571 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10574 p = optnext[-1] + off;
10575 if (p == NULL || *p == '\0') {
10576 /* Current word is done, advance */
10578 if (p == NULL || *p != '-' || *++p == '\0') {
10585 if (LONE_DASH(p)) /* check for "--" */
10590 for (q = optstr; *q != c;) {
10592 if (optstr[0] == ':') {
10594 /*sbuf[1] = '\0'; - already is */
10595 setvar0("OPTARG", sbuf);
10597 fprintf(stderr, "Illegal option -%c\n", c);
10598 unsetvar("OPTARG");
10608 if (*p == '\0' && (p = *optnext) == NULL) {
10609 if (optstr[0] == ':') {
10611 /*sbuf[1] = '\0'; - already is */
10612 setvar0("OPTARG", sbuf);
10615 fprintf(stderr, "No arg for -%c option\n", c);
10616 unsetvar("OPTARG");
10624 setvar0("OPTARG", p);
10627 setvar0("OPTARG", nullstr);
10629 ind = optnext - optfirst + 1;
10630 setvar("OPTIND", itoa(ind), VNOFUNC);
10632 /*sbuf[1] = '\0'; - already is */
10633 setvar0(optvar, sbuf);
10635 shellparam.optoff = p ? p - *(optnext - 1) : -1;
10636 shellparam.optind = ind;
10642 * The getopts builtin. Shellparam.optnext points to the next argument
10643 * to be processed. Shellparam.optptr points to the next character to
10644 * be processed in the current argument. If shellparam.optnext is NULL,
10645 * then it's the first time getopts has been called.
10647 static int FAST_FUNC
10648 getoptscmd(int argc, char **argv)
10653 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10655 optbase = shellparam.p;
10656 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
10657 shellparam.optind = 1;
10658 shellparam.optoff = -1;
10661 optbase = &argv[3];
10662 if ((unsigned)shellparam.optind > argc - 2) {
10663 shellparam.optind = 1;
10664 shellparam.optoff = -1;
10668 return getopts(argv[1], argv[2], optbase);
10670 #endif /* ASH_GETOPTS */
10673 /* ============ Shell parser */
10676 struct heredoc *next; /* next here document in list */
10677 union node *here; /* redirection node */
10678 char *eofmark; /* string indicating end of input */
10679 smallint striptabs; /* if set, strip leading tabs */
10682 static smallint tokpushback; /* last token pushed back */
10683 static smallint quoteflag; /* set if (part of) last token was quoted */
10684 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10685 static struct heredoc *heredoclist; /* list of here documents to read */
10686 static char *wordtext; /* text of last word returned by readtoken */
10687 static struct nodelist *backquotelist;
10688 static union node *redirnode;
10689 static struct heredoc *heredoc;
10691 static const char *
10692 tokname(char *buf, int tok)
10695 return tokname_array[tok];
10696 sprintf(buf, "\"%s\"", tokname_array[tok]);
10700 /* raise_error_unexpected_syntax:
10701 * Called when an unexpected token is read during the parse. The argument
10702 * is the token that is expected, or -1 if more than one type of token can
10703 * occur at this point.
10705 static void raise_error_unexpected_syntax(int) NORETURN;
10707 raise_error_unexpected_syntax(int token)
10713 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10715 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10716 raise_error_syntax(msg);
10720 #define EOFMARKLEN 79
10722 /* parsing is heavily cross-recursive, need these forward decls */
10723 static union node *andor(void);
10724 static union node *pipeline(void);
10725 static union node *parse_command(void);
10726 static void parseheredoc(void);
10727 static int peektoken(void);
10728 static int readtoken(void);
10730 static union node *
10733 union node *n1, *n2, *n3;
10738 switch (peektoken()) {
10746 if (!n1 && (nlflag & 1))
10752 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10753 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
10759 if (tok == TBACKGND) {
10760 if (n2->type == NPIPE) {
10761 n2->npipe.pipe_backgnd = 1;
10763 if (n2->type != NREDIR) {
10764 n3 = stzalloc(sizeof(struct nredir));
10766 /*n3->nredir.redirect = NULL; - stzalloc did it */
10769 n2->type = NBACKGND;
10775 n3 = stzalloc(sizeof(struct nbinary));
10777 n3->nbinary.ch1 = n1;
10778 n3->nbinary.ch2 = n2;
10791 raise_error_unexpected_syntax(-1);
10798 static union node *
10801 union node *n1, *n2, *n3;
10809 } else if (t == TOR) {
10815 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10817 n3 = stzalloc(sizeof(struct nbinary));
10819 n3->nbinary.ch1 = n1;
10820 n3->nbinary.ch2 = n2;
10825 static union node *
10828 union node *n1, *n2, *pipenode;
10829 struct nodelist *lp, *prev;
10833 TRACE(("pipeline: entered\n"));
10834 if (readtoken() == TNOT) {
10836 checkkwd = CHKKWD | CHKALIAS;
10839 n1 = parse_command();
10840 if (readtoken() == TPIPE) {
10841 pipenode = stzalloc(sizeof(struct npipe));
10842 pipenode->type = NPIPE;
10843 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10844 lp = stzalloc(sizeof(struct nodelist));
10845 pipenode->npipe.cmdlist = lp;
10849 lp = stzalloc(sizeof(struct nodelist));
10850 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10851 lp->n = parse_command();
10853 } while (readtoken() == TPIPE);
10859 n2 = stzalloc(sizeof(struct nnot));
10867 static union node *
10872 n = stzalloc(sizeof(struct narg));
10874 /*n->narg.next = NULL; - stzalloc did it */
10875 n->narg.text = wordtext;
10876 n->narg.backquote = backquotelist;
10881 fixredir(union node *n, const char *text, int err)
10885 TRACE(("Fix redir %s %d\n", text, err));
10887 n->ndup.vname = NULL;
10889 fd = bb_strtou(text, NULL, 10);
10890 if (!errno && fd >= 0)
10891 n->ndup.dupfd = fd;
10892 else if (LONE_DASH(text))
10893 n->ndup.dupfd = -1;
10896 raise_error_syntax("bad fd number");
10897 n->ndup.vname = makename();
10902 * Returns true if the text contains nothing to expand (no dollar signs
10906 noexpand(const char *text)
10910 while ((c = *text++) != '\0') {
10911 if (c == CTLQUOTEMARK)
10915 else if (SIT(c, BASESYNTAX) == CCTL)
10924 union node *n = redirnode;
10926 if (readtoken() != TWORD)
10927 raise_error_unexpected_syntax(-1);
10928 if (n->type == NHERE) {
10929 struct heredoc *here = heredoc;
10933 if (quoteflag == 0)
10935 TRACE(("Here document %d\n", n->type));
10936 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10937 raise_error_syntax("illegal eof marker for << redirection");
10938 rmescapes(wordtext, 0);
10939 here->eofmark = wordtext;
10941 if (heredoclist == NULL)
10942 heredoclist = here;
10944 for (p = heredoclist; p->next; p = p->next)
10948 } else if (n->type == NTOFD || n->type == NFROMFD) {
10949 fixredir(n, wordtext, 0);
10951 n->nfile.fname = makename();
10955 static union node *
10958 union node *args, **app;
10959 union node *n = NULL;
10960 union node *vars, **vpp;
10961 union node **rpp, *redir;
10963 #if ENABLE_ASH_BASH_COMPAT
10964 smallint double_brackets_flag = 0;
10965 smallint function_flag = 0;
10975 savecheckkwd = CHKALIAS;
10978 checkkwd = savecheckkwd;
10981 #if ENABLE_ASH_BASH_COMPAT
10983 if (peektoken() != TWORD)
10984 raise_error_unexpected_syntax(TWORD);
10987 case TAND: /* "&&" */
10988 case TOR: /* "||" */
10989 if (!double_brackets_flag) {
10993 wordtext = (char *) (t == TAND ? "-a" : "-o");
10996 n = stzalloc(sizeof(struct narg));
10998 /*n->narg.next = NULL; - stzalloc did it */
10999 n->narg.text = wordtext;
11000 #if ENABLE_ASH_BASH_COMPAT
11001 if (strcmp("[[", wordtext) == 0)
11002 double_brackets_flag = 1;
11003 else if (strcmp("]]", wordtext) == 0)
11004 double_brackets_flag = 0;
11006 n->narg.backquote = backquotelist;
11007 if (savecheckkwd && isassignment(wordtext)) {
11009 vpp = &n->narg.next;
11012 app = &n->narg.next;
11015 #if ENABLE_ASH_BASH_COMPAT
11016 if (function_flag) {
11017 checkkwd = CHKNL | CHKKWD;
11018 switch (peektoken()) {
11030 if (strcmp("[[", wordtext) == 0)
11034 raise_error_unexpected_syntax(-1);
11040 *rpp = n = redirnode;
11041 rpp = &n->nfile.next;
11042 parsefname(); /* read name of redirection file */
11045 IF_ASH_BASH_COMPAT(do_func:)
11046 if (args && app == &args->narg.next
11049 struct builtincmd *bcmd;
11052 /* We have a function */
11053 if (IF_ASH_BASH_COMPAT(!function_flag &&) readtoken() != TRP)
11054 raise_error_unexpected_syntax(TRP);
11055 name = n->narg.text;
11056 if (!goodname(name)
11057 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11059 raise_error_syntax("bad function name");
11062 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11063 n->narg.next = parse_command();
11066 IF_ASH_BASH_COMPAT(function_flag = 0;)
11077 n = stzalloc(sizeof(struct ncmd));
11079 n->ncmd.args = args;
11080 n->ncmd.assign = vars;
11081 n->ncmd.redirect = redir;
11085 static union node *
11086 parse_command(void)
11088 union node *n1, *n2;
11089 union node *ap, **app;
11090 union node *cp, **cpp;
11091 union node *redir, **rpp;
11098 switch (readtoken()) {
11100 raise_error_unexpected_syntax(-1);
11103 n1 = stzalloc(sizeof(struct nif));
11105 n1->nif.test = list(0);
11106 if (readtoken() != TTHEN)
11107 raise_error_unexpected_syntax(TTHEN);
11108 n1->nif.ifpart = list(0);
11110 while (readtoken() == TELIF) {
11111 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11112 n2 = n2->nif.elsepart;
11114 n2->nif.test = list(0);
11115 if (readtoken() != TTHEN)
11116 raise_error_unexpected_syntax(TTHEN);
11117 n2->nif.ifpart = list(0);
11119 if (lasttoken == TELSE)
11120 n2->nif.elsepart = list(0);
11122 n2->nif.elsepart = NULL;
11130 n1 = stzalloc(sizeof(struct nbinary));
11131 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11132 n1->nbinary.ch1 = list(0);
11135 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11136 got == TWORD ? wordtext : ""));
11137 raise_error_unexpected_syntax(TDO);
11139 n1->nbinary.ch2 = list(0);
11144 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11145 raise_error_syntax("bad for loop variable");
11146 n1 = stzalloc(sizeof(struct nfor));
11148 n1->nfor.var = wordtext;
11149 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11150 if (readtoken() == TIN) {
11152 while (readtoken() == TWORD) {
11153 n2 = stzalloc(sizeof(struct narg));
11155 /*n2->narg.next = NULL; - stzalloc did it */
11156 n2->narg.text = wordtext;
11157 n2->narg.backquote = backquotelist;
11159 app = &n2->narg.next;
11162 n1->nfor.args = ap;
11163 if (lasttoken != TNL && lasttoken != TSEMI)
11164 raise_error_unexpected_syntax(-1);
11166 n2 = stzalloc(sizeof(struct narg));
11168 /*n2->narg.next = NULL; - stzalloc did it */
11169 n2->narg.text = (char *)dolatstr;
11170 /*n2->narg.backquote = NULL;*/
11171 n1->nfor.args = n2;
11173 * Newline or semicolon here is optional (but note
11174 * that the original Bourne shell only allowed NL).
11176 if (lasttoken != TSEMI)
11179 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11180 if (readtoken() != TDO)
11181 raise_error_unexpected_syntax(TDO);
11182 n1->nfor.body = list(0);
11186 n1 = stzalloc(sizeof(struct ncase));
11188 if (readtoken() != TWORD)
11189 raise_error_unexpected_syntax(TWORD);
11190 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11192 /*n2->narg.next = NULL; - stzalloc did it */
11193 n2->narg.text = wordtext;
11194 n2->narg.backquote = backquotelist;
11195 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11196 if (readtoken() != TIN)
11197 raise_error_unexpected_syntax(TIN);
11198 cpp = &n1->ncase.cases;
11200 checkkwd = CHKNL | CHKKWD;
11202 while (t != TESAC) {
11203 if (lasttoken == TLP)
11205 *cpp = cp = stzalloc(sizeof(struct nclist));
11207 app = &cp->nclist.pattern;
11209 *app = ap = stzalloc(sizeof(struct narg));
11211 /*ap->narg.next = NULL; - stzalloc did it */
11212 ap->narg.text = wordtext;
11213 ap->narg.backquote = backquotelist;
11214 if (readtoken() != TPIPE)
11216 app = &ap->narg.next;
11219 //ap->narg.next = NULL;
11220 if (lasttoken != TRP)
11221 raise_error_unexpected_syntax(TRP);
11222 cp->nclist.body = list(2);
11224 cpp = &cp->nclist.next;
11226 checkkwd = CHKNL | CHKKWD;
11230 raise_error_unexpected_syntax(TENDCASE);
11237 n1 = stzalloc(sizeof(struct nredir));
11238 n1->type = NSUBSHELL;
11239 n1->nredir.n = list(0);
11240 /*n1->nredir.redirect = NULL; - stzalloc did it */
11247 IF_ASH_BASH_COMPAT(case TFUNCTION:)
11251 return simplecmd();
11254 if (readtoken() != t)
11255 raise_error_unexpected_syntax(t);
11258 /* Now check for redirection which may follow command */
11259 checkkwd = CHKKWD | CHKALIAS;
11261 while (readtoken() == TREDIR) {
11262 *rpp = n2 = redirnode;
11263 rpp = &n2->nfile.next;
11269 if (n1->type != NSUBSHELL) {
11270 n2 = stzalloc(sizeof(struct nredir));
11275 n1->nredir.redirect = redir;
11280 #if ENABLE_ASH_BASH_COMPAT
11282 decode_dollar_squote(void)
11284 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11290 p = strchr(C_escapes, c);
11295 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11299 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11301 } else if (c == 'x') { /* \xHH */
11305 } while (isxdigit(c) && --cnt);
11307 if (cnt == 3) { /* \x but next char is "bad" */
11311 } else { /* simple seq like \\ or \t */
11316 c = bb_process_escape_sequence((void*)&p);
11317 } else { /* unrecognized "\z": print both chars unless ' or " */
11318 if (c != '\'' && c != '"') {
11320 c |= 0x100; /* "please encode \, then me" */
11328 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11329 * is not NULL, read a here document. In the latter case, eofmark is the
11330 * word which marks the end of the document and striptabs is true if
11331 * leading tabs should be stripped from the document. The argument c
11332 * is the first character of the input token or document.
11334 * Because C does not have internal subroutines, I have simulated them
11335 * using goto's to implement the subroutine linkage. The following macros
11336 * will run code that appears at the end of readtoken1.
11338 #define CHECKEND() {goto checkend; checkend_return:;}
11339 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11340 #define PARSESUB() {goto parsesub; parsesub_return:;}
11341 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11342 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11343 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11345 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11347 /* NB: syntax parameter fits into smallint */
11348 /* c parameter is an unsigned char or PEOF or PEOA */
11351 char line[EOFMARKLEN + 1];
11352 struct nodelist *bqlist;
11356 smallint prevsyntax; /* syntax before arithmetic */
11357 #if ENABLE_ASH_EXPAND_PRMT
11358 smallint pssyntax; /* we are expanding a prompt string */
11360 int varnest; /* levels of variables expansion */
11361 int arinest; /* levels of arithmetic expansion */
11362 int parenlevel; /* levels of parens in arithmetic */
11363 int dqvarnest; /* levels of variables expansion within double quotes */
11365 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11367 startlinno = g_parsefile->linno;
11371 #if ENABLE_ASH_EXPAND_PRMT
11372 pssyntax = (syntax == PSSYNTAX);
11376 dblquote = (syntax == DQSYNTAX);
11382 STARTSTACKSTR(out);
11384 /* For each line, until end of word */
11385 CHECKEND(); /* set c to PEOF if at end of here document */
11386 for (;;) { /* until end of line or end of word */
11387 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11388 switch (SIT(c, syntax)) {
11389 case CNL: /* '\n' */
11390 if (syntax == BASESYNTAX)
11391 goto endword; /* exit outer loop */
11395 goto loop; /* continue outer loop */
11400 #if ENABLE_ASH_BASH_COMPAT
11401 if (c == '\\' && bash_dollar_squote) {
11402 c = decode_dollar_squote();
11404 /* skip $'\000', $'\x00' (like bash) */
11408 /* Unknown escape. Encode as '\z' */
11409 c = (unsigned char)c;
11410 if (eofmark == NULL || dblquote)
11411 USTPUTC(CTLESC, out);
11412 USTPUTC('\\', out);
11416 if (eofmark == NULL || dblquote)
11417 USTPUTC(CTLESC, out);
11420 case CBACK: /* backslash */
11421 c = pgetc_without_PEOA();
11423 USTPUTC(CTLESC, out);
11424 USTPUTC('\\', out);
11426 } else if (c == '\n') {
11429 #if ENABLE_ASH_EXPAND_PRMT
11430 if (c == '$' && pssyntax) {
11431 USTPUTC(CTLESC, out);
11432 USTPUTC('\\', out);
11435 /* Backslash is retained if we are in "str" and next char isn't special */
11440 && (c != '"' || eofmark != NULL)
11442 USTPUTC('\\', out);
11444 USTPUTC(CTLESC, out);
11452 if (eofmark == NULL) {
11453 USTPUTC(CTLQUOTEMARK, out);
11461 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11462 if (eofmark != NULL && varnest == 0) {
11465 if (dqvarnest == 0) {
11466 syntax = BASESYNTAX;
11473 case CVAR: /* '$' */
11474 PARSESUB(); /* parse substitution */
11476 case CENDVAR: /* '}' */
11479 if (dqvarnest > 0) {
11486 #if ENABLE_SH_MATH_SUPPORT
11487 case CLP: /* '(' in arithmetic */
11491 case CRP: /* ')' in arithmetic */
11492 if (parenlevel > 0) {
11495 if (pgetc_eatbnl() == ')') {
11497 if (--arinest == 0) {
11498 syntax = prevsyntax;
11502 * unbalanced parens
11503 * (don't 2nd guess - no error)
11511 case CBQUOTE: /* '`' */
11515 goto endword; /* exit outer loop */
11519 if (varnest == 0) {
11520 #if ENABLE_ASH_BASH_COMPAT
11522 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11523 if (pgetc() == '>')
11524 c = 0x100 + '>'; /* flag &> */
11528 goto endword; /* exit outer loop */
11530 IF_ASH_ALIAS(if (c != PEOA))
11537 #if ENABLE_SH_MATH_SUPPORT
11538 if (syntax == ARISYNTAX)
11539 raise_error_syntax("missing '))'");
11541 if (syntax != BASESYNTAX && eofmark == NULL)
11542 raise_error_syntax("unterminated quoted string");
11543 if (varnest != 0) {
11544 startlinno = g_parsefile->linno;
11546 raise_error_syntax("missing '}'");
11548 USTPUTC('\0', out);
11549 len = out - (char *)stackblock();
11550 out = stackblock();
11551 if (eofmark == NULL) {
11552 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11555 if (isdigit_str9(out)) {
11556 PARSEREDIR(); /* passed as params: out, c */
11557 lasttoken = TREDIR;
11560 /* else: non-number X seen, interpret it
11561 * as "NNNX>file" = "NNNX >file" */
11565 quoteflag = quotef;
11566 backquotelist = bqlist;
11567 grabstackblock(len);
11571 /* end of readtoken routine */
11574 * Check to see whether we are at the end of the here document. When this
11575 * is called, c is set to the first character of the next input line. If
11576 * we are at the end of the here document, this routine sets the c to PEOF.
11580 #if ENABLE_ASH_ALIAS
11582 c = pgetc_without_PEOA();
11585 while (c == '\t') {
11586 c = pgetc_without_PEOA();
11589 if (c == *eofmark) {
11590 if (pfgets(line, sizeof(line)) != NULL) {
11595 for (q = eofmark + 1;; p++, q++) {
11599 if (!*q || cc != *q)
11606 pushstring(line, NULL);
11611 goto checkend_return;
11615 * Parse a redirection operator. The variable "out" points to a string
11616 * specifying the fd to be redirected. The variable "c" contains the
11617 * first character of the redirection operator.
11620 /* out is already checked to be a valid number or "" */
11621 int fd = (*out == '\0' ? -1 : atoi(out));
11624 np = stzalloc(sizeof(struct nfile));
11629 np->type = NAPPEND;
11631 np->type = NCLOBBER;
11634 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11640 #if ENABLE_ASH_BASH_COMPAT
11641 else if (c == 0x100 + '>') { /* this flags &> redirection */
11643 pgetc(); /* this is '>', no need to check */
11647 else { /* c == '<' */
11648 /*np->nfile.fd = 0; - stzalloc did it */
11652 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11653 np = stzalloc(sizeof(struct nhere));
11654 /*np->nfile.fd = 0; - stzalloc did it */
11657 heredoc = stzalloc(sizeof(struct heredoc));
11658 heredoc->here = np;
11661 heredoc->striptabs = 1;
11663 /*heredoc->striptabs = 0; - stzalloc did it */
11669 np->type = NFROMFD;
11673 np->type = NFROMTO;
11685 goto parseredir_return;
11689 * Parse a substitution. At this point, we have read the dollar sign
11690 * and nothing else.
11693 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11694 * (assuming ascii char codes, as the original implementation did) */
11695 #define is_special(c) \
11696 (((unsigned)(c) - 33 < 32) \
11697 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11699 unsigned char subtype;
11702 c = pgetc_eatbnl();
11703 if (c > 255 /* PEOA or PEOF */
11704 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11706 #if ENABLE_ASH_BASH_COMPAT
11707 if (syntax != DQSYNTAX && c == '\'')
11708 bash_dollar_squote = 1;
11713 } else if (c == '(') {
11714 /* $(command) or $((arith)) */
11715 if (pgetc_eatbnl() == '(') {
11716 #if ENABLE_SH_MATH_SUPPORT
11719 raise_error_syntax("you disabled math support for $((arith)) syntax");
11726 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11727 USTPUTC(CTLVAR, out);
11728 typeloc = out - (char *)stackblock();
11730 subtype = VSNORMAL;
11732 c = pgetc_eatbnl();
11737 /* $[{[#]]NAME[}] */
11740 c = pgetc_eatbnl();
11741 } while (is_in_name(c));
11742 } else if (isdigit(c)) {
11743 /* $[{[#]]NUM[}] */
11746 c = pgetc_eatbnl();
11747 } while (isdigit(c));
11748 } else if (is_special(c)) {
11749 /* $[{[#]]<specialchar>[}] */
11752 c = pgetc_eatbnl();
11753 if (!subtype && cc == '#') {
11754 subtype = VSLENGTH;
11755 if (c == '_' || isalnum(c))
11758 c = pgetc_eatbnl();
11759 if (cc == '}' || c != '}') {
11770 if (c != '}' && subtype == VSLENGTH) {
11771 /* ${#VAR didn't end with } */
11775 if (subtype == 0) {
11776 static const char types[] ALIGN1 = "}-+?=";
11777 /* ${VAR...} but not $VAR or ${#VAR} */
11778 /* c == first char after VAR */
11781 c = pgetc_eatbnl();
11782 #if ENABLE_ASH_BASH_COMPAT
11783 /* This check is only needed to not misinterpret
11784 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11787 if (!strchr(types, c)) {
11788 subtype = VSSUBSTR;
11790 break; /* "goto badsub" is bigger (!) */
11796 const char *p = strchr(types, c);
11799 subtype |= p - types + VSNORMAL;
11805 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11806 c = pgetc_eatbnl();
11812 #if ENABLE_ASH_BASH_COMPAT
11814 /* ${v/[/]pattern/repl} */
11815 //TODO: encode pattern and repl separately.
11816 // Currently ${v/$var_with_slash/repl} is horribly broken
11817 subtype = VSREPLACE;
11818 c = pgetc_eatbnl();
11821 subtype++; /* VSREPLACEALL */
11829 ((unsigned char *)stackblock())[typeloc] = subtype;
11830 if (subtype != VSNORMAL) {
11837 goto parsesub_return;
11841 * Called to parse command substitutions. Newstyle is set if the command
11842 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11843 * list of commands (passed by reference), and savelen is the number of
11844 * characters on the top of the stack which must be preserved.
11847 struct nodelist **nlpp;
11851 smallint saveprompt = 0;
11854 savelen = out - (char *)stackblock();
11857 * FIXME: this can allocate very large block on stack and SEGV.
11859 * echo "..<100kbytes>..`true` $(true) `true` ..."
11860 * allocates 100kb for every command subst. With about
11861 * a hundred command substitutions stack overflows.
11862 * With larger prepended string, SEGV happens sooner.
11864 str = alloca(savelen);
11865 memcpy(str, stackblock(), savelen);
11869 /* We must read until the closing backquote, giving special
11870 * treatment to some slashes, and then push the string and
11871 * reread it as input, interpreting it normally.
11877 STARTSTACKSTR(pout);
11881 setprompt_if(needprompt, 2);
11892 * If eating a newline, avoid putting
11893 * the newline into the new character
11894 * stream (via the STPUTC after the
11899 if (pc != '\\' && pc != '`' && pc != '$'
11900 && (!dblquote || pc != '"')
11902 STPUTC('\\', pout);
11904 if (pc <= 255 /* not PEOA or PEOF */) {
11910 IF_ASH_ALIAS(case PEOA:)
11911 startlinno = g_parsefile->linno;
11912 raise_error_syntax("EOF in backquote substitution");
11924 STPUTC('\0', pout);
11925 psavelen = pout - (char *)stackblock();
11926 if (psavelen > 0) {
11927 pstr = grabstackstr(pout);
11928 setinputstring(pstr);
11933 nlpp = &(*nlpp)->next;
11934 *nlpp = stzalloc(sizeof(**nlpp));
11935 /* (*nlpp)->next = NULL; - stzalloc did it */
11938 saveprompt = doprompt;
11945 doprompt = saveprompt;
11946 else if (readtoken() != TRP)
11947 raise_error_unexpected_syntax(TRP);
11952 * Start reading from old file again, ignoring any pushed back
11953 * tokens left from the backquote parsing
11958 while (stackblocksize() <= savelen)
11960 STARTSTACKSTR(out);
11962 memcpy(out, str, savelen);
11963 STADJUST(savelen, out);
11965 USTPUTC(CTLBACKQ, out);
11967 goto parsebackq_oldreturn;
11968 goto parsebackq_newreturn;
11971 #if ENABLE_SH_MATH_SUPPORT
11973 * Parse an arithmetic expansion (indicate start of one and set state)
11976 if (++arinest == 1) {
11977 prevsyntax = syntax;
11978 syntax = ARISYNTAX;
11980 USTPUTC(CTLARI, out);
11981 goto parsearith_return;
11984 } /* end of readtoken */
11987 * Read the next input token.
11988 * If the token is a word, we set backquotelist to the list of cmds in
11989 * backquotes. We set quoteflag to true if any part of the word was
11991 * If the token is TREDIR, then we set redirnode to a structure containing
11993 * In all cases, the variable startlinno is set to the number of the line
11994 * on which the token starts.
11996 * [Change comment: here documents and internal procedures]
11997 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11998 * word parsing code into a separate routine. In this case, readtoken
11999 * doesn't need to have any internal procedures, but parseword does.
12000 * We could also make parseoperator in essence the main routine, and
12001 * have parseword (readtoken1?) handle both words and redirection.]
12003 #define NEW_xxreadtoken
12004 #ifdef NEW_xxreadtoken
12005 /* singles must be first! */
12006 static const char xxreadtoken_chars[7] ALIGN1 = {
12007 '\n', '(', ')', /* singles */
12008 '&', '|', ';', /* doubles */
12012 #define xxreadtoken_singles 3
12013 #define xxreadtoken_doubles 3
12015 static const char xxreadtoken_tokens[] ALIGN1 = {
12016 TNL, TLP, TRP, /* only single occurrence allowed */
12017 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12018 TEOF, /* corresponds to trailing nul */
12019 TAND, TOR, TENDCASE /* if double occurrence */
12031 setprompt_if(needprompt, 2);
12032 startlinno = g_parsefile->linno;
12033 for (;;) { /* until token or start of word found */
12035 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12039 while ((c = pgetc()) != '\n' && c != PEOF)
12042 } else if (c == '\\') {
12043 if (pgetc() != '\n') {
12045 break; /* return readtoken1(...) */
12051 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12057 p = strchr(xxreadtoken_chars, c);
12059 break; /* return readtoken1(...) */
12061 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12063 if (cc == c) { /* double occurrence? */
12064 p += xxreadtoken_doubles + 1;
12067 #if ENABLE_ASH_BASH_COMPAT
12068 if (c == '&' && cc == '>') /* &> */
12069 break; /* return readtoken1(...) */
12074 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12079 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12081 #else /* old xxreadtoken */
12082 #define RETURN(token) return lasttoken = token
12092 setprompt_if(needprompt, 2);
12093 startlinno = g_parsefile->linno;
12094 for (;;) { /* until token or start of word found */
12097 case ' ': case '\t':
12098 IF_ASH_ALIAS(case PEOA:)
12101 while ((c = pgetc()) != '\n' && c != PEOF)
12106 if (pgetc() == '\n') {
12118 if (pgetc() == '&')
12123 if (pgetc() == '|')
12128 if (pgetc() == ';')
12141 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12144 #endif /* old xxreadtoken */
12150 int kwd = checkkwd;
12152 smallint alreadyseen = tokpushback;
12155 #if ENABLE_ASH_ALIAS
12171 if (t != TWORD || quoteflag) {
12176 * check for keywords
12178 if (kwd & CHKKWD) {
12179 const char *const *pp;
12181 pp = findkwd(wordtext);
12183 lasttoken = t = pp - tokname_array;
12184 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12189 if (checkkwd & CHKALIAS) {
12190 #if ENABLE_ASH_ALIAS
12192 ap = lookupalias(wordtext, 1);
12195 pushstring(ap->val, ap);
12205 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12207 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12223 * Read and parse a command. Returns NODE_EOF on end of file.
12224 * (NULL is a valid parse tree indicating a blank line.)
12226 static union node *
12227 parsecmd(int interact)
12232 doprompt = interact;
12233 setprompt_if(doprompt, doprompt);
12239 * Input any here documents.
12244 struct heredoc *here;
12247 here = heredoclist;
12248 heredoclist = NULL;
12251 setprompt_if(needprompt, 2);
12252 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12253 here->eofmark, here->striptabs);
12254 n = stzalloc(sizeof(struct narg));
12255 n->narg.type = NARG;
12256 /*n->narg.next = NULL; - stzalloc did it */
12257 n->narg.text = wordtext;
12258 n->narg.backquote = backquotelist;
12259 here->here->nhere.doc = n;
12266 * called by editline -- any expansions to the prompt should be added here.
12268 #if ENABLE_ASH_EXPAND_PRMT
12269 static const char *
12270 expandstr(const char *ps)
12275 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12276 * and token processing _can_ alter it (delete NULs etc). */
12277 setinputstring((char *)ps);
12279 saveprompt = doprompt;
12281 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12282 doprompt = saveprompt;
12286 n.narg.type = NARG;
12287 n.narg.next = NULL;
12288 n.narg.text = wordtext;
12289 n.narg.backquote = backquotelist;
12291 expandarg(&n, NULL, EXP_QUOTED);
12292 return stackblock();
12297 * Execute a command or commands contained in a string.
12300 evalstring(char *s, int flags)
12302 struct jmploc *volatile savehandler;
12303 struct jmploc jmploc;
12307 struct stackmark smark;
12312 setstackmark(&smark);
12315 /* On exception inside execution loop, we must popfile().
12316 * Try interactively:
12318 * command eval "a=b" # throws "is read only" error
12319 * "command BLTIN" is not supposed to abort (even in non-interactive use).
12320 * But if we skip popfile(), we hit EOF in eval's string, and exit.
12322 savehandler = exception_handler;
12323 ex = setjmp(jmploc.loc);
12326 exception_handler = &jmploc;
12328 while ((n = parsecmd(0)) != NODE_EOF) {
12331 i = evaltree(n, flags);
12334 popstackmark(&smark);
12339 popstackmark(&smark);
12343 exception_handler = savehandler;
12345 longjmp(exception_handler->loc, ex);
12351 * The eval command.
12353 static int FAST_FUNC
12354 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12363 STARTSTACKSTR(concat);
12365 concat = stack_putstr(p, concat);
12369 STPUTC(' ', concat);
12371 STPUTC('\0', concat);
12372 p = grabstackstr(concat);
12374 return evalstring(p, flags & EV_TESTED);
12380 * Read and execute commands.
12381 * "Top" is nonzero for the top level command loop;
12382 * it turns on prompting if the shell is interactive.
12388 struct stackmark smark;
12393 TRACE(("cmdloop(%d) called\n", top));
12397 setstackmark(&smark);
12400 showjobs(SHOW_CHANGED|SHOW_STDERR);
12403 if (iflag && top) {
12407 n = parsecmd(inter);
12409 if (DEBUG > 2 && debug && (n != NODE_EOF))
12412 if (n == NODE_EOF) {
12413 if (!top || numeof >= 50)
12415 if (!stoppedjobs()) {
12418 out2str("\nUse \"exit\" to leave shell.\n");
12421 } else if (nflag == 0) {
12424 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12427 i = evaltree(n, 0);
12431 popstackmark(&smark);
12435 evalskip &= ~SKIPFUNC;
12443 * Take commands from a file. To be compatible we should do a path
12444 * search for the file, which is necessary to find sub-commands.
12447 find_dot_file(char *name)
12450 const char *path = pathval();
12453 /* don't try this for absolute or relative paths */
12454 if (strchr(name, '/'))
12457 /* IIRC standards do not say whether . is to be searched.
12458 * And it is even smaller this way, making it unconditional for now:
12460 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12465 while ((fullname = path_advance(&path, name)) != NULL) {
12467 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12469 * Don't bother freeing here, since it will
12470 * be freed by the caller.
12474 if (fullname != name)
12475 stunalloc(fullname);
12478 /* not found in the PATH */
12479 ash_msg_and_raise_error("%s: not found", name);
12483 static int FAST_FUNC
12484 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12486 /* "false; . empty_file; echo $?" should print 0, not 1: */
12490 struct strlist *sp;
12491 volatile struct shparam saveparam;
12493 for (sp = cmdenviron; sp; sp = sp->next)
12494 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12496 nextopt(nullstr); /* handle possible "--" */
12500 /* bash says: "bash: .: filename argument required" */
12501 return 2; /* bash compat */
12504 /* This aborts if file isn't found, which is POSIXly correct.
12505 * bash returns exitcode 1 instead.
12507 fullname = find_dot_file(argv[0]);
12509 if (argv[0]) { /* . FILE ARGS, ARGS exist */
12511 saveparam = shellparam;
12512 shellparam.malloced = 0;
12516 shellparam.nparam = argc;
12517 shellparam.p = argv;
12520 /* This aborts if file can't be opened, which is POSIXly correct.
12521 * bash returns exitcode 1 instead.
12523 setinputfile(fullname, INPUT_PUSH_FILE);
12524 commandname = fullname;
12525 status = cmdloop(0);
12529 freeparam(&shellparam);
12530 shellparam = saveparam;
12536 static int FAST_FUNC
12537 exitcmd(int argc UNUSED_PARAM, char **argv)
12542 exitstatus = number(argv[1]);
12543 raise_exception(EXEXIT);
12548 * Read a file containing shell functions.
12551 readcmdfile(char *name)
12553 setinputfile(name, INPUT_PUSH_FILE);
12559 /* ============ find_command inplementation */
12562 * Resolve a command name. If you change this routine, you may have to
12563 * change the shellexec routine as well.
12566 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12568 struct tblentry *cmdp;
12575 struct builtincmd *bcmd;
12577 /* If name contains a slash, don't use PATH or hash table */
12578 if (strchr(name, '/') != NULL) {
12579 entry->u.index = -1;
12580 if (act & DO_ABS) {
12581 while (stat(name, &statb) < 0) {
12583 if (errno == EINTR)
12586 entry->cmdtype = CMDUNKNOWN;
12590 entry->cmdtype = CMDNORMAL;
12594 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12596 updatetbl = (path == pathval());
12599 if (strstr(path, "%builtin") != NULL)
12600 act |= DO_ALTBLTIN;
12603 /* If name is in the table, check answer will be ok */
12604 cmdp = cmdlookup(name, 0);
12605 if (cmdp != NULL) {
12608 switch (cmdp->cmdtype) {
12626 } else if (cmdp->rehash == 0)
12627 /* if not invalidated by cd, we're done */
12631 /* If %builtin not in path, check for builtin next */
12632 bcmd = find_builtin(name);
12634 if (IS_BUILTIN_REGULAR(bcmd))
12635 goto builtin_success;
12636 if (act & DO_ALTPATH) {
12637 if (!(act & DO_ALTBLTIN))
12638 goto builtin_success;
12639 } else if (builtinloc <= 0) {
12640 goto builtin_success;
12644 #if ENABLE_FEATURE_SH_STANDALONE
12646 int applet_no = find_applet_by_name(name);
12647 if (applet_no >= 0) {
12648 entry->cmdtype = CMDNORMAL;
12649 entry->u.index = -2 - applet_no;
12655 /* We have to search path. */
12656 prev = -1; /* where to start */
12657 if (cmdp && cmdp->rehash) { /* doing a rehash */
12658 if (cmdp->cmdtype == CMDBUILTIN)
12661 prev = cmdp->param.index;
12667 while ((fullname = path_advance(&path, name)) != NULL) {
12668 stunalloc(fullname);
12669 /* NB: code below will still use fullname
12670 * despite it being "unallocated" */
12673 if (prefix(pathopt, "builtin")) {
12675 goto builtin_success;
12678 if ((act & DO_NOFUNC)
12679 || !prefix(pathopt, "func")
12680 ) { /* ignore unimplemented options */
12684 /* if rehash, don't redo absolute path names */
12685 if (fullname[0] == '/' && idx <= prev) {
12688 TRACE(("searchexec \"%s\": no change\n", name));
12691 while (stat(fullname, &statb) < 0) {
12693 if (errno == EINTR)
12696 if (errno != ENOENT && errno != ENOTDIR)
12700 e = EACCES; /* if we fail, this will be the error */
12701 if (!S_ISREG(statb.st_mode))
12703 if (pathopt) { /* this is a %func directory */
12704 stalloc(strlen(fullname) + 1);
12705 /* NB: stalloc will return space pointed by fullname
12706 * (because we don't have any intervening allocations
12707 * between stunalloc above and this stalloc) */
12708 readcmdfile(fullname);
12709 cmdp = cmdlookup(name, 0);
12710 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12711 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12712 stunalloc(fullname);
12715 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12717 entry->cmdtype = CMDNORMAL;
12718 entry->u.index = idx;
12722 cmdp = cmdlookup(name, 1);
12723 cmdp->cmdtype = CMDNORMAL;
12724 cmdp->param.index = idx;
12729 /* We failed. If there was an entry for this command, delete it */
12730 if (cmdp && updatetbl)
12731 delete_cmd_entry();
12733 ash_msg("%s: %s", name, errmsg(e, "not found"));
12734 entry->cmdtype = CMDUNKNOWN;
12739 entry->cmdtype = CMDBUILTIN;
12740 entry->u.cmd = bcmd;
12744 cmdp = cmdlookup(name, 1);
12745 cmdp->cmdtype = CMDBUILTIN;
12746 cmdp->param.cmd = bcmd;
12750 entry->cmdtype = cmdp->cmdtype;
12751 entry->u = cmdp->param;
12756 * The trap builtin.
12758 static int FAST_FUNC
12759 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12763 int signo, exitcode;
12768 for (signo = 0; signo < NSIG; signo++) {
12769 char *tr = trap_ptr[signo];
12771 /* note: bash adds "SIG", but only if invoked
12772 * as "bash". If called as "sh", or if set -o posix,
12773 * then it prints short signal names.
12774 * We are printing short names: */
12775 out1fmt("trap -- %s %s\n",
12777 get_signame(signo));
12778 /* trap_ptr != trap only if we are in special-cased `trap` code.
12779 * In this case, we will exit very soon, no need to free(). */
12780 /* if (trap_ptr != trap && tp[0]) */
12785 if (trap_ptr != trap) {
12798 signo = get_signum(*ap);
12800 /* Mimic bash message exactly */
12801 ash_msg("%s: invalid signal specification", *ap);
12807 if (LONE_DASH(action))
12810 if (action[0]) /* not NULL and not "" and not "-" */
12811 may_have_traps = 1;
12812 action = ckstrdup(action);
12816 trap[signo] = action;
12827 /* ============ Builtins */
12829 #if ENABLE_ASH_HELP
12830 static int FAST_FUNC
12831 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12837 "Built-in commands:\n"
12838 "------------------\n");
12839 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12840 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12841 builtintab[i].name + 1);
12847 # if ENABLE_FEATURE_SH_STANDALONE
12849 const char *a = applet_names;
12851 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12856 while (*a++ != '\0')
12861 newline_and_flush(stdout);
12862 return EXIT_SUCCESS;
12867 static int FAST_FUNC
12868 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12870 show_history(line_input_state);
12871 return EXIT_SUCCESS;
12876 * The export and readonly commands.
12878 static int FAST_FUNC
12879 exportcmd(int argc UNUSED_PARAM, char **argv)
12889 /* "readonly" in bash accepts, but ignores -n.
12890 * We do the same: it saves a conditional in nextopt's param.
12893 while ((opt = nextopt("np")) != '\0') {
12895 flag_off = VEXPORT;
12898 if (argv[0][0] == 'r') {
12900 flag_off = 0; /* readonly ignores -n */
12902 flag_off = ~flag_off;
12904 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12910 p = strchr(name, '=');
12914 vp = *findvar(hashvar(name), name);
12916 vp->flags = ((vp->flags | flag) & flag_off);
12920 setvar(name, p, (flag & flag_off));
12921 } while ((name = *++aptr) != NULL);
12926 /* No arguments. Show the list of exported or readonly vars.
12929 showvars(argv[0], flag, 0);
12934 * Delete a function if it exists.
12937 unsetfunc(const char *name)
12939 struct tblentry *cmdp;
12941 cmdp = cmdlookup(name, 0);
12942 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12943 delete_cmd_entry();
12947 * The unset builtin command. We unset the function before we unset the
12948 * variable to allow a function to be unset when there is a readonly variable
12949 * with the same name.
12951 static int FAST_FUNC
12952 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12959 while ((i = nextopt("vf")) != 0) {
12963 for (ap = argptr; *ap; ap++) {
12976 static const unsigned char timescmd_str[] ALIGN1 = {
12977 ' ', offsetof(struct tms, tms_utime),
12978 '\n', offsetof(struct tms, tms_stime),
12979 ' ', offsetof(struct tms, tms_cutime),
12980 '\n', offsetof(struct tms, tms_cstime),
12983 static int FAST_FUNC
12984 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12986 unsigned long clk_tck, s, t;
12987 const unsigned char *p;
12990 clk_tck = bb_clk_tck();
12995 t = *(clock_t *)(((char *) &buf) + p[1]);
12998 out1fmt("%lum%lu.%03lus%c",
13000 (t * 1000) / clk_tck,
13008 #if ENABLE_SH_MATH_SUPPORT
13010 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13011 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13013 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13015 static int FAST_FUNC
13016 letcmd(int argc UNUSED_PARAM, char **argv)
13022 ash_msg_and_raise_error("expression expected");
13024 i = ash_arith(*argv);
13032 * The read builtin. Options:
13033 * -r Do not interpret '\' specially
13034 * -s Turn off echo (tty only)
13035 * -n NCHARS Read NCHARS max
13036 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13037 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13038 * -u FD Read from given FD instead of fd 0
13039 * This uses unbuffered input, which may be avoidable in some cases.
13040 * TODO: bash also has:
13041 * -a ARRAY Read into array[0],[1],etc
13042 * -d DELIM End on DELIM char, not newline
13043 * -e Use line editing (tty only)
13045 static int FAST_FUNC
13046 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13048 char *opt_n = NULL;
13049 char *opt_p = NULL;
13050 char *opt_t = NULL;
13051 char *opt_u = NULL;
13052 int read_flags = 0;
13056 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13065 read_flags |= BUILTIN_READ_SILENT;
13071 read_flags |= BUILTIN_READ_RAW;
13081 /* "read -s" needs to save/restore termios, can't allow ^C
13082 * to jump out of it.
13085 r = shell_builtin_read(setvar0,
13087 bltinlookup("IFS"), /* can be NULL */
13096 if ((uintptr_t)r > 1)
13097 ash_msg_and_raise_error(r);
13099 return (uintptr_t)r;
13102 static int FAST_FUNC
13103 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13105 static const char permuser[3] ALIGN1 = "ogu";
13108 int symbolic_mode = 0;
13110 while (nextopt("S") != '\0') {
13119 if (*argptr == NULL) {
13120 if (symbolic_mode) {
13121 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13128 *p++ = permuser[i];
13130 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13131 if (!(mask & 0400)) *p++ = 'r';
13132 if (!(mask & 0200)) *p++ = 'w';
13133 if (!(mask & 0100)) *p++ = 'x';
13141 out1fmt("%04o\n", mask);
13144 char *modestr = *argptr;
13145 /* numeric umasks are taken as-is */
13146 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13147 if (!isdigit(modestr[0]))
13149 mask = bb_parse_mode(modestr, mask);
13150 if ((unsigned)mask > 0777) {
13151 ash_msg_and_raise_error("illegal mode: %s", modestr);
13153 if (!isdigit(modestr[0]))
13160 static int FAST_FUNC
13161 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13163 return shell_builtin_ulimit(argv);
13166 /* ============ main() and helpers */
13169 * Called to exit the shell.
13178 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13179 save_history(line_input_state);
13181 status = exitstatus;
13182 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13183 if (setjmp(loc.loc)) {
13184 if (exception_type == EXEXIT)
13185 status = exitstatus;
13188 exception_handler = &loc;
13194 /*free(p); - we'll exit soon */
13197 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13198 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13201 flush_stdout_stderr();
13209 /* we will never free this */
13210 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13212 sigmode[SIGCHLD - 1] = S_DFL;
13213 setsignal(SIGCHLD);
13215 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13216 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13218 signal(SIGHUP, SIG_DFL);
13223 struct stat st1, st2;
13226 for (envp = environ; envp && *envp; envp++) {
13227 p = endofname(*envp);
13228 if (p != *envp && *p == '=') {
13229 setvareq(*envp, VEXPORT|VTEXTFIXED);
13233 setvareq((char*)defoptindvar, VTEXTFIXED);
13235 setvar0("PPID", utoa(getppid()));
13236 #if ENABLE_ASH_BASH_COMPAT
13237 p = lookupvar("SHLVL");
13238 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13239 if (!lookupvar("HOSTNAME")) {
13240 struct utsname uts;
13242 setvar0("HOSTNAME", uts.nodename);
13245 p = lookupvar("PWD");
13247 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13248 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13258 //usage:#define ash_trivial_usage
13259 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13260 //usage:#define ash_full_usage "\n\n"
13261 //usage: "Unix shell interpreter"
13263 //usage:#if ENABLE_FEATURE_SH_IS_ASH
13264 //usage:# define sh_trivial_usage ash_trivial_usage
13265 //usage:# define sh_full_usage ash_full_usage
13267 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
13268 //usage:# define bash_trivial_usage ash_trivial_usage
13269 //usage:# define bash_full_usage ash_full_usage
13273 * Process the shell command line arguments.
13276 procargs(char **argv)
13279 const char *xminusc;
13284 /* if (xargv[0]) - mmm, this is always true! */
13286 for (i = 0; i < NOPTS; i++)
13289 if (options(/*cmdline:*/ 1)) {
13290 /* it already printed err message */
13291 raise_exception(EXERROR);
13295 if (*xargv == NULL) {
13297 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13300 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13304 for (i = 0; i < NOPTS; i++)
13305 if (optlist[i] == 2)
13310 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13315 } else if (!sflag) {
13316 setinputfile(*xargv, 0);
13319 commandname = arg0;
13322 shellparam.p = xargv;
13323 #if ENABLE_ASH_GETOPTS
13324 shellparam.optind = 1;
13325 shellparam.optoff = -1;
13327 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13329 shellparam.nparam++;
13336 * Read /etc/profile, ~/.profile, $ENV.
13339 read_profile(const char *name)
13341 name = expandstr(name);
13342 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13349 * This routine is called when an error or an interrupt occurs in an
13350 * interactive shell and control is returned to the main command loop.
13351 * (In dash, this function is auto-generated by build machinery).
13360 /* from expand.c: */
13363 /* from input.c: */
13364 g_parsefile->left_in_buffer = 0;
13365 g_parsefile->left_in_line = 0; /* clear input buffer */
13368 /* from redir.c: */
13370 popredir(/*drop:*/ 0, /*restore:*/ 0);
13374 static short profile_buf[16384];
13375 extern int etext();
13379 * Main routine. We initialize things, parse the arguments, execute
13380 * profiles if we're a login shell, and then call cmdloop to execute
13381 * commands. The setjmp call sets up the location to jump to when an
13382 * exception occurs. When an exception occurs the variable "state"
13383 * is used to figure out how far we had gotten.
13385 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13386 int ash_main(int argc UNUSED_PARAM, char **argv)
13388 volatile smallint state;
13389 struct jmploc jmploc;
13390 struct stackmark smark;
13392 /* Initialize global data */
13396 #if ENABLE_ASH_ALIAS
13402 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13405 #if ENABLE_FEATURE_EDITING
13406 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13409 if (setjmp(jmploc.loc)) {
13415 e = exception_type;
13417 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13421 newline_and_flush(stderr);
13424 popstackmark(&smark);
13425 FORCE_INT_ON; /* enable interrupts */
13434 exception_handler = &jmploc;
13435 rootpid = getpid();
13438 setstackmark(&smark);
13441 TRACE(("Shell args: "));
13442 trace_puts_args(argv);
13445 if (argv[0] && argv[0][0] == '-')
13451 read_profile("/etc/profile");
13454 hp = lookupvar("HOME");
13456 read_profile("$HOME/.profile");
13462 getuid() == geteuid() && getgid() == getegid() &&
13466 const char *shinit = lookupvar("ENV");
13467 if (shinit != NULL && *shinit != '\0')
13468 read_profile(shinit);
13470 popstackmark(&smark);
13474 /* evalstring pushes parsefile stack.
13475 * Ensure we don't falsely claim that 0 (stdin)
13476 * is one of stacked source fds.
13477 * Testcase: ash -c 'exec 1>&0' must not complain. */
13478 // if (!sflag) g_parsefile->pf_fd = -1;
13479 // ^^ not necessary since now we special-case fd 0
13480 // in is_hidden_fd() to not be considered "hidden fd"
13481 evalstring(minusc, 0);
13484 if (sflag || minusc == NULL) {
13485 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13487 const char *hp = lookupvar("HISTFILE");
13489 hp = lookupvar("HOME");
13491 hp = concat_path_file(hp, ".ash_history");
13492 setvar0("HISTFILE", hp);
13494 hp = lookupvar("HISTFILE");
13498 line_input_state->hist_file = hp;
13499 # if ENABLE_FEATURE_SH_HISTFILESIZE
13500 hp = lookupvar("HISTFILESIZE");
13501 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13505 state4: /* XXX ??? - why isn't this before the "if" statement */
13513 extern void _mcleanup(void);
13517 TRACE(("End of main reached\n"));
13524 * Copyright (c) 1989, 1991, 1993, 1994
13525 * The Regents of the University of California. All rights reserved.
13527 * This code is derived from software contributed to Berkeley by
13528 * Kenneth Almquist.
13530 * Redistribution and use in source and binary forms, with or without
13531 * modification, are permitted provided that the following conditions
13533 * 1. Redistributions of source code must retain the above copyright
13534 * notice, this list of conditions and the following disclaimer.
13535 * 2. Redistributions in binary form must reproduce the above copyright
13536 * notice, this list of conditions and the following disclaimer in the
13537 * documentation and/or other materials provided with the distribution.
13538 * 3. Neither the name of the University nor the names of its contributors
13539 * may be used to endorse or promote products derived from this software
13540 * without specific prior written permission.
13542 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13543 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13544 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13545 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13546 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13547 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13548 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13549 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13550 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13551 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF