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 0
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 /* pid of main shell */
282 /* shell level: 0 for the main shell, 1 for its children, and so on */
284 #define rootshell (!shlvl)
285 char *minusc; /* argument to -c option */
287 char *curdir; // = nullstr; /* current working directory */
288 char *physdir; // = nullstr; /* physical working directory */
290 char *arg0; /* value of $0 */
292 struct jmploc *exception_handler;
294 volatile int suppress_int; /* counter */
295 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
296 /* last pending signal */
297 volatile /*sig_atomic_t*/ smallint pending_sig;
298 smallint exception_type; /* kind of exception (0..5) */
300 #define EXINT 0 /* SIGINT received */
301 #define EXERROR 1 /* a generic error */
302 #define EXSHELLPROC 2 /* execute a shell procedure */
303 #define EXEXEC 3 /* command execution failed */
304 #define EXEXIT 4 /* exit the shell */
305 #define EXSIG 5 /* trapped signal in wait(1) */
308 char nullstr[1]; /* zero length string */
311 #define eflag optlist[0]
312 #define fflag optlist[1]
313 #define Iflag optlist[2]
314 #define iflag optlist[3]
315 #define mflag optlist[4]
316 #define nflag optlist[5]
317 #define sflag optlist[6]
318 #define xflag optlist[7]
319 #define vflag optlist[8]
320 #define Cflag optlist[9]
321 #define aflag optlist[10]
322 #define bflag optlist[11]
323 #define uflag optlist[12]
324 #define viflag optlist[13]
325 #if ENABLE_ASH_BASH_COMPAT
326 # define pipefail optlist[14]
331 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
332 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
335 /* trap handler commands */
337 * Sigmode records the current value of the signal handlers for the various
338 * modes. A value of zero means that the current handler is not known.
339 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
341 char sigmode[NSIG - 1];
342 #define S_DFL 1 /* default signal handling (SIG_DFL) */
343 #define S_CATCH 2 /* signal is caught */
344 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
345 #define S_HARD_IGN 4 /* signal is ignored permanently */
347 /* indicates specified signal received */
348 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
349 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
351 char **trap_ptr; /* used only by "trap hack" */
353 /* Rarely referenced stuff */
354 #if ENABLE_ASH_RANDOM_SUPPORT
357 pid_t backgndpid; /* pid of last background process */
358 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
360 extern struct globals_misc *const ash_ptr_to_globals_misc;
361 #define G_misc (*ash_ptr_to_globals_misc)
362 #define rootpid (G_misc.rootpid )
363 #define shlvl (G_misc.shlvl )
364 #define minusc (G_misc.minusc )
365 #define curdir (G_misc.curdir )
366 #define physdir (G_misc.physdir )
367 #define arg0 (G_misc.arg0 )
368 #define exception_handler (G_misc.exception_handler)
369 #define exception_type (G_misc.exception_type )
370 #define suppress_int (G_misc.suppress_int )
371 #define pending_int (G_misc.pending_int )
372 #define pending_sig (G_misc.pending_sig )
373 #define isloginsh (G_misc.isloginsh )
374 #define nullstr (G_misc.nullstr )
375 #define optlist (G_misc.optlist )
376 #define sigmode (G_misc.sigmode )
377 #define gotsig (G_misc.gotsig )
378 #define may_have_traps (G_misc.may_have_traps )
379 #define trap (G_misc.trap )
380 #define trap_ptr (G_misc.trap_ptr )
381 #define random_gen (G_misc.random_gen )
382 #define backgndpid (G_misc.backgndpid )
383 #define job_warning (G_misc.job_warning)
384 #define INIT_G_misc() do { \
385 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
393 /* ============ DEBUG */
395 static void trace_printf(const char *fmt, ...);
396 static void trace_vprintf(const char *fmt, va_list va);
397 # define TRACE(param) trace_printf param
398 # define TRACEV(param) trace_vprintf param
399 # define close(fd) do { \
401 if (close(dfd) < 0) \
402 bb_error_msg("bug on %d: closing %d(0x%x)", \
403 __LINE__, dfd, dfd); \
406 # define TRACE(param)
407 # define TRACEV(param)
411 /* ============ Utility functions */
412 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
414 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
415 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
417 static int isdigit_str9(const char *str)
419 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
420 while (--maxlen && isdigit(*str))
422 return (*str == '\0');
425 static const char *var_end(const char *var)
434 /* ============ Interrupts / exceptions */
436 static void exitshell(void) NORETURN;
439 * These macros allow the user to suspend the handling of interrupt signals
440 * over a period of time. This is similar to SIGHOLD or to sigblock, but
441 * much more efficient and portable. (But hacking the kernel is so much
442 * more fun than worrying about efficiency and portability. :-))
444 #define INT_OFF do { \
450 * Called to raise an exception. Since C doesn't include exceptions, we
451 * just do a longjmp to the exception handler. The type of exception is
452 * stored in the global variable "exception_type".
454 static void raise_exception(int) NORETURN;
456 raise_exception(int e)
459 if (exception_handler == NULL)
464 longjmp(exception_handler->loc, 1);
467 #define raise_exception(e) do { \
468 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
469 raise_exception(e); \
474 * Called from trap.c when a SIGINT is received. (If the user specifies
475 * that SIGINT is to be trapped or ignored using the trap builtin, then
476 * this routine is not called.) Suppressint is nonzero when interrupts
477 * are held using the INT_OFF macro. (The test for iflag is just
478 * defensive programming.)
480 static void raise_interrupt(void) NORETURN;
482 raise_interrupt(void)
487 /* Signal is not automatically unmasked after it is raised,
488 * do it ourself - unmask all signals */
489 sigprocmask_allsigs(SIG_UNBLOCK);
490 /* pending_sig = 0; - now done in signal_handler() */
493 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
494 if (!(rootshell && iflag)) {
495 /* Kill ourself with SIGINT */
496 signal(SIGINT, SIG_DFL);
501 raise_exception(ex_type);
505 #define raise_interrupt() do { \
506 TRACE(("raising interrupt on line %d\n", __LINE__)); \
511 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
515 if (--suppress_int == 0 && pending_int) {
519 #define INT_ON int_on()
520 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
528 #define FORCE_INT_ON force_int_on()
530 #define SAVE_INT(v) ((v) = suppress_int)
532 #define RESTORE_INT(v) do { \
534 suppress_int = (v); \
535 if (suppress_int == 0 && pending_int) \
540 /* ============ Stdout/stderr output */
543 outstr(const char *p, FILE *file)
551 flush_stdout_stderr(void)
558 /* Was called outcslow(c,FILE*), but c was always '\n' */
560 newline_and_flush(FILE *dest)
568 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
570 out1fmt(const char *fmt, ...)
577 r = vprintf(fmt, ap);
583 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
585 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
592 ret = vsnprintf(outbuf, length, fmt, ap);
599 out1str(const char *p)
605 out2str(const char *p)
608 flush_stdout_stderr();
612 /* ============ Parser structures */
614 /* control characters in argument strings */
615 #define CTL_FIRST CTLESC
616 #define CTLESC ((unsigned char)'\201') /* escape next character */
617 #define CTLVAR ((unsigned char)'\202') /* variable defn */
618 #define CTLENDVAR ((unsigned char)'\203')
619 #define CTLBACKQ ((unsigned char)'\204')
620 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
621 #define CTLENDARI ((unsigned char)'\207')
622 #define CTLQUOTEMARK ((unsigned char)'\210')
623 #define CTL_LAST CTLQUOTEMARK
625 /* variable substitution byte (follows CTLVAR) */
626 #define VSTYPE 0x0f /* type of variable substitution */
627 #define VSNUL 0x10 /* colon--treat the empty string as unset */
629 /* values of VSTYPE field */
630 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
631 #define VSMINUS 0x2 /* ${var-text} */
632 #define VSPLUS 0x3 /* ${var+text} */
633 #define VSQUESTION 0x4 /* ${var?message} */
634 #define VSASSIGN 0x5 /* ${var=text} */
635 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
636 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
637 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
638 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
639 #define VSLENGTH 0xa /* ${#var} */
640 #if ENABLE_ASH_BASH_COMPAT
641 #define VSSUBSTR 0xc /* ${var:position:length} */
642 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
643 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
646 static const char dolatstr[] ALIGN1 = {
647 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
649 #define DOLATSTRLEN 6
668 #if ENABLE_ASH_BASH_COMPAT
685 smallint type; /* Nxxxx */
688 union node *redirect;
693 smallint pipe_backgnd;
694 struct nodelist *cmdlist;
700 union node *redirect;
713 union node *elsepart;
740 struct nodelist *backquote;
743 /* nfile and ndup layout must match!
744 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
745 * that it is actually NTO2 (>&file), and change its type.
762 char *_unused_expfname;
781 struct nredir nredir;
782 struct nbinary nbinary;
786 struct nclist nclist;
795 * NODE_EOF is returned by parsecmd when it encounters an end of file.
796 * It must be distinct from NULL.
798 #define NODE_EOF ((union node *) -1L)
801 struct nodelist *next;
814 freefunc(struct funcnode *f)
816 if (f && --f->count < 0)
821 /* ============ Debugging output */
825 static FILE *tracefile;
828 trace_printf(const char *fmt, ...)
835 fprintf(tracefile, "%u ", (int) time(NULL));
837 fprintf(tracefile, "[%u] ", (int) getpid());
839 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
841 vfprintf(tracefile, fmt, va);
846 trace_vprintf(const char *fmt, va_list va)
851 fprintf(tracefile, "%u ", (int) time(NULL));
853 fprintf(tracefile, "[%u] ", (int) getpid());
855 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
856 vfprintf(tracefile, fmt, va);
860 trace_puts(const char *s)
868 trace_puts_quoted(char *s)
875 putc('"', tracefile);
876 for (p = s; *p; p++) {
877 switch ((unsigned char)*p) {
878 case '\n': c = 'n'; goto backslash;
879 case '\t': c = 't'; goto backslash;
880 case '\r': c = 'r'; goto backslash;
881 case '\"': c = '\"'; goto backslash;
882 case '\\': c = '\\'; goto backslash;
883 case CTLESC: c = 'e'; goto backslash;
884 case CTLVAR: c = 'v'; goto backslash;
885 case CTLBACKQ: c = 'q'; goto backslash;
887 putc('\\', tracefile);
891 if (*p >= ' ' && *p <= '~')
894 putc('\\', tracefile);
895 putc((*p >> 6) & 03, tracefile);
896 putc((*p >> 3) & 07, tracefile);
897 putc(*p & 07, tracefile);
902 putc('"', tracefile);
906 trace_puts_args(char **ap)
913 trace_puts_quoted(*ap);
915 putc('\n', tracefile);
918 putc(' ', tracefile);
933 /* leave open because libedit might be using it */
936 strcpy(s, "./trace");
938 if (!freopen(s, "a", tracefile)) {
939 fprintf(stderr, "Can't re-open %s\n", s);
944 tracefile = fopen(s, "a");
945 if (tracefile == NULL) {
946 fprintf(stderr, "Can't open %s\n", s);
952 flags = fcntl(fileno(tracefile), F_GETFL);
954 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
956 setlinebuf(tracefile);
957 fputs("\nTracing started.\n", tracefile);
961 indent(int amount, char *pfx, FILE *fp)
965 for (i = 0; i < amount; i++) {
966 if (pfx && i == amount - 1)
972 /* little circular references here... */
973 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
976 sharg(union node *arg, FILE *fp)
979 struct nodelist *bqlist;
980 unsigned char subtype;
982 if (arg->type != NARG) {
983 out1fmt("<node type %d>\n", arg->type);
986 bqlist = arg->narg.backquote;
987 for (p = arg->narg.text; *p; p++) {
988 switch ((unsigned char)*p) {
997 if (subtype == VSLENGTH)
1005 if (subtype & VSNUL)
1008 switch (subtype & VSTYPE) {
1034 case VSTRIMRIGHTMAX:
1041 out1fmt("<subtype %d>", subtype);
1050 shtree(bqlist->n, -1, NULL, fp);
1061 shcmd(union node *cmd, FILE *fp)
1069 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1075 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1079 switch (np->nfile.type) {
1080 case NTO: s = ">>"+1; dftfd = 1; break;
1081 case NCLOBBER: s = ">|"; dftfd = 1; break;
1082 case NAPPEND: s = ">>"; dftfd = 1; break;
1083 #if ENABLE_ASH_BASH_COMPAT
1086 case NTOFD: s = ">&"; dftfd = 1; break;
1087 case NFROM: s = "<"; break;
1088 case NFROMFD: s = "<&"; break;
1089 case NFROMTO: s = "<>"; break;
1090 default: s = "*error*"; break;
1092 if (np->nfile.fd != dftfd)
1093 fprintf(fp, "%d", np->nfile.fd);
1095 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1096 fprintf(fp, "%d", np->ndup.dupfd);
1098 sharg(np->nfile.fname, fp);
1105 shtree(union node *n, int ind, char *pfx, FILE *fp)
1107 struct nodelist *lp;
1113 indent(ind, pfx, fp);
1115 if (n == NODE_EOF) {
1130 shtree(n->nbinary.ch1, ind, NULL, fp);
1133 shtree(n->nbinary.ch2, ind, NULL, fp);
1141 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1142 shtree(lp->n, 0, NULL, fp);
1146 if (n->npipe.pipe_backgnd)
1152 fprintf(fp, "<node type %d>", n->type);
1160 showtree(union node *n)
1162 trace_puts("showtree called\n");
1163 shtree(n, 1, NULL, stderr);
1169 /* ============ Parser data */
1172 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1175 struct strlist *next;
1182 struct strpush *prev; /* preceding string on stack */
1184 int prev_left_in_line;
1185 #if ENABLE_ASH_ALIAS
1186 struct alias *ap; /* if push was associated with an alias */
1188 char *string; /* remember the string since it may change */
1190 /* Remember last two characters for pungetc. */
1193 /* Number of outstanding calls to pungetc. */
1198 struct parsefile *prev; /* preceding file on stack */
1199 int linno; /* current line */
1200 int pf_fd; /* file descriptor (or -1 if string) */
1201 int left_in_line; /* number of chars left in this line */
1202 int left_in_buffer; /* number of chars left in this buffer past the line */
1203 char *next_to_pgetc; /* next char in buffer */
1204 char *buf; /* input buffer */
1205 struct strpush *strpush; /* for pushing strings at this level */
1206 struct strpush basestrpush; /* so pushing one is fast */
1208 /* Remember last two characters for pungetc. */
1211 /* Number of outstanding calls to pungetc. */
1215 static struct parsefile basepf; /* top level input file */
1216 static struct parsefile *g_parsefile = &basepf; /* current input file */
1217 static int startlinno; /* line # where last token started */
1218 static char *commandname; /* currently executing command */
1219 static struct strlist *cmdenviron; /* environment for builtin command */
1220 static uint8_t exitstatus; /* exit status of last command */
1223 /* ============ Message printing */
1226 ash_vmsg(const char *msg, va_list ap)
1228 fprintf(stderr, "%s: ", arg0);
1230 if (strcmp(arg0, commandname))
1231 fprintf(stderr, "%s: ", commandname);
1232 if (!iflag || g_parsefile->pf_fd > 0)
1233 fprintf(stderr, "line %d: ", startlinno);
1235 vfprintf(stderr, msg, ap);
1236 newline_and_flush(stderr);
1240 * Exverror is called to raise the error exception. If the second argument
1241 * is not NULL then error prints an error message using printf style
1242 * formatting. It then raises the error exception.
1244 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1246 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1250 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1252 TRACE(("\") pid=%d\n", getpid()));
1254 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1259 flush_stdout_stderr();
1260 raise_exception(cond);
1264 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1266 ash_msg_and_raise_error(const char *msg, ...)
1271 ash_vmsg_and_raise(EXERROR, msg, ap);
1276 static void raise_error_syntax(const char *) NORETURN;
1278 raise_error_syntax(const char *msg)
1280 ash_msg_and_raise_error("syntax error: %s", msg);
1284 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1286 ash_msg_and_raise(int cond, const char *msg, ...)
1291 ash_vmsg_and_raise(cond, msg, ap);
1297 * error/warning routines for external builtins
1300 ash_msg(const char *fmt, ...)
1310 * Return a string describing an error. The returned string may be a
1311 * pointer to a static buffer that will be overwritten on the next call.
1312 * Action describes the operation that got the error.
1315 errmsg(int e, const char *em)
1317 if (e == ENOENT || e == ENOTDIR) {
1324 /* ============ Memory allocation */
1327 /* I consider these wrappers nearly useless:
1328 * ok, they return you to nearest exception handler, but
1329 * how much memory do you leak in the process, making
1330 * memory starvation worse?
1333 ckrealloc(void * p, size_t nbytes)
1335 p = realloc(p, nbytes);
1337 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1342 ckmalloc(size_t nbytes)
1344 return ckrealloc(NULL, nbytes);
1348 ckzalloc(size_t nbytes)
1350 return memset(ckmalloc(nbytes), 0, nbytes);
1354 ckstrdup(const char *s)
1356 char *p = strdup(s);
1358 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1362 /* Using bbox equivalents. They exit if out of memory */
1363 # define ckrealloc xrealloc
1364 # define ckmalloc xmalloc
1365 # define ckzalloc xzalloc
1366 # define ckstrdup xstrdup
1370 * It appears that grabstackstr() will barf with such alignments
1371 * because stalloc() will return a string allocated in a new stackblock.
1373 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1375 /* Most machines require the value returned from malloc to be aligned
1376 * in some way. The following macro will get this right
1377 * on many machines. */
1378 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1379 /* Minimum size of a block */
1380 MINSIZE = SHELL_ALIGN(504),
1383 struct stack_block {
1384 struct stack_block *prev;
1385 char space[MINSIZE];
1389 struct stack_block *stackp;
1395 struct globals_memstack {
1396 struct stack_block *g_stackp; // = &stackbase;
1397 char *g_stacknxt; // = stackbase.space;
1398 char *sstrend; // = stackbase.space + MINSIZE;
1399 size_t g_stacknleft; // = MINSIZE;
1400 int herefd; // = -1;
1401 struct stack_block stackbase;
1403 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1404 #define G_memstack (*ash_ptr_to_globals_memstack)
1405 #define g_stackp (G_memstack.g_stackp )
1406 #define g_stacknxt (G_memstack.g_stacknxt )
1407 #define sstrend (G_memstack.sstrend )
1408 #define g_stacknleft (G_memstack.g_stacknleft)
1409 #define herefd (G_memstack.herefd )
1410 #define stackbase (G_memstack.stackbase )
1411 #define INIT_G_memstack() do { \
1412 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1414 g_stackp = &stackbase; \
1415 g_stacknxt = stackbase.space; \
1416 g_stacknleft = MINSIZE; \
1417 sstrend = stackbase.space + MINSIZE; \
1422 #define stackblock() ((void *)g_stacknxt)
1423 #define stackblocksize() g_stacknleft
1426 * Parse trees for commands are allocated in lifo order, so we use a stack
1427 * to make this more efficient, and also to avoid all sorts of exception
1428 * handling code to handle interrupts in the middle of a parse.
1430 * The size 504 was chosen because the Ultrix malloc handles that size
1434 stalloc(size_t nbytes)
1439 aligned = SHELL_ALIGN(nbytes);
1440 if (aligned > g_stacknleft) {
1443 struct stack_block *sp;
1445 blocksize = aligned;
1446 if (blocksize < MINSIZE)
1447 blocksize = MINSIZE;
1448 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1449 if (len < blocksize)
1450 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1453 sp->prev = g_stackp;
1454 g_stacknxt = sp->space;
1455 g_stacknleft = blocksize;
1456 sstrend = g_stacknxt + blocksize;
1461 g_stacknxt += aligned;
1462 g_stacknleft -= aligned;
1467 stzalloc(size_t nbytes)
1469 return memset(stalloc(nbytes), 0, nbytes);
1476 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1477 write(STDERR_FILENO, "stunalloc\n", 10);
1481 g_stacknleft += g_stacknxt - (char *)p;
1486 * Like strdup but works with the ash stack.
1489 sstrdup(const char *p)
1491 size_t len = strlen(p) + 1;
1492 return memcpy(stalloc(len), p, len);
1496 grabstackblock(size_t len)
1498 len = SHELL_ALIGN(len);
1500 g_stacknleft -= len;
1504 pushstackmark(struct stackmark *mark, size_t len)
1506 mark->stackp = g_stackp;
1507 mark->stacknxt = g_stacknxt;
1508 mark->stacknleft = g_stacknleft;
1509 grabstackblock(len);
1513 setstackmark(struct stackmark *mark)
1515 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1519 popstackmark(struct stackmark *mark)
1521 struct stack_block *sp;
1527 while (g_stackp != mark->stackp) {
1529 g_stackp = sp->prev;
1532 g_stacknxt = mark->stacknxt;
1533 g_stacknleft = mark->stacknleft;
1534 sstrend = mark->stacknxt + mark->stacknleft;
1539 * When the parser reads in a string, it wants to stick the string on the
1540 * stack and only adjust the stack pointer when it knows how big the
1541 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1542 * of space on top of the stack and stackblocklen returns the length of
1543 * this block. Growstackblock will grow this space by at least one byte,
1544 * possibly moving it (like realloc). Grabstackblock actually allocates the
1545 * part of the block that has been used.
1548 growstackblock(void)
1552 newlen = g_stacknleft * 2;
1553 if (newlen < g_stacknleft)
1554 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1558 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1559 struct stack_block *sp;
1560 struct stack_block *prevstackp;
1565 prevstackp = sp->prev;
1566 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1567 sp = ckrealloc(sp, grosslen);
1568 sp->prev = prevstackp;
1570 g_stacknxt = sp->space;
1571 g_stacknleft = newlen;
1572 sstrend = sp->space + newlen;
1575 char *oldspace = g_stacknxt;
1576 size_t oldlen = g_stacknleft;
1577 char *p = stalloc(newlen);
1579 /* free the space we just allocated */
1580 g_stacknxt = memcpy(p, oldspace, oldlen);
1581 g_stacknleft += newlen;
1586 * The following routines are somewhat easier to use than the above.
1587 * The user declares a variable of type STACKSTR, which may be declared
1588 * to be a register. The macro STARTSTACKSTR initializes things. Then
1589 * the user uses the macro STPUTC to add characters to the string. In
1590 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1591 * grown as necessary. When the user is done, she can just leave the
1592 * string there and refer to it using stackblock(). Or she can allocate
1593 * the space for it using grabstackstr(). If it is necessary to allow
1594 * someone else to use the stack temporarily and then continue to grow
1595 * the string, the user should use grabstack to allocate the space, and
1596 * then call ungrabstr(p) to return to the previous mode of operation.
1598 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1599 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1600 * is space for at least one character.
1605 size_t len = stackblocksize();
1606 if (herefd >= 0 && len >= 1024) {
1607 full_write(herefd, stackblock(), len);
1608 return stackblock();
1611 return (char *)stackblock() + len;
1615 * Called from CHECKSTRSPACE.
1618 makestrspace(size_t newlen, char *p)
1620 size_t len = p - g_stacknxt;
1626 size = stackblocksize();
1628 if (nleft >= newlen)
1632 return (char *)stackblock() + len;
1636 stack_nputstr(const char *s, size_t n, char *p)
1638 p = makestrspace(n, p);
1639 p = (char *)memcpy(p, s, n) + n;
1644 stack_putstr(const char *s, char *p)
1646 return stack_nputstr(s, strlen(s), p);
1650 _STPUTC(int c, char *p)
1658 #define STARTSTACKSTR(p) ((p) = stackblock())
1659 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1660 #define CHECKSTRSPACE(n, p) do { \
1663 size_t m = sstrend - q; \
1665 (p) = makestrspace(l, q); \
1667 #define USTPUTC(c, p) (*(p)++ = (c))
1668 #define STACKSTRNUL(p) do { \
1669 if ((p) == sstrend) \
1670 (p) = growstackstr(); \
1673 #define STUNPUTC(p) (--(p))
1674 #define STTOPC(p) ((p)[-1])
1675 #define STADJUST(amount, p) ((p) += (amount))
1677 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1678 #define ungrabstackstr(s, p) stunalloc(s)
1679 #define stackstrend() ((void *)sstrend)
1682 /* ============ String helpers */
1685 * prefix -- see if pfx is a prefix of string.
1688 prefix(const char *string, const char *pfx)
1691 if (*pfx++ != *string++)
1694 return (char *) string;
1698 * Check for a valid number. This should be elsewhere.
1701 is_number(const char *p)
1706 } while (*++p != '\0');
1711 * Convert a string of digits to an integer, printing an error message on
1715 number(const char *s)
1718 ash_msg_and_raise_error(msg_illnum, s);
1723 * Produce a possibly single quoted string suitable as input to the shell.
1724 * The return string is allocated on the stack.
1727 single_quote(const char *s)
1737 len = strchrnul(s, '\'') - s;
1739 q = p = makestrspace(len + 3, p);
1742 q = (char *)memcpy(q, s, len) + len;
1751 do len++; while (*++s == '\'');
1753 q = p = makestrspace(len + 3, p);
1756 q = (char *)memcpy(q, s - len, len) + len;
1764 return stackblock();
1768 /* ============ nextopt */
1770 static char **argptr; /* argument list for builtin commands */
1771 static char *optionarg; /* set by nextopt (like getopt) */
1772 static char *optptr; /* used by nextopt */
1775 * XXX - should get rid of. Have all builtins use getopt(3).
1776 * The library getopt must have the BSD extension static variable
1777 * "optreset", otherwise it can't be used within the shell safely.
1779 * Standard option processing (a la getopt) for builtin routines.
1780 * The only argument that is passed to nextopt is the option string;
1781 * the other arguments are unnecessary. It returns the character,
1782 * or '\0' on end of input.
1785 nextopt(const char *optstring)
1792 if (p == NULL || *p == '\0') {
1793 /* We ate entire "-param", take next one */
1799 if (*++p == '\0') /* just "-" ? */
1802 if (LONE_DASH(p)) /* "--" ? */
1804 /* p => next "-param" */
1806 /* p => some option char in the middle of a "-param" */
1808 for (q = optstring; *q != c;) {
1810 ash_msg_and_raise_error("illegal option -%c", c);
1818 ash_msg_and_raise_error("no arg for -%c option", c);
1828 /* ============ Shell variables */
1831 * The parsefile structure pointed to by the global variable parsefile
1832 * contains information about the current file being read.
1835 int nparam; /* # of positional parameters (without $0) */
1836 #if ENABLE_ASH_GETOPTS
1837 int optind; /* next parameter to be processed by getopts */
1838 int optoff; /* used by getopts */
1840 unsigned char malloced; /* if parameter list dynamically allocated */
1841 char **p; /* parameter list */
1845 * Free the list of positional parameters.
1848 freeparam(volatile struct shparam *param)
1850 if (param->malloced) {
1852 ap = ap1 = param->p;
1859 #if ENABLE_ASH_GETOPTS
1860 static void FAST_FUNC getoptsreset(const char *value);
1864 struct var *next; /* next entry in hash list */
1865 int flags; /* flags are defined above */
1866 const char *var_text; /* name=value */
1867 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1868 /* the variable gets set/unset */
1872 struct localvar *next; /* next local variable in list */
1873 struct var *vp; /* the variable that was made local */
1874 int flags; /* saved flags */
1875 const char *text; /* saved text */
1879 #define VEXPORT 0x01 /* variable is exported */
1880 #define VREADONLY 0x02 /* variable cannot be modified */
1881 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1882 #define VTEXTFIXED 0x08 /* text is statically allocated */
1883 #define VSTACK 0x10 /* text is allocated on the stack */
1884 #define VUNSET 0x20 /* the variable is not set */
1885 #define VNOFUNC 0x40 /* don't call the callback function */
1886 #define VNOSET 0x80 /* do not set variable - just readonly test */
1887 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1888 #if ENABLE_ASH_RANDOM_SUPPORT
1889 # define VDYNAMIC 0x200 /* dynamic variable */
1895 /* Need to be before varinit_data[] */
1896 #if ENABLE_LOCALE_SUPPORT
1897 static void FAST_FUNC
1898 change_lc_all(const char *value)
1900 if (value && *value != '\0')
1901 setlocale(LC_ALL, value);
1903 static void FAST_FUNC
1904 change_lc_ctype(const char *value)
1906 if (value && *value != '\0')
1907 setlocale(LC_CTYPE, value);
1911 static void chkmail(void);
1912 static void changemail(const char *var_value) FAST_FUNC;
1914 # define chkmail() ((void)0)
1916 static void changepath(const char *) FAST_FUNC;
1917 #if ENABLE_ASH_RANDOM_SUPPORT
1918 static void change_random(const char *) FAST_FUNC;
1921 static const struct {
1923 const char *var_text;
1924 void (*var_func)(const char *) FAST_FUNC;
1925 } varinit_data[] = {
1927 * Note: VEXPORT would not work correctly here for NOFORK applets:
1928 * some environment strings may be constant.
1930 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1932 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1933 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1935 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1936 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1937 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1938 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1939 #if ENABLE_ASH_GETOPTS
1940 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
1942 #if ENABLE_ASH_RANDOM_SUPPORT
1943 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1945 #if ENABLE_LOCALE_SUPPORT
1946 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1947 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1949 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1950 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1956 struct globals_var {
1957 struct shparam shellparam; /* $@ current positional parameters */
1958 struct redirtab *redirlist;
1960 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1961 struct var *vartab[VTABSIZE];
1962 struct var varinit[ARRAY_SIZE(varinit_data)];
1964 extern struct globals_var *const ash_ptr_to_globals_var;
1965 #define G_var (*ash_ptr_to_globals_var)
1966 #define shellparam (G_var.shellparam )
1967 //#define redirlist (G_var.redirlist )
1968 #define g_nullredirs (G_var.g_nullredirs )
1969 #define preverrout_fd (G_var.preverrout_fd)
1970 #define vartab (G_var.vartab )
1971 #define varinit (G_var.varinit )
1972 #define INIT_G_var() do { \
1974 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1976 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1977 varinit[i].flags = varinit_data[i].flags; \
1978 varinit[i].var_text = varinit_data[i].var_text; \
1979 varinit[i].var_func = varinit_data[i].var_func; \
1983 #define vifs varinit[0]
1985 # define vmail (&vifs)[1]
1986 # define vmpath (&vmail)[1]
1987 # define vpath (&vmpath)[1]
1989 # define vpath (&vifs)[1]
1991 #define vps1 (&vpath)[1]
1992 #define vps2 (&vps1)[1]
1993 #define vps4 (&vps2)[1]
1994 #if ENABLE_ASH_GETOPTS
1995 # define voptind (&vps4)[1]
1996 # if ENABLE_ASH_RANDOM_SUPPORT
1997 # define vrandom (&voptind)[1]
2000 # if ENABLE_ASH_RANDOM_SUPPORT
2001 # define vrandom (&vps4)[1]
2006 * The following macros access the values of the above variables.
2007 * They have to skip over the name. They return the null string
2008 * for unset variables.
2010 #define ifsval() (vifs.var_text + 4)
2011 #define ifsset() ((vifs.flags & VUNSET) == 0)
2013 # define mailval() (vmail.var_text + 5)
2014 # define mpathval() (vmpath.var_text + 9)
2015 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2017 #define pathval() (vpath.var_text + 5)
2018 #define ps1val() (vps1.var_text + 4)
2019 #define ps2val() (vps2.var_text + 4)
2020 #define ps4val() (vps4.var_text + 4)
2021 #if ENABLE_ASH_GETOPTS
2022 # define optindval() (voptind.var_text + 7)
2025 #if ENABLE_ASH_GETOPTS
2026 static void FAST_FUNC
2027 getoptsreset(const char *value)
2029 shellparam.optind = number(value);
2030 shellparam.optoff = -1;
2035 * Compares two strings up to the first = or '\0'. The first
2036 * string must be terminated by '='; the second may be terminated by
2037 * either '=' or '\0'.
2040 varcmp(const char *p, const char *q)
2044 while ((c = *p) == (d = *q)) {
2045 if (c == '\0' || c == '=')
2059 * Find the appropriate entry in the hash table from the name.
2061 static struct var **
2062 hashvar(const char *p)
2066 hashval = ((unsigned char) *p) << 4;
2067 while (*p && *p != '=')
2068 hashval += (unsigned char) *p++;
2069 return &vartab[hashval % VTABSIZE];
2073 vpcmp(const void *a, const void *b)
2075 return varcmp(*(const char **)a, *(const char **)b);
2079 * This routine initializes the builtin variables.
2089 * PS1 depends on uid
2091 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2092 vps1.var_text = "PS1=\\w \\$ ";
2095 vps1.var_text = "PS1=# ";
2098 end = vp + ARRAY_SIZE(varinit);
2100 vpp = hashvar(vp->var_text);
2103 } while (++vp < end);
2106 static struct var **
2107 findvar(struct var **vpp, const char *name)
2109 for (; *vpp; vpp = &(*vpp)->next) {
2110 if (varcmp((*vpp)->var_text, name) == 0) {
2118 * Find the value of a variable. Returns NULL if not set.
2120 static const char* FAST_FUNC
2121 lookupvar(const char *name)
2125 v = *findvar(hashvar(name), name);
2127 #if ENABLE_ASH_RANDOM_SUPPORT
2129 * Dynamic variables are implemented roughly the same way they are
2130 * in bash. Namely, they're "special" so long as they aren't unset.
2131 * As soon as they're unset, they're no longer dynamic, and dynamic
2132 * lookup will no longer happen at that point. -- PFM.
2134 if (v->flags & VDYNAMIC)
2137 if (!(v->flags & VUNSET))
2138 return var_end(v->var_text);
2143 static void reinit_unicode_for_ash(void)
2145 /* Unicode support should be activated even if LANG is set
2146 * _during_ shell execution, not only if it was set when
2147 * shell was started. Therefore, re-check LANG every time:
2149 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2150 || ENABLE_UNICODE_USING_LOCALE
2152 const char *s = lookupvar("LC_ALL");
2153 if (!s) s = lookupvar("LC_CTYPE");
2154 if (!s) s = lookupvar("LANG");
2160 * Search the environment of a builtin command.
2163 bltinlookup(const char *name)
2167 for (sp = cmdenviron; sp; sp = sp->next) {
2168 if (varcmp(sp->text, name) == 0)
2169 return var_end(sp->text);
2171 return lookupvar(name);
2175 * Same as setvar except that the variable and value are passed in
2176 * the first argument as name=value. Since the first argument will
2177 * be actually stored in the table, it should not be a string that
2179 * Called with interrupts off.
2182 setvareq(char *s, int flags)
2184 struct var *vp, **vpp;
2187 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2188 vp = *findvar(vpp, s);
2190 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2193 if (flags & VNOSAVE)
2196 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2202 if (vp->var_func && !(flags & VNOFUNC))
2203 vp->var_func(var_end(s));
2205 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2206 free((char*)vp->var_text);
2208 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2210 /* variable s is not found */
2213 vp = ckzalloc(sizeof(*vp));
2215 /*vp->func = NULL; - ckzalloc did it */
2218 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2225 * Set the value of a variable. The flags argument is ored with the
2226 * flags of the variable. If val is NULL, the variable is unset.
2229 setvar(const char *name, const char *val, int flags)
2237 q = endofname(name);
2238 p = strchrnul(q, '=');
2240 if (!namelen || p != q)
2241 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2246 vallen = strlen(val);
2250 nameeq = ckmalloc(namelen + vallen + 2);
2251 p = memcpy(nameeq, name, namelen) + namelen;
2254 p = memcpy(p, val, vallen) + vallen;
2257 setvareq(nameeq, flags | VNOSAVE);
2261 static void FAST_FUNC
2262 setvar0(const char *name, const char *val)
2264 setvar(name, val, 0);
2267 #if ENABLE_ASH_GETOPTS
2269 * Safe version of setvar, returns 1 on success 0 on failure.
2272 setvarsafe(const char *name, const char *val, int flags)
2275 volatile int saveint;
2276 struct jmploc *volatile savehandler = exception_handler;
2277 struct jmploc jmploc;
2280 if (setjmp(jmploc.loc))
2283 exception_handler = &jmploc;
2284 setvar(name, val, flags);
2287 exception_handler = savehandler;
2288 RESTORE_INT(saveint);
2294 * Unset the specified variable.
2297 unsetvar(const char *s)
2303 vpp = findvar(hashvar(s), s);
2307 int flags = vp->flags;
2310 if (flags & VREADONLY)
2312 #if ENABLE_ASH_RANDOM_SUPPORT
2313 vp->flags &= ~VDYNAMIC;
2317 if ((flags & VSTRFIXED) == 0) {
2319 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2320 free((char*)vp->var_text);
2326 vp->flags &= ~VEXPORT;
2336 * Process a linked list of variable assignments.
2339 listsetvar(struct strlist *list_set_var, int flags)
2341 struct strlist *lp = list_set_var;
2347 setvareq(lp->text, flags);
2354 * Generate a list of variables satisfying the given conditions.
2357 listvars(int on, int off, char ***end)
2368 for (vp = *vpp; vp; vp = vp->next) {
2369 if ((vp->flags & mask) == on) {
2370 if (ep == stackstrend())
2371 ep = growstackstr();
2372 *ep++ = (char*)vp->var_text;
2375 } while (++vpp < vartab + VTABSIZE);
2376 if (ep == stackstrend())
2377 ep = growstackstr();
2381 return grabstackstr(ep);
2385 /* ============ Path search helper
2387 * The variable path (passed by reference) should be set to the start
2388 * of the path before the first call; path_advance will update
2389 * this value as it proceeds. Successive calls to path_advance will return
2390 * the possible path expansions in sequence. If an option (indicated by
2391 * a percent sign) appears in the path entry then the global variable
2392 * pathopt will be set to point to it; otherwise pathopt will be set to
2395 static const char *pathopt; /* set by path_advance */
2398 path_advance(const char **path, const char *name)
2408 for (p = start; *p && *p != ':' && *p != '%'; p++)
2410 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2411 while (stackblocksize() < len)
2415 memcpy(q, start, p - start);
2423 while (*p && *p != ':')
2430 return stalloc(len);
2434 /* ============ Prompt */
2436 static smallint doprompt; /* if set, prompt the user */
2437 static smallint needprompt; /* true if interactive and at start of line */
2439 #if ENABLE_FEATURE_EDITING
2440 static line_input_t *line_input_state;
2441 static const char *cmdedit_prompt;
2443 putprompt(const char *s)
2445 if (ENABLE_ASH_EXPAND_PRMT) {
2446 free((char*)cmdedit_prompt);
2447 cmdedit_prompt = ckstrdup(s);
2454 putprompt(const char *s)
2460 #if ENABLE_ASH_EXPAND_PRMT
2461 /* expandstr() needs parsing machinery, so it is far away ahead... */
2462 static const char *expandstr(const char *ps);
2464 #define expandstr(s) s
2468 setprompt_if(smallint do_set, int whichprompt)
2471 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2478 switch (whichprompt) {
2488 #if ENABLE_ASH_EXPAND_PRMT
2489 pushstackmark(&smark, stackblocksize());
2491 putprompt(expandstr(prompt));
2492 #if ENABLE_ASH_EXPAND_PRMT
2493 popstackmark(&smark);
2498 /* ============ The cd and pwd commands */
2500 #define CD_PHYSICAL 1
2510 while ((i = nextopt("LP")) != '\0') {
2512 flags ^= CD_PHYSICAL;
2521 * Update curdir (the name of the current directory) in response to a
2525 updatepwd(const char *dir)
2532 cdcomppath = sstrdup(dir);
2535 if (curdir == nullstr)
2537 new = stack_putstr(curdir, new);
2539 new = makestrspace(strlen(dir) + 2, new);
2540 lim = (char *)stackblock() + 1;
2544 if (new > lim && *lim == '/')
2549 if (dir[1] == '/' && dir[2] != '/') {
2555 p = strtok(cdcomppath, "/");
2559 if (p[1] == '.' && p[2] == '\0') {
2571 new = stack_putstr(p, new);
2574 p = strtok(NULL, "/");
2579 return stackblock();
2583 * Find out what the current directory is. If we already know the current
2584 * directory, this routine returns immediately.
2589 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2590 return dir ? dir : nullstr;
2594 setpwd(const char *val, int setold)
2598 oldcur = dir = curdir;
2601 setvar("OLDPWD", oldcur, VEXPORT);
2604 if (physdir != nullstr) {
2605 if (physdir != oldcur)
2609 if (oldcur == val || !val) {
2615 dir = ckstrdup(val);
2616 if (oldcur != dir && oldcur != nullstr) {
2621 setvar("PWD", dir, VEXPORT);
2624 static void hashcd(void);
2627 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2628 * know that the current directory has changed.
2631 docd(const char *dest, int flags)
2633 const char *dir = NULL;
2636 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2639 if (!(flags & CD_PHYSICAL)) {
2640 dir = updatepwd(dest);
2654 static int FAST_FUNC
2655 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2667 dest = bltinlookup("HOME");
2668 else if (LONE_DASH(dest)) {
2669 dest = bltinlookup("OLDPWD");
2691 path = bltinlookup("CDPATH");
2700 p = path_advance(&path, dest);
2701 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2705 if (!docd(p, flags))
2710 ash_msg_and_raise_error("can't cd to %s", dest);
2713 if (flags & CD_PRINT)
2714 out1fmt("%s\n", curdir);
2718 static int FAST_FUNC
2719 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2722 const char *dir = curdir;
2726 if (physdir == nullstr)
2730 out1fmt("%s\n", dir);
2735 /* ============ ... */
2738 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2740 /* Syntax classes */
2741 #define CWORD 0 /* character is nothing special */
2742 #define CNL 1 /* newline character */
2743 #define CBACK 2 /* a backslash character */
2744 #define CSQUOTE 3 /* single quote */
2745 #define CDQUOTE 4 /* double quote */
2746 #define CENDQUOTE 5 /* a terminating quote */
2747 #define CBQUOTE 6 /* backwards single quote */
2748 #define CVAR 7 /* a dollar sign */
2749 #define CENDVAR 8 /* a '}' character */
2750 #define CLP 9 /* a left paren in arithmetic */
2751 #define CRP 10 /* a right paren in arithmetic */
2752 #define CENDFILE 11 /* end of file */
2753 #define CCTL 12 /* like CWORD, except it must be escaped */
2754 #define CSPCL 13 /* these terminate a word */
2755 #define CIGN 14 /* character should be ignored */
2758 #if ENABLE_ASH_ALIAS
2762 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2764 #if ENABLE_SH_MATH_SUPPORT
2765 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2767 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2769 static const uint16_t S_I_T[] ALIGN2 = {
2770 #if ENABLE_ASH_ALIAS
2771 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2773 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2774 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2775 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2776 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2777 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2778 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2779 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2780 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2781 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2782 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2783 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2784 #if !USE_SIT_FUNCTION
2785 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2786 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2787 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2791 /* Constants below must match table above */
2793 #if ENABLE_ASH_ALIAS
2794 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2796 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2797 CNL_CNL_CNL_CNL , /* 2 */
2798 CWORD_CCTL_CCTL_CWORD , /* 3 */
2799 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2800 CVAR_CVAR_CWORD_CVAR , /* 5 */
2801 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2802 CSPCL_CWORD_CWORD_CLP , /* 7 */
2803 CSPCL_CWORD_CWORD_CRP , /* 8 */
2804 CBACK_CBACK_CCTL_CBACK , /* 9 */
2805 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2806 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2807 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2808 CWORD_CWORD_CWORD_CWORD , /* 13 */
2809 CCTL_CCTL_CCTL_CCTL , /* 14 */
2812 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2813 * caller must ensure proper cast on it if c is *char_ptr!
2815 /* Values for syntax param */
2816 #define BASESYNTAX 0 /* not in quotes */
2817 #define DQSYNTAX 1 /* in double quotes */
2818 #define SQSYNTAX 2 /* in single quotes */
2819 #define ARISYNTAX 3 /* in arithmetic */
2820 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2822 #if USE_SIT_FUNCTION
2825 SIT(int c, int syntax)
2827 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2828 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2830 * This causes '/' to be prepended with CTLESC in dquoted string,
2831 * making "./file"* treated incorrectly because we feed
2832 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2833 * The "homegrown" glob implementation is okay with that,
2834 * but glibc one isn't. With '/' always treated as CWORD,
2837 # if ENABLE_ASH_ALIAS
2838 static const uint8_t syntax_index_table[] ALIGN1 = {
2839 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2840 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2841 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2845 static const uint8_t syntax_index_table[] ALIGN1 = {
2846 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2847 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2848 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2857 # if ENABLE_ASH_ALIAS
2863 /* Cast is purely for paranoia here,
2864 * just in case someone passed signed char to us */
2865 if ((unsigned char)c >= CTL_FIRST
2866 && (unsigned char)c <= CTL_LAST
2870 s = strchrnul(spec_symbls, c);
2873 indx = syntax_index_table[s - spec_symbls];
2875 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2878 #else /* !USE_SIT_FUNCTION */
2880 static const uint8_t syntax_index_table[] ALIGN1 = {
2881 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2882 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2892 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2893 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2915 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2916 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2917 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2918 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2919 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2921 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2922 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2923 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2924 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2925 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2927 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2928 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2929 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2930 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2942 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2943 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2944 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2945 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2946 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2947 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2975 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2976 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2977 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2980 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3006 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3007 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3008 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3009 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3010 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3011 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3013 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3014 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3015 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3016 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3017 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3018 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3019 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3020 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3120 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3121 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3122 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3123 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3124 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3125 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3126 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3127 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3128 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3129 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3130 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3131 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3132 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3133 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3134 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3135 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3136 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3137 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3138 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3139 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3140 # if ENABLE_ASH_ALIAS
3141 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3145 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3147 #endif /* !USE_SIT_FUNCTION */
3150 /* ============ Alias handling */
3152 #if ENABLE_ASH_ALIAS
3154 #define ALIASINUSE 1
3165 static struct alias **atab; // [ATABSIZE];
3166 #define INIT_G_alias() do { \
3167 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3171 static struct alias **
3172 __lookupalias(const char *name) {
3173 unsigned int hashval;
3180 ch = (unsigned char)*p;
3184 ch = (unsigned char)*++p;
3186 app = &atab[hashval % ATABSIZE];
3188 for (; *app; app = &(*app)->next) {
3189 if (strcmp(name, (*app)->name) == 0) {
3197 static struct alias *
3198 lookupalias(const char *name, int check)
3200 struct alias *ap = *__lookupalias(name);
3202 if (check && ap && (ap->flag & ALIASINUSE))
3207 static struct alias *
3208 freealias(struct alias *ap)
3212 if (ap->flag & ALIASINUSE) {
3213 ap->flag |= ALIASDEAD;
3225 setalias(const char *name, const char *val)
3227 struct alias *ap, **app;
3229 app = __lookupalias(name);
3233 if (!(ap->flag & ALIASINUSE)) {
3236 ap->val = ckstrdup(val);
3237 ap->flag &= ~ALIASDEAD;
3240 ap = ckzalloc(sizeof(struct alias));
3241 ap->name = ckstrdup(name);
3242 ap->val = ckstrdup(val);
3243 /*ap->flag = 0; - ckzalloc did it */
3244 /*ap->next = NULL;*/
3251 unalias(const char *name)
3255 app = __lookupalias(name);
3259 *app = freealias(*app);
3270 struct alias *ap, **app;
3274 for (i = 0; i < ATABSIZE; i++) {
3276 for (ap = *app; ap; ap = *app) {
3277 *app = freealias(*app);
3287 printalias(const struct alias *ap)
3289 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3293 * TODO - sort output
3295 static int FAST_FUNC
3296 aliascmd(int argc UNUSED_PARAM, char **argv)
3305 for (i = 0; i < ATABSIZE; i++) {
3306 for (ap = atab[i]; ap; ap = ap->next) {
3312 while ((n = *++argv) != NULL) {
3313 v = strchr(n+1, '=');
3314 if (v == NULL) { /* n+1: funny ksh stuff */
3315 ap = *__lookupalias(n);
3317 fprintf(stderr, "%s: %s not found\n", "alias", n);
3330 static int FAST_FUNC
3331 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3335 while ((i = nextopt("a")) != '\0') {
3341 for (i = 0; *argptr; argptr++) {
3342 if (unalias(*argptr)) {
3343 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3351 #endif /* ASH_ALIAS */
3354 /* ============ jobs.c */
3356 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3359 #define FORK_NOJOB 2
3361 /* mode flags for showjob(s) */
3362 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3363 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3364 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3365 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3368 * A job structure contains information about a job. A job is either a
3369 * single process or a set of processes contained in a pipeline. In the
3370 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3374 pid_t ps_pid; /* process id */
3375 int ps_status; /* last process status from wait() */
3376 char *ps_cmd; /* text of command being run */
3380 struct procstat ps0; /* status of process */
3381 struct procstat *ps; /* status or processes when more than one */
3383 int stopstatus; /* status of a stopped job */
3386 nprocs: 16, /* number of processes */
3388 #define JOBRUNNING 0 /* at least one proc running */
3389 #define JOBSTOPPED 1 /* all procs are stopped */
3390 #define JOBDONE 2 /* all procs are completed */
3392 sigint: 1, /* job was killed by SIGINT */
3393 jobctl: 1, /* job running under job control */
3395 waited: 1, /* true if this entry has been waited for */
3396 used: 1, /* true if this entry is in used */
3397 changed: 1; /* true if status has changed */
3398 struct job *prev_job; /* previous job */
3401 static struct job *makejob(/*union node *,*/ int);
3402 static int forkshell(struct job *, union node *, int);
3403 static int waitforjob(struct job *);
3406 enum { doing_jobctl = 0 };
3407 #define setjobctl(on) do {} while (0)
3409 static smallint doing_jobctl; //references:8
3410 static void setjobctl(int);
3417 ignoresig(int signo)
3419 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3420 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3421 /* No, need to do it */
3422 signal(signo, SIG_IGN);
3424 sigmode[signo - 1] = S_HARD_IGN;
3428 * Only one usage site - in setsignal()
3431 signal_handler(int signo)
3433 gotsig[signo - 1] = 1;
3435 if (signo == SIGINT && !trap[SIGINT]) {
3436 if (!suppress_int) {
3438 raise_interrupt(); /* does not return */
3442 pending_sig = signo;
3447 * Set the signal handler for the specified signal. The routine figures
3448 * out what it should be set to.
3451 setsignal(int signo)
3454 char cur_act, new_act;
3455 struct sigaction act;
3459 if (t != NULL) { /* trap for this sig is set */
3461 if (t[0] == '\0') /* trap is "": ignore this sig */
3465 if (rootshell && new_act == S_DFL) {
3468 if (iflag || minusc || sflag == 0)
3477 * "In all cases, bash ignores SIGQUIT. Non-builtin
3478 * commands run by bash have signal handlers
3479 * set to the values inherited by the shell
3480 * from its parent". */
3496 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3497 //whereas we have to restore it to what shell got on entry
3498 //from the parent. See comment above
3500 t = &sigmode[signo - 1];
3503 /* current setting is not yet known */
3504 if (sigaction(signo, NULL, &act)) {
3505 /* pretend it worked; maybe we should give a warning,
3506 * but other shells don't. We don't alter sigmode,
3507 * so we retry every time.
3508 * btw, in Linux it never fails. --vda */
3511 if (act.sa_handler == SIG_IGN) {
3512 cur_act = S_HARD_IGN;
3514 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3516 cur_act = S_IGN; /* don't hard ignore these */
3520 if (cur_act == S_HARD_IGN || cur_act == new_act)
3523 act.sa_handler = SIG_DFL;
3526 act.sa_handler = signal_handler;
3529 act.sa_handler = SIG_IGN;
3533 /* flags and mask matter only if !DFL and !IGN, but we do it
3534 * for all cases for more deterministic behavior:
3537 sigfillset(&act.sa_mask);
3539 sigaction_set(signo, &act);
3544 /* mode flags for set_curjob */
3545 #define CUR_DELETE 2
3546 #define CUR_RUNNING 1
3547 #define CUR_STOPPED 0
3549 /* mode flags for dowait */
3550 #define DOWAIT_NONBLOCK WNOHANG
3551 #define DOWAIT_BLOCK 0
3554 /* pgrp of shell on invocation */
3555 static int initialpgrp; //references:2
3556 static int ttyfd = -1; //5
3559 static struct job *jobtab; //5
3561 static unsigned njobs; //4
3563 static struct job *curjob; //lots
3564 /* number of presumed living untracked jobs */
3565 static int jobless; //4
3568 set_curjob(struct job *jp, unsigned mode)
3571 struct job **jpp, **curp;
3573 /* first remove from list */
3574 jpp = curp = &curjob;
3579 jpp = &jp1->prev_job;
3581 *jpp = jp1->prev_job;
3583 /* Then re-insert in correct position */
3591 /* job being deleted */
3594 /* newly created job or backgrounded job,
3595 * put after all stopped jobs.
3600 if (!jp1 || jp1->state != JOBSTOPPED)
3603 jpp = &jp1->prev_job;
3609 /* newly stopped job - becomes curjob */
3610 jp->prev_job = *jpp;
3618 jobno(const struct job *jp)
3620 return jp - jobtab + 1;
3625 * Convert a job name to a job structure.
3628 #define getjob(name, getctl) getjob(name)
3631 getjob(const char *name, int getctl)
3635 const char *err_msg = "%s: no such job";
3639 char *(*match)(const char *, const char *);
3654 if (c == '+' || c == '%') {
3656 err_msg = "No current job";
3662 err_msg = "No previous job";
3672 if (num > 0 && num <= njobs) {
3673 jp = jobtab + num - 1;
3688 if (match(jp->ps[0].ps_cmd, p)) {
3692 err_msg = "%s: ambiguous";
3702 err_msg = "job %s not created under job control";
3703 if (getctl && jp->jobctl == 0)
3708 ash_msg_and_raise_error(err_msg, name);
3712 * Mark a job structure as unused.
3715 freejob(struct job *jp)
3717 struct procstat *ps;
3721 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3722 if (ps->ps_cmd != nullstr)
3725 if (jp->ps != &jp->ps0)
3728 set_curjob(jp, CUR_DELETE);
3734 xtcsetpgrp(int fd, pid_t pgrp)
3736 if (tcsetpgrp(fd, pgrp))
3737 ash_msg_and_raise_error("can't set tty process group (%m)");
3741 * Turn job control on and off.
3743 * Note: This code assumes that the third arg to ioctl is a character
3744 * pointer, which is true on Berkeley systems but not System V. Since
3745 * System V doesn't have job control yet, this isn't a problem now.
3747 * Called with interrupts off.
3755 if (on == doing_jobctl || rootshell == 0)
3759 ofd = fd = open(_PATH_TTY, O_RDWR);
3761 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3762 * That sometimes helps to acquire controlling tty.
3763 * Obviously, a workaround for bugs when someone
3764 * failed to provide a controlling tty to bash! :) */
3770 fd = fcntl(fd, F_DUPFD, 10);
3775 /* fd is a tty at this point */
3776 close_on_exec_on(fd);
3777 while (1) { /* while we are in the background */
3778 pgrp = tcgetpgrp(fd);
3781 ash_msg("can't access tty; job control turned off");
3785 if (pgrp == getpgrp())
3796 xtcsetpgrp(fd, pgrp);
3798 /* turning job control off */
3801 /* was xtcsetpgrp, but this can make exiting ash
3802 * loop forever if pty is already deleted */
3803 tcsetpgrp(fd, pgrp);
3817 static int FAST_FUNC
3818 killcmd(int argc, char **argv)
3820 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3823 if (argv[i][0] == '%') {
3825 * "kill %N" - job kill
3826 * Converting to pgrp / pid kill
3832 jp = getjob(argv[i], 0);
3834 * In jobs started under job control, we signal
3835 * entire process group by kill -PGRP_ID.
3836 * This happens, f.e., in interactive shell.
3838 * Otherwise, we signal each child via
3839 * kill PID1 PID2 PID3.
3841 * sh -c 'sleep 1|sleep 1 & kill %1'
3842 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3843 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3845 n = jp->nprocs; /* can't be 0 (I hope) */
3848 dst = alloca(n * sizeof(int)*4);
3850 for (j = 0; j < n; j++) {
3851 struct procstat *ps = &jp->ps[j];
3852 /* Skip non-running and not-stopped members
3853 * (i.e. dead members) of the job
3855 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3858 * kill_main has matching code to expect
3859 * leading space. Needed to not confuse
3860 * negative pids with "kill -SIGNAL_NO" syntax
3862 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3866 } while (argv[++i]);
3868 return kill_main(argc, argv);
3872 showpipe(struct job *jp /*, FILE *out*/)
3874 struct procstat *ps;
3875 struct procstat *psend;
3877 psend = jp->ps + jp->nprocs;
3878 for (ps = jp->ps + 1; ps < psend; ps++)
3879 printf(" | %s", ps->ps_cmd);
3880 newline_and_flush(stdout);
3881 flush_stdout_stderr();
3886 restartjob(struct job *jp, int mode)
3888 struct procstat *ps;
3894 if (jp->state == JOBDONE)
3896 jp->state = JOBRUNNING;
3897 pgid = jp->ps[0].ps_pid;
3898 if (mode == FORK_FG)
3899 xtcsetpgrp(ttyfd, pgid);
3900 killpg(pgid, SIGCONT);
3904 if (WIFSTOPPED(ps->ps_status)) {
3910 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3915 static int FAST_FUNC
3916 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3922 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3926 jp = getjob(*argv, 1);
3927 if (mode == FORK_BG) {
3928 set_curjob(jp, CUR_RUNNING);
3929 printf("[%d] ", jobno(jp));
3931 out1str(jp->ps[0].ps_cmd);
3932 showpipe(jp /*, stdout*/);
3933 retval = restartjob(jp, mode);
3934 } while (*argv && *++argv);
3940 sprint_status48(char *s, int status, int sigonly)
3946 if (!WIFEXITED(status)) {
3947 if (JOBS && WIFSTOPPED(status))
3948 st = WSTOPSIG(status);
3950 st = WTERMSIG(status);
3952 if (st == SIGINT || st == SIGPIPE)
3954 if (JOBS && WIFSTOPPED(status))
3958 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3959 col = fmtstr(s, 32, strsignal(st));
3960 if (WCOREDUMP(status)) {
3961 strcpy(s + col, " (core dumped)");
3962 col += sizeof(" (core dumped)")-1;
3964 } else if (!sigonly) {
3965 st = WEXITSTATUS(status);
3966 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
3973 dowait(int wait_flags, struct job *job)
3978 struct job *thisjob;
3980 TRACE(("dowait(0x%x) called\n", wait_flags));
3982 /* Do a wait system call. If job control is compiled in, we accept
3983 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3984 * NB: _not_ safe_waitpid, we need to detect EINTR */
3986 wait_flags |= WUNTRACED;
3987 pid = waitpid(-1, &status, wait_flags);
3988 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3989 pid, status, errno, strerror(errno)));
3995 for (jp = curjob; jp; jp = jp->prev_job) {
3997 struct procstat *ps;
3998 struct procstat *psend;
3999 if (jp->state == JOBDONE)
4003 psend = ps + jp->nprocs;
4005 if (ps->ps_pid == pid) {
4006 TRACE(("Job %d: changing status of proc %d "
4007 "from 0x%x to 0x%x\n",
4008 jobno(jp), pid, ps->ps_status, status));
4009 ps->ps_status = status;
4012 if (ps->ps_status == -1)
4013 jobstate = JOBRUNNING;
4015 if (jobstate == JOBRUNNING)
4017 if (WIFSTOPPED(ps->ps_status)) {
4018 jp->stopstatus = ps->ps_status;
4019 jobstate = JOBSTOPPED;
4022 } while (++ps < psend);
4026 /* Found the job where one of its processes changed its state.
4027 * Is there at least one live and running process in this job? */
4028 if (jobstate != JOBRUNNING) {
4029 /* No. All live processes in the job are stopped
4030 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4032 thisjob->changed = 1;
4033 if (thisjob->state != jobstate) {
4034 TRACE(("Job %d: changing state from %d to %d\n",
4035 jobno(thisjob), thisjob->state, jobstate));
4036 thisjob->state = jobstate;
4038 if (jobstate == JOBSTOPPED)
4039 set_curjob(thisjob, CUR_STOPPED);
4045 /* The process wasn't found in job list */
4046 if (JOBS && !WIFSTOPPED(status))
4051 if (thisjob && thisjob == job) {
4055 len = sprint_status48(s, status, 1);
4066 blocking_wait_with_raise_on_sig(void)
4068 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
4069 if (pid <= 0 && pending_sig)
4070 raise_exception(EXSIG);
4076 showjob(struct job *jp, int mode)
4078 struct procstat *ps;
4079 struct procstat *psend;
4082 char s[16 + 16 + 48];
4083 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4087 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4088 /* just output process (group) id of pipeline */
4089 fprintf(out, "%d\n", ps->ps_pid);
4093 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4098 else if (curjob && jp == curjob->prev_job)
4101 if (mode & SHOW_PIDS)
4102 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4104 psend = ps + jp->nprocs;
4106 if (jp->state == JOBRUNNING) {
4107 strcpy(s + col, "Running");
4108 col += sizeof("Running") - 1;
4110 int status = psend[-1].ps_status;
4111 if (jp->state == JOBSTOPPED)
4112 status = jp->stopstatus;
4113 col += sprint_status48(s + col, status, 0);
4115 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4117 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4118 * or prints several "PID | <cmdN>" lines,
4119 * depending on SHOW_PIDS bit.
4120 * We do not print status of individual processes
4121 * between PID and <cmdN>. bash does it, but not very well:
4122 * first line shows overall job status, not process status,
4123 * making it impossible to know 1st process status.
4127 /* for each process */
4130 if (mode & SHOW_PIDS)
4131 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4133 fprintf(out, "%s%*c%s%s",
4135 33 - col >= 0 ? 33 - col : 0, ' ',
4136 ps == jp->ps ? "" : "| ",
4139 } while (++ps != psend);
4140 newline_and_flush(out);
4144 if (jp->state == JOBDONE) {
4145 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4151 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4152 * statuses have changed since the last call to showjobs.
4159 TRACE(("showjobs(0x%x) called\n", mode));
4161 /* Handle all finished jobs */
4162 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4165 for (jp = curjob; jp; jp = jp->prev_job) {
4166 if (!(mode & SHOW_CHANGED) || jp->changed) {
4172 static int FAST_FUNC
4173 jobscmd(int argc UNUSED_PARAM, char **argv)
4178 while ((m = nextopt("lp")) != '\0') {
4182 mode |= SHOW_ONLY_PGID;
4188 showjob(getjob(*argv, 0), mode);
4198 /* Called only on finished or stopped jobs (no members are running) */
4200 getstatus(struct job *job)
4204 struct procstat *ps;
4206 /* Fetch last member's status */
4207 ps = job->ps + job->nprocs - 1;
4208 status = ps->ps_status;
4210 /* "set -o pipefail" mode: use last _nonzero_ status */
4211 while (status == 0 && --ps >= job->ps)
4212 status = ps->ps_status;
4215 retval = WEXITSTATUS(status);
4216 if (!WIFEXITED(status)) {
4218 retval = WSTOPSIG(status);
4219 if (!WIFSTOPPED(status))
4222 /* XXX: limits number of signals */
4223 retval = WTERMSIG(status);
4225 if (retval == SIGINT)
4231 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4232 jobno(job), job->nprocs, status, retval));
4236 static int FAST_FUNC
4237 waitcmd(int argc UNUSED_PARAM, char **argv)
4244 raise_exception(EXSIG);
4251 /* wait for all jobs */
4255 if (!jp) /* no running procs */
4257 if (jp->state == JOBRUNNING)
4262 blocking_wait_with_raise_on_sig();
4264 * "When bash is waiting for an asynchronous command via
4265 * the wait builtin, the reception of a signal for which a trap
4266 * has been set will cause the wait builtin to return immediately
4267 * with an exit status greater than 128, immediately after which
4268 * the trap is executed."
4270 * blocking_wait_with_raise_on_sig raises signal handlers
4271 * if it gets no pid (pid < 0). However,
4272 * if child sends us a signal *and immediately exits*,
4273 * blocking_wait_with_raise_on_sig gets pid > 0
4274 * and does not handle pending_sig. Check this case: */
4276 raise_exception(EXSIG);
4282 if (**argv != '%') {
4283 pid_t pid = number(*argv);
4288 if (job->ps[job->nprocs - 1].ps_pid == pid)
4290 job = job->prev_job;
4293 job = getjob(*argv, 0);
4295 /* loop until process terminated or stopped */
4296 while (job->state == JOBRUNNING)
4297 blocking_wait_with_raise_on_sig();
4299 retval = getstatus(job);
4312 struct job *jp, *jq;
4314 len = njobs * sizeof(*jp);
4316 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4318 offset = (char *)jp - (char *)jq;
4320 /* Relocate pointers */
4323 jq = (struct job *)((char *)jq + l);
4327 #define joff(p) ((struct job *)((char *)(p) + l))
4328 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4329 if (joff(jp)->ps == &jq->ps0)
4330 jmove(joff(jp)->ps);
4331 if (joff(jp)->prev_job)
4332 jmove(joff(jp)->prev_job);
4342 jp = (struct job *)((char *)jp + len);
4346 } while (--jq >= jp);
4351 * Return a new job structure.
4352 * Called with interrupts off.
4355 makejob(/*union node *node,*/ int nprocs)
4360 for (i = njobs, jp = jobtab; ; jp++) {
4367 if (jp->state != JOBDONE || !jp->waited)
4376 memset(jp, 0, sizeof(*jp));
4378 /* jp->jobctl is a bitfield.
4379 * "jp->jobctl |= jobctl" likely to give awful code */
4383 jp->prev_job = curjob;
4388 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4390 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4397 * Return a string identifying a command (to be printed by the
4400 static char *cmdnextc;
4403 cmdputs(const char *s)
4405 static const char vstype[VSTYPE + 1][3] = {
4406 "", "}", "-", "+", "?", "=",
4407 "%", "%%", "#", "##"
4408 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4411 const char *p, *str;
4415 unsigned char subtype = 0;
4419 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4421 while ((c = *p++) != '\0') {
4429 if ((subtype & VSTYPE) == VSLENGTH)
4435 str = "\"}" + !(quoted & 1);
4442 #if ENABLE_SH_MATH_SUPPORT
4457 if ((subtype & VSTYPE) != VSNORMAL)
4459 str = vstype[subtype & VSTYPE];
4460 if (subtype & VSNUL)
4469 /* These can only happen inside quotes */
4482 while ((c = *str++) != '\0') {
4485 } /* while *p++ not NUL */
4488 USTPUTC('"', nextc);
4494 /* cmdtxt() and cmdlist() call each other */
4495 static void cmdtxt(union node *n);
4498 cmdlist(union node *np, int sep)
4500 for (; np; np = np->narg.next) {
4504 if (sep && np->narg.next)
4510 cmdtxt(union node *n)
4513 struct nodelist *lp;
4524 lp = n->npipe.cmdlist;
4542 cmdtxt(n->nbinary.ch1);
4558 cmdtxt(n->nif.test);
4560 if (n->nif.elsepart) {
4561 cmdtxt(n->nif.ifpart);
4563 n = n->nif.elsepart;
4581 cmdtxt(n->nbinary.ch1);
4591 cmdputs(n->nfor.var);
4593 cmdlist(n->nfor.args, 1);
4598 cmdputs(n->narg.text);
4602 cmdlist(n->ncmd.args, 1);
4603 cmdlist(n->ncmd.redirect, 0);
4616 cmdputs(n->ncase.expr->narg.text);
4618 for (np = n->ncase.cases; np; np = np->nclist.next) {
4619 cmdtxt(np->nclist.pattern);
4621 cmdtxt(np->nclist.body);
4635 #if ENABLE_ASH_BASH_COMPAT
4650 cmdputs(utoa(n->nfile.fd));
4652 if (n->type == NTOFD || n->type == NFROMFD) {
4653 cmdputs(utoa(n->ndup.dupfd));
4662 commandtext(union node *n)
4666 STARTSTACKSTR(cmdnextc);
4668 name = stackblock();
4669 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4670 name, cmdnextc, cmdnextc));
4671 return ckstrdup(name);
4676 * Fork off a subshell. If we are doing job control, give the subshell its
4677 * own process group. Jp is a job structure that the job is to be added to.
4678 * N is the command that will be evaluated by the child. Both jp and n may
4679 * be NULL. The mode parameter can be one of the following:
4680 * FORK_FG - Fork off a foreground process.
4681 * FORK_BG - Fork off a background process.
4682 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4683 * process group even if job control is on.
4685 * When job control is turned off, background processes have their standard
4686 * input redirected to /dev/null (except for the second and later processes
4689 * Called with interrupts off.
4692 * Clear traps on a fork.
4699 for (tp = trap; tp < &trap[NSIG]; tp++) {
4700 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4702 if (trap_ptr == trap)
4704 /* else: it "belongs" to trap_ptr vector, don't free */
4706 if ((tp - trap) != 0)
4707 setsignal(tp - trap);
4714 /* Lives far away from here, needed for forkchild */
4715 static void closescript(void);
4717 /* Called after fork(), in child */
4718 static NOINLINE void
4719 forkchild(struct job *jp, union node *n, int mode)
4723 TRACE(("Child shell %d\n", getpid()));
4727 /* man bash: "Non-builtin commands run by bash have signal handlers
4728 * set to the values inherited by the shell from its parent".
4729 * Do we do it correctly? */
4733 if (mode == FORK_NOJOB /* is it `xxx` ? */
4734 && n && n->type == NCMD /* is it single cmd? */
4735 /* && n->ncmd.args->type == NARG - always true? */
4736 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4737 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4738 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4740 TRACE(("Trap hack\n"));
4741 /* Awful hack for `trap` or $(trap).
4743 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4744 * contains an example where "trap" is executed in a subshell:
4746 * save_traps=$(trap)
4748 * eval "$save_traps"
4750 * Standard does not say that "trap" in subshell shall print
4751 * parent shell's traps. It only says that its output
4752 * must have suitable form, but then, in the above example
4753 * (which is not supposed to be normative), it implies that.
4755 * bash (and probably other shell) does implement it
4756 * (traps are reset to defaults, but "trap" still shows them),
4757 * but as a result, "trap" logic is hopelessly messed up:
4760 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4761 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4762 * # true | trap <--- trap is in subshell - no output (ditto)
4763 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4764 * trap -- 'echo Ho' SIGWINCH
4765 * # echo `(trap)` <--- in subshell in subshell - output
4766 * trap -- 'echo Ho' SIGWINCH
4767 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4768 * trap -- 'echo Ho' SIGWINCH
4770 * The rules when to forget and when to not forget traps
4771 * get really complex and nonsensical.
4773 * Our solution: ONLY bare $(trap) or `trap` is special.
4775 /* Save trap handler strings for trap builtin to print */
4776 trap_ptr = xmemdup(trap, sizeof(trap));
4777 /* Fall through into clearing traps */
4781 /* do job control only in root shell */
4783 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4786 if (jp->nprocs == 0)
4789 pgrp = jp->ps[0].ps_pid;
4790 /* this can fail because we are doing it in the parent also */
4792 if (mode == FORK_FG)
4793 xtcsetpgrp(ttyfd, pgrp);
4798 if (mode == FORK_BG) {
4799 /* man bash: "When job control is not in effect,
4800 * asynchronous commands ignore SIGINT and SIGQUIT" */
4803 if (jp->nprocs == 0) {
4805 if (open(bb_dev_null, O_RDONLY) != 0)
4806 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4810 if (iflag) { /* why if iflag only? */
4815 * "In all cases, bash ignores SIGQUIT. Non-builtin
4816 * commands run by bash have signal handlers
4817 * set to the values inherited by the shell
4819 * Take care of the second rule: */
4823 if (n && n->type == NCMD
4824 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4826 TRACE(("Job hack\n"));
4827 /* "jobs": we do not want to clear job list for it,
4828 * instead we remove only _its_ own_ job from job list.
4829 * This makes "jobs .... | cat" more useful.
4835 for (jp = curjob; jp; jp = jp->prev_job)
4840 /* Called after fork(), in parent */
4842 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4845 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4847 TRACE(("In parent shell: child = %d\n", pid));
4849 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4855 if (mode != FORK_NOJOB && jp->jobctl) {
4858 if (jp->nprocs == 0)
4861 pgrp = jp->ps[0].ps_pid;
4862 /* This can fail because we are doing it in the child also */
4866 if (mode == FORK_BG) {
4867 backgndpid = pid; /* set $! */
4868 set_curjob(jp, CUR_RUNNING);
4871 struct procstat *ps = &jp->ps[jp->nprocs++];
4874 ps->ps_cmd = nullstr;
4876 if (doing_jobctl && n)
4877 ps->ps_cmd = commandtext(n);
4883 forkshell(struct job *jp, union node *n, int mode)
4887 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4890 TRACE(("Fork failed, errno=%d", errno));
4893 ash_msg_and_raise_error("can't fork");
4896 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4897 forkchild(jp, n, mode);
4899 forkparent(jp, n, mode, pid);
4905 * Wait for job to finish.
4907 * Under job control we have the problem that while a child process
4908 * is running interrupts generated by the user are sent to the child
4909 * but not to the shell. This means that an infinite loop started by
4910 * an interactive user may be hard to kill. With job control turned off,
4911 * an interactive user may place an interactive program inside a loop.
4912 * If the interactive program catches interrupts, the user doesn't want
4913 * these interrupts to also abort the loop. The approach we take here
4914 * is to have the shell ignore interrupt signals while waiting for a
4915 * foreground process to terminate, and then send itself an interrupt
4916 * signal if the child process was terminated by an interrupt signal.
4917 * Unfortunately, some programs want to do a bit of cleanup and then
4918 * exit on interrupt; unless these processes terminate themselves by
4919 * sending a signal to themselves (instead of calling exit) they will
4920 * confuse this approach.
4922 * Called with interrupts off.
4925 waitforjob(struct job *jp)
4929 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4932 while (jp->state == JOBRUNNING) {
4933 /* In non-interactive shells, we _can_ get
4934 * a keyboard signal here and be EINTRed,
4935 * but we just loop back, waiting for command to complete.
4938 * "If bash is waiting for a command to complete and receives
4939 * a signal for which a trap has been set, the trap
4940 * will not be executed until the command completes."
4942 * Reality is that even if trap is not set, bash
4943 * will not act on the signal until command completes.
4944 * Try this. sleep5intoff.c:
4945 * #include <signal.h>
4946 * #include <unistd.h>
4949 * sigemptyset(&set);
4950 * sigaddset(&set, SIGINT);
4951 * sigaddset(&set, SIGQUIT);
4952 * sigprocmask(SIG_BLOCK, &set, NULL);
4956 * $ bash -c './sleep5intoff; echo hi'
4957 * ^C^C^C^C <--- pressing ^C once a second
4959 * $ bash -c './sleep5intoff; echo hi'
4960 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4963 dowait(DOWAIT_BLOCK, jp);
4970 xtcsetpgrp(ttyfd, rootpid);
4972 * This is truly gross.
4973 * If we're doing job control, then we did a TIOCSPGRP which
4974 * caused us (the shell) to no longer be in the controlling
4975 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4976 * intuit from the subprocess exit status whether a SIGINT
4977 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4979 if (jp->sigint) /* TODO: do the same with all signals */
4980 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4982 if (jp->state == JOBDONE)
4989 * return 1 if there are stopped jobs, otherwise 0
5001 if (jp && jp->state == JOBSTOPPED) {
5002 out2str("You have stopped jobs.\n");
5011 /* ============ redir.c
5013 * Code for dealing with input/output redirection.
5018 #define EMPTY -2 /* marks an unused slot in redirtab */
5019 #define CLOSED -3 /* marks a slot of previously-closed fd */
5022 * Open a file in noclobber mode.
5023 * The code was copied from bash.
5026 noclobberopen(const char *fname)
5029 struct stat finfo, finfo2;
5032 * If the file exists and is a regular file, return an error
5035 r = stat(fname, &finfo);
5036 if (r == 0 && S_ISREG(finfo.st_mode)) {
5042 * If the file was not present (r != 0), make sure we open it
5043 * exclusively so that if it is created before we open it, our open
5044 * will fail. Make sure that we do not truncate an existing file.
5045 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5046 * file was not a regular file, we leave O_EXCL off.
5049 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5050 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5052 /* If the open failed, return the file descriptor right away. */
5057 * OK, the open succeeded, but the file may have been changed from a
5058 * non-regular file to a regular file between the stat and the open.
5059 * We are assuming that the O_EXCL open handles the case where FILENAME
5060 * did not exist and is symlinked to an existing file between the stat
5065 * If we can open it and fstat the file descriptor, and neither check
5066 * revealed that it was a regular file, and the file has not been
5067 * replaced, return the file descriptor.
5069 if (fstat(fd, &finfo2) == 0
5070 && !S_ISREG(finfo2.st_mode)
5071 && finfo.st_dev == finfo2.st_dev
5072 && finfo.st_ino == finfo2.st_ino
5077 /* The file has been replaced. badness. */
5084 * Handle here documents. Normally we fork off a process to write the
5085 * data to a pipe. If the document is short, we can stuff the data in
5086 * the pipe without forking.
5088 /* openhere needs this forward reference */
5089 static void expandhere(union node *arg, int fd);
5091 openhere(union node *redir)
5097 ash_msg_and_raise_error("pipe call failed");
5098 if (redir->type == NHERE) {
5099 len = strlen(redir->nhere.doc->narg.text);
5100 if (len <= PIPE_BUF) {
5101 full_write(pip[1], redir->nhere.doc->narg.text, len);
5105 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5108 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5109 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5110 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5111 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5112 signal(SIGPIPE, SIG_DFL);
5113 if (redir->type == NHERE)
5114 full_write(pip[1], redir->nhere.doc->narg.text, len);
5116 expandhere(redir->nhere.doc, pip[1]);
5117 _exit(EXIT_SUCCESS);
5125 openredirect(union node *redir)
5130 switch (redir->nfile.type) {
5131 /* Can't happen, our single caller does this itself */
5137 return openhere(redir);
5140 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5141 * allocated space. Do it only when we know it is safe.
5143 fname = redir->nfile.expfname;
5145 switch (redir->nfile.type) {
5151 f = open(fname, O_RDONLY);
5156 f = open(fname, O_RDWR|O_CREAT, 0666);
5161 #if ENABLE_ASH_BASH_COMPAT
5164 /* Take care of noclobber mode. */
5166 f = noclobberopen(fname);
5173 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5178 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5186 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5188 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5192 * Copy a file descriptor to be >= to. Returns -1
5193 * if the source file descriptor is closed, EMPTY if there are no unused
5194 * file descriptors left.
5196 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5197 * old code was doing close(to) prior to copyfd() to achieve the same */
5199 COPYFD_EXACT = (int)~(INT_MAX),
5200 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5203 copyfd(int from, int to)
5207 if (to & COPYFD_EXACT) {
5208 to &= ~COPYFD_EXACT;
5210 newfd = dup2(from, to);
5212 newfd = fcntl(from, F_DUPFD, to);
5215 if (errno == EMFILE)
5217 /* Happens when source fd is not open: try "echo >&99" */
5218 ash_msg_and_raise_error("%d: %m", from);
5223 /* Struct def and variable are moved down to the first usage site */
5228 struct redirtab *next;
5231 struct two_fd_t two_fd[];
5233 #define redirlist (G_var.redirlist)
5235 static int need_to_remember(struct redirtab *rp, int fd)
5239 if (!rp) /* remembering was not requested */
5242 for (i = 0; i < rp->pair_count; i++) {
5243 if (rp->two_fd[i].orig == fd) {
5244 /* already remembered */
5251 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5252 static int is_hidden_fd(struct redirtab *rp, int fd)
5255 struct parsefile *pf;
5259 /* Check open scripts' fds */
5262 /* We skip pf_fd == 0 case because of the following case:
5263 * $ ash # running ash interactively
5265 * and in script.sh: "exec 9>&0".
5266 * Even though top-level pf_fd _is_ 0,
5267 * it's still ok to use it: "read" builtin uses it,
5268 * why should we cripple "exec" builtin?
5270 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5278 /* Check saved fds of redirects */
5279 fd |= COPYFD_RESTORE;
5280 for (i = 0; i < rp->pair_count; i++) {
5281 if (rp->two_fd[i].copy == fd) {
5289 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5290 * old file descriptors are stashed away so that the redirection can be
5291 * undone by calling popredir.
5293 /* flags passed to redirect */
5294 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5295 #define REDIR_SAVEFD2 03 /* set preverrout */
5297 redirect(union node *redir, int flags)
5299 struct redirtab *sv;
5304 int copied_fd2 = -1;
5314 if (flags & REDIR_PUSH) {
5315 union node *tmp = redir;
5318 #if ENABLE_ASH_BASH_COMPAT
5319 if (tmp->nfile.type == NTO2)
5322 tmp = tmp->nfile.next;
5324 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5325 sv->next = redirlist;
5326 sv->pair_count = sv_pos;
5328 sv->nullredirs = g_nullredirs - 1;
5330 while (sv_pos > 0) {
5332 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5338 fd = redir->nfile.fd;
5339 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5340 right_fd = redir->ndup.dupfd;
5341 //bb_error_msg("doing %d > %d", fd, right_fd);
5342 /* redirect from/to same file descriptor? */
5345 /* "echo >&10" and 10 is a fd opened to a sh script? */
5346 if (is_hidden_fd(sv, right_fd)) {
5347 errno = EBADF; /* as if it is closed */
5348 ash_msg_and_raise_error("%d: %m", right_fd);
5352 newfd = openredirect(redir); /* always >= 0 */
5354 /* Descriptor wasn't open before redirect.
5355 * Mark it for close in the future */
5356 if (need_to_remember(sv, fd)) {
5357 goto remember_to_close;
5362 #if ENABLE_ASH_BASH_COMPAT
5365 if (need_to_remember(sv, fd)) {
5366 /* Copy old descriptor */
5367 /* Careful to not accidentally "save"
5368 * to the same fd as right side fd in N>&M */
5369 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5370 i = fcntl(fd, F_DUPFD, minfd);
5371 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5372 * are closed in popredir() in the child, preventing them from leaking
5373 * into child. (popredir() also cleans up the mess in case of failures)
5378 /* Strange error (e.g. "too many files" EMFILE?) */
5382 ash_msg_and_raise_error("%d: %m", fd);
5385 /* EBADF: it is not open - good, remember to close it */
5388 } else { /* fd is open, save its copy */
5389 /* "exec fd>&-" should not close fds
5390 * which point to script file(s).
5391 * Force them to be restored afterwards */
5392 if (is_hidden_fd(sv, fd))
5393 i |= COPYFD_RESTORE;
5397 sv->two_fd[sv_pos].orig = fd;
5398 sv->two_fd[sv_pos].copy = i;
5402 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5403 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5404 /* Don't want to trigger debugging */
5408 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5410 } else if (fd != newfd) { /* move newfd to fd */
5411 copyfd(newfd, fd | COPYFD_EXACT);
5412 #if ENABLE_ASH_BASH_COMPAT
5413 if (!(redir->nfile.type == NTO2 && fd == 2))
5417 #if ENABLE_ASH_BASH_COMPAT
5418 if (redir->nfile.type == NTO2 && fd == 1) {
5419 /* We already redirected it to fd 1, now copy it to 2 */
5425 } while ((redir = redir->nfile.next) != NULL);
5428 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5429 preverrout_fd = copied_fd2;
5433 * Undo the effects of the last redirection.
5436 popredir(int drop, int restore)
5438 struct redirtab *rp;
5441 if (--g_nullredirs >= 0 || redirlist == NULL)
5445 for (i = 0; i < rp->pair_count; i++) {
5446 int fd = rp->two_fd[i].orig;
5447 int copy = rp->two_fd[i].copy;
5448 if (copy == CLOSED) {
5453 if (copy != EMPTY) {
5454 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5455 copy &= ~COPYFD_RESTORE;
5457 copyfd(copy, fd | COPYFD_EXACT);
5459 close(copy & ~COPYFD_RESTORE);
5462 redirlist = rp->next;
5463 g_nullredirs = rp->nullredirs;
5469 * Undo all redirections. Called on error or interrupt.
5473 * Discard all saved file descriptors.
5476 clearredir(int drop)
5482 popredir(drop, /*restore:*/ 0);
5487 redirectsafe(union node *redir, int flags)
5490 volatile int saveint;
5491 struct jmploc *volatile savehandler = exception_handler;
5492 struct jmploc jmploc;
5495 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5496 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5498 exception_handler = &jmploc;
5499 redirect(redir, flags);
5501 exception_handler = savehandler;
5502 if (err && exception_type != EXERROR)
5503 longjmp(exception_handler->loc, 1);
5504 RESTORE_INT(saveint);
5509 /* ============ Routines to expand arguments to commands
5511 * We have to deal with backquotes, shell variables, and file metacharacters.
5514 #if ENABLE_SH_MATH_SUPPORT
5516 ash_arith(const char *s)
5518 arith_state_t math_state;
5521 math_state.lookupvar = lookupvar;
5522 math_state.setvar = setvar0;
5523 //math_state.endofname = endofname;
5526 result = arith(&math_state, s);
5527 if (math_state.errmsg)
5528 ash_msg_and_raise_error(math_state.errmsg);
5538 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5539 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5540 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5541 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5542 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5543 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5544 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5545 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5546 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5550 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5551 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5552 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5553 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5554 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5556 /* Add CTLESC when necessary. */
5557 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5558 /* Do not skip NUL characters. */
5559 #define QUOTES_KEEPNUL EXP_TILDE
5562 * Structure specifying which parts of the string should be searched
5563 * for IFS characters.
5566 struct ifsregion *next; /* next region in list */
5567 int begoff; /* offset of start of region */
5568 int endoff; /* offset of end of region */
5569 int nulonly; /* search for nul bytes only */
5573 struct strlist *list;
5574 struct strlist **lastp;
5577 /* output of current string */
5578 static char *expdest;
5579 /* list of back quote expressions */
5580 static struct nodelist *argbackq;
5581 /* first struct in list of ifs regions */
5582 static struct ifsregion ifsfirst;
5583 /* last struct in list */
5584 static struct ifsregion *ifslastp;
5585 /* holds expanded arg list */
5586 static struct arglist exparg;
5591 #if !ENABLE_SH_MATH_SUPPORT
5592 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5593 typedef long arith_t;
5594 # define ARITH_FMT "%ld"
5601 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5602 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5603 STADJUST(len, expdest);
5608 esclen(const char *start, const char *p)
5612 while (p > start && (unsigned char)*--p == CTLESC) {
5619 * Remove any CTLESC characters from a string.
5622 rmescapes(char *str, int flag)
5624 static const char qchars[] ALIGN1 = {
5625 IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
5629 unsigned protect_against_glob;
5631 IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
5633 p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
5639 if (flag & RMESCAPE_ALLOC) {
5640 size_t len = p - str;
5641 size_t fulllen = len + strlen(p) + 1;
5643 if (flag & RMESCAPE_GROW) {
5644 int strloc = str - (char *)stackblock();
5645 r = makestrspace(fulllen, expdest);
5646 /* p and str may be invalidated by makestrspace */
5647 str = (char *)stackblock() + strloc;
5649 } else if (flag & RMESCAPE_HEAP) {
5650 r = ckmalloc(fulllen);
5652 r = stalloc(fulllen);
5656 q = (char *)memcpy(q, str, len) + len;
5661 globbing = flag & RMESCAPE_GLOB;
5662 protect_against_glob = globbing;
5664 if ((unsigned char)*p == CTLQUOTEMARK) {
5665 // Note: both inquotes and protect_against_glob only affect whether
5666 inquotes = ~inquotes;
5668 protect_against_glob = globbing;
5671 if ((unsigned char)*p == CTLESC) {
5675 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5677 if (protect_against_glob) {
5680 } else if (*p == '\\' && !inquotes) {
5681 /* naked back slash */
5682 protect_against_glob = 0;
5685 #if ENABLE_ASH_BASH_COMPAT
5686 else if (*p == '/' && slash) {
5687 /* stop handling globbing and mark location of slash */
5688 globbing = slash = 0;
5692 protect_against_glob = globbing;
5697 if (flag & RMESCAPE_GROW) {
5699 STADJUST(q - r + 1, expdest);
5703 #define pmatch(a, b) !fnmatch((a), (b), 0)
5706 * Prepare a pattern for a expmeta (internal glob(3)) call.
5708 * Returns an stalloced string.
5711 preglob(const char *pattern, int flag)
5713 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5717 * Put a string on the stack.
5720 memtodest(const char *p, size_t len, int syntax, int quotes)
5727 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5730 unsigned char c = *p++;
5732 int n = SIT(c, syntax);
5733 if ((quotes & QUOTES_ESC)
5735 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
5741 } else if (!(quotes & QUOTES_KEEPNUL))
5750 strtodest(const char *p, int syntax, int quotes)
5752 size_t len = strlen(p);
5753 memtodest(p, len, syntax, quotes);
5758 * Record the fact that we have to scan this region of the
5759 * string for IFS characters.
5762 recordregion(int start, int end, int nulonly)
5764 struct ifsregion *ifsp;
5766 if (ifslastp == NULL) {
5770 ifsp = ckzalloc(sizeof(*ifsp));
5771 /*ifsp->next = NULL; - ckzalloc did it */
5772 ifslastp->next = ifsp;
5776 ifslastp->begoff = start;
5777 ifslastp->endoff = end;
5778 ifslastp->nulonly = nulonly;
5782 removerecordregions(int endoff)
5784 if (ifslastp == NULL)
5787 if (ifsfirst.endoff > endoff) {
5788 while (ifsfirst.next) {
5789 struct ifsregion *ifsp;
5791 ifsp = ifsfirst.next->next;
5792 free(ifsfirst.next);
5793 ifsfirst.next = ifsp;
5796 if (ifsfirst.begoff > endoff) {
5799 ifslastp = &ifsfirst;
5800 ifsfirst.endoff = endoff;
5805 ifslastp = &ifsfirst;
5806 while (ifslastp->next && ifslastp->next->begoff < endoff)
5807 ifslastp = ifslastp->next;
5808 while (ifslastp->next) {
5809 struct ifsregion *ifsp;
5811 ifsp = ifslastp->next->next;
5812 free(ifslastp->next);
5813 ifslastp->next = ifsp;
5816 if (ifslastp->endoff > endoff)
5817 ifslastp->endoff = endoff;
5821 exptilde(char *startp, char *p, int flags)
5827 int quotes = flags & QUOTES_ESC;
5831 while ((c = *++p) != '\0') {
5838 if (flags & EXP_VARTILDE)
5848 if (*name == '\0') {
5849 home = lookupvar("HOME");
5851 pw = getpwnam(name);
5856 if (!home || !*home)
5859 strtodest(home, SQSYNTAX, quotes);
5867 * Execute a command inside back quotes. If it's a builtin command, we
5868 * want to save its output in a block obtained from malloc. Otherwise
5869 * we fork off a subprocess and get the output of the command via a pipe.
5870 * Should be called with interrupts off.
5872 struct backcmd { /* result of evalbackcmd */
5873 int fd; /* file descriptor to read from */
5874 int nleft; /* number of chars in buffer */
5875 char *buf; /* buffer */
5876 struct job *jp; /* job structure for command */
5879 /* These forward decls are needed to use "eval" code for backticks handling: */
5880 static uint8_t back_exitstatus; /* exit status of backquoted command */
5881 #define EV_EXIT 01 /* exit after evaluating tree */
5882 static int evaltree(union node *, int);
5884 static void FAST_FUNC
5885 evalbackcmd(union node *n, struct backcmd *result)
5896 saveherefd = herefd;
5904 ash_msg_and_raise_error("pipe call failed");
5905 jp = makejob(/*n,*/ 1);
5906 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5911 copyfd(pip[1], 1 | COPYFD_EXACT);
5915 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5919 result->fd = pip[0];
5922 herefd = saveherefd;
5924 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5925 result->fd, result->buf, result->nleft, result->jp));
5929 * Expand stuff in backwards quotes.
5932 expbackq(union node *cmd, int flag)
5940 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
5941 struct stackmark smark;
5944 startloc = expdest - (char *)stackblock();
5945 pushstackmark(&smark, startloc);
5946 evalbackcmd(cmd, &in);
5947 popstackmark(&smark);
5954 memtodest(p, i, syntax, flag & QUOTES_ESC);
5958 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
5959 TRACE(("expbackq: read returns %d\n", i));
5968 back_exitstatus = waitforjob(in.jp);
5972 /* Eat all trailing newlines */
5974 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5978 if (!(flag & EXP_QUOTED))
5979 recordregion(startloc, dest - (char *)stackblock(), 0);
5980 TRACE(("evalbackq: size:%d:'%.*s'\n",
5981 (int)((dest - (char *)stackblock()) - startloc),
5982 (int)((dest - (char *)stackblock()) - startloc),
5983 stackblock() + startloc));
5986 #if ENABLE_SH_MATH_SUPPORT
5988 * Expand arithmetic expression. Backup to start of expression,
5989 * evaluate, place result in (backed up) result, adjust string position.
6001 * This routine is slightly over-complicated for
6002 * efficiency. Next we scan backwards looking for the
6003 * start of arithmetic.
6005 start = stackblock();
6012 while ((unsigned char)*p != CTLARI) {
6016 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6021 esc = esclen(start, p);
6031 removerecordregions(begoff);
6035 if (flag & QUOTES_ESC)
6036 rmescapes(p + 1, 0);
6038 len = cvtnum(ash_arith(p + 1));
6040 if (!(flag & EXP_QUOTED))
6041 recordregion(begoff, begoff + len, 0);
6045 /* argstr needs it */
6046 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6049 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6050 * characters to allow for further processing. Otherwise treat
6051 * $@ like $* since no splitting will be performed.
6053 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6054 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6055 * for correct expansion of "B=$A" word.
6058 argstr(char *p, int flags, struct strlist *var_str_list)
6060 static const char spclchars[] ALIGN1 = {
6068 #if ENABLE_SH_MATH_SUPPORT
6073 const char *reject = spclchars;
6074 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6079 if (!(flags & EXP_VARTILDE)) {
6081 } else if (flags & EXP_VARTILDE2) {
6086 if (flags & EXP_TILDE) {
6089 flags &= ~EXP_TILDE;
6093 p = exptilde(p, q, flags);
6096 startloc = expdest - (char *)stackblock();
6100 length += strcspn(p + length, reject);
6104 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6106 /* c == '=' || c == ':' || c == CTLENDARI */
6112 expdest = stack_nputstr(p, length, expdest);
6113 newloc = expdest - (char *)stackblock();
6114 if (breakall && !inquotes && newloc > startloc) {
6115 recordregion(startloc, newloc, 0);
6126 if (flags & EXP_VARTILDE2) {
6130 flags |= EXP_VARTILDE2;
6135 * sort of a hack - expand tildes in variable
6136 * assignments (after the first '=' and after ':'s).
6145 case CTLENDVAR: /* ??? */
6148 inquotes ^= EXP_QUOTED;
6149 /* "$@" syntax adherence hack */
6150 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6151 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6155 if (flags & QUOTES_ESC) {
6166 * Quoted parameter expansion pattern: remove quote
6167 * unless inside inner quotes or we have a literal
6170 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6171 EXP_QPAT && *p != '\\')
6176 TRACE(("argstr: evalvar('%s')\n", p));
6177 p = evalvar(p, flags | inquotes, var_str_list);
6178 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6181 expbackq(argbackq->n, flags | inquotes);
6182 argbackq = argbackq->next;
6184 #if ENABLE_SH_MATH_SUPPORT
6187 expari(flags | inquotes);
6196 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6197 char *pattern, int quotes, int zero)
6206 const char *s = loc2;
6213 match = pmatch(pattern, s);
6218 if (quotes && (unsigned char)*loc == CTLESC)
6227 scanright(char *startp, char *rmesc, char *rmescend,
6228 char *pattern, int quotes, int match_at_start)
6230 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6231 int try2optimize = match_at_start;
6237 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6238 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6239 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6241 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6242 * and on each iteration they go back two/one char until they reach the beginning.
6243 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6245 /* TODO: document in what other circumstances we are called. */
6247 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6250 const char *s = loc2;
6251 if (match_at_start) {
6255 match = pmatch(pattern, s);
6256 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6260 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6262 /* Maybe we can optimize this:
6263 * if pattern ends with unescaped *, we can avoid checking
6264 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6265 * it wont match truncated "raw_value_of_" strings too.
6267 unsigned plen = strlen(pattern);
6268 /* Does it end with "*"? */
6269 if (plen != 0 && pattern[--plen] == '*') {
6270 /* "xxxx*" is not escaped */
6271 /* "xxx\*" is escaped */
6272 /* "xx\\*" is not escaped */
6273 /* "x\\\*" is escaped */
6275 while (plen != 0 && pattern[--plen] == '\\')
6278 break; /* ends with unescaped "*" */
6286 esc = esclen(startp, loc);
6297 static void varunset(const char *, const char *, const char *, int) NORETURN;
6299 varunset(const char *end, const char *var, const char *umsg, int varflags)
6305 msg = "parameter not set";
6307 if ((unsigned char)*end == CTLENDVAR) {
6308 if (varflags & VSNUL)
6314 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6318 subevalvar(char *p, char *varname, int strloc, int subtype,
6319 int startloc, int varflags, int flag, struct strlist *var_str_list)
6321 struct nodelist *saveargbackq = argbackq;
6322 int quotes = flag & QUOTES_ESC;
6325 char *rmesc, *rmescend;
6327 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6328 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6329 int saveherefd = herefd;
6330 int amount, resetloc;
6331 IF_ASH_BASH_COMPAT(int workloc;)
6333 char *(*scan)(char*, char*, char*, char*, int, int);
6335 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6336 // p, varname, strloc, subtype, startloc, varflags, quotes);
6339 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6340 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6342 STPUTC('\0', expdest);
6343 herefd = saveherefd;
6344 argbackq = saveargbackq;
6345 startp = (char *)stackblock() + startloc;
6349 setvar0(varname, startp);
6350 amount = startp - expdest;
6351 STADJUST(amount, expdest);
6355 varunset(p, varname, startp, varflags);
6358 #if ENABLE_ASH_BASH_COMPAT
6360 //TODO: support more general format ${v:EXPR:EXPR},
6361 // where EXPR follows $(()) rules
6362 loc = str = stackblock() + strloc;
6363 /* Read POS in ${var:POS:LEN} */
6364 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6365 len = str - startp - 1;
6367 /* *loc != '\0', guaranteed by parser */
6371 /* Adjust the length by the number of escapes */
6372 for (ptr = startp; ptr < (str - 1); ptr++) {
6373 if ((unsigned char)*ptr == CTLESC) {
6381 if (*loc++ == ':') {
6385 /* Skip POS in ${var:POS:LEN} */
6387 while (*loc && *loc != ':') {
6389 * bash complains on: var=qwe; echo ${var:1a:123}
6391 ash_msg_and_raise_error(msg_illnum, str);
6395 if (*loc++ == ':') {
6400 /* ${VAR:$((-n)):l} starts n chars from the end */
6401 pos = orig_len + pos;
6403 if ((unsigned)pos >= orig_len) {
6404 /* apart from obvious ${VAR:999999:l},
6405 * covers ${VAR:$((-9999999)):l} - result is ""
6411 if (len > (orig_len - pos))
6412 len = orig_len - pos;
6414 for (str = startp; pos; str++, pos--) {
6415 if (quotes && (unsigned char)*str == CTLESC)
6418 for (loc = startp; len; len--) {
6419 if (quotes && (unsigned char)*str == CTLESC)
6424 amount = loc - expdest;
6425 STADJUST(amount, expdest);
6430 resetloc = expdest - (char *)stackblock();
6432 /* We'll comeback here if we grow the stack while handling
6433 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6434 * stack will need rebasing, and we'll need to remove our work
6437 IF_ASH_BASH_COMPAT(restart:)
6439 amount = expdest - ((char *)stackblock() + resetloc);
6440 STADJUST(-amount, expdest);
6441 startp = (char *)stackblock() + startloc;
6444 rmescend = (char *)stackblock() + strloc;
6446 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6447 if (rmesc != startp) {
6449 startp = (char *)stackblock() + startloc;
6453 str = (char *)stackblock() + strloc;
6455 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6456 * The result is a_\_z_c (not a\_\_z_c)!
6458 * The search pattern and replace string treat backslashes differently!
6459 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6460 * and string. It's only used on the first call.
6462 preglob(str, IF_ASH_BASH_COMPAT(
6463 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6464 RMESCAPE_SLASH :) 0);
6466 #if ENABLE_ASH_BASH_COMPAT
6467 workloc = expdest - (char *)stackblock();
6468 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6472 repl = strchr(str, CTLESC);
6478 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6480 /* If there's no pattern to match, return the expansion unmolested */
6489 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6490 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6492 /* No match, advance */
6493 char *restart_detect = stackblock();
6495 STPUTC(*idx, expdest);
6496 if (quotes && (unsigned char)*idx == CTLESC) {
6499 STPUTC(*idx, expdest);
6501 if (stackblock() != restart_detect)
6506 /* continue; - prone to quadratic behavior, smarter code: */
6509 if (str[0] == '*') {
6510 /* Pattern is "*foo". If "*foo" does not match "long_string",
6511 * it would never match "ong_string" etc, no point in trying.
6518 if (subtype == VSREPLACEALL) {
6520 if (quotes && (unsigned char)*idx == CTLESC)
6529 //bb_error_msg("repl:'%s'", repl);
6530 for (loc = (char*)repl; *loc; loc++) {
6531 char *restart_detect = stackblock();
6532 if (quotes && *loc == '\\') {
6533 STPUTC(CTLESC, expdest);
6536 STPUTC(*loc, expdest);
6537 if (stackblock() != restart_detect)
6542 if (subtype == VSREPLACE) {
6543 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6545 char *restart_detect = stackblock();
6546 STPUTC(*idx, expdest);
6547 if (stackblock() != restart_detect)
6556 /* We've put the replaced text into a buffer at workloc, now
6557 * move it to the right place and adjust the stack.
6559 STPUTC('\0', expdest);
6560 startp = (char *)stackblock() + startloc;
6561 memmove(startp, (char *)stackblock() + workloc, len + 1);
6562 //bb_error_msg("startp:'%s'", startp);
6563 amount = expdest - (startp + len);
6564 STADJUST(-amount, expdest);
6567 #endif /* ENABLE_ASH_BASH_COMPAT */
6569 subtype -= VSTRIMRIGHT;
6571 if (subtype < 0 || subtype > 7)
6574 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6575 zero = subtype >> 1;
6576 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6577 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6579 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6582 memmove(startp, loc, str - loc);
6583 loc = startp + (str - loc) - 1;
6586 amount = loc - expdest;
6587 STADJUST(amount, expdest);
6593 * Add the value of a specialized variable to the stack string.
6594 * name parameter (examples):
6595 * ash -c 'echo $1' name:'1='
6596 * ash -c 'echo $qwe' name:'qwe='
6597 * ash -c 'echo $$' name:'$='
6598 * ash -c 'echo ${$}' name:'$='
6599 * ash -c 'echo ${$##q}' name:'$=q'
6600 * ash -c 'echo ${#$}' name:'$='
6601 * note: examples with bad shell syntax:
6602 * ash -c 'echo ${#$1}' name:'$=1'
6603 * ash -c 'echo ${#1#}' name:'1=#'
6605 static NOINLINE ssize_t
6606 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6613 int quoted = flags & EXP_QUOTED;
6614 int subtype = varflags & VSTYPE;
6615 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6616 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6617 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6619 sep = quoted ? ((flags & EXP_FULL) << CHAR_BIT) : 0;
6629 num = shellparam.nparam;
6637 goto check_1char_name;
6639 expdest = makestrspace(NOPTS, expdest);
6640 for (i = NOPTS - 1; i >= 0; i--) {
6642 USTPUTC(optletters(i), expdest);
6648 /* handles cases similar to ${#$1} */
6649 if (name[2] != '\0')
6650 raise_error_syntax("bad substitution");
6657 if (quoted && (flags & EXP_FULL)) {
6658 /* note: this is not meant as PEOF value */
6659 sep = 1 << CHAR_BIT;
6664 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6670 while ((p = *ap++) != NULL) {
6671 len += strtodest(p, syntax, quotes);
6675 memtodest(&sepc, 1, syntax, quotes);
6679 } /* case '@' and '*' */
6690 num = atoi(name); /* number(name) fails on ${N#str} etc */
6691 if (num < 0 || num > shellparam.nparam)
6693 p = num ? shellparam.p[num - 1] : arg0;
6696 /* NB: name has form "VAR=..." */
6698 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6699 * which should be considered before we check variables. */
6701 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6705 str = var_str_list->text;
6706 eq = strchr(str, '=');
6707 if (!eq) /* stop at first non-assignment */
6710 if (name_len == (unsigned)(eq - str)
6711 && strncmp(str, name, name_len) == 0
6714 /* goto value; - WRONG! */
6715 /* think "A=1 A=2 B=$A" */
6717 var_str_list = var_str_list->next;
6718 } while (var_str_list);
6722 p = lookupvar(name);
6727 len = strtodest(p, syntax, quotes);
6728 #if ENABLE_UNICODE_SUPPORT
6729 if (subtype == VSLENGTH && len > 0) {
6730 reinit_unicode_for_ash();
6731 if (unicode_status == UNICODE_ON) {
6732 STADJUST(-len, expdest);
6734 len = unicode_strlen(p);
6742 STADJUST(-len, expdest);
6747 * Expand a variable, and return a pointer to the next character in the
6751 evalvar(char *p, int flags, struct strlist *var_str_list)
6762 varflags = (unsigned char) *p++;
6763 subtype = varflags & VSTYPE;
6764 quoted = flags & EXP_QUOTED;
6766 easy = (!quoted || (*var == '@' && shellparam.nparam));
6767 startloc = expdest - (char *)stackblock();
6768 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6771 varlen = varvalue(var, varflags, flags, var_str_list);
6772 if (varflags & VSNUL)
6775 if (subtype == VSPLUS) {
6776 varlen = -1 - varlen;
6780 if (subtype == VSMINUS) {
6785 flags | EXP_TILDE | EXP_WORD,
6795 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6797 if (subevalvar(p, var, /* strloc: */ 0,
6798 subtype, startloc, varflags,
6799 /* quotes: */ flags & ~QUOTES_ESC,
6804 * Remove any recorded regions beyond
6807 removerecordregions(startloc);
6817 if (varlen < 0 && uflag)
6818 varunset(p, var, 0, 0);
6820 if (subtype == VSLENGTH) {
6821 cvtnum(varlen > 0 ? varlen : 0);
6825 if (subtype == VSNORMAL) {
6836 case VSTRIMRIGHTMAX:
6837 #if ENABLE_ASH_BASH_COMPAT
6850 * Terminate the string and start recording the pattern
6853 STPUTC('\0', expdest);
6854 patloc = expdest - (char *)stackblock();
6855 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6856 startloc, varflags, flags, var_str_list)) {
6857 int amount = expdest - (
6858 (char *)stackblock() + patloc - 1
6860 STADJUST(-amount, expdest);
6862 /* Remove any recorded regions beyond start of variable */
6863 removerecordregions(startloc);
6865 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6869 if (subtype != VSNORMAL) { /* skip to end of alternative */
6872 unsigned char c = *p++;
6875 else if (c == CTLBACKQ) {
6877 argbackq = argbackq->next;
6878 } else if (c == CTLVAR) {
6879 if ((*p++ & VSTYPE) != VSNORMAL)
6881 } else if (c == CTLENDVAR) {
6891 * Break the argument string into pieces based upon IFS and add the
6892 * strings to the argument list. The regions of the string to be
6893 * searched for IFS characters have been stored by recordregion.
6896 ifsbreakup(char *string, struct arglist *arglist)
6898 struct ifsregion *ifsp;
6903 const char *ifs, *realifs;
6908 if (ifslastp != NULL) {
6911 realifs = ifsset() ? ifsval() : defifs;
6914 p = string + ifsp->begoff;
6915 nulonly = ifsp->nulonly;
6916 ifs = nulonly ? nullstr : realifs;
6918 while (p < string + ifsp->endoff) {
6920 if ((unsigned char)*p == CTLESC)
6922 if (!strchr(ifs, *p)) {
6927 ifsspc = (strchr(defifs, *p) != NULL);
6928 /* Ignore IFS whitespace at start */
6929 if (q == start && ifsspc) {
6935 sp = stzalloc(sizeof(*sp));
6937 *arglist->lastp = sp;
6938 arglist->lastp = &sp->next;
6942 if (p >= string + ifsp->endoff) {
6946 if ((unsigned char)*p == CTLESC)
6948 if (strchr(ifs, *p) == NULL) {
6952 if (strchr(defifs, *p) == NULL) {
6967 } while (ifsp != NULL);
6976 sp = stzalloc(sizeof(*sp));
6978 *arglist->lastp = sp;
6979 arglist->lastp = &sp->next;
6985 struct ifsregion *p;
6990 struct ifsregion *ifsp;
6996 ifsfirst.next = NULL;
7001 * Add a file name to the list.
7004 addfname(const char *name)
7008 sp = stzalloc(sizeof(*sp));
7009 sp->text = sstrdup(name);
7011 exparg.lastp = &sp->next;
7014 /* If we want to use glob() from libc... */
7015 #if !ENABLE_ASH_INTERNAL_GLOB
7017 /* Add the result of glob() to the list */
7019 addglob(const glob_t *pglob)
7021 char **p = pglob->gl_pathv;
7028 expandmeta(struct strlist *str /*, int flag*/)
7030 /* TODO - EXP_REDIR */
7040 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7042 * GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7043 * TODO?: GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7045 i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7050 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7051 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7062 *exparg.lastp = str;
7063 rmescapes(str->text, 0);
7064 exparg.lastp = &str->next;
7066 default: /* GLOB_NOSPACE */
7069 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7076 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7079 * Do metacharacter (i.e. *, ?, [...]) expansion.
7082 expmeta(char *expdir, char *enddir, char *name)
7098 for (p = name; esc = 0, *p; p += esc + 1) {
7099 if (*p == '*' || *p == '?')
7101 else if (*p == '[') {
7108 if (*q == '/' || *q == '\0')
7118 if (p[esc] == '/') {
7121 start = p + esc + 1;
7125 if (metaflag == 0) { /* we've reached the end of the file name */
7126 if (enddir != expdir)
7134 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7145 } while (p < start);
7147 if (enddir == expdir) {
7149 } else if (enddir == expdir + 1 && *expdir == '/') {
7158 if (enddir != expdir)
7160 if (*endname == 0) {
7173 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7174 if (dp->d_name[0] == '.' && !matchdot)
7176 if (pmatch(start, dp->d_name)) {
7178 strcpy(enddir, dp->d_name);
7181 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7184 expmeta(expdir, p, endname);
7190 endname[-esc - 1] = esc ? '\\' : '/';
7193 static struct strlist *
7194 msort(struct strlist *list, int len)
7196 struct strlist *p, *q = NULL;
7197 struct strlist **lpp;
7205 for (n = half; --n >= 0;) {
7209 q->next = NULL; /* terminate first half of list */
7210 q = msort(list, half); /* sort first half of list */
7211 p = msort(p, len - half); /* sort second half */
7214 #if ENABLE_LOCALE_SUPPORT
7215 if (strcoll(p->text, q->text) < 0)
7217 if (strcmp(p->text, q->text) < 0)
7241 * Sort the results of file name expansion. It calculates the number of
7242 * strings to sort and then calls msort (short for merge sort) to do the
7245 static struct strlist *
7246 expsort(struct strlist *str)
7252 for (sp = str; sp; sp = sp->next)
7254 return msort(str, len);
7258 expandmeta(struct strlist *str /*, int flag*/)
7260 static const char metachars[] ALIGN1 = {
7263 /* TODO - EXP_REDIR */
7267 struct strlist **savelastp;
7273 if (!strpbrk(str->text, metachars))
7275 savelastp = exparg.lastp;
7278 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7280 int i = strlen(str->text);
7281 //BUGGY estimation of how long expanded name can be
7282 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7284 expmeta(expdir, expdir, p);
7289 if (exparg.lastp == savelastp) {
7294 *exparg.lastp = str;
7295 rmescapes(str->text, 0);
7296 exparg.lastp = &str->next;
7298 *exparg.lastp = NULL;
7299 *savelastp = sp = expsort(*savelastp);
7300 while (sp->next != NULL)
7302 exparg.lastp = &sp->next;
7307 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7310 * Perform variable substitution and command substitution on an argument,
7311 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7312 * perform splitting and file name expansion. When arglist is NULL, perform
7313 * here document expansion.
7316 expandarg(union node *arg, struct arglist *arglist, int flag)
7321 argbackq = arg->narg.backquote;
7322 STARTSTACKSTR(expdest);
7323 ifsfirst.next = NULL;
7325 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7326 argstr(arg->narg.text, flag,
7327 /* var_str_list: */ arglist ? arglist->list : NULL);
7328 p = _STPUTC('\0', expdest);
7330 if (arglist == NULL) {
7331 return; /* here document expanded */
7333 p = grabstackstr(p);
7334 TRACE(("expandarg: p:'%s'\n", p));
7335 exparg.lastp = &exparg.list;
7339 if (flag & EXP_FULL) {
7340 ifsbreakup(p, &exparg);
7341 *exparg.lastp = NULL;
7342 exparg.lastp = &exparg.list;
7343 expandmeta(exparg.list /*, flag*/);
7345 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7347 TRACE(("expandarg: rmescapes:'%s'\n", p));
7349 sp = stzalloc(sizeof(*sp));
7352 exparg.lastp = &sp->next;
7356 *exparg.lastp = NULL;
7358 *arglist->lastp = exparg.list;
7359 arglist->lastp = exparg.lastp;
7364 * Expand shell variables and backquotes inside a here document.
7367 expandhere(union node *arg, int fd)
7370 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7371 full_write(fd, stackblock(), expdest - (char *)stackblock());
7375 * Returns true if the pattern matches the string.
7378 patmatch(char *pattern, const char *string)
7380 return pmatch(preglob(pattern, 0), string);
7384 * See if a pattern matches in a case statement.
7387 casematch(union node *pattern, char *val)
7389 struct stackmark smark;
7392 setstackmark(&smark);
7393 argbackq = pattern->narg.backquote;
7394 STARTSTACKSTR(expdest);
7396 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7397 /* var_str_list: */ NULL);
7398 STACKSTRNUL(expdest);
7399 result = patmatch(stackblock(), val);
7400 popstackmark(&smark);
7405 /* ============ find_command */
7409 int (*builtin)(int, char **) FAST_FUNC;
7410 /* unsigned flags; */
7412 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7413 /* "regular" builtins always take precedence over commands,
7414 * regardless of PATH=....%builtin... position */
7415 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7416 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7419 smallint cmdtype; /* CMDxxx */
7422 /* index >= 0 for commands without path (slashes) */
7423 /* (TODO: what exactly does the value mean? PATH position?) */
7424 /* index == -1 for commands with slashes */
7425 /* index == (-2 - applet_no) for NOFORK applets */
7426 const struct builtincmd *cmd;
7427 struct funcnode *func;
7430 /* values of cmdtype */
7431 #define CMDUNKNOWN -1 /* no entry in table for command */
7432 #define CMDNORMAL 0 /* command is an executable program */
7433 #define CMDFUNCTION 1 /* command is a shell function */
7434 #define CMDBUILTIN 2 /* command is a shell builtin */
7436 /* action to find_command() */
7437 #define DO_ERR 0x01 /* prints errors */
7438 #define DO_ABS 0x02 /* checks absolute paths */
7439 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7440 #define DO_ALTPATH 0x08 /* using alternate path */
7441 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7443 static void find_command(char *, struct cmdentry *, int, const char *);
7446 /* ============ Hashing commands */
7449 * When commands are first encountered, they are entered in a hash table.
7450 * This ensures that a full path search will not have to be done for them
7451 * on each invocation.
7453 * We should investigate converting to a linear search, even though that
7454 * would make the command name "hash" a misnomer.
7458 struct tblentry *next; /* next entry in hash chain */
7459 union param param; /* definition of builtin function */
7460 smallint cmdtype; /* CMDxxx */
7461 char rehash; /* if set, cd done since entry created */
7462 char cmdname[1]; /* name of command */
7465 static struct tblentry **cmdtable;
7466 #define INIT_G_cmdtable() do { \
7467 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7470 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7474 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7476 #if ENABLE_FEATURE_SH_STANDALONE
7477 if (applet_no >= 0) {
7478 if (APPLET_IS_NOEXEC(applet_no)) {
7482 run_applet_no_and_exit(applet_no, argv);
7484 /* re-exec ourselves with the new arguments */
7485 execve(bb_busybox_exec_path, argv, envp);
7486 /* If they called chroot or otherwise made the binary no longer
7487 * executable, fall through */
7494 execve(cmd, argv, envp);
7495 } while (errno == EINTR);
7497 execve(cmd, argv, envp);
7499 if (cmd == (char*) bb_busybox_exec_path) {
7500 /* We already visited ENOEXEC branch below, don't do it again */
7501 //TODO: try execve(initial_argv0_of_shell, argv, envp) before giving up?
7505 if (errno == ENOEXEC) {
7506 /* Run "cmd" as a shell script:
7507 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7508 * "If the execve() function fails with ENOEXEC, the shell
7509 * shall execute a command equivalent to having a shell invoked
7510 * with the command name as its first operand,
7511 * with any remaining arguments passed to the new shell"
7513 * That is, do not use $SHELL, user's shell, or /bin/sh;
7514 * just call ourselves.
7516 * Note that bash reads ~80 chars of the file, and if it sees
7517 * a zero byte before it sees newline, it doesn't try to
7518 * interpret it, but fails with "cannot execute binary file"
7519 * message and exit code 126. For one, this prevents attempts
7520 * to interpret foreign ELF binaries as shell scripts.
7525 for (ap = argv; *ap; ap++)
7527 new = ckmalloc((ap - argv + 2) * sizeof(new[0]));
7528 new[0] = (char*) "ash";
7531 while ((*ap++ = *++argv) != NULL)
7533 cmd = (char*) bb_busybox_exec_path;
7540 * Exec a program. Never returns. If you change this routine, you may
7541 * have to change the find_command routine as well.
7543 static void shellexec(char **, const char *, int) NORETURN;
7545 shellexec(char **argv, const char *path, int idx)
7551 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7553 clearredir(/*drop:*/ 1);
7554 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7555 if (strchr(argv[0], '/') != NULL
7556 #if ENABLE_FEATURE_SH_STANDALONE
7557 || (applet_no = find_applet_by_name(argv[0])) >= 0
7560 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7561 if (applet_no >= 0) {
7562 /* We tried execing ourself, but it didn't work.
7563 * Maybe /proc/self/exe doesn't exist?
7572 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7573 if (--idx < 0 && pathopt == NULL) {
7574 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7575 if (errno != ENOENT && errno != ENOTDIR)
7582 /* Map to POSIX errors */
7594 exitstatus = exerrno;
7595 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7596 argv[0], e, suppress_int));
7597 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7602 printentry(struct tblentry *cmdp)
7608 idx = cmdp->param.index;
7611 name = path_advance(&path, cmdp->cmdname);
7613 } while (--idx >= 0);
7614 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7618 * Clear out command entries. The argument specifies the first entry in
7619 * PATH which has changed.
7622 clearcmdentry(int firstchange)
7624 struct tblentry **tblp;
7625 struct tblentry **pp;
7626 struct tblentry *cmdp;
7629 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7631 while ((cmdp = *pp) != NULL) {
7632 if ((cmdp->cmdtype == CMDNORMAL &&
7633 cmdp->param.index >= firstchange)
7634 || (cmdp->cmdtype == CMDBUILTIN &&
7635 builtinloc >= firstchange)
7648 * Locate a command in the command hash table. If "add" is nonzero,
7649 * add the command to the table if it is not already present. The
7650 * variable "lastcmdentry" is set to point to the address of the link
7651 * pointing to the entry, so that delete_cmd_entry can delete the
7654 * Interrupts must be off if called with add != 0.
7656 static struct tblentry **lastcmdentry;
7658 static struct tblentry *
7659 cmdlookup(const char *name, int add)
7661 unsigned int hashval;
7663 struct tblentry *cmdp;
7664 struct tblentry **pp;
7667 hashval = (unsigned char)*p << 4;
7669 hashval += (unsigned char)*p++;
7671 pp = &cmdtable[hashval % CMDTABLESIZE];
7672 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7673 if (strcmp(cmdp->cmdname, name) == 0)
7677 if (add && cmdp == NULL) {
7678 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7680 /* + 1 - already done because
7681 * tblentry::cmdname is char[1] */);
7682 /*cmdp->next = NULL; - ckzalloc did it */
7683 cmdp->cmdtype = CMDUNKNOWN;
7684 strcpy(cmdp->cmdname, name);
7691 * Delete the command entry returned on the last lookup.
7694 delete_cmd_entry(void)
7696 struct tblentry *cmdp;
7699 cmdp = *lastcmdentry;
7700 *lastcmdentry = cmdp->next;
7701 if (cmdp->cmdtype == CMDFUNCTION)
7702 freefunc(cmdp->param.func);
7708 * Add a new command entry, replacing any existing command entry for
7709 * the same name - except special builtins.
7712 addcmdentry(char *name, struct cmdentry *entry)
7714 struct tblentry *cmdp;
7716 cmdp = cmdlookup(name, 1);
7717 if (cmdp->cmdtype == CMDFUNCTION) {
7718 freefunc(cmdp->param.func);
7720 cmdp->cmdtype = entry->cmdtype;
7721 cmdp->param = entry->u;
7725 static int FAST_FUNC
7726 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7728 struct tblentry **pp;
7729 struct tblentry *cmdp;
7731 struct cmdentry entry;
7734 if (nextopt("r") != '\0') {
7739 if (*argptr == NULL) {
7740 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7741 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7742 if (cmdp->cmdtype == CMDNORMAL)
7750 while ((name = *argptr) != NULL) {
7751 cmdp = cmdlookup(name, 0);
7753 && (cmdp->cmdtype == CMDNORMAL
7754 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7758 find_command(name, &entry, DO_ERR, pathval());
7759 if (entry.cmdtype == CMDUNKNOWN)
7767 * Called when a cd is done. Marks all commands so the next time they
7768 * are executed they will be rehashed.
7773 struct tblentry **pp;
7774 struct tblentry *cmdp;
7776 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7777 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7778 if (cmdp->cmdtype == CMDNORMAL
7779 || (cmdp->cmdtype == CMDBUILTIN
7780 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7790 * Fix command hash table when PATH changed.
7791 * Called before PATH is changed. The argument is the new value of PATH;
7792 * pathval() still returns the old value at this point.
7793 * Called with interrupts off.
7795 static void FAST_FUNC
7796 changepath(const char *new)
7804 firstchange = 9999; /* assume no change */
7810 if ((*old == '\0' && *new == ':')
7811 || (*old == ':' && *new == '\0')
7815 old = new; /* ignore subsequent differences */
7819 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7826 if (builtinloc < 0 && idx_bltin >= 0)
7827 builtinloc = idx_bltin; /* zap builtins */
7828 if (builtinloc >= 0 && idx_bltin < 0)
7830 clearcmdentry(firstchange);
7831 builtinloc = idx_bltin;
7856 #if ENABLE_ASH_BASH_COMPAT
7867 typedef smallint token_id_t;
7869 /* first char is indicating which tokens mark the end of a list */
7870 static const char *const tokname_array[] = {
7884 #define KWDOFFSET 13
7885 /* the following are keywords */
7895 #if ENABLE_ASH_BASH_COMPAT
7907 /* Wrapper around strcmp for qsort/bsearch/... */
7909 pstrcmp(const void *a, const void *b)
7911 return strcmp((char*) a, (*(char**) b) + 1);
7914 static const char *const *
7915 findkwd(const char *s)
7917 return bsearch(s, tokname_array + KWDOFFSET,
7918 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7919 sizeof(tokname_array[0]), pstrcmp);
7923 * Locate and print what a word is...
7926 describe_command(char *command, const char *path, int describe_command_verbose)
7928 struct cmdentry entry;
7929 struct tblentry *cmdp;
7930 #if ENABLE_ASH_ALIAS
7931 const struct alias *ap;
7934 path = path ? path : pathval();
7936 if (describe_command_verbose) {
7940 /* First look at the keywords */
7941 if (findkwd(command)) {
7942 out1str(describe_command_verbose ? " is a shell keyword" : command);
7946 #if ENABLE_ASH_ALIAS
7947 /* Then look at the aliases */
7948 ap = lookupalias(command, 0);
7950 if (!describe_command_verbose) {
7955 out1fmt(" is an alias for %s", ap->val);
7959 /* Then check if it is a tracked alias */
7960 cmdp = cmdlookup(command, 0);
7962 entry.cmdtype = cmdp->cmdtype;
7963 entry.u = cmdp->param;
7965 /* Finally use brute force */
7966 find_command(command, &entry, DO_ABS, path);
7969 switch (entry.cmdtype) {
7971 int j = entry.u.index;
7977 p = path_advance(&path, command);
7981 if (describe_command_verbose) {
7983 (cmdp ? " a tracked alias for" : nullstr), p
7992 if (describe_command_verbose) {
7993 out1str(" is a shell function");
8000 if (describe_command_verbose) {
8001 out1fmt(" is a %sshell builtin",
8002 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8003 "special " : nullstr
8011 if (describe_command_verbose) {
8012 out1str(": not found\n");
8021 static int FAST_FUNC
8022 typecmd(int argc UNUSED_PARAM, char **argv)
8028 /* type -p ... ? (we don't bother checking for 'p') */
8029 if (argv[1] && argv[1][0] == '-') {
8034 err |= describe_command(argv[i++], NULL, verbose);
8039 #if ENABLE_ASH_CMDCMD
8040 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8042 parse_command_args(char **argv, const char **path)
8055 if (c == '-' && !*cp) {
8063 *path = bb_default_path;
8066 /* run 'typecmd' for other options */
8075 static int FAST_FUNC
8076 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8084 const char *path = NULL;
8086 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8087 * never reaches this function.
8090 while ((c = nextopt("pvV")) != '\0')
8092 verify |= VERIFY_VERBOSE;
8094 /*verify |= VERIFY_BRIEF*/;
8100 path = bb_default_path;
8102 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8104 if (/*verify && */ cmd)
8105 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8112 /* ============ eval.c */
8114 static int funcblocksize; /* size of structures in function */
8115 static int funcstringsize; /* size of strings in node */
8116 static void *funcblock; /* block to allocate function from */
8117 static char *funcstring; /* block to allocate strings from */
8119 /* flags in argument to evaltree */
8120 #define EV_EXIT 01 /* exit after evaluating tree */
8121 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8123 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8124 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8125 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8126 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8127 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8128 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8129 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8130 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8131 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8132 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8133 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8134 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8135 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8136 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8137 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8138 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8139 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8140 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8141 #if ENABLE_ASH_BASH_COMPAT
8142 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8144 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8145 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8146 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8147 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8148 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8149 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8150 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8151 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8152 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8155 static void calcsize(union node *n);
8158 sizenodelist(struct nodelist *lp)
8161 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8168 calcsize(union node *n)
8172 funcblocksize += nodesize[n->type];
8175 calcsize(n->ncmd.redirect);
8176 calcsize(n->ncmd.args);
8177 calcsize(n->ncmd.assign);
8180 sizenodelist(n->npipe.cmdlist);
8185 calcsize(n->nredir.redirect);
8186 calcsize(n->nredir.n);
8193 calcsize(n->nbinary.ch2);
8194 calcsize(n->nbinary.ch1);
8197 calcsize(n->nif.elsepart);
8198 calcsize(n->nif.ifpart);
8199 calcsize(n->nif.test);
8202 funcstringsize += strlen(n->nfor.var) + 1;
8203 calcsize(n->nfor.body);
8204 calcsize(n->nfor.args);
8207 calcsize(n->ncase.cases);
8208 calcsize(n->ncase.expr);
8211 calcsize(n->nclist.body);
8212 calcsize(n->nclist.pattern);
8213 calcsize(n->nclist.next);
8217 sizenodelist(n->narg.backquote);
8218 funcstringsize += strlen(n->narg.text) + 1;
8219 calcsize(n->narg.next);
8222 #if ENABLE_ASH_BASH_COMPAT
8229 calcsize(n->nfile.fname);
8230 calcsize(n->nfile.next);
8234 calcsize(n->ndup.vname);
8235 calcsize(n->ndup.next);
8239 calcsize(n->nhere.doc);
8240 calcsize(n->nhere.next);
8243 calcsize(n->nnot.com);
8249 nodeckstrdup(char *s)
8251 char *rtn = funcstring;
8253 strcpy(funcstring, s);
8254 funcstring += strlen(s) + 1;
8258 static union node *copynode(union node *);
8260 static struct nodelist *
8261 copynodelist(struct nodelist *lp)
8263 struct nodelist *start;
8264 struct nodelist **lpp;
8269 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8270 (*lpp)->n = copynode(lp->n);
8272 lpp = &(*lpp)->next;
8279 copynode(union node *n)
8286 funcblock = (char *) funcblock + nodesize[n->type];
8290 new->ncmd.redirect = copynode(n->ncmd.redirect);
8291 new->ncmd.args = copynode(n->ncmd.args);
8292 new->ncmd.assign = copynode(n->ncmd.assign);
8295 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8296 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8301 new->nredir.redirect = copynode(n->nredir.redirect);
8302 new->nredir.n = copynode(n->nredir.n);
8309 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8310 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8313 new->nif.elsepart = copynode(n->nif.elsepart);
8314 new->nif.ifpart = copynode(n->nif.ifpart);
8315 new->nif.test = copynode(n->nif.test);
8318 new->nfor.var = nodeckstrdup(n->nfor.var);
8319 new->nfor.body = copynode(n->nfor.body);
8320 new->nfor.args = copynode(n->nfor.args);
8323 new->ncase.cases = copynode(n->ncase.cases);
8324 new->ncase.expr = copynode(n->ncase.expr);
8327 new->nclist.body = copynode(n->nclist.body);
8328 new->nclist.pattern = copynode(n->nclist.pattern);
8329 new->nclist.next = copynode(n->nclist.next);
8333 new->narg.backquote = copynodelist(n->narg.backquote);
8334 new->narg.text = nodeckstrdup(n->narg.text);
8335 new->narg.next = copynode(n->narg.next);
8338 #if ENABLE_ASH_BASH_COMPAT
8345 new->nfile.fname = copynode(n->nfile.fname);
8346 new->nfile.fd = n->nfile.fd;
8347 new->nfile.next = copynode(n->nfile.next);
8351 new->ndup.vname = copynode(n->ndup.vname);
8352 new->ndup.dupfd = n->ndup.dupfd;
8353 new->ndup.fd = n->ndup.fd;
8354 new->ndup.next = copynode(n->ndup.next);
8358 new->nhere.doc = copynode(n->nhere.doc);
8359 new->nhere.fd = n->nhere.fd;
8360 new->nhere.next = copynode(n->nhere.next);
8363 new->nnot.com = copynode(n->nnot.com);
8366 new->type = n->type;
8371 * Make a copy of a parse tree.
8373 static struct funcnode *
8374 copyfunc(union node *n)
8379 funcblocksize = offsetof(struct funcnode, n);
8382 blocksize = funcblocksize;
8383 f = ckmalloc(blocksize + funcstringsize);
8384 funcblock = (char *) f + offsetof(struct funcnode, n);
8385 funcstring = (char *) f + blocksize;
8392 * Define a shell function.
8395 defun(char *name, union node *func)
8397 struct cmdentry entry;
8400 entry.cmdtype = CMDFUNCTION;
8401 entry.u.func = copyfunc(func);
8402 addcmdentry(name, &entry);
8406 /* Reasons for skipping commands (see comment on breakcmd routine) */
8407 #define SKIPBREAK (1 << 0)
8408 #define SKIPCONT (1 << 1)
8409 #define SKIPFUNC (1 << 2)
8410 #define SKIPEVAL (1 << 4)
8411 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8412 static int skipcount; /* number of levels to skip */
8413 static int funcnest; /* depth of function calls */
8414 static int loopnest; /* current loop nesting level */
8416 /* Forward decl way out to parsing code - dotrap needs it */
8417 static int evalstring(char *s, int mask);
8419 /* Called to execute a trap.
8420 * Single callsite - at the end of evaltree().
8421 * If we return non-zero, evaltree raises EXEXIT exception.
8423 * Perhaps we should avoid entering new trap handlers
8424 * while we are executing a trap handler. [is it a TODO?]
8433 savestatus = exitstatus;
8437 TRACE(("dotrap entered\n"));
8438 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8444 /* non-trapped SIGINT is handled separately by raise_interrupt,
8445 * don't upset it by resetting gotsig[SIGINT-1] */
8446 if (sig == SIGINT && !t)
8449 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8453 evalstring(t, SKIPEVAL);
8454 exitstatus = savestatus;
8456 TRACE(("dotrap returns %d\n", evalskip));
8461 TRACE(("dotrap returns 0\n"));
8465 /* forward declarations - evaluation is fairly recursive business... */
8466 static int evalloop(union node *, int);
8467 static int evalfor(union node *, int);
8468 static int evalcase(union node *, int);
8469 static int evalsubshell(union node *, int);
8470 static void expredir(union node *);
8471 static int evalpipe(union node *, int);
8472 static int evalcommand(union node *, int);
8473 static int evalbltin(const struct builtincmd *, int, char **);
8474 static void prehash(union node *);
8477 * Evaluate a parse tree. The value is left in the global variable
8481 evaltree(union node *n, int flags)
8483 struct jmploc *volatile savehandler = exception_handler;
8484 struct jmploc jmploc;
8486 int (*evalfn)(union node *, int);
8490 SAVE_INT(int_level);
8493 TRACE(("evaltree(NULL) called\n"));
8496 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8498 exception_handler = &jmploc;
8500 int err = setjmp(jmploc.loc);
8502 /* if it was a signal, check for trap handlers */
8503 if (exception_type == EXSIG) {
8504 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8505 exception_type, err));
8508 /* continue on the way out */
8509 TRACE(("exception %d in evaltree, propagating err=%d\n",
8510 exception_type, err));
8511 exception_handler = savehandler;
8512 longjmp(exception_handler->loc, err);
8519 out1fmt("Node type = %d\n", n->type);
8524 status = !evaltree(n->nnot.com, EV_TESTED);
8527 expredir(n->nredir.redirect);
8528 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8530 status = evaltree(n->nredir.n, flags & EV_TESTED);
8532 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8535 evalfn = evalcommand;
8537 if (eflag && !(flags & EV_TESTED))
8548 evalfn = evalsubshell;
8551 evalfn = evalsubshell;
8564 #error NAND + 1 != NOR
8566 #if NOR + 1 != NSEMI
8567 #error NOR + 1 != NSEMI
8569 unsigned is_or = n->type - NAND;
8572 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8574 if (!status == is_or || evalskip)
8580 status = evalfn(n, flags);
8584 status = evaltree(n->nif.test, EV_TESTED);
8591 if (n->nif.elsepart) {
8592 n = n->nif.elsepart;
8598 defun(n->narg.text, n->narg.next);
8599 /* Not necessary. To test it:
8600 * "false; f() { qwerty; }; echo $?" should print 0.
8604 exitstatus = status;
8609 exception_handler = savehandler;
8612 /* Order of checks below is important:
8613 * signal handlers trigger before exit caused by "set -e".
8615 if (pending_sig && dotrap())
8617 if (checkexit & status)
8618 evalskip |= SKIPEVAL;
8620 if (flags & EV_EXIT) {
8622 raise_exception(EXEXIT);
8625 RESTORE_INT(int_level);
8626 TRACE(("leaving evaltree (no interrupts)\n"));
8631 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8634 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8637 evalloop(union node *n, int flags)
8647 i = evaltree(n->nbinary.ch1, EV_TESTED);
8650 if (evalskip == SKIPCONT && --skipcount <= 0) {
8654 if (evalskip == SKIPBREAK && --skipcount <= 0)
8658 if (n->type != NWHILE)
8662 status = evaltree(n->nbinary.ch2, flags);
8666 exitstatus = status;
8673 evalfor(union node *n, int flags)
8675 struct arglist arglist;
8678 struct stackmark smark;
8681 setstackmark(&smark);
8682 arglist.list = NULL;
8683 arglist.lastp = &arglist.list;
8684 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8685 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8690 *arglist.lastp = NULL;
8694 for (sp = arglist.list; sp; sp = sp->next) {
8695 setvar0(n->nfor.var, sp->text);
8696 status = evaltree(n->nfor.body, flags);
8698 if (evalskip == SKIPCONT && --skipcount <= 0) {
8702 if (evalskip == SKIPBREAK && --skipcount <= 0)
8709 popstackmark(&smark);
8715 evalcase(union node *n, int flags)
8719 struct arglist arglist;
8720 struct stackmark smark;
8723 setstackmark(&smark);
8724 arglist.list = NULL;
8725 arglist.lastp = &arglist.list;
8726 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8727 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8728 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8729 if (casematch(patp, arglist.list->text)) {
8730 /* Ensure body is non-empty as otherwise
8731 * EV_EXIT may prevent us from setting the
8734 if (evalskip == 0 && cp->nclist.body) {
8735 status = evaltree(cp->nclist.body, flags);
8742 popstackmark(&smark);
8748 * Kick off a subshell to evaluate a tree.
8751 evalsubshell(union node *n, int flags)
8754 int backgnd = (n->type == NBACKGND);
8757 expredir(n->nredir.redirect);
8758 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8761 jp = makejob(/*n,*/ 1);
8762 if (forkshell(jp, n, backgnd) == 0) {
8767 flags &= ~EV_TESTED;
8769 redirect(n->nredir.redirect, 0);
8770 evaltreenr(n->nredir.n, flags);
8775 status = waitforjob(jp);
8781 * Compute the names of the files in a redirection list.
8783 static void fixredir(union node *, const char *, int);
8785 expredir(union node *n)
8789 for (redir = n; redir; redir = redir->nfile.next) {
8793 fn.lastp = &fn.list;
8794 switch (redir->type) {
8798 #if ENABLE_ASH_BASH_COMPAT
8803 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8804 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8805 #if ENABLE_ASH_BASH_COMPAT
8809 // By the design of stack allocator, the loop of this kind:
8810 // while true; do while true; do break; done </dev/null; done
8811 // will look like a memory leak: ash plans to free expfname's
8812 // of "/dev/null" as soon as it finishes running the loop
8813 // (in this case, never).
8814 // This "fix" is wrong:
8815 if (redir->nfile.expfname)
8816 stunalloc(redir->nfile.expfname);
8817 // It results in corrupted state of stacked allocations.
8819 redir->nfile.expfname = fn.list->text;
8822 case NTOFD: /* >& */
8823 if (redir->ndup.vname) {
8824 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8825 if (fn.list == NULL)
8826 ash_msg_and_raise_error("redir error");
8827 #if ENABLE_ASH_BASH_COMPAT
8828 //FIXME: we used expandarg with different args!
8829 if (!isdigit_str9(fn.list->text)) {
8830 /* >&file, not >&fd */
8831 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8832 ash_msg_and_raise_error("redir error");
8834 goto store_expfname;
8837 fixredir(redir, fn.list->text, 1);
8845 * Evaluate a pipeline. All the processes in the pipeline are children
8846 * of the process creating the pipeline. (This differs from some versions
8847 * of the shell, which make the last process in a pipeline the parent
8851 evalpipe(union node *n, int flags)
8854 struct nodelist *lp;
8860 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8862 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8866 jp = makejob(/*n,*/ pipelen);
8868 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8872 if (pipe(pip) < 0) {
8874 ash_msg_and_raise_error("pipe call failed");
8877 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8890 evaltreenr(lp->n, flags);
8896 /* Don't want to trigger debugging */
8900 if (n->npipe.pipe_backgnd == 0) {
8901 status = waitforjob(jp);
8902 TRACE(("evalpipe: job done exit status %d\n", status));
8910 * Controls whether the shell is interactive or not.
8913 setinteractive(int on)
8915 static smallint is_interactive;
8917 if (++on == is_interactive)
8919 is_interactive = on;
8923 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8924 if (is_interactive > 1) {
8925 /* Looks like they want an interactive shell */
8926 static smallint did_banner;
8929 /* note: ash and hush share this string */
8930 out1fmt("\n\n%s %s\n"
8931 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
8934 "built-in shell (ash)"
8948 setinteractive(iflag);
8950 #if ENABLE_FEATURE_EDITING_VI
8952 line_input_state->flags |= VI_MODE;
8954 line_input_state->flags &= ~VI_MODE;
8956 viflag = 0; /* forcibly keep the option off */
8960 static struct localvar *localvars;
8963 * Called after a function returns.
8964 * Interrupts must be off.
8969 struct localvar *lvp;
8972 while ((lvp = localvars) != NULL) {
8973 localvars = lvp->next;
8975 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
8976 if (vp == NULL) { /* $- saved */
8977 memcpy(optlist, lvp->text, sizeof(optlist));
8978 free((char*)lvp->text);
8980 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8981 unsetvar(vp->var_text);
8984 vp->var_func(var_end(lvp->text));
8985 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8986 free((char*)vp->var_text);
8987 vp->flags = lvp->flags;
8988 vp->var_text = lvp->text;
8995 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8997 volatile struct shparam saveparam;
8998 struct localvar *volatile savelocalvars;
8999 struct jmploc *volatile savehandler;
9000 struct jmploc jmploc;
9003 saveparam = shellparam;
9004 savelocalvars = localvars;
9005 savehandler = exception_handler;
9006 e = setjmp(jmploc.loc);
9011 exception_handler = &jmploc;
9013 shellparam.malloced = 0;
9017 shellparam.nparam = argc - 1;
9018 shellparam.p = argv + 1;
9019 #if ENABLE_ASH_GETOPTS
9020 shellparam.optind = 1;
9021 shellparam.optoff = -1;
9023 evaltree(&func->n, flags & EV_TESTED);
9029 localvars = savelocalvars;
9030 freeparam(&shellparam);
9031 shellparam = saveparam;
9032 exception_handler = savehandler;
9034 evalskip &= ~SKIPFUNC;
9039 * Make a variable a local variable. When a variable is made local, it's
9040 * value and flags are saved in a localvar structure. The saved values
9041 * will be restored when the shell function returns. We handle the name
9042 * "-" as a special case: it makes changes to "set +-options" local
9043 * (options will be restored on return from the function).
9048 struct localvar *lvp;
9051 char *eq = strchr(name, '=');
9054 /* Cater for duplicate "local". Examples:
9055 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9056 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9060 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9064 * it's a duplicate "local VAR" declaration, do nothing
9071 lvp = ckzalloc(sizeof(*lvp));
9072 if (LONE_DASH(name)) {
9074 p = ckmalloc(sizeof(optlist));
9075 lvp->text = memcpy(p, optlist, sizeof(optlist));
9078 vpp = hashvar(name);
9079 vp = *findvar(vpp, name);
9081 /* variable did not exist yet */
9083 setvareq(name, VSTRFIXED);
9085 setvar(name, NULL, VSTRFIXED);
9086 vp = *vpp; /* the new variable */
9087 lvp->flags = VUNSET;
9089 lvp->text = vp->var_text;
9090 lvp->flags = vp->flags;
9091 /* make sure neither "struct var" nor string gets freed
9092 * during (un)setting:
9094 vp->flags |= VSTRFIXED|VTEXTFIXED;
9098 /* "local VAR" unsets VAR: */
9099 setvar0(name, NULL);
9103 lvp->next = localvars;
9109 * The "local" command.
9111 static int FAST_FUNC
9112 localcmd(int argc UNUSED_PARAM, char **argv)
9117 ash_msg_and_raise_error("not in a function");
9120 while ((name = *argv++) != NULL) {
9126 static int FAST_FUNC
9127 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9132 static int FAST_FUNC
9133 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9138 static int FAST_FUNC
9139 execcmd(int argc UNUSED_PARAM, char **argv)
9142 iflag = 0; /* exit on error */
9145 /* We should set up signals for "exec CMD"
9146 * the same way as for "CMD" without "exec".
9147 * But optschanged->setinteractive->setsignal
9148 * still thought we are a root shell. Therefore, for example,
9149 * SIGQUIT is still set to IGN. Fix it:
9153 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9154 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9155 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9157 shellexec(argv + 1, pathval(), 0);
9164 * The return command.
9166 static int FAST_FUNC
9167 returncmd(int argc UNUSED_PARAM, char **argv)
9170 * If called outside a function, do what ksh does;
9171 * skip the rest of the file.
9173 evalskip = SKIPFUNC;
9174 return argv[1] ? number(argv[1]) : exitstatus;
9177 /* Forward declarations for builtintab[] */
9178 static int breakcmd(int, char **) FAST_FUNC;
9179 static int dotcmd(int, char **) FAST_FUNC;
9180 static int evalcmd(int, char **) FAST_FUNC;
9181 static int exitcmd(int, char **) FAST_FUNC;
9182 static int exportcmd(int, char **) FAST_FUNC;
9183 #if ENABLE_ASH_GETOPTS
9184 static int getoptscmd(int, char **) FAST_FUNC;
9187 static int helpcmd(int, char **) FAST_FUNC;
9190 static int historycmd(int, char **) FAST_FUNC;
9192 #if ENABLE_SH_MATH_SUPPORT
9193 static int letcmd(int, char **) FAST_FUNC;
9195 static int readcmd(int, char **) FAST_FUNC;
9196 static int setcmd(int, char **) FAST_FUNC;
9197 static int shiftcmd(int, char **) FAST_FUNC;
9198 static int timescmd(int, char **) FAST_FUNC;
9199 static int trapcmd(int, char **) FAST_FUNC;
9200 static int umaskcmd(int, char **) FAST_FUNC;
9201 static int unsetcmd(int, char **) FAST_FUNC;
9202 static int ulimitcmd(int, char **) FAST_FUNC;
9204 #define BUILTIN_NOSPEC "0"
9205 #define BUILTIN_SPECIAL "1"
9206 #define BUILTIN_REGULAR "2"
9207 #define BUILTIN_SPEC_REG "3"
9208 #define BUILTIN_ASSIGN "4"
9209 #define BUILTIN_SPEC_ASSG "5"
9210 #define BUILTIN_REG_ASSG "6"
9211 #define BUILTIN_SPEC_REG_ASSG "7"
9213 /* Stubs for calling non-FAST_FUNC's */
9214 #if ENABLE_ASH_BUILTIN_ECHO
9215 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9217 #if ENABLE_ASH_BUILTIN_PRINTF
9218 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9220 #if ENABLE_ASH_BUILTIN_TEST
9221 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9224 /* Keep these in proper order since it is searched via bsearch() */
9225 static const struct builtincmd builtintab[] = {
9226 { BUILTIN_SPEC_REG "." , dotcmd },
9227 { BUILTIN_SPEC_REG ":" , truecmd },
9228 #if ENABLE_ASH_BUILTIN_TEST
9229 { BUILTIN_REGULAR "[" , testcmd },
9230 #if ENABLE_ASH_BASH_COMPAT
9231 { BUILTIN_REGULAR "[[" , testcmd },
9234 #if ENABLE_ASH_ALIAS
9235 { BUILTIN_REG_ASSG "alias" , aliascmd },
9238 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9240 { BUILTIN_SPEC_REG "break" , breakcmd },
9241 { BUILTIN_REGULAR "cd" , cdcmd },
9242 { BUILTIN_NOSPEC "chdir" , cdcmd },
9243 #if ENABLE_ASH_CMDCMD
9244 { BUILTIN_REGULAR "command" , commandcmd },
9246 { BUILTIN_SPEC_REG "continue", breakcmd },
9247 #if ENABLE_ASH_BUILTIN_ECHO
9248 { BUILTIN_REGULAR "echo" , echocmd },
9250 { BUILTIN_SPEC_REG "eval" , evalcmd },
9251 { BUILTIN_SPEC_REG "exec" , execcmd },
9252 { BUILTIN_SPEC_REG "exit" , exitcmd },
9253 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9254 { BUILTIN_REGULAR "false" , falsecmd },
9256 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9258 #if ENABLE_ASH_GETOPTS
9259 { BUILTIN_REGULAR "getopts" , getoptscmd },
9261 { BUILTIN_NOSPEC "hash" , hashcmd },
9263 { BUILTIN_NOSPEC "help" , helpcmd },
9266 { BUILTIN_NOSPEC "history" , historycmd },
9269 { BUILTIN_REGULAR "jobs" , jobscmd },
9270 { BUILTIN_REGULAR "kill" , killcmd },
9272 #if ENABLE_SH_MATH_SUPPORT
9273 { BUILTIN_NOSPEC "let" , letcmd },
9275 { BUILTIN_ASSIGN "local" , localcmd },
9276 #if ENABLE_ASH_BUILTIN_PRINTF
9277 { BUILTIN_REGULAR "printf" , printfcmd },
9279 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9280 { BUILTIN_REGULAR "read" , readcmd },
9281 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9282 { BUILTIN_SPEC_REG "return" , returncmd },
9283 { BUILTIN_SPEC_REG "set" , setcmd },
9284 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9285 #if ENABLE_ASH_BASH_COMPAT
9286 { BUILTIN_SPEC_REG "source" , dotcmd },
9288 #if ENABLE_ASH_BUILTIN_TEST
9289 { BUILTIN_REGULAR "test" , testcmd },
9291 { BUILTIN_SPEC_REG "times" , timescmd },
9292 { BUILTIN_SPEC_REG "trap" , trapcmd },
9293 { BUILTIN_REGULAR "true" , truecmd },
9294 { BUILTIN_NOSPEC "type" , typecmd },
9295 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9296 { BUILTIN_REGULAR "umask" , umaskcmd },
9297 #if ENABLE_ASH_ALIAS
9298 { BUILTIN_REGULAR "unalias" , unaliascmd },
9300 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9301 { BUILTIN_REGULAR "wait" , waitcmd },
9304 /* Should match the above table! */
9305 #define COMMANDCMD (builtintab + \
9307 /* [ */ 1 * ENABLE_ASH_BUILTIN_TEST + \
9308 /* [[ */ 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9309 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9310 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9311 /* break cd cddir */ 3)
9312 #define EVALCMD (COMMANDCMD + \
9313 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9314 /* continue */ 1 + \
9315 /* echo */ 1 * ENABLE_ASH_BUILTIN_ECHO + \
9317 #define EXECCMD (EVALCMD + \
9321 * Search the table of builtin commands.
9323 static struct builtincmd *
9324 find_builtin(const char *name)
9326 struct builtincmd *bp;
9329 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9336 * Execute a simple command.
9339 isassignment(const char *p)
9341 const char *q = endofname(p);
9346 static int FAST_FUNC
9347 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9349 /* Preserve exitstatus of a previous possible redirection
9350 * as POSIX mandates */
9351 return back_exitstatus;
9354 evalcommand(union node *cmd, int flags)
9356 static const struct builtincmd null_bltin = {
9357 "\0\0", bltincmd /* why three NULs? */
9359 struct stackmark smark;
9361 struct arglist arglist;
9362 struct arglist varlist;
9365 const struct strlist *sp;
9366 struct cmdentry cmdentry;
9373 struct builtincmd *bcmd;
9374 smallint cmd_is_exec;
9375 smallint pseudovarflag = 0;
9377 /* First expand the arguments. */
9378 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9379 setstackmark(&smark);
9380 back_exitstatus = 0;
9382 cmdentry.cmdtype = CMDBUILTIN;
9383 cmdentry.u.cmd = &null_bltin;
9384 varlist.lastp = &varlist.list;
9385 *varlist.lastp = NULL;
9386 arglist.lastp = &arglist.list;
9387 *arglist.lastp = NULL;
9390 if (cmd->ncmd.args) {
9391 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9392 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9395 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9396 struct strlist **spp;
9398 spp = arglist.lastp;
9399 if (pseudovarflag && isassignment(argp->narg.text))
9400 expandarg(argp, &arglist, EXP_VARTILDE);
9402 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9404 for (sp = *spp; sp; sp = sp->next)
9408 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9409 for (sp = arglist.list; sp; sp = sp->next) {
9410 TRACE(("evalcommand arg: %s\n", sp->text));
9411 *nargv++ = sp->text;
9416 if (iflag && funcnest == 0 && argc > 0)
9417 lastarg = nargv[-1];
9420 expredir(cmd->ncmd.redirect);
9421 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9423 path = vpath.var_text;
9424 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9425 struct strlist **spp;
9428 spp = varlist.lastp;
9429 expandarg(argp, &varlist, EXP_VARTILDE);
9432 * Modify the command lookup path, if a PATH= assignment
9436 if (varcmp(p, path) == 0)
9440 /* Print the command if xflag is set. */
9443 const char *p = " %s" + 1;
9445 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9447 for (n = 0; n < 2; n++) {
9449 fdprintf(preverrout_fd, p, sp->text);
9455 safe_write(preverrout_fd, "\n", 1);
9461 /* Now locate the command. */
9463 int cmd_flag = DO_ERR;
9464 #if ENABLE_ASH_CMDCMD
9465 const char *oldpath = path + 5;
9469 find_command(argv[0], &cmdentry, cmd_flag, path);
9470 if (cmdentry.cmdtype == CMDUNKNOWN) {
9471 flush_stdout_stderr();
9476 /* implement bltin and command here */
9477 if (cmdentry.cmdtype != CMDBUILTIN)
9480 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9481 if (cmdentry.u.cmd == EXECCMD)
9483 #if ENABLE_ASH_CMDCMD
9484 if (cmdentry.u.cmd == COMMANDCMD) {
9486 nargv = parse_command_args(argv, &path);
9489 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9490 * nargv => "PROG". path is updated if -p.
9492 argc -= nargv - argv;
9494 cmd_flag |= DO_NOFUNC;
9502 /* We have a redirection error. */
9504 raise_exception(EXERROR);
9506 exitstatus = status;
9510 /* Execute the command. */
9511 switch (cmdentry.cmdtype) {
9514 #if ENABLE_FEATURE_SH_NOFORK
9515 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9516 * around run_nofork_applet() call.
9517 * (2) Should this check also be done in forkshell()?
9518 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9520 /* find_command() encodes applet_no as (-2 - applet_no) */
9521 int applet_no = (- cmdentry.u.index - 2);
9522 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9523 listsetvar(varlist.list, VEXPORT|VSTACK);
9524 /* run <applet>_main() */
9525 exitstatus = run_nofork_applet(applet_no, argv);
9529 /* Can we avoid forking off? For example, very last command
9530 * in a script or a subshell does not need forking,
9531 * we can just exec it.
9533 if (!(flags & EV_EXIT) || may_have_traps) {
9534 /* No, forking off a child is necessary */
9536 jp = makejob(/*cmd,*/ 1);
9537 if (forkshell(jp, cmd, FORK_FG) != 0) {
9539 status = waitforjob(jp);
9541 TRACE(("forked child exited with %d\n", status));
9546 /* fall through to exec'ing external program */
9548 listsetvar(varlist.list, VEXPORT|VSTACK);
9549 shellexec(argv, path, cmdentry.u.index);
9553 cmdenviron = varlist.list;
9555 struct strlist *list = cmdenviron;
9557 if (spclbltin > 0 || argc == 0) {
9559 if (cmd_is_exec && argc > 1)
9562 listsetvar(list, i);
9564 /* Tight loop with builtins only:
9565 * "while kill -0 $child; do true; done"
9566 * will never exit even if $child died, unless we do this
9567 * to reap the zombie and make kill detect that it's gone: */
9568 dowait(DOWAIT_NONBLOCK, NULL);
9570 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9572 int i = exception_type;
9573 if (i == EXEXIT || i == EXEXEC)
9577 exit_status = 128 + SIGINT;
9579 exit_status = 128 + pending_sig;
9580 exitstatus = exit_status;
9581 if (i == EXINT || spclbltin > 0) {
9583 longjmp(exception_handler->loc, 1);
9590 listsetvar(varlist.list, 0);
9591 /* See above for the rationale */
9592 dowait(DOWAIT_NONBLOCK, NULL);
9593 if (evalfun(cmdentry.u.func, argc, argv, flags))
9596 status = exitstatus;
9601 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9603 /* dsl: I think this is intended to be used to support
9604 * '_' in 'vi' command mode during line editing...
9605 * However I implemented that within libedit itself.
9607 setvar0("_", lastarg);
9609 popstackmark(&smark);
9615 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9617 char *volatile savecmdname;
9618 struct jmploc *volatile savehandler;
9619 struct jmploc jmploc;
9622 savecmdname = commandname;
9623 savehandler = exception_handler;
9624 i = setjmp(jmploc.loc);
9627 exception_handler = &jmploc;
9628 commandname = argv[0];
9630 optptr = NULL; /* initialize nextopt */
9631 exitstatus = (*cmd->builtin)(argc, argv);
9632 flush_stdout_stderr();
9634 exitstatus |= ferror(stdout);
9636 commandname = savecmdname;
9637 exception_handler = savehandler;
9643 goodname(const char *p)
9645 return endofname(p)[0] == '\0';
9650 * Search for a command. This is called before we fork so that the
9651 * location of the command will be available in the parent as well as
9652 * the child. The check for "goodname" is an overly conservative
9653 * check that the name will not be subject to expansion.
9656 prehash(union node *n)
9658 struct cmdentry entry;
9660 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9661 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9665 /* ============ Builtin commands
9667 * Builtin commands whose functions are closely tied to evaluation
9668 * are implemented here.
9672 * Handle break and continue commands. Break, continue, and return are
9673 * all handled by setting the evalskip flag. The evaluation routines
9674 * above all check this flag, and if it is set they start skipping
9675 * commands rather than executing them. The variable skipcount is
9676 * the number of loops to break/continue, or the number of function
9677 * levels to return. (The latter is always 1.) It should probably
9678 * be an error to break out of more loops than exist, but it isn't
9679 * in the standard shell so we don't make it one here.
9681 static int FAST_FUNC
9682 breakcmd(int argc UNUSED_PARAM, char **argv)
9684 int n = argv[1] ? number(argv[1]) : 1;
9687 ash_msg_and_raise_error(msg_illnum, argv[1]);
9691 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9698 /* ============ input.c
9700 * This implements the input routines used by the parser.
9704 INPUT_PUSH_FILE = 1,
9705 INPUT_NOFILE_OK = 2,
9708 static smallint checkkwd;
9709 /* values of checkkwd variable */
9710 #define CHKALIAS 0x1
9715 * Push a string back onto the input at this current parsefile level.
9716 * We handle aliases this way.
9718 #if !ENABLE_ASH_ALIAS
9719 #define pushstring(s, ap) pushstring(s)
9722 pushstring(char *s, struct alias *ap)
9729 if (g_parsefile->strpush) {
9730 sp = ckzalloc(sizeof(*sp));
9731 sp->prev = g_parsefile->strpush;
9733 sp = &(g_parsefile->basestrpush);
9735 g_parsefile->strpush = sp;
9736 sp->prev_string = g_parsefile->next_to_pgetc;
9737 sp->prev_left_in_line = g_parsefile->left_in_line;
9738 sp->unget = g_parsefile->unget;
9739 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9740 #if ENABLE_ASH_ALIAS
9743 ap->flag |= ALIASINUSE;
9747 g_parsefile->next_to_pgetc = s;
9748 g_parsefile->left_in_line = len;
9749 g_parsefile->unget = 0;
9756 struct strpush *sp = g_parsefile->strpush;
9759 #if ENABLE_ASH_ALIAS
9761 if (g_parsefile->next_to_pgetc[-1] == ' '
9762 || g_parsefile->next_to_pgetc[-1] == '\t'
9764 checkkwd |= CHKALIAS;
9766 if (sp->string != sp->ap->val) {
9769 sp->ap->flag &= ~ALIASINUSE;
9770 if (sp->ap->flag & ALIASDEAD) {
9771 unalias(sp->ap->name);
9775 g_parsefile->next_to_pgetc = sp->prev_string;
9776 g_parsefile->left_in_line = sp->prev_left_in_line;
9777 g_parsefile->unget = sp->unget;
9778 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
9779 g_parsefile->strpush = sp->prev;
9780 if (sp != &(g_parsefile->basestrpush))
9789 char *buf = g_parsefile->buf;
9791 g_parsefile->next_to_pgetc = buf;
9792 #if ENABLE_FEATURE_EDITING
9794 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9795 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9798 # if ENABLE_ASH_IDLE_TIMEOUT
9800 const char *tmout_var = lookupvar("TMOUT");
9802 timeout = atoi(tmout_var) * 1000;
9808 # if ENABLE_FEATURE_TAB_COMPLETION
9809 line_input_state->path_lookup = pathval();
9811 reinit_unicode_for_ash();
9812 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9814 /* Ctrl+C pressed */
9825 /* Ctrl+D pressed */
9828 # if ENABLE_ASH_IDLE_TIMEOUT
9829 else if (errno == EAGAIN && timeout > 0) {
9830 puts("\007timed out waiting for input: auto-logout");
9837 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9840 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9842 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9843 int flags = fcntl(0, F_GETFL);
9844 if (flags >= 0 && (flags & O_NONBLOCK)) {
9845 flags &= ~O_NONBLOCK;
9846 if (fcntl(0, F_SETFL, flags) >= 0) {
9847 out2str("sh: turning off NDELAY mode\n");
9858 * Refill the input buffer and return the next input character:
9860 * 1) If a string was pushed back on the input, pop it;
9861 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9862 * or we are reading from a string so we can't refill the buffer,
9864 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9865 * 4) Process input up to the next newline, deleting nul characters.
9867 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9868 #define pgetc_debug(...) ((void)0)
9869 static int pgetc(void);
9876 if (g_parsefile->strpush) {
9877 #if ENABLE_ASH_ALIAS
9878 if (g_parsefile->left_in_line == -1
9879 && g_parsefile->strpush->ap
9880 && g_parsefile->next_to_pgetc[-1] != ' '
9881 && g_parsefile->next_to_pgetc[-1] != '\t'
9883 pgetc_debug("preadbuffer PEOA");
9890 /* on both branches above g_parsefile->left_in_line < 0.
9891 * "pgetc" needs refilling.
9894 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9895 * pungetc() may increment it a few times.
9896 * Assuming it won't increment it to less than -90.
9898 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9899 pgetc_debug("preadbuffer PEOF1");
9900 /* even in failure keep left_in_line and next_to_pgetc
9901 * in lock step, for correct multi-layer pungetc.
9902 * left_in_line was decremented before preadbuffer(),
9903 * must inc next_to_pgetc: */
9904 g_parsefile->next_to_pgetc++;
9908 more = g_parsefile->left_in_buffer;
9910 flush_stdout_stderr();
9914 /* don't try reading again */
9915 g_parsefile->left_in_line = -99;
9916 pgetc_debug("preadbuffer PEOF2");
9917 g_parsefile->next_to_pgetc++;
9922 /* Find out where's the end of line.
9923 * Set g_parsefile->left_in_line
9924 * and g_parsefile->left_in_buffer acordingly.
9925 * NUL chars are deleted.
9927 q = g_parsefile->next_to_pgetc;
9935 memmove(q, q + 1, more);
9939 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9945 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9946 if (g_parsefile->left_in_line < 0)
9951 g_parsefile->left_in_buffer = more;
9956 out2str(g_parsefile->next_to_pgetc);
9960 pgetc_debug("preadbuffer at %d:%p'%s'",
9961 g_parsefile->left_in_line,
9962 g_parsefile->next_to_pgetc,
9963 g_parsefile->next_to_pgetc);
9964 return (unsigned char)*g_parsefile->next_to_pgetc++;
9972 pgetc_debug("pgetc at %d:%p'%s'",
9973 g_parsefile->left_in_line,
9974 g_parsefile->next_to_pgetc,
9975 g_parsefile->next_to_pgetc);
9976 if (g_parsefile->unget)
9977 return g_parsefile->lastc[--g_parsefile->unget];
9979 if (--g_parsefile->left_in_line >= 0)
9980 c = (signed char)*g_parsefile->next_to_pgetc++;
9984 g_parsefile->lastc[1] = g_parsefile->lastc[0];
9985 g_parsefile->lastc[0] = c;
9990 #if ENABLE_ASH_ALIAS
9992 pgetc_without_PEOA(void)
9996 pgetc_debug("pgetc at %d:%p'%s'",
9997 g_parsefile->left_in_line,
9998 g_parsefile->next_to_pgetc,
9999 g_parsefile->next_to_pgetc);
10001 } while (c == PEOA);
10005 # define pgetc_without_PEOA() pgetc()
10009 * Read a line from the script.
10012 pfgets(char *line, int len)
10018 while (--nleft > 0) {
10019 c = pgetc_without_PEOA();
10034 * Undo a call to pgetc. Only two characters may be pushed back.
10035 * PEOF may be pushed back.
10040 g_parsefile->unget++;
10043 /* This one eats backslash+newline */
10049 while ((c = pgetc()) == '\\') {
10050 if (pgetc() != '\n') {
10055 g_parsefile->linno++;
10056 setprompt_if(doprompt, 2);
10063 * To handle the "." command, a stack of input files is used. Pushfile
10064 * adds a new entry to the stack and popfile restores the previous level.
10069 struct parsefile *pf;
10071 pf = ckzalloc(sizeof(*pf));
10072 pf->prev = g_parsefile;
10074 /*pf->strpush = NULL; - ckzalloc did it */
10075 /*pf->basestrpush.prev = NULL;*/
10083 struct parsefile *pf = g_parsefile;
10086 if (pf->pf_fd >= 0)
10089 while (pf->strpush)
10091 g_parsefile = pf->prev;
10097 * Return to top level.
10102 while (g_parsefile != &basepf)
10107 * Close the file(s) that the shell is reading commands from. Called
10108 * after a fork is done.
10114 if (g_parsefile->pf_fd > 0) {
10115 close(g_parsefile->pf_fd);
10116 g_parsefile->pf_fd = 0;
10121 * Like setinputfile, but takes an open file descriptor. Call this with
10125 setinputfd(int fd, int push)
10127 close_on_exec_on(fd);
10130 g_parsefile->buf = NULL;
10132 g_parsefile->pf_fd = fd;
10133 if (g_parsefile->buf == NULL)
10134 g_parsefile->buf = ckmalloc(IBUFSIZ);
10135 g_parsefile->left_in_buffer = 0;
10136 g_parsefile->left_in_line = 0;
10137 g_parsefile->linno = 1;
10141 * Set the input to take input from a file. If push is set, push the
10142 * old input onto the stack first.
10145 setinputfile(const char *fname, int flags)
10151 fd = open(fname, O_RDONLY);
10153 if (flags & INPUT_NOFILE_OK)
10155 ash_msg_and_raise_error("can't open '%s'", fname);
10158 fd2 = copyfd(fd, 10);
10161 ash_msg_and_raise_error("out of file descriptors");
10164 setinputfd(fd, flags & INPUT_PUSH_FILE);
10171 * Like setinputfile, but takes input from a string.
10174 setinputstring(char *string)
10178 g_parsefile->next_to_pgetc = string;
10179 g_parsefile->left_in_line = strlen(string);
10180 g_parsefile->buf = NULL;
10181 g_parsefile->linno = 1;
10186 /* ============ mail.c
10188 * Routines to check for mail.
10191 #if ENABLE_ASH_MAIL
10193 /* Hash of mtimes of mailboxes */
10194 static unsigned mailtime_hash;
10195 /* Set if MAIL or MAILPATH is changed. */
10196 static smallint mail_var_path_changed;
10199 * Print appropriate message(s) if mail has arrived.
10200 * If mail_var_path_changed is set,
10201 * then the value of MAIL has mail_var_path_changed,
10202 * so we just update the values.
10211 struct stackmark smark;
10214 setstackmark(&smark);
10215 mpath = mpathset() ? mpathval() : mailval();
10218 p = path_advance(&mpath, nullstr);
10223 for (q = p; *q; q++)
10229 q[-1] = '\0'; /* delete trailing '/' */
10230 if (stat(p, &statb) < 0) {
10233 /* Very simplistic "hash": just a sum of all mtimes */
10234 new_hash += (unsigned)statb.st_mtime;
10236 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10237 if (mailtime_hash != 0)
10238 out2str("you have mail\n");
10239 mailtime_hash = new_hash;
10241 mail_var_path_changed = 0;
10242 popstackmark(&smark);
10245 static void FAST_FUNC
10246 changemail(const char *val UNUSED_PARAM)
10248 mail_var_path_changed = 1;
10251 #endif /* ASH_MAIL */
10254 /* ============ ??? */
10257 * Set the shell parameters.
10260 setparam(char **argv)
10266 for (nparam = 0; argv[nparam]; nparam++)
10268 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10270 *ap++ = ckstrdup(*argv++);
10273 freeparam(&shellparam);
10274 shellparam.malloced = 1;
10275 shellparam.nparam = nparam;
10276 shellparam.p = newparam;
10277 #if ENABLE_ASH_GETOPTS
10278 shellparam.optind = 1;
10279 shellparam.optoff = -1;
10284 * Process shell options. The global variable argptr contains a pointer
10285 * to the argument list; we advance it past the options.
10287 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10288 * For a non-interactive shell, an error condition encountered
10289 * by a special built-in ... shall cause the shell to write a diagnostic message
10290 * to standard error and exit as shown in the following table:
10291 * Error Special Built-In
10293 * Utility syntax error (option or operand error) Shall exit
10295 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10296 * we see that bash does not do that (set "finishes" with error code 1 instead,
10297 * and shell continues), and people rely on this behavior!
10299 * set -o barfoo 2>/dev/null
10302 * Oh well. Let's mimic that.
10305 plus_minus_o(char *name, int val)
10310 for (i = 0; i < NOPTS; i++) {
10311 if (strcmp(name, optnames(i)) == 0) {
10316 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10319 for (i = 0; i < NOPTS; i++) {
10321 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10323 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10329 setoption(int flag, int val)
10333 for (i = 0; i < NOPTS; i++) {
10334 if (optletters(i) == flag) {
10339 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10343 options(int cmdline)
10351 while ((p = *argptr) != NULL) {
10353 if (c != '-' && c != '+')
10356 val = 0; /* val = 0 if c == '+' */
10359 if (p[0] == '\0' || LONE_DASH(p)) {
10361 /* "-" means turn off -x and -v */
10364 /* "--" means reset params */
10365 else if (*argptr == NULL)
10368 break; /* "-" or "--" terminates options */
10371 /* first char was + or - */
10372 while ((c = *p++) != '\0') {
10373 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10374 if (c == 'c' && cmdline) {
10375 minusc = p; /* command is after shell args */
10376 } else if (c == 'o') {
10377 if (plus_minus_o(*argptr, val)) {
10378 /* it already printed err message */
10379 return 1; /* error */
10383 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10385 /* bash does not accept +-login, we also won't */
10386 } else if (cmdline && val && (c == '-')) { /* long options */
10387 if (strcmp(p, "login") == 0)
10399 * The shift builtin command.
10401 static int FAST_FUNC
10402 shiftcmd(int argc UNUSED_PARAM, char **argv)
10409 n = number(argv[1]);
10410 if (n > shellparam.nparam)
10411 n = 0; /* bash compat, was = shellparam.nparam; */
10413 shellparam.nparam -= n;
10414 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10415 if (shellparam.malloced)
10418 ap2 = shellparam.p;
10419 while ((*ap2++ = *ap1++) != NULL)
10421 #if ENABLE_ASH_GETOPTS
10422 shellparam.optind = 1;
10423 shellparam.optoff = -1;
10430 * POSIX requires that 'set' (but not export or readonly) output the
10431 * variables in lexicographic order - by the locale's collating order (sigh).
10432 * Maybe we could keep them in an ordered balanced binary tree
10433 * instead of hashed lists.
10434 * For now just roll 'em through qsort for printing...
10437 showvars(const char *sep_prefix, int on, int off)
10440 char **ep, **epend;
10442 ep = listvars(on, off, &epend);
10443 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10445 sep = *sep_prefix ? " " : sep_prefix;
10447 for (; ep < epend; ep++) {
10451 p = strchrnul(*ep, '=');
10454 q = single_quote(++p);
10455 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10461 * The set command builtin.
10463 static int FAST_FUNC
10464 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10469 return showvars(nullstr, 0, VUNSET);
10472 retval = options(/*cmdline:*/ 0);
10473 if (retval == 0) { /* if no parse error... */
10475 if (*argptr != NULL) {
10483 #if ENABLE_ASH_RANDOM_SUPPORT
10484 static void FAST_FUNC
10485 change_random(const char *value)
10489 if (value == NULL) {
10490 /* "get", generate */
10491 t = next_random(&random_gen);
10492 /* set without recursion */
10493 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10494 vrandom.flags &= ~VNOFUNC;
10497 t = strtoul(value, NULL, 10);
10498 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10503 #if ENABLE_ASH_GETOPTS
10505 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10516 if (*param_optind < 1)
10518 optnext = optfirst + *param_optind - 1;
10520 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10523 p = optnext[-1] + *optoff;
10524 if (p == NULL || *p == '\0') {
10525 /* Current word is done, advance */
10527 if (p == NULL || *p != '-' || *++p == '\0') {
10534 if (LONE_DASH(p)) /* check for "--" */
10539 for (q = optstr; *q != c;) {
10541 if (optstr[0] == ':') {
10543 /*sbuf[1] = '\0'; - already is */
10544 err |= setvarsafe("OPTARG", sbuf, 0);
10546 fprintf(stderr, "Illegal option -%c\n", c);
10547 unsetvar("OPTARG");
10557 if (*p == '\0' && (p = *optnext) == NULL) {
10558 if (optstr[0] == ':') {
10560 /*sbuf[1] = '\0'; - already is */
10561 err |= setvarsafe("OPTARG", sbuf, 0);
10564 fprintf(stderr, "No arg for -%c option\n", c);
10565 unsetvar("OPTARG");
10573 err |= setvarsafe("OPTARG", p, 0);
10576 err |= setvarsafe("OPTARG", nullstr, 0);
10578 *optoff = p ? p - *(optnext - 1) : -1;
10579 *param_optind = optnext - optfirst + 1;
10580 err |= setvarsafe("OPTIND", itoa(*param_optind), VNOFUNC);
10582 /*sbuf[1] = '\0'; - already is */
10583 err |= setvarsafe(optvar, sbuf, 0);
10587 flush_stdout_stderr();
10588 raise_exception(EXERROR);
10594 * The getopts builtin. Shellparam.optnext points to the next argument
10595 * to be processed. Shellparam.optptr points to the next character to
10596 * be processed in the current argument. If shellparam.optnext is NULL,
10597 * then it's the first time getopts has been called.
10599 static int FAST_FUNC
10600 getoptscmd(int argc, char **argv)
10605 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10607 optbase = shellparam.p;
10608 if (shellparam.optind > shellparam.nparam + 1) {
10609 shellparam.optind = 1;
10610 shellparam.optoff = -1;
10613 optbase = &argv[3];
10614 if (shellparam.optind > argc - 2) {
10615 shellparam.optind = 1;
10616 shellparam.optoff = -1;
10620 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10621 &shellparam.optoff);
10623 #endif /* ASH_GETOPTS */
10626 /* ============ Shell parser */
10629 struct heredoc *next; /* next here document in list */
10630 union node *here; /* redirection node */
10631 char *eofmark; /* string indicating end of input */
10632 smallint striptabs; /* if set, strip leading tabs */
10635 static smallint tokpushback; /* last token pushed back */
10636 static smallint quoteflag; /* set if (part of) last token was quoted */
10637 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10638 static struct heredoc *heredoclist; /* list of here documents to read */
10639 static char *wordtext; /* text of last word returned by readtoken */
10640 static struct nodelist *backquotelist;
10641 static union node *redirnode;
10642 static struct heredoc *heredoc;
10644 static const char *
10645 tokname(char *buf, int tok)
10648 return tokname_array[tok] + 1;
10649 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10653 /* raise_error_unexpected_syntax:
10654 * Called when an unexpected token is read during the parse. The argument
10655 * is the token that is expected, or -1 if more than one type of token can
10656 * occur at this point.
10658 static void raise_error_unexpected_syntax(int) NORETURN;
10660 raise_error_unexpected_syntax(int token)
10666 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10668 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10669 raise_error_syntax(msg);
10673 #define EOFMARKLEN 79
10675 /* parsing is heavily cross-recursive, need these forward decls */
10676 static union node *andor(void);
10677 static union node *pipeline(void);
10678 static union node *parse_command(void);
10679 static void parseheredoc(void);
10680 static int peektoken(void);
10681 static int readtoken(void);
10683 static union node *
10686 union node *n1, *n2, *n3;
10691 switch (peektoken()) {
10699 if (!n1 && (nlflag & 1))
10705 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10706 if (nlflag == 2 && tokname_array[peektoken()][0])
10712 if (tok == TBACKGND) {
10713 if (n2->type == NPIPE) {
10714 n2->npipe.pipe_backgnd = 1;
10716 if (n2->type != NREDIR) {
10717 n3 = stzalloc(sizeof(struct nredir));
10719 /*n3->nredir.redirect = NULL; - stzalloc did it */
10722 n2->type = NBACKGND;
10728 n3 = stzalloc(sizeof(struct nbinary));
10730 n3->nbinary.ch1 = n1;
10731 n3->nbinary.ch2 = n2;
10744 raise_error_unexpected_syntax(-1);
10751 static union node *
10754 union node *n1, *n2, *n3;
10762 } else if (t == TOR) {
10768 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10770 n3 = stzalloc(sizeof(struct nbinary));
10772 n3->nbinary.ch1 = n1;
10773 n3->nbinary.ch2 = n2;
10778 static union node *
10781 union node *n1, *n2, *pipenode;
10782 struct nodelist *lp, *prev;
10786 TRACE(("pipeline: entered\n"));
10787 if (readtoken() == TNOT) {
10789 checkkwd = CHKKWD | CHKALIAS;
10792 n1 = parse_command();
10793 if (readtoken() == TPIPE) {
10794 pipenode = stzalloc(sizeof(struct npipe));
10795 pipenode->type = NPIPE;
10796 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10797 lp = stzalloc(sizeof(struct nodelist));
10798 pipenode->npipe.cmdlist = lp;
10802 lp = stzalloc(sizeof(struct nodelist));
10803 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10804 lp->n = parse_command();
10806 } while (readtoken() == TPIPE);
10812 n2 = stzalloc(sizeof(struct nnot));
10820 static union node *
10825 n = stzalloc(sizeof(struct narg));
10827 /*n->narg.next = NULL; - stzalloc did it */
10828 n->narg.text = wordtext;
10829 n->narg.backquote = backquotelist;
10834 fixredir(union node *n, const char *text, int err)
10838 TRACE(("Fix redir %s %d\n", text, err));
10840 n->ndup.vname = NULL;
10842 fd = bb_strtou(text, NULL, 10);
10843 if (!errno && fd >= 0)
10844 n->ndup.dupfd = fd;
10845 else if (LONE_DASH(text))
10846 n->ndup.dupfd = -1;
10849 raise_error_syntax("bad fd number");
10850 n->ndup.vname = makename();
10855 * Returns true if the text contains nothing to expand (no dollar signs
10859 noexpand(const char *text)
10863 while ((c = *text++) != '\0') {
10864 if (c == CTLQUOTEMARK)
10868 else if (SIT(c, BASESYNTAX) == CCTL)
10877 union node *n = redirnode;
10879 if (readtoken() != TWORD)
10880 raise_error_unexpected_syntax(-1);
10881 if (n->type == NHERE) {
10882 struct heredoc *here = heredoc;
10886 if (quoteflag == 0)
10888 TRACE(("Here document %d\n", n->type));
10889 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10890 raise_error_syntax("illegal eof marker for << redirection");
10891 rmescapes(wordtext, 0);
10892 here->eofmark = wordtext;
10894 if (heredoclist == NULL)
10895 heredoclist = here;
10897 for (p = heredoclist; p->next; p = p->next)
10901 } else if (n->type == NTOFD || n->type == NFROMFD) {
10902 fixredir(n, wordtext, 0);
10904 n->nfile.fname = makename();
10908 static union node *
10911 union node *args, **app;
10912 union node *n = NULL;
10913 union node *vars, **vpp;
10914 union node **rpp, *redir;
10916 #if ENABLE_ASH_BASH_COMPAT
10917 smallint double_brackets_flag = 0;
10918 smallint function_flag = 0;
10928 savecheckkwd = CHKALIAS;
10931 checkkwd = savecheckkwd;
10934 #if ENABLE_ASH_BASH_COMPAT
10936 if (peektoken() != TWORD)
10937 raise_error_unexpected_syntax(TWORD);
10940 case TAND: /* "&&" */
10941 case TOR: /* "||" */
10942 if (!double_brackets_flag) {
10946 wordtext = (char *) (t == TAND ? "-a" : "-o");
10949 n = stzalloc(sizeof(struct narg));
10951 /*n->narg.next = NULL; - stzalloc did it */
10952 n->narg.text = wordtext;
10953 #if ENABLE_ASH_BASH_COMPAT
10954 if (strcmp("[[", wordtext) == 0)
10955 double_brackets_flag = 1;
10956 else if (strcmp("]]", wordtext) == 0)
10957 double_brackets_flag = 0;
10959 n->narg.backquote = backquotelist;
10960 if (savecheckkwd && isassignment(wordtext)) {
10962 vpp = &n->narg.next;
10965 app = &n->narg.next;
10968 #if ENABLE_ASH_BASH_COMPAT
10969 if (function_flag) {
10970 checkkwd = CHKNL | CHKKWD;
10971 switch (peektoken()) {
10983 if (strcmp("[[", wordtext) == 0)
10987 raise_error_unexpected_syntax(-1);
10993 *rpp = n = redirnode;
10994 rpp = &n->nfile.next;
10995 parsefname(); /* read name of redirection file */
10998 IF_ASH_BASH_COMPAT(do_func:)
10999 if (args && app == &args->narg.next
11002 struct builtincmd *bcmd;
11005 /* We have a function */
11006 if (IF_ASH_BASH_COMPAT(!function_flag &&) readtoken() != TRP)
11007 raise_error_unexpected_syntax(TRP);
11008 name = n->narg.text;
11009 if (!goodname(name)
11010 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11012 raise_error_syntax("bad function name");
11015 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11016 n->narg.next = parse_command();
11019 IF_ASH_BASH_COMPAT(function_flag = 0;)
11030 n = stzalloc(sizeof(struct ncmd));
11032 n->ncmd.args = args;
11033 n->ncmd.assign = vars;
11034 n->ncmd.redirect = redir;
11038 static union node *
11039 parse_command(void)
11041 union node *n1, *n2;
11042 union node *ap, **app;
11043 union node *cp, **cpp;
11044 union node *redir, **rpp;
11051 switch (readtoken()) {
11053 raise_error_unexpected_syntax(-1);
11056 n1 = stzalloc(sizeof(struct nif));
11058 n1->nif.test = list(0);
11059 if (readtoken() != TTHEN)
11060 raise_error_unexpected_syntax(TTHEN);
11061 n1->nif.ifpart = list(0);
11063 while (readtoken() == TELIF) {
11064 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11065 n2 = n2->nif.elsepart;
11067 n2->nif.test = list(0);
11068 if (readtoken() != TTHEN)
11069 raise_error_unexpected_syntax(TTHEN);
11070 n2->nif.ifpart = list(0);
11072 if (lasttoken == TELSE)
11073 n2->nif.elsepart = list(0);
11075 n2->nif.elsepart = NULL;
11083 n1 = stzalloc(sizeof(struct nbinary));
11084 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11085 n1->nbinary.ch1 = list(0);
11088 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
11089 got == TWORD ? wordtext : ""));
11090 raise_error_unexpected_syntax(TDO);
11092 n1->nbinary.ch2 = list(0);
11097 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11098 raise_error_syntax("bad for loop variable");
11099 n1 = stzalloc(sizeof(struct nfor));
11101 n1->nfor.var = wordtext;
11102 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11103 if (readtoken() == TIN) {
11105 while (readtoken() == TWORD) {
11106 n2 = stzalloc(sizeof(struct narg));
11108 /*n2->narg.next = NULL; - stzalloc did it */
11109 n2->narg.text = wordtext;
11110 n2->narg.backquote = backquotelist;
11112 app = &n2->narg.next;
11115 n1->nfor.args = ap;
11116 if (lasttoken != TNL && lasttoken != TSEMI)
11117 raise_error_unexpected_syntax(-1);
11119 n2 = stzalloc(sizeof(struct narg));
11121 /*n2->narg.next = NULL; - stzalloc did it */
11122 n2->narg.text = (char *)dolatstr;
11123 /*n2->narg.backquote = NULL;*/
11124 n1->nfor.args = n2;
11126 * Newline or semicolon here is optional (but note
11127 * that the original Bourne shell only allowed NL).
11129 if (lasttoken != TSEMI)
11132 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11133 if (readtoken() != TDO)
11134 raise_error_unexpected_syntax(TDO);
11135 n1->nfor.body = list(0);
11139 n1 = stzalloc(sizeof(struct ncase));
11141 if (readtoken() != TWORD)
11142 raise_error_unexpected_syntax(TWORD);
11143 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11145 /*n2->narg.next = NULL; - stzalloc did it */
11146 n2->narg.text = wordtext;
11147 n2->narg.backquote = backquotelist;
11148 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11149 if (readtoken() != TIN)
11150 raise_error_unexpected_syntax(TIN);
11151 cpp = &n1->ncase.cases;
11153 checkkwd = CHKNL | CHKKWD;
11155 while (t != TESAC) {
11156 if (lasttoken == TLP)
11158 *cpp = cp = stzalloc(sizeof(struct nclist));
11160 app = &cp->nclist.pattern;
11162 *app = ap = stzalloc(sizeof(struct narg));
11164 /*ap->narg.next = NULL; - stzalloc did it */
11165 ap->narg.text = wordtext;
11166 ap->narg.backquote = backquotelist;
11167 if (readtoken() != TPIPE)
11169 app = &ap->narg.next;
11172 //ap->narg.next = NULL;
11173 if (lasttoken != TRP)
11174 raise_error_unexpected_syntax(TRP);
11175 cp->nclist.body = list(2);
11177 cpp = &cp->nclist.next;
11179 checkkwd = CHKNL | CHKKWD;
11183 raise_error_unexpected_syntax(TENDCASE);
11190 n1 = stzalloc(sizeof(struct nredir));
11191 n1->type = NSUBSHELL;
11192 n1->nredir.n = list(0);
11193 /*n1->nredir.redirect = NULL; - stzalloc did it */
11200 IF_ASH_BASH_COMPAT(case TFUNCTION:)
11204 return simplecmd();
11207 if (readtoken() != t)
11208 raise_error_unexpected_syntax(t);
11211 /* Now check for redirection which may follow command */
11212 checkkwd = CHKKWD | CHKALIAS;
11214 while (readtoken() == TREDIR) {
11215 *rpp = n2 = redirnode;
11216 rpp = &n2->nfile.next;
11222 if (n1->type != NSUBSHELL) {
11223 n2 = stzalloc(sizeof(struct nredir));
11228 n1->nredir.redirect = redir;
11233 #if ENABLE_ASH_BASH_COMPAT
11234 static int decode_dollar_squote(void)
11236 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11242 p = strchr(C_escapes, c);
11247 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11251 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11253 } else if (c == 'x') { /* \xHH */
11257 } while (isxdigit(c) && --cnt);
11259 if (cnt == 3) { /* \x but next char is "bad" */
11263 } else { /* simple seq like \\ or \t */
11268 c = bb_process_escape_sequence((void*)&p);
11269 } else { /* unrecognized "\z": print both chars unless ' or " */
11270 if (c != '\'' && c != '"') {
11272 c |= 0x100; /* "please encode \, then me" */
11280 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11281 * is not NULL, read a here document. In the latter case, eofmark is the
11282 * word which marks the end of the document and striptabs is true if
11283 * leading tabs should be stripped from the document. The argument c
11284 * is the first character of the input token or document.
11286 * Because C does not have internal subroutines, I have simulated them
11287 * using goto's to implement the subroutine linkage. The following macros
11288 * will run code that appears at the end of readtoken1.
11290 #define CHECKEND() {goto checkend; checkend_return:;}
11291 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11292 #define PARSESUB() {goto parsesub; parsesub_return:;}
11293 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11294 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11295 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11297 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11299 /* NB: syntax parameter fits into smallint */
11300 /* c parameter is an unsigned char or PEOF or PEOA */
11303 char line[EOFMARKLEN + 1];
11304 struct nodelist *bqlist;
11308 smallint prevsyntax; /* syntax before arithmetic */
11309 #if ENABLE_ASH_EXPAND_PRMT
11310 smallint pssyntax; /* we are expanding a prompt string */
11312 int varnest; /* levels of variables expansion */
11313 int arinest; /* levels of arithmetic expansion */
11314 int parenlevel; /* levels of parens in arithmetic */
11315 int dqvarnest; /* levels of variables expansion within double quotes */
11317 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11319 startlinno = g_parsefile->linno;
11323 #if ENABLE_ASH_EXPAND_PRMT
11324 pssyntax = (syntax == PSSYNTAX);
11328 dblquote = (syntax == DQSYNTAX);
11334 STARTSTACKSTR(out);
11336 /* For each line, until end of word */
11337 CHECKEND(); /* set c to PEOF if at end of here document */
11338 for (;;) { /* until end of line or end of word */
11339 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11340 switch (SIT(c, syntax)) {
11341 case CNL: /* '\n' */
11342 if (syntax == BASESYNTAX)
11343 goto endword; /* exit outer loop */
11345 g_parsefile->linno++;
11346 setprompt_if(doprompt, 2);
11348 goto loop; /* continue outer loop */
11353 #if ENABLE_ASH_BASH_COMPAT
11354 if (c == '\\' && bash_dollar_squote) {
11355 c = decode_dollar_squote();
11357 /* skip $'\000', $'\x00' (like bash) */
11361 /* Unknown escape. Encode as '\z' */
11362 c = (unsigned char)c;
11363 if (eofmark == NULL || dblquote)
11364 USTPUTC(CTLESC, out);
11365 USTPUTC('\\', out);
11369 if (eofmark == NULL || dblquote)
11370 USTPUTC(CTLESC, out);
11373 case CBACK: /* backslash */
11374 c = pgetc_without_PEOA();
11376 USTPUTC(CTLESC, out);
11377 USTPUTC('\\', out);
11379 } else if (c == '\n') {
11380 setprompt_if(doprompt, 2);
11382 #if ENABLE_ASH_EXPAND_PRMT
11383 if (c == '$' && pssyntax) {
11384 USTPUTC(CTLESC, out);
11385 USTPUTC('\\', out);
11388 /* Backslash is retained if we are in "str" and next char isn't special */
11393 && (c != '"' || eofmark != NULL)
11395 USTPUTC('\\', out);
11397 USTPUTC(CTLESC, out);
11405 if (eofmark == NULL) {
11406 USTPUTC(CTLQUOTEMARK, out);
11414 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11415 if (eofmark != NULL && varnest == 0) {
11418 if (dqvarnest == 0) {
11419 syntax = BASESYNTAX;
11426 case CVAR: /* '$' */
11427 PARSESUB(); /* parse substitution */
11429 case CENDVAR: /* '}' */
11432 if (dqvarnest > 0) {
11439 #if ENABLE_SH_MATH_SUPPORT
11440 case CLP: /* '(' in arithmetic */
11444 case CRP: /* ')' in arithmetic */
11445 if (parenlevel > 0) {
11448 if (pgetc_eatbnl() == ')') {
11450 if (--arinest == 0) {
11451 syntax = prevsyntax;
11455 * unbalanced parens
11456 * (don't 2nd guess - no error)
11464 case CBQUOTE: /* '`' */
11468 goto endword; /* exit outer loop */
11472 if (varnest == 0) {
11473 #if ENABLE_ASH_BASH_COMPAT
11475 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11476 if (pgetc() == '>')
11477 c = 0x100 + '>'; /* flag &> */
11481 goto endword; /* exit outer loop */
11483 IF_ASH_ALIAS(if (c != PEOA))
11490 #if ENABLE_SH_MATH_SUPPORT
11491 if (syntax == ARISYNTAX)
11492 raise_error_syntax("missing '))'");
11494 if (syntax != BASESYNTAX && eofmark == NULL)
11495 raise_error_syntax("unterminated quoted string");
11496 if (varnest != 0) {
11497 startlinno = g_parsefile->linno;
11499 raise_error_syntax("missing '}'");
11501 USTPUTC('\0', out);
11502 len = out - (char *)stackblock();
11503 out = stackblock();
11504 if (eofmark == NULL) {
11505 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11508 if (isdigit_str9(out)) {
11509 PARSEREDIR(); /* passed as params: out, c */
11510 lasttoken = TREDIR;
11513 /* else: non-number X seen, interpret it
11514 * as "NNNX>file" = "NNNX >file" */
11518 quoteflag = quotef;
11519 backquotelist = bqlist;
11520 grabstackblock(len);
11524 /* end of readtoken routine */
11527 * Check to see whether we are at the end of the here document. When this
11528 * is called, c is set to the first character of the next input line. If
11529 * we are at the end of the here document, this routine sets the c to PEOF.
11533 #if ENABLE_ASH_ALIAS
11535 c = pgetc_without_PEOA();
11538 while (c == '\t') {
11539 c = pgetc_without_PEOA();
11542 if (c == *eofmark) {
11543 if (pfgets(line, sizeof(line)) != NULL) {
11547 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11549 if (*p == '\n' && *q == '\0') {
11551 g_parsefile->linno++;
11552 needprompt = doprompt;
11554 pushstring(line, NULL);
11559 goto checkend_return;
11563 * Parse a redirection operator. The variable "out" points to a string
11564 * specifying the fd to be redirected. The variable "c" contains the
11565 * first character of the redirection operator.
11568 /* out is already checked to be a valid number or "" */
11569 int fd = (*out == '\0' ? -1 : atoi(out));
11572 np = stzalloc(sizeof(struct nfile));
11577 np->type = NAPPEND;
11579 np->type = NCLOBBER;
11582 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11588 #if ENABLE_ASH_BASH_COMPAT
11589 else if (c == 0x100 + '>') { /* this flags &> redirection */
11591 pgetc(); /* this is '>', no need to check */
11595 else { /* c == '<' */
11596 /*np->nfile.fd = 0; - stzalloc did it */
11600 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11601 np = stzalloc(sizeof(struct nhere));
11602 /*np->nfile.fd = 0; - stzalloc did it */
11605 heredoc = stzalloc(sizeof(struct heredoc));
11606 heredoc->here = np;
11609 heredoc->striptabs = 1;
11611 /*heredoc->striptabs = 0; - stzalloc did it */
11617 np->type = NFROMFD;
11621 np->type = NFROMTO;
11633 goto parseredir_return;
11637 * Parse a substitution. At this point, we have read the dollar sign
11638 * and nothing else.
11641 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11642 * (assuming ascii char codes, as the original implementation did) */
11643 #define is_special(c) \
11644 (((unsigned)(c) - 33 < 32) \
11645 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11647 unsigned char subtype;
11651 c = pgetc_eatbnl();
11652 if (c > 255 /* PEOA or PEOF */
11653 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11655 #if ENABLE_ASH_BASH_COMPAT
11656 if (syntax != DQSYNTAX && c == '\'')
11657 bash_dollar_squote = 1;
11662 } else if (c == '(') {
11663 /* $(command) or $((arith)) */
11664 if (pgetc_eatbnl() == '(') {
11665 #if ENABLE_SH_MATH_SUPPORT
11668 raise_error_syntax("you disabled math support for $((arith)) syntax");
11675 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11676 USTPUTC(CTLVAR, out);
11677 typeloc = out - (char *)stackblock();
11678 USTPUTC(VSNORMAL, out);
11679 subtype = VSNORMAL;
11681 c = pgetc_eatbnl();
11683 c = pgetc_eatbnl();
11685 c = '#'; /* ${#} - same as $# */
11687 subtype = VSLENGTH; /* ${#VAR} */
11692 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11693 /* $[{[#]]NAME[}] */
11696 c = pgetc_eatbnl();
11697 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11698 } else if (isdigit(c)) {
11699 /* $[{[#]]NUM[}] */
11702 c = pgetc_eatbnl();
11703 } while (isdigit(c));
11704 } else if (is_special(c)) {
11705 /* $[{[#]]<specialchar>[}] */
11707 c = pgetc_eatbnl();
11710 raise_error_syntax("bad substitution");
11712 if (c != '}' && subtype == VSLENGTH) {
11713 /* ${#VAR didn't end with } */
11719 if (subtype == 0) {
11720 static const char types[] ALIGN1 = "}-+?=";
11721 /* ${VAR...} but not $VAR or ${#VAR} */
11722 /* c == first char after VAR */
11725 c = pgetc_eatbnl();
11726 #if ENABLE_ASH_BASH_COMPAT
11727 /* This check is only needed to not misinterpret
11728 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11731 if (!strchr(types, c)) {
11732 subtype = VSSUBSTR;
11734 break; /* "goto do_pungetc" is bigger (!) */
11740 const char *p = strchr(types, c);
11743 subtype = p - types + VSNORMAL;
11749 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11750 c = pgetc_eatbnl();
11756 #if ENABLE_ASH_BASH_COMPAT
11758 /* ${v/[/]pattern/repl} */
11759 //TODO: encode pattern and repl separately.
11760 // Currently ${v/$var_with_slash/repl} is horribly broken
11761 subtype = VSREPLACE;
11762 c = pgetc_eatbnl();
11765 subtype++; /* VSREPLACEALL */
11773 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11774 if (subtype != VSNORMAL) {
11781 goto parsesub_return;
11785 * Called to parse command substitutions. Newstyle is set if the command
11786 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11787 * list of commands (passed by reference), and savelen is the number of
11788 * characters on the top of the stack which must be preserved.
11791 struct nodelist **nlpp;
11795 smallint saveprompt = 0;
11798 savelen = out - (char *)stackblock();
11801 * FIXME: this can allocate very large block on stack and SEGV.
11803 * echo "..<100kbytes>..`true` $(true) `true` ..."
11804 * allocates 100kb for every command subst. With about
11805 * a hundred command substitutions stack overflows.
11806 * With larger prepended string, SEGV happens sooner.
11808 str = alloca(savelen);
11809 memcpy(str, stackblock(), savelen);
11813 /* We must read until the closing backquote, giving special
11814 * treatment to some slashes, and then push the string and
11815 * reread it as input, interpreting it normally.
11821 STARTSTACKSTR(pout);
11825 setprompt_if(needprompt, 2);
11834 g_parsefile->linno++;
11835 setprompt_if(doprompt, 2);
11837 * If eating a newline, avoid putting
11838 * the newline into the new character
11839 * stream (via the STPUTC after the
11844 if (pc != '\\' && pc != '`' && pc != '$'
11845 && (!dblquote || pc != '"')
11847 STPUTC('\\', pout);
11849 if (pc <= 255 /* not PEOA or PEOF */) {
11855 IF_ASH_ALIAS(case PEOA:)
11856 startlinno = g_parsefile->linno;
11857 raise_error_syntax("EOF in backquote substitution");
11860 g_parsefile->linno++;
11861 needprompt = doprompt;
11870 STPUTC('\0', pout);
11871 psavelen = pout - (char *)stackblock();
11872 if (psavelen > 0) {
11873 pstr = grabstackstr(pout);
11874 setinputstring(pstr);
11879 nlpp = &(*nlpp)->next;
11880 *nlpp = stzalloc(sizeof(**nlpp));
11881 /* (*nlpp)->next = NULL; - stzalloc did it */
11884 saveprompt = doprompt;
11891 doprompt = saveprompt;
11892 else if (readtoken() != TRP)
11893 raise_error_unexpected_syntax(TRP);
11898 * Start reading from old file again, ignoring any pushed back
11899 * tokens left from the backquote parsing
11904 while (stackblocksize() <= savelen)
11906 STARTSTACKSTR(out);
11908 memcpy(out, str, savelen);
11909 STADJUST(savelen, out);
11911 USTPUTC(CTLBACKQ, out);
11913 goto parsebackq_oldreturn;
11914 goto parsebackq_newreturn;
11917 #if ENABLE_SH_MATH_SUPPORT
11919 * Parse an arithmetic expansion (indicate start of one and set state)
11922 if (++arinest == 1) {
11923 prevsyntax = syntax;
11924 syntax = ARISYNTAX;
11926 USTPUTC(CTLARI, out);
11927 goto parsearith_return;
11930 } /* end of readtoken */
11933 * Read the next input token.
11934 * If the token is a word, we set backquotelist to the list of cmds in
11935 * backquotes. We set quoteflag to true if any part of the word was
11937 * If the token is TREDIR, then we set redirnode to a structure containing
11939 * In all cases, the variable startlinno is set to the number of the line
11940 * on which the token starts.
11942 * [Change comment: here documents and internal procedures]
11943 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11944 * word parsing code into a separate routine. In this case, readtoken
11945 * doesn't need to have any internal procedures, but parseword does.
11946 * We could also make parseoperator in essence the main routine, and
11947 * have parseword (readtoken1?) handle both words and redirection.]
11949 #define NEW_xxreadtoken
11950 #ifdef NEW_xxreadtoken
11951 /* singles must be first! */
11952 static const char xxreadtoken_chars[7] ALIGN1 = {
11953 '\n', '(', ')', /* singles */
11954 '&', '|', ';', /* doubles */
11958 #define xxreadtoken_singles 3
11959 #define xxreadtoken_doubles 3
11961 static const char xxreadtoken_tokens[] ALIGN1 = {
11962 TNL, TLP, TRP, /* only single occurrence allowed */
11963 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11964 TEOF, /* corresponds to trailing nul */
11965 TAND, TOR, TENDCASE /* if double occurrence */
11977 setprompt_if(needprompt, 2);
11978 startlinno = g_parsefile->linno;
11979 for (;;) { /* until token or start of word found */
11981 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11985 while ((c = pgetc()) != '\n' && c != PEOF)
11988 } else if (c == '\\') {
11989 if (pgetc() != '\n') {
11991 break; /* return readtoken1(...) */
11993 startlinno = ++g_parsefile->linno;
11994 setprompt_if(doprompt, 2);
11998 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12001 g_parsefile->linno++;
12002 needprompt = doprompt;
12005 p = strchr(xxreadtoken_chars, c);
12007 break; /* return readtoken1(...) */
12009 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12011 if (cc == c) { /* double occurrence? */
12012 p += xxreadtoken_doubles + 1;
12015 #if ENABLE_ASH_BASH_COMPAT
12016 if (c == '&' && cc == '>') /* &> */
12017 break; /* return readtoken1(...) */
12022 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12027 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12029 #else /* old xxreadtoken */
12030 #define RETURN(token) return lasttoken = token
12040 setprompt_if(needprompt, 2);
12041 startlinno = g_parsefile->linno;
12042 for (;;) { /* until token or start of word found */
12045 case ' ': case '\t':
12046 IF_ASH_ALIAS(case PEOA:)
12049 while ((c = pgetc()) != '\n' && c != PEOF)
12054 if (pgetc() == '\n') {
12055 startlinno = ++g_parsefile->linno;
12056 setprompt_if(doprompt, 2);
12062 g_parsefile->linno++;
12063 needprompt = doprompt;
12068 if (pgetc() == '&')
12073 if (pgetc() == '|')
12078 if (pgetc() == ';')
12091 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12094 #endif /* old xxreadtoken */
12100 int kwd = checkkwd;
12102 smallint alreadyseen = tokpushback;
12105 #if ENABLE_ASH_ALIAS
12121 if (t != TWORD || quoteflag) {
12126 * check for keywords
12128 if (kwd & CHKKWD) {
12129 const char *const *pp;
12131 pp = findkwd(wordtext);
12133 lasttoken = t = pp - tokname_array;
12134 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
12139 if (checkkwd & CHKALIAS) {
12140 #if ENABLE_ASH_ALIAS
12142 ap = lookupalias(wordtext, 1);
12145 pushstring(ap->val, ap);
12155 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
12157 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
12173 * Read and parse a command. Returns NODE_EOF on end of file.
12174 * (NULL is a valid parse tree indicating a blank line.)
12176 static union node *
12177 parsecmd(int interact)
12182 doprompt = interact;
12183 setprompt_if(doprompt, doprompt);
12189 * Input any here documents.
12194 struct heredoc *here;
12197 here = heredoclist;
12198 heredoclist = NULL;
12201 setprompt_if(needprompt, 2);
12202 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12203 here->eofmark, here->striptabs);
12204 n = stzalloc(sizeof(struct narg));
12205 n->narg.type = NARG;
12206 /*n->narg.next = NULL; - stzalloc did it */
12207 n->narg.text = wordtext;
12208 n->narg.backquote = backquotelist;
12209 here->here->nhere.doc = n;
12216 * called by editline -- any expansions to the prompt should be added here.
12218 #if ENABLE_ASH_EXPAND_PRMT
12219 static const char *
12220 expandstr(const char *ps)
12224 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12225 * and token processing _can_ alter it (delete NULs etc). */
12226 setinputstring((char *)ps);
12227 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12230 n.narg.type = NARG;
12231 n.narg.next = NULL;
12232 n.narg.text = wordtext;
12233 n.narg.backquote = backquotelist;
12235 expandarg(&n, NULL, EXP_QUOTED);
12236 return stackblock();
12241 * Execute a command or commands contained in a string.
12244 evalstring(char *s, int mask)
12247 struct stackmark smark;
12252 setstackmark(&smark);
12255 while ((n = parsecmd(0)) != NODE_EOF) {
12258 i = evaltree(n, 0);
12261 popstackmark(&smark);
12265 popstackmark(&smark);
12274 * The eval command.
12276 static int FAST_FUNC
12277 evalcmd(int argc UNUSED_PARAM, char **argv)
12286 STARTSTACKSTR(concat);
12288 concat = stack_putstr(p, concat);
12292 STPUTC(' ', concat);
12294 STPUTC('\0', concat);
12295 p = grabstackstr(concat);
12297 return evalstring(p, ~SKIPEVAL);
12303 * Read and execute commands.
12304 * "Top" is nonzero for the top level command loop;
12305 * it turns on prompting if the shell is interactive.
12311 struct stackmark smark;
12316 TRACE(("cmdloop(%d) called\n", top));
12320 setstackmark(&smark);
12323 showjobs(SHOW_CHANGED|SHOW_STDERR);
12326 if (iflag && top) {
12330 n = parsecmd(inter);
12332 if (DEBUG > 2 && debug && (n != NODE_EOF))
12335 if (n == NODE_EOF) {
12336 if (!top || numeof >= 50)
12338 if (!stoppedjobs()) {
12341 out2str("\nUse \"exit\" to leave shell.\n");
12344 } else if (nflag == 0) {
12347 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12350 i = evaltree(n, 0);
12354 popstackmark(&smark);
12358 evalskip &= ~SKIPFUNC;
12359 return skip & SKIPEVAL;
12366 * Take commands from a file. To be compatible we should do a path
12367 * search for the file, which is necessary to find sub-commands.
12370 find_dot_file(char *name)
12373 const char *path = pathval();
12376 /* don't try this for absolute or relative paths */
12377 if (strchr(name, '/'))
12380 /* IIRC standards do not say whether . is to be searched.
12381 * And it is even smaller this way, making it unconditional for now:
12383 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12388 while ((fullname = path_advance(&path, name)) != NULL) {
12390 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12392 * Don't bother freeing here, since it will
12393 * be freed by the caller.
12397 if (fullname != name)
12398 stunalloc(fullname);
12401 /* not found in the PATH */
12402 ash_msg_and_raise_error("%s: not found", name);
12406 static int FAST_FUNC
12407 dotcmd(int argc, char **argv)
12410 struct strlist *sp;
12411 volatile struct shparam saveparam;
12413 for (sp = cmdenviron; sp; sp = sp->next)
12414 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12417 /* bash says: "bash: .: filename argument required" */
12418 return 2; /* bash compat */
12421 /* "false; . empty_file; echo $?" should print 0, not 1: */
12424 /* This aborts if file isn't found, which is POSIXly correct.
12425 * bash returns exitcode 1 instead.
12427 fullname = find_dot_file(argv[1]);
12430 if (argc) { /* argc > 0, argv[0] != NULL */
12431 saveparam = shellparam;
12432 shellparam.malloced = 0;
12433 shellparam.nparam = argc;
12434 shellparam.p = argv;
12437 /* This aborts if file can't be opened, which is POSIXly correct.
12438 * bash returns exitcode 1 instead.
12440 setinputfile(fullname, INPUT_PUSH_FILE);
12441 commandname = fullname;
12446 freeparam(&shellparam);
12447 shellparam = saveparam;
12453 static int FAST_FUNC
12454 exitcmd(int argc UNUSED_PARAM, char **argv)
12459 exitstatus = number(argv[1]);
12460 raise_exception(EXEXIT);
12465 * Read a file containing shell functions.
12468 readcmdfile(char *name)
12470 setinputfile(name, INPUT_PUSH_FILE);
12476 /* ============ find_command inplementation */
12479 * Resolve a command name. If you change this routine, you may have to
12480 * change the shellexec routine as well.
12483 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12485 struct tblentry *cmdp;
12492 struct builtincmd *bcmd;
12494 /* If name contains a slash, don't use PATH or hash table */
12495 if (strchr(name, '/') != NULL) {
12496 entry->u.index = -1;
12497 if (act & DO_ABS) {
12498 while (stat(name, &statb) < 0) {
12500 if (errno == EINTR)
12503 entry->cmdtype = CMDUNKNOWN;
12507 entry->cmdtype = CMDNORMAL;
12511 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12513 updatetbl = (path == pathval());
12516 if (strstr(path, "%builtin") != NULL)
12517 act |= DO_ALTBLTIN;
12520 /* If name is in the table, check answer will be ok */
12521 cmdp = cmdlookup(name, 0);
12522 if (cmdp != NULL) {
12525 switch (cmdp->cmdtype) {
12543 } else if (cmdp->rehash == 0)
12544 /* if not invalidated by cd, we're done */
12548 /* If %builtin not in path, check for builtin next */
12549 bcmd = find_builtin(name);
12551 if (IS_BUILTIN_REGULAR(bcmd))
12552 goto builtin_success;
12553 if (act & DO_ALTPATH) {
12554 if (!(act & DO_ALTBLTIN))
12555 goto builtin_success;
12556 } else if (builtinloc <= 0) {
12557 goto builtin_success;
12561 #if ENABLE_FEATURE_SH_STANDALONE
12563 int applet_no = find_applet_by_name(name);
12564 if (applet_no >= 0) {
12565 entry->cmdtype = CMDNORMAL;
12566 entry->u.index = -2 - applet_no;
12572 /* We have to search path. */
12573 prev = -1; /* where to start */
12574 if (cmdp && cmdp->rehash) { /* doing a rehash */
12575 if (cmdp->cmdtype == CMDBUILTIN)
12578 prev = cmdp->param.index;
12584 while ((fullname = path_advance(&path, name)) != NULL) {
12585 stunalloc(fullname);
12586 /* NB: code below will still use fullname
12587 * despite it being "unallocated" */
12590 if (prefix(pathopt, "builtin")) {
12592 goto builtin_success;
12595 if ((act & DO_NOFUNC)
12596 || !prefix(pathopt, "func")
12597 ) { /* ignore unimplemented options */
12601 /* if rehash, don't redo absolute path names */
12602 if (fullname[0] == '/' && idx <= prev) {
12605 TRACE(("searchexec \"%s\": no change\n", name));
12608 while (stat(fullname, &statb) < 0) {
12610 if (errno == EINTR)
12613 if (errno != ENOENT && errno != ENOTDIR)
12617 e = EACCES; /* if we fail, this will be the error */
12618 if (!S_ISREG(statb.st_mode))
12620 if (pathopt) { /* this is a %func directory */
12621 stalloc(strlen(fullname) + 1);
12622 /* NB: stalloc will return space pointed by fullname
12623 * (because we don't have any intervening allocations
12624 * between stunalloc above and this stalloc) */
12625 readcmdfile(fullname);
12626 cmdp = cmdlookup(name, 0);
12627 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12628 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12629 stunalloc(fullname);
12632 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12634 entry->cmdtype = CMDNORMAL;
12635 entry->u.index = idx;
12639 cmdp = cmdlookup(name, 1);
12640 cmdp->cmdtype = CMDNORMAL;
12641 cmdp->param.index = idx;
12646 /* We failed. If there was an entry for this command, delete it */
12647 if (cmdp && updatetbl)
12648 delete_cmd_entry();
12650 ash_msg("%s: %s", name, errmsg(e, "not found"));
12651 entry->cmdtype = CMDUNKNOWN;
12656 entry->cmdtype = CMDBUILTIN;
12657 entry->u.cmd = bcmd;
12661 cmdp = cmdlookup(name, 1);
12662 cmdp->cmdtype = CMDBUILTIN;
12663 cmdp->param.cmd = bcmd;
12667 entry->cmdtype = cmdp->cmdtype;
12668 entry->u = cmdp->param;
12672 /* ============ trap.c */
12675 * The trap builtin.
12677 static int FAST_FUNC
12678 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12682 int signo, exitcode;
12687 for (signo = 0; signo < NSIG; signo++) {
12688 char *tr = trap_ptr[signo];
12690 /* note: bash adds "SIG", but only if invoked
12691 * as "bash". If called as "sh", or if set -o posix,
12692 * then it prints short signal names.
12693 * We are printing short names: */
12694 out1fmt("trap -- %s %s\n",
12696 get_signame(signo));
12697 /* trap_ptr != trap only if we are in special-cased `trap` code.
12698 * In this case, we will exit very soon, no need to free(). */
12699 /* if (trap_ptr != trap && tp[0]) */
12704 if (trap_ptr != trap) {
12717 signo = get_signum(*ap);
12719 /* Mimic bash message exactly */
12720 ash_msg("%s: invalid signal specification", *ap);
12726 if (LONE_DASH(action))
12729 action = ckstrdup(action);
12733 may_have_traps = 1;
12734 trap[signo] = action;
12745 /* ============ Builtins */
12747 #if ENABLE_ASH_HELP
12748 static int FAST_FUNC
12749 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12755 "Built-in commands:\n"
12756 "------------------\n");
12757 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12758 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12759 builtintab[i].name + 1);
12765 # if ENABLE_FEATURE_SH_STANDALONE
12767 const char *a = applet_names;
12769 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12774 while (*a++ != '\0')
12780 return EXIT_SUCCESS;
12785 static int FAST_FUNC
12786 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12788 show_history(line_input_state);
12789 return EXIT_SUCCESS;
12794 * The export and readonly commands.
12796 static int FAST_FUNC
12797 exportcmd(int argc UNUSED_PARAM, char **argv)
12807 /* "readonly" in bash accepts, but ignores -n.
12808 * We do the same: it saves a conditional in nextopt's param.
12811 while ((opt = nextopt("np")) != '\0') {
12813 flag_off = VEXPORT;
12816 if (argv[0][0] == 'r') {
12818 flag_off = 0; /* readonly ignores -n */
12820 flag_off = ~flag_off;
12822 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12828 p = strchr(name, '=');
12832 vp = *findvar(hashvar(name), name);
12834 vp->flags = ((vp->flags | flag) & flag_off);
12838 setvar(name, p, (flag & flag_off));
12839 } while ((name = *++aptr) != NULL);
12844 /* No arguments. Show the list of exported or readonly vars.
12847 showvars(argv[0], flag, 0);
12852 * Delete a function if it exists.
12855 unsetfunc(const char *name)
12857 struct tblentry *cmdp;
12859 cmdp = cmdlookup(name, 0);
12860 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12861 delete_cmd_entry();
12865 * The unset builtin command. We unset the function before we unset the
12866 * variable to allow a function to be unset when there is a readonly variable
12867 * with the same name.
12869 static int FAST_FUNC
12870 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12877 while ((i = nextopt("vf")) != 0) {
12881 for (ap = argptr; *ap; ap++) {
12894 static const unsigned char timescmd_str[] ALIGN1 = {
12895 ' ', offsetof(struct tms, tms_utime),
12896 '\n', offsetof(struct tms, tms_stime),
12897 ' ', offsetof(struct tms, tms_cutime),
12898 '\n', offsetof(struct tms, tms_cstime),
12901 static int FAST_FUNC
12902 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12904 unsigned long clk_tck, s, t;
12905 const unsigned char *p;
12908 clk_tck = bb_clk_tck();
12913 t = *(clock_t *)(((char *) &buf) + p[1]);
12916 out1fmt("%lum%lu.%03lus%c",
12918 (t * 1000) / clk_tck,
12926 #if ENABLE_SH_MATH_SUPPORT
12928 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12929 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12931 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12933 static int FAST_FUNC
12934 letcmd(int argc UNUSED_PARAM, char **argv)
12940 ash_msg_and_raise_error("expression expected");
12942 i = ash_arith(*argv);
12950 * The read builtin. Options:
12951 * -r Do not interpret '\' specially
12952 * -s Turn off echo (tty only)
12953 * -n NCHARS Read NCHARS max
12954 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12955 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12956 * -u FD Read from given FD instead of fd 0
12957 * This uses unbuffered input, which may be avoidable in some cases.
12958 * TODO: bash also has:
12959 * -a ARRAY Read into array[0],[1],etc
12960 * -d DELIM End on DELIM char, not newline
12961 * -e Use line editing (tty only)
12963 static int FAST_FUNC
12964 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12966 char *opt_n = NULL;
12967 char *opt_p = NULL;
12968 char *opt_t = NULL;
12969 char *opt_u = NULL;
12970 int read_flags = 0;
12974 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12983 read_flags |= BUILTIN_READ_SILENT;
12989 read_flags |= BUILTIN_READ_RAW;
12999 /* "read -s" needs to save/restore termios, can't allow ^C
13000 * to jump out of it.
13003 r = shell_builtin_read(setvar0,
13005 bltinlookup("IFS"), /* can be NULL */
13014 if ((uintptr_t)r > 1)
13015 ash_msg_and_raise_error(r);
13017 return (uintptr_t)r;
13020 static int FAST_FUNC
13021 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13023 static const char permuser[3] ALIGN1 = "ogu";
13026 int symbolic_mode = 0;
13028 while (nextopt("S") != '\0') {
13037 if (*argptr == NULL) {
13038 if (symbolic_mode) {
13039 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13046 *p++ = permuser[i];
13048 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13049 if (!(mask & 0400)) *p++ = 'r';
13050 if (!(mask & 0200)) *p++ = 'w';
13051 if (!(mask & 0100)) *p++ = 'x';
13059 out1fmt("%04o\n", mask);
13062 char *modestr = *argptr;
13063 /* numeric umasks are taken as-is */
13064 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13065 if (!isdigit(modestr[0]))
13067 mask = bb_parse_mode(modestr, mask);
13068 if ((unsigned)mask > 0777) {
13069 ash_msg_and_raise_error("illegal mode: %s", modestr);
13071 if (!isdigit(modestr[0]))
13078 static int FAST_FUNC
13079 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13081 return shell_builtin_ulimit(argv);
13084 /* ============ main() and helpers */
13087 * Called to exit the shell.
13096 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13097 save_history(line_input_state);
13100 status = exitstatus;
13101 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13102 if (setjmp(loc.loc)) {
13103 if (exception_type == EXEXIT)
13104 /* dash bug: it just does _exit(exitstatus) here
13105 * but we have to do setjobctl(0) first!
13106 * (bug is still not fixed in dash-0.5.3 - if you run dash
13107 * under Midnight Commander, on exit from dash MC is backgrounded) */
13108 status = exitstatus;
13111 exception_handler = &loc;
13118 flush_stdout_stderr();
13128 /* from input.c: */
13129 /* we will never free this */
13130 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13133 signal(SIGCHLD, SIG_DFL);
13134 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13135 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13137 signal(SIGHUP, SIG_DFL);
13143 struct stat st1, st2;
13146 for (envp = environ; envp && *envp; envp++) {
13147 p = endofname(*envp);
13148 if (p != *envp && *p == '=') {
13149 setvareq(*envp, VEXPORT|VTEXTFIXED);
13153 setvareq((char*)defoptindvar, VTEXTFIXED);
13155 setvar0("PPID", utoa(getppid()));
13156 #if ENABLE_ASH_BASH_COMPAT
13157 p = lookupvar("SHLVL");
13158 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13159 if (!lookupvar("HOSTNAME")) {
13160 struct utsname uts;
13162 setvar0("HOSTNAME", uts.nodename);
13165 p = lookupvar("PWD");
13167 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13168 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13178 //usage:#define ash_trivial_usage
13179 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13180 //usage:#define ash_full_usage "\n\n"
13181 //usage: "Unix shell interpreter"
13183 //usage:#if ENABLE_FEATURE_SH_IS_ASH
13184 //usage:# define sh_trivial_usage ash_trivial_usage
13185 //usage:# define sh_full_usage ash_full_usage
13187 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
13188 //usage:# define bash_trivial_usage ash_trivial_usage
13189 //usage:# define bash_full_usage ash_full_usage
13193 * Process the shell command line arguments.
13196 procargs(char **argv)
13199 const char *xminusc;
13204 /* if (xargv[0]) - mmm, this is always true! */
13206 for (i = 0; i < NOPTS; i++)
13209 if (options(/*cmdline:*/ 1)) {
13210 /* it already printed err message */
13211 raise_exception(EXERROR);
13215 if (*xargv == NULL) {
13217 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13220 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13224 for (i = 0; i < NOPTS; i++)
13225 if (optlist[i] == 2)
13230 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13235 } else if (!sflag) {
13236 setinputfile(*xargv, 0);
13239 commandname = arg0;
13242 shellparam.p = xargv;
13243 #if ENABLE_ASH_GETOPTS
13244 shellparam.optind = 1;
13245 shellparam.optoff = -1;
13247 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13249 shellparam.nparam++;
13256 * Read /etc/profile or .profile.
13259 read_profile(const char *name)
13263 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13272 * This routine is called when an error or an interrupt occurs in an
13273 * interactive shell and control is returned to the main command loop.
13281 /* from input.c: */
13282 g_parsefile->left_in_buffer = 0;
13283 g_parsefile->left_in_line = 0; /* clear input buffer */
13285 /* from parser.c: */
13288 /* from redir.c: */
13289 clearredir(/*drop:*/ 0);
13293 static short profile_buf[16384];
13294 extern int etext();
13298 * Main routine. We initialize things, parse the arguments, execute
13299 * profiles if we're a login shell, and then call cmdloop to execute
13300 * commands. The setjmp call sets up the location to jump to when an
13301 * exception occurs. When an exception occurs the variable "state"
13302 * is used to figure out how far we had gotten.
13304 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13305 int ash_main(int argc UNUSED_PARAM, char **argv)
13307 const char *shinit;
13308 volatile smallint state;
13309 struct jmploc jmploc;
13310 struct stackmark smark;
13312 /* Initialize global data */
13316 #if ENABLE_ASH_ALIAS
13322 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13325 #if ENABLE_FEATURE_EDITING
13326 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13329 if (setjmp(jmploc.loc)) {
13335 e = exception_type;
13339 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13343 newline_and_flush(stderr);
13346 popstackmark(&smark);
13347 FORCE_INT_ON; /* enable interrupts */
13356 exception_handler = &jmploc;
13359 TRACE(("Shell args: "));
13360 trace_puts_args(argv);
13362 rootpid = getpid();
13365 setstackmark(&smark);
13368 if (argv[0] && argv[0][0] == '-')
13374 read_profile("/etc/profile");
13377 hp = lookupvar("HOME");
13379 hp = concat_path_file(hp, ".profile");
13388 getuid() == geteuid() && getgid() == getegid() &&
13392 shinit = lookupvar("ENV");
13393 if (shinit != NULL && *shinit != '\0') {
13394 read_profile(shinit);
13400 /* evalstring pushes parsefile stack.
13401 * Ensure we don't falsely claim that 0 (stdin)
13402 * is one of stacked source fds.
13403 * Testcase: ash -c 'exec 1>&0' must not complain. */
13404 // if (!sflag) g_parsefile->pf_fd = -1;
13405 // ^^ not necessary since now we special-case fd 0
13406 // in is_hidden_fd() to not be considered "hidden fd"
13407 evalstring(minusc, 0);
13410 if (sflag || minusc == NULL) {
13411 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13413 const char *hp = lookupvar("HISTFILE");
13415 hp = lookupvar("HOME");
13417 hp = concat_path_file(hp, ".ash_history");
13418 setvar0("HISTFILE", hp);
13420 hp = lookupvar("HISTFILE");
13424 line_input_state->hist_file = hp;
13425 # if ENABLE_FEATURE_SH_HISTFILESIZE
13426 hp = lookupvar("HISTFILESIZE");
13427 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13431 state4: /* XXX ??? - why isn't this before the "if" statement */
13439 extern void _mcleanup(void);
13443 TRACE(("End of main reached\n"));
13450 * Copyright (c) 1989, 1991, 1993, 1994
13451 * The Regents of the University of California. All rights reserved.
13453 * This code is derived from software contributed to Berkeley by
13454 * Kenneth Almquist.
13456 * Redistribution and use in source and binary forms, with or without
13457 * modification, are permitted provided that the following conditions
13459 * 1. Redistributions of source code must retain the above copyright
13460 * notice, this list of conditions and the following disclaimer.
13461 * 2. Redistributions in binary form must reproduce the above copyright
13462 * notice, this list of conditions and the following disclaimer in the
13463 * documentation and/or other materials provided with the distribution.
13464 * 3. Neither the name of the University nor the names of its contributors
13465 * may be used to endorse or promote products derived from this software
13466 * without specific prior written permission.
13468 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13469 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13470 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13471 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13472 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13473 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13474 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13475 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13476 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13477 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF