1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
20 * The following should be set to reflect the type of system you have:
21 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22 * define SYSV if you are running under System V.
23 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24 * define DEBUG=2 to compile in and turn on debugging.
26 * When debugging is on (DEBUG is 1 and "set -o debug" was executed),
27 * debugging info will be written to ./trace and a quit signal
28 * will generate a core dump.
31 /* Tweak debug output verbosity here */
38 #define JOBS ENABLE_ASH_JOB_CONTROL
42 #include <sys/times.h>
43 #include <sys/utsname.h> /* for setting $HOSTNAME */
45 #include "busybox.h" /* for applet_names */
47 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
48 /* Bionic at least up to version 24 has no glob() */
49 # undef ENABLE_ASH_INTERNAL_GLOB
50 # define ENABLE_ASH_INTERNAL_GLOB 1
53 #if !ENABLE_ASH_INTERNAL_GLOB
58 #include "shell_common.h"
59 #if ENABLE_SH_MATH_SUPPORT
62 #if ENABLE_ASH_RANDOM_SUPPORT
65 # define CLEAR_RANDOM_T(rnd) ((void)0)
68 #include "NUM_APPLETS.h"
70 /* STANDALONE does not make sense, and won't compile */
71 # undef CONFIG_FEATURE_SH_STANDALONE
72 # undef ENABLE_FEATURE_SH_STANDALONE
73 # undef IF_FEATURE_SH_STANDALONE
74 # undef IF_NOT_FEATURE_SH_STANDALONE
75 # define ENABLE_FEATURE_SH_STANDALONE 0
76 # define IF_FEATURE_SH_STANDALONE(...)
77 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
81 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
85 # error "Do not even bother, ash will not run on NOMMU machine"
91 //config: depends on !NOMMU
93 //config: Tha 'ash' shell adds about 60k in the default configuration and is
94 //config: the most complete and most pedantically correct shell included with
95 //config: busybox. This shell is actually a derivative of the Debian 'dash'
96 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
97 //config: (written by Kenneth Almquist) from NetBSD.
99 //config:config ASH_OPTIMIZE_FOR_SIZE
100 //config: bool "Optimize for size instead of speed"
102 //config: depends on ASH
104 //config: Compile ash for reduced size at the price of speed.
106 //config:config ASH_INTERNAL_GLOB
107 //config: bool "Use internal glob() implementation"
109 //config: depends on ASH
111 //config: Do not use glob() function from libc, use internal implementation.
112 //config: Use this if you are getting "glob.h: No such file or directory"
113 //config: or similar build errors.
115 //config:config ASH_RANDOM_SUPPORT
116 //config: bool "Pseudorandom generator and $RANDOM variable"
118 //config: depends on ASH
120 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
121 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
122 //config: You can reset the generator by using a specified start value.
123 //config: After "unset RANDOM" the generator will switch off and this
124 //config: variable will no longer have special treatment.
126 //config:config ASH_EXPAND_PRMT
127 //config: bool "Expand prompt string"
129 //config: depends on ASH
131 //config: "PS#" may contain volatile content, such as backquote commands.
132 //config: This option recreates the prompt string from the environment
133 //config: variable each time it is displayed.
135 //config:config ASH_BASH_COMPAT
136 //config: bool "bash-compatible extensions"
138 //config: depends on ASH
140 //config: Enable bash-compatible extensions.
142 //config:config ASH_IDLE_TIMEOUT
143 //config: bool "Idle timeout variable"
145 //config: depends on ASH
147 //config: Enables bash-like auto-logout after $TMOUT seconds of idle time.
149 //config:config ASH_JOB_CONTROL
150 //config: bool "Job control"
152 //config: depends on ASH
154 //config: Enable job control in the ash shell.
156 //config:config ASH_ALIAS
157 //config: bool "Alias support"
159 //config: depends on ASH
161 //config: Enable alias support in the ash shell.
163 //config:config ASH_GETOPTS
164 //config: bool "Builtin getopt to parse positional parameters"
166 //config: depends on ASH
168 //config: Enable support for getopts builtin in ash.
170 //config:config ASH_BUILTIN_ECHO
171 //config: bool "Builtin version of 'echo'"
173 //config: depends on ASH
175 //config: Enable support for echo builtin in ash.
177 //config:config ASH_BUILTIN_PRINTF
178 //config: bool "Builtin version of 'printf'"
180 //config: depends on ASH
182 //config: Enable support for printf builtin in ash.
184 //config:config ASH_BUILTIN_TEST
185 //config: bool "Builtin version of 'test'"
187 //config: depends on ASH
189 //config: Enable support for test builtin in ash.
191 //config:config ASH_HELP
192 //config: bool "help builtin"
194 //config: depends on ASH
196 //config: Enable help builtin in ash.
198 //config:config ASH_CMDCMD
199 //config: bool "'command' command to override shell builtins"
201 //config: depends on ASH
203 //config: Enable support for the ash 'command' builtin, which allows
204 //config: you to run the specified command with the specified arguments,
205 //config: even when there is an ash builtin command with the same name.
207 //config:config ASH_MAIL
208 //config: bool "Check for new mail on interactive shells"
210 //config: depends on ASH
212 //config: Enable "check for new mail" function in the ash shell.
215 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
216 //applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, sh))
217 //applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, bash))
219 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
220 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
223 /* ============ Hash table sizes. Configurable. */
227 #define CMDTABLESIZE 31 /* should be prime */
230 /* ============ Shell options */
232 static const char *const optletters_optnames[] = {
247 #if ENABLE_ASH_BASH_COMPAT
256 #define optletters(n) optletters_optnames[n][0]
257 #define optnames(n) (optletters_optnames[n] + 1)
259 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
262 /* ============ Misc data */
264 #define msg_illnum "Illegal number: %s"
267 * We enclose jmp_buf in a structure so that we can declare pointers to
268 * jump locations. The global variable handler contains the location to
269 * jump to when an exception occurs, and the global variable exception_type
270 * contains a code identifying the exception. To implement nested
271 * exception handlers, the user should save the value of handler on entry
272 * to an inner scope, set handler to point to a jmploc structure for the
273 * inner scope, and restore handler on exit from the scope.
279 struct globals_misc {
280 uint8_t exitstatus; /* exit status of last command */
281 uint8_t back_exitstatus;/* exit status of backquoted command */
282 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
283 int rootpid; /* pid of main shell */
284 /* shell level: 0 for the main shell, 1 for its children, and so on */
286 #define rootshell (!shlvl)
287 char *minusc; /* argument to -c option */
289 char *curdir; // = nullstr; /* current working directory */
290 char *physdir; // = nullstr; /* physical working directory */
292 char *arg0; /* value of $0 */
294 struct jmploc *exception_handler;
296 volatile int suppress_int; /* counter */
297 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
298 /* last pending signal */
299 volatile /*sig_atomic_t*/ smallint pending_sig;
300 smallint exception_type; /* kind of exception (0..5) */
302 #define EXINT 0 /* SIGINT received */
303 #define EXERROR 1 /* a generic error */
304 #define EXSHELLPROC 2 /* execute a shell procedure */
305 #define EXEXEC 3 /* command execution failed */
306 #define EXEXIT 4 /* exit the shell */
307 #define EXSIG 5 /* trapped signal in wait(1) */
310 char nullstr[1]; /* zero length string */
313 #define eflag optlist[0]
314 #define fflag optlist[1]
315 #define Iflag optlist[2]
316 #define iflag optlist[3]
317 #define mflag optlist[4]
318 #define nflag optlist[5]
319 #define sflag optlist[6]
320 #define xflag optlist[7]
321 #define vflag optlist[8]
322 #define Cflag optlist[9]
323 #define aflag optlist[10]
324 #define bflag optlist[11]
325 #define uflag optlist[12]
326 #define viflag optlist[13]
327 #if ENABLE_ASH_BASH_COMPAT
328 # define pipefail optlist[14]
333 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
334 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
337 /* trap handler commands */
339 * Sigmode records the current value of the signal handlers for the various
340 * modes. A value of zero means that the current handler is not known.
341 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
343 char sigmode[NSIG - 1];
344 #define S_DFL 1 /* default signal handling (SIG_DFL) */
345 #define S_CATCH 2 /* signal is caught */
346 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
347 #define S_HARD_IGN 4 /* signal is ignored permanently */
349 /* indicates specified signal received */
350 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
351 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
353 char **trap_ptr; /* used only by "trap hack" */
355 /* Rarely referenced stuff */
356 #if ENABLE_ASH_RANDOM_SUPPORT
359 pid_t backgndpid; /* pid of last background process */
361 extern struct globals_misc *const ash_ptr_to_globals_misc;
362 #define G_misc (*ash_ptr_to_globals_misc)
363 #define exitstatus (G_misc.exitstatus )
364 #define back_exitstatus (G_misc.back_exitstatus )
365 #define job_warning (G_misc.job_warning)
366 #define rootpid (G_misc.rootpid )
367 #define shlvl (G_misc.shlvl )
368 #define minusc (G_misc.minusc )
369 #define curdir (G_misc.curdir )
370 #define physdir (G_misc.physdir )
371 #define arg0 (G_misc.arg0 )
372 #define exception_handler (G_misc.exception_handler)
373 #define exception_type (G_misc.exception_type )
374 #define suppress_int (G_misc.suppress_int )
375 #define pending_int (G_misc.pending_int )
376 #define pending_sig (G_misc.pending_sig )
377 #define isloginsh (G_misc.isloginsh )
378 #define nullstr (G_misc.nullstr )
379 #define optlist (G_misc.optlist )
380 #define sigmode (G_misc.sigmode )
381 #define gotsig (G_misc.gotsig )
382 #define may_have_traps (G_misc.may_have_traps )
383 #define trap (G_misc.trap )
384 #define trap_ptr (G_misc.trap_ptr )
385 #define random_gen (G_misc.random_gen )
386 #define backgndpid (G_misc.backgndpid )
387 #define INIT_G_misc() do { \
388 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
396 /* ============ DEBUG */
398 static void trace_printf(const char *fmt, ...);
399 static void trace_vprintf(const char *fmt, va_list va);
400 # define TRACE(param) trace_printf param
401 # define TRACEV(param) trace_vprintf param
402 # define close(fd) do { \
404 if (close(dfd) < 0) \
405 bb_error_msg("bug on %d: closing %d(0x%x)", \
406 __LINE__, dfd, dfd); \
409 # define TRACE(param)
410 # define TRACEV(param)
414 /* ============ Utility functions */
415 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
416 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
419 isdigit_str9(const char *str)
421 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
422 while (--maxlen && isdigit(*str))
424 return (*str == '\0');
428 var_end(const char *var)
437 /* ============ Interrupts / exceptions */
439 static void exitshell(void) NORETURN;
442 * These macros allow the user to suspend the handling of interrupt signals
443 * over a period of time. This is similar to SIGHOLD or to sigblock, but
444 * much more efficient and portable. (But hacking the kernel is so much
445 * more fun than worrying about efficiency and portability. :-))
447 #define INT_OFF do { \
453 * Called to raise an exception. Since C doesn't include exceptions, we
454 * just do a longjmp to the exception handler. The type of exception is
455 * stored in the global variable "exception_type".
457 static void raise_exception(int) NORETURN;
459 raise_exception(int e)
462 if (exception_handler == NULL)
467 longjmp(exception_handler->loc, 1);
470 #define raise_exception(e) do { \
471 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
472 raise_exception(e); \
477 * Called from trap.c when a SIGINT is received. (If the user specifies
478 * that SIGINT is to be trapped or ignored using the trap builtin, then
479 * this routine is not called.) Suppressint is nonzero when interrupts
480 * are held using the INT_OFF macro. (The test for iflag is just
481 * defensive programming.)
483 static void raise_interrupt(void) NORETURN;
485 raise_interrupt(void)
490 /* Signal is not automatically unmasked after it is raised,
491 * do it ourself - unmask all signals */
492 sigprocmask_allsigs(SIG_UNBLOCK);
493 /* pending_sig = 0; - now done in signal_handler() */
496 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
497 if (!(rootshell && iflag)) {
498 /* Kill ourself with SIGINT */
499 signal(SIGINT, SIG_DFL);
504 /* bash: ^C even on empty command line sets $? */
505 exitstatus = SIGINT + 128;
506 raise_exception(ex_type);
510 #define raise_interrupt() do { \
511 TRACE(("raising interrupt on line %d\n", __LINE__)); \
516 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
520 if (--suppress_int == 0 && pending_int) {
524 #define INT_ON int_on()
525 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
533 #define FORCE_INT_ON force_int_on()
535 #define SAVE_INT(v) ((v) = suppress_int)
537 #define RESTORE_INT(v) do { \
539 suppress_int = (v); \
540 if (suppress_int == 0 && pending_int) \
545 /* ============ Stdout/stderr output */
548 outstr(const char *p, FILE *file)
556 flush_stdout_stderr(void)
563 /* Was called outcslow(c,FILE*), but c was always '\n' */
565 newline_and_flush(FILE *dest)
573 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
575 out1fmt(const char *fmt, ...)
582 r = vprintf(fmt, ap);
588 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
590 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
597 ret = vsnprintf(outbuf, length, fmt, ap);
604 out1str(const char *p)
610 out2str(const char *p)
613 flush_stdout_stderr();
617 /* ============ Parser structures */
619 /* control characters in argument strings */
620 #define CTL_FIRST CTLESC
621 #define CTLESC ((unsigned char)'\201') /* escape next character */
622 #define CTLVAR ((unsigned char)'\202') /* variable defn */
623 #define CTLENDVAR ((unsigned char)'\203')
624 #define CTLBACKQ ((unsigned char)'\204')
625 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
626 #define CTLENDARI ((unsigned char)'\207')
627 #define CTLQUOTEMARK ((unsigned char)'\210')
628 #define CTL_LAST CTLQUOTEMARK
630 /* variable substitution byte (follows CTLVAR) */
631 #define VSTYPE 0x0f /* type of variable substitution */
632 #define VSNUL 0x10 /* colon--treat the empty string as unset */
634 /* values of VSTYPE field */
635 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
636 #define VSMINUS 0x2 /* ${var-text} */
637 #define VSPLUS 0x3 /* ${var+text} */
638 #define VSQUESTION 0x4 /* ${var?message} */
639 #define VSASSIGN 0x5 /* ${var=text} */
640 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
641 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
642 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
643 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
644 #define VSLENGTH 0xa /* ${#var} */
645 #if ENABLE_ASH_BASH_COMPAT
646 #define VSSUBSTR 0xc /* ${var:position:length} */
647 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
648 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
651 static const char dolatstr[] ALIGN1 = {
652 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
654 #define DOLATSTRLEN 6
673 #if ENABLE_ASH_BASH_COMPAT
690 smallint type; /* Nxxxx */
693 union node *redirect;
698 smallint pipe_backgnd;
699 struct nodelist *cmdlist;
705 union node *redirect;
718 union node *elsepart;
745 struct nodelist *backquote;
748 /* nfile and ndup layout must match!
749 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
750 * that it is actually NTO2 (>&file), and change its type.
767 char *_unused_expfname;
786 struct nredir nredir;
787 struct nbinary nbinary;
791 struct nclist nclist;
800 * NODE_EOF is returned by parsecmd when it encounters an end of file.
801 * It must be distinct from NULL.
803 #define NODE_EOF ((union node *) -1L)
806 struct nodelist *next;
819 freefunc(struct funcnode *f)
821 if (f && --f->count < 0)
826 /* ============ Debugging output */
830 static FILE *tracefile;
833 trace_printf(const char *fmt, ...)
840 fprintf(tracefile, "%u ", (int) time(NULL));
842 fprintf(tracefile, "[%u] ", (int) getpid());
844 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
846 vfprintf(tracefile, fmt, va);
851 trace_vprintf(const char *fmt, va_list va)
856 fprintf(tracefile, "%u ", (int) time(NULL));
858 fprintf(tracefile, "[%u] ", (int) getpid());
860 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
861 vfprintf(tracefile, fmt, va);
865 trace_puts(const char *s)
873 trace_puts_quoted(char *s)
880 putc('"', tracefile);
881 for (p = s; *p; p++) {
882 switch ((unsigned char)*p) {
883 case '\n': c = 'n'; goto backslash;
884 case '\t': c = 't'; goto backslash;
885 case '\r': c = 'r'; goto backslash;
886 case '\"': c = '\"'; goto backslash;
887 case '\\': c = '\\'; goto backslash;
888 case CTLESC: c = 'e'; goto backslash;
889 case CTLVAR: c = 'v'; goto backslash;
890 case CTLBACKQ: c = 'q'; goto backslash;
892 putc('\\', tracefile);
896 if (*p >= ' ' && *p <= '~')
899 putc('\\', tracefile);
900 putc((*p >> 6) & 03, tracefile);
901 putc((*p >> 3) & 07, tracefile);
902 putc(*p & 07, tracefile);
907 putc('"', tracefile);
911 trace_puts_args(char **ap)
918 trace_puts_quoted(*ap);
920 putc('\n', tracefile);
923 putc(' ', tracefile);
938 /* leave open because libedit might be using it */
941 strcpy(s, "./trace");
943 if (!freopen(s, "a", tracefile)) {
944 fprintf(stderr, "Can't re-open %s\n", s);
949 tracefile = fopen(s, "a");
950 if (tracefile == NULL) {
951 fprintf(stderr, "Can't open %s\n", s);
957 flags = fcntl(fileno(tracefile), F_GETFL);
959 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
961 setlinebuf(tracefile);
962 fputs("\nTracing started.\n", tracefile);
966 indent(int amount, char *pfx, FILE *fp)
970 for (i = 0; i < amount; i++) {
971 if (pfx && i == amount - 1)
977 /* little circular references here... */
978 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
981 sharg(union node *arg, FILE *fp)
984 struct nodelist *bqlist;
985 unsigned char subtype;
987 if (arg->type != NARG) {
988 out1fmt("<node type %d>\n", arg->type);
991 bqlist = arg->narg.backquote;
992 for (p = arg->narg.text; *p; p++) {
993 switch ((unsigned char)*p) {
1002 if (subtype == VSLENGTH)
1010 if (subtype & VSNUL)
1013 switch (subtype & VSTYPE) {
1039 case VSTRIMRIGHTMAX:
1046 out1fmt("<subtype %d>", subtype);
1055 shtree(bqlist->n, -1, NULL, fp);
1066 shcmd(union node *cmd, FILE *fp)
1074 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1080 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1084 switch (np->nfile.type) {
1085 case NTO: s = ">>"+1; dftfd = 1; break;
1086 case NCLOBBER: s = ">|"; dftfd = 1; break;
1087 case NAPPEND: s = ">>"; dftfd = 1; break;
1088 #if ENABLE_ASH_BASH_COMPAT
1091 case NTOFD: s = ">&"; dftfd = 1; break;
1092 case NFROM: s = "<"; break;
1093 case NFROMFD: s = "<&"; break;
1094 case NFROMTO: s = "<>"; break;
1095 default: s = "*error*"; break;
1097 if (np->nfile.fd != dftfd)
1098 fprintf(fp, "%d", np->nfile.fd);
1100 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1101 fprintf(fp, "%d", np->ndup.dupfd);
1103 sharg(np->nfile.fname, fp);
1110 shtree(union node *n, int ind, char *pfx, FILE *fp)
1112 struct nodelist *lp;
1118 indent(ind, pfx, fp);
1120 if (n == NODE_EOF) {
1135 shtree(n->nbinary.ch1, ind, NULL, fp);
1138 shtree(n->nbinary.ch2, ind, NULL, fp);
1146 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1147 shtree(lp->n, 0, NULL, fp);
1151 if (n->npipe.pipe_backgnd)
1157 fprintf(fp, "<node type %d>", n->type);
1165 showtree(union node *n)
1167 trace_puts("showtree called\n");
1168 shtree(n, 1, NULL, stderr);
1174 /* ============ Parser data */
1177 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1180 struct strlist *next;
1187 struct strpush *prev; /* preceding string on stack */
1189 int prev_left_in_line;
1190 #if ENABLE_ASH_ALIAS
1191 struct alias *ap; /* if push was associated with an alias */
1193 char *string; /* remember the string since it may change */
1195 /* Remember last two characters for pungetc. */
1198 /* Number of outstanding calls to pungetc. */
1203 struct parsefile *prev; /* preceding file on stack */
1204 int linno; /* current line */
1205 int pf_fd; /* file descriptor (or -1 if string) */
1206 int left_in_line; /* number of chars left in this line */
1207 int left_in_buffer; /* number of chars left in this buffer past the line */
1208 char *next_to_pgetc; /* next char in buffer */
1209 char *buf; /* input buffer */
1210 struct strpush *strpush; /* for pushing strings at this level */
1211 struct strpush basestrpush; /* so pushing one is fast */
1213 /* Remember last two characters for pungetc. */
1216 /* Number of outstanding calls to pungetc. */
1220 static struct parsefile basepf; /* top level input file */
1221 static struct parsefile *g_parsefile = &basepf; /* current input file */
1222 static int startlinno; /* line # where last token started */
1223 static char *commandname; /* currently executing command */
1224 static struct strlist *cmdenviron; /* environment for builtin command */
1227 /* ============ Message printing */
1230 ash_vmsg(const char *msg, va_list ap)
1232 fprintf(stderr, "%s: ", arg0);
1234 if (strcmp(arg0, commandname))
1235 fprintf(stderr, "%s: ", commandname);
1236 if (!iflag || g_parsefile->pf_fd > 0)
1237 fprintf(stderr, "line %d: ", startlinno);
1239 vfprintf(stderr, msg, ap);
1240 newline_and_flush(stderr);
1244 * Exverror is called to raise the error exception. If the second argument
1245 * is not NULL then error prints an error message using printf style
1246 * formatting. It then raises the error exception.
1248 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1250 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1254 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1256 TRACE(("\") pid=%d\n", getpid()));
1258 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1263 flush_stdout_stderr();
1264 raise_exception(cond);
1268 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1270 ash_msg_and_raise_error(const char *msg, ...)
1275 ash_vmsg_and_raise(EXERROR, msg, ap);
1280 static void raise_error_syntax(const char *) NORETURN;
1282 raise_error_syntax(const char *msg)
1284 ash_msg_and_raise_error("syntax error: %s", msg);
1288 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1290 ash_msg_and_raise(int cond, const char *msg, ...)
1295 ash_vmsg_and_raise(cond, msg, ap);
1301 * error/warning routines for external builtins
1304 ash_msg(const char *fmt, ...)
1314 * Return a string describing an error. The returned string may be a
1315 * pointer to a static buffer that will be overwritten on the next call.
1316 * Action describes the operation that got the error.
1319 errmsg(int e, const char *em)
1321 if (e == ENOENT || e == ENOTDIR) {
1328 /* ============ Memory allocation */
1331 /* I consider these wrappers nearly useless:
1332 * ok, they return you to nearest exception handler, but
1333 * how much memory do you leak in the process, making
1334 * memory starvation worse?
1337 ckrealloc(void * p, size_t nbytes)
1339 p = realloc(p, nbytes);
1341 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1346 ckmalloc(size_t nbytes)
1348 return ckrealloc(NULL, nbytes);
1352 ckzalloc(size_t nbytes)
1354 return memset(ckmalloc(nbytes), 0, nbytes);
1358 ckstrdup(const char *s)
1360 char *p = strdup(s);
1362 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1366 /* Using bbox equivalents. They exit if out of memory */
1367 # define ckrealloc xrealloc
1368 # define ckmalloc xmalloc
1369 # define ckzalloc xzalloc
1370 # define ckstrdup xstrdup
1374 * It appears that grabstackstr() will barf with such alignments
1375 * because stalloc() will return a string allocated in a new stackblock.
1377 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1379 /* Most machines require the value returned from malloc to be aligned
1380 * in some way. The following macro will get this right
1381 * on many machines. */
1382 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1383 /* Minimum size of a block */
1384 MINSIZE = SHELL_ALIGN(504),
1387 struct stack_block {
1388 struct stack_block *prev;
1389 char space[MINSIZE];
1393 struct stack_block *stackp;
1399 struct globals_memstack {
1400 struct stack_block *g_stackp; // = &stackbase;
1401 char *g_stacknxt; // = stackbase.space;
1402 char *sstrend; // = stackbase.space + MINSIZE;
1403 size_t g_stacknleft; // = MINSIZE;
1404 int herefd; // = -1;
1405 struct stack_block stackbase;
1407 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1408 #define G_memstack (*ash_ptr_to_globals_memstack)
1409 #define g_stackp (G_memstack.g_stackp )
1410 #define g_stacknxt (G_memstack.g_stacknxt )
1411 #define sstrend (G_memstack.sstrend )
1412 #define g_stacknleft (G_memstack.g_stacknleft)
1413 #define herefd (G_memstack.herefd )
1414 #define stackbase (G_memstack.stackbase )
1415 #define INIT_G_memstack() do { \
1416 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1418 g_stackp = &stackbase; \
1419 g_stacknxt = stackbase.space; \
1420 g_stacknleft = MINSIZE; \
1421 sstrend = stackbase.space + MINSIZE; \
1426 #define stackblock() ((void *)g_stacknxt)
1427 #define stackblocksize() g_stacknleft
1430 * Parse trees for commands are allocated in lifo order, so we use a stack
1431 * to make this more efficient, and also to avoid all sorts of exception
1432 * handling code to handle interrupts in the middle of a parse.
1434 * The size 504 was chosen because the Ultrix malloc handles that size
1438 stalloc(size_t nbytes)
1443 aligned = SHELL_ALIGN(nbytes);
1444 if (aligned > g_stacknleft) {
1447 struct stack_block *sp;
1449 blocksize = aligned;
1450 if (blocksize < MINSIZE)
1451 blocksize = MINSIZE;
1452 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1453 if (len < blocksize)
1454 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1457 sp->prev = g_stackp;
1458 g_stacknxt = sp->space;
1459 g_stacknleft = blocksize;
1460 sstrend = g_stacknxt + blocksize;
1465 g_stacknxt += aligned;
1466 g_stacknleft -= aligned;
1471 stzalloc(size_t nbytes)
1473 return memset(stalloc(nbytes), 0, nbytes);
1480 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1481 write(STDERR_FILENO, "stunalloc\n", 10);
1485 g_stacknleft += g_stacknxt - (char *)p;
1490 * Like strdup but works with the ash stack.
1493 sstrdup(const char *p)
1495 size_t len = strlen(p) + 1;
1496 return memcpy(stalloc(len), p, len);
1500 grabstackblock(size_t len)
1502 len = SHELL_ALIGN(len);
1504 g_stacknleft -= len;
1508 pushstackmark(struct stackmark *mark, size_t len)
1510 mark->stackp = g_stackp;
1511 mark->stacknxt = g_stacknxt;
1512 mark->stacknleft = g_stacknleft;
1513 grabstackblock(len);
1517 setstackmark(struct stackmark *mark)
1519 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1523 popstackmark(struct stackmark *mark)
1525 struct stack_block *sp;
1531 while (g_stackp != mark->stackp) {
1533 g_stackp = sp->prev;
1536 g_stacknxt = mark->stacknxt;
1537 g_stacknleft = mark->stacknleft;
1538 sstrend = mark->stacknxt + mark->stacknleft;
1543 * When the parser reads in a string, it wants to stick the string on the
1544 * stack and only adjust the stack pointer when it knows how big the
1545 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1546 * of space on top of the stack and stackblocklen returns the length of
1547 * this block. Growstackblock will grow this space by at least one byte,
1548 * possibly moving it (like realloc). Grabstackblock actually allocates the
1549 * part of the block that has been used.
1552 growstackblock(void)
1556 newlen = g_stacknleft * 2;
1557 if (newlen < g_stacknleft)
1558 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1562 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1563 struct stack_block *sp;
1564 struct stack_block *prevstackp;
1569 prevstackp = sp->prev;
1570 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1571 sp = ckrealloc(sp, grosslen);
1572 sp->prev = prevstackp;
1574 g_stacknxt = sp->space;
1575 g_stacknleft = newlen;
1576 sstrend = sp->space + newlen;
1579 char *oldspace = g_stacknxt;
1580 size_t oldlen = g_stacknleft;
1581 char *p = stalloc(newlen);
1583 /* free the space we just allocated */
1584 g_stacknxt = memcpy(p, oldspace, oldlen);
1585 g_stacknleft += newlen;
1590 * The following routines are somewhat easier to use than the above.
1591 * The user declares a variable of type STACKSTR, which may be declared
1592 * to be a register. The macro STARTSTACKSTR initializes things. Then
1593 * the user uses the macro STPUTC to add characters to the string. In
1594 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1595 * grown as necessary. When the user is done, she can just leave the
1596 * string there and refer to it using stackblock(). Or she can allocate
1597 * the space for it using grabstackstr(). If it is necessary to allow
1598 * someone else to use the stack temporarily and then continue to grow
1599 * the string, the user should use grabstack to allocate the space, and
1600 * then call ungrabstr(p) to return to the previous mode of operation.
1602 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1603 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1604 * is space for at least one character.
1609 size_t len = stackblocksize();
1610 if (herefd >= 0 && len >= 1024) {
1611 full_write(herefd, stackblock(), len);
1612 return stackblock();
1615 return (char *)stackblock() + len;
1619 * Called from CHECKSTRSPACE.
1622 makestrspace(size_t newlen, char *p)
1624 size_t len = p - g_stacknxt;
1630 size = stackblocksize();
1632 if (nleft >= newlen)
1636 return (char *)stackblock() + len;
1640 stack_nputstr(const char *s, size_t n, char *p)
1642 p = makestrspace(n, p);
1643 p = (char *)memcpy(p, s, n) + n;
1648 stack_putstr(const char *s, char *p)
1650 return stack_nputstr(s, strlen(s), p);
1654 _STPUTC(int c, char *p)
1662 #define STARTSTACKSTR(p) ((p) = stackblock())
1663 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1664 #define CHECKSTRSPACE(n, p) do { \
1667 size_t m = sstrend - q; \
1669 (p) = makestrspace(l, q); \
1671 #define USTPUTC(c, p) (*(p)++ = (c))
1672 #define STACKSTRNUL(p) do { \
1673 if ((p) == sstrend) \
1674 (p) = growstackstr(); \
1677 #define STUNPUTC(p) (--(p))
1678 #define STTOPC(p) ((p)[-1])
1679 #define STADJUST(amount, p) ((p) += (amount))
1681 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1682 #define ungrabstackstr(s, p) stunalloc(s)
1683 #define stackstrend() ((void *)sstrend)
1686 /* ============ String helpers */
1689 * prefix -- see if pfx is a prefix of string.
1692 prefix(const char *string, const char *pfx)
1695 if (*pfx++ != *string++)
1698 return (char *) string;
1702 * Check for a valid number. This should be elsewhere.
1705 is_number(const char *p)
1710 } while (*++p != '\0');
1715 * Convert a string of digits to an integer, printing an error message on
1719 number(const char *s)
1722 ash_msg_and_raise_error(msg_illnum, s);
1727 * Produce a possibly single quoted string suitable as input to the shell.
1728 * The return string is allocated on the stack.
1731 single_quote(const char *s)
1741 len = strchrnul(s, '\'') - s;
1743 q = p = makestrspace(len + 3, p);
1746 q = (char *)memcpy(q, s, len) + len;
1755 do len++; while (*++s == '\'');
1757 q = p = makestrspace(len + 3, p);
1760 q = (char *)memcpy(q, s - len, len) + len;
1768 return stackblock();
1772 /* ============ nextopt */
1774 static char **argptr; /* argument list for builtin commands */
1775 static char *optionarg; /* set by nextopt (like getopt) */
1776 static char *optptr; /* used by nextopt */
1779 * XXX - should get rid of. Have all builtins use getopt(3).
1780 * The library getopt must have the BSD extension static variable
1781 * "optreset", otherwise it can't be used within the shell safely.
1783 * Standard option processing (a la getopt) for builtin routines.
1784 * The only argument that is passed to nextopt is the option string;
1785 * the other arguments are unnecessary. It returns the character,
1786 * or '\0' on end of input.
1789 nextopt(const char *optstring)
1796 if (p == NULL || *p == '\0') {
1797 /* We ate entire "-param", take next one */
1803 if (*++p == '\0') /* just "-" ? */
1806 if (LONE_DASH(p)) /* "--" ? */
1808 /* p => next "-param" */
1810 /* p => some option char in the middle of a "-param" */
1812 for (q = optstring; *q != c;) {
1814 ash_msg_and_raise_error("illegal option -%c", c);
1822 ash_msg_and_raise_error("no arg for -%c option", c);
1832 /* ============ Shell variables */
1835 * The parsefile structure pointed to by the global variable parsefile
1836 * contains information about the current file being read.
1839 int nparam; /* # of positional parameters (without $0) */
1840 #if ENABLE_ASH_GETOPTS
1841 int optind; /* next parameter to be processed by getopts */
1842 int optoff; /* used by getopts */
1844 unsigned char malloced; /* if parameter list dynamically allocated */
1845 char **p; /* parameter list */
1849 * Free the list of positional parameters.
1852 freeparam(volatile struct shparam *param)
1854 if (param->malloced) {
1856 ap = ap1 = param->p;
1863 #if ENABLE_ASH_GETOPTS
1864 static void FAST_FUNC getoptsreset(const char *value);
1868 struct var *next; /* next entry in hash list */
1869 int flags; /* flags are defined above */
1870 const char *var_text; /* name=value */
1871 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1872 /* the variable gets set/unset */
1876 struct localvar *next; /* next local variable in list */
1877 struct var *vp; /* the variable that was made local */
1878 int flags; /* saved flags */
1879 const char *text; /* saved text */
1883 #define VEXPORT 0x01 /* variable is exported */
1884 #define VREADONLY 0x02 /* variable cannot be modified */
1885 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1886 #define VTEXTFIXED 0x08 /* text is statically allocated */
1887 #define VSTACK 0x10 /* text is allocated on the stack */
1888 #define VUNSET 0x20 /* the variable is not set */
1889 #define VNOFUNC 0x40 /* don't call the callback function */
1890 #define VNOSET 0x80 /* do not set variable - just readonly test */
1891 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1892 #if ENABLE_ASH_RANDOM_SUPPORT
1893 # define VDYNAMIC 0x200 /* dynamic variable */
1899 /* Need to be before varinit_data[] */
1900 #if ENABLE_LOCALE_SUPPORT
1901 static void FAST_FUNC
1902 change_lc_all(const char *value)
1904 if (value && *value != '\0')
1905 setlocale(LC_ALL, value);
1907 static void FAST_FUNC
1908 change_lc_ctype(const char *value)
1910 if (value && *value != '\0')
1911 setlocale(LC_CTYPE, value);
1915 static void chkmail(void);
1916 static void changemail(const char *var_value) FAST_FUNC;
1918 # define chkmail() ((void)0)
1920 static void changepath(const char *) FAST_FUNC;
1921 #if ENABLE_ASH_RANDOM_SUPPORT
1922 static void change_random(const char *) FAST_FUNC;
1925 static const struct {
1927 const char *var_text;
1928 void (*var_func)(const char *) FAST_FUNC;
1929 } varinit_data[] = {
1931 * Note: VEXPORT would not work correctly here for NOFORK applets:
1932 * some environment strings may be constant.
1934 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1936 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1937 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1939 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1940 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1941 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1942 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1943 #if ENABLE_ASH_GETOPTS
1944 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
1946 #if ENABLE_ASH_RANDOM_SUPPORT
1947 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1949 #if ENABLE_LOCALE_SUPPORT
1950 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1951 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1953 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1954 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1960 struct globals_var {
1961 struct shparam shellparam; /* $@ current positional parameters */
1962 struct redirtab *redirlist;
1964 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1965 struct var *vartab[VTABSIZE];
1966 struct var varinit[ARRAY_SIZE(varinit_data)];
1968 extern struct globals_var *const ash_ptr_to_globals_var;
1969 #define G_var (*ash_ptr_to_globals_var)
1970 #define shellparam (G_var.shellparam )
1971 //#define redirlist (G_var.redirlist )
1972 #define g_nullredirs (G_var.g_nullredirs )
1973 #define preverrout_fd (G_var.preverrout_fd)
1974 #define vartab (G_var.vartab )
1975 #define varinit (G_var.varinit )
1976 #define INIT_G_var() do { \
1978 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1980 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1981 varinit[i].flags = varinit_data[i].flags; \
1982 varinit[i].var_text = varinit_data[i].var_text; \
1983 varinit[i].var_func = varinit_data[i].var_func; \
1987 #define vifs varinit[0]
1989 # define vmail (&vifs)[1]
1990 # define vmpath (&vmail)[1]
1991 # define vpath (&vmpath)[1]
1993 # define vpath (&vifs)[1]
1995 #define vps1 (&vpath)[1]
1996 #define vps2 (&vps1)[1]
1997 #define vps4 (&vps2)[1]
1998 #if ENABLE_ASH_GETOPTS
1999 # define voptind (&vps4)[1]
2000 # if ENABLE_ASH_RANDOM_SUPPORT
2001 # define vrandom (&voptind)[1]
2004 # if ENABLE_ASH_RANDOM_SUPPORT
2005 # define vrandom (&vps4)[1]
2010 * The following macros access the values of the above variables.
2011 * They have to skip over the name. They return the null string
2012 * for unset variables.
2014 #define ifsval() (vifs.var_text + 4)
2015 #define ifsset() ((vifs.flags & VUNSET) == 0)
2017 # define mailval() (vmail.var_text + 5)
2018 # define mpathval() (vmpath.var_text + 9)
2019 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2021 #define pathval() (vpath.var_text + 5)
2022 #define ps1val() (vps1.var_text + 4)
2023 #define ps2val() (vps2.var_text + 4)
2024 #define ps4val() (vps4.var_text + 4)
2025 #if ENABLE_ASH_GETOPTS
2026 # define optindval() (voptind.var_text + 7)
2029 #if ENABLE_ASH_GETOPTS
2030 static void FAST_FUNC
2031 getoptsreset(const char *value)
2033 shellparam.optind = number(value);
2034 shellparam.optoff = -1;
2039 * Compares two strings up to the first = or '\0'. The first
2040 * string must be terminated by '='; the second may be terminated by
2041 * either '=' or '\0'.
2044 varcmp(const char *p, const char *q)
2048 while ((c = *p) == (d = *q)) {
2049 if (c == '\0' || c == '=')
2063 * Find the appropriate entry in the hash table from the name.
2065 static struct var **
2066 hashvar(const char *p)
2070 hashval = ((unsigned char) *p) << 4;
2071 while (*p && *p != '=')
2072 hashval += (unsigned char) *p++;
2073 return &vartab[hashval % VTABSIZE];
2077 vpcmp(const void *a, const void *b)
2079 return varcmp(*(const char **)a, *(const char **)b);
2083 * This routine initializes the builtin variables.
2093 * PS1 depends on uid
2095 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2096 vps1.var_text = "PS1=\\w \\$ ";
2099 vps1.var_text = "PS1=# ";
2102 end = vp + ARRAY_SIZE(varinit);
2104 vpp = hashvar(vp->var_text);
2107 } while (++vp < end);
2110 static struct var **
2111 findvar(struct var **vpp, const char *name)
2113 for (; *vpp; vpp = &(*vpp)->next) {
2114 if (varcmp((*vpp)->var_text, name) == 0) {
2122 * Find the value of a variable. Returns NULL if not set.
2124 static const char* FAST_FUNC
2125 lookupvar(const char *name)
2129 v = *findvar(hashvar(name), name);
2131 #if ENABLE_ASH_RANDOM_SUPPORT
2133 * Dynamic variables are implemented roughly the same way they are
2134 * in bash. Namely, they're "special" so long as they aren't unset.
2135 * As soon as they're unset, they're no longer dynamic, and dynamic
2136 * lookup will no longer happen at that point. -- PFM.
2138 if (v->flags & VDYNAMIC)
2141 if (!(v->flags & VUNSET))
2142 return var_end(v->var_text);
2148 reinit_unicode_for_ash(void)
2150 /* Unicode support should be activated even if LANG is set
2151 * _during_ shell execution, not only if it was set when
2152 * shell was started. Therefore, re-check LANG every time:
2154 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2155 || ENABLE_UNICODE_USING_LOCALE
2157 const char *s = lookupvar("LC_ALL");
2158 if (!s) s = lookupvar("LC_CTYPE");
2159 if (!s) s = lookupvar("LANG");
2165 * Search the environment of a builtin command.
2168 bltinlookup(const char *name)
2172 for (sp = cmdenviron; sp; sp = sp->next) {
2173 if (varcmp(sp->text, name) == 0)
2174 return var_end(sp->text);
2176 return lookupvar(name);
2180 * Same as setvar except that the variable and value are passed in
2181 * the first argument as name=value. Since the first argument will
2182 * be actually stored in the table, it should not be a string that
2184 * Called with interrupts off.
2187 setvareq(char *s, int flags)
2189 struct var *vp, **vpp;
2192 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2193 vp = *findvar(vpp, s);
2195 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2198 if (flags & VNOSAVE)
2201 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2207 if (vp->var_func && !(flags & VNOFUNC))
2208 vp->var_func(var_end(s));
2210 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2211 free((char*)vp->var_text);
2213 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2215 /* variable s is not found */
2218 vp = ckzalloc(sizeof(*vp));
2220 /*vp->func = NULL; - ckzalloc did it */
2223 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2230 * Set the value of a variable. The flags argument is ored with the
2231 * flags of the variable. If val is NULL, the variable is unset.
2234 setvar(const char *name, const char *val, int flags)
2242 q = endofname(name);
2243 p = strchrnul(q, '=');
2245 if (!namelen || p != q)
2246 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2251 vallen = strlen(val);
2255 nameeq = ckmalloc(namelen + vallen + 2);
2256 p = memcpy(nameeq, name, namelen) + namelen;
2259 p = memcpy(p, val, vallen) + vallen;
2262 setvareq(nameeq, flags | VNOSAVE);
2266 static void FAST_FUNC
2267 setvar0(const char *name, const char *val)
2269 setvar(name, val, 0);
2272 #if ENABLE_ASH_GETOPTS
2274 * Safe version of setvar, returns 1 on success 0 on failure.
2277 setvarsafe(const char *name, const char *val, int flags)
2280 volatile int saveint;
2281 struct jmploc *volatile savehandler = exception_handler;
2282 struct jmploc jmploc;
2285 if (setjmp(jmploc.loc))
2288 exception_handler = &jmploc;
2289 setvar(name, val, flags);
2292 exception_handler = savehandler;
2293 RESTORE_INT(saveint);
2299 * Unset the specified variable.
2302 unsetvar(const char *s)
2308 vpp = findvar(hashvar(s), s);
2312 int flags = vp->flags;
2315 if (flags & VREADONLY)
2317 #if ENABLE_ASH_RANDOM_SUPPORT
2318 vp->flags &= ~VDYNAMIC;
2322 if ((flags & VSTRFIXED) == 0) {
2324 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2325 free((char*)vp->var_text);
2331 vp->flags &= ~VEXPORT;
2341 * Process a linked list of variable assignments.
2344 listsetvar(struct strlist *list_set_var, int flags)
2346 struct strlist *lp = list_set_var;
2352 setvareq(lp->text, flags);
2359 * Generate a list of variables satisfying the given conditions.
2362 listvars(int on, int off, char ***end)
2373 for (vp = *vpp; vp; vp = vp->next) {
2374 if ((vp->flags & mask) == on) {
2375 if (ep == stackstrend())
2376 ep = growstackstr();
2377 *ep++ = (char*)vp->var_text;
2380 } while (++vpp < vartab + VTABSIZE);
2381 if (ep == stackstrend())
2382 ep = growstackstr();
2386 return grabstackstr(ep);
2390 /* ============ Path search helper
2392 * The variable path (passed by reference) should be set to the start
2393 * of the path before the first call; path_advance will update
2394 * this value as it proceeds. Successive calls to path_advance will return
2395 * the possible path expansions in sequence. If an option (indicated by
2396 * a percent sign) appears in the path entry then the global variable
2397 * pathopt will be set to point to it; otherwise pathopt will be set to
2400 static const char *pathopt; /* set by path_advance */
2403 path_advance(const char **path, const char *name)
2413 for (p = start; *p && *p != ':' && *p != '%'; p++)
2415 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2416 while (stackblocksize() < len)
2420 memcpy(q, start, p - start);
2428 while (*p && *p != ':')
2435 return stalloc(len);
2439 /* ============ Prompt */
2441 static smallint doprompt; /* if set, prompt the user */
2442 static smallint needprompt; /* true if interactive and at start of line */
2444 #if ENABLE_FEATURE_EDITING
2445 static line_input_t *line_input_state;
2446 static const char *cmdedit_prompt;
2448 putprompt(const char *s)
2450 if (ENABLE_ASH_EXPAND_PRMT) {
2451 free((char*)cmdedit_prompt);
2452 cmdedit_prompt = ckstrdup(s);
2459 putprompt(const char *s)
2465 #if ENABLE_ASH_EXPAND_PRMT
2466 /* expandstr() needs parsing machinery, so it is far away ahead... */
2467 static const char *expandstr(const char *ps);
2469 #define expandstr(s) s
2473 setprompt_if(smallint do_set, int whichprompt)
2476 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2483 switch (whichprompt) {
2493 #if ENABLE_ASH_EXPAND_PRMT
2494 pushstackmark(&smark, stackblocksize());
2496 putprompt(expandstr(prompt));
2497 #if ENABLE_ASH_EXPAND_PRMT
2498 popstackmark(&smark);
2503 /* ============ The cd and pwd commands */
2505 #define CD_PHYSICAL 1
2515 while ((i = nextopt("LP")) != '\0') {
2517 flags ^= CD_PHYSICAL;
2526 * Update curdir (the name of the current directory) in response to a
2530 updatepwd(const char *dir)
2537 cdcomppath = sstrdup(dir);
2540 if (curdir == nullstr)
2542 new = stack_putstr(curdir, new);
2544 new = makestrspace(strlen(dir) + 2, new);
2545 lim = (char *)stackblock() + 1;
2549 if (new > lim && *lim == '/')
2554 if (dir[1] == '/' && dir[2] != '/') {
2560 p = strtok(cdcomppath, "/");
2564 if (p[1] == '.' && p[2] == '\0') {
2576 new = stack_putstr(p, new);
2579 p = strtok(NULL, "/");
2584 return stackblock();
2588 * Find out what the current directory is. If we already know the current
2589 * directory, this routine returns immediately.
2594 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2595 return dir ? dir : nullstr;
2599 setpwd(const char *val, int setold)
2603 oldcur = dir = curdir;
2606 setvar("OLDPWD", oldcur, VEXPORT);
2609 if (physdir != nullstr) {
2610 if (physdir != oldcur)
2614 if (oldcur == val || !val) {
2620 dir = ckstrdup(val);
2621 if (oldcur != dir && oldcur != nullstr) {
2626 setvar("PWD", dir, VEXPORT);
2629 static void hashcd(void);
2632 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2633 * know that the current directory has changed.
2636 docd(const char *dest, int flags)
2638 const char *dir = NULL;
2641 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2644 if (!(flags & CD_PHYSICAL)) {
2645 dir = updatepwd(dest);
2659 static int FAST_FUNC
2660 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2672 dest = bltinlookup("HOME");
2673 else if (LONE_DASH(dest)) {
2674 dest = bltinlookup("OLDPWD");
2696 path = bltinlookup("CDPATH");
2705 p = path_advance(&path, dest);
2706 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2710 if (!docd(p, flags))
2715 ash_msg_and_raise_error("can't cd to %s", dest);
2718 if (flags & CD_PRINT)
2719 out1fmt("%s\n", curdir);
2723 static int FAST_FUNC
2724 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2727 const char *dir = curdir;
2731 if (physdir == nullstr)
2735 out1fmt("%s\n", dir);
2740 /* ============ ... */
2743 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2745 /* Syntax classes */
2746 #define CWORD 0 /* character is nothing special */
2747 #define CNL 1 /* newline character */
2748 #define CBACK 2 /* a backslash character */
2749 #define CSQUOTE 3 /* single quote */
2750 #define CDQUOTE 4 /* double quote */
2751 #define CENDQUOTE 5 /* a terminating quote */
2752 #define CBQUOTE 6 /* backwards single quote */
2753 #define CVAR 7 /* a dollar sign */
2754 #define CENDVAR 8 /* a '}' character */
2755 #define CLP 9 /* a left paren in arithmetic */
2756 #define CRP 10 /* a right paren in arithmetic */
2757 #define CENDFILE 11 /* end of file */
2758 #define CCTL 12 /* like CWORD, except it must be escaped */
2759 #define CSPCL 13 /* these terminate a word */
2760 #define CIGN 14 /* character should be ignored */
2763 #if ENABLE_ASH_ALIAS
2767 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2769 #if ENABLE_SH_MATH_SUPPORT
2770 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2772 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2774 static const uint16_t S_I_T[] ALIGN2 = {
2775 #if ENABLE_ASH_ALIAS
2776 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2778 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2779 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2780 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2781 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2782 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2783 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2784 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2785 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2786 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2787 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2788 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2789 #if !USE_SIT_FUNCTION
2790 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2791 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2792 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2796 /* Constants below must match table above */
2798 #if ENABLE_ASH_ALIAS
2799 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2801 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2802 CNL_CNL_CNL_CNL , /* 2 */
2803 CWORD_CCTL_CCTL_CWORD , /* 3 */
2804 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2805 CVAR_CVAR_CWORD_CVAR , /* 5 */
2806 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2807 CSPCL_CWORD_CWORD_CLP , /* 7 */
2808 CSPCL_CWORD_CWORD_CRP , /* 8 */
2809 CBACK_CBACK_CCTL_CBACK , /* 9 */
2810 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2811 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2812 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2813 CWORD_CWORD_CWORD_CWORD , /* 13 */
2814 CCTL_CCTL_CCTL_CCTL , /* 14 */
2817 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2818 * caller must ensure proper cast on it if c is *char_ptr!
2820 /* Values for syntax param */
2821 #define BASESYNTAX 0 /* not in quotes */
2822 #define DQSYNTAX 1 /* in double quotes */
2823 #define SQSYNTAX 2 /* in single quotes */
2824 #define ARISYNTAX 3 /* in arithmetic */
2825 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2827 #if USE_SIT_FUNCTION
2830 SIT(int c, int syntax)
2832 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2833 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2835 * This causes '/' to be prepended with CTLESC in dquoted string,
2836 * making "./file"* treated incorrectly because we feed
2837 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2838 * The "homegrown" glob implementation is okay with that,
2839 * but glibc one isn't. With '/' always treated as CWORD,
2842 # if ENABLE_ASH_ALIAS
2843 static const uint8_t syntax_index_table[] ALIGN1 = {
2844 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2845 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2846 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2850 static const uint8_t syntax_index_table[] ALIGN1 = {
2851 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2852 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2853 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2862 # if ENABLE_ASH_ALIAS
2868 /* Cast is purely for paranoia here,
2869 * just in case someone passed signed char to us */
2870 if ((unsigned char)c >= CTL_FIRST
2871 && (unsigned char)c <= CTL_LAST
2875 s = strchrnul(spec_symbls, c);
2878 indx = syntax_index_table[s - spec_symbls];
2880 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2883 #else /* !USE_SIT_FUNCTION */
2885 static const uint8_t syntax_index_table[] ALIGN1 = {
2886 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2887 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2897 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2898 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2920 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2921 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2922 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2924 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2926 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2927 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2928 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2929 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2930 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2932 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2933 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2934 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2935 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2947 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2948 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2949 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2950 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2951 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2952 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2980 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2981 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2982 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2985 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3006 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3007 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3008 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3009 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3010 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3011 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3012 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3013 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3014 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3015 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3016 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3018 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3019 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3020 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3021 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3022 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3023 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3024 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3025 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3120 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3121 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3122 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3123 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3124 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3125 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3126 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3127 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3128 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3129 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3130 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3131 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3132 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3133 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3134 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3135 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3136 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3137 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3138 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3139 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3140 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3141 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3142 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3143 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3144 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3145 # if ENABLE_ASH_ALIAS
3146 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3150 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3152 #endif /* !USE_SIT_FUNCTION */
3155 /* ============ Alias handling */
3157 #if ENABLE_ASH_ALIAS
3159 #define ALIASINUSE 1
3170 static struct alias **atab; // [ATABSIZE];
3171 #define INIT_G_alias() do { \
3172 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3176 static struct alias **
3177 __lookupalias(const char *name)
3179 unsigned int hashval;
3186 ch = (unsigned char)*p;
3190 ch = (unsigned char)*++p;
3192 app = &atab[hashval % ATABSIZE];
3194 for (; *app; app = &(*app)->next) {
3195 if (strcmp(name, (*app)->name) == 0) {
3203 static struct alias *
3204 lookupalias(const char *name, int check)
3206 struct alias *ap = *__lookupalias(name);
3208 if (check && ap && (ap->flag & ALIASINUSE))
3213 static struct alias *
3214 freealias(struct alias *ap)
3218 if (ap->flag & ALIASINUSE) {
3219 ap->flag |= ALIASDEAD;
3231 setalias(const char *name, const char *val)
3233 struct alias *ap, **app;
3235 app = __lookupalias(name);
3239 if (!(ap->flag & ALIASINUSE)) {
3242 ap->val = ckstrdup(val);
3243 ap->flag &= ~ALIASDEAD;
3246 ap = ckzalloc(sizeof(struct alias));
3247 ap->name = ckstrdup(name);
3248 ap->val = ckstrdup(val);
3249 /*ap->flag = 0; - ckzalloc did it */
3250 /*ap->next = NULL;*/
3257 unalias(const char *name)
3261 app = __lookupalias(name);
3265 *app = freealias(*app);
3276 struct alias *ap, **app;
3280 for (i = 0; i < ATABSIZE; i++) {
3282 for (ap = *app; ap; ap = *app) {
3283 *app = freealias(*app);
3293 printalias(const struct alias *ap)
3295 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3299 * TODO - sort output
3301 static int FAST_FUNC
3302 aliascmd(int argc UNUSED_PARAM, char **argv)
3311 for (i = 0; i < ATABSIZE; i++) {
3312 for (ap = atab[i]; ap; ap = ap->next) {
3318 while ((n = *++argv) != NULL) {
3319 v = strchr(n+1, '=');
3320 if (v == NULL) { /* n+1: funny ksh stuff */
3321 ap = *__lookupalias(n);
3323 fprintf(stderr, "%s: %s not found\n", "alias", n);
3336 static int FAST_FUNC
3337 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3341 while ((i = nextopt("a")) != '\0') {
3347 for (i = 0; *argptr; argptr++) {
3348 if (unalias(*argptr)) {
3349 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3357 #endif /* ASH_ALIAS */
3360 /* ============ jobs.c */
3362 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3365 #define FORK_NOJOB 2
3367 /* mode flags for showjob(s) */
3368 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3369 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3370 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3371 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3374 * A job structure contains information about a job. A job is either a
3375 * single process or a set of processes contained in a pipeline. In the
3376 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3380 pid_t ps_pid; /* process id */
3381 int ps_status; /* last process status from wait() */
3382 char *ps_cmd; /* text of command being run */
3386 struct procstat ps0; /* status of process */
3387 struct procstat *ps; /* status or processes when more than one */
3389 int stopstatus; /* status of a stopped job */
3392 nprocs: 16, /* number of processes */
3394 #define JOBRUNNING 0 /* at least one proc running */
3395 #define JOBSTOPPED 1 /* all procs are stopped */
3396 #define JOBDONE 2 /* all procs are completed */
3398 sigint: 1, /* job was killed by SIGINT */
3399 jobctl: 1, /* job running under job control */
3401 waited: 1, /* true if this entry has been waited for */
3402 used: 1, /* true if this entry is in used */
3403 changed: 1; /* true if status has changed */
3404 struct job *prev_job; /* previous job */
3407 static struct job *makejob(/*union node *,*/ int);
3408 static int forkshell(struct job *, union node *, int);
3409 static int waitforjob(struct job *);
3412 enum { doing_jobctl = 0 };
3413 #define setjobctl(on) do {} while (0)
3415 static smallint doing_jobctl; //references:8
3416 static void setjobctl(int);
3423 ignoresig(int signo)
3425 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3426 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3427 /* No, need to do it */
3428 signal(signo, SIG_IGN);
3430 sigmode[signo - 1] = S_HARD_IGN;
3434 * Only one usage site - in setsignal()
3437 signal_handler(int signo)
3439 gotsig[signo - 1] = 1;
3441 if (signo == SIGINT && !trap[SIGINT]) {
3442 if (!suppress_int) {
3444 raise_interrupt(); /* does not return */
3448 pending_sig = signo;
3453 * Set the signal handler for the specified signal. The routine figures
3454 * out what it should be set to.
3457 setsignal(int signo)
3460 char cur_act, new_act;
3461 struct sigaction act;
3465 if (t != NULL) { /* trap for this sig is set */
3467 if (t[0] == '\0') /* trap is "": ignore this sig */
3471 if (rootshell && new_act == S_DFL) {
3474 if (iflag || minusc || sflag == 0)
3483 * "In all cases, bash ignores SIGQUIT. Non-builtin
3484 * commands run by bash have signal handlers
3485 * set to the values inherited by the shell
3486 * from its parent". */
3502 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3503 //whereas we have to restore it to what shell got on entry
3504 //from the parent. See comment above
3506 t = &sigmode[signo - 1];
3509 /* current setting is not yet known */
3510 if (sigaction(signo, NULL, &act)) {
3511 /* pretend it worked; maybe we should give a warning,
3512 * but other shells don't. We don't alter sigmode,
3513 * so we retry every time.
3514 * btw, in Linux it never fails. --vda */
3517 if (act.sa_handler == SIG_IGN) {
3518 cur_act = S_HARD_IGN;
3520 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3522 cur_act = S_IGN; /* don't hard ignore these */
3526 if (cur_act == S_HARD_IGN || cur_act == new_act)
3529 act.sa_handler = SIG_DFL;
3532 act.sa_handler = signal_handler;
3535 act.sa_handler = SIG_IGN;
3539 /* flags and mask matter only if !DFL and !IGN, but we do it
3540 * for all cases for more deterministic behavior:
3543 sigfillset(&act.sa_mask);
3545 sigaction_set(signo, &act);
3550 /* mode flags for set_curjob */
3551 #define CUR_DELETE 2
3552 #define CUR_RUNNING 1
3553 #define CUR_STOPPED 0
3555 /* mode flags for dowait */
3556 #define DOWAIT_NONBLOCK WNOHANG
3557 #define DOWAIT_BLOCK 0
3560 /* pgrp of shell on invocation */
3561 static int initialpgrp; //references:2
3562 static int ttyfd = -1; //5
3565 static struct job *jobtab; //5
3567 static unsigned njobs; //4
3569 static struct job *curjob; //lots
3570 /* number of presumed living untracked jobs */
3571 static int jobless; //4
3574 set_curjob(struct job *jp, unsigned mode)
3577 struct job **jpp, **curp;
3579 /* first remove from list */
3580 jpp = curp = &curjob;
3585 jpp = &jp1->prev_job;
3587 *jpp = jp1->prev_job;
3589 /* Then re-insert in correct position */
3597 /* job being deleted */
3600 /* newly created job or backgrounded job,
3601 * put after all stopped jobs.
3606 if (!jp1 || jp1->state != JOBSTOPPED)
3609 jpp = &jp1->prev_job;
3615 /* newly stopped job - becomes curjob */
3616 jp->prev_job = *jpp;
3624 jobno(const struct job *jp)
3626 return jp - jobtab + 1;
3631 * Convert a job name to a job structure.
3634 #define getjob(name, getctl) getjob(name)
3637 getjob(const char *name, int getctl)
3641 const char *err_msg = "%s: no such job";
3645 char *(*match)(const char *, const char *);
3660 if (c == '+' || c == '%') {
3662 err_msg = "No current job";
3668 err_msg = "No previous job";
3678 if (num > 0 && num <= njobs) {
3679 jp = jobtab + num - 1;
3694 if (match(jp->ps[0].ps_cmd, p)) {
3698 err_msg = "%s: ambiguous";
3708 err_msg = "job %s not created under job control";
3709 if (getctl && jp->jobctl == 0)
3714 ash_msg_and_raise_error(err_msg, name);
3718 * Mark a job structure as unused.
3721 freejob(struct job *jp)
3723 struct procstat *ps;
3727 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3728 if (ps->ps_cmd != nullstr)
3731 if (jp->ps != &jp->ps0)
3734 set_curjob(jp, CUR_DELETE);
3740 xtcsetpgrp(int fd, pid_t pgrp)
3742 if (tcsetpgrp(fd, pgrp))
3743 ash_msg_and_raise_error("can't set tty process group (%m)");
3747 * Turn job control on and off.
3749 * Note: This code assumes that the third arg to ioctl is a character
3750 * pointer, which is true on Berkeley systems but not System V. Since
3751 * System V doesn't have job control yet, this isn't a problem now.
3753 * Called with interrupts off.
3761 if (on == doing_jobctl || rootshell == 0)
3765 ofd = fd = open(_PATH_TTY, O_RDWR);
3767 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3768 * That sometimes helps to acquire controlling tty.
3769 * Obviously, a workaround for bugs when someone
3770 * failed to provide a controlling tty to bash! :) */
3776 fd = fcntl(fd, F_DUPFD, 10);
3781 /* fd is a tty at this point */
3782 close_on_exec_on(fd);
3783 while (1) { /* while we are in the background */
3784 pgrp = tcgetpgrp(fd);
3787 ash_msg("can't access tty; job control turned off");
3791 if (pgrp == getpgrp())
3802 xtcsetpgrp(fd, pgrp);
3804 /* turning job control off */
3807 /* was xtcsetpgrp, but this can make exiting ash
3808 * loop forever if pty is already deleted */
3809 tcsetpgrp(fd, pgrp);
3823 static int FAST_FUNC
3824 killcmd(int argc, char **argv)
3826 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3829 if (argv[i][0] == '%') {
3831 * "kill %N" - job kill
3832 * Converting to pgrp / pid kill
3838 jp = getjob(argv[i], 0);
3840 * In jobs started under job control, we signal
3841 * entire process group by kill -PGRP_ID.
3842 * This happens, f.e., in interactive shell.
3844 * Otherwise, we signal each child via
3845 * kill PID1 PID2 PID3.
3847 * sh -c 'sleep 1|sleep 1 & kill %1'
3848 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3849 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3851 n = jp->nprocs; /* can't be 0 (I hope) */
3854 dst = alloca(n * sizeof(int)*4);
3856 for (j = 0; j < n; j++) {
3857 struct procstat *ps = &jp->ps[j];
3858 /* Skip non-running and not-stopped members
3859 * (i.e. dead members) of the job
3861 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3864 * kill_main has matching code to expect
3865 * leading space. Needed to not confuse
3866 * negative pids with "kill -SIGNAL_NO" syntax
3868 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3872 } while (argv[++i]);
3874 return kill_main(argc, argv);
3878 showpipe(struct job *jp /*, FILE *out*/)
3880 struct procstat *ps;
3881 struct procstat *psend;
3883 psend = jp->ps + jp->nprocs;
3884 for (ps = jp->ps + 1; ps < psend; ps++)
3885 printf(" | %s", ps->ps_cmd);
3886 newline_and_flush(stdout);
3887 flush_stdout_stderr();
3892 restartjob(struct job *jp, int mode)
3894 struct procstat *ps;
3900 if (jp->state == JOBDONE)
3902 jp->state = JOBRUNNING;
3903 pgid = jp->ps[0].ps_pid;
3904 if (mode == FORK_FG)
3905 xtcsetpgrp(ttyfd, pgid);
3906 killpg(pgid, SIGCONT);
3910 if (WIFSTOPPED(ps->ps_status)) {
3916 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3921 static int FAST_FUNC
3922 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3928 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3932 jp = getjob(*argv, 1);
3933 if (mode == FORK_BG) {
3934 set_curjob(jp, CUR_RUNNING);
3935 printf("[%d] ", jobno(jp));
3937 out1str(jp->ps[0].ps_cmd);
3938 showpipe(jp /*, stdout*/);
3939 retval = restartjob(jp, mode);
3940 } while (*argv && *++argv);
3946 sprint_status48(char *s, int status, int sigonly)
3952 if (!WIFEXITED(status)) {
3953 if (JOBS && WIFSTOPPED(status))
3954 st = WSTOPSIG(status);
3956 st = WTERMSIG(status);
3958 if (st == SIGINT || st == SIGPIPE)
3960 if (JOBS && WIFSTOPPED(status))
3964 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3965 col = fmtstr(s, 32, strsignal(st));
3966 if (WCOREDUMP(status)) {
3967 strcpy(s + col, " (core dumped)");
3968 col += sizeof(" (core dumped)")-1;
3970 } else if (!sigonly) {
3971 st = WEXITSTATUS(status);
3972 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
3979 dowait(int wait_flags, struct job *job)
3984 struct job *thisjob;
3986 TRACE(("dowait(0x%x) called\n", wait_flags));
3988 /* Do a wait system call. If job control is compiled in, we accept
3989 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3990 * NB: _not_ safe_waitpid, we need to detect EINTR */
3992 wait_flags |= WUNTRACED;
3993 pid = waitpid(-1, &status, wait_flags);
3994 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3995 pid, status, errno, strerror(errno)));
4001 for (jp = curjob; jp; jp = jp->prev_job) {
4003 struct procstat *ps;
4004 struct procstat *psend;
4005 if (jp->state == JOBDONE)
4009 psend = ps + jp->nprocs;
4011 if (ps->ps_pid == pid) {
4012 TRACE(("Job %d: changing status of proc %d "
4013 "from 0x%x to 0x%x\n",
4014 jobno(jp), pid, ps->ps_status, status));
4015 ps->ps_status = status;
4018 if (ps->ps_status == -1)
4019 jobstate = JOBRUNNING;
4021 if (jobstate == JOBRUNNING)
4023 if (WIFSTOPPED(ps->ps_status)) {
4024 jp->stopstatus = ps->ps_status;
4025 jobstate = JOBSTOPPED;
4028 } while (++ps < psend);
4032 /* Found the job where one of its processes changed its state.
4033 * Is there at least one live and running process in this job? */
4034 if (jobstate != JOBRUNNING) {
4035 /* No. All live processes in the job are stopped
4036 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4038 thisjob->changed = 1;
4039 if (thisjob->state != jobstate) {
4040 TRACE(("Job %d: changing state from %d to %d\n",
4041 jobno(thisjob), thisjob->state, jobstate));
4042 thisjob->state = jobstate;
4044 if (jobstate == JOBSTOPPED)
4045 set_curjob(thisjob, CUR_STOPPED);
4051 /* The process wasn't found in job list */
4052 if (JOBS && !WIFSTOPPED(status))
4057 if (thisjob && thisjob == job) {
4061 len = sprint_status48(s, status, 1);
4072 blocking_wait_with_raise_on_sig(void)
4074 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
4075 if (pid <= 0 && pending_sig)
4076 raise_exception(EXSIG);
4082 showjob(struct job *jp, int mode)
4084 struct procstat *ps;
4085 struct procstat *psend;
4088 char s[16 + 16 + 48];
4089 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4093 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4094 /* just output process (group) id of pipeline */
4095 fprintf(out, "%d\n", ps->ps_pid);
4099 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4104 else if (curjob && jp == curjob->prev_job)
4107 if (mode & SHOW_PIDS)
4108 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4110 psend = ps + jp->nprocs;
4112 if (jp->state == JOBRUNNING) {
4113 strcpy(s + col, "Running");
4114 col += sizeof("Running") - 1;
4116 int status = psend[-1].ps_status;
4117 if (jp->state == JOBSTOPPED)
4118 status = jp->stopstatus;
4119 col += sprint_status48(s + col, status, 0);
4121 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4123 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4124 * or prints several "PID | <cmdN>" lines,
4125 * depending on SHOW_PIDS bit.
4126 * We do not print status of individual processes
4127 * between PID and <cmdN>. bash does it, but not very well:
4128 * first line shows overall job status, not process status,
4129 * making it impossible to know 1st process status.
4133 /* for each process */
4136 if (mode & SHOW_PIDS)
4137 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4139 fprintf(out, "%s%*c%s%s",
4141 33 - col >= 0 ? 33 - col : 0, ' ',
4142 ps == jp->ps ? "" : "| ",
4145 } while (++ps != psend);
4146 newline_and_flush(out);
4150 if (jp->state == JOBDONE) {
4151 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4157 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4158 * statuses have changed since the last call to showjobs.
4165 TRACE(("showjobs(0x%x) called\n", mode));
4167 /* Handle all finished jobs */
4168 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4171 for (jp = curjob; jp; jp = jp->prev_job) {
4172 if (!(mode & SHOW_CHANGED) || jp->changed) {
4178 static int FAST_FUNC
4179 jobscmd(int argc UNUSED_PARAM, char **argv)
4184 while ((m = nextopt("lp")) != '\0') {
4188 mode |= SHOW_ONLY_PGID;
4194 showjob(getjob(*argv, 0), mode);
4204 /* Called only on finished or stopped jobs (no members are running) */
4206 getstatus(struct job *job)
4210 struct procstat *ps;
4212 /* Fetch last member's status */
4213 ps = job->ps + job->nprocs - 1;
4214 status = ps->ps_status;
4216 /* "set -o pipefail" mode: use last _nonzero_ status */
4217 while (status == 0 && --ps >= job->ps)
4218 status = ps->ps_status;
4221 retval = WEXITSTATUS(status);
4222 if (!WIFEXITED(status)) {
4224 retval = WSTOPSIG(status);
4225 if (!WIFSTOPPED(status))
4228 /* XXX: limits number of signals */
4229 retval = WTERMSIG(status);
4231 if (retval == SIGINT)
4237 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4238 jobno(job), job->nprocs, status, retval));
4242 static int FAST_FUNC
4243 waitcmd(int argc UNUSED_PARAM, char **argv)
4250 raise_exception(EXSIG);
4257 /* wait for all jobs */
4261 if (!jp) /* no running procs */
4263 if (jp->state == JOBRUNNING)
4268 blocking_wait_with_raise_on_sig();
4270 * "When bash is waiting for an asynchronous command via
4271 * the wait builtin, the reception of a signal for which a trap
4272 * has been set will cause the wait builtin to return immediately
4273 * with an exit status greater than 128, immediately after which
4274 * the trap is executed."
4276 * blocking_wait_with_raise_on_sig raises signal handlers
4277 * if it gets no pid (pid < 0). However,
4278 * if child sends us a signal *and immediately exits*,
4279 * blocking_wait_with_raise_on_sig gets pid > 0
4280 * and does not handle pending_sig. Check this case: */
4282 raise_exception(EXSIG);
4288 if (**argv != '%') {
4289 pid_t pid = number(*argv);
4294 if (job->ps[job->nprocs - 1].ps_pid == pid)
4296 job = job->prev_job;
4299 job = getjob(*argv, 0);
4301 /* loop until process terminated or stopped */
4302 while (job->state == JOBRUNNING)
4303 blocking_wait_with_raise_on_sig();
4305 retval = getstatus(job);
4318 struct job *jp, *jq;
4320 len = njobs * sizeof(*jp);
4322 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4324 offset = (char *)jp - (char *)jq;
4326 /* Relocate pointers */
4329 jq = (struct job *)((char *)jq + l);
4333 #define joff(p) ((struct job *)((char *)(p) + l))
4334 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4335 if (joff(jp)->ps == &jq->ps0)
4336 jmove(joff(jp)->ps);
4337 if (joff(jp)->prev_job)
4338 jmove(joff(jp)->prev_job);
4348 jp = (struct job *)((char *)jp + len);
4352 } while (--jq >= jp);
4357 * Return a new job structure.
4358 * Called with interrupts off.
4361 makejob(/*union node *node,*/ int nprocs)
4366 for (i = njobs, jp = jobtab; ; jp++) {
4373 if (jp->state != JOBDONE || !jp->waited)
4382 memset(jp, 0, sizeof(*jp));
4384 /* jp->jobctl is a bitfield.
4385 * "jp->jobctl |= jobctl" likely to give awful code */
4389 jp->prev_job = curjob;
4394 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4396 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4403 * Return a string identifying a command (to be printed by the
4406 static char *cmdnextc;
4409 cmdputs(const char *s)
4411 static const char vstype[VSTYPE + 1][3] = {
4412 "", "}", "-", "+", "?", "=",
4413 "%", "%%", "#", "##"
4414 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4417 const char *p, *str;
4421 unsigned char subtype = 0;
4425 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4427 while ((c = *p++) != '\0') {
4435 if ((subtype & VSTYPE) == VSLENGTH)
4441 str = "\"}" + !(quoted & 1);
4448 #if ENABLE_SH_MATH_SUPPORT
4463 if ((subtype & VSTYPE) != VSNORMAL)
4465 str = vstype[subtype & VSTYPE];
4466 if (subtype & VSNUL)
4475 /* These can only happen inside quotes */
4488 while ((c = *str++) != '\0') {
4491 } /* while *p++ not NUL */
4494 USTPUTC('"', nextc);
4500 /* cmdtxt() and cmdlist() call each other */
4501 static void cmdtxt(union node *n);
4504 cmdlist(union node *np, int sep)
4506 for (; np; np = np->narg.next) {
4510 if (sep && np->narg.next)
4516 cmdtxt(union node *n)
4519 struct nodelist *lp;
4530 lp = n->npipe.cmdlist;
4548 cmdtxt(n->nbinary.ch1);
4564 cmdtxt(n->nif.test);
4566 if (n->nif.elsepart) {
4567 cmdtxt(n->nif.ifpart);
4569 n = n->nif.elsepart;
4587 cmdtxt(n->nbinary.ch1);
4597 cmdputs(n->nfor.var);
4599 cmdlist(n->nfor.args, 1);
4604 cmdputs(n->narg.text);
4608 cmdlist(n->ncmd.args, 1);
4609 cmdlist(n->ncmd.redirect, 0);
4622 cmdputs(n->ncase.expr->narg.text);
4624 for (np = n->ncase.cases; np; np = np->nclist.next) {
4625 cmdtxt(np->nclist.pattern);
4627 cmdtxt(np->nclist.body);
4641 #if ENABLE_ASH_BASH_COMPAT
4656 cmdputs(utoa(n->nfile.fd));
4658 if (n->type == NTOFD || n->type == NFROMFD) {
4659 cmdputs(utoa(n->ndup.dupfd));
4668 commandtext(union node *n)
4672 STARTSTACKSTR(cmdnextc);
4674 name = stackblock();
4675 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4676 name, cmdnextc, cmdnextc));
4677 return ckstrdup(name);
4682 * Fork off a subshell. If we are doing job control, give the subshell its
4683 * own process group. Jp is a job structure that the job is to be added to.
4684 * N is the command that will be evaluated by the child. Both jp and n may
4685 * be NULL. The mode parameter can be one of the following:
4686 * FORK_FG - Fork off a foreground process.
4687 * FORK_BG - Fork off a background process.
4688 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4689 * process group even if job control is on.
4691 * When job control is turned off, background processes have their standard
4692 * input redirected to /dev/null (except for the second and later processes
4695 * Called with interrupts off.
4698 * Clear traps on a fork.
4705 for (tp = trap; tp < &trap[NSIG]; tp++) {
4706 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4708 if (trap_ptr == trap)
4710 /* else: it "belongs" to trap_ptr vector, don't free */
4712 if ((tp - trap) != 0)
4713 setsignal(tp - trap);
4720 /* Lives far away from here, needed for forkchild */
4721 static void closescript(void);
4723 /* Called after fork(), in child */
4724 static NOINLINE void
4725 forkchild(struct job *jp, union node *n, int mode)
4729 TRACE(("Child shell %d\n", getpid()));
4733 /* man bash: "Non-builtin commands run by bash have signal handlers
4734 * set to the values inherited by the shell from its parent".
4735 * Do we do it correctly? */
4739 if (mode == FORK_NOJOB /* is it `xxx` ? */
4740 && n && n->type == NCMD /* is it single cmd? */
4741 /* && n->ncmd.args->type == NARG - always true? */
4742 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4743 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4744 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4746 TRACE(("Trap hack\n"));
4747 /* Awful hack for `trap` or $(trap).
4749 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4750 * contains an example where "trap" is executed in a subshell:
4752 * save_traps=$(trap)
4754 * eval "$save_traps"
4756 * Standard does not say that "trap" in subshell shall print
4757 * parent shell's traps. It only says that its output
4758 * must have suitable form, but then, in the above example
4759 * (which is not supposed to be normative), it implies that.
4761 * bash (and probably other shell) does implement it
4762 * (traps are reset to defaults, but "trap" still shows them),
4763 * but as a result, "trap" logic is hopelessly messed up:
4766 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4767 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4768 * # true | trap <--- trap is in subshell - no output (ditto)
4769 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4770 * trap -- 'echo Ho' SIGWINCH
4771 * # echo `(trap)` <--- in subshell in subshell - output
4772 * trap -- 'echo Ho' SIGWINCH
4773 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4774 * trap -- 'echo Ho' SIGWINCH
4776 * The rules when to forget and when to not forget traps
4777 * get really complex and nonsensical.
4779 * Our solution: ONLY bare $(trap) or `trap` is special.
4781 /* Save trap handler strings for trap builtin to print */
4782 trap_ptr = xmemdup(trap, sizeof(trap));
4783 /* Fall through into clearing traps */
4787 /* do job control only in root shell */
4789 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4792 if (jp->nprocs == 0)
4795 pgrp = jp->ps[0].ps_pid;
4796 /* this can fail because we are doing it in the parent also */
4798 if (mode == FORK_FG)
4799 xtcsetpgrp(ttyfd, pgrp);
4804 if (mode == FORK_BG) {
4805 /* man bash: "When job control is not in effect,
4806 * asynchronous commands ignore SIGINT and SIGQUIT" */
4809 if (jp->nprocs == 0) {
4811 if (open(bb_dev_null, O_RDONLY) != 0)
4812 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4816 if (iflag) { /* why if iflag only? */
4821 * "In all cases, bash ignores SIGQUIT. Non-builtin
4822 * commands run by bash have signal handlers
4823 * set to the values inherited by the shell
4825 * Take care of the second rule: */
4829 if (n && n->type == NCMD
4830 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4832 TRACE(("Job hack\n"));
4833 /* "jobs": we do not want to clear job list for it,
4834 * instead we remove only _its_ own_ job from job list.
4835 * This makes "jobs .... | cat" more useful.
4841 for (jp = curjob; jp; jp = jp->prev_job)
4846 /* Called after fork(), in parent */
4848 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4851 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4853 TRACE(("In parent shell: child = %d\n", pid));
4855 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4861 if (mode != FORK_NOJOB && jp->jobctl) {
4864 if (jp->nprocs == 0)
4867 pgrp = jp->ps[0].ps_pid;
4868 /* This can fail because we are doing it in the child also */
4872 if (mode == FORK_BG) {
4873 backgndpid = pid; /* set $! */
4874 set_curjob(jp, CUR_RUNNING);
4877 struct procstat *ps = &jp->ps[jp->nprocs++];
4880 ps->ps_cmd = nullstr;
4882 if (doing_jobctl && n)
4883 ps->ps_cmd = commandtext(n);
4889 forkshell(struct job *jp, union node *n, int mode)
4893 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4896 TRACE(("Fork failed, errno=%d", errno));
4899 ash_msg_and_raise_error("can't fork");
4902 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4903 forkchild(jp, n, mode);
4905 forkparent(jp, n, mode, pid);
4911 * Wait for job to finish.
4913 * Under job control we have the problem that while a child process
4914 * is running interrupts generated by the user are sent to the child
4915 * but not to the shell. This means that an infinite loop started by
4916 * an interactive user may be hard to kill. With job control turned off,
4917 * an interactive user may place an interactive program inside a loop.
4918 * If the interactive program catches interrupts, the user doesn't want
4919 * these interrupts to also abort the loop. The approach we take here
4920 * is to have the shell ignore interrupt signals while waiting for a
4921 * foreground process to terminate, and then send itself an interrupt
4922 * signal if the child process was terminated by an interrupt signal.
4923 * Unfortunately, some programs want to do a bit of cleanup and then
4924 * exit on interrupt; unless these processes terminate themselves by
4925 * sending a signal to themselves (instead of calling exit) they will
4926 * confuse this approach.
4928 * Called with interrupts off.
4931 waitforjob(struct job *jp)
4935 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4938 while (jp->state == JOBRUNNING) {
4939 /* In non-interactive shells, we _can_ get
4940 * a keyboard signal here and be EINTRed,
4941 * but we just loop back, waiting for command to complete.
4944 * "If bash is waiting for a command to complete and receives
4945 * a signal for which a trap has been set, the trap
4946 * will not be executed until the command completes."
4948 * Reality is that even if trap is not set, bash
4949 * will not act on the signal until command completes.
4950 * Try this. sleep5intoff.c:
4951 * #include <signal.h>
4952 * #include <unistd.h>
4955 * sigemptyset(&set);
4956 * sigaddset(&set, SIGINT);
4957 * sigaddset(&set, SIGQUIT);
4958 * sigprocmask(SIG_BLOCK, &set, NULL);
4962 * $ bash -c './sleep5intoff; echo hi'
4963 * ^C^C^C^C <--- pressing ^C once a second
4965 * $ bash -c './sleep5intoff; echo hi'
4966 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4969 dowait(DOWAIT_BLOCK, jp);
4976 xtcsetpgrp(ttyfd, rootpid);
4978 * This is truly gross.
4979 * If we're doing job control, then we did a TIOCSPGRP which
4980 * caused us (the shell) to no longer be in the controlling
4981 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4982 * intuit from the subprocess exit status whether a SIGINT
4983 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4985 if (jp->sigint) /* TODO: do the same with all signals */
4986 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4988 if (jp->state == JOBDONE)
4995 * return 1 if there are stopped jobs, otherwise 0
5007 if (jp && jp->state == JOBSTOPPED) {
5008 out2str("You have stopped jobs.\n");
5017 /* ============ redir.c
5019 * Code for dealing with input/output redirection.
5024 #define EMPTY -2 /* marks an unused slot in redirtab */
5025 #define CLOSED -3 /* marks a slot of previously-closed fd */
5028 * Open a file in noclobber mode.
5029 * The code was copied from bash.
5032 noclobberopen(const char *fname)
5035 struct stat finfo, finfo2;
5038 * If the file exists and is a regular file, return an error
5041 r = stat(fname, &finfo);
5042 if (r == 0 && S_ISREG(finfo.st_mode)) {
5048 * If the file was not present (r != 0), make sure we open it
5049 * exclusively so that if it is created before we open it, our open
5050 * will fail. Make sure that we do not truncate an existing file.
5051 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5052 * file was not a regular file, we leave O_EXCL off.
5055 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5056 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5058 /* If the open failed, return the file descriptor right away. */
5063 * OK, the open succeeded, but the file may have been changed from a
5064 * non-regular file to a regular file between the stat and the open.
5065 * We are assuming that the O_EXCL open handles the case where FILENAME
5066 * did not exist and is symlinked to an existing file between the stat
5071 * If we can open it and fstat the file descriptor, and neither check
5072 * revealed that it was a regular file, and the file has not been
5073 * replaced, return the file descriptor.
5075 if (fstat(fd, &finfo2) == 0
5076 && !S_ISREG(finfo2.st_mode)
5077 && finfo.st_dev == finfo2.st_dev
5078 && finfo.st_ino == finfo2.st_ino
5083 /* The file has been replaced. badness. */
5090 * Handle here documents. Normally we fork off a process to write the
5091 * data to a pipe. If the document is short, we can stuff the data in
5092 * the pipe without forking.
5094 /* openhere needs this forward reference */
5095 static void expandhere(union node *arg, int fd);
5097 openhere(union node *redir)
5103 ash_msg_and_raise_error("pipe call failed");
5104 if (redir->type == NHERE) {
5105 len = strlen(redir->nhere.doc->narg.text);
5106 if (len <= PIPE_BUF) {
5107 full_write(pip[1], redir->nhere.doc->narg.text, len);
5111 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5114 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5115 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5116 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5117 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5118 signal(SIGPIPE, SIG_DFL);
5119 if (redir->type == NHERE)
5120 full_write(pip[1], redir->nhere.doc->narg.text, len);
5122 expandhere(redir->nhere.doc, pip[1]);
5123 _exit(EXIT_SUCCESS);
5131 openredirect(union node *redir)
5136 switch (redir->nfile.type) {
5137 /* Can't happen, our single caller does this itself */
5143 return openhere(redir);
5146 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5147 * allocated space. Do it only when we know it is safe.
5149 fname = redir->nfile.expfname;
5151 switch (redir->nfile.type) {
5157 f = open(fname, O_RDONLY);
5162 f = open(fname, O_RDWR|O_CREAT, 0666);
5167 #if ENABLE_ASH_BASH_COMPAT
5170 /* Take care of noclobber mode. */
5172 f = noclobberopen(fname);
5179 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5184 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5192 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5194 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5198 * Copy a file descriptor to be >= to. Returns -1
5199 * if the source file descriptor is closed, EMPTY if there are no unused
5200 * file descriptors left.
5202 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5203 * old code was doing close(to) prior to copyfd() to achieve the same */
5205 COPYFD_EXACT = (int)~(INT_MAX),
5206 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5209 copyfd(int from, int to)
5213 if (to & COPYFD_EXACT) {
5214 to &= ~COPYFD_EXACT;
5216 newfd = dup2(from, to);
5218 newfd = fcntl(from, F_DUPFD, to);
5221 if (errno == EMFILE)
5223 /* Happens when source fd is not open: try "echo >&99" */
5224 ash_msg_and_raise_error("%d: %m", from);
5229 /* Struct def and variable are moved down to the first usage site */
5234 struct redirtab *next;
5237 struct two_fd_t two_fd[];
5239 #define redirlist (G_var.redirlist)
5242 need_to_remember(struct redirtab *rp, int fd)
5246 if (!rp) /* remembering was not requested */
5249 for (i = 0; i < rp->pair_count; i++) {
5250 if (rp->two_fd[i].orig == fd) {
5251 /* already remembered */
5258 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5260 is_hidden_fd(struct redirtab *rp, int fd)
5263 struct parsefile *pf;
5267 /* Check open scripts' fds */
5270 /* We skip pf_fd == 0 case because of the following case:
5271 * $ ash # running ash interactively
5273 * and in script.sh: "exec 9>&0".
5274 * Even though top-level pf_fd _is_ 0,
5275 * it's still ok to use it: "read" builtin uses it,
5276 * why should we cripple "exec" builtin?
5278 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5286 /* Check saved fds of redirects */
5287 fd |= COPYFD_RESTORE;
5288 for (i = 0; i < rp->pair_count; i++) {
5289 if (rp->two_fd[i].copy == fd) {
5297 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5298 * old file descriptors are stashed away so that the redirection can be
5299 * undone by calling popredir.
5301 /* flags passed to redirect */
5302 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5303 #define REDIR_SAVEFD2 03 /* set preverrout */
5305 redirect(union node *redir, int flags)
5307 struct redirtab *sv;
5312 int copied_fd2 = -1;
5322 if (flags & REDIR_PUSH) {
5323 union node *tmp = redir;
5326 #if ENABLE_ASH_BASH_COMPAT
5327 if (tmp->nfile.type == NTO2)
5330 tmp = tmp->nfile.next;
5332 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5333 sv->next = redirlist;
5334 sv->pair_count = sv_pos;
5336 sv->nullredirs = g_nullredirs - 1;
5338 while (sv_pos > 0) {
5340 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5346 fd = redir->nfile.fd;
5347 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5348 right_fd = redir->ndup.dupfd;
5349 //bb_error_msg("doing %d > %d", fd, right_fd);
5350 /* redirect from/to same file descriptor? */
5353 /* "echo >&10" and 10 is a fd opened to a sh script? */
5354 if (is_hidden_fd(sv, right_fd)) {
5355 errno = EBADF; /* as if it is closed */
5356 ash_msg_and_raise_error("%d: %m", right_fd);
5360 newfd = openredirect(redir); /* always >= 0 */
5362 /* Descriptor wasn't open before redirect.
5363 * Mark it for close in the future */
5364 if (need_to_remember(sv, fd)) {
5365 goto remember_to_close;
5370 #if ENABLE_ASH_BASH_COMPAT
5373 if (need_to_remember(sv, fd)) {
5374 /* Copy old descriptor */
5375 /* Careful to not accidentally "save"
5376 * to the same fd as right side fd in N>&M */
5377 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5378 i = fcntl(fd, F_DUPFD, minfd);
5379 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5380 * are closed in popredir() in the child, preventing them from leaking
5381 * into child. (popredir() also cleans up the mess in case of failures)
5386 /* Strange error (e.g. "too many files" EMFILE?) */
5390 ash_msg_and_raise_error("%d: %m", fd);
5393 /* EBADF: it is not open - good, remember to close it */
5396 } else { /* fd is open, save its copy */
5397 /* "exec fd>&-" should not close fds
5398 * which point to script file(s).
5399 * Force them to be restored afterwards */
5400 if (is_hidden_fd(sv, fd))
5401 i |= COPYFD_RESTORE;
5405 sv->two_fd[sv_pos].orig = fd;
5406 sv->two_fd[sv_pos].copy = i;
5410 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5411 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5412 /* Don't want to trigger debugging */
5416 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5418 } else if (fd != newfd) { /* move newfd to fd */
5419 copyfd(newfd, fd | COPYFD_EXACT);
5420 #if ENABLE_ASH_BASH_COMPAT
5421 if (!(redir->nfile.type == NTO2 && fd == 2))
5425 #if ENABLE_ASH_BASH_COMPAT
5426 if (redir->nfile.type == NTO2 && fd == 1) {
5427 /* We already redirected it to fd 1, now copy it to 2 */
5433 } while ((redir = redir->nfile.next) != NULL);
5436 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5437 preverrout_fd = copied_fd2;
5441 * Undo the effects of the last redirection.
5444 popredir(int drop, int restore)
5446 struct redirtab *rp;
5449 if (--g_nullredirs >= 0 || redirlist == NULL)
5453 for (i = 0; i < rp->pair_count; i++) {
5454 int fd = rp->two_fd[i].orig;
5455 int copy = rp->two_fd[i].copy;
5456 if (copy == CLOSED) {
5461 if (copy != EMPTY) {
5462 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5463 copy &= ~COPYFD_RESTORE;
5465 copyfd(copy, fd | COPYFD_EXACT);
5467 close(copy & ~COPYFD_RESTORE);
5470 redirlist = rp->next;
5471 g_nullredirs = rp->nullredirs;
5477 * Undo all redirections. Called on error or interrupt.
5481 * Discard all saved file descriptors.
5484 clearredir(int drop)
5490 popredir(drop, /*restore:*/ 0);
5495 redirectsafe(union node *redir, int flags)
5498 volatile int saveint;
5499 struct jmploc *volatile savehandler = exception_handler;
5500 struct jmploc jmploc;
5503 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5504 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5506 exception_handler = &jmploc;
5507 redirect(redir, flags);
5509 exception_handler = savehandler;
5510 if (err && exception_type != EXERROR)
5511 longjmp(exception_handler->loc, 1);
5512 RESTORE_INT(saveint);
5517 /* ============ Routines to expand arguments to commands
5519 * We have to deal with backquotes, shell variables, and file metacharacters.
5522 #if ENABLE_SH_MATH_SUPPORT
5524 ash_arith(const char *s)
5526 arith_state_t math_state;
5529 math_state.lookupvar = lookupvar;
5530 math_state.setvar = setvar0;
5531 //math_state.endofname = endofname;
5534 result = arith(&math_state, s);
5535 if (math_state.errmsg)
5536 ash_msg_and_raise_error(math_state.errmsg);
5546 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5547 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5548 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5549 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5550 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5551 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5552 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5553 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5554 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5558 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5559 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5560 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5561 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5562 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5564 /* Add CTLESC when necessary. */
5565 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5566 /* Do not skip NUL characters. */
5567 #define QUOTES_KEEPNUL EXP_TILDE
5570 * Structure specifying which parts of the string should be searched
5571 * for IFS characters.
5574 struct ifsregion *next; /* next region in list */
5575 int begoff; /* offset of start of region */
5576 int endoff; /* offset of end of region */
5577 int nulonly; /* search for nul bytes only */
5581 struct strlist *list;
5582 struct strlist **lastp;
5585 /* output of current string */
5586 static char *expdest;
5587 /* list of back quote expressions */
5588 static struct nodelist *argbackq;
5589 /* first struct in list of ifs regions */
5590 static struct ifsregion ifsfirst;
5591 /* last struct in list */
5592 static struct ifsregion *ifslastp;
5593 /* holds expanded arg list */
5594 static struct arglist exparg;
5599 #if !ENABLE_SH_MATH_SUPPORT
5600 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5601 typedef long arith_t;
5602 # define ARITH_FMT "%ld"
5609 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5610 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5611 STADJUST(len, expdest);
5616 esclen(const char *start, const char *p)
5620 while (p > start && (unsigned char)*--p == CTLESC) {
5627 * Remove any CTLESC characters from a string.
5630 rmescapes(char *str, int flag)
5632 static const char qchars[] ALIGN1 = {
5633 IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
5637 unsigned protect_against_glob;
5639 IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
5641 p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
5647 if (flag & RMESCAPE_ALLOC) {
5648 size_t len = p - str;
5649 size_t fulllen = len + strlen(p) + 1;
5651 if (flag & RMESCAPE_GROW) {
5652 int strloc = str - (char *)stackblock();
5653 r = makestrspace(fulllen, expdest);
5654 /* p and str may be invalidated by makestrspace */
5655 str = (char *)stackblock() + strloc;
5657 } else if (flag & RMESCAPE_HEAP) {
5658 r = ckmalloc(fulllen);
5660 r = stalloc(fulllen);
5664 q = (char *)memcpy(q, str, len) + len;
5669 globbing = flag & RMESCAPE_GLOB;
5670 protect_against_glob = globbing;
5672 if ((unsigned char)*p == CTLQUOTEMARK) {
5673 // Note: both inquotes and protect_against_glob only affect whether
5674 inquotes = ~inquotes;
5676 protect_against_glob = globbing;
5679 if ((unsigned char)*p == CTLESC) {
5683 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5685 if (protect_against_glob) {
5688 } else if (*p == '\\' && !inquotes) {
5689 /* naked back slash */
5690 protect_against_glob = 0;
5693 #if ENABLE_ASH_BASH_COMPAT
5694 else if (*p == '/' && slash) {
5695 /* stop handling globbing and mark location of slash */
5696 globbing = slash = 0;
5700 protect_against_glob = globbing;
5705 if (flag & RMESCAPE_GROW) {
5707 STADJUST(q - r + 1, expdest);
5711 #define pmatch(a, b) !fnmatch((a), (b), 0)
5714 * Prepare a pattern for a expmeta (internal glob(3)) call.
5716 * Returns an stalloced string.
5719 preglob(const char *pattern, int flag)
5721 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5725 * Put a string on the stack.
5728 memtodest(const char *p, size_t len, int syntax, int quotes)
5735 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5738 unsigned char c = *p++;
5740 int n = SIT(c, syntax);
5741 if ((quotes & QUOTES_ESC)
5743 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
5749 } else if (!(quotes & QUOTES_KEEPNUL))
5758 strtodest(const char *p, int syntax, int quotes)
5760 size_t len = strlen(p);
5761 memtodest(p, len, syntax, quotes);
5766 * Record the fact that we have to scan this region of the
5767 * string for IFS characters.
5770 recordregion(int start, int end, int nulonly)
5772 struct ifsregion *ifsp;
5774 if (ifslastp == NULL) {
5778 ifsp = ckzalloc(sizeof(*ifsp));
5779 /*ifsp->next = NULL; - ckzalloc did it */
5780 ifslastp->next = ifsp;
5784 ifslastp->begoff = start;
5785 ifslastp->endoff = end;
5786 ifslastp->nulonly = nulonly;
5790 removerecordregions(int endoff)
5792 if (ifslastp == NULL)
5795 if (ifsfirst.endoff > endoff) {
5796 while (ifsfirst.next) {
5797 struct ifsregion *ifsp;
5799 ifsp = ifsfirst.next->next;
5800 free(ifsfirst.next);
5801 ifsfirst.next = ifsp;
5804 if (ifsfirst.begoff > endoff) {
5807 ifslastp = &ifsfirst;
5808 ifsfirst.endoff = endoff;
5813 ifslastp = &ifsfirst;
5814 while (ifslastp->next && ifslastp->next->begoff < endoff)
5815 ifslastp = ifslastp->next;
5816 while (ifslastp->next) {
5817 struct ifsregion *ifsp;
5819 ifsp = ifslastp->next->next;
5820 free(ifslastp->next);
5821 ifslastp->next = ifsp;
5824 if (ifslastp->endoff > endoff)
5825 ifslastp->endoff = endoff;
5829 exptilde(char *startp, char *p, int flags)
5835 int quotes = flags & QUOTES_ESC;
5839 while ((c = *++p) != '\0') {
5846 if (flags & EXP_VARTILDE)
5856 if (*name == '\0') {
5857 home = lookupvar("HOME");
5859 pw = getpwnam(name);
5864 if (!home || !*home)
5867 strtodest(home, SQSYNTAX, quotes);
5875 * Execute a command inside back quotes. If it's a builtin command, we
5876 * want to save its output in a block obtained from malloc. Otherwise
5877 * we fork off a subprocess and get the output of the command via a pipe.
5878 * Should be called with interrupts off.
5880 struct backcmd { /* result of evalbackcmd */
5881 int fd; /* file descriptor to read from */
5882 int nleft; /* number of chars in buffer */
5883 char *buf; /* buffer */
5884 struct job *jp; /* job structure for command */
5887 /* These forward decls are needed to use "eval" code for backticks handling: */
5888 #define EV_EXIT 01 /* exit after evaluating tree */
5889 static int evaltree(union node *, int);
5891 static void FAST_FUNC
5892 evalbackcmd(union node *n, struct backcmd *result)
5903 saveherefd = herefd;
5911 ash_msg_and_raise_error("pipe call failed");
5912 jp = makejob(/*n,*/ 1);
5913 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5918 copyfd(pip[1], 1 | COPYFD_EXACT);
5922 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5926 result->fd = pip[0];
5929 herefd = saveherefd;
5931 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5932 result->fd, result->buf, result->nleft, result->jp));
5936 * Expand stuff in backwards quotes.
5939 expbackq(union node *cmd, int flag)
5947 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
5948 struct stackmark smark;
5951 startloc = expdest - (char *)stackblock();
5952 pushstackmark(&smark, startloc);
5953 evalbackcmd(cmd, &in);
5954 popstackmark(&smark);
5961 memtodest(p, i, syntax, flag & QUOTES_ESC);
5965 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
5966 TRACE(("expbackq: read returns %d\n", i));
5975 back_exitstatus = waitforjob(in.jp);
5979 /* Eat all trailing newlines */
5981 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5985 if (!(flag & EXP_QUOTED))
5986 recordregion(startloc, dest - (char *)stackblock(), 0);
5987 TRACE(("evalbackq: size:%d:'%.*s'\n",
5988 (int)((dest - (char *)stackblock()) - startloc),
5989 (int)((dest - (char *)stackblock()) - startloc),
5990 stackblock() + startloc));
5993 #if ENABLE_SH_MATH_SUPPORT
5995 * Expand arithmetic expression. Backup to start of expression,
5996 * evaluate, place result in (backed up) result, adjust string position.
6008 * This routine is slightly over-complicated for
6009 * efficiency. Next we scan backwards looking for the
6010 * start of arithmetic.
6012 start = stackblock();
6019 while ((unsigned char)*p != CTLARI) {
6023 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6028 esc = esclen(start, p);
6038 removerecordregions(begoff);
6042 if (flag & QUOTES_ESC)
6043 rmescapes(p + 1, 0);
6045 len = cvtnum(ash_arith(p + 1));
6047 if (!(flag & EXP_QUOTED))
6048 recordregion(begoff, begoff + len, 0);
6052 /* argstr needs it */
6053 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6056 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6057 * characters to allow for further processing. Otherwise treat
6058 * $@ like $* since no splitting will be performed.
6060 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6061 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6062 * for correct expansion of "B=$A" word.
6065 argstr(char *p, int flags, struct strlist *var_str_list)
6067 static const char spclchars[] ALIGN1 = {
6075 #if ENABLE_SH_MATH_SUPPORT
6080 const char *reject = spclchars;
6081 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6086 if (!(flags & EXP_VARTILDE)) {
6088 } else if (flags & EXP_VARTILDE2) {
6093 if (flags & EXP_TILDE) {
6096 flags &= ~EXP_TILDE;
6100 p = exptilde(p, q, flags);
6103 startloc = expdest - (char *)stackblock();
6107 length += strcspn(p + length, reject);
6111 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6113 /* c == '=' || c == ':' || c == CTLENDARI */
6119 expdest = stack_nputstr(p, length, expdest);
6120 newloc = expdest - (char *)stackblock();
6121 if (breakall && !inquotes && newloc > startloc) {
6122 recordregion(startloc, newloc, 0);
6133 if (flags & EXP_VARTILDE2) {
6137 flags |= EXP_VARTILDE2;
6142 * sort of a hack - expand tildes in variable
6143 * assignments (after the first '=' and after ':'s).
6152 case CTLENDVAR: /* ??? */
6155 inquotes ^= EXP_QUOTED;
6156 /* "$@" syntax adherence hack */
6157 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6158 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6162 if (flags & QUOTES_ESC) {
6173 * Quoted parameter expansion pattern: remove quote
6174 * unless inside inner quotes or we have a literal
6177 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6178 EXP_QPAT && *p != '\\')
6183 TRACE(("argstr: evalvar('%s')\n", p));
6184 p = evalvar(p, flags | inquotes, var_str_list);
6185 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6188 expbackq(argbackq->n, flags | inquotes);
6189 argbackq = argbackq->next;
6191 #if ENABLE_SH_MATH_SUPPORT
6194 expari(flags | inquotes);
6203 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6204 char *pattern, int quotes, int zero)
6213 const char *s = loc2;
6220 match = pmatch(pattern, s);
6225 if (quotes && (unsigned char)*loc == CTLESC)
6234 scanright(char *startp, char *rmesc, char *rmescend,
6235 char *pattern, int quotes, int match_at_start)
6237 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6238 int try2optimize = match_at_start;
6244 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6245 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6246 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6248 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6249 * and on each iteration they go back two/one char until they reach the beginning.
6250 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6252 /* TODO: document in what other circumstances we are called. */
6254 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6257 const char *s = loc2;
6258 if (match_at_start) {
6262 match = pmatch(pattern, s);
6263 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6267 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6269 /* Maybe we can optimize this:
6270 * if pattern ends with unescaped *, we can avoid checking
6271 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6272 * it wont match truncated "raw_value_of_" strings too.
6274 unsigned plen = strlen(pattern);
6275 /* Does it end with "*"? */
6276 if (plen != 0 && pattern[--plen] == '*') {
6277 /* "xxxx*" is not escaped */
6278 /* "xxx\*" is escaped */
6279 /* "xx\\*" is not escaped */
6280 /* "x\\\*" is escaped */
6282 while (plen != 0 && pattern[--plen] == '\\')
6285 break; /* ends with unescaped "*" */
6293 esc = esclen(startp, loc);
6304 static void varunset(const char *, const char *, const char *, int) NORETURN;
6306 varunset(const char *end, const char *var, const char *umsg, int varflags)
6312 msg = "parameter not set";
6314 if ((unsigned char)*end == CTLENDVAR) {
6315 if (varflags & VSNUL)
6321 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6325 subevalvar(char *p, char *varname, int strloc, int subtype,
6326 int startloc, int varflags, int flag, struct strlist *var_str_list)
6328 struct nodelist *saveargbackq = argbackq;
6329 int quotes = flag & QUOTES_ESC;
6332 char *rmesc, *rmescend;
6334 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6335 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6336 int saveherefd = herefd;
6337 int amount, resetloc;
6338 IF_ASH_BASH_COMPAT(int workloc;)
6340 char *(*scan)(char*, char*, char*, char*, int, int);
6342 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6343 // p, varname, strloc, subtype, startloc, varflags, quotes);
6346 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6347 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6349 STPUTC('\0', expdest);
6350 herefd = saveherefd;
6351 argbackq = saveargbackq;
6352 startp = (char *)stackblock() + startloc;
6356 setvar0(varname, startp);
6357 amount = startp - expdest;
6358 STADJUST(amount, expdest);
6362 varunset(p, varname, startp, varflags);
6365 #if ENABLE_ASH_BASH_COMPAT
6367 //TODO: support more general format ${v:EXPR:EXPR},
6368 // where EXPR follows $(()) rules
6369 loc = str = stackblock() + strloc;
6370 /* Read POS in ${var:POS:LEN} */
6371 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6372 len = str - startp - 1;
6374 /* *loc != '\0', guaranteed by parser */
6378 /* Adjust the length by the number of escapes */
6379 for (ptr = startp; ptr < (str - 1); ptr++) {
6380 if ((unsigned char)*ptr == CTLESC) {
6388 if (*loc++ == ':') {
6392 /* Skip POS in ${var:POS:LEN} */
6394 while (*loc && *loc != ':') {
6396 * bash complains on: var=qwe; echo ${var:1a:123}
6398 ash_msg_and_raise_error(msg_illnum, str);
6402 if (*loc++ == ':') {
6407 /* ${VAR:$((-n)):l} starts n chars from the end */
6408 pos = orig_len + pos;
6410 if ((unsigned)pos >= orig_len) {
6411 /* apart from obvious ${VAR:999999:l},
6412 * covers ${VAR:$((-9999999)):l} - result is ""
6418 if (len > (orig_len - pos))
6419 len = orig_len - pos;
6421 for (str = startp; pos; str++, pos--) {
6422 if (quotes && (unsigned char)*str == CTLESC)
6425 for (loc = startp; len; len--) {
6426 if (quotes && (unsigned char)*str == CTLESC)
6431 amount = loc - expdest;
6432 STADJUST(amount, expdest);
6437 resetloc = expdest - (char *)stackblock();
6439 /* We'll comeback here if we grow the stack while handling
6440 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6441 * stack will need rebasing, and we'll need to remove our work
6444 IF_ASH_BASH_COMPAT(restart:)
6446 amount = expdest - ((char *)stackblock() + resetloc);
6447 STADJUST(-amount, expdest);
6448 startp = (char *)stackblock() + startloc;
6451 rmescend = (char *)stackblock() + strloc;
6453 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6454 if (rmesc != startp) {
6456 startp = (char *)stackblock() + startloc;
6460 str = (char *)stackblock() + strloc;
6462 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6463 * The result is a_\_z_c (not a\_\_z_c)!
6465 * The search pattern and replace string treat backslashes differently!
6466 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6467 * and string. It's only used on the first call.
6469 preglob(str, IF_ASH_BASH_COMPAT(
6470 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6471 RMESCAPE_SLASH :) 0);
6473 #if ENABLE_ASH_BASH_COMPAT
6474 workloc = expdest - (char *)stackblock();
6475 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6479 repl = strchr(str, CTLESC);
6485 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6487 /* If there's no pattern to match, return the expansion unmolested */
6496 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6497 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6499 /* No match, advance */
6500 char *restart_detect = stackblock();
6502 STPUTC(*idx, expdest);
6503 if (quotes && (unsigned char)*idx == CTLESC) {
6506 STPUTC(*idx, expdest);
6508 if (stackblock() != restart_detect)
6513 /* continue; - prone to quadratic behavior, smarter code: */
6516 if (str[0] == '*') {
6517 /* Pattern is "*foo". If "*foo" does not match "long_string",
6518 * it would never match "ong_string" etc, no point in trying.
6525 if (subtype == VSREPLACEALL) {
6527 if (quotes && (unsigned char)*idx == CTLESC)
6536 //bb_error_msg("repl:'%s'", repl);
6537 for (loc = (char*)repl; *loc; loc++) {
6538 char *restart_detect = stackblock();
6539 if (quotes && *loc == '\\') {
6540 STPUTC(CTLESC, expdest);
6543 STPUTC(*loc, expdest);
6544 if (stackblock() != restart_detect)
6549 if (subtype == VSREPLACE) {
6550 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6552 char *restart_detect = stackblock();
6553 STPUTC(*idx, expdest);
6554 if (stackblock() != restart_detect)
6563 /* We've put the replaced text into a buffer at workloc, now
6564 * move it to the right place and adjust the stack.
6566 STPUTC('\0', expdest);
6567 startp = (char *)stackblock() + startloc;
6568 memmove(startp, (char *)stackblock() + workloc, len + 1);
6569 //bb_error_msg("startp:'%s'", startp);
6570 amount = expdest - (startp + len);
6571 STADJUST(-amount, expdest);
6574 #endif /* ENABLE_ASH_BASH_COMPAT */
6576 subtype -= VSTRIMRIGHT;
6578 if (subtype < 0 || subtype > 7)
6581 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6582 zero = subtype >> 1;
6583 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6584 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6586 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6589 memmove(startp, loc, str - loc);
6590 loc = startp + (str - loc) - 1;
6593 amount = loc - expdest;
6594 STADJUST(amount, expdest);
6600 * Add the value of a specialized variable to the stack string.
6601 * name parameter (examples):
6602 * ash -c 'echo $1' name:'1='
6603 * ash -c 'echo $qwe' name:'qwe='
6604 * ash -c 'echo $$' name:'$='
6605 * ash -c 'echo ${$}' name:'$='
6606 * ash -c 'echo ${$##q}' name:'$=q'
6607 * ash -c 'echo ${#$}' name:'$='
6608 * note: examples with bad shell syntax:
6609 * ash -c 'echo ${#$1}' name:'$=1'
6610 * ash -c 'echo ${#1#}' name:'1=#'
6612 static NOINLINE ssize_t
6613 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list, int *quotedp)
6620 int quoted = *quotedp;
6621 int subtype = varflags & VSTYPE;
6622 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6623 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6626 sep = (flags & EXP_FULL) << CHAR_BIT;
6627 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6637 num = shellparam.nparam;
6645 goto check_1char_name;
6647 expdest = makestrspace(NOPTS, expdest);
6648 for (i = NOPTS - 1; i >= 0; i--) {
6650 USTPUTC(optletters(i), expdest);
6656 /* handles cases similar to ${#$1} */
6657 if (name[2] != '\0')
6658 raise_error_syntax("bad substitution");
6671 sep |= ifsset() ? ifsval()[0] : ' ';
6678 while ((p = *ap++) != NULL) {
6679 len += strtodest(p, syntax, quotes);
6683 memtodest(&sepc, 1, syntax, quotes);
6698 num = atoi(name); /* number(name) fails on ${N#str} etc */
6699 if (num < 0 || num > shellparam.nparam)
6701 p = num ? shellparam.p[num - 1] : arg0;
6704 /* NB: name has form "VAR=..." */
6706 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6707 * which should be considered before we check variables. */
6709 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6713 str = var_str_list->text;
6714 eq = strchr(str, '=');
6715 if (!eq) /* stop at first non-assignment */
6718 if (name_len == (unsigned)(eq - str)
6719 && strncmp(str, name, name_len) == 0
6722 /* goto value; - WRONG! */
6723 /* think "A=1 A=2 B=$A" */
6725 var_str_list = var_str_list->next;
6726 } while (var_str_list);
6730 p = lookupvar(name);
6735 len = strtodest(p, syntax, quotes);
6736 #if ENABLE_UNICODE_SUPPORT
6737 if (subtype == VSLENGTH && len > 0) {
6738 reinit_unicode_for_ash();
6739 if (unicode_status == UNICODE_ON) {
6740 STADJUST(-len, expdest);
6742 len = unicode_strlen(p);
6750 STADJUST(-len, expdest);
6755 * Expand a variable, and return a pointer to the next character in the
6759 evalvar(char *p, int flag, struct strlist *var_str_list)
6770 varflags = (unsigned char) *p++;
6771 subtype = varflags & VSTYPE;
6772 quoted = flag & EXP_QUOTED;
6774 easy = (!quoted || (*var == '@' && shellparam.nparam));
6775 startloc = expdest - (char *)stackblock();
6776 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6779 varlen = varvalue(var, varflags, flag, var_str_list, "ed);
6780 if (varflags & VSNUL)
6783 if (subtype == VSPLUS) {
6784 varlen = -1 - varlen;
6788 if (subtype == VSMINUS) {
6793 flag | EXP_TILDE | EXP_WORD,
6801 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6805 subevalvar(p, var, 0, subtype, startloc, varflags,
6806 flag & ~QUOTES_ESC, var_str_list);
6809 * Remove any recorded regions beyond
6812 removerecordregions(startloc);
6816 if (varlen < 0 && uflag)
6817 varunset(p, var, 0, 0);
6819 if (subtype == VSLENGTH) {
6820 cvtnum(varlen > 0 ? varlen : 0);
6824 if (subtype == VSNORMAL) {
6828 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6837 case VSTRIMRIGHTMAX:
6838 #if ENABLE_ASH_BASH_COMPAT
6851 * Terminate the string and start recording the pattern
6854 STPUTC('\0', expdest);
6855 patloc = expdest - (char *)stackblock();
6856 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6857 startloc, varflags, flag, var_str_list)) {
6858 int amount = expdest - (
6859 (char *)stackblock() + patloc - 1
6861 STADJUST(-amount, expdest);
6863 /* Remove any recorded regions beyond start of variable */
6864 removerecordregions(startloc);
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);
7041 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7042 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7044 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7045 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7046 // Which means you need to unescape the string, right? Not so fast:
7047 // if there _is_ a file named "file\?" (with backslash), it is returned
7048 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7049 // You DONT KNOW by looking at the result whether you need to unescape it.
7051 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7052 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7053 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7054 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7055 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7056 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7057 i = glob(p, 0, NULL, &pglob);
7058 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7063 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7064 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7065 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7077 *exparg.lastp = str;
7078 rmescapes(str->text, 0);
7079 exparg.lastp = &str->next;
7081 default: /* GLOB_NOSPACE */
7084 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7091 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7094 * Do metacharacter (i.e. *, ?, [...]) expansion.
7097 expmeta(char *expdir, char *enddir, char *name)
7113 for (p = name; esc = 0, *p; p += esc + 1) {
7114 if (*p == '*' || *p == '?')
7116 else if (*p == '[') {
7123 if (*q == '/' || *q == '\0')
7133 if (p[esc] == '/') {
7136 start = p + esc + 1;
7140 if (metaflag == 0) { /* we've reached the end of the file name */
7141 if (enddir != expdir)
7149 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7160 } while (p < start);
7162 if (enddir == expdir) {
7164 } else if (enddir == expdir + 1 && *expdir == '/') {
7173 if (enddir != expdir)
7175 if (*endname == 0) {
7188 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7189 if (dp->d_name[0] == '.' && !matchdot)
7191 if (pmatch(start, dp->d_name)) {
7193 strcpy(enddir, dp->d_name);
7196 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7199 expmeta(expdir, p, endname);
7205 endname[-esc - 1] = esc ? '\\' : '/';
7208 static struct strlist *
7209 msort(struct strlist *list, int len)
7211 struct strlist *p, *q = NULL;
7212 struct strlist **lpp;
7220 for (n = half; --n >= 0;) {
7224 q->next = NULL; /* terminate first half of list */
7225 q = msort(list, half); /* sort first half of list */
7226 p = msort(p, len - half); /* sort second half */
7229 #if ENABLE_LOCALE_SUPPORT
7230 if (strcoll(p->text, q->text) < 0)
7232 if (strcmp(p->text, q->text) < 0)
7256 * Sort the results of file name expansion. It calculates the number of
7257 * strings to sort and then calls msort (short for merge sort) to do the
7260 static struct strlist *
7261 expsort(struct strlist *str)
7267 for (sp = str; sp; sp = sp->next)
7269 return msort(str, len);
7273 expandmeta(struct strlist *str /*, int flag*/)
7275 static const char metachars[] ALIGN1 = {
7278 /* TODO - EXP_REDIR */
7282 struct strlist **savelastp;
7288 if (!strpbrk(str->text, metachars))
7290 savelastp = exparg.lastp;
7293 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7295 int i = strlen(str->text);
7296 //BUGGY estimation of how long expanded name can be
7297 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7299 expmeta(expdir, expdir, p);
7304 if (exparg.lastp == savelastp) {
7309 *exparg.lastp = str;
7310 rmescapes(str->text, 0);
7311 exparg.lastp = &str->next;
7313 *exparg.lastp = NULL;
7314 *savelastp = sp = expsort(*savelastp);
7315 while (sp->next != NULL)
7317 exparg.lastp = &sp->next;
7322 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7325 * Perform variable substitution and command substitution on an argument,
7326 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7327 * perform splitting and file name expansion. When arglist is NULL, perform
7328 * here document expansion.
7331 expandarg(union node *arg, struct arglist *arglist, int flag)
7336 argbackq = arg->narg.backquote;
7337 STARTSTACKSTR(expdest);
7338 ifsfirst.next = NULL;
7340 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7341 argstr(arg->narg.text, flag,
7342 /* var_str_list: */ arglist ? arglist->list : NULL);
7343 p = _STPUTC('\0', expdest);
7345 if (arglist == NULL) {
7346 return; /* here document expanded */
7348 p = grabstackstr(p);
7349 TRACE(("expandarg: p:'%s'\n", p));
7350 exparg.lastp = &exparg.list;
7354 if (flag & EXP_FULL) {
7355 ifsbreakup(p, &exparg);
7356 *exparg.lastp = NULL;
7357 exparg.lastp = &exparg.list;
7358 expandmeta(exparg.list /*, flag*/);
7360 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7362 TRACE(("expandarg: rmescapes:'%s'\n", p));
7364 sp = stzalloc(sizeof(*sp));
7367 exparg.lastp = &sp->next;
7371 *exparg.lastp = NULL;
7373 *arglist->lastp = exparg.list;
7374 arglist->lastp = exparg.lastp;
7379 * Expand shell variables and backquotes inside a here document.
7382 expandhere(union node *arg, int fd)
7385 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7386 full_write(fd, stackblock(), expdest - (char *)stackblock());
7390 * Returns true if the pattern matches the string.
7393 patmatch(char *pattern, const char *string)
7395 return pmatch(preglob(pattern, 0), string);
7399 * See if a pattern matches in a case statement.
7402 casematch(union node *pattern, char *val)
7404 struct stackmark smark;
7407 setstackmark(&smark);
7408 argbackq = pattern->narg.backquote;
7409 STARTSTACKSTR(expdest);
7411 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7412 /* var_str_list: */ NULL);
7413 STACKSTRNUL(expdest);
7414 result = patmatch(stackblock(), val);
7415 popstackmark(&smark);
7420 /* ============ find_command */
7424 int (*builtin)(int, char **) FAST_FUNC;
7425 /* unsigned flags; */
7427 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7428 /* "regular" builtins always take precedence over commands,
7429 * regardless of PATH=....%builtin... position */
7430 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7431 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7434 smallint cmdtype; /* CMDxxx */
7437 /* index >= 0 for commands without path (slashes) */
7438 /* (TODO: what exactly does the value mean? PATH position?) */
7439 /* index == -1 for commands with slashes */
7440 /* index == (-2 - applet_no) for NOFORK applets */
7441 const struct builtincmd *cmd;
7442 struct funcnode *func;
7445 /* values of cmdtype */
7446 #define CMDUNKNOWN -1 /* no entry in table for command */
7447 #define CMDNORMAL 0 /* command is an executable program */
7448 #define CMDFUNCTION 1 /* command is a shell function */
7449 #define CMDBUILTIN 2 /* command is a shell builtin */
7451 /* action to find_command() */
7452 #define DO_ERR 0x01 /* prints errors */
7453 #define DO_ABS 0x02 /* checks absolute paths */
7454 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7455 #define DO_ALTPATH 0x08 /* using alternate path */
7456 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7458 static void find_command(char *, struct cmdentry *, int, const char *);
7461 /* ============ Hashing commands */
7464 * When commands are first encountered, they are entered in a hash table.
7465 * This ensures that a full path search will not have to be done for them
7466 * on each invocation.
7468 * We should investigate converting to a linear search, even though that
7469 * would make the command name "hash" a misnomer.
7473 struct tblentry *next; /* next entry in hash chain */
7474 union param param; /* definition of builtin function */
7475 smallint cmdtype; /* CMDxxx */
7476 char rehash; /* if set, cd done since entry created */
7477 char cmdname[1]; /* name of command */
7480 static struct tblentry **cmdtable;
7481 #define INIT_G_cmdtable() do { \
7482 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7485 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7489 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7491 #if ENABLE_FEATURE_SH_STANDALONE
7492 if (applet_no >= 0) {
7493 if (APPLET_IS_NOEXEC(applet_no)) {
7497 run_applet_no_and_exit(applet_no, argv);
7499 /* re-exec ourselves with the new arguments */
7500 execve(bb_busybox_exec_path, argv, envp);
7501 /* If they called chroot or otherwise made the binary no longer
7502 * executable, fall through */
7509 execve(cmd, argv, envp);
7510 } while (errno == EINTR);
7512 execve(cmd, argv, envp);
7514 if (cmd == (char*) bb_busybox_exec_path) {
7515 /* We already visited ENOEXEC branch below, don't do it again */
7516 //TODO: try execve(initial_argv0_of_shell, argv, envp) before giving up?
7520 if (errno == ENOEXEC) {
7521 /* Run "cmd" as a shell script:
7522 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7523 * "If the execve() function fails with ENOEXEC, the shell
7524 * shall execute a command equivalent to having a shell invoked
7525 * with the command name as its first operand,
7526 * with any remaining arguments passed to the new shell"
7528 * That is, do not use $SHELL, user's shell, or /bin/sh;
7529 * just call ourselves.
7531 * Note that bash reads ~80 chars of the file, and if it sees
7532 * a zero byte before it sees newline, it doesn't try to
7533 * interpret it, but fails with "cannot execute binary file"
7534 * message and exit code 126. For one, this prevents attempts
7535 * to interpret foreign ELF binaries as shell scripts.
7540 for (ap = argv; *ap; ap++)
7542 new = ckmalloc((ap - argv + 2) * sizeof(new[0]));
7543 new[0] = (char*) "ash";
7546 while ((*ap++ = *++argv) != NULL)
7548 cmd = (char*) bb_busybox_exec_path;
7555 * Exec a program. Never returns. If you change this routine, you may
7556 * have to change the find_command routine as well.
7558 static void shellexec(char **, const char *, int) NORETURN;
7560 shellexec(char **argv, const char *path, int idx)
7566 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7568 clearredir(/*drop:*/ 1);
7569 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7570 if (strchr(argv[0], '/') != NULL
7571 #if ENABLE_FEATURE_SH_STANDALONE
7572 || (applet_no = find_applet_by_name(argv[0])) >= 0
7575 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7576 if (applet_no >= 0) {
7577 /* We tried execing ourself, but it didn't work.
7578 * Maybe /proc/self/exe doesn't exist?
7587 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7588 if (--idx < 0 && pathopt == NULL) {
7589 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7590 if (errno != ENOENT && errno != ENOTDIR)
7597 /* Map to POSIX errors */
7609 exitstatus = exerrno;
7610 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7611 argv[0], e, suppress_int));
7612 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7617 printentry(struct tblentry *cmdp)
7623 idx = cmdp->param.index;
7626 name = path_advance(&path, cmdp->cmdname);
7628 } while (--idx >= 0);
7629 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7633 * Clear out command entries. The argument specifies the first entry in
7634 * PATH which has changed.
7637 clearcmdentry(int firstchange)
7639 struct tblentry **tblp;
7640 struct tblentry **pp;
7641 struct tblentry *cmdp;
7644 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7646 while ((cmdp = *pp) != NULL) {
7647 if ((cmdp->cmdtype == CMDNORMAL &&
7648 cmdp->param.index >= firstchange)
7649 || (cmdp->cmdtype == CMDBUILTIN &&
7650 builtinloc >= firstchange)
7663 * Locate a command in the command hash table. If "add" is nonzero,
7664 * add the command to the table if it is not already present. The
7665 * variable "lastcmdentry" is set to point to the address of the link
7666 * pointing to the entry, so that delete_cmd_entry can delete the
7669 * Interrupts must be off if called with add != 0.
7671 static struct tblentry **lastcmdentry;
7673 static struct tblentry *
7674 cmdlookup(const char *name, int add)
7676 unsigned int hashval;
7678 struct tblentry *cmdp;
7679 struct tblentry **pp;
7682 hashval = (unsigned char)*p << 4;
7684 hashval += (unsigned char)*p++;
7686 pp = &cmdtable[hashval % CMDTABLESIZE];
7687 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7688 if (strcmp(cmdp->cmdname, name) == 0)
7692 if (add && cmdp == NULL) {
7693 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7695 /* + 1 - already done because
7696 * tblentry::cmdname is char[1] */);
7697 /*cmdp->next = NULL; - ckzalloc did it */
7698 cmdp->cmdtype = CMDUNKNOWN;
7699 strcpy(cmdp->cmdname, name);
7706 * Delete the command entry returned on the last lookup.
7709 delete_cmd_entry(void)
7711 struct tblentry *cmdp;
7714 cmdp = *lastcmdentry;
7715 *lastcmdentry = cmdp->next;
7716 if (cmdp->cmdtype == CMDFUNCTION)
7717 freefunc(cmdp->param.func);
7723 * Add a new command entry, replacing any existing command entry for
7724 * the same name - except special builtins.
7727 addcmdentry(char *name, struct cmdentry *entry)
7729 struct tblentry *cmdp;
7731 cmdp = cmdlookup(name, 1);
7732 if (cmdp->cmdtype == CMDFUNCTION) {
7733 freefunc(cmdp->param.func);
7735 cmdp->cmdtype = entry->cmdtype;
7736 cmdp->param = entry->u;
7740 static int FAST_FUNC
7741 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7743 struct tblentry **pp;
7744 struct tblentry *cmdp;
7746 struct cmdentry entry;
7749 if (nextopt("r") != '\0') {
7754 if (*argptr == NULL) {
7755 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7756 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7757 if (cmdp->cmdtype == CMDNORMAL)
7765 while ((name = *argptr) != NULL) {
7766 cmdp = cmdlookup(name, 0);
7768 && (cmdp->cmdtype == CMDNORMAL
7769 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7773 find_command(name, &entry, DO_ERR, pathval());
7774 if (entry.cmdtype == CMDUNKNOWN)
7782 * Called when a cd is done. Marks all commands so the next time they
7783 * are executed they will be rehashed.
7788 struct tblentry **pp;
7789 struct tblentry *cmdp;
7791 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7792 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7793 if (cmdp->cmdtype == CMDNORMAL
7794 || (cmdp->cmdtype == CMDBUILTIN
7795 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7805 * Fix command hash table when PATH changed.
7806 * Called before PATH is changed. The argument is the new value of PATH;
7807 * pathval() still returns the old value at this point.
7808 * Called with interrupts off.
7810 static void FAST_FUNC
7811 changepath(const char *new)
7819 firstchange = 9999; /* assume no change */
7825 if ((*old == '\0' && *new == ':')
7826 || (*old == ':' && *new == '\0')
7830 old = new; /* ignore subsequent differences */
7834 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7841 if (builtinloc < 0 && idx_bltin >= 0)
7842 builtinloc = idx_bltin; /* zap builtins */
7843 if (builtinloc >= 0 && idx_bltin < 0)
7845 clearcmdentry(firstchange);
7846 builtinloc = idx_bltin;
7871 #if ENABLE_ASH_BASH_COMPAT
7882 typedef smallint token_id_t;
7884 /* first char is indicating which tokens mark the end of a list */
7885 static const char *const tokname_array[] = {
7899 #define KWDOFFSET 13
7900 /* the following are keywords */
7910 #if ENABLE_ASH_BASH_COMPAT
7922 /* Wrapper around strcmp for qsort/bsearch/... */
7924 pstrcmp(const void *a, const void *b)
7926 return strcmp((char*) a, (*(char**) b) + 1);
7929 static const char *const *
7930 findkwd(const char *s)
7932 return bsearch(s, tokname_array + KWDOFFSET,
7933 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7934 sizeof(tokname_array[0]), pstrcmp);
7938 * Locate and print what a word is...
7941 describe_command(char *command, const char *path, int describe_command_verbose)
7943 struct cmdentry entry;
7944 struct tblentry *cmdp;
7945 #if ENABLE_ASH_ALIAS
7946 const struct alias *ap;
7949 path = path ? path : pathval();
7951 if (describe_command_verbose) {
7955 /* First look at the keywords */
7956 if (findkwd(command)) {
7957 out1str(describe_command_verbose ? " is a shell keyword" : command);
7961 #if ENABLE_ASH_ALIAS
7962 /* Then look at the aliases */
7963 ap = lookupalias(command, 0);
7965 if (!describe_command_verbose) {
7970 out1fmt(" is an alias for %s", ap->val);
7974 /* Then check if it is a tracked alias */
7975 cmdp = cmdlookup(command, 0);
7977 entry.cmdtype = cmdp->cmdtype;
7978 entry.u = cmdp->param;
7980 /* Finally use brute force */
7981 find_command(command, &entry, DO_ABS, path);
7984 switch (entry.cmdtype) {
7986 int j = entry.u.index;
7992 p = path_advance(&path, command);
7996 if (describe_command_verbose) {
7998 (cmdp ? " a tracked alias for" : nullstr), p
8007 if (describe_command_verbose) {
8008 out1str(" is a shell function");
8015 if (describe_command_verbose) {
8016 out1fmt(" is a %sshell builtin",
8017 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8018 "special " : nullstr
8026 if (describe_command_verbose) {
8027 out1str(": not found\n");
8036 static int FAST_FUNC
8037 typecmd(int argc UNUSED_PARAM, char **argv)
8043 /* type -p ... ? (we don't bother checking for 'p') */
8044 if (argv[1] && argv[1][0] == '-') {
8049 err |= describe_command(argv[i++], NULL, verbose);
8054 #if ENABLE_ASH_CMDCMD
8055 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8057 parse_command_args(char **argv, const char **path)
8070 if (c == '-' && !*cp) {
8078 *path = bb_default_path;
8081 /* run 'typecmd' for other options */
8090 static int FAST_FUNC
8091 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8099 const char *path = NULL;
8101 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8102 * never reaches this function.
8105 while ((c = nextopt("pvV")) != '\0')
8107 verify |= VERIFY_VERBOSE;
8109 /*verify |= VERIFY_BRIEF*/;
8115 path = bb_default_path;
8117 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8119 if (/*verify && */ cmd)
8120 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8127 /* ============ eval.c */
8129 static int funcblocksize; /* size of structures in function */
8130 static int funcstringsize; /* size of strings in node */
8131 static void *funcblock; /* block to allocate function from */
8132 static char *funcstring; /* block to allocate strings from */
8134 /* flags in argument to evaltree */
8135 #define EV_EXIT 01 /* exit after evaluating tree */
8136 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8138 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8139 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8140 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8141 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8142 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8143 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8144 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8145 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8146 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8147 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8148 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8149 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8150 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8151 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8152 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8153 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8154 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8155 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8156 #if ENABLE_ASH_BASH_COMPAT
8157 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8159 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8160 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8161 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8162 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8163 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8164 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8165 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8166 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8167 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8170 static void calcsize(union node *n);
8173 sizenodelist(struct nodelist *lp)
8176 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8183 calcsize(union node *n)
8187 funcblocksize += nodesize[n->type];
8190 calcsize(n->ncmd.redirect);
8191 calcsize(n->ncmd.args);
8192 calcsize(n->ncmd.assign);
8195 sizenodelist(n->npipe.cmdlist);
8200 calcsize(n->nredir.redirect);
8201 calcsize(n->nredir.n);
8208 calcsize(n->nbinary.ch2);
8209 calcsize(n->nbinary.ch1);
8212 calcsize(n->nif.elsepart);
8213 calcsize(n->nif.ifpart);
8214 calcsize(n->nif.test);
8217 funcstringsize += strlen(n->nfor.var) + 1;
8218 calcsize(n->nfor.body);
8219 calcsize(n->nfor.args);
8222 calcsize(n->ncase.cases);
8223 calcsize(n->ncase.expr);
8226 calcsize(n->nclist.body);
8227 calcsize(n->nclist.pattern);
8228 calcsize(n->nclist.next);
8232 sizenodelist(n->narg.backquote);
8233 funcstringsize += strlen(n->narg.text) + 1;
8234 calcsize(n->narg.next);
8237 #if ENABLE_ASH_BASH_COMPAT
8244 calcsize(n->nfile.fname);
8245 calcsize(n->nfile.next);
8249 calcsize(n->ndup.vname);
8250 calcsize(n->ndup.next);
8254 calcsize(n->nhere.doc);
8255 calcsize(n->nhere.next);
8258 calcsize(n->nnot.com);
8264 nodeckstrdup(char *s)
8266 char *rtn = funcstring;
8268 strcpy(funcstring, s);
8269 funcstring += strlen(s) + 1;
8273 static union node *copynode(union node *);
8275 static struct nodelist *
8276 copynodelist(struct nodelist *lp)
8278 struct nodelist *start;
8279 struct nodelist **lpp;
8284 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8285 (*lpp)->n = copynode(lp->n);
8287 lpp = &(*lpp)->next;
8294 copynode(union node *n)
8301 funcblock = (char *) funcblock + nodesize[n->type];
8305 new->ncmd.redirect = copynode(n->ncmd.redirect);
8306 new->ncmd.args = copynode(n->ncmd.args);
8307 new->ncmd.assign = copynode(n->ncmd.assign);
8310 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8311 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8316 new->nredir.redirect = copynode(n->nredir.redirect);
8317 new->nredir.n = copynode(n->nredir.n);
8324 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8325 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8328 new->nif.elsepart = copynode(n->nif.elsepart);
8329 new->nif.ifpart = copynode(n->nif.ifpart);
8330 new->nif.test = copynode(n->nif.test);
8333 new->nfor.var = nodeckstrdup(n->nfor.var);
8334 new->nfor.body = copynode(n->nfor.body);
8335 new->nfor.args = copynode(n->nfor.args);
8338 new->ncase.cases = copynode(n->ncase.cases);
8339 new->ncase.expr = copynode(n->ncase.expr);
8342 new->nclist.body = copynode(n->nclist.body);
8343 new->nclist.pattern = copynode(n->nclist.pattern);
8344 new->nclist.next = copynode(n->nclist.next);
8348 new->narg.backquote = copynodelist(n->narg.backquote);
8349 new->narg.text = nodeckstrdup(n->narg.text);
8350 new->narg.next = copynode(n->narg.next);
8353 #if ENABLE_ASH_BASH_COMPAT
8360 new->nfile.fname = copynode(n->nfile.fname);
8361 new->nfile.fd = n->nfile.fd;
8362 new->nfile.next = copynode(n->nfile.next);
8366 new->ndup.vname = copynode(n->ndup.vname);
8367 new->ndup.dupfd = n->ndup.dupfd;
8368 new->ndup.fd = n->ndup.fd;
8369 new->ndup.next = copynode(n->ndup.next);
8373 new->nhere.doc = copynode(n->nhere.doc);
8374 new->nhere.fd = n->nhere.fd;
8375 new->nhere.next = copynode(n->nhere.next);
8378 new->nnot.com = copynode(n->nnot.com);
8381 new->type = n->type;
8386 * Make a copy of a parse tree.
8388 static struct funcnode *
8389 copyfunc(union node *n)
8394 funcblocksize = offsetof(struct funcnode, n);
8397 blocksize = funcblocksize;
8398 f = ckmalloc(blocksize + funcstringsize);
8399 funcblock = (char *) f + offsetof(struct funcnode, n);
8400 funcstring = (char *) f + blocksize;
8407 * Define a shell function.
8410 defun(char *name, union node *func)
8412 struct cmdentry entry;
8415 entry.cmdtype = CMDFUNCTION;
8416 entry.u.func = copyfunc(func);
8417 addcmdentry(name, &entry);
8421 /* Reasons for skipping commands (see comment on breakcmd routine) */
8422 #define SKIPBREAK (1 << 0)
8423 #define SKIPCONT (1 << 1)
8424 #define SKIPFUNC (1 << 2)
8425 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8426 static int skipcount; /* number of levels to skip */
8427 static int funcnest; /* depth of function calls */
8428 static int loopnest; /* current loop nesting level */
8430 /* Forward decl way out to parsing code - dotrap needs it */
8431 static int evalstring(char *s, int flags);
8433 /* Called to execute a trap.
8434 * Single callsite - at the end of evaltree().
8435 * If we return non-zero, evaltree raises EXEXIT exception.
8437 * Perhaps we should avoid entering new trap handlers
8438 * while we are executing a trap handler. [is it a TODO?]
8445 uint8_t last_status;
8450 last_status = exitstatus;
8454 TRACE(("dotrap entered\n"));
8455 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8467 /* non-trapped SIGINT is handled separately by raise_interrupt,
8468 * don't upset it by resetting gotsig[SIGINT-1] */
8469 if (sig == SIGINT && !p)
8472 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8478 exitstatus = last_status;
8479 TRACE(("dotrap returns\n"));
8482 /* forward declarations - evaluation is fairly recursive business... */
8483 static int evalloop(union node *, int);
8484 static int evalfor(union node *, int);
8485 static int evalcase(union node *, int);
8486 static int evalsubshell(union node *, int);
8487 static void expredir(union node *);
8488 static int evalpipe(union node *, int);
8489 static int evalcommand(union node *, int);
8490 static int evalbltin(const struct builtincmd *, int, char **, int);
8491 static void prehash(union node *);
8494 * Evaluate a parse tree. The value is left in the global variable
8498 evaltree(union node *n, int flags)
8500 struct jmploc *volatile savehandler = exception_handler;
8501 struct jmploc jmploc;
8503 int (*evalfn)(union node *, int);
8507 SAVE_INT(int_level);
8510 TRACE(("evaltree(NULL) called\n"));
8513 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8517 exception_handler = &jmploc;
8519 int err = setjmp(jmploc.loc);
8521 /* if it was a signal, check for trap handlers */
8522 if (exception_type == EXSIG) {
8523 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8524 exception_type, err));
8527 /* continue on the way out */
8528 TRACE(("exception %d in evaltree, propagating err=%d\n",
8529 exception_type, err));
8530 exception_handler = savehandler;
8531 longjmp(exception_handler->loc, err);
8538 out1fmt("Node type = %d\n", n->type);
8543 status = !evaltree(n->nnot.com, EV_TESTED);
8546 expredir(n->nredir.redirect);
8547 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8549 status = evaltree(n->nredir.n, flags & EV_TESTED);
8551 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8554 evalfn = evalcommand;
8556 if (eflag && !(flags & EV_TESTED))
8567 evalfn = evalsubshell;
8570 evalfn = evalsubshell;
8583 #error NAND + 1 != NOR
8585 #if NOR + 1 != NSEMI
8586 #error NOR + 1 != NSEMI
8588 unsigned is_or = n->type - NAND;
8591 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8593 if ((!status) == is_or || evalskip)
8599 status = evalfn(n, flags);
8603 status = evaltree(n->nif.test, EV_TESTED);
8610 if (n->nif.elsepart) {
8611 n = n->nif.elsepart;
8617 defun(n->narg.text, n->narg.next);
8618 /* Not necessary. To test it:
8619 * "false; f() { qwerty; }; echo $?" should print 0.
8623 exitstatus = status;
8628 exception_handler = savehandler;
8631 /* Order of checks below is important:
8632 * signal handlers trigger before exit caused by "set -e".
8636 if (checkexit & status)
8637 raise_exception(EXEXIT);
8638 if (flags & EV_EXIT)
8639 raise_exception(EXEXIT);
8641 RESTORE_INT(int_level);
8642 TRACE(("leaving evaltree (no interrupts)\n"));
8647 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8650 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8655 int skip = evalskip;
8662 if (--skipcount <= 0) {
8673 evalloop(union node *n, int flags)
8684 i = evaltree(n->nbinary.ch1, EV_TESTED);
8686 if (skip == SKIPFUNC)
8690 if (n->type != NWHILE)
8694 status = evaltree(n->nbinary.ch2, flags);
8696 } while (!(skip & ~SKIPCONT));
8703 evalfor(union node *n, int flags)
8705 struct arglist arglist;
8708 struct stackmark smark;
8711 setstackmark(&smark);
8712 arglist.list = NULL;
8713 arglist.lastp = &arglist.list;
8714 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8715 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8717 *arglist.lastp = NULL;
8721 for (sp = arglist.list; sp; sp = sp->next) {
8722 setvar0(n->nfor.var, sp->text);
8723 status = evaltree(n->nfor.body, flags);
8724 if (skiploop() & ~SKIPCONT)
8728 popstackmark(&smark);
8734 evalcase(union node *n, int flags)
8738 struct arglist arglist;
8739 struct stackmark smark;
8742 setstackmark(&smark);
8743 arglist.list = NULL;
8744 arglist.lastp = &arglist.list;
8745 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8746 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8747 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8748 if (casematch(patp, arglist.list->text)) {
8749 /* Ensure body is non-empty as otherwise
8750 * EV_EXIT may prevent us from setting the
8753 if (evalskip == 0 && cp->nclist.body) {
8754 status = evaltree(cp->nclist.body, flags);
8761 popstackmark(&smark);
8767 * Kick off a subshell to evaluate a tree.
8770 evalsubshell(union node *n, int flags)
8773 int backgnd = (n->type == NBACKGND);
8776 expredir(n->nredir.redirect);
8777 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8780 jp = makejob(/*n,*/ 1);
8781 if (forkshell(jp, n, backgnd) == 0) {
8786 flags &= ~EV_TESTED;
8788 redirect(n->nredir.redirect, 0);
8789 evaltreenr(n->nredir.n, flags);
8794 status = waitforjob(jp);
8800 * Compute the names of the files in a redirection list.
8802 static void fixredir(union node *, const char *, int);
8804 expredir(union node *n)
8808 for (redir = n; redir; redir = redir->nfile.next) {
8812 fn.lastp = &fn.list;
8813 switch (redir->type) {
8817 #if ENABLE_ASH_BASH_COMPAT
8822 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8823 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8824 #if ENABLE_ASH_BASH_COMPAT
8828 // By the design of stack allocator, the loop of this kind:
8829 // while true; do while true; do break; done </dev/null; done
8830 // will look like a memory leak: ash plans to free expfname's
8831 // of "/dev/null" as soon as it finishes running the loop
8832 // (in this case, never).
8833 // This "fix" is wrong:
8834 if (redir->nfile.expfname)
8835 stunalloc(redir->nfile.expfname);
8836 // It results in corrupted state of stacked allocations.
8838 redir->nfile.expfname = fn.list->text;
8841 case NTOFD: /* >& */
8842 if (redir->ndup.vname) {
8843 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8844 if (fn.list == NULL)
8845 ash_msg_and_raise_error("redir error");
8846 #if ENABLE_ASH_BASH_COMPAT
8847 //FIXME: we used expandarg with different args!
8848 if (!isdigit_str9(fn.list->text)) {
8849 /* >&file, not >&fd */
8850 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8851 ash_msg_and_raise_error("redir error");
8853 goto store_expfname;
8856 fixredir(redir, fn.list->text, 1);
8864 * Evaluate a pipeline. All the processes in the pipeline are children
8865 * of the process creating the pipeline. (This differs from some versions
8866 * of the shell, which make the last process in a pipeline the parent
8870 evalpipe(union node *n, int flags)
8873 struct nodelist *lp;
8879 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8881 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8885 jp = makejob(/*n,*/ pipelen);
8887 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8891 if (pipe(pip) < 0) {
8893 ash_msg_and_raise_error("pipe call failed");
8896 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8909 evaltreenr(lp->n, flags);
8915 /* Don't want to trigger debugging */
8919 if (n->npipe.pipe_backgnd == 0) {
8920 status = waitforjob(jp);
8921 TRACE(("evalpipe: job done exit status %d\n", status));
8929 * Controls whether the shell is interactive or not.
8932 setinteractive(int on)
8934 static smallint is_interactive;
8936 if (++on == is_interactive)
8938 is_interactive = on;
8942 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8943 if (is_interactive > 1) {
8944 /* Looks like they want an interactive shell */
8945 static smallint did_banner;
8948 /* note: ash and hush share this string */
8949 out1fmt("\n\n%s %s\n"
8950 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
8953 "built-in shell (ash)"
8967 setinteractive(iflag);
8969 #if ENABLE_FEATURE_EDITING_VI
8971 line_input_state->flags |= VI_MODE;
8973 line_input_state->flags &= ~VI_MODE;
8975 viflag = 0; /* forcibly keep the option off */
8979 static struct localvar *localvars;
8982 * Called after a function returns.
8983 * Interrupts must be off.
8988 struct localvar *lvp;
8991 while ((lvp = localvars) != NULL) {
8992 localvars = lvp->next;
8994 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
8995 if (vp == NULL) { /* $- saved */
8996 memcpy(optlist, lvp->text, sizeof(optlist));
8997 free((char*)lvp->text);
8999 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
9000 unsetvar(vp->var_text);
9003 vp->var_func(var_end(lvp->text));
9004 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9005 free((char*)vp->var_text);
9006 vp->flags = lvp->flags;
9007 vp->var_text = lvp->text;
9014 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9016 volatile struct shparam saveparam;
9017 struct localvar *volatile savelocalvars;
9018 struct jmploc *volatile savehandler;
9019 struct jmploc jmploc;
9022 saveparam = shellparam;
9023 savelocalvars = localvars;
9024 savehandler = exception_handler;
9025 e = setjmp(jmploc.loc);
9030 exception_handler = &jmploc;
9032 shellparam.malloced = 0;
9036 shellparam.nparam = argc - 1;
9037 shellparam.p = argv + 1;
9038 #if ENABLE_ASH_GETOPTS
9039 shellparam.optind = 1;
9040 shellparam.optoff = -1;
9042 evaltree(&func->n, flags & EV_TESTED);
9048 localvars = savelocalvars;
9049 freeparam(&shellparam);
9050 shellparam = saveparam;
9051 exception_handler = savehandler;
9053 evalskip &= ~SKIPFUNC;
9058 * Make a variable a local variable. When a variable is made local, it's
9059 * value and flags are saved in a localvar structure. The saved values
9060 * will be restored when the shell function returns. We handle the name
9061 * "-" as a special case: it makes changes to "set +-options" local
9062 * (options will be restored on return from the function).
9067 struct localvar *lvp;
9070 char *eq = strchr(name, '=');
9073 /* Cater for duplicate "local". Examples:
9074 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9075 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9079 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9083 * it's a duplicate "local VAR" declaration, do nothing
9090 lvp = ckzalloc(sizeof(*lvp));
9091 if (LONE_DASH(name)) {
9093 p = ckmalloc(sizeof(optlist));
9094 lvp->text = memcpy(p, optlist, sizeof(optlist));
9097 vpp = hashvar(name);
9098 vp = *findvar(vpp, name);
9100 /* variable did not exist yet */
9102 setvareq(name, VSTRFIXED);
9104 setvar(name, NULL, VSTRFIXED);
9105 vp = *vpp; /* the new variable */
9106 lvp->flags = VUNSET;
9108 lvp->text = vp->var_text;
9109 lvp->flags = vp->flags;
9110 /* make sure neither "struct var" nor string gets freed
9111 * during (un)setting:
9113 vp->flags |= VSTRFIXED|VTEXTFIXED;
9117 /* "local VAR" unsets VAR: */
9118 setvar0(name, NULL);
9122 lvp->next = localvars;
9128 * The "local" command.
9130 static int FAST_FUNC
9131 localcmd(int argc UNUSED_PARAM, char **argv)
9136 ash_msg_and_raise_error("not in a function");
9139 while ((name = *argv++) != NULL) {
9145 static int FAST_FUNC
9146 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9151 static int FAST_FUNC
9152 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9157 static int FAST_FUNC
9158 execcmd(int argc UNUSED_PARAM, char **argv)
9161 iflag = 0; /* exit on error */
9164 /* We should set up signals for "exec CMD"
9165 * the same way as for "CMD" without "exec".
9166 * But optschanged->setinteractive->setsignal
9167 * still thought we are a root shell. Therefore, for example,
9168 * SIGQUIT is still set to IGN. Fix it:
9172 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9173 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9174 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9176 shellexec(argv + 1, pathval(), 0);
9183 * The return command.
9185 static int FAST_FUNC
9186 returncmd(int argc UNUSED_PARAM, char **argv)
9189 * If called outside a function, do what ksh does;
9190 * skip the rest of the file.
9192 evalskip = SKIPFUNC;
9193 return argv[1] ? number(argv[1]) : exitstatus;
9196 /* Forward declarations for builtintab[] */
9197 static int breakcmd(int, char **) FAST_FUNC;
9198 static int dotcmd(int, char **) FAST_FUNC;
9199 static int evalcmd(int, char **, int) FAST_FUNC;
9200 static int exitcmd(int, char **) FAST_FUNC;
9201 static int exportcmd(int, char **) FAST_FUNC;
9202 #if ENABLE_ASH_GETOPTS
9203 static int getoptscmd(int, char **) FAST_FUNC;
9206 static int helpcmd(int, char **) FAST_FUNC;
9209 static int historycmd(int, char **) FAST_FUNC;
9211 #if ENABLE_SH_MATH_SUPPORT
9212 static int letcmd(int, char **) FAST_FUNC;
9214 static int readcmd(int, char **) FAST_FUNC;
9215 static int setcmd(int, char **) FAST_FUNC;
9216 static int shiftcmd(int, char **) FAST_FUNC;
9217 static int timescmd(int, char **) FAST_FUNC;
9218 static int trapcmd(int, char **) FAST_FUNC;
9219 static int umaskcmd(int, char **) FAST_FUNC;
9220 static int unsetcmd(int, char **) FAST_FUNC;
9221 static int ulimitcmd(int, char **) FAST_FUNC;
9223 #define BUILTIN_NOSPEC "0"
9224 #define BUILTIN_SPECIAL "1"
9225 #define BUILTIN_REGULAR "2"
9226 #define BUILTIN_SPEC_REG "3"
9227 #define BUILTIN_ASSIGN "4"
9228 #define BUILTIN_SPEC_ASSG "5"
9229 #define BUILTIN_REG_ASSG "6"
9230 #define BUILTIN_SPEC_REG_ASSG "7"
9232 /* Stubs for calling non-FAST_FUNC's */
9233 #if ENABLE_ASH_BUILTIN_ECHO
9234 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9236 #if ENABLE_ASH_BUILTIN_PRINTF
9237 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9239 #if ENABLE_ASH_BUILTIN_TEST
9240 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9243 /* Keep these in proper order since it is searched via bsearch() */
9244 static const struct builtincmd builtintab[] = {
9245 { BUILTIN_SPEC_REG "." , dotcmd },
9246 { BUILTIN_SPEC_REG ":" , truecmd },
9247 #if ENABLE_ASH_BUILTIN_TEST
9248 { BUILTIN_REGULAR "[" , testcmd },
9249 #if ENABLE_ASH_BASH_COMPAT
9250 { BUILTIN_REGULAR "[[" , testcmd },
9253 #if ENABLE_ASH_ALIAS
9254 { BUILTIN_REG_ASSG "alias" , aliascmd },
9257 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9259 { BUILTIN_SPEC_REG "break" , breakcmd },
9260 { BUILTIN_REGULAR "cd" , cdcmd },
9261 { BUILTIN_NOSPEC "chdir" , cdcmd },
9262 #if ENABLE_ASH_CMDCMD
9263 { BUILTIN_REGULAR "command" , commandcmd },
9265 { BUILTIN_SPEC_REG "continue", breakcmd },
9266 #if ENABLE_ASH_BUILTIN_ECHO
9267 { BUILTIN_REGULAR "echo" , echocmd },
9269 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9270 { BUILTIN_SPEC_REG "exec" , execcmd },
9271 { BUILTIN_SPEC_REG "exit" , exitcmd },
9272 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9273 { BUILTIN_REGULAR "false" , falsecmd },
9275 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9277 #if ENABLE_ASH_GETOPTS
9278 { BUILTIN_REGULAR "getopts" , getoptscmd },
9280 { BUILTIN_NOSPEC "hash" , hashcmd },
9282 { BUILTIN_NOSPEC "help" , helpcmd },
9285 { BUILTIN_NOSPEC "history" , historycmd },
9288 { BUILTIN_REGULAR "jobs" , jobscmd },
9289 { BUILTIN_REGULAR "kill" , killcmd },
9291 #if ENABLE_SH_MATH_SUPPORT
9292 { BUILTIN_NOSPEC "let" , letcmd },
9294 { BUILTIN_ASSIGN "local" , localcmd },
9295 #if ENABLE_ASH_BUILTIN_PRINTF
9296 { BUILTIN_REGULAR "printf" , printfcmd },
9298 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9299 { BUILTIN_REGULAR "read" , readcmd },
9300 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9301 { BUILTIN_SPEC_REG "return" , returncmd },
9302 { BUILTIN_SPEC_REG "set" , setcmd },
9303 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9304 #if ENABLE_ASH_BASH_COMPAT
9305 { BUILTIN_SPEC_REG "source" , dotcmd },
9307 #if ENABLE_ASH_BUILTIN_TEST
9308 { BUILTIN_REGULAR "test" , testcmd },
9310 { BUILTIN_SPEC_REG "times" , timescmd },
9311 { BUILTIN_SPEC_REG "trap" , trapcmd },
9312 { BUILTIN_REGULAR "true" , truecmd },
9313 { BUILTIN_NOSPEC "type" , typecmd },
9314 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9315 { BUILTIN_REGULAR "umask" , umaskcmd },
9316 #if ENABLE_ASH_ALIAS
9317 { BUILTIN_REGULAR "unalias" , unaliascmd },
9319 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9320 { BUILTIN_REGULAR "wait" , waitcmd },
9323 /* Should match the above table! */
9324 #define COMMANDCMD (builtintab + \
9326 /* [ */ 1 * ENABLE_ASH_BUILTIN_TEST + \
9327 /* [[ */ 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9328 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9329 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9330 /* break cd cddir */ 3)
9331 #define EVALCMD (COMMANDCMD + \
9332 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9333 /* continue */ 1 + \
9334 /* echo */ 1 * ENABLE_ASH_BUILTIN_ECHO + \
9336 #define EXECCMD (EVALCMD + \
9340 * Search the table of builtin commands.
9342 static struct builtincmd *
9343 find_builtin(const char *name)
9345 struct builtincmd *bp;
9348 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9355 * Execute a simple command.
9358 isassignment(const char *p)
9360 const char *q = endofname(p);
9365 static int FAST_FUNC
9366 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9368 /* Preserve exitstatus of a previous possible redirection
9369 * as POSIX mandates */
9370 return back_exitstatus;
9373 evalcommand(union node *cmd, int flags)
9375 static const struct builtincmd null_bltin = {
9376 "\0\0", bltincmd /* why three NULs? */
9378 struct stackmark smark;
9380 struct arglist arglist;
9381 struct arglist varlist;
9384 const struct strlist *sp;
9385 struct cmdentry cmdentry;
9392 struct builtincmd *bcmd;
9393 smallint cmd_is_exec;
9394 smallint pseudovarflag = 0;
9396 /* First expand the arguments. */
9397 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9398 setstackmark(&smark);
9399 back_exitstatus = 0;
9401 cmdentry.cmdtype = CMDBUILTIN;
9402 cmdentry.u.cmd = &null_bltin;
9403 varlist.lastp = &varlist.list;
9404 *varlist.lastp = NULL;
9405 arglist.lastp = &arglist.list;
9406 *arglist.lastp = NULL;
9409 if (cmd->ncmd.args) {
9410 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9411 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9414 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9415 struct strlist **spp;
9417 spp = arglist.lastp;
9418 if (pseudovarflag && isassignment(argp->narg.text))
9419 expandarg(argp, &arglist, EXP_VARTILDE);
9421 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9423 for (sp = *spp; sp; sp = sp->next)
9427 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9428 for (sp = arglist.list; sp; sp = sp->next) {
9429 TRACE(("evalcommand arg: %s\n", sp->text));
9430 *nargv++ = sp->text;
9435 if (iflag && funcnest == 0 && argc > 0)
9436 lastarg = nargv[-1];
9439 expredir(cmd->ncmd.redirect);
9440 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9442 path = vpath.var_text;
9443 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9444 struct strlist **spp;
9447 spp = varlist.lastp;
9448 expandarg(argp, &varlist, EXP_VARTILDE);
9451 * Modify the command lookup path, if a PATH= assignment
9455 if (varcmp(p, path) == 0)
9459 /* Print the command if xflag is set. */
9462 const char *p = " %s" + 1;
9464 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9466 for (n = 0; n < 2; n++) {
9468 fdprintf(preverrout_fd, p, sp->text);
9474 safe_write(preverrout_fd, "\n", 1);
9480 /* Now locate the command. */
9482 int cmd_flag = DO_ERR;
9483 #if ENABLE_ASH_CMDCMD
9484 const char *oldpath = path + 5;
9488 find_command(argv[0], &cmdentry, cmd_flag, path);
9489 if (cmdentry.cmdtype == CMDUNKNOWN) {
9490 flush_stdout_stderr();
9495 /* implement bltin and command here */
9496 if (cmdentry.cmdtype != CMDBUILTIN)
9499 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9500 if (cmdentry.u.cmd == EXECCMD)
9502 #if ENABLE_ASH_CMDCMD
9503 if (cmdentry.u.cmd == COMMANDCMD) {
9505 nargv = parse_command_args(argv, &path);
9508 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9509 * nargv => "PROG". path is updated if -p.
9511 argc -= nargv - argv;
9513 cmd_flag |= DO_NOFUNC;
9521 /* We have a redirection error. */
9523 raise_exception(EXERROR);
9525 exitstatus = status;
9529 /* Execute the command. */
9530 switch (cmdentry.cmdtype) {
9533 #if ENABLE_FEATURE_SH_NOFORK
9534 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9535 * around run_nofork_applet() call.
9536 * (2) Should this check also be done in forkshell()?
9537 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9539 /* find_command() encodes applet_no as (-2 - applet_no) */
9540 int applet_no = (- cmdentry.u.index - 2);
9541 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9542 listsetvar(varlist.list, VEXPORT|VSTACK);
9543 /* run <applet>_main() */
9544 exitstatus = run_nofork_applet(applet_no, argv);
9548 /* Can we avoid forking off? For example, very last command
9549 * in a script or a subshell does not need forking,
9550 * we can just exec it.
9552 if (!(flags & EV_EXIT) || may_have_traps) {
9553 /* No, forking off a child is necessary */
9555 jp = makejob(/*cmd,*/ 1);
9556 if (forkshell(jp, cmd, FORK_FG) != 0) {
9558 status = waitforjob(jp);
9560 TRACE(("forked child exited with %d\n", status));
9565 /* fall through to exec'ing external program */
9567 listsetvar(varlist.list, VEXPORT|VSTACK);
9568 shellexec(argv, path, cmdentry.u.index);
9572 cmdenviron = varlist.list;
9574 struct strlist *list = cmdenviron;
9576 if (spclbltin > 0 || argc == 0) {
9578 if (cmd_is_exec && argc > 1)
9581 listsetvar(list, i);
9583 /* Tight loop with builtins only:
9584 * "while kill -0 $child; do true; done"
9585 * will never exit even if $child died, unless we do this
9586 * to reap the zombie and make kill detect that it's gone: */
9587 dowait(DOWAIT_NONBLOCK, NULL);
9589 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9591 int i = exception_type;
9592 if (i == EXEXIT || i == EXEXEC)
9596 exit_status = 128 + SIGINT;
9598 exit_status = 128 + pending_sig;
9599 exitstatus = exit_status;
9600 if (i == EXINT || spclbltin > 0) {
9602 longjmp(exception_handler->loc, 1);
9609 listsetvar(varlist.list, 0);
9610 /* See above for the rationale */
9611 dowait(DOWAIT_NONBLOCK, NULL);
9612 if (evalfun(cmdentry.u.func, argc, argv, flags))
9615 status = exitstatus;
9620 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9622 /* dsl: I think this is intended to be used to support
9623 * '_' in 'vi' command mode during line editing...
9624 * However I implemented that within libedit itself.
9626 setvar0("_", lastarg);
9628 popstackmark(&smark);
9634 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9636 char *volatile savecmdname;
9637 struct jmploc *volatile savehandler;
9638 struct jmploc jmploc;
9642 savecmdname = commandname;
9643 savehandler = exception_handler;
9644 i = setjmp(jmploc.loc);
9647 exception_handler = &jmploc;
9648 commandname = argv[0];
9650 optptr = NULL; /* initialize nextopt */
9652 status = evalcmd(argc, argv, flags);
9654 status = (*cmd->builtin)(argc, argv);
9655 flush_stdout_stderr();
9656 status |= ferror(stdout);
9657 exitstatus = status;
9660 commandname = savecmdname;
9661 exception_handler = savehandler;
9667 goodname(const char *p)
9669 return endofname(p)[0] == '\0';
9674 * Search for a command. This is called before we fork so that the
9675 * location of the command will be available in the parent as well as
9676 * the child. The check for "goodname" is an overly conservative
9677 * check that the name will not be subject to expansion.
9680 prehash(union node *n)
9682 struct cmdentry entry;
9684 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9685 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9689 /* ============ Builtin commands
9691 * Builtin commands whose functions are closely tied to evaluation
9692 * are implemented here.
9696 * Handle break and continue commands. Break, continue, and return are
9697 * all handled by setting the evalskip flag. The evaluation routines
9698 * above all check this flag, and if it is set they start skipping
9699 * commands rather than executing them. The variable skipcount is
9700 * the number of loops to break/continue, or the number of function
9701 * levels to return. (The latter is always 1.) It should probably
9702 * be an error to break out of more loops than exist, but it isn't
9703 * in the standard shell so we don't make it one here.
9705 static int FAST_FUNC
9706 breakcmd(int argc UNUSED_PARAM, char **argv)
9708 int n = argv[1] ? number(argv[1]) : 1;
9711 ash_msg_and_raise_error(msg_illnum, argv[1]);
9715 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9722 /* ============ input.c
9724 * This implements the input routines used by the parser.
9728 INPUT_PUSH_FILE = 1,
9729 INPUT_NOFILE_OK = 2,
9732 static smallint checkkwd;
9733 /* values of checkkwd variable */
9734 #define CHKALIAS 0x1
9739 * Push a string back onto the input at this current parsefile level.
9740 * We handle aliases this way.
9742 #if !ENABLE_ASH_ALIAS
9743 #define pushstring(s, ap) pushstring(s)
9746 pushstring(char *s, struct alias *ap)
9753 if (g_parsefile->strpush) {
9754 sp = ckzalloc(sizeof(*sp));
9755 sp->prev = g_parsefile->strpush;
9757 sp = &(g_parsefile->basestrpush);
9759 g_parsefile->strpush = sp;
9760 sp->prev_string = g_parsefile->next_to_pgetc;
9761 sp->prev_left_in_line = g_parsefile->left_in_line;
9762 sp->unget = g_parsefile->unget;
9763 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9764 #if ENABLE_ASH_ALIAS
9767 ap->flag |= ALIASINUSE;
9771 g_parsefile->next_to_pgetc = s;
9772 g_parsefile->left_in_line = len;
9773 g_parsefile->unget = 0;
9780 struct strpush *sp = g_parsefile->strpush;
9783 #if ENABLE_ASH_ALIAS
9785 if (g_parsefile->next_to_pgetc[-1] == ' '
9786 || g_parsefile->next_to_pgetc[-1] == '\t'
9788 checkkwd |= CHKALIAS;
9790 if (sp->string != sp->ap->val) {
9793 sp->ap->flag &= ~ALIASINUSE;
9794 if (sp->ap->flag & ALIASDEAD) {
9795 unalias(sp->ap->name);
9799 g_parsefile->next_to_pgetc = sp->prev_string;
9800 g_parsefile->left_in_line = sp->prev_left_in_line;
9801 g_parsefile->unget = sp->unget;
9802 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
9803 g_parsefile->strpush = sp->prev;
9804 if (sp != &(g_parsefile->basestrpush))
9813 char *buf = g_parsefile->buf;
9815 g_parsefile->next_to_pgetc = buf;
9816 #if ENABLE_FEATURE_EDITING
9818 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9819 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9822 # if ENABLE_ASH_IDLE_TIMEOUT
9824 const char *tmout_var = lookupvar("TMOUT");
9826 timeout = atoi(tmout_var) * 1000;
9832 # if ENABLE_FEATURE_TAB_COMPLETION
9833 line_input_state->path_lookup = pathval();
9835 reinit_unicode_for_ash();
9836 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9838 /* Ctrl+C pressed */
9849 /* Ctrl+D pressed */
9852 # if ENABLE_ASH_IDLE_TIMEOUT
9853 else if (errno == EAGAIN && timeout > 0) {
9854 puts("\007timed out waiting for input: auto-logout");
9861 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9864 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9866 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9867 int flags = fcntl(0, F_GETFL);
9868 if (flags >= 0 && (flags & O_NONBLOCK)) {
9869 flags &= ~O_NONBLOCK;
9870 if (fcntl(0, F_SETFL, flags) >= 0) {
9871 out2str("sh: turning off NDELAY mode\n");
9882 * Refill the input buffer and return the next input character:
9884 * 1) If a string was pushed back on the input, pop it;
9885 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9886 * or we are reading from a string so we can't refill the buffer,
9888 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9889 * 4) Process input up to the next newline, deleting nul characters.
9891 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9892 #define pgetc_debug(...) ((void)0)
9893 static int pgetc(void);
9900 if (g_parsefile->strpush) {
9901 #if ENABLE_ASH_ALIAS
9902 if (g_parsefile->left_in_line == -1
9903 && g_parsefile->strpush->ap
9904 && g_parsefile->next_to_pgetc[-1] != ' '
9905 && g_parsefile->next_to_pgetc[-1] != '\t'
9907 pgetc_debug("preadbuffer PEOA");
9914 /* on both branches above g_parsefile->left_in_line < 0.
9915 * "pgetc" needs refilling.
9918 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9919 * pungetc() may increment it a few times.
9920 * Assuming it won't increment it to less than -90.
9922 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9923 pgetc_debug("preadbuffer PEOF1");
9924 /* even in failure keep left_in_line and next_to_pgetc
9925 * in lock step, for correct multi-layer pungetc.
9926 * left_in_line was decremented before preadbuffer(),
9927 * must inc next_to_pgetc: */
9928 g_parsefile->next_to_pgetc++;
9932 more = g_parsefile->left_in_buffer;
9934 flush_stdout_stderr();
9938 /* don't try reading again */
9939 g_parsefile->left_in_line = -99;
9940 pgetc_debug("preadbuffer PEOF2");
9941 g_parsefile->next_to_pgetc++;
9946 /* Find out where's the end of line.
9947 * Set g_parsefile->left_in_line
9948 * and g_parsefile->left_in_buffer acordingly.
9949 * NUL chars are deleted.
9951 q = g_parsefile->next_to_pgetc;
9959 memmove(q, q + 1, more);
9963 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9969 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9970 if (g_parsefile->left_in_line < 0)
9975 g_parsefile->left_in_buffer = more;
9980 out2str(g_parsefile->next_to_pgetc);
9984 pgetc_debug("preadbuffer at %d:%p'%s'",
9985 g_parsefile->left_in_line,
9986 g_parsefile->next_to_pgetc,
9987 g_parsefile->next_to_pgetc);
9988 return (unsigned char)*g_parsefile->next_to_pgetc++;
9996 pgetc_debug("pgetc at %d:%p'%s'",
9997 g_parsefile->left_in_line,
9998 g_parsefile->next_to_pgetc,
9999 g_parsefile->next_to_pgetc);
10000 if (g_parsefile->unget)
10001 return g_parsefile->lastc[--g_parsefile->unget];
10003 if (--g_parsefile->left_in_line >= 0)
10004 c = (signed char)*g_parsefile->next_to_pgetc++;
10008 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10009 g_parsefile->lastc[0] = c;
10014 #if ENABLE_ASH_ALIAS
10016 pgetc_without_PEOA(void)
10020 pgetc_debug("pgetc at %d:%p'%s'",
10021 g_parsefile->left_in_line,
10022 g_parsefile->next_to_pgetc,
10023 g_parsefile->next_to_pgetc);
10025 } while (c == PEOA);
10029 # define pgetc_without_PEOA() pgetc()
10033 * Read a line from the script.
10036 pfgets(char *line, int len)
10042 while (--nleft > 0) {
10043 c = pgetc_without_PEOA();
10058 * Undo a call to pgetc. Only two characters may be pushed back.
10059 * PEOF may be pushed back.
10064 g_parsefile->unget++;
10067 /* This one eats backslash+newline */
10073 while ((c = pgetc()) == '\\') {
10074 if (pgetc() != '\n') {
10079 g_parsefile->linno++;
10080 setprompt_if(doprompt, 2);
10087 * To handle the "." command, a stack of input files is used. Pushfile
10088 * adds a new entry to the stack and popfile restores the previous level.
10093 struct parsefile *pf;
10095 pf = ckzalloc(sizeof(*pf));
10096 pf->prev = g_parsefile;
10098 /*pf->strpush = NULL; - ckzalloc did it */
10099 /*pf->basestrpush.prev = NULL;*/
10107 struct parsefile *pf = g_parsefile;
10110 if (pf->pf_fd >= 0)
10113 while (pf->strpush)
10115 g_parsefile = pf->prev;
10121 * Return to top level.
10126 while (g_parsefile != &basepf)
10131 * Close the file(s) that the shell is reading commands from. Called
10132 * after a fork is done.
10138 if (g_parsefile->pf_fd > 0) {
10139 close(g_parsefile->pf_fd);
10140 g_parsefile->pf_fd = 0;
10145 * Like setinputfile, but takes an open file descriptor. Call this with
10149 setinputfd(int fd, int push)
10151 close_on_exec_on(fd);
10154 g_parsefile->buf = NULL;
10156 g_parsefile->pf_fd = fd;
10157 if (g_parsefile->buf == NULL)
10158 g_parsefile->buf = ckmalloc(IBUFSIZ);
10159 g_parsefile->left_in_buffer = 0;
10160 g_parsefile->left_in_line = 0;
10161 g_parsefile->linno = 1;
10165 * Set the input to take input from a file. If push is set, push the
10166 * old input onto the stack first.
10169 setinputfile(const char *fname, int flags)
10175 fd = open(fname, O_RDONLY);
10177 if (flags & INPUT_NOFILE_OK)
10179 ash_msg_and_raise_error("can't open '%s'", fname);
10182 fd2 = copyfd(fd, 10);
10185 ash_msg_and_raise_error("out of file descriptors");
10188 setinputfd(fd, flags & INPUT_PUSH_FILE);
10195 * Like setinputfile, but takes input from a string.
10198 setinputstring(char *string)
10202 g_parsefile->next_to_pgetc = string;
10203 g_parsefile->left_in_line = strlen(string);
10204 g_parsefile->buf = NULL;
10205 g_parsefile->linno = 1;
10210 /* ============ mail.c
10212 * Routines to check for mail.
10215 #if ENABLE_ASH_MAIL
10217 /* Hash of mtimes of mailboxes */
10218 static unsigned mailtime_hash;
10219 /* Set if MAIL or MAILPATH is changed. */
10220 static smallint mail_var_path_changed;
10223 * Print appropriate message(s) if mail has arrived.
10224 * If mail_var_path_changed is set,
10225 * then the value of MAIL has mail_var_path_changed,
10226 * so we just update the values.
10235 struct stackmark smark;
10238 setstackmark(&smark);
10239 mpath = mpathset() ? mpathval() : mailval();
10242 p = path_advance(&mpath, nullstr);
10247 for (q = p; *q; q++)
10253 q[-1] = '\0'; /* delete trailing '/' */
10254 if (stat(p, &statb) < 0) {
10257 /* Very simplistic "hash": just a sum of all mtimes */
10258 new_hash += (unsigned)statb.st_mtime;
10260 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10261 if (mailtime_hash != 0)
10262 out2str("you have mail\n");
10263 mailtime_hash = new_hash;
10265 mail_var_path_changed = 0;
10266 popstackmark(&smark);
10269 static void FAST_FUNC
10270 changemail(const char *val UNUSED_PARAM)
10272 mail_var_path_changed = 1;
10275 #endif /* ASH_MAIL */
10278 /* ============ ??? */
10281 * Set the shell parameters.
10284 setparam(char **argv)
10290 for (nparam = 0; argv[nparam]; nparam++)
10292 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10294 *ap++ = ckstrdup(*argv++);
10297 freeparam(&shellparam);
10298 shellparam.malloced = 1;
10299 shellparam.nparam = nparam;
10300 shellparam.p = newparam;
10301 #if ENABLE_ASH_GETOPTS
10302 shellparam.optind = 1;
10303 shellparam.optoff = -1;
10308 * Process shell options. The global variable argptr contains a pointer
10309 * to the argument list; we advance it past the options.
10311 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10312 * For a non-interactive shell, an error condition encountered
10313 * by a special built-in ... shall cause the shell to write a diagnostic message
10314 * to standard error and exit as shown in the following table:
10315 * Error Special Built-In
10317 * Utility syntax error (option or operand error) Shall exit
10319 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10320 * we see that bash does not do that (set "finishes" with error code 1 instead,
10321 * and shell continues), and people rely on this behavior!
10323 * set -o barfoo 2>/dev/null
10326 * Oh well. Let's mimic that.
10329 plus_minus_o(char *name, int val)
10334 for (i = 0; i < NOPTS; i++) {
10335 if (strcmp(name, optnames(i)) == 0) {
10340 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10343 for (i = 0; i < NOPTS; i++) {
10345 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10347 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10353 setoption(int flag, int val)
10357 for (i = 0; i < NOPTS; i++) {
10358 if (optletters(i) == flag) {
10363 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10367 options(int cmdline)
10375 while ((p = *argptr) != NULL) {
10377 if (c != '-' && c != '+')
10380 val = 0; /* val = 0 if c == '+' */
10383 if (p[0] == '\0' || LONE_DASH(p)) {
10385 /* "-" means turn off -x and -v */
10388 /* "--" means reset params */
10389 else if (*argptr == NULL)
10392 break; /* "-" or "--" terminates options */
10395 /* first char was + or - */
10396 while ((c = *p++) != '\0') {
10397 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10398 if (c == 'c' && cmdline) {
10399 minusc = p; /* command is after shell args */
10400 } else if (c == 'o') {
10401 if (plus_minus_o(*argptr, val)) {
10402 /* it already printed err message */
10403 return 1; /* error */
10407 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10409 /* bash does not accept +-login, we also won't */
10410 } else if (cmdline && val && (c == '-')) { /* long options */
10411 if (strcmp(p, "login") == 0)
10423 * The shift builtin command.
10425 static int FAST_FUNC
10426 shiftcmd(int argc UNUSED_PARAM, char **argv)
10433 n = number(argv[1]);
10434 if (n > shellparam.nparam)
10435 n = 0; /* bash compat, was = shellparam.nparam; */
10437 shellparam.nparam -= n;
10438 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10439 if (shellparam.malloced)
10442 ap2 = shellparam.p;
10443 while ((*ap2++ = *ap1++) != NULL)
10445 #if ENABLE_ASH_GETOPTS
10446 shellparam.optind = 1;
10447 shellparam.optoff = -1;
10454 * POSIX requires that 'set' (but not export or readonly) output the
10455 * variables in lexicographic order - by the locale's collating order (sigh).
10456 * Maybe we could keep them in an ordered balanced binary tree
10457 * instead of hashed lists.
10458 * For now just roll 'em through qsort for printing...
10461 showvars(const char *sep_prefix, int on, int off)
10464 char **ep, **epend;
10466 ep = listvars(on, off, &epend);
10467 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10469 sep = *sep_prefix ? " " : sep_prefix;
10471 for (; ep < epend; ep++) {
10475 p = strchrnul(*ep, '=');
10478 q = single_quote(++p);
10479 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10485 * The set command builtin.
10487 static int FAST_FUNC
10488 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10493 return showvars(nullstr, 0, VUNSET);
10496 retval = options(/*cmdline:*/ 0);
10497 if (retval == 0) { /* if no parse error... */
10499 if (*argptr != NULL) {
10507 #if ENABLE_ASH_RANDOM_SUPPORT
10508 static void FAST_FUNC
10509 change_random(const char *value)
10513 if (value == NULL) {
10514 /* "get", generate */
10515 t = next_random(&random_gen);
10516 /* set without recursion */
10517 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10518 vrandom.flags &= ~VNOFUNC;
10521 t = strtoul(value, NULL, 10);
10522 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10527 #if ENABLE_ASH_GETOPTS
10529 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10540 if (*param_optind < 1)
10542 optnext = optfirst + *param_optind - 1;
10544 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10547 p = optnext[-1] + *optoff;
10548 if (p == NULL || *p == '\0') {
10549 /* Current word is done, advance */
10551 if (p == NULL || *p != '-' || *++p == '\0') {
10558 if (LONE_DASH(p)) /* check for "--" */
10563 for (q = optstr; *q != c;) {
10565 if (optstr[0] == ':') {
10567 /*sbuf[1] = '\0'; - already is */
10568 err |= setvarsafe("OPTARG", sbuf, 0);
10570 fprintf(stderr, "Illegal option -%c\n", c);
10571 unsetvar("OPTARG");
10581 if (*p == '\0' && (p = *optnext) == NULL) {
10582 if (optstr[0] == ':') {
10584 /*sbuf[1] = '\0'; - already is */
10585 err |= setvarsafe("OPTARG", sbuf, 0);
10588 fprintf(stderr, "No arg for -%c option\n", c);
10589 unsetvar("OPTARG");
10597 err |= setvarsafe("OPTARG", p, 0);
10600 err |= setvarsafe("OPTARG", nullstr, 0);
10602 *optoff = p ? p - *(optnext - 1) : -1;
10603 *param_optind = optnext - optfirst + 1;
10604 err |= setvarsafe("OPTIND", itoa(*param_optind), VNOFUNC);
10606 /*sbuf[1] = '\0'; - already is */
10607 err |= setvarsafe(optvar, sbuf, 0);
10611 flush_stdout_stderr();
10612 raise_exception(EXERROR);
10618 * The getopts builtin. Shellparam.optnext points to the next argument
10619 * to be processed. Shellparam.optptr points to the next character to
10620 * be processed in the current argument. If shellparam.optnext is NULL,
10621 * then it's the first time getopts has been called.
10623 static int FAST_FUNC
10624 getoptscmd(int argc, char **argv)
10629 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10631 optbase = shellparam.p;
10632 if (shellparam.optind > shellparam.nparam + 1) {
10633 shellparam.optind = 1;
10634 shellparam.optoff = -1;
10637 optbase = &argv[3];
10638 if (shellparam.optind > argc - 2) {
10639 shellparam.optind = 1;
10640 shellparam.optoff = -1;
10644 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10645 &shellparam.optoff);
10647 #endif /* ASH_GETOPTS */
10650 /* ============ Shell parser */
10653 struct heredoc *next; /* next here document in list */
10654 union node *here; /* redirection node */
10655 char *eofmark; /* string indicating end of input */
10656 smallint striptabs; /* if set, strip leading tabs */
10659 static smallint tokpushback; /* last token pushed back */
10660 static smallint quoteflag; /* set if (part of) last token was quoted */
10661 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10662 static struct heredoc *heredoclist; /* list of here documents to read */
10663 static char *wordtext; /* text of last word returned by readtoken */
10664 static struct nodelist *backquotelist;
10665 static union node *redirnode;
10666 static struct heredoc *heredoc;
10668 static const char *
10669 tokname(char *buf, int tok)
10672 return tokname_array[tok] + 1;
10673 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10677 /* raise_error_unexpected_syntax:
10678 * Called when an unexpected token is read during the parse. The argument
10679 * is the token that is expected, or -1 if more than one type of token can
10680 * occur at this point.
10682 static void raise_error_unexpected_syntax(int) NORETURN;
10684 raise_error_unexpected_syntax(int token)
10690 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10692 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10693 raise_error_syntax(msg);
10697 #define EOFMARKLEN 79
10699 /* parsing is heavily cross-recursive, need these forward decls */
10700 static union node *andor(void);
10701 static union node *pipeline(void);
10702 static union node *parse_command(void);
10703 static void parseheredoc(void);
10704 static int peektoken(void);
10705 static int readtoken(void);
10707 static union node *
10710 union node *n1, *n2, *n3;
10715 switch (peektoken()) {
10723 if (!n1 && (nlflag & 1))
10729 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10730 if (nlflag == 2 && tokname_array[peektoken()][0])
10736 if (tok == TBACKGND) {
10737 if (n2->type == NPIPE) {
10738 n2->npipe.pipe_backgnd = 1;
10740 if (n2->type != NREDIR) {
10741 n3 = stzalloc(sizeof(struct nredir));
10743 /*n3->nredir.redirect = NULL; - stzalloc did it */
10746 n2->type = NBACKGND;
10752 n3 = stzalloc(sizeof(struct nbinary));
10754 n3->nbinary.ch1 = n1;
10755 n3->nbinary.ch2 = n2;
10768 raise_error_unexpected_syntax(-1);
10775 static union node *
10778 union node *n1, *n2, *n3;
10786 } else if (t == TOR) {
10792 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10794 n3 = stzalloc(sizeof(struct nbinary));
10796 n3->nbinary.ch1 = n1;
10797 n3->nbinary.ch2 = n2;
10802 static union node *
10805 union node *n1, *n2, *pipenode;
10806 struct nodelist *lp, *prev;
10810 TRACE(("pipeline: entered\n"));
10811 if (readtoken() == TNOT) {
10813 checkkwd = CHKKWD | CHKALIAS;
10816 n1 = parse_command();
10817 if (readtoken() == TPIPE) {
10818 pipenode = stzalloc(sizeof(struct npipe));
10819 pipenode->type = NPIPE;
10820 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10821 lp = stzalloc(sizeof(struct nodelist));
10822 pipenode->npipe.cmdlist = lp;
10826 lp = stzalloc(sizeof(struct nodelist));
10827 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10828 lp->n = parse_command();
10830 } while (readtoken() == TPIPE);
10836 n2 = stzalloc(sizeof(struct nnot));
10844 static union node *
10849 n = stzalloc(sizeof(struct narg));
10851 /*n->narg.next = NULL; - stzalloc did it */
10852 n->narg.text = wordtext;
10853 n->narg.backquote = backquotelist;
10858 fixredir(union node *n, const char *text, int err)
10862 TRACE(("Fix redir %s %d\n", text, err));
10864 n->ndup.vname = NULL;
10866 fd = bb_strtou(text, NULL, 10);
10867 if (!errno && fd >= 0)
10868 n->ndup.dupfd = fd;
10869 else if (LONE_DASH(text))
10870 n->ndup.dupfd = -1;
10873 raise_error_syntax("bad fd number");
10874 n->ndup.vname = makename();
10879 * Returns true if the text contains nothing to expand (no dollar signs
10883 noexpand(const char *text)
10887 while ((c = *text++) != '\0') {
10888 if (c == CTLQUOTEMARK)
10892 else if (SIT(c, BASESYNTAX) == CCTL)
10901 union node *n = redirnode;
10903 if (readtoken() != TWORD)
10904 raise_error_unexpected_syntax(-1);
10905 if (n->type == NHERE) {
10906 struct heredoc *here = heredoc;
10910 if (quoteflag == 0)
10912 TRACE(("Here document %d\n", n->type));
10913 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10914 raise_error_syntax("illegal eof marker for << redirection");
10915 rmescapes(wordtext, 0);
10916 here->eofmark = wordtext;
10918 if (heredoclist == NULL)
10919 heredoclist = here;
10921 for (p = heredoclist; p->next; p = p->next)
10925 } else if (n->type == NTOFD || n->type == NFROMFD) {
10926 fixredir(n, wordtext, 0);
10928 n->nfile.fname = makename();
10932 static union node *
10935 union node *args, **app;
10936 union node *n = NULL;
10937 union node *vars, **vpp;
10938 union node **rpp, *redir;
10940 #if ENABLE_ASH_BASH_COMPAT
10941 smallint double_brackets_flag = 0;
10942 smallint function_flag = 0;
10952 savecheckkwd = CHKALIAS;
10955 checkkwd = savecheckkwd;
10958 #if ENABLE_ASH_BASH_COMPAT
10960 if (peektoken() != TWORD)
10961 raise_error_unexpected_syntax(TWORD);
10964 case TAND: /* "&&" */
10965 case TOR: /* "||" */
10966 if (!double_brackets_flag) {
10970 wordtext = (char *) (t == TAND ? "-a" : "-o");
10973 n = stzalloc(sizeof(struct narg));
10975 /*n->narg.next = NULL; - stzalloc did it */
10976 n->narg.text = wordtext;
10977 #if ENABLE_ASH_BASH_COMPAT
10978 if (strcmp("[[", wordtext) == 0)
10979 double_brackets_flag = 1;
10980 else if (strcmp("]]", wordtext) == 0)
10981 double_brackets_flag = 0;
10983 n->narg.backquote = backquotelist;
10984 if (savecheckkwd && isassignment(wordtext)) {
10986 vpp = &n->narg.next;
10989 app = &n->narg.next;
10992 #if ENABLE_ASH_BASH_COMPAT
10993 if (function_flag) {
10994 checkkwd = CHKNL | CHKKWD;
10995 switch (peektoken()) {
11007 if (strcmp("[[", wordtext) == 0)
11011 raise_error_unexpected_syntax(-1);
11017 *rpp = n = redirnode;
11018 rpp = &n->nfile.next;
11019 parsefname(); /* read name of redirection file */
11022 IF_ASH_BASH_COMPAT(do_func:)
11023 if (args && app == &args->narg.next
11026 struct builtincmd *bcmd;
11029 /* We have a function */
11030 if (IF_ASH_BASH_COMPAT(!function_flag &&) readtoken() != TRP)
11031 raise_error_unexpected_syntax(TRP);
11032 name = n->narg.text;
11033 if (!goodname(name)
11034 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11036 raise_error_syntax("bad function name");
11039 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11040 n->narg.next = parse_command();
11043 IF_ASH_BASH_COMPAT(function_flag = 0;)
11054 n = stzalloc(sizeof(struct ncmd));
11056 n->ncmd.args = args;
11057 n->ncmd.assign = vars;
11058 n->ncmd.redirect = redir;
11062 static union node *
11063 parse_command(void)
11065 union node *n1, *n2;
11066 union node *ap, **app;
11067 union node *cp, **cpp;
11068 union node *redir, **rpp;
11075 switch (readtoken()) {
11077 raise_error_unexpected_syntax(-1);
11080 n1 = stzalloc(sizeof(struct nif));
11082 n1->nif.test = list(0);
11083 if (readtoken() != TTHEN)
11084 raise_error_unexpected_syntax(TTHEN);
11085 n1->nif.ifpart = list(0);
11087 while (readtoken() == TELIF) {
11088 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11089 n2 = n2->nif.elsepart;
11091 n2->nif.test = list(0);
11092 if (readtoken() != TTHEN)
11093 raise_error_unexpected_syntax(TTHEN);
11094 n2->nif.ifpart = list(0);
11096 if (lasttoken == TELSE)
11097 n2->nif.elsepart = list(0);
11099 n2->nif.elsepart = NULL;
11107 n1 = stzalloc(sizeof(struct nbinary));
11108 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11109 n1->nbinary.ch1 = list(0);
11112 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
11113 got == TWORD ? wordtext : ""));
11114 raise_error_unexpected_syntax(TDO);
11116 n1->nbinary.ch2 = list(0);
11121 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11122 raise_error_syntax("bad for loop variable");
11123 n1 = stzalloc(sizeof(struct nfor));
11125 n1->nfor.var = wordtext;
11126 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11127 if (readtoken() == TIN) {
11129 while (readtoken() == TWORD) {
11130 n2 = stzalloc(sizeof(struct narg));
11132 /*n2->narg.next = NULL; - stzalloc did it */
11133 n2->narg.text = wordtext;
11134 n2->narg.backquote = backquotelist;
11136 app = &n2->narg.next;
11139 n1->nfor.args = ap;
11140 if (lasttoken != TNL && lasttoken != TSEMI)
11141 raise_error_unexpected_syntax(-1);
11143 n2 = stzalloc(sizeof(struct narg));
11145 /*n2->narg.next = NULL; - stzalloc did it */
11146 n2->narg.text = (char *)dolatstr;
11147 /*n2->narg.backquote = NULL;*/
11148 n1->nfor.args = n2;
11150 * Newline or semicolon here is optional (but note
11151 * that the original Bourne shell only allowed NL).
11153 if (lasttoken != TSEMI)
11156 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11157 if (readtoken() != TDO)
11158 raise_error_unexpected_syntax(TDO);
11159 n1->nfor.body = list(0);
11163 n1 = stzalloc(sizeof(struct ncase));
11165 if (readtoken() != TWORD)
11166 raise_error_unexpected_syntax(TWORD);
11167 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11169 /*n2->narg.next = NULL; - stzalloc did it */
11170 n2->narg.text = wordtext;
11171 n2->narg.backquote = backquotelist;
11172 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11173 if (readtoken() != TIN)
11174 raise_error_unexpected_syntax(TIN);
11175 cpp = &n1->ncase.cases;
11177 checkkwd = CHKNL | CHKKWD;
11179 while (t != TESAC) {
11180 if (lasttoken == TLP)
11182 *cpp = cp = stzalloc(sizeof(struct nclist));
11184 app = &cp->nclist.pattern;
11186 *app = ap = stzalloc(sizeof(struct narg));
11188 /*ap->narg.next = NULL; - stzalloc did it */
11189 ap->narg.text = wordtext;
11190 ap->narg.backquote = backquotelist;
11191 if (readtoken() != TPIPE)
11193 app = &ap->narg.next;
11196 //ap->narg.next = NULL;
11197 if (lasttoken != TRP)
11198 raise_error_unexpected_syntax(TRP);
11199 cp->nclist.body = list(2);
11201 cpp = &cp->nclist.next;
11203 checkkwd = CHKNL | CHKKWD;
11207 raise_error_unexpected_syntax(TENDCASE);
11214 n1 = stzalloc(sizeof(struct nredir));
11215 n1->type = NSUBSHELL;
11216 n1->nredir.n = list(0);
11217 /*n1->nredir.redirect = NULL; - stzalloc did it */
11224 IF_ASH_BASH_COMPAT(case TFUNCTION:)
11228 return simplecmd();
11231 if (readtoken() != t)
11232 raise_error_unexpected_syntax(t);
11235 /* Now check for redirection which may follow command */
11236 checkkwd = CHKKWD | CHKALIAS;
11238 while (readtoken() == TREDIR) {
11239 *rpp = n2 = redirnode;
11240 rpp = &n2->nfile.next;
11246 if (n1->type != NSUBSHELL) {
11247 n2 = stzalloc(sizeof(struct nredir));
11252 n1->nredir.redirect = redir;
11257 #if ENABLE_ASH_BASH_COMPAT
11259 decode_dollar_squote(void)
11261 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11267 p = strchr(C_escapes, c);
11272 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11276 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11278 } else if (c == 'x') { /* \xHH */
11282 } while (isxdigit(c) && --cnt);
11284 if (cnt == 3) { /* \x but next char is "bad" */
11288 } else { /* simple seq like \\ or \t */
11293 c = bb_process_escape_sequence((void*)&p);
11294 } else { /* unrecognized "\z": print both chars unless ' or " */
11295 if (c != '\'' && c != '"') {
11297 c |= 0x100; /* "please encode \, then me" */
11305 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11306 * is not NULL, read a here document. In the latter case, eofmark is the
11307 * word which marks the end of the document and striptabs is true if
11308 * leading tabs should be stripped from the document. The argument c
11309 * is the first character of the input token or document.
11311 * Because C does not have internal subroutines, I have simulated them
11312 * using goto's to implement the subroutine linkage. The following macros
11313 * will run code that appears at the end of readtoken1.
11315 #define CHECKEND() {goto checkend; checkend_return:;}
11316 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11317 #define PARSESUB() {goto parsesub; parsesub_return:;}
11318 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11319 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11320 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11322 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11324 /* NB: syntax parameter fits into smallint */
11325 /* c parameter is an unsigned char or PEOF or PEOA */
11328 char line[EOFMARKLEN + 1];
11329 struct nodelist *bqlist;
11333 smallint prevsyntax; /* syntax before arithmetic */
11334 #if ENABLE_ASH_EXPAND_PRMT
11335 smallint pssyntax; /* we are expanding a prompt string */
11337 int varnest; /* levels of variables expansion */
11338 int arinest; /* levels of arithmetic expansion */
11339 int parenlevel; /* levels of parens in arithmetic */
11340 int dqvarnest; /* levels of variables expansion within double quotes */
11342 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11344 startlinno = g_parsefile->linno;
11348 #if ENABLE_ASH_EXPAND_PRMT
11349 pssyntax = (syntax == PSSYNTAX);
11353 dblquote = (syntax == DQSYNTAX);
11359 STARTSTACKSTR(out);
11361 /* For each line, until end of word */
11362 CHECKEND(); /* set c to PEOF if at end of here document */
11363 for (;;) { /* until end of line or end of word */
11364 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11365 switch (SIT(c, syntax)) {
11366 case CNL: /* '\n' */
11367 if (syntax == BASESYNTAX)
11368 goto endword; /* exit outer loop */
11370 g_parsefile->linno++;
11371 setprompt_if(doprompt, 2);
11373 goto loop; /* continue outer loop */
11378 #if ENABLE_ASH_BASH_COMPAT
11379 if (c == '\\' && bash_dollar_squote) {
11380 c = decode_dollar_squote();
11382 /* skip $'\000', $'\x00' (like bash) */
11386 /* Unknown escape. Encode as '\z' */
11387 c = (unsigned char)c;
11388 if (eofmark == NULL || dblquote)
11389 USTPUTC(CTLESC, out);
11390 USTPUTC('\\', out);
11394 if (eofmark == NULL || dblquote)
11395 USTPUTC(CTLESC, out);
11398 case CBACK: /* backslash */
11399 c = pgetc_without_PEOA();
11401 USTPUTC(CTLESC, out);
11402 USTPUTC('\\', out);
11404 } else if (c == '\n') {
11405 setprompt_if(doprompt, 2);
11407 #if ENABLE_ASH_EXPAND_PRMT
11408 if (c == '$' && pssyntax) {
11409 USTPUTC(CTLESC, out);
11410 USTPUTC('\\', out);
11413 /* Backslash is retained if we are in "str" and next char isn't special */
11418 && (c != '"' || eofmark != NULL)
11420 USTPUTC('\\', out);
11422 USTPUTC(CTLESC, out);
11430 if (eofmark == NULL) {
11431 USTPUTC(CTLQUOTEMARK, out);
11439 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11440 if (eofmark != NULL && varnest == 0) {
11443 if (dqvarnest == 0) {
11444 syntax = BASESYNTAX;
11451 case CVAR: /* '$' */
11452 PARSESUB(); /* parse substitution */
11454 case CENDVAR: /* '}' */
11457 if (dqvarnest > 0) {
11464 #if ENABLE_SH_MATH_SUPPORT
11465 case CLP: /* '(' in arithmetic */
11469 case CRP: /* ')' in arithmetic */
11470 if (parenlevel > 0) {
11473 if (pgetc_eatbnl() == ')') {
11475 if (--arinest == 0) {
11476 syntax = prevsyntax;
11480 * unbalanced parens
11481 * (don't 2nd guess - no error)
11489 case CBQUOTE: /* '`' */
11493 goto endword; /* exit outer loop */
11497 if (varnest == 0) {
11498 #if ENABLE_ASH_BASH_COMPAT
11500 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11501 if (pgetc() == '>')
11502 c = 0x100 + '>'; /* flag &> */
11506 goto endword; /* exit outer loop */
11508 IF_ASH_ALIAS(if (c != PEOA))
11515 #if ENABLE_SH_MATH_SUPPORT
11516 if (syntax == ARISYNTAX)
11517 raise_error_syntax("missing '))'");
11519 if (syntax != BASESYNTAX && eofmark == NULL)
11520 raise_error_syntax("unterminated quoted string");
11521 if (varnest != 0) {
11522 startlinno = g_parsefile->linno;
11524 raise_error_syntax("missing '}'");
11526 USTPUTC('\0', out);
11527 len = out - (char *)stackblock();
11528 out = stackblock();
11529 if (eofmark == NULL) {
11530 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11533 if (isdigit_str9(out)) {
11534 PARSEREDIR(); /* passed as params: out, c */
11535 lasttoken = TREDIR;
11538 /* else: non-number X seen, interpret it
11539 * as "NNNX>file" = "NNNX >file" */
11543 quoteflag = quotef;
11544 backquotelist = bqlist;
11545 grabstackblock(len);
11549 /* end of readtoken routine */
11552 * Check to see whether we are at the end of the here document. When this
11553 * is called, c is set to the first character of the next input line. If
11554 * we are at the end of the here document, this routine sets the c to PEOF.
11558 #if ENABLE_ASH_ALIAS
11560 c = pgetc_without_PEOA();
11563 while (c == '\t') {
11564 c = pgetc_without_PEOA();
11567 if (c == *eofmark) {
11568 if (pfgets(line, sizeof(line)) != NULL) {
11572 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11574 if (*p == '\n' && *q == '\0') {
11576 g_parsefile->linno++;
11577 needprompt = doprompt;
11579 pushstring(line, NULL);
11584 goto checkend_return;
11588 * Parse a redirection operator. The variable "out" points to a string
11589 * specifying the fd to be redirected. The variable "c" contains the
11590 * first character of the redirection operator.
11593 /* out is already checked to be a valid number or "" */
11594 int fd = (*out == '\0' ? -1 : atoi(out));
11597 np = stzalloc(sizeof(struct nfile));
11602 np->type = NAPPEND;
11604 np->type = NCLOBBER;
11607 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11613 #if ENABLE_ASH_BASH_COMPAT
11614 else if (c == 0x100 + '>') { /* this flags &> redirection */
11616 pgetc(); /* this is '>', no need to check */
11620 else { /* c == '<' */
11621 /*np->nfile.fd = 0; - stzalloc did it */
11625 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11626 np = stzalloc(sizeof(struct nhere));
11627 /*np->nfile.fd = 0; - stzalloc did it */
11630 heredoc = stzalloc(sizeof(struct heredoc));
11631 heredoc->here = np;
11634 heredoc->striptabs = 1;
11636 /*heredoc->striptabs = 0; - stzalloc did it */
11642 np->type = NFROMFD;
11646 np->type = NFROMTO;
11658 goto parseredir_return;
11662 * Parse a substitution. At this point, we have read the dollar sign
11663 * and nothing else.
11666 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11667 * (assuming ascii char codes, as the original implementation did) */
11668 #define is_special(c) \
11669 (((unsigned)(c) - 33 < 32) \
11670 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11672 unsigned char subtype;
11676 c = pgetc_eatbnl();
11677 if (c > 255 /* PEOA or PEOF */
11678 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11680 #if ENABLE_ASH_BASH_COMPAT
11681 if (syntax != DQSYNTAX && c == '\'')
11682 bash_dollar_squote = 1;
11687 } else if (c == '(') {
11688 /* $(command) or $((arith)) */
11689 if (pgetc_eatbnl() == '(') {
11690 #if ENABLE_SH_MATH_SUPPORT
11693 raise_error_syntax("you disabled math support for $((arith)) syntax");
11700 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11701 USTPUTC(CTLVAR, out);
11702 typeloc = out - (char *)stackblock();
11703 USTPUTC(VSNORMAL, out);
11704 subtype = VSNORMAL;
11706 c = pgetc_eatbnl();
11708 c = pgetc_eatbnl();
11710 c = '#'; /* ${#} - same as $# */
11712 subtype = VSLENGTH; /* ${#VAR} */
11717 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11718 /* $[{[#]]NAME[}] */
11721 c = pgetc_eatbnl();
11722 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11723 } else if (isdigit(c)) {
11724 /* $[{[#]]NUM[}] */
11727 c = pgetc_eatbnl();
11728 } while (isdigit(c));
11729 } else if (is_special(c)) {
11730 /* $[{[#]]<specialchar>[}] */
11732 c = pgetc_eatbnl();
11735 raise_error_syntax("bad substitution");
11737 if (c != '}' && subtype == VSLENGTH) {
11738 /* ${#VAR didn't end with } */
11744 if (subtype == 0) {
11745 static const char types[] ALIGN1 = "}-+?=";
11746 /* ${VAR...} but not $VAR or ${#VAR} */
11747 /* c == first char after VAR */
11750 c = pgetc_eatbnl();
11751 #if ENABLE_ASH_BASH_COMPAT
11752 /* This check is only needed to not misinterpret
11753 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11756 if (!strchr(types, c)) {
11757 subtype = VSSUBSTR;
11759 break; /* "goto do_pungetc" is bigger (!) */
11765 const char *p = strchr(types, c);
11768 subtype = p - types + VSNORMAL;
11774 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11775 c = pgetc_eatbnl();
11781 #if ENABLE_ASH_BASH_COMPAT
11783 /* ${v/[/]pattern/repl} */
11784 //TODO: encode pattern and repl separately.
11785 // Currently ${v/$var_with_slash/repl} is horribly broken
11786 subtype = VSREPLACE;
11787 c = pgetc_eatbnl();
11790 subtype++; /* VSREPLACEALL */
11798 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11799 if (subtype != VSNORMAL) {
11806 goto parsesub_return;
11810 * Called to parse command substitutions. Newstyle is set if the command
11811 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11812 * list of commands (passed by reference), and savelen is the number of
11813 * characters on the top of the stack which must be preserved.
11816 struct nodelist **nlpp;
11820 smallint saveprompt = 0;
11823 savelen = out - (char *)stackblock();
11826 * FIXME: this can allocate very large block on stack and SEGV.
11828 * echo "..<100kbytes>..`true` $(true) `true` ..."
11829 * allocates 100kb for every command subst. With about
11830 * a hundred command substitutions stack overflows.
11831 * With larger prepended string, SEGV happens sooner.
11833 str = alloca(savelen);
11834 memcpy(str, stackblock(), savelen);
11838 /* We must read until the closing backquote, giving special
11839 * treatment to some slashes, and then push the string and
11840 * reread it as input, interpreting it normally.
11846 STARTSTACKSTR(pout);
11850 setprompt_if(needprompt, 2);
11859 g_parsefile->linno++;
11860 setprompt_if(doprompt, 2);
11862 * If eating a newline, avoid putting
11863 * the newline into the new character
11864 * stream (via the STPUTC after the
11869 if (pc != '\\' && pc != '`' && pc != '$'
11870 && (!dblquote || pc != '"')
11872 STPUTC('\\', pout);
11874 if (pc <= 255 /* not PEOA or PEOF */) {
11880 IF_ASH_ALIAS(case PEOA:)
11881 startlinno = g_parsefile->linno;
11882 raise_error_syntax("EOF in backquote substitution");
11885 g_parsefile->linno++;
11886 needprompt = doprompt;
11895 STPUTC('\0', pout);
11896 psavelen = pout - (char *)stackblock();
11897 if (psavelen > 0) {
11898 pstr = grabstackstr(pout);
11899 setinputstring(pstr);
11904 nlpp = &(*nlpp)->next;
11905 *nlpp = stzalloc(sizeof(**nlpp));
11906 /* (*nlpp)->next = NULL; - stzalloc did it */
11909 saveprompt = doprompt;
11916 doprompt = saveprompt;
11917 else if (readtoken() != TRP)
11918 raise_error_unexpected_syntax(TRP);
11923 * Start reading from old file again, ignoring any pushed back
11924 * tokens left from the backquote parsing
11929 while (stackblocksize() <= savelen)
11931 STARTSTACKSTR(out);
11933 memcpy(out, str, savelen);
11934 STADJUST(savelen, out);
11936 USTPUTC(CTLBACKQ, out);
11938 goto parsebackq_oldreturn;
11939 goto parsebackq_newreturn;
11942 #if ENABLE_SH_MATH_SUPPORT
11944 * Parse an arithmetic expansion (indicate start of one and set state)
11947 if (++arinest == 1) {
11948 prevsyntax = syntax;
11949 syntax = ARISYNTAX;
11951 USTPUTC(CTLARI, out);
11952 goto parsearith_return;
11955 } /* end of readtoken */
11958 * Read the next input token.
11959 * If the token is a word, we set backquotelist to the list of cmds in
11960 * backquotes. We set quoteflag to true if any part of the word was
11962 * If the token is TREDIR, then we set redirnode to a structure containing
11964 * In all cases, the variable startlinno is set to the number of the line
11965 * on which the token starts.
11967 * [Change comment: here documents and internal procedures]
11968 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11969 * word parsing code into a separate routine. In this case, readtoken
11970 * doesn't need to have any internal procedures, but parseword does.
11971 * We could also make parseoperator in essence the main routine, and
11972 * have parseword (readtoken1?) handle both words and redirection.]
11974 #define NEW_xxreadtoken
11975 #ifdef NEW_xxreadtoken
11976 /* singles must be first! */
11977 static const char xxreadtoken_chars[7] ALIGN1 = {
11978 '\n', '(', ')', /* singles */
11979 '&', '|', ';', /* doubles */
11983 #define xxreadtoken_singles 3
11984 #define xxreadtoken_doubles 3
11986 static const char xxreadtoken_tokens[] ALIGN1 = {
11987 TNL, TLP, TRP, /* only single occurrence allowed */
11988 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11989 TEOF, /* corresponds to trailing nul */
11990 TAND, TOR, TENDCASE /* if double occurrence */
12002 setprompt_if(needprompt, 2);
12003 startlinno = g_parsefile->linno;
12004 for (;;) { /* until token or start of word found */
12006 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12010 while ((c = pgetc()) != '\n' && c != PEOF)
12013 } else if (c == '\\') {
12014 if (pgetc() != '\n') {
12016 break; /* return readtoken1(...) */
12018 startlinno = ++g_parsefile->linno;
12019 setprompt_if(doprompt, 2);
12023 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12026 g_parsefile->linno++;
12027 needprompt = doprompt;
12030 p = strchr(xxreadtoken_chars, c);
12032 break; /* return readtoken1(...) */
12034 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12036 if (cc == c) { /* double occurrence? */
12037 p += xxreadtoken_doubles + 1;
12040 #if ENABLE_ASH_BASH_COMPAT
12041 if (c == '&' && cc == '>') /* &> */
12042 break; /* return readtoken1(...) */
12047 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12052 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12054 #else /* old xxreadtoken */
12055 #define RETURN(token) return lasttoken = token
12065 setprompt_if(needprompt, 2);
12066 startlinno = g_parsefile->linno;
12067 for (;;) { /* until token or start of word found */
12070 case ' ': case '\t':
12071 IF_ASH_ALIAS(case PEOA:)
12074 while ((c = pgetc()) != '\n' && c != PEOF)
12079 if (pgetc() == '\n') {
12080 startlinno = ++g_parsefile->linno;
12081 setprompt_if(doprompt, 2);
12087 g_parsefile->linno++;
12088 needprompt = doprompt;
12093 if (pgetc() == '&')
12098 if (pgetc() == '|')
12103 if (pgetc() == ';')
12116 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12119 #endif /* old xxreadtoken */
12125 int kwd = checkkwd;
12127 smallint alreadyseen = tokpushback;
12130 #if ENABLE_ASH_ALIAS
12146 if (t != TWORD || quoteflag) {
12151 * check for keywords
12153 if (kwd & CHKKWD) {
12154 const char *const *pp;
12156 pp = findkwd(wordtext);
12158 lasttoken = t = pp - tokname_array;
12159 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
12164 if (checkkwd & CHKALIAS) {
12165 #if ENABLE_ASH_ALIAS
12167 ap = lookupalias(wordtext, 1);
12170 pushstring(ap->val, ap);
12180 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
12182 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
12198 * Read and parse a command. Returns NODE_EOF on end of file.
12199 * (NULL is a valid parse tree indicating a blank line.)
12201 static union node *
12202 parsecmd(int interact)
12207 doprompt = interact;
12208 setprompt_if(doprompt, doprompt);
12214 * Input any here documents.
12219 struct heredoc *here;
12222 here = heredoclist;
12223 heredoclist = NULL;
12226 setprompt_if(needprompt, 2);
12227 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12228 here->eofmark, here->striptabs);
12229 n = stzalloc(sizeof(struct narg));
12230 n->narg.type = NARG;
12231 /*n->narg.next = NULL; - stzalloc did it */
12232 n->narg.text = wordtext;
12233 n->narg.backquote = backquotelist;
12234 here->here->nhere.doc = n;
12241 * called by editline -- any expansions to the prompt should be added here.
12243 #if ENABLE_ASH_EXPAND_PRMT
12244 static const char *
12245 expandstr(const char *ps)
12249 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12250 * and token processing _can_ alter it (delete NULs etc). */
12251 setinputstring((char *)ps);
12252 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12255 n.narg.type = NARG;
12256 n.narg.next = NULL;
12257 n.narg.text = wordtext;
12258 n.narg.backquote = backquotelist;
12260 expandarg(&n, NULL, EXP_QUOTED);
12261 return stackblock();
12266 * Execute a command or commands contained in a string.
12269 evalstring(char *s, int flags)
12272 struct stackmark smark;
12277 setstackmark(&smark);
12280 while ((n = parsecmd(0)) != NODE_EOF) {
12283 i = evaltree(n, flags);
12286 popstackmark(&smark);
12290 popstackmark(&smark);
12298 * The eval command.
12300 static int FAST_FUNC
12301 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12310 STARTSTACKSTR(concat);
12312 concat = stack_putstr(p, concat);
12316 STPUTC(' ', concat);
12318 STPUTC('\0', concat);
12319 p = grabstackstr(concat);
12321 return evalstring(p, flags & EV_TESTED);
12327 * Read and execute commands.
12328 * "Top" is nonzero for the top level command loop;
12329 * it turns on prompting if the shell is interactive.
12335 struct stackmark smark;
12340 TRACE(("cmdloop(%d) called\n", top));
12344 setstackmark(&smark);
12347 showjobs(SHOW_CHANGED|SHOW_STDERR);
12350 if (iflag && top) {
12354 n = parsecmd(inter);
12356 if (DEBUG > 2 && debug && (n != NODE_EOF))
12359 if (n == NODE_EOF) {
12360 if (!top || numeof >= 50)
12362 if (!stoppedjobs()) {
12365 out2str("\nUse \"exit\" to leave shell.\n");
12368 } else if (nflag == 0) {
12371 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12374 i = evaltree(n, 0);
12378 popstackmark(&smark);
12382 evalskip &= ~SKIPFUNC;
12390 * Take commands from a file. To be compatible we should do a path
12391 * search for the file, which is necessary to find sub-commands.
12394 find_dot_file(char *name)
12397 const char *path = pathval();
12400 /* don't try this for absolute or relative paths */
12401 if (strchr(name, '/'))
12404 /* IIRC standards do not say whether . is to be searched.
12405 * And it is even smaller this way, making it unconditional for now:
12407 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12412 while ((fullname = path_advance(&path, name)) != NULL) {
12414 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12416 * Don't bother freeing here, since it will
12417 * be freed by the caller.
12421 if (fullname != name)
12422 stunalloc(fullname);
12425 /* not found in the PATH */
12426 ash_msg_and_raise_error("%s: not found", name);
12430 static int FAST_FUNC
12431 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12433 /* "false; . empty_file; echo $?" should print 0, not 1: */
12437 struct strlist *sp;
12438 volatile struct shparam saveparam;
12440 for (sp = cmdenviron; sp; sp = sp->next)
12441 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12443 nextopt(nullstr); /* handle possible "--" */
12447 /* bash says: "bash: .: filename argument required" */
12448 return 2; /* bash compat */
12451 /* This aborts if file isn't found, which is POSIXly correct.
12452 * bash returns exitcode 1 instead.
12454 fullname = find_dot_file(argv[0]);
12456 if (argv[0]) { /* . FILE ARGS, ARGS exist */
12458 saveparam = shellparam;
12459 shellparam.malloced = 0;
12463 shellparam.nparam = argc;
12464 shellparam.p = argv;
12467 /* This aborts if file can't be opened, which is POSIXly correct.
12468 * bash returns exitcode 1 instead.
12470 setinputfile(fullname, INPUT_PUSH_FILE);
12471 commandname = fullname;
12472 status = cmdloop(0);
12476 freeparam(&shellparam);
12477 shellparam = saveparam;
12483 static int FAST_FUNC
12484 exitcmd(int argc UNUSED_PARAM, char **argv)
12489 exitstatus = number(argv[1]);
12490 raise_exception(EXEXIT);
12495 * Read a file containing shell functions.
12498 readcmdfile(char *name)
12500 setinputfile(name, INPUT_PUSH_FILE);
12506 /* ============ find_command inplementation */
12509 * Resolve a command name. If you change this routine, you may have to
12510 * change the shellexec routine as well.
12513 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12515 struct tblentry *cmdp;
12522 struct builtincmd *bcmd;
12524 /* If name contains a slash, don't use PATH or hash table */
12525 if (strchr(name, '/') != NULL) {
12526 entry->u.index = -1;
12527 if (act & DO_ABS) {
12528 while (stat(name, &statb) < 0) {
12530 if (errno == EINTR)
12533 entry->cmdtype = CMDUNKNOWN;
12537 entry->cmdtype = CMDNORMAL;
12541 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12543 updatetbl = (path == pathval());
12546 if (strstr(path, "%builtin") != NULL)
12547 act |= DO_ALTBLTIN;
12550 /* If name is in the table, check answer will be ok */
12551 cmdp = cmdlookup(name, 0);
12552 if (cmdp != NULL) {
12555 switch (cmdp->cmdtype) {
12573 } else if (cmdp->rehash == 0)
12574 /* if not invalidated by cd, we're done */
12578 /* If %builtin not in path, check for builtin next */
12579 bcmd = find_builtin(name);
12581 if (IS_BUILTIN_REGULAR(bcmd))
12582 goto builtin_success;
12583 if (act & DO_ALTPATH) {
12584 if (!(act & DO_ALTBLTIN))
12585 goto builtin_success;
12586 } else if (builtinloc <= 0) {
12587 goto builtin_success;
12591 #if ENABLE_FEATURE_SH_STANDALONE
12593 int applet_no = find_applet_by_name(name);
12594 if (applet_no >= 0) {
12595 entry->cmdtype = CMDNORMAL;
12596 entry->u.index = -2 - applet_no;
12602 /* We have to search path. */
12603 prev = -1; /* where to start */
12604 if (cmdp && cmdp->rehash) { /* doing a rehash */
12605 if (cmdp->cmdtype == CMDBUILTIN)
12608 prev = cmdp->param.index;
12614 while ((fullname = path_advance(&path, name)) != NULL) {
12615 stunalloc(fullname);
12616 /* NB: code below will still use fullname
12617 * despite it being "unallocated" */
12620 if (prefix(pathopt, "builtin")) {
12622 goto builtin_success;
12625 if ((act & DO_NOFUNC)
12626 || !prefix(pathopt, "func")
12627 ) { /* ignore unimplemented options */
12631 /* if rehash, don't redo absolute path names */
12632 if (fullname[0] == '/' && idx <= prev) {
12635 TRACE(("searchexec \"%s\": no change\n", name));
12638 while (stat(fullname, &statb) < 0) {
12640 if (errno == EINTR)
12643 if (errno != ENOENT && errno != ENOTDIR)
12647 e = EACCES; /* if we fail, this will be the error */
12648 if (!S_ISREG(statb.st_mode))
12650 if (pathopt) { /* this is a %func directory */
12651 stalloc(strlen(fullname) + 1);
12652 /* NB: stalloc will return space pointed by fullname
12653 * (because we don't have any intervening allocations
12654 * between stunalloc above and this stalloc) */
12655 readcmdfile(fullname);
12656 cmdp = cmdlookup(name, 0);
12657 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12658 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12659 stunalloc(fullname);
12662 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12664 entry->cmdtype = CMDNORMAL;
12665 entry->u.index = idx;
12669 cmdp = cmdlookup(name, 1);
12670 cmdp->cmdtype = CMDNORMAL;
12671 cmdp->param.index = idx;
12676 /* We failed. If there was an entry for this command, delete it */
12677 if (cmdp && updatetbl)
12678 delete_cmd_entry();
12680 ash_msg("%s: %s", name, errmsg(e, "not found"));
12681 entry->cmdtype = CMDUNKNOWN;
12686 entry->cmdtype = CMDBUILTIN;
12687 entry->u.cmd = bcmd;
12691 cmdp = cmdlookup(name, 1);
12692 cmdp->cmdtype = CMDBUILTIN;
12693 cmdp->param.cmd = bcmd;
12697 entry->cmdtype = cmdp->cmdtype;
12698 entry->u = cmdp->param;
12702 /* ============ trap.c */
12705 * The trap builtin.
12707 static int FAST_FUNC
12708 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12712 int signo, exitcode;
12717 for (signo = 0; signo < NSIG; signo++) {
12718 char *tr = trap_ptr[signo];
12720 /* note: bash adds "SIG", but only if invoked
12721 * as "bash". If called as "sh", or if set -o posix,
12722 * then it prints short signal names.
12723 * We are printing short names: */
12724 out1fmt("trap -- %s %s\n",
12726 get_signame(signo));
12727 /* trap_ptr != trap only if we are in special-cased `trap` code.
12728 * In this case, we will exit very soon, no need to free(). */
12729 /* if (trap_ptr != trap && tp[0]) */
12734 if (trap_ptr != trap) {
12747 signo = get_signum(*ap);
12749 /* Mimic bash message exactly */
12750 ash_msg("%s: invalid signal specification", *ap);
12756 if (LONE_DASH(action))
12759 action = ckstrdup(action);
12763 may_have_traps = 1;
12764 trap[signo] = action;
12775 /* ============ Builtins */
12777 #if ENABLE_ASH_HELP
12778 static int FAST_FUNC
12779 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12785 "Built-in commands:\n"
12786 "------------------\n");
12787 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12788 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12789 builtintab[i].name + 1);
12795 # if ENABLE_FEATURE_SH_STANDALONE
12797 const char *a = applet_names;
12799 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12804 while (*a++ != '\0')
12810 return EXIT_SUCCESS;
12815 static int FAST_FUNC
12816 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12818 show_history(line_input_state);
12819 return EXIT_SUCCESS;
12824 * The export and readonly commands.
12826 static int FAST_FUNC
12827 exportcmd(int argc UNUSED_PARAM, char **argv)
12837 /* "readonly" in bash accepts, but ignores -n.
12838 * We do the same: it saves a conditional in nextopt's param.
12841 while ((opt = nextopt("np")) != '\0') {
12843 flag_off = VEXPORT;
12846 if (argv[0][0] == 'r') {
12848 flag_off = 0; /* readonly ignores -n */
12850 flag_off = ~flag_off;
12852 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12858 p = strchr(name, '=');
12862 vp = *findvar(hashvar(name), name);
12864 vp->flags = ((vp->flags | flag) & flag_off);
12868 setvar(name, p, (flag & flag_off));
12869 } while ((name = *++aptr) != NULL);
12874 /* No arguments. Show the list of exported or readonly vars.
12877 showvars(argv[0], flag, 0);
12882 * Delete a function if it exists.
12885 unsetfunc(const char *name)
12887 struct tblentry *cmdp;
12889 cmdp = cmdlookup(name, 0);
12890 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12891 delete_cmd_entry();
12895 * The unset builtin command. We unset the function before we unset the
12896 * variable to allow a function to be unset when there is a readonly variable
12897 * with the same name.
12899 static int FAST_FUNC
12900 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12907 while ((i = nextopt("vf")) != 0) {
12911 for (ap = argptr; *ap; ap++) {
12924 static const unsigned char timescmd_str[] ALIGN1 = {
12925 ' ', offsetof(struct tms, tms_utime),
12926 '\n', offsetof(struct tms, tms_stime),
12927 ' ', offsetof(struct tms, tms_cutime),
12928 '\n', offsetof(struct tms, tms_cstime),
12931 static int FAST_FUNC
12932 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12934 unsigned long clk_tck, s, t;
12935 const unsigned char *p;
12938 clk_tck = bb_clk_tck();
12943 t = *(clock_t *)(((char *) &buf) + p[1]);
12946 out1fmt("%lum%lu.%03lus%c",
12948 (t * 1000) / clk_tck,
12956 #if ENABLE_SH_MATH_SUPPORT
12958 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12959 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12961 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12963 static int FAST_FUNC
12964 letcmd(int argc UNUSED_PARAM, char **argv)
12970 ash_msg_and_raise_error("expression expected");
12972 i = ash_arith(*argv);
12980 * The read builtin. Options:
12981 * -r Do not interpret '\' specially
12982 * -s Turn off echo (tty only)
12983 * -n NCHARS Read NCHARS max
12984 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12985 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12986 * -u FD Read from given FD instead of fd 0
12987 * This uses unbuffered input, which may be avoidable in some cases.
12988 * TODO: bash also has:
12989 * -a ARRAY Read into array[0],[1],etc
12990 * -d DELIM End on DELIM char, not newline
12991 * -e Use line editing (tty only)
12993 static int FAST_FUNC
12994 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12996 char *opt_n = NULL;
12997 char *opt_p = NULL;
12998 char *opt_t = NULL;
12999 char *opt_u = NULL;
13000 int read_flags = 0;
13004 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13013 read_flags |= BUILTIN_READ_SILENT;
13019 read_flags |= BUILTIN_READ_RAW;
13029 /* "read -s" needs to save/restore termios, can't allow ^C
13030 * to jump out of it.
13033 r = shell_builtin_read(setvar0,
13035 bltinlookup("IFS"), /* can be NULL */
13044 if ((uintptr_t)r > 1)
13045 ash_msg_and_raise_error(r);
13047 return (uintptr_t)r;
13050 static int FAST_FUNC
13051 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13053 static const char permuser[3] ALIGN1 = "ogu";
13056 int symbolic_mode = 0;
13058 while (nextopt("S") != '\0') {
13067 if (*argptr == NULL) {
13068 if (symbolic_mode) {
13069 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13076 *p++ = permuser[i];
13078 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13079 if (!(mask & 0400)) *p++ = 'r';
13080 if (!(mask & 0200)) *p++ = 'w';
13081 if (!(mask & 0100)) *p++ = 'x';
13089 out1fmt("%04o\n", mask);
13092 char *modestr = *argptr;
13093 /* numeric umasks are taken as-is */
13094 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13095 if (!isdigit(modestr[0]))
13097 mask = bb_parse_mode(modestr, mask);
13098 if ((unsigned)mask > 0777) {
13099 ash_msg_and_raise_error("illegal mode: %s", modestr);
13101 if (!isdigit(modestr[0]))
13108 static int FAST_FUNC
13109 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13111 return shell_builtin_ulimit(argv);
13114 /* ============ main() and helpers */
13117 * Called to exit the shell.
13126 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13127 save_history(line_input_state);
13130 status = exitstatus;
13131 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13132 if (setjmp(loc.loc)) {
13133 if (exception_type == EXEXIT)
13134 /* dash bug: it just does _exit(exitstatus) here
13135 * but we have to do setjobctl(0) first!
13136 * (bug is still not fixed in dash-0.5.3 - if you run dash
13137 * under Midnight Commander, on exit from dash MC is backgrounded) */
13138 status = exitstatus;
13141 exception_handler = &loc;
13149 flush_stdout_stderr();
13159 /* from input.c: */
13160 /* we will never free this */
13161 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13164 signal(SIGCHLD, SIG_DFL);
13165 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13166 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13168 signal(SIGHUP, SIG_DFL);
13174 struct stat st1, st2;
13177 for (envp = environ; envp && *envp; envp++) {
13178 p = endofname(*envp);
13179 if (p != *envp && *p == '=') {
13180 setvareq(*envp, VEXPORT|VTEXTFIXED);
13184 setvareq((char*)defoptindvar, VTEXTFIXED);
13186 setvar0("PPID", utoa(getppid()));
13187 #if ENABLE_ASH_BASH_COMPAT
13188 p = lookupvar("SHLVL");
13189 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13190 if (!lookupvar("HOSTNAME")) {
13191 struct utsname uts;
13193 setvar0("HOSTNAME", uts.nodename);
13196 p = lookupvar("PWD");
13198 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13199 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13209 //usage:#define ash_trivial_usage
13210 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13211 //usage:#define ash_full_usage "\n\n"
13212 //usage: "Unix shell interpreter"
13214 //usage:#if ENABLE_FEATURE_SH_IS_ASH
13215 //usage:# define sh_trivial_usage ash_trivial_usage
13216 //usage:# define sh_full_usage ash_full_usage
13218 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
13219 //usage:# define bash_trivial_usage ash_trivial_usage
13220 //usage:# define bash_full_usage ash_full_usage
13224 * Process the shell command line arguments.
13227 procargs(char **argv)
13230 const char *xminusc;
13235 /* if (xargv[0]) - mmm, this is always true! */
13237 for (i = 0; i < NOPTS; i++)
13240 if (options(/*cmdline:*/ 1)) {
13241 /* it already printed err message */
13242 raise_exception(EXERROR);
13246 if (*xargv == NULL) {
13248 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13251 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13255 for (i = 0; i < NOPTS; i++)
13256 if (optlist[i] == 2)
13261 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13266 } else if (!sflag) {
13267 setinputfile(*xargv, 0);
13270 commandname = arg0;
13273 shellparam.p = xargv;
13274 #if ENABLE_ASH_GETOPTS
13275 shellparam.optind = 1;
13276 shellparam.optoff = -1;
13278 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13280 shellparam.nparam++;
13287 * Read /etc/profile or .profile.
13290 read_profile(const char *name)
13292 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13299 * This routine is called when an error or an interrupt occurs in an
13300 * interactive shell and control is returned to the main command loop.
13308 /* from input.c: */
13309 g_parsefile->left_in_buffer = 0;
13310 g_parsefile->left_in_line = 0; /* clear input buffer */
13312 /* from parser.c: */
13315 /* from redir.c: */
13316 clearredir(/*drop:*/ 0);
13320 static short profile_buf[16384];
13321 extern int etext();
13325 * Main routine. We initialize things, parse the arguments, execute
13326 * profiles if we're a login shell, and then call cmdloop to execute
13327 * commands. The setjmp call sets up the location to jump to when an
13328 * exception occurs. When an exception occurs the variable "state"
13329 * is used to figure out how far we had gotten.
13331 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13332 int ash_main(int argc UNUSED_PARAM, char **argv)
13334 const char *shinit;
13335 volatile smallint state;
13336 struct jmploc jmploc;
13337 struct stackmark smark;
13339 /* Initialize global data */
13343 #if ENABLE_ASH_ALIAS
13349 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13352 #if ENABLE_FEATURE_EDITING
13353 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13356 if (setjmp(jmploc.loc)) {
13362 e = exception_type;
13366 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13370 newline_and_flush(stderr);
13373 popstackmark(&smark);
13374 FORCE_INT_ON; /* enable interrupts */
13383 exception_handler = &jmploc;
13386 TRACE(("Shell args: "));
13387 trace_puts_args(argv);
13389 rootpid = getpid();
13392 setstackmark(&smark);
13395 if (argv[0] && argv[0][0] == '-')
13401 read_profile("/etc/profile");
13404 hp = lookupvar("HOME");
13406 hp = concat_path_file(hp, ".profile");
13415 getuid() == geteuid() && getgid() == getegid() &&
13419 shinit = lookupvar("ENV");
13420 if (shinit != NULL && *shinit != '\0') {
13421 read_profile(shinit);
13427 /* evalstring pushes parsefile stack.
13428 * Ensure we don't falsely claim that 0 (stdin)
13429 * is one of stacked source fds.
13430 * Testcase: ash -c 'exec 1>&0' must not complain. */
13431 // if (!sflag) g_parsefile->pf_fd = -1;
13432 // ^^ not necessary since now we special-case fd 0
13433 // in is_hidden_fd() to not be considered "hidden fd"
13434 evalstring(minusc, 0);
13437 if (sflag || minusc == NULL) {
13438 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13440 const char *hp = lookupvar("HISTFILE");
13442 hp = lookupvar("HOME");
13444 hp = concat_path_file(hp, ".ash_history");
13445 setvar0("HISTFILE", hp);
13447 hp = lookupvar("HISTFILE");
13451 line_input_state->hist_file = hp;
13452 # if ENABLE_FEATURE_SH_HISTFILESIZE
13453 hp = lookupvar("HISTFILESIZE");
13454 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13458 state4: /* XXX ??? - why isn't this before the "if" statement */
13466 extern void _mcleanup(void);
13470 TRACE(("End of main reached\n"));
13477 * Copyright (c) 1989, 1991, 1993, 1994
13478 * The Regents of the University of California. All rights reserved.
13480 * This code is derived from software contributed to Berkeley by
13481 * Kenneth Almquist.
13483 * Redistribution and use in source and binary forms, with or without
13484 * modification, are permitted provided that the following conditions
13486 * 1. Redistributions of source code must retain the above copyright
13487 * notice, this list of conditions and the following disclaimer.
13488 * 2. Redistributions in binary form must reproduce the above copyright
13489 * notice, this list of conditions and the following disclaimer in the
13490 * documentation and/or other materials provided with the distribution.
13491 * 3. Neither the name of the University nor the names of its contributors
13492 * may be used to endorse or promote products derived from this software
13493 * without specific prior written permission.
13495 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13496 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13497 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13498 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13499 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13500 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13501 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13502 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13503 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13504 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF