1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
20 * The following should be set to reflect the type of system you have:
21 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22 * define SYSV if you are running under System V.
23 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24 * define DEBUG=2 to compile in and turn on debugging.
26 * When debugging is on (DEBUG is 1 and "set -o debug" was executed),
27 * debugging info will be written to ./trace and a quit signal
28 * will generate a core dump.
31 /* Tweak debug output verbosity here */
38 #define JOBS ENABLE_ASH_JOB_CONTROL
42 #include <sys/times.h>
43 #include <sys/utsname.h> /* for setting $HOSTNAME */
45 #include "busybox.h" /* for applet_names */
47 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
48 /* Bionic at least up to version 24 has no glob() */
49 # undef ENABLE_ASH_INTERNAL_GLOB
50 # define ENABLE_ASH_INTERNAL_GLOB 1
53 #if !ENABLE_ASH_INTERNAL_GLOB
58 #include "shell_common.h"
59 #if ENABLE_SH_MATH_SUPPORT
62 #if ENABLE_ASH_RANDOM_SUPPORT
65 # define CLEAR_RANDOM_T(rnd) ((void)0)
68 #include "NUM_APPLETS.h"
70 /* STANDALONE does not make sense, and won't compile */
71 # undef CONFIG_FEATURE_SH_STANDALONE
72 # undef ENABLE_FEATURE_SH_STANDALONE
73 # undef IF_FEATURE_SH_STANDALONE
74 # undef IF_NOT_FEATURE_SH_STANDALONE
75 # define ENABLE_FEATURE_SH_STANDALONE 0
76 # define IF_FEATURE_SH_STANDALONE(...)
77 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
81 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
85 # error "Do not even bother, ash will not run on NOMMU machine"
91 //config: depends on !NOMMU
93 //config: Tha 'ash' shell adds about 60k in the default configuration and is
94 //config: the most complete and most pedantically correct shell included with
95 //config: busybox. This shell is actually a derivative of the Debian 'dash'
96 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
97 //config: (written by Kenneth Almquist) from NetBSD.
99 //config:config ASH_OPTIMIZE_FOR_SIZE
100 //config: bool "Optimize for size instead of speed"
102 //config: depends on ASH
104 //config: Compile ash for reduced size at the price of speed.
106 //config:config ASH_INTERNAL_GLOB
107 //config: bool "Use internal glob() implementation"
109 //config: depends on ASH
111 //config: Do not use glob() function from libc, use internal implementation.
112 //config: Use this if you are getting "glob.h: No such file or directory"
113 //config: or similar build errors.
115 //config:config ASH_RANDOM_SUPPORT
116 //config: bool "Pseudorandom generator and $RANDOM variable"
118 //config: depends on ASH
120 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
121 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
122 //config: You can reset the generator by using a specified start value.
123 //config: After "unset RANDOM" the generator will switch off and this
124 //config: variable will no longer have special treatment.
126 //config:config ASH_EXPAND_PRMT
127 //config: bool "Expand prompt string"
129 //config: depends on ASH
131 //config: "PS#" may contain volatile content, such as backquote commands.
132 //config: This option recreates the prompt string from the environment
133 //config: variable each time it is displayed.
135 //config:config ASH_BASH_COMPAT
136 //config: bool "bash-compatible extensions"
138 //config: depends on ASH
140 //config: Enable bash-compatible extensions.
142 //config:config ASH_IDLE_TIMEOUT
143 //config: bool "Idle timeout variable"
145 //config: depends on ASH
147 //config: Enables bash-like auto-logout after $TMOUT seconds of idle time.
149 //config:config ASH_JOB_CONTROL
150 //config: bool "Job control"
152 //config: depends on ASH
154 //config: Enable job control in the ash shell.
156 //config:config ASH_ALIAS
157 //config: bool "Alias support"
159 //config: depends on ASH
161 //config: Enable alias support in the ash shell.
163 //config:config ASH_GETOPTS
164 //config: bool "Builtin getopt to parse positional parameters"
166 //config: depends on ASH
168 //config: Enable support for getopts builtin in ash.
170 //config:config ASH_BUILTIN_ECHO
171 //config: bool "Builtin version of 'echo'"
173 //config: depends on ASH
175 //config: Enable support for echo builtin in ash.
177 //config:config ASH_BUILTIN_PRINTF
178 //config: bool "Builtin version of 'printf'"
180 //config: depends on ASH
182 //config: Enable support for printf builtin in ash.
184 //config:config ASH_BUILTIN_TEST
185 //config: bool "Builtin version of 'test'"
187 //config: depends on ASH
189 //config: Enable support for test builtin in ash.
191 //config:config ASH_HELP
192 //config: bool "help builtin"
194 //config: depends on ASH
196 //config: Enable help builtin in ash.
198 //config:config ASH_CMDCMD
199 //config: bool "'command' command to override shell builtins"
201 //config: depends on ASH
203 //config: Enable support for the ash 'command' builtin, which allows
204 //config: you to run the specified command with the specified arguments,
205 //config: even when there is an ash builtin command with the same name.
207 //config:config ASH_MAIL
208 //config: bool "Check for new mail on interactive shells"
210 //config: depends on ASH
212 //config: Enable "check for new mail" function in the ash shell.
215 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
216 //applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, sh))
217 //applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, bash))
219 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
220 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
223 /* ============ Hash table sizes. Configurable. */
227 #define CMDTABLESIZE 31 /* should be prime */
230 /* ============ Shell options */
232 static const char *const optletters_optnames[] = {
247 #if ENABLE_ASH_BASH_COMPAT
256 #define optletters(n) optletters_optnames[n][0]
257 #define optnames(n) (optletters_optnames[n] + 1)
259 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
262 /* ============ Misc data */
264 #define msg_illnum "Illegal number: %s"
267 * We enclose jmp_buf in a structure so that we can declare pointers to
268 * jump locations. The global variable handler contains the location to
269 * jump to when an exception occurs, and the global variable exception_type
270 * contains a code identifying the exception. To implement nested
271 * exception handlers, the user should save the value of handler on entry
272 * to an inner scope, set handler to point to a jmploc structure for the
273 * inner scope, and restore handler on exit from the scope.
279 struct globals_misc {
280 /* 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 flags);
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));
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 **, int);
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 **, int) 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" , NULL }, /*evalcmd() has a differing prototype*/
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, flags)) {
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, int flags)
9617 char *volatile savecmdname;
9618 struct jmploc *volatile savehandler;
9619 struct jmploc jmploc;
9623 savecmdname = commandname;
9624 savehandler = exception_handler;
9625 i = setjmp(jmploc.loc);
9628 exception_handler = &jmploc;
9629 commandname = argv[0];
9631 optptr = NULL; /* initialize nextopt */
9633 status = evalcmd(argc, argv, flags);
9635 status = (*cmd->builtin)(argc, argv);
9636 flush_stdout_stderr();
9637 status |= ferror(stdout);
9638 exitstatus = status;
9641 commandname = savecmdname;
9642 exception_handler = savehandler;
9648 goodname(const char *p)
9650 return endofname(p)[0] == '\0';
9655 * Search for a command. This is called before we fork so that the
9656 * location of the command will be available in the parent as well as
9657 * the child. The check for "goodname" is an overly conservative
9658 * check that the name will not be subject to expansion.
9661 prehash(union node *n)
9663 struct cmdentry entry;
9665 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9666 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9670 /* ============ Builtin commands
9672 * Builtin commands whose functions are closely tied to evaluation
9673 * are implemented here.
9677 * Handle break and continue commands. Break, continue, and return are
9678 * all handled by setting the evalskip flag. The evaluation routines
9679 * above all check this flag, and if it is set they start skipping
9680 * commands rather than executing them. The variable skipcount is
9681 * the number of loops to break/continue, or the number of function
9682 * levels to return. (The latter is always 1.) It should probably
9683 * be an error to break out of more loops than exist, but it isn't
9684 * in the standard shell so we don't make it one here.
9686 static int FAST_FUNC
9687 breakcmd(int argc UNUSED_PARAM, char **argv)
9689 int n = argv[1] ? number(argv[1]) : 1;
9692 ash_msg_and_raise_error(msg_illnum, argv[1]);
9696 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9703 /* ============ input.c
9705 * This implements the input routines used by the parser.
9709 INPUT_PUSH_FILE = 1,
9710 INPUT_NOFILE_OK = 2,
9713 static smallint checkkwd;
9714 /* values of checkkwd variable */
9715 #define CHKALIAS 0x1
9720 * Push a string back onto the input at this current parsefile level.
9721 * We handle aliases this way.
9723 #if !ENABLE_ASH_ALIAS
9724 #define pushstring(s, ap) pushstring(s)
9727 pushstring(char *s, struct alias *ap)
9734 if (g_parsefile->strpush) {
9735 sp = ckzalloc(sizeof(*sp));
9736 sp->prev = g_parsefile->strpush;
9738 sp = &(g_parsefile->basestrpush);
9740 g_parsefile->strpush = sp;
9741 sp->prev_string = g_parsefile->next_to_pgetc;
9742 sp->prev_left_in_line = g_parsefile->left_in_line;
9743 sp->unget = g_parsefile->unget;
9744 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9745 #if ENABLE_ASH_ALIAS
9748 ap->flag |= ALIASINUSE;
9752 g_parsefile->next_to_pgetc = s;
9753 g_parsefile->left_in_line = len;
9754 g_parsefile->unget = 0;
9761 struct strpush *sp = g_parsefile->strpush;
9764 #if ENABLE_ASH_ALIAS
9766 if (g_parsefile->next_to_pgetc[-1] == ' '
9767 || g_parsefile->next_to_pgetc[-1] == '\t'
9769 checkkwd |= CHKALIAS;
9771 if (sp->string != sp->ap->val) {
9774 sp->ap->flag &= ~ALIASINUSE;
9775 if (sp->ap->flag & ALIASDEAD) {
9776 unalias(sp->ap->name);
9780 g_parsefile->next_to_pgetc = sp->prev_string;
9781 g_parsefile->left_in_line = sp->prev_left_in_line;
9782 g_parsefile->unget = sp->unget;
9783 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
9784 g_parsefile->strpush = sp->prev;
9785 if (sp != &(g_parsefile->basestrpush))
9794 char *buf = g_parsefile->buf;
9796 g_parsefile->next_to_pgetc = buf;
9797 #if ENABLE_FEATURE_EDITING
9799 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9800 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9803 # if ENABLE_ASH_IDLE_TIMEOUT
9805 const char *tmout_var = lookupvar("TMOUT");
9807 timeout = atoi(tmout_var) * 1000;
9813 # if ENABLE_FEATURE_TAB_COMPLETION
9814 line_input_state->path_lookup = pathval();
9816 reinit_unicode_for_ash();
9817 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9819 /* Ctrl+C pressed */
9830 /* Ctrl+D pressed */
9833 # if ENABLE_ASH_IDLE_TIMEOUT
9834 else if (errno == EAGAIN && timeout > 0) {
9835 puts("\007timed out waiting for input: auto-logout");
9842 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9845 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9847 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9848 int flags = fcntl(0, F_GETFL);
9849 if (flags >= 0 && (flags & O_NONBLOCK)) {
9850 flags &= ~O_NONBLOCK;
9851 if (fcntl(0, F_SETFL, flags) >= 0) {
9852 out2str("sh: turning off NDELAY mode\n");
9863 * Refill the input buffer and return the next input character:
9865 * 1) If a string was pushed back on the input, pop it;
9866 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9867 * or we are reading from a string so we can't refill the buffer,
9869 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9870 * 4) Process input up to the next newline, deleting nul characters.
9872 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9873 #define pgetc_debug(...) ((void)0)
9874 static int pgetc(void);
9881 if (g_parsefile->strpush) {
9882 #if ENABLE_ASH_ALIAS
9883 if (g_parsefile->left_in_line == -1
9884 && g_parsefile->strpush->ap
9885 && g_parsefile->next_to_pgetc[-1] != ' '
9886 && g_parsefile->next_to_pgetc[-1] != '\t'
9888 pgetc_debug("preadbuffer PEOA");
9895 /* on both branches above g_parsefile->left_in_line < 0.
9896 * "pgetc" needs refilling.
9899 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9900 * pungetc() may increment it a few times.
9901 * Assuming it won't increment it to less than -90.
9903 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9904 pgetc_debug("preadbuffer PEOF1");
9905 /* even in failure keep left_in_line and next_to_pgetc
9906 * in lock step, for correct multi-layer pungetc.
9907 * left_in_line was decremented before preadbuffer(),
9908 * must inc next_to_pgetc: */
9909 g_parsefile->next_to_pgetc++;
9913 more = g_parsefile->left_in_buffer;
9915 flush_stdout_stderr();
9919 /* don't try reading again */
9920 g_parsefile->left_in_line = -99;
9921 pgetc_debug("preadbuffer PEOF2");
9922 g_parsefile->next_to_pgetc++;
9927 /* Find out where's the end of line.
9928 * Set g_parsefile->left_in_line
9929 * and g_parsefile->left_in_buffer acordingly.
9930 * NUL chars are deleted.
9932 q = g_parsefile->next_to_pgetc;
9940 memmove(q, q + 1, more);
9944 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9950 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9951 if (g_parsefile->left_in_line < 0)
9956 g_parsefile->left_in_buffer = more;
9961 out2str(g_parsefile->next_to_pgetc);
9965 pgetc_debug("preadbuffer at %d:%p'%s'",
9966 g_parsefile->left_in_line,
9967 g_parsefile->next_to_pgetc,
9968 g_parsefile->next_to_pgetc);
9969 return (unsigned char)*g_parsefile->next_to_pgetc++;
9977 pgetc_debug("pgetc at %d:%p'%s'",
9978 g_parsefile->left_in_line,
9979 g_parsefile->next_to_pgetc,
9980 g_parsefile->next_to_pgetc);
9981 if (g_parsefile->unget)
9982 return g_parsefile->lastc[--g_parsefile->unget];
9984 if (--g_parsefile->left_in_line >= 0)
9985 c = (signed char)*g_parsefile->next_to_pgetc++;
9989 g_parsefile->lastc[1] = g_parsefile->lastc[0];
9990 g_parsefile->lastc[0] = c;
9995 #if ENABLE_ASH_ALIAS
9997 pgetc_without_PEOA(void)
10001 pgetc_debug("pgetc at %d:%p'%s'",
10002 g_parsefile->left_in_line,
10003 g_parsefile->next_to_pgetc,
10004 g_parsefile->next_to_pgetc);
10006 } while (c == PEOA);
10010 # define pgetc_without_PEOA() pgetc()
10014 * Read a line from the script.
10017 pfgets(char *line, int len)
10023 while (--nleft > 0) {
10024 c = pgetc_without_PEOA();
10039 * Undo a call to pgetc. Only two characters may be pushed back.
10040 * PEOF may be pushed back.
10045 g_parsefile->unget++;
10048 /* This one eats backslash+newline */
10054 while ((c = pgetc()) == '\\') {
10055 if (pgetc() != '\n') {
10060 g_parsefile->linno++;
10061 setprompt_if(doprompt, 2);
10068 * To handle the "." command, a stack of input files is used. Pushfile
10069 * adds a new entry to the stack and popfile restores the previous level.
10074 struct parsefile *pf;
10076 pf = ckzalloc(sizeof(*pf));
10077 pf->prev = g_parsefile;
10079 /*pf->strpush = NULL; - ckzalloc did it */
10080 /*pf->basestrpush.prev = NULL;*/
10088 struct parsefile *pf = g_parsefile;
10091 if (pf->pf_fd >= 0)
10094 while (pf->strpush)
10096 g_parsefile = pf->prev;
10102 * Return to top level.
10107 while (g_parsefile != &basepf)
10112 * Close the file(s) that the shell is reading commands from. Called
10113 * after a fork is done.
10119 if (g_parsefile->pf_fd > 0) {
10120 close(g_parsefile->pf_fd);
10121 g_parsefile->pf_fd = 0;
10126 * Like setinputfile, but takes an open file descriptor. Call this with
10130 setinputfd(int fd, int push)
10132 close_on_exec_on(fd);
10135 g_parsefile->buf = NULL;
10137 g_parsefile->pf_fd = fd;
10138 if (g_parsefile->buf == NULL)
10139 g_parsefile->buf = ckmalloc(IBUFSIZ);
10140 g_parsefile->left_in_buffer = 0;
10141 g_parsefile->left_in_line = 0;
10142 g_parsefile->linno = 1;
10146 * Set the input to take input from a file. If push is set, push the
10147 * old input onto the stack first.
10150 setinputfile(const char *fname, int flags)
10156 fd = open(fname, O_RDONLY);
10158 if (flags & INPUT_NOFILE_OK)
10160 ash_msg_and_raise_error("can't open '%s'", fname);
10163 fd2 = copyfd(fd, 10);
10166 ash_msg_and_raise_error("out of file descriptors");
10169 setinputfd(fd, flags & INPUT_PUSH_FILE);
10176 * Like setinputfile, but takes input from a string.
10179 setinputstring(char *string)
10183 g_parsefile->next_to_pgetc = string;
10184 g_parsefile->left_in_line = strlen(string);
10185 g_parsefile->buf = NULL;
10186 g_parsefile->linno = 1;
10191 /* ============ mail.c
10193 * Routines to check for mail.
10196 #if ENABLE_ASH_MAIL
10198 /* Hash of mtimes of mailboxes */
10199 static unsigned mailtime_hash;
10200 /* Set if MAIL or MAILPATH is changed. */
10201 static smallint mail_var_path_changed;
10204 * Print appropriate message(s) if mail has arrived.
10205 * If mail_var_path_changed is set,
10206 * then the value of MAIL has mail_var_path_changed,
10207 * so we just update the values.
10216 struct stackmark smark;
10219 setstackmark(&smark);
10220 mpath = mpathset() ? mpathval() : mailval();
10223 p = path_advance(&mpath, nullstr);
10228 for (q = p; *q; q++)
10234 q[-1] = '\0'; /* delete trailing '/' */
10235 if (stat(p, &statb) < 0) {
10238 /* Very simplistic "hash": just a sum of all mtimes */
10239 new_hash += (unsigned)statb.st_mtime;
10241 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10242 if (mailtime_hash != 0)
10243 out2str("you have mail\n");
10244 mailtime_hash = new_hash;
10246 mail_var_path_changed = 0;
10247 popstackmark(&smark);
10250 static void FAST_FUNC
10251 changemail(const char *val UNUSED_PARAM)
10253 mail_var_path_changed = 1;
10256 #endif /* ASH_MAIL */
10259 /* ============ ??? */
10262 * Set the shell parameters.
10265 setparam(char **argv)
10271 for (nparam = 0; argv[nparam]; nparam++)
10273 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10275 *ap++ = ckstrdup(*argv++);
10278 freeparam(&shellparam);
10279 shellparam.malloced = 1;
10280 shellparam.nparam = nparam;
10281 shellparam.p = newparam;
10282 #if ENABLE_ASH_GETOPTS
10283 shellparam.optind = 1;
10284 shellparam.optoff = -1;
10289 * Process shell options. The global variable argptr contains a pointer
10290 * to the argument list; we advance it past the options.
10292 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10293 * For a non-interactive shell, an error condition encountered
10294 * by a special built-in ... shall cause the shell to write a diagnostic message
10295 * to standard error and exit as shown in the following table:
10296 * Error Special Built-In
10298 * Utility syntax error (option or operand error) Shall exit
10300 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10301 * we see that bash does not do that (set "finishes" with error code 1 instead,
10302 * and shell continues), and people rely on this behavior!
10304 * set -o barfoo 2>/dev/null
10307 * Oh well. Let's mimic that.
10310 plus_minus_o(char *name, int val)
10315 for (i = 0; i < NOPTS; i++) {
10316 if (strcmp(name, optnames(i)) == 0) {
10321 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10324 for (i = 0; i < NOPTS; i++) {
10326 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10328 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10334 setoption(int flag, int val)
10338 for (i = 0; i < NOPTS; i++) {
10339 if (optletters(i) == flag) {
10344 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10348 options(int cmdline)
10356 while ((p = *argptr) != NULL) {
10358 if (c != '-' && c != '+')
10361 val = 0; /* val = 0 if c == '+' */
10364 if (p[0] == '\0' || LONE_DASH(p)) {
10366 /* "-" means turn off -x and -v */
10369 /* "--" means reset params */
10370 else if (*argptr == NULL)
10373 break; /* "-" or "--" terminates options */
10376 /* first char was + or - */
10377 while ((c = *p++) != '\0') {
10378 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10379 if (c == 'c' && cmdline) {
10380 minusc = p; /* command is after shell args */
10381 } else if (c == 'o') {
10382 if (plus_minus_o(*argptr, val)) {
10383 /* it already printed err message */
10384 return 1; /* error */
10388 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10390 /* bash does not accept +-login, we also won't */
10391 } else if (cmdline && val && (c == '-')) { /* long options */
10392 if (strcmp(p, "login") == 0)
10404 * The shift builtin command.
10406 static int FAST_FUNC
10407 shiftcmd(int argc UNUSED_PARAM, char **argv)
10414 n = number(argv[1]);
10415 if (n > shellparam.nparam)
10416 n = 0; /* bash compat, was = shellparam.nparam; */
10418 shellparam.nparam -= n;
10419 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10420 if (shellparam.malloced)
10423 ap2 = shellparam.p;
10424 while ((*ap2++ = *ap1++) != NULL)
10426 #if ENABLE_ASH_GETOPTS
10427 shellparam.optind = 1;
10428 shellparam.optoff = -1;
10435 * POSIX requires that 'set' (but not export or readonly) output the
10436 * variables in lexicographic order - by the locale's collating order (sigh).
10437 * Maybe we could keep them in an ordered balanced binary tree
10438 * instead of hashed lists.
10439 * For now just roll 'em through qsort for printing...
10442 showvars(const char *sep_prefix, int on, int off)
10445 char **ep, **epend;
10447 ep = listvars(on, off, &epend);
10448 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10450 sep = *sep_prefix ? " " : sep_prefix;
10452 for (; ep < epend; ep++) {
10456 p = strchrnul(*ep, '=');
10459 q = single_quote(++p);
10460 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10466 * The set command builtin.
10468 static int FAST_FUNC
10469 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10474 return showvars(nullstr, 0, VUNSET);
10477 retval = options(/*cmdline:*/ 0);
10478 if (retval == 0) { /* if no parse error... */
10480 if (*argptr != NULL) {
10488 #if ENABLE_ASH_RANDOM_SUPPORT
10489 static void FAST_FUNC
10490 change_random(const char *value)
10494 if (value == NULL) {
10495 /* "get", generate */
10496 t = next_random(&random_gen);
10497 /* set without recursion */
10498 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10499 vrandom.flags &= ~VNOFUNC;
10502 t = strtoul(value, NULL, 10);
10503 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10508 #if ENABLE_ASH_GETOPTS
10510 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10521 if (*param_optind < 1)
10523 optnext = optfirst + *param_optind - 1;
10525 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10528 p = optnext[-1] + *optoff;
10529 if (p == NULL || *p == '\0') {
10530 /* Current word is done, advance */
10532 if (p == NULL || *p != '-' || *++p == '\0') {
10539 if (LONE_DASH(p)) /* check for "--" */
10544 for (q = optstr; *q != c;) {
10546 if (optstr[0] == ':') {
10548 /*sbuf[1] = '\0'; - already is */
10549 err |= setvarsafe("OPTARG", sbuf, 0);
10551 fprintf(stderr, "Illegal option -%c\n", c);
10552 unsetvar("OPTARG");
10562 if (*p == '\0' && (p = *optnext) == NULL) {
10563 if (optstr[0] == ':') {
10565 /*sbuf[1] = '\0'; - already is */
10566 err |= setvarsafe("OPTARG", sbuf, 0);
10569 fprintf(stderr, "No arg for -%c option\n", c);
10570 unsetvar("OPTARG");
10578 err |= setvarsafe("OPTARG", p, 0);
10581 err |= setvarsafe("OPTARG", nullstr, 0);
10583 *optoff = p ? p - *(optnext - 1) : -1;
10584 *param_optind = optnext - optfirst + 1;
10585 err |= setvarsafe("OPTIND", itoa(*param_optind), VNOFUNC);
10587 /*sbuf[1] = '\0'; - already is */
10588 err |= setvarsafe(optvar, sbuf, 0);
10592 flush_stdout_stderr();
10593 raise_exception(EXERROR);
10599 * The getopts builtin. Shellparam.optnext points to the next argument
10600 * to be processed. Shellparam.optptr points to the next character to
10601 * be processed in the current argument. If shellparam.optnext is NULL,
10602 * then it's the first time getopts has been called.
10604 static int FAST_FUNC
10605 getoptscmd(int argc, char **argv)
10610 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10612 optbase = shellparam.p;
10613 if (shellparam.optind > shellparam.nparam + 1) {
10614 shellparam.optind = 1;
10615 shellparam.optoff = -1;
10618 optbase = &argv[3];
10619 if (shellparam.optind > argc - 2) {
10620 shellparam.optind = 1;
10621 shellparam.optoff = -1;
10625 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10626 &shellparam.optoff);
10628 #endif /* ASH_GETOPTS */
10631 /* ============ Shell parser */
10634 struct heredoc *next; /* next here document in list */
10635 union node *here; /* redirection node */
10636 char *eofmark; /* string indicating end of input */
10637 smallint striptabs; /* if set, strip leading tabs */
10640 static smallint tokpushback; /* last token pushed back */
10641 static smallint quoteflag; /* set if (part of) last token was quoted */
10642 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10643 static struct heredoc *heredoclist; /* list of here documents to read */
10644 static char *wordtext; /* text of last word returned by readtoken */
10645 static struct nodelist *backquotelist;
10646 static union node *redirnode;
10647 static struct heredoc *heredoc;
10649 static const char *
10650 tokname(char *buf, int tok)
10653 return tokname_array[tok] + 1;
10654 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10658 /* raise_error_unexpected_syntax:
10659 * Called when an unexpected token is read during the parse. The argument
10660 * is the token that is expected, or -1 if more than one type of token can
10661 * occur at this point.
10663 static void raise_error_unexpected_syntax(int) NORETURN;
10665 raise_error_unexpected_syntax(int token)
10671 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10673 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10674 raise_error_syntax(msg);
10678 #define EOFMARKLEN 79
10680 /* parsing is heavily cross-recursive, need these forward decls */
10681 static union node *andor(void);
10682 static union node *pipeline(void);
10683 static union node *parse_command(void);
10684 static void parseheredoc(void);
10685 static int peektoken(void);
10686 static int readtoken(void);
10688 static union node *
10691 union node *n1, *n2, *n3;
10696 switch (peektoken()) {
10704 if (!n1 && (nlflag & 1))
10710 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10711 if (nlflag == 2 && tokname_array[peektoken()][0])
10717 if (tok == TBACKGND) {
10718 if (n2->type == NPIPE) {
10719 n2->npipe.pipe_backgnd = 1;
10721 if (n2->type != NREDIR) {
10722 n3 = stzalloc(sizeof(struct nredir));
10724 /*n3->nredir.redirect = NULL; - stzalloc did it */
10727 n2->type = NBACKGND;
10733 n3 = stzalloc(sizeof(struct nbinary));
10735 n3->nbinary.ch1 = n1;
10736 n3->nbinary.ch2 = n2;
10749 raise_error_unexpected_syntax(-1);
10756 static union node *
10759 union node *n1, *n2, *n3;
10767 } else if (t == TOR) {
10773 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10775 n3 = stzalloc(sizeof(struct nbinary));
10777 n3->nbinary.ch1 = n1;
10778 n3->nbinary.ch2 = n2;
10783 static union node *
10786 union node *n1, *n2, *pipenode;
10787 struct nodelist *lp, *prev;
10791 TRACE(("pipeline: entered\n"));
10792 if (readtoken() == TNOT) {
10794 checkkwd = CHKKWD | CHKALIAS;
10797 n1 = parse_command();
10798 if (readtoken() == TPIPE) {
10799 pipenode = stzalloc(sizeof(struct npipe));
10800 pipenode->type = NPIPE;
10801 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10802 lp = stzalloc(sizeof(struct nodelist));
10803 pipenode->npipe.cmdlist = lp;
10807 lp = stzalloc(sizeof(struct nodelist));
10808 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10809 lp->n = parse_command();
10811 } while (readtoken() == TPIPE);
10817 n2 = stzalloc(sizeof(struct nnot));
10825 static union node *
10830 n = stzalloc(sizeof(struct narg));
10832 /*n->narg.next = NULL; - stzalloc did it */
10833 n->narg.text = wordtext;
10834 n->narg.backquote = backquotelist;
10839 fixredir(union node *n, const char *text, int err)
10843 TRACE(("Fix redir %s %d\n", text, err));
10845 n->ndup.vname = NULL;
10847 fd = bb_strtou(text, NULL, 10);
10848 if (!errno && fd >= 0)
10849 n->ndup.dupfd = fd;
10850 else if (LONE_DASH(text))
10851 n->ndup.dupfd = -1;
10854 raise_error_syntax("bad fd number");
10855 n->ndup.vname = makename();
10860 * Returns true if the text contains nothing to expand (no dollar signs
10864 noexpand(const char *text)
10868 while ((c = *text++) != '\0') {
10869 if (c == CTLQUOTEMARK)
10873 else if (SIT(c, BASESYNTAX) == CCTL)
10882 union node *n = redirnode;
10884 if (readtoken() != TWORD)
10885 raise_error_unexpected_syntax(-1);
10886 if (n->type == NHERE) {
10887 struct heredoc *here = heredoc;
10891 if (quoteflag == 0)
10893 TRACE(("Here document %d\n", n->type));
10894 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10895 raise_error_syntax("illegal eof marker for << redirection");
10896 rmescapes(wordtext, 0);
10897 here->eofmark = wordtext;
10899 if (heredoclist == NULL)
10900 heredoclist = here;
10902 for (p = heredoclist; p->next; p = p->next)
10906 } else if (n->type == NTOFD || n->type == NFROMFD) {
10907 fixredir(n, wordtext, 0);
10909 n->nfile.fname = makename();
10913 static union node *
10916 union node *args, **app;
10917 union node *n = NULL;
10918 union node *vars, **vpp;
10919 union node **rpp, *redir;
10921 #if ENABLE_ASH_BASH_COMPAT
10922 smallint double_brackets_flag = 0;
10923 smallint function_flag = 0;
10933 savecheckkwd = CHKALIAS;
10936 checkkwd = savecheckkwd;
10939 #if ENABLE_ASH_BASH_COMPAT
10941 if (peektoken() != TWORD)
10942 raise_error_unexpected_syntax(TWORD);
10945 case TAND: /* "&&" */
10946 case TOR: /* "||" */
10947 if (!double_brackets_flag) {
10951 wordtext = (char *) (t == TAND ? "-a" : "-o");
10954 n = stzalloc(sizeof(struct narg));
10956 /*n->narg.next = NULL; - stzalloc did it */
10957 n->narg.text = wordtext;
10958 #if ENABLE_ASH_BASH_COMPAT
10959 if (strcmp("[[", wordtext) == 0)
10960 double_brackets_flag = 1;
10961 else if (strcmp("]]", wordtext) == 0)
10962 double_brackets_flag = 0;
10964 n->narg.backquote = backquotelist;
10965 if (savecheckkwd && isassignment(wordtext)) {
10967 vpp = &n->narg.next;
10970 app = &n->narg.next;
10973 #if ENABLE_ASH_BASH_COMPAT
10974 if (function_flag) {
10975 checkkwd = CHKNL | CHKKWD;
10976 switch (peektoken()) {
10988 if (strcmp("[[", wordtext) == 0)
10992 raise_error_unexpected_syntax(-1);
10998 *rpp = n = redirnode;
10999 rpp = &n->nfile.next;
11000 parsefname(); /* read name of redirection file */
11003 IF_ASH_BASH_COMPAT(do_func:)
11004 if (args && app == &args->narg.next
11007 struct builtincmd *bcmd;
11010 /* We have a function */
11011 if (IF_ASH_BASH_COMPAT(!function_flag &&) readtoken() != TRP)
11012 raise_error_unexpected_syntax(TRP);
11013 name = n->narg.text;
11014 if (!goodname(name)
11015 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11017 raise_error_syntax("bad function name");
11020 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11021 n->narg.next = parse_command();
11024 IF_ASH_BASH_COMPAT(function_flag = 0;)
11035 n = stzalloc(sizeof(struct ncmd));
11037 n->ncmd.args = args;
11038 n->ncmd.assign = vars;
11039 n->ncmd.redirect = redir;
11043 static union node *
11044 parse_command(void)
11046 union node *n1, *n2;
11047 union node *ap, **app;
11048 union node *cp, **cpp;
11049 union node *redir, **rpp;
11056 switch (readtoken()) {
11058 raise_error_unexpected_syntax(-1);
11061 n1 = stzalloc(sizeof(struct nif));
11063 n1->nif.test = list(0);
11064 if (readtoken() != TTHEN)
11065 raise_error_unexpected_syntax(TTHEN);
11066 n1->nif.ifpart = list(0);
11068 while (readtoken() == TELIF) {
11069 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11070 n2 = n2->nif.elsepart;
11072 n2->nif.test = list(0);
11073 if (readtoken() != TTHEN)
11074 raise_error_unexpected_syntax(TTHEN);
11075 n2->nif.ifpart = list(0);
11077 if (lasttoken == TELSE)
11078 n2->nif.elsepart = list(0);
11080 n2->nif.elsepart = NULL;
11088 n1 = stzalloc(sizeof(struct nbinary));
11089 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11090 n1->nbinary.ch1 = list(0);
11093 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
11094 got == TWORD ? wordtext : ""));
11095 raise_error_unexpected_syntax(TDO);
11097 n1->nbinary.ch2 = list(0);
11102 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11103 raise_error_syntax("bad for loop variable");
11104 n1 = stzalloc(sizeof(struct nfor));
11106 n1->nfor.var = wordtext;
11107 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11108 if (readtoken() == TIN) {
11110 while (readtoken() == TWORD) {
11111 n2 = stzalloc(sizeof(struct narg));
11113 /*n2->narg.next = NULL; - stzalloc did it */
11114 n2->narg.text = wordtext;
11115 n2->narg.backquote = backquotelist;
11117 app = &n2->narg.next;
11120 n1->nfor.args = ap;
11121 if (lasttoken != TNL && lasttoken != TSEMI)
11122 raise_error_unexpected_syntax(-1);
11124 n2 = stzalloc(sizeof(struct narg));
11126 /*n2->narg.next = NULL; - stzalloc did it */
11127 n2->narg.text = (char *)dolatstr;
11128 /*n2->narg.backquote = NULL;*/
11129 n1->nfor.args = n2;
11131 * Newline or semicolon here is optional (but note
11132 * that the original Bourne shell only allowed NL).
11134 if (lasttoken != TSEMI)
11137 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11138 if (readtoken() != TDO)
11139 raise_error_unexpected_syntax(TDO);
11140 n1->nfor.body = list(0);
11144 n1 = stzalloc(sizeof(struct ncase));
11146 if (readtoken() != TWORD)
11147 raise_error_unexpected_syntax(TWORD);
11148 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11150 /*n2->narg.next = NULL; - stzalloc did it */
11151 n2->narg.text = wordtext;
11152 n2->narg.backquote = backquotelist;
11153 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11154 if (readtoken() != TIN)
11155 raise_error_unexpected_syntax(TIN);
11156 cpp = &n1->ncase.cases;
11158 checkkwd = CHKNL | CHKKWD;
11160 while (t != TESAC) {
11161 if (lasttoken == TLP)
11163 *cpp = cp = stzalloc(sizeof(struct nclist));
11165 app = &cp->nclist.pattern;
11167 *app = ap = stzalloc(sizeof(struct narg));
11169 /*ap->narg.next = NULL; - stzalloc did it */
11170 ap->narg.text = wordtext;
11171 ap->narg.backquote = backquotelist;
11172 if (readtoken() != TPIPE)
11174 app = &ap->narg.next;
11177 //ap->narg.next = NULL;
11178 if (lasttoken != TRP)
11179 raise_error_unexpected_syntax(TRP);
11180 cp->nclist.body = list(2);
11182 cpp = &cp->nclist.next;
11184 checkkwd = CHKNL | CHKKWD;
11188 raise_error_unexpected_syntax(TENDCASE);
11195 n1 = stzalloc(sizeof(struct nredir));
11196 n1->type = NSUBSHELL;
11197 n1->nredir.n = list(0);
11198 /*n1->nredir.redirect = NULL; - stzalloc did it */
11205 IF_ASH_BASH_COMPAT(case TFUNCTION:)
11209 return simplecmd();
11212 if (readtoken() != t)
11213 raise_error_unexpected_syntax(t);
11216 /* Now check for redirection which may follow command */
11217 checkkwd = CHKKWD | CHKALIAS;
11219 while (readtoken() == TREDIR) {
11220 *rpp = n2 = redirnode;
11221 rpp = &n2->nfile.next;
11227 if (n1->type != NSUBSHELL) {
11228 n2 = stzalloc(sizeof(struct nredir));
11233 n1->nredir.redirect = redir;
11238 #if ENABLE_ASH_BASH_COMPAT
11239 static int decode_dollar_squote(void)
11241 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11247 p = strchr(C_escapes, c);
11252 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11256 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11258 } else if (c == 'x') { /* \xHH */
11262 } while (isxdigit(c) && --cnt);
11264 if (cnt == 3) { /* \x but next char is "bad" */
11268 } else { /* simple seq like \\ or \t */
11273 c = bb_process_escape_sequence((void*)&p);
11274 } else { /* unrecognized "\z": print both chars unless ' or " */
11275 if (c != '\'' && c != '"') {
11277 c |= 0x100; /* "please encode \, then me" */
11285 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11286 * is not NULL, read a here document. In the latter case, eofmark is the
11287 * word which marks the end of the document and striptabs is true if
11288 * leading tabs should be stripped from the document. The argument c
11289 * is the first character of the input token or document.
11291 * Because C does not have internal subroutines, I have simulated them
11292 * using goto's to implement the subroutine linkage. The following macros
11293 * will run code that appears at the end of readtoken1.
11295 #define CHECKEND() {goto checkend; checkend_return:;}
11296 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11297 #define PARSESUB() {goto parsesub; parsesub_return:;}
11298 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11299 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11300 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11302 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11304 /* NB: syntax parameter fits into smallint */
11305 /* c parameter is an unsigned char or PEOF or PEOA */
11308 char line[EOFMARKLEN + 1];
11309 struct nodelist *bqlist;
11313 smallint prevsyntax; /* syntax before arithmetic */
11314 #if ENABLE_ASH_EXPAND_PRMT
11315 smallint pssyntax; /* we are expanding a prompt string */
11317 int varnest; /* levels of variables expansion */
11318 int arinest; /* levels of arithmetic expansion */
11319 int parenlevel; /* levels of parens in arithmetic */
11320 int dqvarnest; /* levels of variables expansion within double quotes */
11322 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11324 startlinno = g_parsefile->linno;
11328 #if ENABLE_ASH_EXPAND_PRMT
11329 pssyntax = (syntax == PSSYNTAX);
11333 dblquote = (syntax == DQSYNTAX);
11339 STARTSTACKSTR(out);
11341 /* For each line, until end of word */
11342 CHECKEND(); /* set c to PEOF if at end of here document */
11343 for (;;) { /* until end of line or end of word */
11344 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11345 switch (SIT(c, syntax)) {
11346 case CNL: /* '\n' */
11347 if (syntax == BASESYNTAX)
11348 goto endword; /* exit outer loop */
11350 g_parsefile->linno++;
11351 setprompt_if(doprompt, 2);
11353 goto loop; /* continue outer loop */
11358 #if ENABLE_ASH_BASH_COMPAT
11359 if (c == '\\' && bash_dollar_squote) {
11360 c = decode_dollar_squote();
11362 /* skip $'\000', $'\x00' (like bash) */
11366 /* Unknown escape. Encode as '\z' */
11367 c = (unsigned char)c;
11368 if (eofmark == NULL || dblquote)
11369 USTPUTC(CTLESC, out);
11370 USTPUTC('\\', out);
11374 if (eofmark == NULL || dblquote)
11375 USTPUTC(CTLESC, out);
11378 case CBACK: /* backslash */
11379 c = pgetc_without_PEOA();
11381 USTPUTC(CTLESC, out);
11382 USTPUTC('\\', out);
11384 } else if (c == '\n') {
11385 setprompt_if(doprompt, 2);
11387 #if ENABLE_ASH_EXPAND_PRMT
11388 if (c == '$' && pssyntax) {
11389 USTPUTC(CTLESC, out);
11390 USTPUTC('\\', out);
11393 /* Backslash is retained if we are in "str" and next char isn't special */
11398 && (c != '"' || eofmark != NULL)
11400 USTPUTC('\\', out);
11402 USTPUTC(CTLESC, out);
11410 if (eofmark == NULL) {
11411 USTPUTC(CTLQUOTEMARK, out);
11419 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11420 if (eofmark != NULL && varnest == 0) {
11423 if (dqvarnest == 0) {
11424 syntax = BASESYNTAX;
11431 case CVAR: /* '$' */
11432 PARSESUB(); /* parse substitution */
11434 case CENDVAR: /* '}' */
11437 if (dqvarnest > 0) {
11444 #if ENABLE_SH_MATH_SUPPORT
11445 case CLP: /* '(' in arithmetic */
11449 case CRP: /* ')' in arithmetic */
11450 if (parenlevel > 0) {
11453 if (pgetc_eatbnl() == ')') {
11455 if (--arinest == 0) {
11456 syntax = prevsyntax;
11460 * unbalanced parens
11461 * (don't 2nd guess - no error)
11469 case CBQUOTE: /* '`' */
11473 goto endword; /* exit outer loop */
11477 if (varnest == 0) {
11478 #if ENABLE_ASH_BASH_COMPAT
11480 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11481 if (pgetc() == '>')
11482 c = 0x100 + '>'; /* flag &> */
11486 goto endword; /* exit outer loop */
11488 IF_ASH_ALIAS(if (c != PEOA))
11495 #if ENABLE_SH_MATH_SUPPORT
11496 if (syntax == ARISYNTAX)
11497 raise_error_syntax("missing '))'");
11499 if (syntax != BASESYNTAX && eofmark == NULL)
11500 raise_error_syntax("unterminated quoted string");
11501 if (varnest != 0) {
11502 startlinno = g_parsefile->linno;
11504 raise_error_syntax("missing '}'");
11506 USTPUTC('\0', out);
11507 len = out - (char *)stackblock();
11508 out = stackblock();
11509 if (eofmark == NULL) {
11510 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11513 if (isdigit_str9(out)) {
11514 PARSEREDIR(); /* passed as params: out, c */
11515 lasttoken = TREDIR;
11518 /* else: non-number X seen, interpret it
11519 * as "NNNX>file" = "NNNX >file" */
11523 quoteflag = quotef;
11524 backquotelist = bqlist;
11525 grabstackblock(len);
11529 /* end of readtoken routine */
11532 * Check to see whether we are at the end of the here document. When this
11533 * is called, c is set to the first character of the next input line. If
11534 * we are at the end of the here document, this routine sets the c to PEOF.
11538 #if ENABLE_ASH_ALIAS
11540 c = pgetc_without_PEOA();
11543 while (c == '\t') {
11544 c = pgetc_without_PEOA();
11547 if (c == *eofmark) {
11548 if (pfgets(line, sizeof(line)) != NULL) {
11552 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11554 if (*p == '\n' && *q == '\0') {
11556 g_parsefile->linno++;
11557 needprompt = doprompt;
11559 pushstring(line, NULL);
11564 goto checkend_return;
11568 * Parse a redirection operator. The variable "out" points to a string
11569 * specifying the fd to be redirected. The variable "c" contains the
11570 * first character of the redirection operator.
11573 /* out is already checked to be a valid number or "" */
11574 int fd = (*out == '\0' ? -1 : atoi(out));
11577 np = stzalloc(sizeof(struct nfile));
11582 np->type = NAPPEND;
11584 np->type = NCLOBBER;
11587 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11593 #if ENABLE_ASH_BASH_COMPAT
11594 else if (c == 0x100 + '>') { /* this flags &> redirection */
11596 pgetc(); /* this is '>', no need to check */
11600 else { /* c == '<' */
11601 /*np->nfile.fd = 0; - stzalloc did it */
11605 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11606 np = stzalloc(sizeof(struct nhere));
11607 /*np->nfile.fd = 0; - stzalloc did it */
11610 heredoc = stzalloc(sizeof(struct heredoc));
11611 heredoc->here = np;
11614 heredoc->striptabs = 1;
11616 /*heredoc->striptabs = 0; - stzalloc did it */
11622 np->type = NFROMFD;
11626 np->type = NFROMTO;
11638 goto parseredir_return;
11642 * Parse a substitution. At this point, we have read the dollar sign
11643 * and nothing else.
11646 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11647 * (assuming ascii char codes, as the original implementation did) */
11648 #define is_special(c) \
11649 (((unsigned)(c) - 33 < 32) \
11650 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11652 unsigned char subtype;
11656 c = pgetc_eatbnl();
11657 if (c > 255 /* PEOA or PEOF */
11658 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11660 #if ENABLE_ASH_BASH_COMPAT
11661 if (syntax != DQSYNTAX && c == '\'')
11662 bash_dollar_squote = 1;
11667 } else if (c == '(') {
11668 /* $(command) or $((arith)) */
11669 if (pgetc_eatbnl() == '(') {
11670 #if ENABLE_SH_MATH_SUPPORT
11673 raise_error_syntax("you disabled math support for $((arith)) syntax");
11680 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11681 USTPUTC(CTLVAR, out);
11682 typeloc = out - (char *)stackblock();
11683 USTPUTC(VSNORMAL, out);
11684 subtype = VSNORMAL;
11686 c = pgetc_eatbnl();
11688 c = pgetc_eatbnl();
11690 c = '#'; /* ${#} - same as $# */
11692 subtype = VSLENGTH; /* ${#VAR} */
11697 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11698 /* $[{[#]]NAME[}] */
11701 c = pgetc_eatbnl();
11702 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11703 } else if (isdigit(c)) {
11704 /* $[{[#]]NUM[}] */
11707 c = pgetc_eatbnl();
11708 } while (isdigit(c));
11709 } else if (is_special(c)) {
11710 /* $[{[#]]<specialchar>[}] */
11712 c = pgetc_eatbnl();
11715 raise_error_syntax("bad substitution");
11717 if (c != '}' && subtype == VSLENGTH) {
11718 /* ${#VAR didn't end with } */
11724 if (subtype == 0) {
11725 static const char types[] ALIGN1 = "}-+?=";
11726 /* ${VAR...} but not $VAR or ${#VAR} */
11727 /* c == first char after VAR */
11730 c = pgetc_eatbnl();
11731 #if ENABLE_ASH_BASH_COMPAT
11732 /* This check is only needed to not misinterpret
11733 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11736 if (!strchr(types, c)) {
11737 subtype = VSSUBSTR;
11739 break; /* "goto do_pungetc" is bigger (!) */
11745 const char *p = strchr(types, c);
11748 subtype = p - types + VSNORMAL;
11754 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11755 c = pgetc_eatbnl();
11761 #if ENABLE_ASH_BASH_COMPAT
11763 /* ${v/[/]pattern/repl} */
11764 //TODO: encode pattern and repl separately.
11765 // Currently ${v/$var_with_slash/repl} is horribly broken
11766 subtype = VSREPLACE;
11767 c = pgetc_eatbnl();
11770 subtype++; /* VSREPLACEALL */
11778 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11779 if (subtype != VSNORMAL) {
11786 goto parsesub_return;
11790 * Called to parse command substitutions. Newstyle is set if the command
11791 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11792 * list of commands (passed by reference), and savelen is the number of
11793 * characters on the top of the stack which must be preserved.
11796 struct nodelist **nlpp;
11800 smallint saveprompt = 0;
11803 savelen = out - (char *)stackblock();
11806 * FIXME: this can allocate very large block on stack and SEGV.
11808 * echo "..<100kbytes>..`true` $(true) `true` ..."
11809 * allocates 100kb for every command subst. With about
11810 * a hundred command substitutions stack overflows.
11811 * With larger prepended string, SEGV happens sooner.
11813 str = alloca(savelen);
11814 memcpy(str, stackblock(), savelen);
11818 /* We must read until the closing backquote, giving special
11819 * treatment to some slashes, and then push the string and
11820 * reread it as input, interpreting it normally.
11826 STARTSTACKSTR(pout);
11830 setprompt_if(needprompt, 2);
11839 g_parsefile->linno++;
11840 setprompt_if(doprompt, 2);
11842 * If eating a newline, avoid putting
11843 * the newline into the new character
11844 * stream (via the STPUTC after the
11849 if (pc != '\\' && pc != '`' && pc != '$'
11850 && (!dblquote || pc != '"')
11852 STPUTC('\\', pout);
11854 if (pc <= 255 /* not PEOA or PEOF */) {
11860 IF_ASH_ALIAS(case PEOA:)
11861 startlinno = g_parsefile->linno;
11862 raise_error_syntax("EOF in backquote substitution");
11865 g_parsefile->linno++;
11866 needprompt = doprompt;
11875 STPUTC('\0', pout);
11876 psavelen = pout - (char *)stackblock();
11877 if (psavelen > 0) {
11878 pstr = grabstackstr(pout);
11879 setinputstring(pstr);
11884 nlpp = &(*nlpp)->next;
11885 *nlpp = stzalloc(sizeof(**nlpp));
11886 /* (*nlpp)->next = NULL; - stzalloc did it */
11889 saveprompt = doprompt;
11896 doprompt = saveprompt;
11897 else if (readtoken() != TRP)
11898 raise_error_unexpected_syntax(TRP);
11903 * Start reading from old file again, ignoring any pushed back
11904 * tokens left from the backquote parsing
11909 while (stackblocksize() <= savelen)
11911 STARTSTACKSTR(out);
11913 memcpy(out, str, savelen);
11914 STADJUST(savelen, out);
11916 USTPUTC(CTLBACKQ, out);
11918 goto parsebackq_oldreturn;
11919 goto parsebackq_newreturn;
11922 #if ENABLE_SH_MATH_SUPPORT
11924 * Parse an arithmetic expansion (indicate start of one and set state)
11927 if (++arinest == 1) {
11928 prevsyntax = syntax;
11929 syntax = ARISYNTAX;
11931 USTPUTC(CTLARI, out);
11932 goto parsearith_return;
11935 } /* end of readtoken */
11938 * Read the next input token.
11939 * If the token is a word, we set backquotelist to the list of cmds in
11940 * backquotes. We set quoteflag to true if any part of the word was
11942 * If the token is TREDIR, then we set redirnode to a structure containing
11944 * In all cases, the variable startlinno is set to the number of the line
11945 * on which the token starts.
11947 * [Change comment: here documents and internal procedures]
11948 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11949 * word parsing code into a separate routine. In this case, readtoken
11950 * doesn't need to have any internal procedures, but parseword does.
11951 * We could also make parseoperator in essence the main routine, and
11952 * have parseword (readtoken1?) handle both words and redirection.]
11954 #define NEW_xxreadtoken
11955 #ifdef NEW_xxreadtoken
11956 /* singles must be first! */
11957 static const char xxreadtoken_chars[7] ALIGN1 = {
11958 '\n', '(', ')', /* singles */
11959 '&', '|', ';', /* doubles */
11963 #define xxreadtoken_singles 3
11964 #define xxreadtoken_doubles 3
11966 static const char xxreadtoken_tokens[] ALIGN1 = {
11967 TNL, TLP, TRP, /* only single occurrence allowed */
11968 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11969 TEOF, /* corresponds to trailing nul */
11970 TAND, TOR, TENDCASE /* if double occurrence */
11982 setprompt_if(needprompt, 2);
11983 startlinno = g_parsefile->linno;
11984 for (;;) { /* until token or start of word found */
11986 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11990 while ((c = pgetc()) != '\n' && c != PEOF)
11993 } else if (c == '\\') {
11994 if (pgetc() != '\n') {
11996 break; /* return readtoken1(...) */
11998 startlinno = ++g_parsefile->linno;
11999 setprompt_if(doprompt, 2);
12003 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12006 g_parsefile->linno++;
12007 needprompt = doprompt;
12010 p = strchr(xxreadtoken_chars, c);
12012 break; /* return readtoken1(...) */
12014 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12016 if (cc == c) { /* double occurrence? */
12017 p += xxreadtoken_doubles + 1;
12020 #if ENABLE_ASH_BASH_COMPAT
12021 if (c == '&' && cc == '>') /* &> */
12022 break; /* return readtoken1(...) */
12027 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12032 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12034 #else /* old xxreadtoken */
12035 #define RETURN(token) return lasttoken = token
12045 setprompt_if(needprompt, 2);
12046 startlinno = g_parsefile->linno;
12047 for (;;) { /* until token or start of word found */
12050 case ' ': case '\t':
12051 IF_ASH_ALIAS(case PEOA:)
12054 while ((c = pgetc()) != '\n' && c != PEOF)
12059 if (pgetc() == '\n') {
12060 startlinno = ++g_parsefile->linno;
12061 setprompt_if(doprompt, 2);
12067 g_parsefile->linno++;
12068 needprompt = doprompt;
12073 if (pgetc() == '&')
12078 if (pgetc() == '|')
12083 if (pgetc() == ';')
12096 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12099 #endif /* old xxreadtoken */
12105 int kwd = checkkwd;
12107 smallint alreadyseen = tokpushback;
12110 #if ENABLE_ASH_ALIAS
12126 if (t != TWORD || quoteflag) {
12131 * check for keywords
12133 if (kwd & CHKKWD) {
12134 const char *const *pp;
12136 pp = findkwd(wordtext);
12138 lasttoken = t = pp - tokname_array;
12139 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
12144 if (checkkwd & CHKALIAS) {
12145 #if ENABLE_ASH_ALIAS
12147 ap = lookupalias(wordtext, 1);
12150 pushstring(ap->val, ap);
12160 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
12162 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
12178 * Read and parse a command. Returns NODE_EOF on end of file.
12179 * (NULL is a valid parse tree indicating a blank line.)
12181 static union node *
12182 parsecmd(int interact)
12187 doprompt = interact;
12188 setprompt_if(doprompt, doprompt);
12194 * Input any here documents.
12199 struct heredoc *here;
12202 here = heredoclist;
12203 heredoclist = NULL;
12206 setprompt_if(needprompt, 2);
12207 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12208 here->eofmark, here->striptabs);
12209 n = stzalloc(sizeof(struct narg));
12210 n->narg.type = NARG;
12211 /*n->narg.next = NULL; - stzalloc did it */
12212 n->narg.text = wordtext;
12213 n->narg.backquote = backquotelist;
12214 here->here->nhere.doc = n;
12221 * called by editline -- any expansions to the prompt should be added here.
12223 #if ENABLE_ASH_EXPAND_PRMT
12224 static const char *
12225 expandstr(const char *ps)
12229 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12230 * and token processing _can_ alter it (delete NULs etc). */
12231 setinputstring((char *)ps);
12232 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12235 n.narg.type = NARG;
12236 n.narg.next = NULL;
12237 n.narg.text = wordtext;
12238 n.narg.backquote = backquotelist;
12240 expandarg(&n, NULL, EXP_QUOTED);
12241 return stackblock();
12246 * Execute a command or commands contained in a string.
12249 evalstring(char *s, int flags)
12252 struct stackmark smark;
12257 setstackmark(&smark);
12260 while ((n = parsecmd(0)) != NODE_EOF) {
12263 i = evaltree(n, flags);
12266 popstackmark(&smark);
12270 popstackmark(&smark);
12278 * The eval command.
12280 static int FAST_FUNC
12281 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12290 STARTSTACKSTR(concat);
12292 concat = stack_putstr(p, concat);
12296 STPUTC(' ', concat);
12298 STPUTC('\0', concat);
12299 p = grabstackstr(concat);
12301 return evalstring(p, flags & EV_TESTED);
12307 * Read and execute commands.
12308 * "Top" is nonzero for the top level command loop;
12309 * it turns on prompting if the shell is interactive.
12315 struct stackmark smark;
12320 TRACE(("cmdloop(%d) called\n", top));
12324 setstackmark(&smark);
12327 showjobs(SHOW_CHANGED|SHOW_STDERR);
12330 if (iflag && top) {
12334 n = parsecmd(inter);
12336 if (DEBUG > 2 && debug && (n != NODE_EOF))
12339 if (n == NODE_EOF) {
12340 if (!top || numeof >= 50)
12342 if (!stoppedjobs()) {
12345 out2str("\nUse \"exit\" to leave shell.\n");
12348 } else if (nflag == 0) {
12351 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12354 i = evaltree(n, 0);
12358 popstackmark(&smark);
12362 evalskip &= ~SKIPFUNC;
12363 return skip & SKIPEVAL;
12370 * Take commands from a file. To be compatible we should do a path
12371 * search for the file, which is necessary to find sub-commands.
12374 find_dot_file(char *name)
12377 const char *path = pathval();
12380 /* don't try this for absolute or relative paths */
12381 if (strchr(name, '/'))
12384 /* IIRC standards do not say whether . is to be searched.
12385 * And it is even smaller this way, making it unconditional for now:
12387 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12392 while ((fullname = path_advance(&path, name)) != NULL) {
12394 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12396 * Don't bother freeing here, since it will
12397 * be freed by the caller.
12401 if (fullname != name)
12402 stunalloc(fullname);
12405 /* not found in the PATH */
12406 ash_msg_and_raise_error("%s: not found", name);
12410 static int FAST_FUNC
12411 dotcmd(int argc, char **argv)
12414 struct strlist *sp;
12415 volatile struct shparam saveparam;
12417 for (sp = cmdenviron; sp; sp = sp->next)
12418 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12421 /* bash says: "bash: .: filename argument required" */
12422 return 2; /* bash compat */
12425 /* "false; . empty_file; echo $?" should print 0, not 1: */
12428 /* This aborts if file isn't found, which is POSIXly correct.
12429 * bash returns exitcode 1 instead.
12431 fullname = find_dot_file(argv[1]);
12434 if (argc) { /* argc > 0, argv[0] != NULL */
12435 saveparam = shellparam;
12436 shellparam.malloced = 0;
12437 shellparam.nparam = argc;
12438 shellparam.p = argv;
12441 /* This aborts if file can't be opened, which is POSIXly correct.
12442 * bash returns exitcode 1 instead.
12444 setinputfile(fullname, INPUT_PUSH_FILE);
12445 commandname = fullname;
12450 freeparam(&shellparam);
12451 shellparam = saveparam;
12457 static int FAST_FUNC
12458 exitcmd(int argc UNUSED_PARAM, char **argv)
12463 exitstatus = number(argv[1]);
12464 raise_exception(EXEXIT);
12469 * Read a file containing shell functions.
12472 readcmdfile(char *name)
12474 setinputfile(name, INPUT_PUSH_FILE);
12480 /* ============ find_command inplementation */
12483 * Resolve a command name. If you change this routine, you may have to
12484 * change the shellexec routine as well.
12487 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12489 struct tblentry *cmdp;
12496 struct builtincmd *bcmd;
12498 /* If name contains a slash, don't use PATH or hash table */
12499 if (strchr(name, '/') != NULL) {
12500 entry->u.index = -1;
12501 if (act & DO_ABS) {
12502 while (stat(name, &statb) < 0) {
12504 if (errno == EINTR)
12507 entry->cmdtype = CMDUNKNOWN;
12511 entry->cmdtype = CMDNORMAL;
12515 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12517 updatetbl = (path == pathval());
12520 if (strstr(path, "%builtin") != NULL)
12521 act |= DO_ALTBLTIN;
12524 /* If name is in the table, check answer will be ok */
12525 cmdp = cmdlookup(name, 0);
12526 if (cmdp != NULL) {
12529 switch (cmdp->cmdtype) {
12547 } else if (cmdp->rehash == 0)
12548 /* if not invalidated by cd, we're done */
12552 /* If %builtin not in path, check for builtin next */
12553 bcmd = find_builtin(name);
12555 if (IS_BUILTIN_REGULAR(bcmd))
12556 goto builtin_success;
12557 if (act & DO_ALTPATH) {
12558 if (!(act & DO_ALTBLTIN))
12559 goto builtin_success;
12560 } else if (builtinloc <= 0) {
12561 goto builtin_success;
12565 #if ENABLE_FEATURE_SH_STANDALONE
12567 int applet_no = find_applet_by_name(name);
12568 if (applet_no >= 0) {
12569 entry->cmdtype = CMDNORMAL;
12570 entry->u.index = -2 - applet_no;
12576 /* We have to search path. */
12577 prev = -1; /* where to start */
12578 if (cmdp && cmdp->rehash) { /* doing a rehash */
12579 if (cmdp->cmdtype == CMDBUILTIN)
12582 prev = cmdp->param.index;
12588 while ((fullname = path_advance(&path, name)) != NULL) {
12589 stunalloc(fullname);
12590 /* NB: code below will still use fullname
12591 * despite it being "unallocated" */
12594 if (prefix(pathopt, "builtin")) {
12596 goto builtin_success;
12599 if ((act & DO_NOFUNC)
12600 || !prefix(pathopt, "func")
12601 ) { /* ignore unimplemented options */
12605 /* if rehash, don't redo absolute path names */
12606 if (fullname[0] == '/' && idx <= prev) {
12609 TRACE(("searchexec \"%s\": no change\n", name));
12612 while (stat(fullname, &statb) < 0) {
12614 if (errno == EINTR)
12617 if (errno != ENOENT && errno != ENOTDIR)
12621 e = EACCES; /* if we fail, this will be the error */
12622 if (!S_ISREG(statb.st_mode))
12624 if (pathopt) { /* this is a %func directory */
12625 stalloc(strlen(fullname) + 1);
12626 /* NB: stalloc will return space pointed by fullname
12627 * (because we don't have any intervening allocations
12628 * between stunalloc above and this stalloc) */
12629 readcmdfile(fullname);
12630 cmdp = cmdlookup(name, 0);
12631 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12632 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12633 stunalloc(fullname);
12636 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12638 entry->cmdtype = CMDNORMAL;
12639 entry->u.index = idx;
12643 cmdp = cmdlookup(name, 1);
12644 cmdp->cmdtype = CMDNORMAL;
12645 cmdp->param.index = idx;
12650 /* We failed. If there was an entry for this command, delete it */
12651 if (cmdp && updatetbl)
12652 delete_cmd_entry();
12654 ash_msg("%s: %s", name, errmsg(e, "not found"));
12655 entry->cmdtype = CMDUNKNOWN;
12660 entry->cmdtype = CMDBUILTIN;
12661 entry->u.cmd = bcmd;
12665 cmdp = cmdlookup(name, 1);
12666 cmdp->cmdtype = CMDBUILTIN;
12667 cmdp->param.cmd = bcmd;
12671 entry->cmdtype = cmdp->cmdtype;
12672 entry->u = cmdp->param;
12676 /* ============ trap.c */
12679 * The trap builtin.
12681 static int FAST_FUNC
12682 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12686 int signo, exitcode;
12691 for (signo = 0; signo < NSIG; signo++) {
12692 char *tr = trap_ptr[signo];
12694 /* note: bash adds "SIG", but only if invoked
12695 * as "bash". If called as "sh", or if set -o posix,
12696 * then it prints short signal names.
12697 * We are printing short names: */
12698 out1fmt("trap -- %s %s\n",
12700 get_signame(signo));
12701 /* trap_ptr != trap only if we are in special-cased `trap` code.
12702 * In this case, we will exit very soon, no need to free(). */
12703 /* if (trap_ptr != trap && tp[0]) */
12708 if (trap_ptr != trap) {
12721 signo = get_signum(*ap);
12723 /* Mimic bash message exactly */
12724 ash_msg("%s: invalid signal specification", *ap);
12730 if (LONE_DASH(action))
12733 action = ckstrdup(action);
12737 may_have_traps = 1;
12738 trap[signo] = action;
12749 /* ============ Builtins */
12751 #if ENABLE_ASH_HELP
12752 static int FAST_FUNC
12753 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12759 "Built-in commands:\n"
12760 "------------------\n");
12761 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12762 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12763 builtintab[i].name + 1);
12769 # if ENABLE_FEATURE_SH_STANDALONE
12771 const char *a = applet_names;
12773 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12778 while (*a++ != '\0')
12784 return EXIT_SUCCESS;
12789 static int FAST_FUNC
12790 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12792 show_history(line_input_state);
12793 return EXIT_SUCCESS;
12798 * The export and readonly commands.
12800 static int FAST_FUNC
12801 exportcmd(int argc UNUSED_PARAM, char **argv)
12811 /* "readonly" in bash accepts, but ignores -n.
12812 * We do the same: it saves a conditional in nextopt's param.
12815 while ((opt = nextopt("np")) != '\0') {
12817 flag_off = VEXPORT;
12820 if (argv[0][0] == 'r') {
12822 flag_off = 0; /* readonly ignores -n */
12824 flag_off = ~flag_off;
12826 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12832 p = strchr(name, '=');
12836 vp = *findvar(hashvar(name), name);
12838 vp->flags = ((vp->flags | flag) & flag_off);
12842 setvar(name, p, (flag & flag_off));
12843 } while ((name = *++aptr) != NULL);
12848 /* No arguments. Show the list of exported or readonly vars.
12851 showvars(argv[0], flag, 0);
12856 * Delete a function if it exists.
12859 unsetfunc(const char *name)
12861 struct tblentry *cmdp;
12863 cmdp = cmdlookup(name, 0);
12864 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12865 delete_cmd_entry();
12869 * The unset builtin command. We unset the function before we unset the
12870 * variable to allow a function to be unset when there is a readonly variable
12871 * with the same name.
12873 static int FAST_FUNC
12874 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12881 while ((i = nextopt("vf")) != 0) {
12885 for (ap = argptr; *ap; ap++) {
12898 static const unsigned char timescmd_str[] ALIGN1 = {
12899 ' ', offsetof(struct tms, tms_utime),
12900 '\n', offsetof(struct tms, tms_stime),
12901 ' ', offsetof(struct tms, tms_cutime),
12902 '\n', offsetof(struct tms, tms_cstime),
12905 static int FAST_FUNC
12906 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12908 unsigned long clk_tck, s, t;
12909 const unsigned char *p;
12912 clk_tck = bb_clk_tck();
12917 t = *(clock_t *)(((char *) &buf) + p[1]);
12920 out1fmt("%lum%lu.%03lus%c",
12922 (t * 1000) / clk_tck,
12930 #if ENABLE_SH_MATH_SUPPORT
12932 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12933 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12935 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12937 static int FAST_FUNC
12938 letcmd(int argc UNUSED_PARAM, char **argv)
12944 ash_msg_and_raise_error("expression expected");
12946 i = ash_arith(*argv);
12954 * The read builtin. Options:
12955 * -r Do not interpret '\' specially
12956 * -s Turn off echo (tty only)
12957 * -n NCHARS Read NCHARS max
12958 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12959 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12960 * -u FD Read from given FD instead of fd 0
12961 * This uses unbuffered input, which may be avoidable in some cases.
12962 * TODO: bash also has:
12963 * -a ARRAY Read into array[0],[1],etc
12964 * -d DELIM End on DELIM char, not newline
12965 * -e Use line editing (tty only)
12967 static int FAST_FUNC
12968 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12970 char *opt_n = NULL;
12971 char *opt_p = NULL;
12972 char *opt_t = NULL;
12973 char *opt_u = NULL;
12974 int read_flags = 0;
12978 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12987 read_flags |= BUILTIN_READ_SILENT;
12993 read_flags |= BUILTIN_READ_RAW;
13003 /* "read -s" needs to save/restore termios, can't allow ^C
13004 * to jump out of it.
13007 r = shell_builtin_read(setvar0,
13009 bltinlookup("IFS"), /* can be NULL */
13018 if ((uintptr_t)r > 1)
13019 ash_msg_and_raise_error(r);
13021 return (uintptr_t)r;
13024 static int FAST_FUNC
13025 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13027 static const char permuser[3] ALIGN1 = "ogu";
13030 int symbolic_mode = 0;
13032 while (nextopt("S") != '\0') {
13041 if (*argptr == NULL) {
13042 if (symbolic_mode) {
13043 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13050 *p++ = permuser[i];
13052 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13053 if (!(mask & 0400)) *p++ = 'r';
13054 if (!(mask & 0200)) *p++ = 'w';
13055 if (!(mask & 0100)) *p++ = 'x';
13063 out1fmt("%04o\n", mask);
13066 char *modestr = *argptr;
13067 /* numeric umasks are taken as-is */
13068 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13069 if (!isdigit(modestr[0]))
13071 mask = bb_parse_mode(modestr, mask);
13072 if ((unsigned)mask > 0777) {
13073 ash_msg_and_raise_error("illegal mode: %s", modestr);
13075 if (!isdigit(modestr[0]))
13082 static int FAST_FUNC
13083 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13085 return shell_builtin_ulimit(argv);
13088 /* ============ main() and helpers */
13091 * Called to exit the shell.
13100 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13101 save_history(line_input_state);
13104 status = exitstatus;
13105 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13106 if (setjmp(loc.loc)) {
13107 if (exception_type == EXEXIT)
13108 /* dash bug: it just does _exit(exitstatus) here
13109 * but we have to do setjobctl(0) first!
13110 * (bug is still not fixed in dash-0.5.3 - if you run dash
13111 * under Midnight Commander, on exit from dash MC is backgrounded) */
13112 status = exitstatus;
13115 exception_handler = &loc;
13123 flush_stdout_stderr();
13133 /* from input.c: */
13134 /* we will never free this */
13135 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13138 signal(SIGCHLD, SIG_DFL);
13139 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13140 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13142 signal(SIGHUP, SIG_DFL);
13148 struct stat st1, st2;
13151 for (envp = environ; envp && *envp; envp++) {
13152 p = endofname(*envp);
13153 if (p != *envp && *p == '=') {
13154 setvareq(*envp, VEXPORT|VTEXTFIXED);
13158 setvareq((char*)defoptindvar, VTEXTFIXED);
13160 setvar0("PPID", utoa(getppid()));
13161 #if ENABLE_ASH_BASH_COMPAT
13162 p = lookupvar("SHLVL");
13163 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13164 if (!lookupvar("HOSTNAME")) {
13165 struct utsname uts;
13167 setvar0("HOSTNAME", uts.nodename);
13170 p = lookupvar("PWD");
13172 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13173 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13183 //usage:#define ash_trivial_usage
13184 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13185 //usage:#define ash_full_usage "\n\n"
13186 //usage: "Unix shell interpreter"
13188 //usage:#if ENABLE_FEATURE_SH_IS_ASH
13189 //usage:# define sh_trivial_usage ash_trivial_usage
13190 //usage:# define sh_full_usage ash_full_usage
13192 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
13193 //usage:# define bash_trivial_usage ash_trivial_usage
13194 //usage:# define bash_full_usage ash_full_usage
13198 * Process the shell command line arguments.
13201 procargs(char **argv)
13204 const char *xminusc;
13209 /* if (xargv[0]) - mmm, this is always true! */
13211 for (i = 0; i < NOPTS; i++)
13214 if (options(/*cmdline:*/ 1)) {
13215 /* it already printed err message */
13216 raise_exception(EXERROR);
13220 if (*xargv == NULL) {
13222 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13225 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13229 for (i = 0; i < NOPTS; i++)
13230 if (optlist[i] == 2)
13235 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13240 } else if (!sflag) {
13241 setinputfile(*xargv, 0);
13244 commandname = arg0;
13247 shellparam.p = xargv;
13248 #if ENABLE_ASH_GETOPTS
13249 shellparam.optind = 1;
13250 shellparam.optoff = -1;
13252 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13254 shellparam.nparam++;
13261 * Read /etc/profile or .profile.
13264 read_profile(const char *name)
13268 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13277 * This routine is called when an error or an interrupt occurs in an
13278 * interactive shell and control is returned to the main command loop.
13286 /* from input.c: */
13287 g_parsefile->left_in_buffer = 0;
13288 g_parsefile->left_in_line = 0; /* clear input buffer */
13290 /* from parser.c: */
13293 /* from redir.c: */
13294 clearredir(/*drop:*/ 0);
13298 static short profile_buf[16384];
13299 extern int etext();
13303 * Main routine. We initialize things, parse the arguments, execute
13304 * profiles if we're a login shell, and then call cmdloop to execute
13305 * commands. The setjmp call sets up the location to jump to when an
13306 * exception occurs. When an exception occurs the variable "state"
13307 * is used to figure out how far we had gotten.
13309 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13310 int ash_main(int argc UNUSED_PARAM, char **argv)
13312 const char *shinit;
13313 volatile smallint state;
13314 struct jmploc jmploc;
13315 struct stackmark smark;
13317 /* Initialize global data */
13321 #if ENABLE_ASH_ALIAS
13327 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13330 #if ENABLE_FEATURE_EDITING
13331 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13334 if (setjmp(jmploc.loc)) {
13340 e = exception_type;
13344 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13348 newline_and_flush(stderr);
13351 popstackmark(&smark);
13352 FORCE_INT_ON; /* enable interrupts */
13361 exception_handler = &jmploc;
13364 TRACE(("Shell args: "));
13365 trace_puts_args(argv);
13367 rootpid = getpid();
13370 setstackmark(&smark);
13373 if (argv[0] && argv[0][0] == '-')
13379 read_profile("/etc/profile");
13382 hp = lookupvar("HOME");
13384 hp = concat_path_file(hp, ".profile");
13393 getuid() == geteuid() && getgid() == getegid() &&
13397 shinit = lookupvar("ENV");
13398 if (shinit != NULL && *shinit != '\0') {
13399 read_profile(shinit);
13405 /* evalstring pushes parsefile stack.
13406 * Ensure we don't falsely claim that 0 (stdin)
13407 * is one of stacked source fds.
13408 * Testcase: ash -c 'exec 1>&0' must not complain. */
13409 // if (!sflag) g_parsefile->pf_fd = -1;
13410 // ^^ not necessary since now we special-case fd 0
13411 // in is_hidden_fd() to not be considered "hidden fd"
13412 evalstring(minusc, 0);
13415 if (sflag || minusc == NULL) {
13416 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13418 const char *hp = lookupvar("HISTFILE");
13420 hp = lookupvar("HOME");
13422 hp = concat_path_file(hp, ".ash_history");
13423 setvar0("HISTFILE", hp);
13425 hp = lookupvar("HISTFILE");
13429 line_input_state->hist_file = hp;
13430 # if ENABLE_FEATURE_SH_HISTFILESIZE
13431 hp = lookupvar("HISTFILESIZE");
13432 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13436 state4: /* XXX ??? - why isn't this before the "if" statement */
13444 extern void _mcleanup(void);
13448 TRACE(("End of main reached\n"));
13455 * Copyright (c) 1989, 1991, 1993, 1994
13456 * The Regents of the University of California. All rights reserved.
13458 * This code is derived from software contributed to Berkeley by
13459 * Kenneth Almquist.
13461 * Redistribution and use in source and binary forms, with or without
13462 * modification, are permitted provided that the following conditions
13464 * 1. Redistributions of source code must retain the above copyright
13465 * notice, this list of conditions and the following disclaimer.
13466 * 2. Redistributions in binary form must reproduce the above copyright
13467 * notice, this list of conditions and the following disclaimer in the
13468 * documentation and/or other materials provided with the distribution.
13469 * 3. Neither the name of the University nor the names of its contributors
13470 * may be used to endorse or promote products derived from this software
13471 * without specific prior written permission.
13473 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13474 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13475 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13476 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13477 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13478 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13479 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13480 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13481 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13482 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF