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)
3936 /* Poll all children for changes in their state */
3938 /* if job control is active, accept stopped processes too */
3939 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
3941 break; /* Error (e.g. EINTR, ECHILD) or pid */
3943 /* Children exist, but none are ready. Sleep until interesting signal */
3944 #if 0 /* dash does this */
3947 sigprocmask(SIG_SETMASK, &mask, &mask);
3948 while (!got_sigchld && !pending_sig)
3950 sigprocmask(SIG_SETMASK, &mask, NULL);
3952 while (!got_sigchld && !pending_sig)
3956 /* If it was SIGCHLD, poll children again */
3957 } while (got_sigchld);
3962 #define DOWAIT_NONBLOCK 0
3963 #define DOWAIT_BLOCK 1
3964 #define DOWAIT_BLOCK_OR_SIG 2
3967 dowait(int block, struct job *job)
3972 struct job *thisjob = NULL;
3974 TRACE(("dowait(0x%x) called\n", block));
3976 /* It's wrong to call waitpid() outside of INT_OFF region:
3977 * signal can arrive just after syscall return and handler can
3978 * longjmp away, losing stop/exit notification processing.
3979 * Thus, for "jobs" builtin, and for waiting for a fg job,
3980 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
3982 * However, for "wait" builtin it is wrong to simply call waitpid()
3983 * in INT_OFF region: "wait" needs to wait for any running job
3984 * to change state, but should exit on any trap too.
3985 * In INT_OFF region, a signal just before syscall entry can set
3986 * pending_sig variables, but we can't check them, and we would
3987 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
3989 * Because of this, we run inside INT_OFF, but use a special routine
3990 * which combines waitpid() and pause().
3991 * This is the reason why we need to have a handler for SIGCHLD:
3992 * SIG_DFL handler does not wake pause().
3995 if (block == DOWAIT_BLOCK_OR_SIG) {
3996 pid = wait_block_or_sig(&status);
3999 if (block == DOWAIT_NONBLOCK)
4000 wait_flags = WNOHANG;
4001 /* if job control is active, accept stopped processes too */
4003 wait_flags |= WUNTRACED;
4004 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4005 pid = waitpid(-1, &status, wait_flags);
4007 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4008 pid, status, errno, strerror(errno)));
4013 for (jp = curjob; jp; jp = jp->prev_job) {
4015 struct procstat *ps;
4016 struct procstat *psend;
4017 if (jp->state == JOBDONE)
4021 psend = ps + jp->nprocs;
4023 if (ps->ps_pid == pid) {
4024 TRACE(("Job %d: changing status of proc %d "
4025 "from 0x%x to 0x%x\n",
4026 jobno(jp), pid, ps->ps_status, status));
4027 ps->ps_status = status;
4030 if (ps->ps_status == -1)
4031 jobstate = JOBRUNNING;
4033 if (jobstate == JOBRUNNING)
4035 if (WIFSTOPPED(ps->ps_status)) {
4036 jp->stopstatus = ps->ps_status;
4037 jobstate = JOBSTOPPED;
4040 } while (++ps < psend);
4044 /* Found the job where one of its processes changed its state.
4045 * Is there at least one live and running process in this job? */
4046 if (jobstate != JOBRUNNING) {
4047 /* No. All live processes in the job are stopped
4048 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4050 thisjob->changed = 1;
4051 if (thisjob->state != jobstate) {
4052 TRACE(("Job %d: changing state from %d to %d\n",
4053 jobno(thisjob), thisjob->state, jobstate));
4054 thisjob->state = jobstate;
4056 if (jobstate == JOBSTOPPED)
4057 set_curjob(thisjob, CUR_STOPPED);
4063 /* The process wasn't found in job list */
4064 if (JOBS && !WIFSTOPPED(status))
4069 if (thisjob && thisjob == job) {
4073 len = sprint_status48(s, status, 1);
4085 showjob(struct job *jp, int mode)
4087 struct procstat *ps;
4088 struct procstat *psend;
4091 char s[16 + 16 + 48];
4092 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4096 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4097 /* just output process (group) id of pipeline */
4098 fprintf(out, "%d\n", ps->ps_pid);
4102 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4107 else if (curjob && jp == curjob->prev_job)
4110 if (mode & SHOW_PIDS)
4111 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4113 psend = ps + jp->nprocs;
4115 if (jp->state == JOBRUNNING) {
4116 strcpy(s + col, "Running");
4117 col += sizeof("Running") - 1;
4119 int status = psend[-1].ps_status;
4120 if (jp->state == JOBSTOPPED)
4121 status = jp->stopstatus;
4122 col += sprint_status48(s + col, status, 0);
4124 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4126 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4127 * or prints several "PID | <cmdN>" lines,
4128 * depending on SHOW_PIDS bit.
4129 * We do not print status of individual processes
4130 * between PID and <cmdN>. bash does it, but not very well:
4131 * first line shows overall job status, not process status,
4132 * making it impossible to know 1st process status.
4136 /* for each process */
4139 if (mode & SHOW_PIDS)
4140 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4142 fprintf(out, "%s%*c%s%s",
4144 33 - col >= 0 ? 33 - col : 0, ' ',
4145 ps == jp->ps ? "" : "| ",
4148 } while (++ps != psend);
4149 newline_and_flush(out);
4153 if (jp->state == JOBDONE) {
4154 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4160 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4161 * statuses have changed since the last call to showjobs.
4168 TRACE(("showjobs(0x%x) called\n", mode));
4170 /* Handle all finished jobs */
4171 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4174 for (jp = curjob; jp; jp = jp->prev_job) {
4175 if (!(mode & SHOW_CHANGED) || jp->changed) {
4181 static int FAST_FUNC
4182 jobscmd(int argc UNUSED_PARAM, char **argv)
4187 while ((m = nextopt("lp")) != '\0') {
4191 mode |= SHOW_ONLY_PGID;
4197 showjob(getjob(*argv, 0), mode);
4207 /* Called only on finished or stopped jobs (no members are running) */
4209 getstatus(struct job *job)
4213 struct procstat *ps;
4215 /* Fetch last member's status */
4216 ps = job->ps + job->nprocs - 1;
4217 status = ps->ps_status;
4219 /* "set -o pipefail" mode: use last _nonzero_ status */
4220 while (status == 0 && --ps >= job->ps)
4221 status = ps->ps_status;
4224 retval = WEXITSTATUS(status);
4225 if (!WIFEXITED(status)) {
4227 retval = WSTOPSIG(status);
4228 if (!WIFSTOPPED(status))
4231 /* XXX: limits number of signals */
4232 retval = WTERMSIG(status);
4234 if (retval == SIGINT)
4240 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4241 jobno(job), job->nprocs, status, retval));
4245 static int FAST_FUNC
4246 waitcmd(int argc UNUSED_PARAM, char **argv)
4257 /* wait for all jobs */
4261 if (!jp) /* no running procs */
4263 if (jp->state == JOBRUNNING)
4269 * "When bash is waiting for an asynchronous command via
4270 * the wait builtin, the reception of a signal for which a trap
4271 * has been set will cause the wait builtin to return immediately
4272 * with an exit status greater than 128, immediately after which
4273 * the trap is executed."
4275 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4276 /* if child sends us a signal *and immediately exits*,
4277 * dowait() returns pid > 0. Check this case,
4278 * not "if (dowait() < 0)"!
4287 if (**argv != '%') {
4288 pid_t pid = number(*argv);
4293 if (job->ps[job->nprocs - 1].ps_pid == pid)
4295 job = job->prev_job;
4298 job = getjob(*argv, 0);
4300 /* loop until process terminated or stopped */
4301 while (job->state == JOBRUNNING) {
4302 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4307 retval = getstatus(job);
4314 retval = 128 + pending_sig;
4323 struct job *jp, *jq;
4325 len = njobs * sizeof(*jp);
4327 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4329 offset = (char *)jp - (char *)jq;
4331 /* Relocate pointers */
4334 jq = (struct job *)((char *)jq + l);
4338 #define joff(p) ((struct job *)((char *)(p) + l))
4339 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4340 if (joff(jp)->ps == &jq->ps0)
4341 jmove(joff(jp)->ps);
4342 if (joff(jp)->prev_job)
4343 jmove(joff(jp)->prev_job);
4353 jp = (struct job *)((char *)jp + len);
4357 } while (--jq >= jp);
4362 * Return a new job structure.
4363 * Called with interrupts off.
4366 makejob(/*union node *node,*/ int nprocs)
4371 for (i = njobs, jp = jobtab; ; jp++) {
4378 if (jp->state != JOBDONE || !jp->waited)
4387 memset(jp, 0, sizeof(*jp));
4389 /* jp->jobctl is a bitfield.
4390 * "jp->jobctl |= jobctl" likely to give awful code */
4394 jp->prev_job = curjob;
4399 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4401 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4408 * Return a string identifying a command (to be printed by the
4411 static char *cmdnextc;
4414 cmdputs(const char *s)
4416 static const char vstype[VSTYPE + 1][3] = {
4417 "", "}", "-", "+", "?", "=",
4418 "%", "%%", "#", "##"
4419 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4422 const char *p, *str;
4426 unsigned char subtype = 0;
4430 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4432 while ((c = *p++) != '\0') {
4440 if ((subtype & VSTYPE) == VSLENGTH)
4446 str = "\"}" + !(quoted & 1);
4453 #if ENABLE_SH_MATH_SUPPORT
4468 if ((subtype & VSTYPE) != VSNORMAL)
4470 str = vstype[subtype & VSTYPE];
4471 if (subtype & VSNUL)
4480 /* These can only happen inside quotes */
4493 while ((c = *str++) != '\0') {
4496 } /* while *p++ not NUL */
4499 USTPUTC('"', nextc);
4505 /* cmdtxt() and cmdlist() call each other */
4506 static void cmdtxt(union node *n);
4509 cmdlist(union node *np, int sep)
4511 for (; np; np = np->narg.next) {
4515 if (sep && np->narg.next)
4521 cmdtxt(union node *n)
4524 struct nodelist *lp;
4535 lp = n->npipe.cmdlist;
4553 cmdtxt(n->nbinary.ch1);
4569 cmdtxt(n->nif.test);
4571 if (n->nif.elsepart) {
4572 cmdtxt(n->nif.ifpart);
4574 n = n->nif.elsepart;
4592 cmdtxt(n->nbinary.ch1);
4602 cmdputs(n->nfor.var);
4604 cmdlist(n->nfor.args, 1);
4609 cmdputs(n->narg.text);
4613 cmdlist(n->ncmd.args, 1);
4614 cmdlist(n->ncmd.redirect, 0);
4627 cmdputs(n->ncase.expr->narg.text);
4629 for (np = n->ncase.cases; np; np = np->nclist.next) {
4630 cmdtxt(np->nclist.pattern);
4632 cmdtxt(np->nclist.body);
4646 #if ENABLE_ASH_BASH_COMPAT
4661 cmdputs(utoa(n->nfile.fd));
4663 if (n->type == NTOFD || n->type == NFROMFD) {
4664 cmdputs(utoa(n->ndup.dupfd));
4673 commandtext(union node *n)
4677 STARTSTACKSTR(cmdnextc);
4679 name = stackblock();
4680 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4681 return ckstrdup(name);
4686 * Fork off a subshell. If we are doing job control, give the subshell its
4687 * own process group. Jp is a job structure that the job is to be added to.
4688 * N is the command that will be evaluated by the child. Both jp and n may
4689 * be NULL. The mode parameter can be one of the following:
4690 * FORK_FG - Fork off a foreground process.
4691 * FORK_BG - Fork off a background process.
4692 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4693 * process group even if job control is on.
4695 * When job control is turned off, background processes have their standard
4696 * input redirected to /dev/null (except for the second and later processes
4699 * Called with interrupts off.
4702 * Clear traps on a fork.
4710 for (tp = trap; tp < &trap[NSIG]; tp++) {
4711 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4712 if (trap_ptr == trap)
4714 /* else: it "belongs" to trap_ptr vector, don't free */
4716 if ((tp - trap) != 0)
4717 setsignal(tp - trap);
4724 /* Lives far away from here, needed for forkchild */
4725 static void closescript(void);
4727 /* Called after fork(), in child */
4728 /* jp and n are NULL when called by openhere() for heredoc support */
4729 static NOINLINE void
4730 forkchild(struct job *jp, union node *n, int mode)
4734 TRACE(("Child shell %d\n", getpid()));
4738 /* man bash: "Non-builtin commands run by bash have signal handlers
4739 * set to the values inherited by the shell from its parent".
4740 * Do we do it correctly? */
4744 if (mode == FORK_NOJOB /* is it `xxx` ? */
4745 && n && n->type == NCMD /* is it single cmd? */
4746 /* && n->ncmd.args->type == NARG - always true? */
4747 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4748 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4749 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4751 TRACE(("Trap hack\n"));
4752 /* Awful hack for `trap` or $(trap).
4754 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4755 * contains an example where "trap" is executed in a subshell:
4757 * save_traps=$(trap)
4759 * eval "$save_traps"
4761 * Standard does not say that "trap" in subshell shall print
4762 * parent shell's traps. It only says that its output
4763 * must have suitable form, but then, in the above example
4764 * (which is not supposed to be normative), it implies that.
4766 * bash (and probably other shell) does implement it
4767 * (traps are reset to defaults, but "trap" still shows them),
4768 * but as a result, "trap" logic is hopelessly messed up:
4771 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4772 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4773 * # true | trap <--- trap is in subshell - no output (ditto)
4774 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4775 * trap -- 'echo Ho' SIGWINCH
4776 * # echo `(trap)` <--- in subshell in subshell - output
4777 * trap -- 'echo Ho' SIGWINCH
4778 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4779 * trap -- 'echo Ho' SIGWINCH
4781 * The rules when to forget and when to not forget traps
4782 * get really complex and nonsensical.
4784 * Our solution: ONLY bare $(trap) or `trap` is special.
4786 /* Save trap handler strings for trap builtin to print */
4787 trap_ptr = xmemdup(trap, sizeof(trap));
4788 /* Fall through into clearing traps */
4792 /* do job control only in root shell */
4794 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4797 if (jp->nprocs == 0)
4800 pgrp = jp->ps[0].ps_pid;
4801 /* this can fail because we are doing it in the parent also */
4803 if (mode == FORK_FG)
4804 xtcsetpgrp(ttyfd, pgrp);
4809 if (mode == FORK_BG) {
4810 /* man bash: "When job control is not in effect,
4811 * asynchronous commands ignore SIGINT and SIGQUIT" */
4814 if (jp->nprocs == 0) {
4816 if (open(bb_dev_null, O_RDONLY) != 0)
4817 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4821 if (iflag) { /* why if iflag only? */
4826 * "In all cases, bash ignores SIGQUIT. Non-builtin
4827 * commands run by bash have signal handlers
4828 * set to the values inherited by the shell
4830 * Take care of the second rule: */
4834 if (n && n->type == NCMD
4835 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4837 TRACE(("Job hack\n"));
4838 /* "jobs": we do not want to clear job list for it,
4839 * instead we remove only _its_ own_ job from job list.
4840 * This makes "jobs .... | cat" more useful.
4846 for (jp = curjob; jp; jp = jp->prev_job)
4851 /* Called after fork(), in parent */
4853 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4856 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4858 TRACE(("In parent shell: child = %d\n", pid));
4860 /* jp is NULL when called by openhere() for heredoc support */
4861 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4867 if (mode != FORK_NOJOB && jp->jobctl) {
4870 if (jp->nprocs == 0)
4873 pgrp = jp->ps[0].ps_pid;
4874 /* This can fail because we are doing it in the child also */
4878 if (mode == FORK_BG) {
4879 backgndpid = pid; /* set $! */
4880 set_curjob(jp, CUR_RUNNING);
4883 struct procstat *ps = &jp->ps[jp->nprocs++];
4886 ps->ps_cmd = nullstr;
4888 if (doing_jobctl && n)
4889 ps->ps_cmd = commandtext(n);
4894 /* jp and n are NULL when called by openhere() for heredoc support */
4896 forkshell(struct job *jp, union node *n, int mode)
4900 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4903 TRACE(("Fork failed, errno=%d", errno));
4906 ash_msg_and_raise_error("can't fork");
4909 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4910 forkchild(jp, n, mode);
4912 forkparent(jp, n, mode, pid);
4918 * Wait for job to finish.
4920 * Under job control we have the problem that while a child process
4921 * is running interrupts generated by the user are sent to the child
4922 * but not to the shell. This means that an infinite loop started by
4923 * an interactive user may be hard to kill. With job control turned off,
4924 * an interactive user may place an interactive program inside a loop.
4925 * If the interactive program catches interrupts, the user doesn't want
4926 * these interrupts to also abort the loop. The approach we take here
4927 * is to have the shell ignore interrupt signals while waiting for a
4928 * foreground process to terminate, and then send itself an interrupt
4929 * signal if the child process was terminated by an interrupt signal.
4930 * Unfortunately, some programs want to do a bit of cleanup and then
4931 * exit on interrupt; unless these processes terminate themselves by
4932 * sending a signal to themselves (instead of calling exit) they will
4933 * confuse this approach.
4935 * Called with interrupts off.
4938 waitforjob(struct job *jp)
4942 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4945 while (jp->state == JOBRUNNING) {
4946 /* In non-interactive shells, we _can_ get
4947 * a keyboard signal here and be EINTRed,
4948 * but we just loop back, waiting for command to complete.
4951 * "If bash is waiting for a command to complete and receives
4952 * a signal for which a trap has been set, the trap
4953 * will not be executed until the command completes."
4955 * Reality is that even if trap is not set, bash
4956 * will not act on the signal until command completes.
4957 * Try this. sleep5intoff.c:
4958 * #include <signal.h>
4959 * #include <unistd.h>
4962 * sigemptyset(&set);
4963 * sigaddset(&set, SIGINT);
4964 * sigaddset(&set, SIGQUIT);
4965 * sigprocmask(SIG_BLOCK, &set, NULL);
4969 * $ bash -c './sleep5intoff; echo hi'
4970 * ^C^C^C^C <--- pressing ^C once a second
4972 * $ bash -c './sleep5intoff; echo hi'
4973 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4976 dowait(DOWAIT_BLOCK, jp);
4983 xtcsetpgrp(ttyfd, rootpid);
4985 * This is truly gross.
4986 * If we're doing job control, then we did a TIOCSPGRP which
4987 * caused us (the shell) to no longer be in the controlling
4988 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4989 * intuit from the subprocess exit status whether a SIGINT
4990 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4992 if (jp->sigint) /* TODO: do the same with all signals */
4993 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4995 if (jp->state == JOBDONE)
5002 * return 1 if there are stopped jobs, otherwise 0
5014 if (jp && jp->state == JOBSTOPPED) {
5015 out2str("You have stopped jobs.\n");
5025 * Code for dealing with input/output redirection.
5030 #define EMPTY -2 /* marks an unused slot in redirtab */
5031 #define CLOSED -3 /* marks a slot of previously-closed fd */
5034 * Open a file in noclobber mode.
5035 * The code was copied from bash.
5038 noclobberopen(const char *fname)
5041 struct stat finfo, finfo2;
5044 * If the file exists and is a regular file, return an error
5047 r = stat(fname, &finfo);
5048 if (r == 0 && S_ISREG(finfo.st_mode)) {
5054 * If the file was not present (r != 0), make sure we open it
5055 * exclusively so that if it is created before we open it, our open
5056 * will fail. Make sure that we do not truncate an existing file.
5057 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5058 * file was not a regular file, we leave O_EXCL off.
5061 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5062 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5064 /* If the open failed, return the file descriptor right away. */
5069 * OK, the open succeeded, but the file may have been changed from a
5070 * non-regular file to a regular file between the stat and the open.
5071 * We are assuming that the O_EXCL open handles the case where FILENAME
5072 * did not exist and is symlinked to an existing file between the stat
5077 * If we can open it and fstat the file descriptor, and neither check
5078 * revealed that it was a regular file, and the file has not been
5079 * replaced, return the file descriptor.
5081 if (fstat(fd, &finfo2) == 0
5082 && !S_ISREG(finfo2.st_mode)
5083 && finfo.st_dev == finfo2.st_dev
5084 && finfo.st_ino == finfo2.st_ino
5089 /* The file has been replaced. badness. */
5096 * Handle here documents. Normally we fork off a process to write the
5097 * data to a pipe. If the document is short, we can stuff the data in
5098 * the pipe without forking.
5100 /* openhere needs this forward reference */
5101 static void expandhere(union node *arg, int fd);
5103 openhere(union node *redir)
5109 ash_msg_and_raise_error("pipe call failed");
5110 if (redir->type == NHERE) {
5111 len = strlen(redir->nhere.doc->narg.text);
5112 if (len <= PIPE_BUF) {
5113 full_write(pip[1], redir->nhere.doc->narg.text, len);
5117 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5120 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5121 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5122 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5123 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5124 signal(SIGPIPE, SIG_DFL);
5125 if (redir->type == NHERE)
5126 full_write(pip[1], redir->nhere.doc->narg.text, len);
5128 expandhere(redir->nhere.doc, pip[1]);
5129 _exit(EXIT_SUCCESS);
5137 openredirect(union node *redir)
5142 switch (redir->nfile.type) {
5143 /* Can't happen, our single caller does this itself */
5149 return openhere(redir);
5152 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5153 * allocated space. Do it only when we know it is safe.
5155 fname = redir->nfile.expfname;
5157 switch (redir->nfile.type) {
5163 f = open(fname, O_RDONLY);
5168 f = open(fname, O_RDWR|O_CREAT, 0666);
5173 #if ENABLE_ASH_BASH_COMPAT
5176 /* Take care of noclobber mode. */
5178 f = noclobberopen(fname);
5185 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5190 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5198 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5200 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5204 * Copy a file descriptor to be >= 10. Throws exception on error.
5212 newfd = fcntl(from, F_DUPFD, 10);
5213 err = newfd < 0 ? errno : 0;
5216 ash_msg_and_raise_error("%d: %m", from);
5218 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5224 dup2_or_raise(int from, int to)
5228 newfd = (from != to) ? dup2(from, to) : to;
5230 /* Happens when source fd is not open: try "echo >&99" */
5231 ash_msg_and_raise_error("%d: %m", from);
5236 /* Struct def and variable are moved down to the first usage site */
5241 struct redirtab *next;
5243 struct two_fd_t two_fd[];
5245 #define redirlist (G_var.redirlist)
5247 COPYFD_RESTORE = (int)~(INT_MAX),
5251 need_to_remember(struct redirtab *rp, int fd)
5255 if (!rp) /* remembering was not requested */
5258 for (i = 0; i < rp->pair_count; i++) {
5259 if (rp->two_fd[i].orig == fd) {
5260 /* already remembered */
5267 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5269 is_hidden_fd(struct redirtab *rp, int fd)
5272 struct parsefile *pf;
5276 /* Check open scripts' fds */
5279 /* We skip pf_fd == 0 case because of the following case:
5280 * $ ash # running ash interactively
5282 * and in script.sh: "exec 9>&0".
5283 * Even though top-level pf_fd _is_ 0,
5284 * it's still ok to use it: "read" builtin uses it,
5285 * why should we cripple "exec" builtin?
5287 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5295 /* Check saved fds of redirects */
5296 fd |= COPYFD_RESTORE;
5297 for (i = 0; i < rp->pair_count; i++) {
5298 if (rp->two_fd[i].copy == fd) {
5306 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5307 * old file descriptors are stashed away so that the redirection can be
5308 * undone by calling popredir.
5310 /* flags passed to redirect */
5311 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5312 #define REDIR_SAVEFD2 03 /* set preverrout */
5314 redirect(union node *redir, int flags)
5316 struct redirtab *sv;
5321 int copied_fd2 = -1;
5330 if (flags & REDIR_PUSH) {
5331 union node *tmp = redir;
5334 #if ENABLE_ASH_BASH_COMPAT
5335 if (tmp->nfile.type == NTO2)
5338 tmp = tmp->nfile.next;
5340 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5341 sv->next = redirlist;
5342 sv->pair_count = sv_pos;
5344 while (sv_pos > 0) {
5346 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5352 fd = redir->nfile.fd;
5353 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5354 right_fd = redir->ndup.dupfd;
5355 //bb_error_msg("doing %d > %d", fd, right_fd);
5356 /* redirect from/to same file descriptor? */
5359 /* "echo >&10" and 10 is a fd opened to a sh script? */
5360 if (is_hidden_fd(sv, right_fd)) {
5361 errno = EBADF; /* as if it is closed */
5362 ash_msg_and_raise_error("%d: %m", right_fd);
5366 newfd = openredirect(redir); /* always >= 0 */
5368 /* Descriptor wasn't open before redirect.
5369 * Mark it for close in the future */
5370 if (need_to_remember(sv, fd)) {
5371 goto remember_to_close;
5376 #if ENABLE_ASH_BASH_COMPAT
5379 if (need_to_remember(sv, fd)) {
5380 /* Copy old descriptor */
5381 /* Careful to not accidentally "save"
5382 * to the same fd as right side fd in N>&M */
5383 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5384 i = fcntl(fd, F_DUPFD, minfd);
5385 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5386 * are closed in popredir() in the child, preventing them from leaking
5387 * into child. (popredir() also cleans up the mess in case of failures)
5392 /* Strange error (e.g. "too many files" EMFILE?) */
5396 ash_msg_and_raise_error("%d: %m", fd);
5399 /* EBADF: it is not open - good, remember to close it */
5402 } else { /* fd is open, save its copy */
5403 /* "exec fd>&-" should not close fds
5404 * which point to script file(s).
5405 * Force them to be restored afterwards */
5406 if (is_hidden_fd(sv, fd))
5407 i |= COPYFD_RESTORE;
5411 sv->two_fd[sv_pos].orig = fd;
5412 sv->two_fd[sv_pos].copy = i;
5416 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5417 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5418 /* Don't want to trigger debugging */
5422 dup2_or_raise(redir->ndup.dupfd, fd);
5424 } else if (fd != newfd) { /* move newfd to fd */
5425 dup2_or_raise(newfd, fd);
5426 #if ENABLE_ASH_BASH_COMPAT
5427 if (!(redir->nfile.type == NTO2 && fd == 2))
5431 #if ENABLE_ASH_BASH_COMPAT
5432 if (redir->nfile.type == NTO2 && fd == 1) {
5433 /* We already redirected it to fd 1, now copy it to 2 */
5439 } while ((redir = redir->nfile.next) != NULL);
5442 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5443 preverrout_fd = copied_fd2;
5447 * Undo the effects of the last redirection.
5450 popredir(int drop, int restore)
5452 struct redirtab *rp;
5455 if (redirlist == NULL)
5459 for (i = 0; i < rp->pair_count; i++) {
5460 int fd = rp->two_fd[i].orig;
5461 int copy = rp->two_fd[i].copy;
5462 if (copy == CLOSED) {
5467 if (copy != EMPTY) {
5468 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5469 copy &= ~COPYFD_RESTORE;
5471 dup2_or_raise(copy, fd);
5473 close(copy & ~COPYFD_RESTORE);
5476 redirlist = rp->next;
5482 * Undo all redirections. Called on error or interrupt.
5486 redirectsafe(union node *redir, int flags)
5489 volatile int saveint;
5490 struct jmploc *volatile savehandler = exception_handler;
5491 struct jmploc jmploc;
5494 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5495 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5497 exception_handler = &jmploc;
5498 redirect(redir, flags);
5500 exception_handler = savehandler;
5501 if (err && exception_type != EXERROR)
5502 longjmp(exception_handler->loc, 1);
5503 RESTORE_INT(saveint);
5508 /* ============ Routines to expand arguments to commands
5510 * We have to deal with backquotes, shell variables, and file metacharacters.
5513 #if ENABLE_SH_MATH_SUPPORT
5515 ash_arith(const char *s)
5517 arith_state_t math_state;
5520 math_state.lookupvar = lookupvar;
5521 math_state.setvar = setvar0;
5522 //math_state.endofname = endofname;
5525 result = arith(&math_state, s);
5526 if (math_state.errmsg)
5527 ash_msg_and_raise_error(math_state.errmsg);
5537 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5538 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5539 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5540 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5541 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5542 * POSIX says for this case:
5543 * Pathname expansion shall not be performed on the word by a
5544 * non-interactive shell; an interactive shell may perform it, but shall
5545 * do so only when the expansion would result in one word.
5546 * Currently, our code complies to the above rule by never globbing
5547 * redirection filenames.
5548 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5549 * (this means that on a typical Linux distro, bash almost always
5550 * performs globbing, and thus diverges from what we do).
5552 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5553 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5554 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5555 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5556 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5560 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5561 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5562 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5563 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5564 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5566 /* Add CTLESC when necessary. */
5567 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5568 /* Do not skip NUL characters. */
5569 #define QUOTES_KEEPNUL EXP_TILDE
5572 * Structure specifying which parts of the string should be searched
5573 * for IFS characters.
5576 struct ifsregion *next; /* next region in list */
5577 int begoff; /* offset of start of region */
5578 int endoff; /* offset of end of region */
5579 int nulonly; /* search for nul bytes only */
5583 struct strlist *list;
5584 struct strlist **lastp;
5587 /* output of current string */
5588 static char *expdest;
5589 /* list of back quote expressions */
5590 static struct nodelist *argbackq;
5591 /* first struct in list of ifs regions */
5592 static struct ifsregion ifsfirst;
5593 /* last struct in list */
5594 static struct ifsregion *ifslastp;
5595 /* holds expanded arg list */
5596 static struct arglist exparg;
5601 #if !ENABLE_SH_MATH_SUPPORT
5602 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5603 typedef long arith_t;
5604 # define ARITH_FMT "%ld"
5611 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5612 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5613 STADJUST(len, expdest);
5618 * Break the argument string into pieces based upon IFS and add the
5619 * strings to the argument list. The regions of the string to be
5620 * searched for IFS characters have been stored by recordregion.
5623 ifsbreakup(char *string, struct arglist *arglist)
5625 struct ifsregion *ifsp;
5630 const char *ifs, *realifs;
5635 if (ifslastp != NULL) {
5638 realifs = ifsset() ? ifsval() : defifs;
5641 p = string + ifsp->begoff;
5642 nulonly = ifsp->nulonly;
5643 ifs = nulonly ? nullstr : realifs;
5645 while (p < string + ifsp->endoff) {
5647 if ((unsigned char)*p == CTLESC)
5649 if (!strchr(ifs, *p)) {
5654 ifsspc = (strchr(defifs, *p) != NULL);
5655 /* Ignore IFS whitespace at start */
5656 if (q == start && ifsspc) {
5662 sp = stzalloc(sizeof(*sp));
5664 *arglist->lastp = sp;
5665 arglist->lastp = &sp->next;
5669 if (p >= string + ifsp->endoff) {
5673 if ((unsigned char)*p == CTLESC)
5675 if (strchr(ifs, *p) == NULL) {
5679 if (strchr(defifs, *p) == NULL) {
5694 } while (ifsp != NULL);
5703 sp = stzalloc(sizeof(*sp));
5705 *arglist->lastp = sp;
5706 arglist->lastp = &sp->next;
5712 struct ifsregion *p = ifsfirst.next;
5719 struct ifsregion *ifsp;
5724 ifsfirst.next = NULL;
5731 esclen(const char *start, const char *p)
5735 while (p > start && (unsigned char)*--p == CTLESC) {
5742 * Remove any CTLESC characters from a string.
5745 rmescapes(char *str, int flag)
5747 static const char qchars[] ALIGN1 = {
5748 IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
5752 unsigned protect_against_glob;
5754 IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
5756 p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
5762 if (flag & RMESCAPE_ALLOC) {
5763 size_t len = p - str;
5764 size_t fulllen = len + strlen(p) + 1;
5766 if (flag & RMESCAPE_GROW) {
5767 int strloc = str - (char *)stackblock();
5768 r = makestrspace(fulllen, expdest);
5769 /* p and str may be invalidated by makestrspace */
5770 str = (char *)stackblock() + strloc;
5772 } else if (flag & RMESCAPE_HEAP) {
5773 r = ckmalloc(fulllen);
5775 r = stalloc(fulllen);
5779 q = (char *)memcpy(q, str, len) + len;
5784 globbing = flag & RMESCAPE_GLOB;
5785 protect_against_glob = globbing;
5787 if ((unsigned char)*p == CTLQUOTEMARK) {
5788 // Note: both inquotes and protect_against_glob only affect whether
5789 inquotes = ~inquotes;
5791 protect_against_glob = globbing;
5794 if ((unsigned char)*p == CTLESC) {
5798 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5800 if (protect_against_glob) {
5803 } else if (*p == '\\' && !inquotes) {
5804 /* naked back slash */
5805 protect_against_glob = 0;
5808 #if ENABLE_ASH_BASH_COMPAT
5809 else if (*p == '/' && slash) {
5810 /* stop handling globbing and mark location of slash */
5811 globbing = slash = 0;
5815 protect_against_glob = globbing;
5820 if (flag & RMESCAPE_GROW) {
5822 STADJUST(q - r + 1, expdest);
5826 #define pmatch(a, b) !fnmatch((a), (b), 0)
5829 * Prepare a pattern for a expmeta (internal glob(3)) call.
5831 * Returns an stalloced string.
5834 preglob(const char *pattern, int flag)
5836 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5840 * Put a string on the stack.
5843 memtodest(const char *p, size_t len, int syntax, int quotes)
5850 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5853 unsigned char c = *p++;
5855 int n = SIT(c, syntax);
5856 if ((quotes & QUOTES_ESC)
5858 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
5864 } else if (!(quotes & QUOTES_KEEPNUL))
5873 strtodest(const char *p, int syntax, int quotes)
5875 size_t len = strlen(p);
5876 memtodest(p, len, syntax, quotes);
5881 * Record the fact that we have to scan this region of the
5882 * string for IFS characters.
5885 recordregion(int start, int end, int nulonly)
5887 struct ifsregion *ifsp;
5889 if (ifslastp == NULL) {
5893 ifsp = ckzalloc(sizeof(*ifsp));
5894 /*ifsp->next = NULL; - ckzalloc did it */
5895 ifslastp->next = ifsp;
5899 ifslastp->begoff = start;
5900 ifslastp->endoff = end;
5901 ifslastp->nulonly = nulonly;
5905 removerecordregions(int endoff)
5907 if (ifslastp == NULL)
5910 if (ifsfirst.endoff > endoff) {
5911 while (ifsfirst.next) {
5912 struct ifsregion *ifsp;
5914 ifsp = ifsfirst.next->next;
5915 free(ifsfirst.next);
5916 ifsfirst.next = ifsp;
5919 if (ifsfirst.begoff > endoff) {
5922 ifslastp = &ifsfirst;
5923 ifsfirst.endoff = endoff;
5928 ifslastp = &ifsfirst;
5929 while (ifslastp->next && ifslastp->next->begoff < endoff)
5930 ifslastp = ifslastp->next;
5931 while (ifslastp->next) {
5932 struct ifsregion *ifsp;
5934 ifsp = ifslastp->next->next;
5935 free(ifslastp->next);
5936 ifslastp->next = ifsp;
5939 if (ifslastp->endoff > endoff)
5940 ifslastp->endoff = endoff;
5944 exptilde(char *startp, char *p, int flags)
5950 int quotes = flags & QUOTES_ESC;
5954 while ((c = *++p) != '\0') {
5961 if (flags & EXP_VARTILDE)
5971 if (*name == '\0') {
5972 home = lookupvar("HOME");
5974 pw = getpwnam(name);
5979 if (!home || !*home)
5982 strtodest(home, SQSYNTAX, quotes);
5990 * Execute a command inside back quotes. If it's a builtin command, we
5991 * want to save its output in a block obtained from malloc. Otherwise
5992 * we fork off a subprocess and get the output of the command via a pipe.
5993 * Should be called with interrupts off.
5995 struct backcmd { /* result of evalbackcmd */
5996 int fd; /* file descriptor to read from */
5997 int nleft; /* number of chars in buffer */
5998 char *buf; /* buffer */
5999 struct job *jp; /* job structure for command */
6002 /* These forward decls are needed to use "eval" code for backticks handling: */
6003 #define EV_EXIT 01 /* exit after evaluating tree */
6004 static int evaltree(union node *, int);
6006 static void FAST_FUNC
6007 evalbackcmd(union node *n, struct backcmd *result)
6021 ash_msg_and_raise_error("pipe call failed");
6022 jp = makejob(/*n,*/ 1);
6023 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6029 dup2_or_raise(pip[1], 1);
6032 /* TODO: eflag clearing makes the following not abort:
6033 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6034 * which is what bash does (unless it is in POSIX mode).
6035 * dash deleted "eflag = 0" line in the commit
6036 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6037 * [EVAL] Don't clear eflag in evalbackcmd
6038 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6042 evaltree(n, EV_EXIT); /* actually evaltreenr... */
6047 result->fd = pip[0];
6051 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6052 result->fd, result->buf, result->nleft, result->jp));
6056 * Expand stuff in backwards quotes.
6059 expbackq(union node *cmd, int flag)
6067 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6068 struct stackmark smark;
6071 startloc = expdest - (char *)stackblock();
6072 pushstackmark(&smark, startloc);
6073 evalbackcmd(cmd, &in);
6074 popstackmark(&smark);
6081 memtodest(p, i, syntax, flag & QUOTES_ESC);
6085 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6086 TRACE(("expbackq: read returns %d\n", i));
6095 back_exitstatus = waitforjob(in.jp);
6099 /* Eat all trailing newlines */
6101 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6105 if (!(flag & EXP_QUOTED))
6106 recordregion(startloc, dest - (char *)stackblock(), 0);
6107 TRACE(("evalbackq: size:%d:'%.*s'\n",
6108 (int)((dest - (char *)stackblock()) - startloc),
6109 (int)((dest - (char *)stackblock()) - startloc),
6110 stackblock() + startloc));
6113 #if ENABLE_SH_MATH_SUPPORT
6115 * Expand arithmetic expression. Backup to start of expression,
6116 * evaluate, place result in (backed up) result, adjust string position.
6128 * This routine is slightly over-complicated for
6129 * efficiency. Next we scan backwards looking for the
6130 * start of arithmetic.
6132 start = stackblock();
6139 while ((unsigned char)*p != CTLARI) {
6143 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6148 esc = esclen(start, p);
6158 removerecordregions(begoff);
6162 if (flag & QUOTES_ESC)
6163 rmescapes(p + 1, 0);
6165 len = cvtnum(ash_arith(p + 1));
6167 if (!(flag & EXP_QUOTED))
6168 recordregion(begoff, begoff + len, 0);
6172 /* argstr needs it */
6173 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6176 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6177 * characters to allow for further processing. Otherwise treat
6178 * $@ like $* since no splitting will be performed.
6180 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6181 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6182 * for correct expansion of "B=$A" word.
6185 argstr(char *p, int flags, struct strlist *var_str_list)
6187 static const char spclchars[] ALIGN1 = {
6195 #if ENABLE_SH_MATH_SUPPORT
6200 const char *reject = spclchars;
6201 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6206 if (!(flags & EXP_VARTILDE)) {
6208 } else if (flags & EXP_VARTILDE2) {
6213 if (flags & EXP_TILDE) {
6216 flags &= ~EXP_TILDE;
6220 p = exptilde(p, q, flags);
6223 startloc = expdest - (char *)stackblock();
6227 length += strcspn(p + length, reject);
6231 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6233 /* c == '=' || c == ':' || c == CTLENDARI */
6239 expdest = stack_nputstr(p, length, expdest);
6240 newloc = expdest - (char *)stackblock();
6241 if (breakall && !inquotes && newloc > startloc) {
6242 recordregion(startloc, newloc, 0);
6253 if (flags & EXP_VARTILDE2) {
6257 flags |= EXP_VARTILDE2;
6262 * sort of a hack - expand tildes in variable
6263 * assignments (after the first '=' and after ':'s).
6272 case CTLENDVAR: /* ??? */
6275 inquotes ^= EXP_QUOTED;
6276 /* "$@" syntax adherence hack */
6277 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6278 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6282 if (flags & QUOTES_ESC) {
6293 * Quoted parameter expansion pattern: remove quote
6294 * unless inside inner quotes or we have a literal
6297 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6298 EXP_QPAT && *p != '\\')
6303 TRACE(("argstr: evalvar('%s')\n", p));
6304 p = evalvar(p, flags | inquotes, var_str_list);
6305 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6308 expbackq(argbackq->n, flags | inquotes);
6309 argbackq = argbackq->next;
6311 #if ENABLE_SH_MATH_SUPPORT
6314 expari(flags | inquotes);
6323 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6324 char *pattern, int quotes, int zero)
6333 const char *s = loc2;
6340 match = pmatch(pattern, s);
6345 if (quotes && (unsigned char)*loc == CTLESC)
6354 scanright(char *startp, char *rmesc, char *rmescend,
6355 char *pattern, int quotes, int match_at_start)
6357 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6358 int try2optimize = match_at_start;
6364 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6365 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6366 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6368 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6369 * and on each iteration they go back two/one char until they reach the beginning.
6370 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6372 /* TODO: document in what other circumstances we are called. */
6374 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6377 const char *s = loc2;
6378 if (match_at_start) {
6382 match = pmatch(pattern, s);
6383 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6387 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6389 /* Maybe we can optimize this:
6390 * if pattern ends with unescaped *, we can avoid checking
6391 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6392 * it wont match truncated "raw_value_of_" strings too.
6394 unsigned plen = strlen(pattern);
6395 /* Does it end with "*"? */
6396 if (plen != 0 && pattern[--plen] == '*') {
6397 /* "xxxx*" is not escaped */
6398 /* "xxx\*" is escaped */
6399 /* "xx\\*" is not escaped */
6400 /* "x\\\*" is escaped */
6402 while (plen != 0 && pattern[--plen] == '\\')
6405 break; /* ends with unescaped "*" */
6413 esc = esclen(startp, loc);
6424 static void varunset(const char *, const char *, const char *, int) NORETURN;
6426 varunset(const char *end, const char *var, const char *umsg, int varflags)
6432 msg = "parameter not set";
6434 if ((unsigned char)*end == CTLENDVAR) {
6435 if (varflags & VSNUL)
6441 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6445 subevalvar(char *p, char *varname, int strloc, int subtype,
6446 int startloc, int varflags, int flag, struct strlist *var_str_list)
6448 struct nodelist *saveargbackq = argbackq;
6449 int quotes = flag & QUOTES_ESC;
6452 char *rmesc, *rmescend;
6454 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6455 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6456 int amount, resetloc;
6457 IF_ASH_BASH_COMPAT(int workloc;)
6459 char *(*scan)(char*, char*, char*, char*, int, int);
6461 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6462 // p, varname, strloc, subtype, startloc, varflags, quotes);
6464 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6465 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6467 STPUTC('\0', expdest);
6468 argbackq = saveargbackq;
6469 startp = (char *)stackblock() + startloc;
6473 setvar0(varname, startp);
6474 amount = startp - expdest;
6475 STADJUST(amount, expdest);
6479 varunset(p, varname, startp, varflags);
6482 #if ENABLE_ASH_BASH_COMPAT
6484 //TODO: support more general format ${v:EXPR:EXPR},
6485 // where EXPR follows $(()) rules
6486 loc = str = stackblock() + strloc;
6487 /* Read POS in ${var:POS:LEN} */
6488 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6489 len = str - startp - 1;
6491 /* *loc != '\0', guaranteed by parser */
6495 /* Adjust the length by the number of escapes */
6496 for (ptr = startp; ptr < (str - 1); ptr++) {
6497 if ((unsigned char)*ptr == CTLESC) {
6505 if (*loc++ == ':') {
6509 /* Skip POS in ${var:POS:LEN} */
6511 while (*loc && *loc != ':') {
6513 * bash complains on: var=qwe; echo ${var:1a:123}
6515 ash_msg_and_raise_error(msg_illnum, str);
6519 if (*loc++ == ':') {
6524 /* ${VAR:$((-n)):l} starts n chars from the end */
6525 pos = orig_len + pos;
6527 if ((unsigned)pos >= orig_len) {
6528 /* apart from obvious ${VAR:999999:l},
6529 * covers ${VAR:$((-9999999)):l} - result is ""
6535 if (len > (orig_len - pos))
6536 len = orig_len - pos;
6538 for (str = startp; pos; str++, pos--) {
6539 if (quotes && (unsigned char)*str == CTLESC)
6542 for (loc = startp; len; len--) {
6543 if (quotes && (unsigned char)*str == CTLESC)
6548 amount = loc - expdest;
6549 STADJUST(amount, expdest);
6554 resetloc = expdest - (char *)stackblock();
6556 /* We'll comeback here if we grow the stack while handling
6557 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6558 * stack will need rebasing, and we'll need to remove our work
6561 IF_ASH_BASH_COMPAT(restart:)
6563 amount = expdest - ((char *)stackblock() + resetloc);
6564 STADJUST(-amount, expdest);
6565 startp = (char *)stackblock() + startloc;
6568 rmescend = (char *)stackblock() + strloc;
6570 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6571 if (rmesc != startp) {
6573 startp = (char *)stackblock() + startloc;
6577 str = (char *)stackblock() + strloc;
6579 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6580 * The result is a_\_z_c (not a\_\_z_c)!
6582 * The search pattern and replace string treat backslashes differently!
6583 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6584 * and string. It's only used on the first call.
6586 preglob(str, IF_ASH_BASH_COMPAT(
6587 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6588 RMESCAPE_SLASH :) 0);
6590 #if ENABLE_ASH_BASH_COMPAT
6591 workloc = expdest - (char *)stackblock();
6592 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6596 repl = strchr(str, CTLESC);
6602 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6604 /* If there's no pattern to match, return the expansion unmolested */
6613 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6614 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6616 /* No match, advance */
6617 char *restart_detect = stackblock();
6619 STPUTC(*idx, expdest);
6620 if (quotes && (unsigned char)*idx == CTLESC) {
6623 STPUTC(*idx, expdest);
6625 if (stackblock() != restart_detect)
6630 /* continue; - prone to quadratic behavior, smarter code: */
6633 if (str[0] == '*') {
6634 /* Pattern is "*foo". If "*foo" does not match "long_string",
6635 * it would never match "ong_string" etc, no point in trying.
6642 if (subtype == VSREPLACEALL) {
6644 if (quotes && (unsigned char)*idx == CTLESC)
6653 //bb_error_msg("repl:'%s'", repl);
6654 for (loc = (char*)repl; *loc; loc++) {
6655 char *restart_detect = stackblock();
6656 if (quotes && *loc == '\\') {
6657 STPUTC(CTLESC, expdest);
6660 STPUTC(*loc, expdest);
6661 if (stackblock() != restart_detect)
6666 if (subtype == VSREPLACE) {
6667 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6669 char *restart_detect = stackblock();
6670 STPUTC(*idx, expdest);
6671 if (stackblock() != restart_detect)
6680 /* We've put the replaced text into a buffer at workloc, now
6681 * move it to the right place and adjust the stack.
6683 STPUTC('\0', expdest);
6684 startp = (char *)stackblock() + startloc;
6685 memmove(startp, (char *)stackblock() + workloc, len + 1);
6686 //bb_error_msg("startp:'%s'", startp);
6687 amount = expdest - (startp + len);
6688 STADJUST(-amount, expdest);
6691 #endif /* ENABLE_ASH_BASH_COMPAT */
6693 subtype -= VSTRIMRIGHT;
6695 if (subtype < 0 || subtype > 7)
6698 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6699 zero = subtype >> 1;
6700 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6701 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6703 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6706 memmove(startp, loc, str - loc);
6707 loc = startp + (str - loc) - 1;
6710 amount = loc - expdest;
6711 STADJUST(amount, expdest);
6717 * Add the value of a specialized variable to the stack string.
6718 * name parameter (examples):
6719 * ash -c 'echo $1' name:'1='
6720 * ash -c 'echo $qwe' name:'qwe='
6721 * ash -c 'echo $$' name:'$='
6722 * ash -c 'echo ${$}' name:'$='
6723 * ash -c 'echo ${$##q}' name:'$=q'
6724 * ash -c 'echo ${#$}' name:'$='
6725 * note: examples with bad shell syntax:
6726 * ash -c 'echo ${#$1}' name:'$=1'
6727 * ash -c 'echo ${#1#}' name:'1=#'
6729 static NOINLINE ssize_t
6730 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list, int *quotedp)
6737 int quoted = *quotedp;
6738 int subtype = varflags & VSTYPE;
6739 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6740 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6743 sep = (flags & EXP_FULL) << CHAR_BIT;
6744 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6754 num = shellparam.nparam;
6762 goto check_1char_name;
6764 expdest = makestrspace(NOPTS, expdest);
6765 for (i = NOPTS - 1; i >= 0; i--) {
6767 USTPUTC(optletters(i), expdest);
6773 /* handles cases similar to ${#$1} */
6774 if (name[2] != '\0')
6775 raise_error_syntax("bad substitution");
6788 sep |= ifsset() ? ifsval()[0] : ' ';
6795 while ((p = *ap++) != NULL) {
6796 len += strtodest(p, syntax, quotes);
6800 memtodest(&sepc, 1, syntax, quotes);
6815 num = atoi(name); /* number(name) fails on ${N#str} etc */
6816 if (num < 0 || num > shellparam.nparam)
6818 p = num ? shellparam.p[num - 1] : arg0;
6821 /* NB: name has form "VAR=..." */
6823 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6824 * which should be considered before we check variables. */
6826 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6830 str = var_str_list->text;
6831 eq = strchr(str, '=');
6832 if (!eq) /* stop at first non-assignment */
6835 if (name_len == (unsigned)(eq - str)
6836 && strncmp(str, name, name_len) == 0
6839 /* goto value; - WRONG! */
6840 /* think "A=1 A=2 B=$A" */
6842 var_str_list = var_str_list->next;
6843 } while (var_str_list);
6847 p = lookupvar(name);
6852 len = strtodest(p, syntax, quotes);
6853 #if ENABLE_UNICODE_SUPPORT
6854 if (subtype == VSLENGTH && len > 0) {
6855 reinit_unicode_for_ash();
6856 if (unicode_status == UNICODE_ON) {
6857 STADJUST(-len, expdest);
6859 len = unicode_strlen(p);
6867 STADJUST(-len, expdest);
6872 * Expand a variable, and return a pointer to the next character in the
6876 evalvar(char *p, int flag, struct strlist *var_str_list)
6887 varflags = (unsigned char) *p++;
6888 subtype = varflags & VSTYPE;
6891 raise_error_syntax("bad substitution");
6893 quoted = flag & EXP_QUOTED;
6895 easy = (!quoted || (*var == '@' && shellparam.nparam));
6896 startloc = expdest - (char *)stackblock();
6897 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6900 varlen = varvalue(var, varflags, flag, var_str_list, "ed);
6901 if (varflags & VSNUL)
6904 if (subtype == VSPLUS) {
6905 varlen = -1 - varlen;
6909 if (subtype == VSMINUS) {
6914 flag | EXP_TILDE | EXP_WORD,
6922 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6926 subevalvar(p, var, 0, subtype, startloc, varflags,
6927 flag & ~QUOTES_ESC, var_str_list);
6930 * Remove any recorded regions beyond
6933 removerecordregions(startloc);
6937 if (varlen < 0 && uflag)
6938 varunset(p, var, 0, 0);
6940 if (subtype == VSLENGTH) {
6941 cvtnum(varlen > 0 ? varlen : 0);
6945 if (subtype == VSNORMAL) {
6949 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6958 case VSTRIMRIGHTMAX:
6959 #if ENABLE_ASH_BASH_COMPAT
6972 * Terminate the string and start recording the pattern
6975 STPUTC('\0', expdest);
6976 patloc = expdest - (char *)stackblock();
6977 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6978 startloc, varflags, flag, var_str_list)) {
6979 int amount = expdest - (
6980 (char *)stackblock() + patloc - 1
6982 STADJUST(-amount, expdest);
6984 /* Remove any recorded regions beyond start of variable */
6985 removerecordregions(startloc);
6990 if (subtype != VSNORMAL) { /* skip to end of alternative */
6993 unsigned char c = *p++;
6996 else if (c == CTLBACKQ) {
6998 argbackq = argbackq->next;
6999 } else if (c == CTLVAR) {
7000 if ((*p++ & VSTYPE) != VSNORMAL)
7002 } else if (c == CTLENDVAR) {
7012 * Add a file name to the list.
7015 addfname(const char *name)
7019 sp = stzalloc(sizeof(*sp));
7020 sp->text = sstrdup(name);
7022 exparg.lastp = &sp->next;
7025 /* If we want to use glob() from libc... */
7026 #if !ENABLE_ASH_INTERNAL_GLOB
7028 /* Add the result of glob() to the list */
7030 addglob(const glob_t *pglob)
7032 char **p = pglob->gl_pathv;
7039 expandmeta(struct strlist *str /*, int flag*/)
7041 /* TODO - EXP_REDIR */
7051 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7066 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7067 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7068 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7070 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7071 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7072 // Which means you need to unescape the string, right? Not so fast:
7073 // if there _is_ a file named "file\?" (with backslash), it is returned
7074 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7075 // You DONT KNOW by looking at the result whether you need to unescape it.
7077 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7078 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7079 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7080 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7081 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7082 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7083 i = glob(p, 0, NULL, &pglob);
7084 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7089 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7090 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7091 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7103 *exparg.lastp = str;
7104 rmescapes(str->text, 0);
7105 exparg.lastp = &str->next;
7107 default: /* GLOB_NOSPACE */
7110 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7117 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7120 * Do metacharacter (i.e. *, ?, [...]) expansion.
7123 expmeta(char *expdir, char *enddir, char *name)
7139 for (p = name; esc = 0, *p; p += esc + 1) {
7140 if (*p == '*' || *p == '?')
7142 else if (*p == '[') {
7149 if (*q == '/' || *q == '\0')
7159 if (p[esc] == '/') {
7162 start = p + esc + 1;
7166 if (metaflag == 0) { /* we've reached the end of the file name */
7167 if (enddir != expdir)
7175 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7186 } while (p < start);
7188 if (enddir == expdir) {
7190 } else if (enddir == expdir + 1 && *expdir == '/') {
7199 if (enddir != expdir)
7201 if (*endname == 0) {
7214 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7215 if (dp->d_name[0] == '.' && !matchdot)
7217 if (pmatch(start, dp->d_name)) {
7219 strcpy(enddir, dp->d_name);
7222 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7225 expmeta(expdir, p, endname);
7231 endname[-esc - 1] = esc ? '\\' : '/';
7234 static struct strlist *
7235 msort(struct strlist *list, int len)
7237 struct strlist *p, *q = NULL;
7238 struct strlist **lpp;
7246 for (n = half; --n >= 0;) {
7250 q->next = NULL; /* terminate first half of list */
7251 q = msort(list, half); /* sort first half of list */
7252 p = msort(p, len - half); /* sort second half */
7255 #if ENABLE_LOCALE_SUPPORT
7256 if (strcoll(p->text, q->text) < 0)
7258 if (strcmp(p->text, q->text) < 0)
7282 * Sort the results of file name expansion. It calculates the number of
7283 * strings to sort and then calls msort (short for merge sort) to do the
7286 static struct strlist *
7287 expsort(struct strlist *str)
7293 for (sp = str; sp; sp = sp->next)
7295 return msort(str, len);
7299 expandmeta(struct strlist *str /*, int flag*/)
7301 static const char metachars[] ALIGN1 = {
7304 /* TODO - EXP_REDIR */
7308 struct strlist **savelastp;
7314 if (!strpbrk(str->text, metachars))
7316 savelastp = exparg.lastp;
7319 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7321 int i = strlen(str->text);
7322 //BUGGY estimation of how long expanded name can be
7323 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7325 expmeta(expdir, expdir, p);
7330 if (exparg.lastp == savelastp) {
7335 *exparg.lastp = str;
7336 rmescapes(str->text, 0);
7337 exparg.lastp = &str->next;
7339 *exparg.lastp = NULL;
7340 *savelastp = sp = expsort(*savelastp);
7341 while (sp->next != NULL)
7343 exparg.lastp = &sp->next;
7348 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7351 * Perform variable substitution and command substitution on an argument,
7352 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7353 * perform splitting and file name expansion. When arglist is NULL, perform
7354 * here document expansion.
7357 expandarg(union node *arg, struct arglist *arglist, int flag)
7362 argbackq = arg->narg.backquote;
7363 STARTSTACKSTR(expdest);
7364 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7365 argstr(arg->narg.text, flag,
7366 /* var_str_list: */ arglist ? arglist->list : NULL);
7367 p = _STPUTC('\0', expdest);
7369 if (arglist == NULL) {
7370 /* here document expanded */
7373 p = grabstackstr(p);
7374 TRACE(("expandarg: p:'%s'\n", p));
7375 exparg.lastp = &exparg.list;
7379 if (flag & EXP_FULL) {
7380 ifsbreakup(p, &exparg);
7381 *exparg.lastp = NULL;
7382 exparg.lastp = &exparg.list;
7383 expandmeta(exparg.list /*, flag*/);
7385 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7387 TRACE(("expandarg: rmescapes:'%s'\n", p));
7389 sp = stzalloc(sizeof(*sp));
7392 exparg.lastp = &sp->next;
7394 *exparg.lastp = NULL;
7396 *arglist->lastp = exparg.list;
7397 arglist->lastp = exparg.lastp;
7405 * Expand shell variables and backquotes inside a here document.
7408 expandhere(union node *arg, int fd)
7410 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7411 full_write(fd, stackblock(), expdest - (char *)stackblock());
7415 * Returns true if the pattern matches the string.
7418 patmatch(char *pattern, const char *string)
7420 return pmatch(preglob(pattern, 0), string);
7424 * See if a pattern matches in a case statement.
7427 casematch(union node *pattern, char *val)
7429 struct stackmark smark;
7432 setstackmark(&smark);
7433 argbackq = pattern->narg.backquote;
7434 STARTSTACKSTR(expdest);
7435 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7436 /* var_str_list: */ NULL);
7437 STACKSTRNUL(expdest);
7439 result = patmatch(stackblock(), val);
7440 popstackmark(&smark);
7445 /* ============ find_command */
7449 int (*builtin)(int, char **) FAST_FUNC;
7450 /* unsigned flags; */
7452 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7453 /* "regular" builtins always take precedence over commands,
7454 * regardless of PATH=....%builtin... position */
7455 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7456 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7459 smallint cmdtype; /* CMDxxx */
7462 /* index >= 0 for commands without path (slashes) */
7463 /* (TODO: what exactly does the value mean? PATH position?) */
7464 /* index == -1 for commands with slashes */
7465 /* index == (-2 - applet_no) for NOFORK applets */
7466 const struct builtincmd *cmd;
7467 struct funcnode *func;
7470 /* values of cmdtype */
7471 #define CMDUNKNOWN -1 /* no entry in table for command */
7472 #define CMDNORMAL 0 /* command is an executable program */
7473 #define CMDFUNCTION 1 /* command is a shell function */
7474 #define CMDBUILTIN 2 /* command is a shell builtin */
7476 /* action to find_command() */
7477 #define DO_ERR 0x01 /* prints errors */
7478 #define DO_ABS 0x02 /* checks absolute paths */
7479 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7480 #define DO_ALTPATH 0x08 /* using alternate path */
7481 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7483 static void find_command(char *, struct cmdentry *, int, const char *);
7486 /* ============ Hashing commands */
7489 * When commands are first encountered, they are entered in a hash table.
7490 * This ensures that a full path search will not have to be done for them
7491 * on each invocation.
7493 * We should investigate converting to a linear search, even though that
7494 * would make the command name "hash" a misnomer.
7498 struct tblentry *next; /* next entry in hash chain */
7499 union param param; /* definition of builtin function */
7500 smallint cmdtype; /* CMDxxx */
7501 char rehash; /* if set, cd done since entry created */
7502 char cmdname[1]; /* name of command */
7505 static struct tblentry **cmdtable;
7506 #define INIT_G_cmdtable() do { \
7507 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7510 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7514 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7516 #if ENABLE_FEATURE_SH_STANDALONE
7517 if (applet_no >= 0) {
7518 if (APPLET_IS_NOEXEC(applet_no)) {
7522 run_applet_no_and_exit(applet_no, argv);
7524 /* re-exec ourselves with the new arguments */
7525 execve(bb_busybox_exec_path, argv, envp);
7526 /* If they called chroot or otherwise made the binary no longer
7527 * executable, fall through */
7534 execve(cmd, argv, envp);
7535 } while (errno == EINTR);
7537 execve(cmd, argv, envp);
7539 if (cmd != (char*) bb_busybox_exec_path && errno == ENOEXEC) {
7540 /* Run "cmd" as a shell script:
7541 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7542 * "If the execve() function fails with ENOEXEC, the shell
7543 * shall execute a command equivalent to having a shell invoked
7544 * with the command name as its first operand,
7545 * with any remaining arguments passed to the new shell"
7547 * That is, do not use $SHELL, user's shell, or /bin/sh;
7548 * just call ourselves.
7550 * Note that bash reads ~80 chars of the file, and if it sees
7551 * a zero byte before it sees newline, it doesn't try to
7552 * interpret it, but fails with "cannot execute binary file"
7553 * message and exit code 126. For one, this prevents attempts
7554 * to interpret foreign ELF binaries as shell scripts.
7557 cmd = (char*) bb_busybox_exec_path;
7558 /* NB: this is only possible because all callers of shellexec()
7559 * ensure that the argv[-1] slot exists!
7562 argv[0] = (char*) "ash";
7568 * Exec a program. Never returns. If you change this routine, you may
7569 * have to change the find_command routine as well.
7570 * argv[-1] must exist and be writable! See tryexec() for why.
7572 static void shellexec(char **, const char *, int) NORETURN;
7574 shellexec(char **argv, const char *path, int idx)
7580 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7582 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7583 if (strchr(argv[0], '/') != NULL
7584 #if ENABLE_FEATURE_SH_STANDALONE
7585 || (applet_no = find_applet_by_name(argv[0])) >= 0
7588 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7589 if (applet_no >= 0) {
7590 /* We tried execing ourself, but it didn't work.
7591 * Maybe /proc/self/exe doesn't exist?
7600 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7601 if (--idx < 0 && pathopt == NULL) {
7602 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7603 if (errno != ENOENT && errno != ENOTDIR)
7610 /* Map to POSIX errors */
7622 exitstatus = exerrno;
7623 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7624 argv[0], e, suppress_int));
7625 ash_msg_and_raise(EXEXIT, "%s: %s", argv[0], errmsg(e, "not found"));
7630 printentry(struct tblentry *cmdp)
7636 idx = cmdp->param.index;
7639 name = path_advance(&path, cmdp->cmdname);
7641 } while (--idx >= 0);
7642 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7646 * Clear out command entries. The argument specifies the first entry in
7647 * PATH which has changed.
7650 clearcmdentry(int firstchange)
7652 struct tblentry **tblp;
7653 struct tblentry **pp;
7654 struct tblentry *cmdp;
7657 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7659 while ((cmdp = *pp) != NULL) {
7660 if ((cmdp->cmdtype == CMDNORMAL &&
7661 cmdp->param.index >= firstchange)
7662 || (cmdp->cmdtype == CMDBUILTIN &&
7663 builtinloc >= firstchange)
7676 * Locate a command in the command hash table. If "add" is nonzero,
7677 * add the command to the table if it is not already present. The
7678 * variable "lastcmdentry" is set to point to the address of the link
7679 * pointing to the entry, so that delete_cmd_entry can delete the
7682 * Interrupts must be off if called with add != 0.
7684 static struct tblentry **lastcmdentry;
7686 static struct tblentry *
7687 cmdlookup(const char *name, int add)
7689 unsigned int hashval;
7691 struct tblentry *cmdp;
7692 struct tblentry **pp;
7695 hashval = (unsigned char)*p << 4;
7697 hashval += (unsigned char)*p++;
7699 pp = &cmdtable[hashval % CMDTABLESIZE];
7700 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7701 if (strcmp(cmdp->cmdname, name) == 0)
7705 if (add && cmdp == NULL) {
7706 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7708 /* + 1 - already done because
7709 * tblentry::cmdname is char[1] */);
7710 /*cmdp->next = NULL; - ckzalloc did it */
7711 cmdp->cmdtype = CMDUNKNOWN;
7712 strcpy(cmdp->cmdname, name);
7719 * Delete the command entry returned on the last lookup.
7722 delete_cmd_entry(void)
7724 struct tblentry *cmdp;
7727 cmdp = *lastcmdentry;
7728 *lastcmdentry = cmdp->next;
7729 if (cmdp->cmdtype == CMDFUNCTION)
7730 freefunc(cmdp->param.func);
7736 * Add a new command entry, replacing any existing command entry for
7737 * the same name - except special builtins.
7740 addcmdentry(char *name, struct cmdentry *entry)
7742 struct tblentry *cmdp;
7744 cmdp = cmdlookup(name, 1);
7745 if (cmdp->cmdtype == CMDFUNCTION) {
7746 freefunc(cmdp->param.func);
7748 cmdp->cmdtype = entry->cmdtype;
7749 cmdp->param = entry->u;
7753 static int FAST_FUNC
7754 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7756 struct tblentry **pp;
7757 struct tblentry *cmdp;
7759 struct cmdentry entry;
7762 if (nextopt("r") != '\0') {
7767 if (*argptr == NULL) {
7768 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7769 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7770 if (cmdp->cmdtype == CMDNORMAL)
7778 while ((name = *argptr) != NULL) {
7779 cmdp = cmdlookup(name, 0);
7781 && (cmdp->cmdtype == CMDNORMAL
7782 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7786 find_command(name, &entry, DO_ERR, pathval());
7787 if (entry.cmdtype == CMDUNKNOWN)
7795 * Called when a cd is done. Marks all commands so the next time they
7796 * are executed they will be rehashed.
7801 struct tblentry **pp;
7802 struct tblentry *cmdp;
7804 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7805 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7806 if (cmdp->cmdtype == CMDNORMAL
7807 || (cmdp->cmdtype == CMDBUILTIN
7808 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7818 * Fix command hash table when PATH changed.
7819 * Called before PATH is changed. The argument is the new value of PATH;
7820 * pathval() still returns the old value at this point.
7821 * Called with interrupts off.
7823 static void FAST_FUNC
7824 changepath(const char *new)
7832 firstchange = 9999; /* assume no change */
7838 if ((*old == '\0' && *new == ':')
7839 || (*old == ':' && *new == '\0')
7843 old = new; /* ignore subsequent differences */
7847 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7854 if (builtinloc < 0 && idx_bltin >= 0)
7855 builtinloc = idx_bltin; /* zap builtins */
7856 if (builtinloc >= 0 && idx_bltin < 0)
7858 clearcmdentry(firstchange);
7859 builtinloc = idx_bltin;
7884 #if ENABLE_ASH_BASH_COMPAT
7895 typedef smallint token_id_t;
7897 /* Nth bit indicates if token marks the end of a list */
7900 /* 0 */ | (1u << TEOF)
7901 /* 1 */ | (0u << TNL)
7902 /* 2 */ | (0u << TREDIR)
7903 /* 3 */ | (0u << TWORD)
7904 /* 4 */ | (0u << TSEMI)
7905 /* 5 */ | (0u << TBACKGND)
7906 /* 6 */ | (0u << TAND)
7907 /* 7 */ | (0u << TOR)
7908 /* 8 */ | (0u << TPIPE)
7909 /* 9 */ | (0u << TLP)
7910 /* 10 */ | (1u << TRP)
7911 /* 11 */ | (1u << TENDCASE)
7912 /* 12 */ | (1u << TENDBQUOTE)
7913 /* 13 */ | (0u << TNOT)
7914 /* 14 */ | (0u << TCASE)
7915 /* 15 */ | (1u << TDO)
7916 /* 16 */ | (1u << TDONE)
7917 /* 17 */ | (1u << TELIF)
7918 /* 18 */ | (1u << TELSE)
7919 /* 19 */ | (1u << TESAC)
7920 /* 20 */ | (1u << TFI)
7921 /* 21 */ | (0u << TFOR)
7922 #if ENABLE_ASH_BASH_COMPAT
7923 /* 22 */ | (0u << TFUNCTION)
7925 /* 23 */ | (0u << TIF)
7926 /* 24 */ | (0u << TIN)
7927 /* 25 */ | (1u << TTHEN)
7928 /* 26 */ | (0u << TUNTIL)
7929 /* 27 */ | (0u << TWHILE)
7930 /* 28 */ | (0u << TBEGIN)
7931 /* 29 */ | (1u << TEND)
7932 , /* thus far 29 bits used */
7935 static const char *const tokname_array[] = {
7949 #define KWDOFFSET 13
7950 /* the following are keywords */
7960 #if ENABLE_ASH_BASH_COMPAT
7972 /* Wrapper around strcmp for qsort/bsearch/... */
7974 pstrcmp(const void *a, const void *b)
7976 return strcmp((char*)a, *(char**)b);
7979 static const char *const *
7980 findkwd(const char *s)
7982 return bsearch(s, tokname_array + KWDOFFSET,
7983 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7984 sizeof(tokname_array[0]), pstrcmp);
7988 * Locate and print what a word is...
7991 describe_command(char *command, const char *path, int describe_command_verbose)
7993 struct cmdentry entry;
7994 struct tblentry *cmdp;
7995 #if ENABLE_ASH_ALIAS
7996 const struct alias *ap;
7999 path = path ? path : pathval();
8001 if (describe_command_verbose) {
8005 /* First look at the keywords */
8006 if (findkwd(command)) {
8007 out1str(describe_command_verbose ? " is a shell keyword" : command);
8011 #if ENABLE_ASH_ALIAS
8012 /* Then look at the aliases */
8013 ap = lookupalias(command, 0);
8015 if (!describe_command_verbose) {
8020 out1fmt(" is an alias for %s", ap->val);
8024 /* Then check if it is a tracked alias */
8025 cmdp = cmdlookup(command, 0);
8027 entry.cmdtype = cmdp->cmdtype;
8028 entry.u = cmdp->param;
8030 /* Finally use brute force */
8031 find_command(command, &entry, DO_ABS, path);
8034 switch (entry.cmdtype) {
8036 int j = entry.u.index;
8042 p = path_advance(&path, command);
8046 if (describe_command_verbose) {
8048 (cmdp ? " a tracked alias for" : nullstr), p
8057 if (describe_command_verbose) {
8058 out1str(" is a shell function");
8065 if (describe_command_verbose) {
8066 out1fmt(" is a %sshell builtin",
8067 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8068 "special " : nullstr
8076 if (describe_command_verbose) {
8077 out1str(": not found\n");
8086 static int FAST_FUNC
8087 typecmd(int argc UNUSED_PARAM, char **argv)
8093 /* type -p ... ? (we don't bother checking for 'p') */
8094 if (argv[1] && argv[1][0] == '-') {
8099 err |= describe_command(argv[i++], NULL, verbose);
8104 #if ENABLE_ASH_CMDCMD
8105 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8107 parse_command_args(char **argv, const char **path)
8120 if (c == '-' && !*cp) {
8128 *path = bb_default_path;
8131 /* run 'typecmd' for other options */
8140 static int FAST_FUNC
8141 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8149 const char *path = NULL;
8151 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8152 * never reaches this function.
8155 while ((c = nextopt("pvV")) != '\0')
8157 verify |= VERIFY_VERBOSE;
8159 /*verify |= VERIFY_BRIEF*/;
8165 path = bb_default_path;
8167 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8169 if (/*verify && */ cmd)
8170 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8177 /*static int funcblocksize; // size of structures in function */
8178 /*static int funcstringsize; // size of strings in node */
8179 static void *funcblock; /* block to allocate function from */
8180 static char *funcstring_end; /* end of block to allocate strings from */
8182 /* flags in argument to evaltree */
8183 #define EV_EXIT 01 /* exit after evaluating tree */
8184 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8186 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8187 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8188 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8189 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8190 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8191 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8192 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8193 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8194 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8195 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8196 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8197 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8198 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8199 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8200 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8201 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8202 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8203 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8204 #if ENABLE_ASH_BASH_COMPAT
8205 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8207 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8208 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8209 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8210 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8211 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8212 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8213 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8214 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8215 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8218 static int calcsize(int funcblocksize, union node *n);
8221 sizenodelist(int funcblocksize, struct nodelist *lp)
8224 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8225 funcblocksize = calcsize(funcblocksize, lp->n);
8228 return funcblocksize;
8232 calcsize(int funcblocksize, union node *n)
8235 return funcblocksize;
8236 funcblocksize += nodesize[n->type];
8239 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8240 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8241 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8244 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8249 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8250 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8257 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8258 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8261 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8262 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8263 funcblocksize = calcsize(funcblocksize, n->nif.test);
8266 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8267 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8268 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8271 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8272 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8275 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8276 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8277 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8281 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8282 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8283 funcblocksize = calcsize(funcblocksize, n->narg.next);
8286 #if ENABLE_ASH_BASH_COMPAT
8293 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8294 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8298 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8299 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8303 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8304 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8307 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8310 return funcblocksize;
8314 nodeckstrdup(char *s)
8316 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8317 return strcpy(funcstring_end, s);
8320 static union node *copynode(union node *);
8322 static struct nodelist *
8323 copynodelist(struct nodelist *lp)
8325 struct nodelist *start;
8326 struct nodelist **lpp;
8331 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8332 (*lpp)->n = copynode(lp->n);
8334 lpp = &(*lpp)->next;
8341 copynode(union node *n)
8348 funcblock = (char *) funcblock + nodesize[n->type];
8352 new->ncmd.redirect = copynode(n->ncmd.redirect);
8353 new->ncmd.args = copynode(n->ncmd.args);
8354 new->ncmd.assign = copynode(n->ncmd.assign);
8357 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8358 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8363 new->nredir.redirect = copynode(n->nredir.redirect);
8364 new->nredir.n = copynode(n->nredir.n);
8371 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8372 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8375 new->nif.elsepart = copynode(n->nif.elsepart);
8376 new->nif.ifpart = copynode(n->nif.ifpart);
8377 new->nif.test = copynode(n->nif.test);
8380 new->nfor.var = nodeckstrdup(n->nfor.var);
8381 new->nfor.body = copynode(n->nfor.body);
8382 new->nfor.args = copynode(n->nfor.args);
8385 new->ncase.cases = copynode(n->ncase.cases);
8386 new->ncase.expr = copynode(n->ncase.expr);
8389 new->nclist.body = copynode(n->nclist.body);
8390 new->nclist.pattern = copynode(n->nclist.pattern);
8391 new->nclist.next = copynode(n->nclist.next);
8395 new->narg.backquote = copynodelist(n->narg.backquote);
8396 new->narg.text = nodeckstrdup(n->narg.text);
8397 new->narg.next = copynode(n->narg.next);
8400 #if ENABLE_ASH_BASH_COMPAT
8407 new->nfile.fname = copynode(n->nfile.fname);
8408 new->nfile.fd = n->nfile.fd;
8409 new->nfile.next = copynode(n->nfile.next);
8413 new->ndup.vname = copynode(n->ndup.vname);
8414 new->ndup.dupfd = n->ndup.dupfd;
8415 new->ndup.fd = n->ndup.fd;
8416 new->ndup.next = copynode(n->ndup.next);
8420 new->nhere.doc = copynode(n->nhere.doc);
8421 new->nhere.fd = n->nhere.fd;
8422 new->nhere.next = copynode(n->nhere.next);
8425 new->nnot.com = copynode(n->nnot.com);
8428 new->type = n->type;
8433 * Make a copy of a parse tree.
8435 static struct funcnode *
8436 copyfunc(union node *n)
8441 /*funcstringsize = 0;*/
8442 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8443 f = ckzalloc(blocksize /* + funcstringsize */);
8444 funcblock = (char *) f + offsetof(struct funcnode, n);
8445 funcstring_end = (char *) f + blocksize;
8447 /* f->count = 0; - ckzalloc did it */
8452 * Define a shell function.
8455 defun(union node *func)
8457 struct cmdentry entry;
8460 entry.cmdtype = CMDFUNCTION;
8461 entry.u.func = copyfunc(func);
8462 addcmdentry(func->narg.text, &entry);
8466 /* Reasons for skipping commands (see comment on breakcmd routine) */
8467 #define SKIPBREAK (1 << 0)
8468 #define SKIPCONT (1 << 1)
8469 #define SKIPFUNC (1 << 2)
8470 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8471 static int skipcount; /* number of levels to skip */
8472 static int funcnest; /* depth of function calls */
8473 static int loopnest; /* current loop nesting level */
8475 /* Forward decl way out to parsing code - dotrap needs it */
8476 static int evalstring(char *s, int flags);
8478 /* Called to execute a trap.
8479 * Single callsite - at the end of evaltree().
8480 * If we return non-zero, evaltree raises EXEXIT exception.
8482 * Perhaps we should avoid entering new trap handlers
8483 * while we are executing a trap handler. [is it a TODO?]
8490 uint8_t last_status;
8495 last_status = exitstatus;
8499 TRACE(("dotrap entered\n"));
8500 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8512 /* non-trapped SIGINT is handled separately by raise_interrupt,
8513 * don't upset it by resetting gotsig[SIGINT-1] */
8514 if (sig == SIGINT && !p)
8517 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8523 exitstatus = last_status;
8524 TRACE(("dotrap returns\n"));
8527 /* forward declarations - evaluation is fairly recursive business... */
8528 static int evalloop(union node *, int);
8529 static int evalfor(union node *, int);
8530 static int evalcase(union node *, int);
8531 static int evalsubshell(union node *, int);
8532 static void expredir(union node *);
8533 static int evalpipe(union node *, int);
8534 static int evalcommand(union node *, int);
8535 static int evalbltin(const struct builtincmd *, int, char **, int);
8536 static void prehash(union node *);
8539 * Evaluate a parse tree. The value is left in the global variable
8543 evaltree(union node *n, int flags)
8546 int (*evalfn)(union node *, int);
8550 TRACE(("evaltree(NULL) called\n"));
8553 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8560 out1fmt("Node type = %d\n", n->type);
8565 status = !evaltree(n->nnot.com, EV_TESTED);
8568 expredir(n->nredir.redirect);
8569 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8571 status = evaltree(n->nredir.n, flags & EV_TESTED);
8573 if (n->nredir.redirect)
8574 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8577 evalfn = evalcommand;
8579 if (eflag && !(flags & EV_TESTED))
8591 evalfn = evalsubshell;
8604 #error NAND + 1 != NOR
8606 #if NOR + 1 != NSEMI
8607 #error NOR + 1 != NSEMI
8609 unsigned is_or = n->type - NAND;
8612 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8614 if ((!status) == is_or || evalskip)
8620 status = evalfn(n, flags);
8624 status = evaltree(n->nif.test, EV_TESTED);
8631 if (n->nif.elsepart) {
8632 n = n->nif.elsepart;
8639 /* Not necessary. To test it:
8640 * "false; f() { qwerty; }; echo $?" should print 0.
8644 exitstatus = status;
8648 /* Order of checks below is important:
8649 * signal handlers trigger before exit caused by "set -e".
8653 if (checkexit & status)
8654 raise_exception(EXEXIT);
8655 if (flags & EV_EXIT)
8656 raise_exception(EXEXIT);
8658 TRACE(("leaving evaltree (no interrupts)\n"));
8662 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8665 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8670 int skip = evalskip;
8677 if (--skipcount <= 0) {
8688 evalloop(union node *n, int flags)
8699 i = evaltree(n->nbinary.ch1, EV_TESTED);
8701 if (skip == SKIPFUNC)
8705 if (n->type != NWHILE)
8709 status = evaltree(n->nbinary.ch2, flags);
8711 } while (!(skip & ~SKIPCONT));
8718 evalfor(union node *n, int flags)
8720 struct arglist arglist;
8723 struct stackmark smark;
8726 setstackmark(&smark);
8727 arglist.list = NULL;
8728 arglist.lastp = &arglist.list;
8729 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8730 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8732 *arglist.lastp = NULL;
8736 for (sp = arglist.list; sp; sp = sp->next) {
8737 setvar0(n->nfor.var, sp->text);
8738 status = evaltree(n->nfor.body, flags);
8739 if (skiploop() & ~SKIPCONT)
8743 popstackmark(&smark);
8749 evalcase(union node *n, int flags)
8753 struct arglist arglist;
8754 struct stackmark smark;
8757 setstackmark(&smark);
8758 arglist.list = NULL;
8759 arglist.lastp = &arglist.list;
8760 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8761 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8762 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8763 if (casematch(patp, arglist.list->text)) {
8764 /* Ensure body is non-empty as otherwise
8765 * EV_EXIT may prevent us from setting the
8768 if (evalskip == 0 && cp->nclist.body) {
8769 status = evaltree(cp->nclist.body, flags);
8776 popstackmark(&smark);
8782 * Kick off a subshell to evaluate a tree.
8785 evalsubshell(union node *n, int flags)
8788 int backgnd = (n->type == NBACKGND);
8791 expredir(n->nredir.redirect);
8792 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8795 jp = makejob(/*n,*/ 1);
8796 if (forkshell(jp, n, backgnd) == 0) {
8801 flags &= ~EV_TESTED;
8803 redirect(n->nredir.redirect, 0);
8804 evaltreenr(n->nredir.n, flags);
8810 status = waitforjob(jp);
8816 * Compute the names of the files in a redirection list.
8818 static void fixredir(union node *, const char *, int);
8820 expredir(union node *n)
8824 for (redir = n; redir; redir = redir->nfile.next) {
8828 fn.lastp = &fn.list;
8829 switch (redir->type) {
8833 #if ENABLE_ASH_BASH_COMPAT
8838 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8839 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8840 #if ENABLE_ASH_BASH_COMPAT
8844 // By the design of stack allocator, the loop of this kind:
8845 // while true; do while true; do break; done </dev/null; done
8846 // will look like a memory leak: ash plans to free expfname's
8847 // of "/dev/null" as soon as it finishes running the loop
8848 // (in this case, never).
8849 // This "fix" is wrong:
8850 if (redir->nfile.expfname)
8851 stunalloc(redir->nfile.expfname);
8852 // It results in corrupted state of stacked allocations.
8854 redir->nfile.expfname = fn.list->text;
8857 case NTOFD: /* >& */
8858 if (redir->ndup.vname) {
8859 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8860 if (fn.list == NULL)
8861 ash_msg_and_raise_error("redir error");
8862 #if ENABLE_ASH_BASH_COMPAT
8863 //FIXME: we used expandarg with different args!
8864 if (!isdigit_str9(fn.list->text)) {
8865 /* >&file, not >&fd */
8866 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8867 ash_msg_and_raise_error("redir error");
8869 goto store_expfname;
8872 fixredir(redir, fn.list->text, 1);
8880 * Evaluate a pipeline. All the processes in the pipeline are children
8881 * of the process creating the pipeline. (This differs from some versions
8882 * of the shell, which make the last process in a pipeline the parent
8886 evalpipe(union node *n, int flags)
8889 struct nodelist *lp;
8895 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8897 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8901 jp = makejob(/*n,*/ pipelen);
8903 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8907 if (pipe(pip) < 0) {
8909 ash_msg_and_raise_error("pipe call failed");
8912 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8926 evaltreenr(lp->n, flags);
8933 /* Don't want to trigger debugging */
8937 if (n->npipe.pipe_backgnd == 0) {
8938 status = waitforjob(jp);
8939 TRACE(("evalpipe: job done exit status %d\n", status));
8947 * Controls whether the shell is interactive or not.
8950 setinteractive(int on)
8952 static smallint is_interactive;
8954 if (++on == is_interactive)
8956 is_interactive = on;
8960 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8961 if (is_interactive > 1) {
8962 /* Looks like they want an interactive shell */
8963 static smallint did_banner;
8966 /* note: ash and hush share this string */
8967 out1fmt("\n\n%s %s\n"
8968 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
8971 "built-in shell (ash)"
8985 setinteractive(iflag);
8987 #if ENABLE_FEATURE_EDITING_VI
8989 line_input_state->flags |= VI_MODE;
8991 line_input_state->flags &= ~VI_MODE;
8993 viflag = 0; /* forcibly keep the option off */
8997 static struct localvar *localvars;
9000 * Called after a function returns.
9001 * Interrupts must be off.
9006 struct localvar *lvp;
9009 while ((lvp = localvars) != NULL) {
9010 localvars = lvp->next;
9012 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9013 if (vp == NULL) { /* $- saved */
9014 memcpy(optlist, lvp->text, sizeof(optlist));
9015 free((char*)lvp->text);
9017 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
9018 unsetvar(vp->var_text);
9021 vp->var_func(var_end(lvp->text));
9022 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9023 free((char*)vp->var_text);
9024 vp->flags = lvp->flags;
9025 vp->var_text = lvp->text;
9032 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9034 volatile struct shparam saveparam;
9035 struct localvar *volatile savelocalvars;
9036 struct jmploc *volatile savehandler;
9037 struct jmploc jmploc;
9040 saveparam = shellparam;
9041 savelocalvars = localvars;
9042 savehandler = exception_handler;
9043 e = setjmp(jmploc.loc);
9048 exception_handler = &jmploc;
9050 shellparam.malloced = 0;
9054 shellparam.nparam = argc - 1;
9055 shellparam.p = argv + 1;
9056 #if ENABLE_ASH_GETOPTS
9057 shellparam.optind = 1;
9058 shellparam.optoff = -1;
9060 evaltree(func->n.narg.next, flags & EV_TESTED);
9066 localvars = savelocalvars;
9067 freeparam(&shellparam);
9068 shellparam = saveparam;
9069 exception_handler = savehandler;
9071 evalskip &= ~SKIPFUNC;
9076 * Make a variable a local variable. When a variable is made local, it's
9077 * value and flags are saved in a localvar structure. The saved values
9078 * will be restored when the shell function returns. We handle the name
9079 * "-" as a special case: it makes changes to "set +-options" local
9080 * (options will be restored on return from the function).
9085 struct localvar *lvp;
9088 char *eq = strchr(name, '=');
9091 /* Cater for duplicate "local". Examples:
9092 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9093 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9097 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9101 * it's a duplicate "local VAR" declaration, do nothing
9108 lvp = ckzalloc(sizeof(*lvp));
9109 if (LONE_DASH(name)) {
9111 p = ckmalloc(sizeof(optlist));
9112 lvp->text = memcpy(p, optlist, sizeof(optlist));
9115 vpp = hashvar(name);
9116 vp = *findvar(vpp, name);
9118 /* variable did not exist yet */
9120 setvareq(name, VSTRFIXED);
9122 setvar(name, NULL, VSTRFIXED);
9123 vp = *vpp; /* the new variable */
9124 lvp->flags = VUNSET;
9126 lvp->text = vp->var_text;
9127 lvp->flags = vp->flags;
9128 /* make sure neither "struct var" nor string gets freed
9129 * during (un)setting:
9131 vp->flags |= VSTRFIXED|VTEXTFIXED;
9135 /* "local VAR" unsets VAR: */
9136 setvar0(name, NULL);
9140 lvp->next = localvars;
9146 * The "local" command.
9148 static int FAST_FUNC
9149 localcmd(int argc UNUSED_PARAM, char **argv)
9154 ash_msg_and_raise_error("not in a function");
9157 while ((name = *argv++) != NULL) {
9163 static int FAST_FUNC
9164 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9169 static int FAST_FUNC
9170 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9175 static int FAST_FUNC
9176 execcmd(int argc UNUSED_PARAM, char **argv)
9179 iflag = 0; /* exit on error */
9182 /* We should set up signals for "exec CMD"
9183 * the same way as for "CMD" without "exec".
9184 * But optschanged->setinteractive->setsignal
9185 * still thought we are a root shell. Therefore, for example,
9186 * SIGQUIT is still set to IGN. Fix it:
9190 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9191 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9192 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9194 shellexec(argv + 1, pathval(), 0);
9201 * The return command.
9203 static int FAST_FUNC
9204 returncmd(int argc UNUSED_PARAM, char **argv)
9207 * If called outside a function, do what ksh does;
9208 * skip the rest of the file.
9210 evalskip = SKIPFUNC;
9211 return argv[1] ? number(argv[1]) : exitstatus;
9214 /* Forward declarations for builtintab[] */
9215 static int breakcmd(int, char **) FAST_FUNC;
9216 static int dotcmd(int, char **) FAST_FUNC;
9217 static int evalcmd(int, char **, int) FAST_FUNC;
9218 static int exitcmd(int, char **) FAST_FUNC;
9219 static int exportcmd(int, char **) FAST_FUNC;
9220 #if ENABLE_ASH_GETOPTS
9221 static int getoptscmd(int, char **) FAST_FUNC;
9224 static int helpcmd(int, char **) FAST_FUNC;
9227 static int historycmd(int, char **) FAST_FUNC;
9229 #if ENABLE_SH_MATH_SUPPORT
9230 static int letcmd(int, char **) FAST_FUNC;
9232 static int readcmd(int, char **) FAST_FUNC;
9233 static int setcmd(int, char **) FAST_FUNC;
9234 static int shiftcmd(int, char **) FAST_FUNC;
9235 static int timescmd(int, char **) FAST_FUNC;
9236 static int trapcmd(int, char **) FAST_FUNC;
9237 static int umaskcmd(int, char **) FAST_FUNC;
9238 static int unsetcmd(int, char **) FAST_FUNC;
9239 static int ulimitcmd(int, char **) FAST_FUNC;
9241 #define BUILTIN_NOSPEC "0"
9242 #define BUILTIN_SPECIAL "1"
9243 #define BUILTIN_REGULAR "2"
9244 #define BUILTIN_SPEC_REG "3"
9245 #define BUILTIN_ASSIGN "4"
9246 #define BUILTIN_SPEC_ASSG "5"
9247 #define BUILTIN_REG_ASSG "6"
9248 #define BUILTIN_SPEC_REG_ASSG "7"
9250 /* Stubs for calling non-FAST_FUNC's */
9251 #if ENABLE_ASH_BUILTIN_ECHO
9252 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9254 #if ENABLE_ASH_BUILTIN_PRINTF
9255 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9257 #if ENABLE_ASH_BUILTIN_TEST
9258 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9261 /* Keep these in proper order since it is searched via bsearch() */
9262 static const struct builtincmd builtintab[] = {
9263 { BUILTIN_SPEC_REG "." , dotcmd },
9264 { BUILTIN_SPEC_REG ":" , truecmd },
9265 #if ENABLE_ASH_BUILTIN_TEST
9266 { BUILTIN_REGULAR "[" , testcmd },
9267 #if ENABLE_ASH_BASH_COMPAT
9268 { BUILTIN_REGULAR "[[" , testcmd },
9271 #if ENABLE_ASH_ALIAS
9272 { BUILTIN_REG_ASSG "alias" , aliascmd },
9275 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9277 { BUILTIN_SPEC_REG "break" , breakcmd },
9278 { BUILTIN_REGULAR "cd" , cdcmd },
9279 { BUILTIN_NOSPEC "chdir" , cdcmd },
9280 #if ENABLE_ASH_CMDCMD
9281 { BUILTIN_REGULAR "command" , commandcmd },
9283 { BUILTIN_SPEC_REG "continue", breakcmd },
9284 #if ENABLE_ASH_BUILTIN_ECHO
9285 { BUILTIN_REGULAR "echo" , echocmd },
9287 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9288 { BUILTIN_SPEC_REG "exec" , execcmd },
9289 { BUILTIN_SPEC_REG "exit" , exitcmd },
9290 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9291 { BUILTIN_REGULAR "false" , falsecmd },
9293 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9295 #if ENABLE_ASH_GETOPTS
9296 { BUILTIN_REGULAR "getopts" , getoptscmd },
9298 { BUILTIN_NOSPEC "hash" , hashcmd },
9300 { BUILTIN_NOSPEC "help" , helpcmd },
9303 { BUILTIN_NOSPEC "history" , historycmd },
9306 { BUILTIN_REGULAR "jobs" , jobscmd },
9307 { BUILTIN_REGULAR "kill" , killcmd },
9309 #if ENABLE_SH_MATH_SUPPORT
9310 { BUILTIN_NOSPEC "let" , letcmd },
9312 { BUILTIN_ASSIGN "local" , localcmd },
9313 #if ENABLE_ASH_BUILTIN_PRINTF
9314 { BUILTIN_REGULAR "printf" , printfcmd },
9316 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9317 { BUILTIN_REGULAR "read" , readcmd },
9318 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9319 { BUILTIN_SPEC_REG "return" , returncmd },
9320 { BUILTIN_SPEC_REG "set" , setcmd },
9321 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9322 #if ENABLE_ASH_BASH_COMPAT
9323 { BUILTIN_SPEC_REG "source" , dotcmd },
9325 #if ENABLE_ASH_BUILTIN_TEST
9326 { BUILTIN_REGULAR "test" , testcmd },
9328 { BUILTIN_SPEC_REG "times" , timescmd },
9329 { BUILTIN_SPEC_REG "trap" , trapcmd },
9330 { BUILTIN_REGULAR "true" , truecmd },
9331 { BUILTIN_NOSPEC "type" , typecmd },
9332 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9333 { BUILTIN_REGULAR "umask" , umaskcmd },
9334 #if ENABLE_ASH_ALIAS
9335 { BUILTIN_REGULAR "unalias" , unaliascmd },
9337 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9338 { BUILTIN_REGULAR "wait" , waitcmd },
9341 /* Should match the above table! */
9342 #define COMMANDCMD (builtintab + \
9344 /* [ */ 1 * ENABLE_ASH_BUILTIN_TEST + \
9345 /* [[ */ 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9346 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9347 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9348 /* break cd cddir */ 3)
9349 #define EVALCMD (COMMANDCMD + \
9350 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9351 /* continue */ 1 + \
9352 /* echo */ 1 * ENABLE_ASH_BUILTIN_ECHO + \
9354 #define EXECCMD (EVALCMD + \
9358 * Search the table of builtin commands.
9361 pstrcmp1(const void *a, const void *b)
9363 return strcmp((char*)a, *(char**)b + 1);
9365 static struct builtincmd *
9366 find_builtin(const char *name)
9368 struct builtincmd *bp;
9371 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9378 * Execute a simple command.
9381 isassignment(const char *p)
9383 const char *q = endofname(p);
9388 static int FAST_FUNC
9389 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9391 /* Preserve exitstatus of a previous possible redirection
9392 * as POSIX mandates */
9393 return back_exitstatus;
9396 evalcommand(union node *cmd, int flags)
9398 static const struct builtincmd null_bltin = {
9399 "\0\0", bltincmd /* why three NULs? */
9401 struct stackmark smark;
9403 struct arglist arglist;
9404 struct arglist varlist;
9407 const struct strlist *sp;
9408 struct cmdentry cmdentry;
9415 struct builtincmd *bcmd;
9416 smallint cmd_is_exec;
9417 smallint pseudovarflag = 0;
9419 /* First expand the arguments. */
9420 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9421 setstackmark(&smark);
9422 back_exitstatus = 0;
9424 cmdentry.cmdtype = CMDBUILTIN;
9425 cmdentry.u.cmd = &null_bltin;
9426 varlist.lastp = &varlist.list;
9427 *varlist.lastp = NULL;
9428 arglist.lastp = &arglist.list;
9429 *arglist.lastp = NULL;
9432 if (cmd->ncmd.args) {
9433 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9434 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9437 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9438 struct strlist **spp;
9440 spp = arglist.lastp;
9441 if (pseudovarflag && isassignment(argp->narg.text))
9442 expandarg(argp, &arglist, EXP_VARTILDE);
9444 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9446 for (sp = *spp; sp; sp = sp->next)
9450 /* Reserve one extra spot at the front for shellexec. */
9451 nargv = stalloc(sizeof(char *) * (argc + 2));
9453 for (sp = arglist.list; sp; sp = sp->next) {
9454 TRACE(("evalcommand arg: %s\n", sp->text));
9455 *nargv++ = sp->text;
9460 if (iflag && funcnest == 0 && argc > 0)
9461 lastarg = nargv[-1];
9464 expredir(cmd->ncmd.redirect);
9465 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9467 path = vpath.var_text;
9468 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9469 struct strlist **spp;
9472 spp = varlist.lastp;
9473 expandarg(argp, &varlist, EXP_VARTILDE);
9476 * Modify the command lookup path, if a PATH= assignment
9480 if (varcmp(p, path) == 0)
9484 /* Print the command if xflag is set. */
9487 const char *p = " %s" + 1;
9489 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9491 for (n = 0; n < 2; n++) {
9493 fdprintf(preverrout_fd, p, sp->text);
9499 safe_write(preverrout_fd, "\n", 1);
9505 /* Now locate the command. */
9507 int cmd_flag = DO_ERR;
9508 #if ENABLE_ASH_CMDCMD
9509 const char *oldpath = path + 5;
9513 find_command(argv[0], &cmdentry, cmd_flag, path);
9514 if (cmdentry.cmdtype == CMDUNKNOWN) {
9515 flush_stdout_stderr();
9520 /* implement bltin and command here */
9521 if (cmdentry.cmdtype != CMDBUILTIN)
9524 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9525 if (cmdentry.u.cmd == EXECCMD)
9527 #if ENABLE_ASH_CMDCMD
9528 if (cmdentry.u.cmd == COMMANDCMD) {
9530 nargv = parse_command_args(argv, &path);
9533 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9534 * nargv => "PROG". path is updated if -p.
9536 argc -= nargv - argv;
9538 cmd_flag |= DO_NOFUNC;
9546 /* We have a redirection error. */
9548 raise_exception(EXERROR);
9550 exitstatus = status;
9554 /* Execute the command. */
9555 switch (cmdentry.cmdtype) {
9558 #if ENABLE_FEATURE_SH_NOFORK
9559 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9560 * around run_nofork_applet() call.
9561 * (2) Should this check also be done in forkshell()?
9562 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9564 /* find_command() encodes applet_no as (-2 - applet_no) */
9565 int applet_no = (- cmdentry.u.index - 2);
9566 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9567 listsetvar(varlist.list, VEXPORT|VSTACK);
9568 /* run <applet>_main() */
9569 status = run_nofork_applet(applet_no, argv);
9573 /* Can we avoid forking off? For example, very last command
9574 * in a script or a subshell does not need forking,
9575 * we can just exec it.
9577 if (!(flags & EV_EXIT) || may_have_traps) {
9578 /* No, forking off a child is necessary */
9580 jp = makejob(/*cmd,*/ 1);
9581 if (forkshell(jp, cmd, FORK_FG) != 0) {
9583 status = waitforjob(jp);
9585 TRACE(("forked child exited with %d\n", status));
9590 /* fall through to exec'ing external program */
9592 listsetvar(varlist.list, VEXPORT|VSTACK);
9593 shellexec(argv, path, cmdentry.u.index);
9597 cmdenviron = varlist.list;
9599 struct strlist *list = cmdenviron;
9601 if (spclbltin > 0 || argc == 0) {
9603 if (cmd_is_exec && argc > 1)
9606 listsetvar(list, i);
9608 /* Tight loop with builtins only:
9609 * "while kill -0 $child; do true; done"
9610 * will never exit even if $child died, unless we do this
9611 * to reap the zombie and make kill detect that it's gone: */
9612 dowait(DOWAIT_NONBLOCK, NULL);
9614 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9615 if (exception_type == EXERROR && spclbltin <= 0) {
9620 longjmp(exception_handler->loc, 1);
9625 listsetvar(varlist.list, 0);
9626 /* See above for the rationale */
9627 dowait(DOWAIT_NONBLOCK, NULL);
9628 if (evalfun(cmdentry.u.func, argc, argv, flags))
9631 status = exitstatus;
9636 if (cmd->ncmd.redirect)
9637 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9639 /* dsl: I think this is intended to be used to support
9640 * '_' in 'vi' command mode during line editing...
9641 * However I implemented that within libedit itself.
9643 setvar0("_", lastarg);
9645 popstackmark(&smark);
9651 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9653 char *volatile savecmdname;
9654 struct jmploc *volatile savehandler;
9655 struct jmploc jmploc;
9659 savecmdname = commandname;
9660 savehandler = exception_handler;
9661 i = setjmp(jmploc.loc);
9664 exception_handler = &jmploc;
9665 commandname = argv[0];
9667 optptr = NULL; /* initialize nextopt */
9669 status = evalcmd(argc, argv, flags);
9671 status = (*cmd->builtin)(argc, argv);
9672 flush_stdout_stderr();
9673 status |= ferror(stdout);
9674 exitstatus = status;
9677 commandname = savecmdname;
9678 exception_handler = savehandler;
9684 goodname(const char *p)
9686 return endofname(p)[0] == '\0';
9691 * Search for a command. This is called before we fork so that the
9692 * location of the command will be available in the parent as well as
9693 * the child. The check for "goodname" is an overly conservative
9694 * check that the name will not be subject to expansion.
9697 prehash(union node *n)
9699 struct cmdentry entry;
9701 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9702 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9706 /* ============ Builtin commands
9708 * Builtin commands whose functions are closely tied to evaluation
9709 * are implemented here.
9713 * Handle break and continue commands. Break, continue, and return are
9714 * all handled by setting the evalskip flag. The evaluation routines
9715 * above all check this flag, and if it is set they start skipping
9716 * commands rather than executing them. The variable skipcount is
9717 * the number of loops to break/continue, or the number of function
9718 * levels to return. (The latter is always 1.) It should probably
9719 * be an error to break out of more loops than exist, but it isn't
9720 * in the standard shell so we don't make it one here.
9722 static int FAST_FUNC
9723 breakcmd(int argc UNUSED_PARAM, char **argv)
9725 int n = argv[1] ? number(argv[1]) : 1;
9728 ash_msg_and_raise_error(msg_illnum, argv[1]);
9732 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9740 * This implements the input routines used by the parser.
9744 INPUT_PUSH_FILE = 1,
9745 INPUT_NOFILE_OK = 2,
9748 static smallint checkkwd;
9749 /* values of checkkwd variable */
9750 #define CHKALIAS 0x1
9755 * Push a string back onto the input at this current parsefile level.
9756 * We handle aliases this way.
9758 #if !ENABLE_ASH_ALIAS
9759 #define pushstring(s, ap) pushstring(s)
9762 pushstring(char *s, struct alias *ap)
9769 if (g_parsefile->strpush) {
9770 sp = ckzalloc(sizeof(*sp));
9771 sp->prev = g_parsefile->strpush;
9773 sp = &(g_parsefile->basestrpush);
9775 g_parsefile->strpush = sp;
9776 sp->prev_string = g_parsefile->next_to_pgetc;
9777 sp->prev_left_in_line = g_parsefile->left_in_line;
9778 sp->unget = g_parsefile->unget;
9779 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9780 #if ENABLE_ASH_ALIAS
9783 ap->flag |= ALIASINUSE;
9787 g_parsefile->next_to_pgetc = s;
9788 g_parsefile->left_in_line = len;
9789 g_parsefile->unget = 0;
9796 struct strpush *sp = g_parsefile->strpush;
9799 #if ENABLE_ASH_ALIAS
9801 if (g_parsefile->next_to_pgetc[-1] == ' '
9802 || g_parsefile->next_to_pgetc[-1] == '\t'
9804 checkkwd |= CHKALIAS;
9806 if (sp->string != sp->ap->val) {
9809 sp->ap->flag &= ~ALIASINUSE;
9810 if (sp->ap->flag & ALIASDEAD) {
9811 unalias(sp->ap->name);
9815 g_parsefile->next_to_pgetc = sp->prev_string;
9816 g_parsefile->left_in_line = sp->prev_left_in_line;
9817 g_parsefile->unget = sp->unget;
9818 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
9819 g_parsefile->strpush = sp->prev;
9820 if (sp != &(g_parsefile->basestrpush))
9829 char *buf = g_parsefile->buf;
9831 g_parsefile->next_to_pgetc = buf;
9832 #if ENABLE_FEATURE_EDITING
9834 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9835 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9838 # if ENABLE_ASH_IDLE_TIMEOUT
9840 const char *tmout_var = lookupvar("TMOUT");
9842 timeout = atoi(tmout_var) * 1000;
9848 # if ENABLE_FEATURE_TAB_COMPLETION
9849 line_input_state->path_lookup = pathval();
9851 reinit_unicode_for_ash();
9852 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9854 /* Ctrl+C pressed */
9865 /* Ctrl+D pressed */
9868 # if ENABLE_ASH_IDLE_TIMEOUT
9869 else if (errno == EAGAIN && timeout > 0) {
9870 puts("\007timed out waiting for input: auto-logout");
9877 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9880 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9882 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9883 int flags = fcntl(0, F_GETFL);
9884 if (flags >= 0 && (flags & O_NONBLOCK)) {
9885 flags &= ~O_NONBLOCK;
9886 if (fcntl(0, F_SETFL, flags) >= 0) {
9887 out2str("sh: turning off NDELAY mode\n");
9898 * Refill the input buffer and return the next input character:
9900 * 1) If a string was pushed back on the input, pop it;
9901 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9902 * or we are reading from a string so we can't refill the buffer,
9904 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9905 * 4) Process input up to the next newline, deleting nul characters.
9907 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9908 #define pgetc_debug(...) ((void)0)
9909 static int pgetc(void);
9916 if (g_parsefile->strpush) {
9917 #if ENABLE_ASH_ALIAS
9918 if (g_parsefile->left_in_line == -1
9919 && g_parsefile->strpush->ap
9920 && g_parsefile->next_to_pgetc[-1] != ' '
9921 && g_parsefile->next_to_pgetc[-1] != '\t'
9923 pgetc_debug("preadbuffer PEOA");
9930 /* on both branches above g_parsefile->left_in_line < 0.
9931 * "pgetc" needs refilling.
9934 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9935 * pungetc() may increment it a few times.
9936 * Assuming it won't increment it to less than -90.
9938 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9939 pgetc_debug("preadbuffer PEOF1");
9940 /* even in failure keep left_in_line and next_to_pgetc
9941 * in lock step, for correct multi-layer pungetc.
9942 * left_in_line was decremented before preadbuffer(),
9943 * must inc next_to_pgetc: */
9944 g_parsefile->next_to_pgetc++;
9948 more = g_parsefile->left_in_buffer;
9950 flush_stdout_stderr();
9954 /* don't try reading again */
9955 g_parsefile->left_in_line = -99;
9956 pgetc_debug("preadbuffer PEOF2");
9957 g_parsefile->next_to_pgetc++;
9962 /* Find out where's the end of line.
9963 * Set g_parsefile->left_in_line
9964 * and g_parsefile->left_in_buffer acordingly.
9965 * NUL chars are deleted.
9967 q = g_parsefile->next_to_pgetc;
9975 memmove(q, q + 1, more);
9979 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9985 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9986 if (g_parsefile->left_in_line < 0)
9991 g_parsefile->left_in_buffer = more;
9996 out2str(g_parsefile->next_to_pgetc);
10000 pgetc_debug("preadbuffer at %d:%p'%s'",
10001 g_parsefile->left_in_line,
10002 g_parsefile->next_to_pgetc,
10003 g_parsefile->next_to_pgetc);
10004 return (unsigned char)*g_parsefile->next_to_pgetc++;
10010 g_parsefile->linno++;
10011 setprompt_if(doprompt, 2);
10016 g_parsefile->linno++;
10017 needprompt = doprompt;
10025 pgetc_debug("pgetc at %d:%p'%s'",
10026 g_parsefile->left_in_line,
10027 g_parsefile->next_to_pgetc,
10028 g_parsefile->next_to_pgetc);
10029 if (g_parsefile->unget)
10030 return g_parsefile->lastc[--g_parsefile->unget];
10032 if (--g_parsefile->left_in_line >= 0)
10033 c = (signed char)*g_parsefile->next_to_pgetc++;
10037 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10038 g_parsefile->lastc[0] = c;
10043 #if ENABLE_ASH_ALIAS
10045 pgetc_without_PEOA(void)
10049 pgetc_debug("pgetc at %d:%p'%s'",
10050 g_parsefile->left_in_line,
10051 g_parsefile->next_to_pgetc,
10052 g_parsefile->next_to_pgetc);
10054 } while (c == PEOA);
10058 # define pgetc_without_PEOA() pgetc()
10062 * Read a line from the script.
10065 pfgets(char *line, int len)
10071 while (--nleft > 0) {
10072 c = pgetc_without_PEOA();
10087 * Undo a call to pgetc. Only two characters may be pushed back.
10088 * PEOF may be pushed back.
10093 g_parsefile->unget++;
10096 /* This one eats backslash+newline */
10102 while ((c = pgetc()) == '\\') {
10103 if (pgetc() != '\n') {
10115 * To handle the "." command, a stack of input files is used. Pushfile
10116 * adds a new entry to the stack and popfile restores the previous level.
10121 struct parsefile *pf;
10123 pf = ckzalloc(sizeof(*pf));
10124 pf->prev = g_parsefile;
10126 /*pf->strpush = NULL; - ckzalloc did it */
10127 /*pf->basestrpush.prev = NULL;*/
10135 struct parsefile *pf = g_parsefile;
10141 if (pf->pf_fd >= 0)
10144 while (pf->strpush)
10146 g_parsefile = pf->prev;
10152 * Return to top level.
10157 while (g_parsefile != &basepf)
10162 * Close the file(s) that the shell is reading commands from. Called
10163 * after a fork is done.
10169 if (g_parsefile->pf_fd > 0) {
10170 close(g_parsefile->pf_fd);
10171 g_parsefile->pf_fd = 0;
10176 * Like setinputfile, but takes an open file descriptor. Call this with
10180 setinputfd(int fd, int push)
10184 g_parsefile->buf = NULL;
10186 g_parsefile->pf_fd = fd;
10187 if (g_parsefile->buf == NULL)
10188 g_parsefile->buf = ckmalloc(IBUFSIZ);
10189 g_parsefile->left_in_buffer = 0;
10190 g_parsefile->left_in_line = 0;
10191 g_parsefile->linno = 1;
10195 * Set the input to take input from a file. If push is set, push the
10196 * old input onto the stack first.
10199 setinputfile(const char *fname, int flags)
10204 fd = open(fname, O_RDONLY);
10206 if (flags & INPUT_NOFILE_OK)
10209 ash_msg_and_raise_error("can't open '%s'", fname);
10214 close_on_exec_on(fd);
10215 setinputfd(fd, flags & INPUT_PUSH_FILE);
10222 * Like setinputfile, but takes input from a string.
10225 setinputstring(char *string)
10229 g_parsefile->next_to_pgetc = string;
10230 g_parsefile->left_in_line = strlen(string);
10231 g_parsefile->buf = NULL;
10232 g_parsefile->linno = 1;
10238 * Routines to check for mail.
10241 #if ENABLE_ASH_MAIL
10243 /* Hash of mtimes of mailboxes */
10244 static unsigned mailtime_hash;
10245 /* Set if MAIL or MAILPATH is changed. */
10246 static smallint mail_var_path_changed;
10249 * Print appropriate message(s) if mail has arrived.
10250 * If mail_var_path_changed is set,
10251 * then the value of MAIL has mail_var_path_changed,
10252 * so we just update the values.
10261 struct stackmark smark;
10264 setstackmark(&smark);
10265 mpath = mpathset() ? mpathval() : mailval();
10268 p = path_advance(&mpath, nullstr);
10273 for (q = p; *q; q++)
10279 q[-1] = '\0'; /* delete trailing '/' */
10280 if (stat(p, &statb) < 0) {
10283 /* Very simplistic "hash": just a sum of all mtimes */
10284 new_hash += (unsigned)statb.st_mtime;
10286 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10287 if (mailtime_hash != 0)
10288 out2str("you have mail\n");
10289 mailtime_hash = new_hash;
10291 mail_var_path_changed = 0;
10292 popstackmark(&smark);
10295 static void FAST_FUNC
10296 changemail(const char *val UNUSED_PARAM)
10298 mail_var_path_changed = 1;
10301 #endif /* ASH_MAIL */
10304 /* ============ ??? */
10307 * Set the shell parameters.
10310 setparam(char **argv)
10316 for (nparam = 0; argv[nparam]; nparam++)
10318 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10320 *ap++ = ckstrdup(*argv++);
10323 freeparam(&shellparam);
10324 shellparam.malloced = 1;
10325 shellparam.nparam = nparam;
10326 shellparam.p = newparam;
10327 #if ENABLE_ASH_GETOPTS
10328 shellparam.optind = 1;
10329 shellparam.optoff = -1;
10334 * Process shell options. The global variable argptr contains a pointer
10335 * to the argument list; we advance it past the options.
10337 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10338 * For a non-interactive shell, an error condition encountered
10339 * by a special built-in ... shall cause the shell to write a diagnostic message
10340 * to standard error and exit as shown in the following table:
10341 * Error Special Built-In
10343 * Utility syntax error (option or operand error) Shall exit
10345 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10346 * we see that bash does not do that (set "finishes" with error code 1 instead,
10347 * and shell continues), and people rely on this behavior!
10349 * set -o barfoo 2>/dev/null
10352 * Oh well. Let's mimic that.
10355 plus_minus_o(char *name, int val)
10360 for (i = 0; i < NOPTS; i++) {
10361 if (strcmp(name, optnames(i)) == 0) {
10366 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10369 for (i = 0; i < NOPTS; i++) {
10371 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10373 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10379 setoption(int flag, int val)
10383 for (i = 0; i < NOPTS; i++) {
10384 if (optletters(i) == flag) {
10389 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10393 options(int cmdline)
10401 while ((p = *argptr) != NULL) {
10403 if (c != '-' && c != '+')
10406 val = 0; /* val = 0 if c == '+' */
10409 if (p[0] == '\0' || LONE_DASH(p)) {
10411 /* "-" means turn off -x and -v */
10414 /* "--" means reset params */
10415 else if (*argptr == NULL)
10418 break; /* "-" or "--" terminates options */
10421 /* first char was + or - */
10422 while ((c = *p++) != '\0') {
10423 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10424 if (c == 'c' && cmdline) {
10425 minusc = p; /* command is after shell args */
10426 } else if (c == 'o') {
10427 if (plus_minus_o(*argptr, val)) {
10428 /* it already printed err message */
10429 return 1; /* error */
10433 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10435 /* bash does not accept +-login, we also won't */
10436 } else if (cmdline && val && (c == '-')) { /* long options */
10437 if (strcmp(p, "login") == 0)
10449 * The shift builtin command.
10451 static int FAST_FUNC
10452 shiftcmd(int argc UNUSED_PARAM, char **argv)
10459 n = number(argv[1]);
10460 if (n > shellparam.nparam)
10461 n = 0; /* bash compat, was = shellparam.nparam; */
10463 shellparam.nparam -= n;
10464 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10465 if (shellparam.malloced)
10468 ap2 = shellparam.p;
10469 while ((*ap2++ = *ap1++) != NULL)
10471 #if ENABLE_ASH_GETOPTS
10472 shellparam.optind = 1;
10473 shellparam.optoff = -1;
10480 * POSIX requires that 'set' (but not export or readonly) output the
10481 * variables in lexicographic order - by the locale's collating order (sigh).
10482 * Maybe we could keep them in an ordered balanced binary tree
10483 * instead of hashed lists.
10484 * For now just roll 'em through qsort for printing...
10487 showvars(const char *sep_prefix, int on, int off)
10490 char **ep, **epend;
10492 ep = listvars(on, off, &epend);
10493 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10495 sep = *sep_prefix ? " " : sep_prefix;
10497 for (; ep < epend; ep++) {
10501 p = strchrnul(*ep, '=');
10504 q = single_quote(++p);
10505 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10511 * The set command builtin.
10513 static int FAST_FUNC
10514 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10519 return showvars(nullstr, 0, VUNSET);
10522 retval = options(/*cmdline:*/ 0);
10523 if (retval == 0) { /* if no parse error... */
10525 if (*argptr != NULL) {
10533 #if ENABLE_ASH_RANDOM_SUPPORT
10534 static void FAST_FUNC
10535 change_random(const char *value)
10539 if (value == NULL) {
10540 /* "get", generate */
10541 t = next_random(&random_gen);
10542 /* set without recursion */
10543 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10544 vrandom.flags &= ~VNOFUNC;
10547 t = strtoul(value, NULL, 10);
10548 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10553 #if ENABLE_ASH_GETOPTS
10555 getopts(char *optstr, char *optvar, char **optfirst)
10562 int ind = shellparam.optind;
10563 int off = shellparam.optoff;
10567 shellparam.optind = -1;
10568 optnext = optfirst + ind - 1;
10570 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10573 p = optnext[-1] + off;
10574 if (p == NULL || *p == '\0') {
10575 /* Current word is done, advance */
10577 if (p == NULL || *p != '-' || *++p == '\0') {
10584 if (LONE_DASH(p)) /* check for "--" */
10589 for (q = optstr; *q != c;) {
10591 if (optstr[0] == ':') {
10593 /*sbuf[1] = '\0'; - already is */
10594 setvar0("OPTARG", sbuf);
10596 fprintf(stderr, "Illegal option -%c\n", c);
10597 unsetvar("OPTARG");
10607 if (*p == '\0' && (p = *optnext) == NULL) {
10608 if (optstr[0] == ':') {
10610 /*sbuf[1] = '\0'; - already is */
10611 setvar0("OPTARG", sbuf);
10614 fprintf(stderr, "No arg for -%c option\n", c);
10615 unsetvar("OPTARG");
10623 setvar0("OPTARG", p);
10626 setvar0("OPTARG", nullstr);
10628 ind = optnext - optfirst + 1;
10629 setvar("OPTIND", itoa(ind), VNOFUNC);
10631 /*sbuf[1] = '\0'; - already is */
10632 setvar0(optvar, sbuf);
10634 shellparam.optoff = p ? p - *(optnext - 1) : -1;
10635 shellparam.optind = ind;
10641 * The getopts builtin. Shellparam.optnext points to the next argument
10642 * to be processed. Shellparam.optptr points to the next character to
10643 * be processed in the current argument. If shellparam.optnext is NULL,
10644 * then it's the first time getopts has been called.
10646 static int FAST_FUNC
10647 getoptscmd(int argc, char **argv)
10652 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10654 optbase = shellparam.p;
10655 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
10656 shellparam.optind = 1;
10657 shellparam.optoff = -1;
10660 optbase = &argv[3];
10661 if ((unsigned)shellparam.optind > argc - 2) {
10662 shellparam.optind = 1;
10663 shellparam.optoff = -1;
10667 return getopts(argv[1], argv[2], optbase);
10669 #endif /* ASH_GETOPTS */
10672 /* ============ Shell parser */
10675 struct heredoc *next; /* next here document in list */
10676 union node *here; /* redirection node */
10677 char *eofmark; /* string indicating end of input */
10678 smallint striptabs; /* if set, strip leading tabs */
10681 static smallint tokpushback; /* last token pushed back */
10682 static smallint quoteflag; /* set if (part of) last token was quoted */
10683 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10684 static struct heredoc *heredoclist; /* list of here documents to read */
10685 static char *wordtext; /* text of last word returned by readtoken */
10686 static struct nodelist *backquotelist;
10687 static union node *redirnode;
10688 static struct heredoc *heredoc;
10690 static const char *
10691 tokname(char *buf, int tok)
10694 return tokname_array[tok];
10695 sprintf(buf, "\"%s\"", tokname_array[tok]);
10699 /* raise_error_unexpected_syntax:
10700 * Called when an unexpected token is read during the parse. The argument
10701 * is the token that is expected, or -1 if more than one type of token can
10702 * occur at this point.
10704 static void raise_error_unexpected_syntax(int) NORETURN;
10706 raise_error_unexpected_syntax(int token)
10712 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10714 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10715 raise_error_syntax(msg);
10719 #define EOFMARKLEN 79
10721 /* parsing is heavily cross-recursive, need these forward decls */
10722 static union node *andor(void);
10723 static union node *pipeline(void);
10724 static union node *parse_command(void);
10725 static void parseheredoc(void);
10726 static int peektoken(void);
10727 static int readtoken(void);
10729 static union node *
10732 union node *n1, *n2, *n3;
10737 switch (peektoken()) {
10745 if (!n1 && (nlflag & 1))
10751 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10752 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
10758 if (tok == TBACKGND) {
10759 if (n2->type == NPIPE) {
10760 n2->npipe.pipe_backgnd = 1;
10762 if (n2->type != NREDIR) {
10763 n3 = stzalloc(sizeof(struct nredir));
10765 /*n3->nredir.redirect = NULL; - stzalloc did it */
10768 n2->type = NBACKGND;
10774 n3 = stzalloc(sizeof(struct nbinary));
10776 n3->nbinary.ch1 = n1;
10777 n3->nbinary.ch2 = n2;
10790 raise_error_unexpected_syntax(-1);
10797 static union node *
10800 union node *n1, *n2, *n3;
10808 } else if (t == TOR) {
10814 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10816 n3 = stzalloc(sizeof(struct nbinary));
10818 n3->nbinary.ch1 = n1;
10819 n3->nbinary.ch2 = n2;
10824 static union node *
10827 union node *n1, *n2, *pipenode;
10828 struct nodelist *lp, *prev;
10832 TRACE(("pipeline: entered\n"));
10833 if (readtoken() == TNOT) {
10835 checkkwd = CHKKWD | CHKALIAS;
10838 n1 = parse_command();
10839 if (readtoken() == TPIPE) {
10840 pipenode = stzalloc(sizeof(struct npipe));
10841 pipenode->type = NPIPE;
10842 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10843 lp = stzalloc(sizeof(struct nodelist));
10844 pipenode->npipe.cmdlist = lp;
10848 lp = stzalloc(sizeof(struct nodelist));
10849 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10850 lp->n = parse_command();
10852 } while (readtoken() == TPIPE);
10858 n2 = stzalloc(sizeof(struct nnot));
10866 static union node *
10871 n = stzalloc(sizeof(struct narg));
10873 /*n->narg.next = NULL; - stzalloc did it */
10874 n->narg.text = wordtext;
10875 n->narg.backquote = backquotelist;
10880 fixredir(union node *n, const char *text, int err)
10884 TRACE(("Fix redir %s %d\n", text, err));
10886 n->ndup.vname = NULL;
10888 fd = bb_strtou(text, NULL, 10);
10889 if (!errno && fd >= 0)
10890 n->ndup.dupfd = fd;
10891 else if (LONE_DASH(text))
10892 n->ndup.dupfd = -1;
10895 raise_error_syntax("bad fd number");
10896 n->ndup.vname = makename();
10901 * Returns true if the text contains nothing to expand (no dollar signs
10905 noexpand(const char *text)
10909 while ((c = *text++) != '\0') {
10910 if (c == CTLQUOTEMARK)
10914 else if (SIT(c, BASESYNTAX) == CCTL)
10923 union node *n = redirnode;
10925 if (readtoken() != TWORD)
10926 raise_error_unexpected_syntax(-1);
10927 if (n->type == NHERE) {
10928 struct heredoc *here = heredoc;
10932 if (quoteflag == 0)
10934 TRACE(("Here document %d\n", n->type));
10935 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10936 raise_error_syntax("illegal eof marker for << redirection");
10937 rmescapes(wordtext, 0);
10938 here->eofmark = wordtext;
10940 if (heredoclist == NULL)
10941 heredoclist = here;
10943 for (p = heredoclist; p->next; p = p->next)
10947 } else if (n->type == NTOFD || n->type == NFROMFD) {
10948 fixredir(n, wordtext, 0);
10950 n->nfile.fname = makename();
10954 static union node *
10957 union node *args, **app;
10958 union node *n = NULL;
10959 union node *vars, **vpp;
10960 union node **rpp, *redir;
10962 #if ENABLE_ASH_BASH_COMPAT
10963 smallint double_brackets_flag = 0;
10964 smallint function_flag = 0;
10974 savecheckkwd = CHKALIAS;
10977 checkkwd = savecheckkwd;
10980 #if ENABLE_ASH_BASH_COMPAT
10982 if (peektoken() != TWORD)
10983 raise_error_unexpected_syntax(TWORD);
10986 case TAND: /* "&&" */
10987 case TOR: /* "||" */
10988 if (!double_brackets_flag) {
10992 wordtext = (char *) (t == TAND ? "-a" : "-o");
10995 n = stzalloc(sizeof(struct narg));
10997 /*n->narg.next = NULL; - stzalloc did it */
10998 n->narg.text = wordtext;
10999 #if ENABLE_ASH_BASH_COMPAT
11000 if (strcmp("[[", wordtext) == 0)
11001 double_brackets_flag = 1;
11002 else if (strcmp("]]", wordtext) == 0)
11003 double_brackets_flag = 0;
11005 n->narg.backquote = backquotelist;
11006 if (savecheckkwd && isassignment(wordtext)) {
11008 vpp = &n->narg.next;
11011 app = &n->narg.next;
11014 #if ENABLE_ASH_BASH_COMPAT
11015 if (function_flag) {
11016 checkkwd = CHKNL | CHKKWD;
11017 switch (peektoken()) {
11029 if (strcmp("[[", wordtext) == 0)
11033 raise_error_unexpected_syntax(-1);
11039 *rpp = n = redirnode;
11040 rpp = &n->nfile.next;
11041 parsefname(); /* read name of redirection file */
11044 IF_ASH_BASH_COMPAT(do_func:)
11045 if (args && app == &args->narg.next
11048 struct builtincmd *bcmd;
11051 /* We have a function */
11052 if (IF_ASH_BASH_COMPAT(!function_flag &&) readtoken() != TRP)
11053 raise_error_unexpected_syntax(TRP);
11054 name = n->narg.text;
11055 if (!goodname(name)
11056 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11058 raise_error_syntax("bad function name");
11061 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11062 n->narg.next = parse_command();
11065 IF_ASH_BASH_COMPAT(function_flag = 0;)
11076 n = stzalloc(sizeof(struct ncmd));
11078 n->ncmd.args = args;
11079 n->ncmd.assign = vars;
11080 n->ncmd.redirect = redir;
11084 static union node *
11085 parse_command(void)
11087 union node *n1, *n2;
11088 union node *ap, **app;
11089 union node *cp, **cpp;
11090 union node *redir, **rpp;
11097 switch (readtoken()) {
11099 raise_error_unexpected_syntax(-1);
11102 n1 = stzalloc(sizeof(struct nif));
11104 n1->nif.test = list(0);
11105 if (readtoken() != TTHEN)
11106 raise_error_unexpected_syntax(TTHEN);
11107 n1->nif.ifpart = list(0);
11109 while (readtoken() == TELIF) {
11110 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11111 n2 = n2->nif.elsepart;
11113 n2->nif.test = list(0);
11114 if (readtoken() != TTHEN)
11115 raise_error_unexpected_syntax(TTHEN);
11116 n2->nif.ifpart = list(0);
11118 if (lasttoken == TELSE)
11119 n2->nif.elsepart = list(0);
11121 n2->nif.elsepart = NULL;
11129 n1 = stzalloc(sizeof(struct nbinary));
11130 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11131 n1->nbinary.ch1 = list(0);
11134 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11135 got == TWORD ? wordtext : ""));
11136 raise_error_unexpected_syntax(TDO);
11138 n1->nbinary.ch2 = list(0);
11143 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11144 raise_error_syntax("bad for loop variable");
11145 n1 = stzalloc(sizeof(struct nfor));
11147 n1->nfor.var = wordtext;
11148 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11149 if (readtoken() == TIN) {
11151 while (readtoken() == TWORD) {
11152 n2 = stzalloc(sizeof(struct narg));
11154 /*n2->narg.next = NULL; - stzalloc did it */
11155 n2->narg.text = wordtext;
11156 n2->narg.backquote = backquotelist;
11158 app = &n2->narg.next;
11161 n1->nfor.args = ap;
11162 if (lasttoken != TNL && lasttoken != TSEMI)
11163 raise_error_unexpected_syntax(-1);
11165 n2 = stzalloc(sizeof(struct narg));
11167 /*n2->narg.next = NULL; - stzalloc did it */
11168 n2->narg.text = (char *)dolatstr;
11169 /*n2->narg.backquote = NULL;*/
11170 n1->nfor.args = n2;
11172 * Newline or semicolon here is optional (but note
11173 * that the original Bourne shell only allowed NL).
11175 if (lasttoken != TSEMI)
11178 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11179 if (readtoken() != TDO)
11180 raise_error_unexpected_syntax(TDO);
11181 n1->nfor.body = list(0);
11185 n1 = stzalloc(sizeof(struct ncase));
11187 if (readtoken() != TWORD)
11188 raise_error_unexpected_syntax(TWORD);
11189 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11191 /*n2->narg.next = NULL; - stzalloc did it */
11192 n2->narg.text = wordtext;
11193 n2->narg.backquote = backquotelist;
11194 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11195 if (readtoken() != TIN)
11196 raise_error_unexpected_syntax(TIN);
11197 cpp = &n1->ncase.cases;
11199 checkkwd = CHKNL | CHKKWD;
11201 while (t != TESAC) {
11202 if (lasttoken == TLP)
11204 *cpp = cp = stzalloc(sizeof(struct nclist));
11206 app = &cp->nclist.pattern;
11208 *app = ap = stzalloc(sizeof(struct narg));
11210 /*ap->narg.next = NULL; - stzalloc did it */
11211 ap->narg.text = wordtext;
11212 ap->narg.backquote = backquotelist;
11213 if (readtoken() != TPIPE)
11215 app = &ap->narg.next;
11218 //ap->narg.next = NULL;
11219 if (lasttoken != TRP)
11220 raise_error_unexpected_syntax(TRP);
11221 cp->nclist.body = list(2);
11223 cpp = &cp->nclist.next;
11225 checkkwd = CHKNL | CHKKWD;
11229 raise_error_unexpected_syntax(TENDCASE);
11236 n1 = stzalloc(sizeof(struct nredir));
11237 n1->type = NSUBSHELL;
11238 n1->nredir.n = list(0);
11239 /*n1->nredir.redirect = NULL; - stzalloc did it */
11246 IF_ASH_BASH_COMPAT(case TFUNCTION:)
11250 return simplecmd();
11253 if (readtoken() != t)
11254 raise_error_unexpected_syntax(t);
11257 /* Now check for redirection which may follow command */
11258 checkkwd = CHKKWD | CHKALIAS;
11260 while (readtoken() == TREDIR) {
11261 *rpp = n2 = redirnode;
11262 rpp = &n2->nfile.next;
11268 if (n1->type != NSUBSHELL) {
11269 n2 = stzalloc(sizeof(struct nredir));
11274 n1->nredir.redirect = redir;
11279 #if ENABLE_ASH_BASH_COMPAT
11281 decode_dollar_squote(void)
11283 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11289 p = strchr(C_escapes, c);
11294 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11298 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11300 } else if (c == 'x') { /* \xHH */
11304 } while (isxdigit(c) && --cnt);
11306 if (cnt == 3) { /* \x but next char is "bad" */
11310 } else { /* simple seq like \\ or \t */
11315 c = bb_process_escape_sequence((void*)&p);
11316 } else { /* unrecognized "\z": print both chars unless ' or " */
11317 if (c != '\'' && c != '"') {
11319 c |= 0x100; /* "please encode \, then me" */
11327 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11328 * is not NULL, read a here document. In the latter case, eofmark is the
11329 * word which marks the end of the document and striptabs is true if
11330 * leading tabs should be stripped from the document. The argument c
11331 * is the first character of the input token or document.
11333 * Because C does not have internal subroutines, I have simulated them
11334 * using goto's to implement the subroutine linkage. The following macros
11335 * will run code that appears at the end of readtoken1.
11337 #define CHECKEND() {goto checkend; checkend_return:;}
11338 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11339 #define PARSESUB() {goto parsesub; parsesub_return:;}
11340 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11341 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11342 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11344 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11346 /* NB: syntax parameter fits into smallint */
11347 /* c parameter is an unsigned char or PEOF or PEOA */
11350 char line[EOFMARKLEN + 1];
11351 struct nodelist *bqlist;
11355 smallint prevsyntax; /* syntax before arithmetic */
11356 #if ENABLE_ASH_EXPAND_PRMT
11357 smallint pssyntax; /* we are expanding a prompt string */
11359 int varnest; /* levels of variables expansion */
11360 int arinest; /* levels of arithmetic expansion */
11361 int parenlevel; /* levels of parens in arithmetic */
11362 int dqvarnest; /* levels of variables expansion within double quotes */
11364 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11366 startlinno = g_parsefile->linno;
11370 #if ENABLE_ASH_EXPAND_PRMT
11371 pssyntax = (syntax == PSSYNTAX);
11375 dblquote = (syntax == DQSYNTAX);
11381 STARTSTACKSTR(out);
11383 /* For each line, until end of word */
11384 CHECKEND(); /* set c to PEOF if at end of here document */
11385 for (;;) { /* until end of line or end of word */
11386 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11387 switch (SIT(c, syntax)) {
11388 case CNL: /* '\n' */
11389 if (syntax == BASESYNTAX)
11390 goto endword; /* exit outer loop */
11394 goto loop; /* continue outer loop */
11399 #if ENABLE_ASH_BASH_COMPAT
11400 if (c == '\\' && bash_dollar_squote) {
11401 c = decode_dollar_squote();
11403 /* skip $'\000', $'\x00' (like bash) */
11407 /* Unknown escape. Encode as '\z' */
11408 c = (unsigned char)c;
11409 if (eofmark == NULL || dblquote)
11410 USTPUTC(CTLESC, out);
11411 USTPUTC('\\', out);
11415 if (eofmark == NULL || dblquote)
11416 USTPUTC(CTLESC, out);
11419 case CBACK: /* backslash */
11420 c = pgetc_without_PEOA();
11422 USTPUTC(CTLESC, out);
11423 USTPUTC('\\', out);
11425 } else if (c == '\n') {
11428 #if ENABLE_ASH_EXPAND_PRMT
11429 if (c == '$' && pssyntax) {
11430 USTPUTC(CTLESC, out);
11431 USTPUTC('\\', out);
11434 /* Backslash is retained if we are in "str" and next char isn't special */
11439 && (c != '"' || eofmark != NULL)
11441 USTPUTC('\\', out);
11443 USTPUTC(CTLESC, out);
11451 if (eofmark == NULL) {
11452 USTPUTC(CTLQUOTEMARK, out);
11460 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11461 if (eofmark != NULL && varnest == 0) {
11464 if (dqvarnest == 0) {
11465 syntax = BASESYNTAX;
11472 case CVAR: /* '$' */
11473 PARSESUB(); /* parse substitution */
11475 case CENDVAR: /* '}' */
11478 if (dqvarnest > 0) {
11485 #if ENABLE_SH_MATH_SUPPORT
11486 case CLP: /* '(' in arithmetic */
11490 case CRP: /* ')' in arithmetic */
11491 if (parenlevel > 0) {
11494 if (pgetc_eatbnl() == ')') {
11496 if (--arinest == 0) {
11497 syntax = prevsyntax;
11501 * unbalanced parens
11502 * (don't 2nd guess - no error)
11510 case CBQUOTE: /* '`' */
11514 goto endword; /* exit outer loop */
11518 if (varnest == 0) {
11519 #if ENABLE_ASH_BASH_COMPAT
11521 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11522 if (pgetc() == '>')
11523 c = 0x100 + '>'; /* flag &> */
11527 goto endword; /* exit outer loop */
11529 IF_ASH_ALIAS(if (c != PEOA))
11536 #if ENABLE_SH_MATH_SUPPORT
11537 if (syntax == ARISYNTAX)
11538 raise_error_syntax("missing '))'");
11540 if (syntax != BASESYNTAX && eofmark == NULL)
11541 raise_error_syntax("unterminated quoted string");
11542 if (varnest != 0) {
11543 startlinno = g_parsefile->linno;
11545 raise_error_syntax("missing '}'");
11547 USTPUTC('\0', out);
11548 len = out - (char *)stackblock();
11549 out = stackblock();
11550 if (eofmark == NULL) {
11551 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11554 if (isdigit_str9(out)) {
11555 PARSEREDIR(); /* passed as params: out, c */
11556 lasttoken = TREDIR;
11559 /* else: non-number X seen, interpret it
11560 * as "NNNX>file" = "NNNX >file" */
11564 quoteflag = quotef;
11565 backquotelist = bqlist;
11566 grabstackblock(len);
11570 /* end of readtoken routine */
11573 * Check to see whether we are at the end of the here document. When this
11574 * is called, c is set to the first character of the next input line. If
11575 * we are at the end of the here document, this routine sets the c to PEOF.
11579 #if ENABLE_ASH_ALIAS
11581 c = pgetc_without_PEOA();
11584 while (c == '\t') {
11585 c = pgetc_without_PEOA();
11588 if (c == *eofmark) {
11589 if (pfgets(line, sizeof(line)) != NULL) {
11594 for (q = eofmark + 1;; p++, q++) {
11598 if (!*q || cc != *q)
11605 pushstring(line, NULL);
11610 goto checkend_return;
11614 * Parse a redirection operator. The variable "out" points to a string
11615 * specifying the fd to be redirected. The variable "c" contains the
11616 * first character of the redirection operator.
11619 /* out is already checked to be a valid number or "" */
11620 int fd = (*out == '\0' ? -1 : atoi(out));
11623 np = stzalloc(sizeof(struct nfile));
11628 np->type = NAPPEND;
11630 np->type = NCLOBBER;
11633 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11639 #if ENABLE_ASH_BASH_COMPAT
11640 else if (c == 0x100 + '>') { /* this flags &> redirection */
11642 pgetc(); /* this is '>', no need to check */
11646 else { /* c == '<' */
11647 /*np->nfile.fd = 0; - stzalloc did it */
11651 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11652 np = stzalloc(sizeof(struct nhere));
11653 /*np->nfile.fd = 0; - stzalloc did it */
11656 heredoc = stzalloc(sizeof(struct heredoc));
11657 heredoc->here = np;
11660 heredoc->striptabs = 1;
11662 /*heredoc->striptabs = 0; - stzalloc did it */
11668 np->type = NFROMFD;
11672 np->type = NFROMTO;
11684 goto parseredir_return;
11688 * Parse a substitution. At this point, we have read the dollar sign
11689 * and nothing else.
11692 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11693 * (assuming ascii char codes, as the original implementation did) */
11694 #define is_special(c) \
11695 (((unsigned)(c) - 33 < 32) \
11696 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11698 unsigned char subtype;
11701 c = pgetc_eatbnl();
11702 if (c > 255 /* PEOA or PEOF */
11703 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11705 #if ENABLE_ASH_BASH_COMPAT
11706 if (syntax != DQSYNTAX && c == '\'')
11707 bash_dollar_squote = 1;
11712 } else if (c == '(') {
11713 /* $(command) or $((arith)) */
11714 if (pgetc_eatbnl() == '(') {
11715 #if ENABLE_SH_MATH_SUPPORT
11718 raise_error_syntax("you disabled math support for $((arith)) syntax");
11725 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11726 USTPUTC(CTLVAR, out);
11727 typeloc = out - (char *)stackblock();
11729 subtype = VSNORMAL;
11731 c = pgetc_eatbnl();
11736 /* $[{[#]]NAME[}] */
11739 c = pgetc_eatbnl();
11740 } while (is_in_name(c));
11741 } else if (isdigit(c)) {
11742 /* $[{[#]]NUM[}] */
11745 c = pgetc_eatbnl();
11746 } while (isdigit(c));
11747 } else if (is_special(c)) {
11748 /* $[{[#]]<specialchar>[}] */
11751 c = pgetc_eatbnl();
11752 if (!subtype && cc == '#') {
11753 subtype = VSLENGTH;
11754 if (c == '_' || isalnum(c))
11757 c = pgetc_eatbnl();
11758 if (cc == '}' || c != '}') {
11769 if (c != '}' && subtype == VSLENGTH) {
11770 /* ${#VAR didn't end with } */
11774 if (subtype == 0) {
11775 static const char types[] ALIGN1 = "}-+?=";
11776 /* ${VAR...} but not $VAR or ${#VAR} */
11777 /* c == first char after VAR */
11780 c = pgetc_eatbnl();
11781 #if ENABLE_ASH_BASH_COMPAT
11782 /* This check is only needed to not misinterpret
11783 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11786 if (!strchr(types, c)) {
11787 subtype = VSSUBSTR;
11789 break; /* "goto badsub" is bigger (!) */
11795 const char *p = strchr(types, c);
11798 subtype |= p - types + VSNORMAL;
11804 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11805 c = pgetc_eatbnl();
11811 #if ENABLE_ASH_BASH_COMPAT
11813 /* ${v/[/]pattern/repl} */
11814 //TODO: encode pattern and repl separately.
11815 // Currently ${v/$var_with_slash/repl} is horribly broken
11816 subtype = VSREPLACE;
11817 c = pgetc_eatbnl();
11820 subtype++; /* VSREPLACEALL */
11828 ((unsigned char *)stackblock())[typeloc] = subtype;
11829 if (subtype != VSNORMAL) {
11836 goto parsesub_return;
11840 * Called to parse command substitutions. Newstyle is set if the command
11841 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11842 * list of commands (passed by reference), and savelen is the number of
11843 * characters on the top of the stack which must be preserved.
11846 struct nodelist **nlpp;
11850 smallint saveprompt = 0;
11853 savelen = out - (char *)stackblock();
11856 * FIXME: this can allocate very large block on stack and SEGV.
11858 * echo "..<100kbytes>..`true` $(true) `true` ..."
11859 * allocates 100kb for every command subst. With about
11860 * a hundred command substitutions stack overflows.
11861 * With larger prepended string, SEGV happens sooner.
11863 str = alloca(savelen);
11864 memcpy(str, stackblock(), savelen);
11868 /* We must read until the closing backquote, giving special
11869 * treatment to some slashes, and then push the string and
11870 * reread it as input, interpreting it normally.
11876 STARTSTACKSTR(pout);
11880 setprompt_if(needprompt, 2);
11891 * If eating a newline, avoid putting
11892 * the newline into the new character
11893 * stream (via the STPUTC after the
11898 if (pc != '\\' && pc != '`' && pc != '$'
11899 && (!dblquote || pc != '"')
11901 STPUTC('\\', pout);
11903 if (pc <= 255 /* not PEOA or PEOF */) {
11909 IF_ASH_ALIAS(case PEOA:)
11910 startlinno = g_parsefile->linno;
11911 raise_error_syntax("EOF in backquote substitution");
11923 STPUTC('\0', pout);
11924 psavelen = pout - (char *)stackblock();
11925 if (psavelen > 0) {
11926 pstr = grabstackstr(pout);
11927 setinputstring(pstr);
11932 nlpp = &(*nlpp)->next;
11933 *nlpp = stzalloc(sizeof(**nlpp));
11934 /* (*nlpp)->next = NULL; - stzalloc did it */
11937 saveprompt = doprompt;
11944 doprompt = saveprompt;
11945 else if (readtoken() != TRP)
11946 raise_error_unexpected_syntax(TRP);
11951 * Start reading from old file again, ignoring any pushed back
11952 * tokens left from the backquote parsing
11957 while (stackblocksize() <= savelen)
11959 STARTSTACKSTR(out);
11961 memcpy(out, str, savelen);
11962 STADJUST(savelen, out);
11964 USTPUTC(CTLBACKQ, out);
11966 goto parsebackq_oldreturn;
11967 goto parsebackq_newreturn;
11970 #if ENABLE_SH_MATH_SUPPORT
11972 * Parse an arithmetic expansion (indicate start of one and set state)
11975 if (++arinest == 1) {
11976 prevsyntax = syntax;
11977 syntax = ARISYNTAX;
11979 USTPUTC(CTLARI, out);
11980 goto parsearith_return;
11983 } /* end of readtoken */
11986 * Read the next input token.
11987 * If the token is a word, we set backquotelist to the list of cmds in
11988 * backquotes. We set quoteflag to true if any part of the word was
11990 * If the token is TREDIR, then we set redirnode to a structure containing
11992 * In all cases, the variable startlinno is set to the number of the line
11993 * on which the token starts.
11995 * [Change comment: here documents and internal procedures]
11996 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11997 * word parsing code into a separate routine. In this case, readtoken
11998 * doesn't need to have any internal procedures, but parseword does.
11999 * We could also make parseoperator in essence the main routine, and
12000 * have parseword (readtoken1?) handle both words and redirection.]
12002 #define NEW_xxreadtoken
12003 #ifdef NEW_xxreadtoken
12004 /* singles must be first! */
12005 static const char xxreadtoken_chars[7] ALIGN1 = {
12006 '\n', '(', ')', /* singles */
12007 '&', '|', ';', /* doubles */
12011 #define xxreadtoken_singles 3
12012 #define xxreadtoken_doubles 3
12014 static const char xxreadtoken_tokens[] ALIGN1 = {
12015 TNL, TLP, TRP, /* only single occurrence allowed */
12016 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12017 TEOF, /* corresponds to trailing nul */
12018 TAND, TOR, TENDCASE /* if double occurrence */
12030 setprompt_if(needprompt, 2);
12031 startlinno = g_parsefile->linno;
12032 for (;;) { /* until token or start of word found */
12034 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12038 while ((c = pgetc()) != '\n' && c != PEOF)
12041 } else if (c == '\\') {
12042 if (pgetc() != '\n') {
12044 break; /* return readtoken1(...) */
12050 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12056 p = strchr(xxreadtoken_chars, c);
12058 break; /* return readtoken1(...) */
12060 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12062 if (cc == c) { /* double occurrence? */
12063 p += xxreadtoken_doubles + 1;
12066 #if ENABLE_ASH_BASH_COMPAT
12067 if (c == '&' && cc == '>') /* &> */
12068 break; /* return readtoken1(...) */
12073 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12078 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12080 #else /* old xxreadtoken */
12081 #define RETURN(token) return lasttoken = token
12091 setprompt_if(needprompt, 2);
12092 startlinno = g_parsefile->linno;
12093 for (;;) { /* until token or start of word found */
12096 case ' ': case '\t':
12097 IF_ASH_ALIAS(case PEOA:)
12100 while ((c = pgetc()) != '\n' && c != PEOF)
12105 if (pgetc() == '\n') {
12117 if (pgetc() == '&')
12122 if (pgetc() == '|')
12127 if (pgetc() == ';')
12140 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12143 #endif /* old xxreadtoken */
12149 int kwd = checkkwd;
12151 smallint alreadyseen = tokpushback;
12154 #if ENABLE_ASH_ALIAS
12170 if (t != TWORD || quoteflag) {
12175 * check for keywords
12177 if (kwd & CHKKWD) {
12178 const char *const *pp;
12180 pp = findkwd(wordtext);
12182 lasttoken = t = pp - tokname_array;
12183 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12188 if (checkkwd & CHKALIAS) {
12189 #if ENABLE_ASH_ALIAS
12191 ap = lookupalias(wordtext, 1);
12194 pushstring(ap->val, ap);
12204 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12206 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12222 * Read and parse a command. Returns NODE_EOF on end of file.
12223 * (NULL is a valid parse tree indicating a blank line.)
12225 static union node *
12226 parsecmd(int interact)
12231 doprompt = interact;
12232 setprompt_if(doprompt, doprompt);
12238 * Input any here documents.
12243 struct heredoc *here;
12246 here = heredoclist;
12247 heredoclist = NULL;
12250 setprompt_if(needprompt, 2);
12251 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12252 here->eofmark, here->striptabs);
12253 n = stzalloc(sizeof(struct narg));
12254 n->narg.type = NARG;
12255 /*n->narg.next = NULL; - stzalloc did it */
12256 n->narg.text = wordtext;
12257 n->narg.backquote = backquotelist;
12258 here->here->nhere.doc = n;
12265 * called by editline -- any expansions to the prompt should be added here.
12267 #if ENABLE_ASH_EXPAND_PRMT
12268 static const char *
12269 expandstr(const char *ps)
12274 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12275 * and token processing _can_ alter it (delete NULs etc). */
12276 setinputstring((char *)ps);
12278 saveprompt = doprompt;
12280 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12281 doprompt = saveprompt;
12285 n.narg.type = NARG;
12286 n.narg.next = NULL;
12287 n.narg.text = wordtext;
12288 n.narg.backquote = backquotelist;
12290 expandarg(&n, NULL, EXP_QUOTED);
12291 return stackblock();
12296 * Execute a command or commands contained in a string.
12299 evalstring(char *s, int flags)
12301 struct jmploc *volatile savehandler;
12302 struct jmploc jmploc;
12306 struct stackmark smark;
12311 setstackmark(&smark);
12314 /* On exception inside execution loop, we must popfile().
12315 * Try interactively:
12317 * command eval "a=b" # throws "is read only" error
12318 * "command BLTIN" is not supposed to abort (even in non-interactive use).
12319 * But if we skip popfile(), we hit EOF in eval's string, and exit.
12321 savehandler = exception_handler;
12322 ex = setjmp(jmploc.loc);
12325 exception_handler = &jmploc;
12327 while ((n = parsecmd(0)) != NODE_EOF) {
12330 i = evaltree(n, flags);
12333 popstackmark(&smark);
12338 popstackmark(&smark);
12342 exception_handler = savehandler;
12344 longjmp(exception_handler->loc, ex);
12350 * The eval command.
12352 static int FAST_FUNC
12353 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12362 STARTSTACKSTR(concat);
12364 concat = stack_putstr(p, concat);
12368 STPUTC(' ', concat);
12370 STPUTC('\0', concat);
12371 p = grabstackstr(concat);
12373 return evalstring(p, flags & EV_TESTED);
12379 * Read and execute commands.
12380 * "Top" is nonzero for the top level command loop;
12381 * it turns on prompting if the shell is interactive.
12387 struct stackmark smark;
12392 TRACE(("cmdloop(%d) called\n", top));
12396 setstackmark(&smark);
12399 showjobs(SHOW_CHANGED|SHOW_STDERR);
12402 if (iflag && top) {
12406 n = parsecmd(inter);
12408 if (DEBUG > 2 && debug && (n != NODE_EOF))
12411 if (n == NODE_EOF) {
12412 if (!top || numeof >= 50)
12414 if (!stoppedjobs()) {
12417 out2str("\nUse \"exit\" to leave shell.\n");
12420 } else if (nflag == 0) {
12423 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12426 i = evaltree(n, 0);
12430 popstackmark(&smark);
12434 evalskip &= ~SKIPFUNC;
12442 * Take commands from a file. To be compatible we should do a path
12443 * search for the file, which is necessary to find sub-commands.
12446 find_dot_file(char *name)
12449 const char *path = pathval();
12452 /* don't try this for absolute or relative paths */
12453 if (strchr(name, '/'))
12456 /* IIRC standards do not say whether . is to be searched.
12457 * And it is even smaller this way, making it unconditional for now:
12459 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12464 while ((fullname = path_advance(&path, name)) != NULL) {
12466 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12468 * Don't bother freeing here, since it will
12469 * be freed by the caller.
12473 if (fullname != name)
12474 stunalloc(fullname);
12477 /* not found in the PATH */
12478 ash_msg_and_raise_error("%s: not found", name);
12482 static int FAST_FUNC
12483 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12485 /* "false; . empty_file; echo $?" should print 0, not 1: */
12489 struct strlist *sp;
12490 volatile struct shparam saveparam;
12492 for (sp = cmdenviron; sp; sp = sp->next)
12493 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12495 nextopt(nullstr); /* handle possible "--" */
12499 /* bash says: "bash: .: filename argument required" */
12500 return 2; /* bash compat */
12503 /* This aborts if file isn't found, which is POSIXly correct.
12504 * bash returns exitcode 1 instead.
12506 fullname = find_dot_file(argv[0]);
12508 if (argv[0]) { /* . FILE ARGS, ARGS exist */
12510 saveparam = shellparam;
12511 shellparam.malloced = 0;
12515 shellparam.nparam = argc;
12516 shellparam.p = argv;
12519 /* This aborts if file can't be opened, which is POSIXly correct.
12520 * bash returns exitcode 1 instead.
12522 setinputfile(fullname, INPUT_PUSH_FILE);
12523 commandname = fullname;
12524 status = cmdloop(0);
12528 freeparam(&shellparam);
12529 shellparam = saveparam;
12535 static int FAST_FUNC
12536 exitcmd(int argc UNUSED_PARAM, char **argv)
12541 exitstatus = number(argv[1]);
12542 raise_exception(EXEXIT);
12547 * Read a file containing shell functions.
12550 readcmdfile(char *name)
12552 setinputfile(name, INPUT_PUSH_FILE);
12558 /* ============ find_command inplementation */
12561 * Resolve a command name. If you change this routine, you may have to
12562 * change the shellexec routine as well.
12565 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12567 struct tblentry *cmdp;
12574 struct builtincmd *bcmd;
12576 /* If name contains a slash, don't use PATH or hash table */
12577 if (strchr(name, '/') != NULL) {
12578 entry->u.index = -1;
12579 if (act & DO_ABS) {
12580 while (stat(name, &statb) < 0) {
12582 if (errno == EINTR)
12585 entry->cmdtype = CMDUNKNOWN;
12589 entry->cmdtype = CMDNORMAL;
12593 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12595 updatetbl = (path == pathval());
12598 if (strstr(path, "%builtin") != NULL)
12599 act |= DO_ALTBLTIN;
12602 /* If name is in the table, check answer will be ok */
12603 cmdp = cmdlookup(name, 0);
12604 if (cmdp != NULL) {
12607 switch (cmdp->cmdtype) {
12625 } else if (cmdp->rehash == 0)
12626 /* if not invalidated by cd, we're done */
12630 /* If %builtin not in path, check for builtin next */
12631 bcmd = find_builtin(name);
12633 if (IS_BUILTIN_REGULAR(bcmd))
12634 goto builtin_success;
12635 if (act & DO_ALTPATH) {
12636 if (!(act & DO_ALTBLTIN))
12637 goto builtin_success;
12638 } else if (builtinloc <= 0) {
12639 goto builtin_success;
12643 #if ENABLE_FEATURE_SH_STANDALONE
12645 int applet_no = find_applet_by_name(name);
12646 if (applet_no >= 0) {
12647 entry->cmdtype = CMDNORMAL;
12648 entry->u.index = -2 - applet_no;
12654 /* We have to search path. */
12655 prev = -1; /* where to start */
12656 if (cmdp && cmdp->rehash) { /* doing a rehash */
12657 if (cmdp->cmdtype == CMDBUILTIN)
12660 prev = cmdp->param.index;
12666 while ((fullname = path_advance(&path, name)) != NULL) {
12667 stunalloc(fullname);
12668 /* NB: code below will still use fullname
12669 * despite it being "unallocated" */
12672 if (prefix(pathopt, "builtin")) {
12674 goto builtin_success;
12677 if ((act & DO_NOFUNC)
12678 || !prefix(pathopt, "func")
12679 ) { /* ignore unimplemented options */
12683 /* if rehash, don't redo absolute path names */
12684 if (fullname[0] == '/' && idx <= prev) {
12687 TRACE(("searchexec \"%s\": no change\n", name));
12690 while (stat(fullname, &statb) < 0) {
12692 if (errno == EINTR)
12695 if (errno != ENOENT && errno != ENOTDIR)
12699 e = EACCES; /* if we fail, this will be the error */
12700 if (!S_ISREG(statb.st_mode))
12702 if (pathopt) { /* this is a %func directory */
12703 stalloc(strlen(fullname) + 1);
12704 /* NB: stalloc will return space pointed by fullname
12705 * (because we don't have any intervening allocations
12706 * between stunalloc above and this stalloc) */
12707 readcmdfile(fullname);
12708 cmdp = cmdlookup(name, 0);
12709 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12710 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12711 stunalloc(fullname);
12714 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12716 entry->cmdtype = CMDNORMAL;
12717 entry->u.index = idx;
12721 cmdp = cmdlookup(name, 1);
12722 cmdp->cmdtype = CMDNORMAL;
12723 cmdp->param.index = idx;
12728 /* We failed. If there was an entry for this command, delete it */
12729 if (cmdp && updatetbl)
12730 delete_cmd_entry();
12732 ash_msg("%s: %s", name, errmsg(e, "not found"));
12733 entry->cmdtype = CMDUNKNOWN;
12738 entry->cmdtype = CMDBUILTIN;
12739 entry->u.cmd = bcmd;
12743 cmdp = cmdlookup(name, 1);
12744 cmdp->cmdtype = CMDBUILTIN;
12745 cmdp->param.cmd = bcmd;
12749 entry->cmdtype = cmdp->cmdtype;
12750 entry->u = cmdp->param;
12755 * The trap builtin.
12757 static int FAST_FUNC
12758 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12762 int signo, exitcode;
12767 for (signo = 0; signo < NSIG; signo++) {
12768 char *tr = trap_ptr[signo];
12770 /* note: bash adds "SIG", but only if invoked
12771 * as "bash". If called as "sh", or if set -o posix,
12772 * then it prints short signal names.
12773 * We are printing short names: */
12774 out1fmt("trap -- %s %s\n",
12776 get_signame(signo));
12777 /* trap_ptr != trap only if we are in special-cased `trap` code.
12778 * In this case, we will exit very soon, no need to free(). */
12779 /* if (trap_ptr != trap && tp[0]) */
12784 if (trap_ptr != trap) {
12797 signo = get_signum(*ap);
12799 /* Mimic bash message exactly */
12800 ash_msg("%s: invalid signal specification", *ap);
12806 if (LONE_DASH(action))
12809 if (action[0]) /* not NULL and not "" and not "-" */
12810 may_have_traps = 1;
12811 action = ckstrdup(action);
12815 trap[signo] = action;
12826 /* ============ Builtins */
12828 #if ENABLE_ASH_HELP
12829 static int FAST_FUNC
12830 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12836 "Built-in commands:\n"
12837 "------------------\n");
12838 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12839 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12840 builtintab[i].name + 1);
12846 # if ENABLE_FEATURE_SH_STANDALONE
12848 const char *a = applet_names;
12850 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12855 while (*a++ != '\0')
12860 newline_and_flush(stdout);
12861 return EXIT_SUCCESS;
12866 static int FAST_FUNC
12867 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12869 show_history(line_input_state);
12870 return EXIT_SUCCESS;
12875 * The export and readonly commands.
12877 static int FAST_FUNC
12878 exportcmd(int argc UNUSED_PARAM, char **argv)
12888 /* "readonly" in bash accepts, but ignores -n.
12889 * We do the same: it saves a conditional in nextopt's param.
12892 while ((opt = nextopt("np")) != '\0') {
12894 flag_off = VEXPORT;
12897 if (argv[0][0] == 'r') {
12899 flag_off = 0; /* readonly ignores -n */
12901 flag_off = ~flag_off;
12903 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12909 p = strchr(name, '=');
12913 vp = *findvar(hashvar(name), name);
12915 vp->flags = ((vp->flags | flag) & flag_off);
12919 setvar(name, p, (flag & flag_off));
12920 } while ((name = *++aptr) != NULL);
12925 /* No arguments. Show the list of exported or readonly vars.
12928 showvars(argv[0], flag, 0);
12933 * Delete a function if it exists.
12936 unsetfunc(const char *name)
12938 struct tblentry *cmdp;
12940 cmdp = cmdlookup(name, 0);
12941 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12942 delete_cmd_entry();
12946 * The unset builtin command. We unset the function before we unset the
12947 * variable to allow a function to be unset when there is a readonly variable
12948 * with the same name.
12950 static int FAST_FUNC
12951 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12958 while ((i = nextopt("vf")) != 0) {
12962 for (ap = argptr; *ap; ap++) {
12975 static const unsigned char timescmd_str[] ALIGN1 = {
12976 ' ', offsetof(struct tms, tms_utime),
12977 '\n', offsetof(struct tms, tms_stime),
12978 ' ', offsetof(struct tms, tms_cutime),
12979 '\n', offsetof(struct tms, tms_cstime),
12982 static int FAST_FUNC
12983 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12985 unsigned long clk_tck, s, t;
12986 const unsigned char *p;
12989 clk_tck = bb_clk_tck();
12994 t = *(clock_t *)(((char *) &buf) + p[1]);
12997 out1fmt("%lum%lu.%03lus%c",
12999 (t * 1000) / clk_tck,
13007 #if ENABLE_SH_MATH_SUPPORT
13009 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13010 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13012 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13014 static int FAST_FUNC
13015 letcmd(int argc UNUSED_PARAM, char **argv)
13021 ash_msg_and_raise_error("expression expected");
13023 i = ash_arith(*argv);
13031 * The read builtin. Options:
13032 * -r Do not interpret '\' specially
13033 * -s Turn off echo (tty only)
13034 * -n NCHARS Read NCHARS max
13035 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13036 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13037 * -u FD Read from given FD instead of fd 0
13038 * This uses unbuffered input, which may be avoidable in some cases.
13039 * TODO: bash also has:
13040 * -a ARRAY Read into array[0],[1],etc
13041 * -d DELIM End on DELIM char, not newline
13042 * -e Use line editing (tty only)
13044 static int FAST_FUNC
13045 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13047 char *opt_n = NULL;
13048 char *opt_p = NULL;
13049 char *opt_t = NULL;
13050 char *opt_u = NULL;
13051 int read_flags = 0;
13055 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13064 read_flags |= BUILTIN_READ_SILENT;
13070 read_flags |= BUILTIN_READ_RAW;
13080 /* "read -s" needs to save/restore termios, can't allow ^C
13081 * to jump out of it.
13084 r = shell_builtin_read(setvar0,
13086 bltinlookup("IFS"), /* can be NULL */
13095 if ((uintptr_t)r > 1)
13096 ash_msg_and_raise_error(r);
13098 return (uintptr_t)r;
13101 static int FAST_FUNC
13102 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13104 static const char permuser[3] ALIGN1 = "ogu";
13107 int symbolic_mode = 0;
13109 while (nextopt("S") != '\0') {
13118 if (*argptr == NULL) {
13119 if (symbolic_mode) {
13120 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13127 *p++ = permuser[i];
13129 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13130 if (!(mask & 0400)) *p++ = 'r';
13131 if (!(mask & 0200)) *p++ = 'w';
13132 if (!(mask & 0100)) *p++ = 'x';
13140 out1fmt("%04o\n", mask);
13143 char *modestr = *argptr;
13144 /* numeric umasks are taken as-is */
13145 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13146 if (!isdigit(modestr[0]))
13148 mask = bb_parse_mode(modestr, mask);
13149 if ((unsigned)mask > 0777) {
13150 ash_msg_and_raise_error("illegal mode: %s", modestr);
13152 if (!isdigit(modestr[0]))
13159 static int FAST_FUNC
13160 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13162 return shell_builtin_ulimit(argv);
13165 /* ============ main() and helpers */
13168 * Called to exit the shell.
13177 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13178 save_history(line_input_state);
13180 status = exitstatus;
13181 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13182 if (setjmp(loc.loc)) {
13183 if (exception_type == EXEXIT)
13184 status = exitstatus;
13187 exception_handler = &loc;
13193 /*free(p); - we'll exit soon */
13196 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13197 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13200 flush_stdout_stderr();
13208 /* we will never free this */
13209 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13211 sigmode[SIGCHLD - 1] = S_DFL;
13212 setsignal(SIGCHLD);
13214 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13215 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13217 signal(SIGHUP, SIG_DFL);
13222 struct stat st1, st2;
13225 for (envp = environ; envp && *envp; envp++) {
13226 p = endofname(*envp);
13227 if (p != *envp && *p == '=') {
13228 setvareq(*envp, VEXPORT|VTEXTFIXED);
13232 setvareq((char*)defoptindvar, VTEXTFIXED);
13234 setvar0("PPID", utoa(getppid()));
13235 #if ENABLE_ASH_BASH_COMPAT
13236 p = lookupvar("SHLVL");
13237 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13238 if (!lookupvar("HOSTNAME")) {
13239 struct utsname uts;
13241 setvar0("HOSTNAME", uts.nodename);
13244 p = lookupvar("PWD");
13246 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13247 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13257 //usage:#define ash_trivial_usage
13258 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13259 //usage:#define ash_full_usage "\n\n"
13260 //usage: "Unix shell interpreter"
13262 //usage:#if ENABLE_FEATURE_SH_IS_ASH
13263 //usage:# define sh_trivial_usage ash_trivial_usage
13264 //usage:# define sh_full_usage ash_full_usage
13266 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
13267 //usage:# define bash_trivial_usage ash_trivial_usage
13268 //usage:# define bash_full_usage ash_full_usage
13272 * Process the shell command line arguments.
13275 procargs(char **argv)
13278 const char *xminusc;
13283 /* if (xargv[0]) - mmm, this is always true! */
13285 for (i = 0; i < NOPTS; i++)
13288 if (options(/*cmdline:*/ 1)) {
13289 /* it already printed err message */
13290 raise_exception(EXERROR);
13294 if (*xargv == NULL) {
13296 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13299 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13303 for (i = 0; i < NOPTS; i++)
13304 if (optlist[i] == 2)
13309 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13314 } else if (!sflag) {
13315 setinputfile(*xargv, 0);
13318 commandname = arg0;
13321 shellparam.p = xargv;
13322 #if ENABLE_ASH_GETOPTS
13323 shellparam.optind = 1;
13324 shellparam.optoff = -1;
13326 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13328 shellparam.nparam++;
13335 * Read /etc/profile, ~/.profile, $ENV.
13338 read_profile(const char *name)
13340 name = expandstr(name);
13341 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13348 * This routine is called when an error or an interrupt occurs in an
13349 * interactive shell and control is returned to the main command loop.
13350 * (In dash, this function is auto-generated by build machinery).
13359 /* from expand.c: */
13362 /* from input.c: */
13363 g_parsefile->left_in_buffer = 0;
13364 g_parsefile->left_in_line = 0; /* clear input buffer */
13367 /* from redir.c: */
13369 popredir(/*drop:*/ 0, /*restore:*/ 0);
13373 static short profile_buf[16384];
13374 extern int etext();
13378 * Main routine. We initialize things, parse the arguments, execute
13379 * profiles if we're a login shell, and then call cmdloop to execute
13380 * commands. The setjmp call sets up the location to jump to when an
13381 * exception occurs. When an exception occurs the variable "state"
13382 * is used to figure out how far we had gotten.
13384 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13385 int ash_main(int argc UNUSED_PARAM, char **argv)
13387 volatile smallint state;
13388 struct jmploc jmploc;
13389 struct stackmark smark;
13391 /* Initialize global data */
13395 #if ENABLE_ASH_ALIAS
13401 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13404 #if ENABLE_FEATURE_EDITING
13405 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13408 if (setjmp(jmploc.loc)) {
13414 e = exception_type;
13416 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13420 newline_and_flush(stderr);
13423 popstackmark(&smark);
13424 FORCE_INT_ON; /* enable interrupts */
13433 exception_handler = &jmploc;
13434 rootpid = getpid();
13437 setstackmark(&smark);
13440 TRACE(("Shell args: "));
13441 trace_puts_args(argv);
13444 if (argv[0] && argv[0][0] == '-')
13450 read_profile("/etc/profile");
13453 hp = lookupvar("HOME");
13455 read_profile("$HOME/.profile");
13461 getuid() == geteuid() && getgid() == getegid() &&
13465 const char *shinit = lookupvar("ENV");
13466 if (shinit != NULL && *shinit != '\0')
13467 read_profile(shinit);
13469 popstackmark(&smark);
13473 /* evalstring pushes parsefile stack.
13474 * Ensure we don't falsely claim that 0 (stdin)
13475 * is one of stacked source fds.
13476 * Testcase: ash -c 'exec 1>&0' must not complain. */
13477 // if (!sflag) g_parsefile->pf_fd = -1;
13478 // ^^ not necessary since now we special-case fd 0
13479 // in is_hidden_fd() to not be considered "hidden fd"
13480 evalstring(minusc, 0);
13483 if (sflag || minusc == NULL) {
13484 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13486 const char *hp = lookupvar("HISTFILE");
13488 hp = lookupvar("HOME");
13490 hp = concat_path_file(hp, ".ash_history");
13491 setvar0("HISTFILE", hp);
13493 hp = lookupvar("HISTFILE");
13497 line_input_state->hist_file = hp;
13498 # if ENABLE_FEATURE_SH_HISTFILESIZE
13499 hp = lookupvar("HISTFILESIZE");
13500 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13504 state4: /* XXX ??? - why isn't this before the "if" statement */
13512 extern void _mcleanup(void);
13516 TRACE(("End of main reached\n"));
13523 * Copyright (c) 1989, 1991, 1993, 1994
13524 * The Regents of the University of California. All rights reserved.
13526 * This code is derived from software contributed to Berkeley by
13527 * Kenneth Almquist.
13529 * Redistribution and use in source and binary forms, with or without
13530 * modification, are permitted provided that the following conditions
13532 * 1. Redistributions of source code must retain the above copyright
13533 * notice, this list of conditions and the following disclaimer.
13534 * 2. Redistributions in binary form must reproduce the above copyright
13535 * notice, this list of conditions and the following disclaimer in the
13536 * documentation and/or other materials provided with the distribution.
13537 * 3. Neither the name of the University nor the names of its contributors
13538 * may be used to endorse or promote products derived from this software
13539 * without specific prior written permission.
13541 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13542 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13543 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13544 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13545 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13546 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13547 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13548 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13549 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13550 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF