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
43 #include <sys/times.h>
44 #include <sys/utsname.h> /* for setting $HOSTNAME */
46 #include "busybox.h" /* for applet_names */
49 #include "shell_common.h"
50 #if ENABLE_SH_MATH_SUPPORT
53 #if ENABLE_ASH_RANDOM_SUPPORT
56 # define CLEAR_RANDOM_T(rnd) ((void)0)
59 #include "NUM_APPLETS.h"
61 /* STANDALONE does not make sense, and won't compile */
62 # undef CONFIG_FEATURE_SH_STANDALONE
63 # undef ENABLE_FEATURE_SH_STANDALONE
64 # undef IF_FEATURE_SH_STANDALONE
65 # undef IF_NOT_FEATURE_SH_STANDALONE
66 # define ENABLE_FEATURE_SH_STANDALONE 0
67 # define IF_FEATURE_SH_STANDALONE(...)
68 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
72 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
76 # error "Do not even bother, ash will not run on NOMMU machine"
82 //config: depends on !NOMMU
84 //config: Tha 'ash' shell adds about 60k in the default configuration and is
85 //config: the most complete and most pedantically correct shell included with
86 //config: busybox. This shell is actually a derivative of the Debian 'dash'
87 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
88 //config: (written by Kenneth Almquist) from NetBSD.
90 //config:config ASH_BASH_COMPAT
91 //config: bool "bash-compatible extensions"
93 //config: depends on ASH
95 //config: Enable bash-compatible extensions.
97 //config:config ASH_IDLE_TIMEOUT
98 //config: bool "Idle timeout variable"
100 //config: depends on ASH
102 //config: Enables bash-like auto-logout after $TMOUT seconds of idle time.
104 //config:config ASH_JOB_CONTROL
105 //config: bool "Job control"
107 //config: depends on ASH
109 //config: Enable job control in the ash shell.
111 //config:config ASH_ALIAS
112 //config: bool "Alias support"
114 //config: depends on ASH
116 //config: Enable alias support in the ash shell.
118 //config:config ASH_GETOPTS
119 //config: bool "Builtin getopt to parse positional parameters"
121 //config: depends on ASH
123 //config: Enable support for getopts builtin in ash.
125 //config:config ASH_BUILTIN_ECHO
126 //config: bool "Builtin version of 'echo'"
128 //config: depends on ASH
130 //config: Enable support for echo builtin in ash.
132 //config:config ASH_BUILTIN_PRINTF
133 //config: bool "Builtin version of 'printf'"
135 //config: depends on ASH
137 //config: Enable support for printf builtin in ash.
139 //config:config ASH_BUILTIN_TEST
140 //config: bool "Builtin version of 'test'"
142 //config: depends on ASH
144 //config: Enable support for test builtin in ash.
146 //config:config ASH_HELP
147 //config: bool "help builtin"
149 //config: depends on ASH
151 //config: Enable help builtin in ash.
153 //config:config ASH_CMDCMD
154 //config: bool "'command' command to override shell builtins"
156 //config: depends on ASH
158 //config: Enable support for the ash 'command' builtin, which allows
159 //config: you to run the specified command with the specified arguments,
160 //config: even when there is an ash builtin command with the same name.
162 //config:config ASH_MAIL
163 //config: bool "Check for new mail on interactive shells"
165 //config: depends on ASH
167 //config: Enable "check for new mail" function in the ash shell.
169 //config:config ASH_OPTIMIZE_FOR_SIZE
170 //config: bool "Optimize for size instead of speed"
172 //config: depends on ASH
174 //config: Compile ash for reduced size at the price of speed.
176 //config:config ASH_RANDOM_SUPPORT
177 //config: bool "Pseudorandom generator and $RANDOM variable"
179 //config: depends on ASH
181 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
182 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
183 //config: You can reset the generator by using a specified start value.
184 //config: After "unset RANDOM" the generator will switch off and this
185 //config: variable will no longer have special treatment.
187 //config:config ASH_EXPAND_PRMT
188 //config: bool "Expand prompt string"
190 //config: depends on ASH
192 //config: "PS#" may contain volatile content, such as backquote commands.
193 //config: This option recreates the prompt string from the environment
194 //config: variable each time it is displayed.
197 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
198 //applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, sh))
199 //applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, bash))
201 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
202 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
205 /* ============ Hash table sizes. Configurable. */
209 #define CMDTABLESIZE 31 /* should be prime */
212 /* ============ Shell options */
214 static const char *const optletters_optnames[] = {
229 #if ENABLE_ASH_BASH_COMPAT
238 #define optletters(n) optletters_optnames[n][0]
239 #define optnames(n) (optletters_optnames[n] + 1)
241 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
244 /* ============ Misc data */
246 #define msg_illnum "Illegal number: %s"
249 * We enclose jmp_buf in a structure so that we can declare pointers to
250 * jump locations. The global variable handler contains the location to
251 * jump to when an exception occurs, and the global variable exception_type
252 * contains a code identifying the exception. To implement nested
253 * exception handlers, the user should save the value of handler on entry
254 * to an inner scope, set handler to point to a jmploc structure for the
255 * inner scope, and restore handler on exit from the scope.
261 struct globals_misc {
262 /* pid of main shell */
264 /* shell level: 0 for the main shell, 1 for its children, and so on */
266 #define rootshell (!shlvl)
267 char *minusc; /* argument to -c option */
269 char *curdir; // = nullstr; /* current working directory */
270 char *physdir; // = nullstr; /* physical working directory */
272 char *arg0; /* value of $0 */
274 struct jmploc *exception_handler;
276 volatile int suppress_int; /* counter */
277 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
278 /* last pending signal */
279 volatile /*sig_atomic_t*/ smallint pending_sig;
280 smallint exception_type; /* kind of exception (0..5) */
282 #define EXINT 0 /* SIGINT received */
283 #define EXERROR 1 /* a generic error */
284 #define EXSHELLPROC 2 /* execute a shell procedure */
285 #define EXEXEC 3 /* command execution failed */
286 #define EXEXIT 4 /* exit the shell */
287 #define EXSIG 5 /* trapped signal in wait(1) */
290 char nullstr[1]; /* zero length string */
293 #define eflag optlist[0]
294 #define fflag optlist[1]
295 #define Iflag optlist[2]
296 #define iflag optlist[3]
297 #define mflag optlist[4]
298 #define nflag optlist[5]
299 #define sflag optlist[6]
300 #define xflag optlist[7]
301 #define vflag optlist[8]
302 #define Cflag optlist[9]
303 #define aflag optlist[10]
304 #define bflag optlist[11]
305 #define uflag optlist[12]
306 #define viflag optlist[13]
307 #if ENABLE_ASH_BASH_COMPAT
308 # define pipefail optlist[14]
313 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
314 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
317 /* trap handler commands */
319 * Sigmode records the current value of the signal handlers for the various
320 * modes. A value of zero means that the current handler is not known.
321 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
323 char sigmode[NSIG - 1];
324 #define S_DFL 1 /* default signal handling (SIG_DFL) */
325 #define S_CATCH 2 /* signal is caught */
326 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
327 #define S_HARD_IGN 4 /* signal is ignored permanently */
329 /* indicates specified signal received */
330 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
331 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
333 char **trap_ptr; /* used only by "trap hack" */
335 /* Rarely referenced stuff */
336 #if ENABLE_ASH_RANDOM_SUPPORT
339 pid_t backgndpid; /* pid of last background process */
340 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
342 extern struct globals_misc *const ash_ptr_to_globals_misc;
343 #define G_misc (*ash_ptr_to_globals_misc)
344 #define rootpid (G_misc.rootpid )
345 #define shlvl (G_misc.shlvl )
346 #define minusc (G_misc.minusc )
347 #define curdir (G_misc.curdir )
348 #define physdir (G_misc.physdir )
349 #define arg0 (G_misc.arg0 )
350 #define exception_handler (G_misc.exception_handler)
351 #define exception_type (G_misc.exception_type )
352 #define suppress_int (G_misc.suppress_int )
353 #define pending_int (G_misc.pending_int )
354 #define pending_sig (G_misc.pending_sig )
355 #define isloginsh (G_misc.isloginsh )
356 #define nullstr (G_misc.nullstr )
357 #define optlist (G_misc.optlist )
358 #define sigmode (G_misc.sigmode )
359 #define gotsig (G_misc.gotsig )
360 #define may_have_traps (G_misc.may_have_traps )
361 #define trap (G_misc.trap )
362 #define trap_ptr (G_misc.trap_ptr )
363 #define random_gen (G_misc.random_gen )
364 #define backgndpid (G_misc.backgndpid )
365 #define job_warning (G_misc.job_warning)
366 #define INIT_G_misc() do { \
367 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
375 /* ============ DEBUG */
377 static void trace_printf(const char *fmt, ...);
378 static void trace_vprintf(const char *fmt, va_list va);
379 # define TRACE(param) trace_printf param
380 # define TRACEV(param) trace_vprintf param
381 # define close(fd) do { \
383 if (close(dfd) < 0) \
384 bb_error_msg("bug on %d: closing %d(0x%x)", \
385 __LINE__, dfd, dfd); \
388 # define TRACE(param)
389 # define TRACEV(param)
393 /* ============ Utility functions */
394 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
396 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
397 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
399 static int isdigit_str9(const char *str)
401 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
402 while (--maxlen && isdigit(*str))
404 return (*str == '\0');
407 static const char *var_end(const char *var)
416 /* ============ Interrupts / exceptions */
418 static void exitshell(void) NORETURN;
421 * These macros allow the user to suspend the handling of interrupt signals
422 * over a period of time. This is similar to SIGHOLD or to sigblock, but
423 * much more efficient and portable. (But hacking the kernel is so much
424 * more fun than worrying about efficiency and portability. :-))
426 #define INT_OFF do { \
432 * Called to raise an exception. Since C doesn't include exceptions, we
433 * just do a longjmp to the exception handler. The type of exception is
434 * stored in the global variable "exception_type".
436 static void raise_exception(int) NORETURN;
438 raise_exception(int e)
441 if (exception_handler == NULL)
446 longjmp(exception_handler->loc, 1);
449 #define raise_exception(e) do { \
450 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
451 raise_exception(e); \
456 * Called from trap.c when a SIGINT is received. (If the user specifies
457 * that SIGINT is to be trapped or ignored using the trap builtin, then
458 * this routine is not called.) Suppressint is nonzero when interrupts
459 * are held using the INT_OFF macro. (The test for iflag is just
460 * defensive programming.)
462 static void raise_interrupt(void) NORETURN;
464 raise_interrupt(void)
469 /* Signal is not automatically unmasked after it is raised,
470 * do it ourself - unmask all signals */
471 sigprocmask_allsigs(SIG_UNBLOCK);
472 /* pending_sig = 0; - now done in signal_handler() */
475 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
476 if (!(rootshell && iflag)) {
477 /* Kill ourself with SIGINT */
478 signal(SIGINT, SIG_DFL);
483 raise_exception(ex_type);
487 #define raise_interrupt() do { \
488 TRACE(("raising interrupt on line %d\n", __LINE__)); \
493 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
497 if (--suppress_int == 0 && pending_int) {
501 #define INT_ON int_on()
502 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
510 #define FORCE_INT_ON force_int_on()
512 #define SAVE_INT(v) ((v) = suppress_int)
514 #define RESTORE_INT(v) do { \
516 suppress_int = (v); \
517 if (suppress_int == 0 && pending_int) \
522 /* ============ Stdout/stderr output */
525 outstr(const char *p, FILE *file)
533 flush_stdout_stderr(void)
540 /* Was called outcslow(c,FILE*), but c was always '\n' */
542 newline_and_flush(FILE *dest)
550 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
552 out1fmt(const char *fmt, ...)
559 r = vprintf(fmt, ap);
565 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
567 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
574 ret = vsnprintf(outbuf, length, fmt, ap);
581 out1str(const char *p)
587 out2str(const char *p)
590 flush_stdout_stderr();
594 /* ============ Parser structures */
596 /* control characters in argument strings */
597 #define CTL_FIRST CTLESC
598 #define CTLESC ((unsigned char)'\201') /* escape next character */
599 #define CTLVAR ((unsigned char)'\202') /* variable defn */
600 #define CTLENDVAR ((unsigned char)'\203')
601 #define CTLBACKQ ((unsigned char)'\204')
602 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
603 #define CTLENDARI ((unsigned char)'\207')
604 #define CTLQUOTEMARK ((unsigned char)'\210')
605 #define CTL_LAST CTLQUOTEMARK
607 /* variable substitution byte (follows CTLVAR) */
608 #define VSTYPE 0x0f /* type of variable substitution */
609 #define VSNUL 0x10 /* colon--treat the empty string as unset */
611 /* values of VSTYPE field */
612 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
613 #define VSMINUS 0x2 /* ${var-text} */
614 #define VSPLUS 0x3 /* ${var+text} */
615 #define VSQUESTION 0x4 /* ${var?message} */
616 #define VSASSIGN 0x5 /* ${var=text} */
617 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
618 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
619 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
620 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
621 #define VSLENGTH 0xa /* ${#var} */
622 #if ENABLE_ASH_BASH_COMPAT
623 #define VSSUBSTR 0xc /* ${var:position:length} */
624 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
625 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
628 static const char dolatstr[] ALIGN1 = {
629 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
631 #define DOLATSTRLEN 6
650 #if ENABLE_ASH_BASH_COMPAT
667 smallint type; /* Nxxxx */
670 union node *redirect;
675 smallint pipe_backgnd;
676 struct nodelist *cmdlist;
682 union node *redirect;
695 union node *elsepart;
722 struct nodelist *backquote;
725 /* nfile and ndup layout must match!
726 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
727 * that it is actually NTO2 (>&file), and change its type.
744 char *_unused_expfname;
763 struct nredir nredir;
764 struct nbinary nbinary;
768 struct nclist nclist;
777 * NODE_EOF is returned by parsecmd when it encounters an end of file.
778 * It must be distinct from NULL.
780 #define NODE_EOF ((union node *) -1L)
783 struct nodelist *next;
796 freefunc(struct funcnode *f)
798 if (f && --f->count < 0)
803 /* ============ Debugging output */
807 static FILE *tracefile;
810 trace_printf(const char *fmt, ...)
817 fprintf(tracefile, "%u ", (int) time(NULL));
819 fprintf(tracefile, "[%u] ", (int) getpid());
821 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
823 vfprintf(tracefile, fmt, va);
828 trace_vprintf(const char *fmt, va_list va)
833 fprintf(tracefile, "%u ", (int) time(NULL));
835 fprintf(tracefile, "[%u] ", (int) getpid());
837 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
838 vfprintf(tracefile, fmt, va);
842 trace_puts(const char *s)
850 trace_puts_quoted(char *s)
857 putc('"', tracefile);
858 for (p = s; *p; p++) {
859 switch ((unsigned char)*p) {
860 case '\n': c = 'n'; goto backslash;
861 case '\t': c = 't'; goto backslash;
862 case '\r': c = 'r'; goto backslash;
863 case '\"': c = '\"'; goto backslash;
864 case '\\': c = '\\'; goto backslash;
865 case CTLESC: c = 'e'; goto backslash;
866 case CTLVAR: c = 'v'; goto backslash;
867 case CTLBACKQ: c = 'q'; goto backslash;
869 putc('\\', tracefile);
873 if (*p >= ' ' && *p <= '~')
876 putc('\\', tracefile);
877 putc((*p >> 6) & 03, tracefile);
878 putc((*p >> 3) & 07, tracefile);
879 putc(*p & 07, tracefile);
884 putc('"', tracefile);
888 trace_puts_args(char **ap)
895 trace_puts_quoted(*ap);
897 putc('\n', tracefile);
900 putc(' ', tracefile);
915 /* leave open because libedit might be using it */
918 strcpy(s, "./trace");
920 if (!freopen(s, "a", tracefile)) {
921 fprintf(stderr, "Can't re-open %s\n", s);
926 tracefile = fopen(s, "a");
927 if (tracefile == NULL) {
928 fprintf(stderr, "Can't open %s\n", s);
934 flags = fcntl(fileno(tracefile), F_GETFL);
936 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
938 setlinebuf(tracefile);
939 fputs("\nTracing started.\n", tracefile);
943 indent(int amount, char *pfx, FILE *fp)
947 for (i = 0; i < amount; i++) {
948 if (pfx && i == amount - 1)
954 /* little circular references here... */
955 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
958 sharg(union node *arg, FILE *fp)
961 struct nodelist *bqlist;
962 unsigned char subtype;
964 if (arg->type != NARG) {
965 out1fmt("<node type %d>\n", arg->type);
968 bqlist = arg->narg.backquote;
969 for (p = arg->narg.text; *p; p++) {
970 switch ((unsigned char)*p) {
979 if (subtype == VSLENGTH)
990 switch (subtype & VSTYPE) {
1016 case VSTRIMRIGHTMAX:
1023 out1fmt("<subtype %d>", subtype);
1032 shtree(bqlist->n, -1, NULL, fp);
1043 shcmd(union node *cmd, FILE *fp)
1051 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1057 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1061 switch (np->nfile.type) {
1062 case NTO: s = ">>"+1; dftfd = 1; break;
1063 case NCLOBBER: s = ">|"; dftfd = 1; break;
1064 case NAPPEND: s = ">>"; dftfd = 1; break;
1065 #if ENABLE_ASH_BASH_COMPAT
1068 case NTOFD: s = ">&"; dftfd = 1; break;
1069 case NFROM: s = "<"; break;
1070 case NFROMFD: s = "<&"; break;
1071 case NFROMTO: s = "<>"; break;
1072 default: s = "*error*"; break;
1074 if (np->nfile.fd != dftfd)
1075 fprintf(fp, "%d", np->nfile.fd);
1077 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1078 fprintf(fp, "%d", np->ndup.dupfd);
1080 sharg(np->nfile.fname, fp);
1087 shtree(union node *n, int ind, char *pfx, FILE *fp)
1089 struct nodelist *lp;
1095 indent(ind, pfx, fp);
1097 if (n == NODE_EOF) {
1112 shtree(n->nbinary.ch1, ind, NULL, fp);
1115 shtree(n->nbinary.ch2, ind, NULL, fp);
1123 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1124 shtree(lp->n, 0, NULL, fp);
1128 if (n->npipe.pipe_backgnd)
1134 fprintf(fp, "<node type %d>", n->type);
1142 showtree(union node *n)
1144 trace_puts("showtree called\n");
1145 shtree(n, 1, NULL, stderr);
1151 /* ============ Parser data */
1154 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1157 struct strlist *next;
1164 struct strpush *prev; /* preceding string on stack */
1166 int prev_left_in_line;
1167 #if ENABLE_ASH_ALIAS
1168 struct alias *ap; /* if push was associated with an alias */
1170 char *string; /* remember the string since it may change */
1172 /* Remember last two characters for pungetc. */
1175 /* Number of outstanding calls to pungetc. */
1180 struct parsefile *prev; /* preceding file on stack */
1181 int linno; /* current line */
1182 int pf_fd; /* file descriptor (or -1 if string) */
1183 int left_in_line; /* number of chars left in this line */
1184 int left_in_buffer; /* number of chars left in this buffer past the line */
1185 char *next_to_pgetc; /* next char in buffer */
1186 char *buf; /* input buffer */
1187 struct strpush *strpush; /* for pushing strings at this level */
1188 struct strpush basestrpush; /* so pushing one is fast */
1190 /* Remember last two characters for pungetc. */
1193 /* Number of outstanding calls to pungetc. */
1197 static struct parsefile basepf; /* top level input file */
1198 static struct parsefile *g_parsefile = &basepf; /* current input file */
1199 static int startlinno; /* line # where last token started */
1200 static char *commandname; /* currently executing command */
1201 static struct strlist *cmdenviron; /* environment for builtin command */
1202 static uint8_t exitstatus; /* exit status of last command */
1205 /* ============ Message printing */
1208 ash_vmsg(const char *msg, va_list ap)
1210 fprintf(stderr, "%s: ", arg0);
1212 if (strcmp(arg0, commandname))
1213 fprintf(stderr, "%s: ", commandname);
1214 if (!iflag || g_parsefile->pf_fd > 0)
1215 fprintf(stderr, "line %d: ", startlinno);
1217 vfprintf(stderr, msg, ap);
1218 newline_and_flush(stderr);
1222 * Exverror is called to raise the error exception. If the second argument
1223 * is not NULL then error prints an error message using printf style
1224 * formatting. It then raises the error exception.
1226 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1228 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1232 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1234 TRACE(("\") pid=%d\n", getpid()));
1236 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1241 flush_stdout_stderr();
1242 raise_exception(cond);
1246 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1248 ash_msg_and_raise_error(const char *msg, ...)
1253 ash_vmsg_and_raise(EXERROR, msg, ap);
1258 static void raise_error_syntax(const char *) NORETURN;
1260 raise_error_syntax(const char *msg)
1262 ash_msg_and_raise_error("syntax error: %s", msg);
1266 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1268 ash_msg_and_raise(int cond, const char *msg, ...)
1273 ash_vmsg_and_raise(cond, msg, ap);
1279 * error/warning routines for external builtins
1282 ash_msg(const char *fmt, ...)
1292 * Return a string describing an error. The returned string may be a
1293 * pointer to a static buffer that will be overwritten on the next call.
1294 * Action describes the operation that got the error.
1297 errmsg(int e, const char *em)
1299 if (e == ENOENT || e == ENOTDIR) {
1306 /* ============ Memory allocation */
1309 /* I consider these wrappers nearly useless:
1310 * ok, they return you to nearest exception handler, but
1311 * how much memory do you leak in the process, making
1312 * memory starvation worse?
1315 ckrealloc(void * p, size_t nbytes)
1317 p = realloc(p, nbytes);
1319 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1324 ckmalloc(size_t nbytes)
1326 return ckrealloc(NULL, nbytes);
1330 ckzalloc(size_t nbytes)
1332 return memset(ckmalloc(nbytes), 0, nbytes);
1336 ckstrdup(const char *s)
1338 char *p = strdup(s);
1340 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1344 /* Using bbox equivalents. They exit if out of memory */
1345 # define ckrealloc xrealloc
1346 # define ckmalloc xmalloc
1347 # define ckzalloc xzalloc
1348 # define ckstrdup xstrdup
1352 * It appears that grabstackstr() will barf with such alignments
1353 * because stalloc() will return a string allocated in a new stackblock.
1355 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1357 /* Most machines require the value returned from malloc to be aligned
1358 * in some way. The following macro will get this right
1359 * on many machines. */
1360 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1361 /* Minimum size of a block */
1362 MINSIZE = SHELL_ALIGN(504),
1365 struct stack_block {
1366 struct stack_block *prev;
1367 char space[MINSIZE];
1371 struct stack_block *stackp;
1374 struct stackmark *marknext;
1378 struct globals_memstack {
1379 struct stack_block *g_stackp; // = &stackbase;
1380 struct stackmark *markp;
1381 char *g_stacknxt; // = stackbase.space;
1382 char *sstrend; // = stackbase.space + MINSIZE;
1383 size_t g_stacknleft; // = MINSIZE;
1384 int herefd; // = -1;
1385 struct stack_block stackbase;
1387 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1388 #define G_memstack (*ash_ptr_to_globals_memstack)
1389 #define g_stackp (G_memstack.g_stackp )
1390 #define markp (G_memstack.markp )
1391 #define g_stacknxt (G_memstack.g_stacknxt )
1392 #define sstrend (G_memstack.sstrend )
1393 #define g_stacknleft (G_memstack.g_stacknleft)
1394 #define herefd (G_memstack.herefd )
1395 #define stackbase (G_memstack.stackbase )
1396 #define INIT_G_memstack() do { \
1397 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1399 g_stackp = &stackbase; \
1400 g_stacknxt = stackbase.space; \
1401 g_stacknleft = MINSIZE; \
1402 sstrend = stackbase.space + MINSIZE; \
1407 #define stackblock() ((void *)g_stacknxt)
1408 #define stackblocksize() g_stacknleft
1411 * Parse trees for commands are allocated in lifo order, so we use a stack
1412 * to make this more efficient, and also to avoid all sorts of exception
1413 * handling code to handle interrupts in the middle of a parse.
1415 * The size 504 was chosen because the Ultrix malloc handles that size
1419 stalloc(size_t nbytes)
1424 aligned = SHELL_ALIGN(nbytes);
1425 if (aligned > g_stacknleft) {
1428 struct stack_block *sp;
1430 blocksize = aligned;
1431 if (blocksize < MINSIZE)
1432 blocksize = MINSIZE;
1433 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1434 if (len < blocksize)
1435 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1438 sp->prev = g_stackp;
1439 g_stacknxt = sp->space;
1440 g_stacknleft = blocksize;
1441 sstrend = g_stacknxt + blocksize;
1446 g_stacknxt += aligned;
1447 g_stacknleft -= aligned;
1452 stzalloc(size_t nbytes)
1454 return memset(stalloc(nbytes), 0, nbytes);
1461 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1462 write(STDERR_FILENO, "stunalloc\n", 10);
1466 g_stacknleft += g_stacknxt - (char *)p;
1471 * Like strdup but works with the ash stack.
1474 sstrdup(const char *p)
1476 size_t len = strlen(p) + 1;
1477 return memcpy(stalloc(len), p, len);
1481 setstackmark(struct stackmark *mark)
1483 mark->stackp = g_stackp;
1484 mark->stacknxt = g_stacknxt;
1485 mark->stacknleft = g_stacknleft;
1486 mark->marknext = markp;
1491 popstackmark(struct stackmark *mark)
1493 struct stack_block *sp;
1499 markp = mark->marknext;
1500 while (g_stackp != mark->stackp) {
1502 g_stackp = sp->prev;
1505 g_stacknxt = mark->stacknxt;
1506 g_stacknleft = mark->stacknleft;
1507 sstrend = mark->stacknxt + mark->stacknleft;
1512 * When the parser reads in a string, it wants to stick the string on the
1513 * stack and only adjust the stack pointer when it knows how big the
1514 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1515 * of space on top of the stack and stackblocklen returns the length of
1516 * this block. Growstackblock will grow this space by at least one byte,
1517 * possibly moving it (like realloc). Grabstackblock actually allocates the
1518 * part of the block that has been used.
1521 growstackblock(void)
1525 newlen = g_stacknleft * 2;
1526 if (newlen < g_stacknleft)
1527 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1531 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1532 struct stack_block *oldstackp;
1533 struct stackmark *xmark;
1534 struct stack_block *sp;
1535 struct stack_block *prevstackp;
1539 oldstackp = g_stackp;
1541 prevstackp = sp->prev;
1542 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1543 sp = ckrealloc(sp, grosslen);
1544 sp->prev = prevstackp;
1546 g_stacknxt = sp->space;
1547 g_stacknleft = newlen;
1548 sstrend = sp->space + newlen;
1551 * Stack marks pointing to the start of the old block
1552 * must be relocated to point to the new block
1555 while (xmark != NULL && xmark->stackp == oldstackp) {
1556 xmark->stackp = g_stackp;
1557 xmark->stacknxt = g_stacknxt;
1558 xmark->stacknleft = g_stacknleft;
1559 xmark = xmark->marknext;
1563 char *oldspace = g_stacknxt;
1564 size_t oldlen = g_stacknleft;
1565 char *p = stalloc(newlen);
1567 /* free the space we just allocated */
1568 g_stacknxt = memcpy(p, oldspace, oldlen);
1569 g_stacknleft += newlen;
1574 grabstackblock(size_t len)
1576 len = SHELL_ALIGN(len);
1578 g_stacknleft -= len;
1582 * The following routines are somewhat easier to use than the above.
1583 * The user declares a variable of type STACKSTR, which may be declared
1584 * to be a register. The macro STARTSTACKSTR initializes things. Then
1585 * the user uses the macro STPUTC to add characters to the string. In
1586 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1587 * grown as necessary. When the user is done, she can just leave the
1588 * string there and refer to it using stackblock(). Or she can allocate
1589 * the space for it using grabstackstr(). If it is necessary to allow
1590 * someone else to use the stack temporarily and then continue to grow
1591 * the string, the user should use grabstack to allocate the space, and
1592 * then call ungrabstr(p) to return to the previous mode of operation.
1594 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1595 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1596 * is space for at least one character.
1601 size_t len = stackblocksize();
1602 if (herefd >= 0 && len >= 1024) {
1603 full_write(herefd, stackblock(), len);
1604 return stackblock();
1607 return (char *)stackblock() + len;
1611 * Called from CHECKSTRSPACE.
1614 makestrspace(size_t newlen, char *p)
1616 size_t len = p - g_stacknxt;
1617 size_t size = stackblocksize();
1622 size = stackblocksize();
1624 if (nleft >= newlen)
1628 return (char *)stackblock() + len;
1632 stack_nputstr(const char *s, size_t n, char *p)
1634 p = makestrspace(n, p);
1635 p = (char *)memcpy(p, s, n) + n;
1640 stack_putstr(const char *s, char *p)
1642 return stack_nputstr(s, strlen(s), p);
1646 _STPUTC(int c, char *p)
1654 #define STARTSTACKSTR(p) ((p) = stackblock())
1655 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1656 #define CHECKSTRSPACE(n, p) do { \
1659 size_t m = sstrend - q; \
1661 (p) = makestrspace(l, q); \
1663 #define USTPUTC(c, p) (*(p)++ = (c))
1664 #define STACKSTRNUL(p) do { \
1665 if ((p) == sstrend) \
1666 (p) = growstackstr(); \
1669 #define STUNPUTC(p) (--(p))
1670 #define STTOPC(p) ((p)[-1])
1671 #define STADJUST(amount, p) ((p) += (amount))
1673 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1674 #define ungrabstackstr(s, p) stunalloc(s)
1675 #define stackstrend() ((void *)sstrend)
1678 /* ============ String helpers */
1681 * prefix -- see if pfx is a prefix of string.
1684 prefix(const char *string, const char *pfx)
1687 if (*pfx++ != *string++)
1690 return (char *) string;
1694 * Check for a valid number. This should be elsewhere.
1697 is_number(const char *p)
1702 } while (*++p != '\0');
1707 * Convert a string of digits to an integer, printing an error message on
1711 number(const char *s)
1714 ash_msg_and_raise_error(msg_illnum, s);
1719 * Produce a possibly single quoted string suitable as input to the shell.
1720 * The return string is allocated on the stack.
1723 single_quote(const char *s)
1733 len = strchrnul(s, '\'') - s;
1735 q = p = makestrspace(len + 3, p);
1738 q = (char *)memcpy(q, s, len) + len;
1747 do len++; while (*++s == '\'');
1749 q = p = makestrspace(len + 3, p);
1752 q = (char *)memcpy(q, s - len, len) + len;
1760 return stackblock();
1764 /* ============ nextopt */
1766 static char **argptr; /* argument list for builtin commands */
1767 static char *optionarg; /* set by nextopt (like getopt) */
1768 static char *optptr; /* used by nextopt */
1771 * XXX - should get rid of. Have all builtins use getopt(3).
1772 * The library getopt must have the BSD extension static variable
1773 * "optreset", otherwise it can't be used within the shell safely.
1775 * Standard option processing (a la getopt) for builtin routines.
1776 * The only argument that is passed to nextopt is the option string;
1777 * the other arguments are unnecessary. It returns the character,
1778 * or '\0' on end of input.
1781 nextopt(const char *optstring)
1788 if (p == NULL || *p == '\0') {
1789 /* We ate entire "-param", take next one */
1795 if (*++p == '\0') /* just "-" ? */
1798 if (LONE_DASH(p)) /* "--" ? */
1800 /* p => next "-param" */
1802 /* p => some option char in the middle of a "-param" */
1804 for (q = optstring; *q != c;) {
1806 ash_msg_and_raise_error("illegal option -%c", c);
1814 ash_msg_and_raise_error("no arg for -%c option", c);
1824 /* ============ Shell variables */
1827 * The parsefile structure pointed to by the global variable parsefile
1828 * contains information about the current file being read.
1831 int nparam; /* # of positional parameters (without $0) */
1832 #if ENABLE_ASH_GETOPTS
1833 int optind; /* next parameter to be processed by getopts */
1834 int optoff; /* used by getopts */
1836 unsigned char malloced; /* if parameter list dynamically allocated */
1837 char **p; /* parameter list */
1841 * Free the list of positional parameters.
1844 freeparam(volatile struct shparam *param)
1846 if (param->malloced) {
1848 ap = ap1 = param->p;
1855 #if ENABLE_ASH_GETOPTS
1856 static void FAST_FUNC getoptsreset(const char *value);
1860 struct var *next; /* next entry in hash list */
1861 int flags; /* flags are defined above */
1862 const char *var_text; /* name=value */
1863 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1864 /* the variable gets set/unset */
1868 struct localvar *next; /* next local variable in list */
1869 struct var *vp; /* the variable that was made local */
1870 int flags; /* saved flags */
1871 const char *text; /* saved text */
1875 #define VEXPORT 0x01 /* variable is exported */
1876 #define VREADONLY 0x02 /* variable cannot be modified */
1877 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1878 #define VTEXTFIXED 0x08 /* text is statically allocated */
1879 #define VSTACK 0x10 /* text is allocated on the stack */
1880 #define VUNSET 0x20 /* the variable is not set */
1881 #define VNOFUNC 0x40 /* don't call the callback function */
1882 #define VNOSET 0x80 /* do not set variable - just readonly test */
1883 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1884 #if ENABLE_ASH_RANDOM_SUPPORT
1885 # define VDYNAMIC 0x200 /* dynamic variable */
1891 /* Need to be before varinit_data[] */
1892 #if ENABLE_LOCALE_SUPPORT
1893 static void FAST_FUNC
1894 change_lc_all(const char *value)
1896 if (value && *value != '\0')
1897 setlocale(LC_ALL, value);
1899 static void FAST_FUNC
1900 change_lc_ctype(const char *value)
1902 if (value && *value != '\0')
1903 setlocale(LC_CTYPE, value);
1907 static void chkmail(void);
1908 static void changemail(const char *var_value) FAST_FUNC;
1910 # define chkmail() ((void)0)
1912 static void changepath(const char *) FAST_FUNC;
1913 #if ENABLE_ASH_RANDOM_SUPPORT
1914 static void change_random(const char *) FAST_FUNC;
1917 static const struct {
1919 const char *var_text;
1920 void (*var_func)(const char *) FAST_FUNC;
1921 } varinit_data[] = {
1923 * Note: VEXPORT would not work correctly here for NOFORK applets:
1924 * some environment strings may be constant.
1926 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1928 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1929 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1931 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1932 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1933 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1934 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1935 #if ENABLE_ASH_GETOPTS
1936 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1938 #if ENABLE_ASH_RANDOM_SUPPORT
1939 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1941 #if ENABLE_LOCALE_SUPPORT
1942 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1943 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1945 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1946 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1952 struct globals_var {
1953 struct shparam shellparam; /* $@ current positional parameters */
1954 struct redirtab *redirlist;
1956 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1957 struct var *vartab[VTABSIZE];
1958 struct var varinit[ARRAY_SIZE(varinit_data)];
1960 extern struct globals_var *const ash_ptr_to_globals_var;
1961 #define G_var (*ash_ptr_to_globals_var)
1962 #define shellparam (G_var.shellparam )
1963 //#define redirlist (G_var.redirlist )
1964 #define g_nullredirs (G_var.g_nullredirs )
1965 #define preverrout_fd (G_var.preverrout_fd)
1966 #define vartab (G_var.vartab )
1967 #define varinit (G_var.varinit )
1968 #define INIT_G_var() do { \
1970 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1972 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1973 varinit[i].flags = varinit_data[i].flags; \
1974 varinit[i].var_text = varinit_data[i].var_text; \
1975 varinit[i].var_func = varinit_data[i].var_func; \
1979 #define vifs varinit[0]
1981 # define vmail (&vifs)[1]
1982 # define vmpath (&vmail)[1]
1983 # define vpath (&vmpath)[1]
1985 # define vpath (&vifs)[1]
1987 #define vps1 (&vpath)[1]
1988 #define vps2 (&vps1)[1]
1989 #define vps4 (&vps2)[1]
1990 #if ENABLE_ASH_GETOPTS
1991 # define voptind (&vps4)[1]
1992 # if ENABLE_ASH_RANDOM_SUPPORT
1993 # define vrandom (&voptind)[1]
1996 # if ENABLE_ASH_RANDOM_SUPPORT
1997 # define vrandom (&vps4)[1]
2002 * The following macros access the values of the above variables.
2003 * They have to skip over the name. They return the null string
2004 * for unset variables.
2006 #define ifsval() (vifs.var_text + 4)
2007 #define ifsset() ((vifs.flags & VUNSET) == 0)
2009 # define mailval() (vmail.var_text + 5)
2010 # define mpathval() (vmpath.var_text + 9)
2011 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2013 #define pathval() (vpath.var_text + 5)
2014 #define ps1val() (vps1.var_text + 4)
2015 #define ps2val() (vps2.var_text + 4)
2016 #define ps4val() (vps4.var_text + 4)
2017 #if ENABLE_ASH_GETOPTS
2018 # define optindval() (voptind.var_text + 7)
2021 #if ENABLE_ASH_GETOPTS
2022 static void FAST_FUNC
2023 getoptsreset(const char *value)
2025 shellparam.optind = number(value);
2026 shellparam.optoff = -1;
2031 * Compares two strings up to the first = or '\0'. The first
2032 * string must be terminated by '='; the second may be terminated by
2033 * either '=' or '\0'.
2036 varcmp(const char *p, const char *q)
2040 while ((c = *p) == (d = *q)) {
2041 if (c == '\0' || c == '=')
2055 * Find the appropriate entry in the hash table from the name.
2057 static struct var **
2058 hashvar(const char *p)
2062 hashval = ((unsigned char) *p) << 4;
2063 while (*p && *p != '=')
2064 hashval += (unsigned char) *p++;
2065 return &vartab[hashval % VTABSIZE];
2069 vpcmp(const void *a, const void *b)
2071 return varcmp(*(const char **)a, *(const char **)b);
2075 * This routine initializes the builtin variables.
2085 * PS1 depends on uid
2087 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2088 vps1.var_text = "PS1=\\w \\$ ";
2091 vps1.var_text = "PS1=# ";
2094 end = vp + ARRAY_SIZE(varinit);
2096 vpp = hashvar(vp->var_text);
2099 } while (++vp < end);
2102 static struct var **
2103 findvar(struct var **vpp, const char *name)
2105 for (; *vpp; vpp = &(*vpp)->next) {
2106 if (varcmp((*vpp)->var_text, name) == 0) {
2114 * Find the value of a variable. Returns NULL if not set.
2116 static const char* FAST_FUNC
2117 lookupvar(const char *name)
2121 v = *findvar(hashvar(name), name);
2123 #if ENABLE_ASH_RANDOM_SUPPORT
2125 * Dynamic variables are implemented roughly the same way they are
2126 * in bash. Namely, they're "special" so long as they aren't unset.
2127 * As soon as they're unset, they're no longer dynamic, and dynamic
2128 * lookup will no longer happen at that point. -- PFM.
2130 if (v->flags & VDYNAMIC)
2133 if (!(v->flags & VUNSET))
2134 return var_end(v->var_text);
2139 static void reinit_unicode_for_ash(void)
2141 /* Unicode support should be activated even if LANG is set
2142 * _during_ shell execution, not only if it was set when
2143 * shell was started. Therefore, re-check LANG every time:
2145 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2146 || ENABLE_UNICODE_USING_LOCALE
2148 const char *s = lookupvar("LC_ALL");
2149 if (!s) s = lookupvar("LC_CTYPE");
2150 if (!s) s = lookupvar("LANG");
2156 * Search the environment of a builtin command.
2159 bltinlookup(const char *name)
2163 for (sp = cmdenviron; sp; sp = sp->next) {
2164 if (varcmp(sp->text, name) == 0)
2165 return var_end(sp->text);
2167 return lookupvar(name);
2171 * Same as setvar except that the variable and value are passed in
2172 * the first argument as name=value. Since the first argument will
2173 * be actually stored in the table, it should not be a string that
2175 * Called with interrupts off.
2178 setvareq(char *s, int flags)
2180 struct var *vp, **vpp;
2183 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2184 vp = *findvar(vpp, s);
2186 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2189 if (flags & VNOSAVE)
2192 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2198 if (vp->var_func && !(flags & VNOFUNC))
2199 vp->var_func(var_end(s));
2201 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2202 free((char*)vp->var_text);
2204 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2206 /* variable s is not found */
2209 vp = ckzalloc(sizeof(*vp));
2211 /*vp->func = NULL; - ckzalloc did it */
2214 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2221 * Set the value of a variable. The flags argument is ored with the
2222 * flags of the variable. If val is NULL, the variable is unset.
2225 setvar(const char *name, const char *val, int flags)
2233 q = endofname(name);
2234 p = strchrnul(q, '=');
2236 if (!namelen || p != q)
2237 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2242 vallen = strlen(val);
2246 nameeq = ckmalloc(namelen + vallen + 2);
2247 p = memcpy(nameeq, name, namelen) + namelen;
2250 p = memcpy(p, val, vallen) + vallen;
2253 setvareq(nameeq, flags | VNOSAVE);
2257 static void FAST_FUNC
2258 setvar0(const char *name, const char *val)
2260 setvar(name, val, 0);
2263 #if ENABLE_ASH_GETOPTS
2265 * Safe version of setvar, returns 1 on success 0 on failure.
2268 setvarsafe(const char *name, const char *val, int flags)
2271 volatile int saveint;
2272 struct jmploc *volatile savehandler = exception_handler;
2273 struct jmploc jmploc;
2276 if (setjmp(jmploc.loc))
2279 exception_handler = &jmploc;
2280 setvar(name, val, flags);
2283 exception_handler = savehandler;
2284 RESTORE_INT(saveint);
2290 * Unset the specified variable.
2293 unsetvar(const char *s)
2299 vpp = findvar(hashvar(s), s);
2303 int flags = vp->flags;
2306 if (flags & VREADONLY)
2308 #if ENABLE_ASH_RANDOM_SUPPORT
2309 vp->flags &= ~VDYNAMIC;
2313 if ((flags & VSTRFIXED) == 0) {
2315 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2316 free((char*)vp->var_text);
2322 vp->flags &= ~VEXPORT;
2332 * Process a linked list of variable assignments.
2335 listsetvar(struct strlist *list_set_var, int flags)
2337 struct strlist *lp = list_set_var;
2343 setvareq(lp->text, flags);
2350 * Generate a list of variables satisfying the given conditions.
2353 listvars(int on, int off, char ***end)
2364 for (vp = *vpp; vp; vp = vp->next) {
2365 if ((vp->flags & mask) == on) {
2366 if (ep == stackstrend())
2367 ep = growstackstr();
2368 *ep++ = (char*)vp->var_text;
2371 } while (++vpp < vartab + VTABSIZE);
2372 if (ep == stackstrend())
2373 ep = growstackstr();
2377 return grabstackstr(ep);
2381 /* ============ Path search helper
2383 * The variable path (passed by reference) should be set to the start
2384 * of the path before the first call; path_advance will update
2385 * this value as it proceeds. Successive calls to path_advance will return
2386 * the possible path expansions in sequence. If an option (indicated by
2387 * a percent sign) appears in the path entry then the global variable
2388 * pathopt will be set to point to it; otherwise pathopt will be set to
2391 static const char *pathopt; /* set by path_advance */
2394 path_advance(const char **path, const char *name)
2404 for (p = start; *p && *p != ':' && *p != '%'; p++)
2406 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2407 while (stackblocksize() < len)
2411 memcpy(q, start, p - start);
2419 while (*p && *p != ':')
2426 return stalloc(len);
2430 /* ============ Prompt */
2432 static smallint doprompt; /* if set, prompt the user */
2433 static smallint needprompt; /* true if interactive and at start of line */
2435 #if ENABLE_FEATURE_EDITING
2436 static line_input_t *line_input_state;
2437 static const char *cmdedit_prompt;
2439 putprompt(const char *s)
2441 if (ENABLE_ASH_EXPAND_PRMT) {
2442 free((char*)cmdedit_prompt);
2443 cmdedit_prompt = ckstrdup(s);
2450 putprompt(const char *s)
2456 #if ENABLE_ASH_EXPAND_PRMT
2457 /* expandstr() needs parsing machinery, so it is far away ahead... */
2458 static const char *expandstr(const char *ps);
2460 #define expandstr(s) s
2464 setprompt_if(smallint do_set, int whichprompt)
2467 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2474 switch (whichprompt) {
2484 #if ENABLE_ASH_EXPAND_PRMT
2485 setstackmark(&smark);
2486 stalloc(stackblocksize());
2488 putprompt(expandstr(prompt));
2489 #if ENABLE_ASH_EXPAND_PRMT
2490 popstackmark(&smark);
2495 /* ============ The cd and pwd commands */
2497 #define CD_PHYSICAL 1
2507 while ((i = nextopt("LP")) != '\0') {
2509 flags ^= CD_PHYSICAL;
2518 * Update curdir (the name of the current directory) in response to a
2522 updatepwd(const char *dir)
2529 cdcomppath = sstrdup(dir);
2532 if (curdir == nullstr)
2534 new = stack_putstr(curdir, new);
2536 new = makestrspace(strlen(dir) + 2, new);
2537 lim = (char *)stackblock() + 1;
2541 if (new > lim && *lim == '/')
2546 if (dir[1] == '/' && dir[2] != '/') {
2552 p = strtok(cdcomppath, "/");
2556 if (p[1] == '.' && p[2] == '\0') {
2568 new = stack_putstr(p, new);
2571 p = strtok(NULL, "/");
2576 return stackblock();
2580 * Find out what the current directory is. If we already know the current
2581 * directory, this routine returns immediately.
2586 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2587 return dir ? dir : nullstr;
2591 setpwd(const char *val, int setold)
2595 oldcur = dir = curdir;
2598 setvar("OLDPWD", oldcur, VEXPORT);
2601 if (physdir != nullstr) {
2602 if (physdir != oldcur)
2606 if (oldcur == val || !val) {
2612 dir = ckstrdup(val);
2613 if (oldcur != dir && oldcur != nullstr) {
2618 setvar("PWD", dir, VEXPORT);
2621 static void hashcd(void);
2624 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2625 * know that the current directory has changed.
2628 docd(const char *dest, int flags)
2630 const char *dir = NULL;
2633 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2636 if (!(flags & CD_PHYSICAL)) {
2637 dir = updatepwd(dest);
2651 static int FAST_FUNC
2652 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2664 dest = bltinlookup("HOME");
2665 else if (LONE_DASH(dest)) {
2666 dest = bltinlookup("OLDPWD");
2688 path = bltinlookup("CDPATH");
2697 p = path_advance(&path, dest);
2698 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2702 if (!docd(p, flags))
2707 ash_msg_and_raise_error("can't cd to %s", dest);
2710 if (flags & CD_PRINT)
2711 out1fmt("%s\n", curdir);
2715 static int FAST_FUNC
2716 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2719 const char *dir = curdir;
2723 if (physdir == nullstr)
2727 out1fmt("%s\n", dir);
2732 /* ============ ... */
2735 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2737 /* Syntax classes */
2738 #define CWORD 0 /* character is nothing special */
2739 #define CNL 1 /* newline character */
2740 #define CBACK 2 /* a backslash character */
2741 #define CSQUOTE 3 /* single quote */
2742 #define CDQUOTE 4 /* double quote */
2743 #define CENDQUOTE 5 /* a terminating quote */
2744 #define CBQUOTE 6 /* backwards single quote */
2745 #define CVAR 7 /* a dollar sign */
2746 #define CENDVAR 8 /* a '}' character */
2747 #define CLP 9 /* a left paren in arithmetic */
2748 #define CRP 10 /* a right paren in arithmetic */
2749 #define CENDFILE 11 /* end of file */
2750 #define CCTL 12 /* like CWORD, except it must be escaped */
2751 #define CSPCL 13 /* these terminate a word */
2752 #define CIGN 14 /* character should be ignored */
2755 #if ENABLE_ASH_ALIAS
2759 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2761 #if ENABLE_SH_MATH_SUPPORT
2762 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2764 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2766 static const uint16_t S_I_T[] ALIGN2 = {
2767 #if ENABLE_ASH_ALIAS
2768 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2770 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2771 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2772 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2773 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2774 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2775 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2776 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2777 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2778 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2779 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2780 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2781 #if !USE_SIT_FUNCTION
2782 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2783 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2784 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2788 /* Constants below must match table above */
2790 #if ENABLE_ASH_ALIAS
2791 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2793 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2794 CNL_CNL_CNL_CNL , /* 2 */
2795 CWORD_CCTL_CCTL_CWORD , /* 3 */
2796 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2797 CVAR_CVAR_CWORD_CVAR , /* 5 */
2798 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2799 CSPCL_CWORD_CWORD_CLP , /* 7 */
2800 CSPCL_CWORD_CWORD_CRP , /* 8 */
2801 CBACK_CBACK_CCTL_CBACK , /* 9 */
2802 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2803 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2804 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2805 CWORD_CWORD_CWORD_CWORD , /* 13 */
2806 CCTL_CCTL_CCTL_CCTL , /* 14 */
2809 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2810 * caller must ensure proper cast on it if c is *char_ptr!
2812 /* Values for syntax param */
2813 #define BASESYNTAX 0 /* not in quotes */
2814 #define DQSYNTAX 1 /* in double quotes */
2815 #define SQSYNTAX 2 /* in single quotes */
2816 #define ARISYNTAX 3 /* in arithmetic */
2817 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2819 #if USE_SIT_FUNCTION
2822 SIT(int c, int syntax)
2824 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2825 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2827 * This causes '/' to be prepended with CTLESC in dquoted string,
2828 * making "./file"* treated incorrectly because we feed
2829 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2830 * The "homegrown" glob implementation is okay with that,
2831 * but glibc one isn't. With '/' always treated as CWORD,
2834 # if ENABLE_ASH_ALIAS
2835 static const uint8_t syntax_index_table[] ALIGN1 = {
2836 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2837 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2838 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2842 static const uint8_t syntax_index_table[] ALIGN1 = {
2843 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2844 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2845 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2854 # if ENABLE_ASH_ALIAS
2860 /* Cast is purely for paranoia here,
2861 * just in case someone passed signed char to us */
2862 if ((unsigned char)c >= CTL_FIRST
2863 && (unsigned char)c <= CTL_LAST
2867 s = strchrnul(spec_symbls, c);
2870 indx = syntax_index_table[s - spec_symbls];
2872 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2875 #else /* !USE_SIT_FUNCTION */
2877 static const uint8_t syntax_index_table[] ALIGN1 = {
2878 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2879 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2889 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2890 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2912 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2913 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2914 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2916 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2918 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2919 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2920 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2921 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2922 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2924 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2925 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2926 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2927 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2939 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2940 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2941 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2942 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2943 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2944 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2972 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2973 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2974 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2977 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3005 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3006 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3007 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3008 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3010 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3011 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3012 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3013 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3014 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3015 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3016 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3017 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3120 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3121 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3122 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3123 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3124 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3125 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3126 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3127 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3128 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3129 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3130 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3131 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3132 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3133 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3134 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3135 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3136 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3137 # if ENABLE_ASH_ALIAS
3138 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3142 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3144 #endif /* !USE_SIT_FUNCTION */
3147 /* ============ Alias handling */
3149 #if ENABLE_ASH_ALIAS
3151 #define ALIASINUSE 1
3162 static struct alias **atab; // [ATABSIZE];
3163 #define INIT_G_alias() do { \
3164 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3168 static struct alias **
3169 __lookupalias(const char *name) {
3170 unsigned int hashval;
3177 ch = (unsigned char)*p;
3181 ch = (unsigned char)*++p;
3183 app = &atab[hashval % ATABSIZE];
3185 for (; *app; app = &(*app)->next) {
3186 if (strcmp(name, (*app)->name) == 0) {
3194 static struct alias *
3195 lookupalias(const char *name, int check)
3197 struct alias *ap = *__lookupalias(name);
3199 if (check && ap && (ap->flag & ALIASINUSE))
3204 static struct alias *
3205 freealias(struct alias *ap)
3209 if (ap->flag & ALIASINUSE) {
3210 ap->flag |= ALIASDEAD;
3222 setalias(const char *name, const char *val)
3224 struct alias *ap, **app;
3226 app = __lookupalias(name);
3230 if (!(ap->flag & ALIASINUSE)) {
3233 ap->val = ckstrdup(val);
3234 ap->flag &= ~ALIASDEAD;
3237 ap = ckzalloc(sizeof(struct alias));
3238 ap->name = ckstrdup(name);
3239 ap->val = ckstrdup(val);
3240 /*ap->flag = 0; - ckzalloc did it */
3241 /*ap->next = NULL;*/
3248 unalias(const char *name)
3252 app = __lookupalias(name);
3256 *app = freealias(*app);
3267 struct alias *ap, **app;
3271 for (i = 0; i < ATABSIZE; i++) {
3273 for (ap = *app; ap; ap = *app) {
3274 *app = freealias(*app);
3284 printalias(const struct alias *ap)
3286 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3290 * TODO - sort output
3292 static int FAST_FUNC
3293 aliascmd(int argc UNUSED_PARAM, char **argv)
3302 for (i = 0; i < ATABSIZE; i++) {
3303 for (ap = atab[i]; ap; ap = ap->next) {
3309 while ((n = *++argv) != NULL) {
3310 v = strchr(n+1, '=');
3311 if (v == NULL) { /* n+1: funny ksh stuff */
3312 ap = *__lookupalias(n);
3314 fprintf(stderr, "%s: %s not found\n", "alias", n);
3327 static int FAST_FUNC
3328 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3332 while ((i = nextopt("a")) != '\0') {
3338 for (i = 0; *argptr; argptr++) {
3339 if (unalias(*argptr)) {
3340 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3348 #endif /* ASH_ALIAS */
3351 /* ============ jobs.c */
3353 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3356 #define FORK_NOJOB 2
3358 /* mode flags for showjob(s) */
3359 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3360 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3361 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3362 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3365 * A job structure contains information about a job. A job is either a
3366 * single process or a set of processes contained in a pipeline. In the
3367 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3371 pid_t ps_pid; /* process id */
3372 int ps_status; /* last process status from wait() */
3373 char *ps_cmd; /* text of command being run */
3377 struct procstat ps0; /* status of process */
3378 struct procstat *ps; /* status or processes when more than one */
3380 int stopstatus; /* status of a stopped job */
3383 nprocs: 16, /* number of processes */
3385 #define JOBRUNNING 0 /* at least one proc running */
3386 #define JOBSTOPPED 1 /* all procs are stopped */
3387 #define JOBDONE 2 /* all procs are completed */
3389 sigint: 1, /* job was killed by SIGINT */
3390 jobctl: 1, /* job running under job control */
3392 waited: 1, /* true if this entry has been waited for */
3393 used: 1, /* true if this entry is in used */
3394 changed: 1; /* true if status has changed */
3395 struct job *prev_job; /* previous job */
3398 static struct job *makejob(/*union node *,*/ int);
3399 static int forkshell(struct job *, union node *, int);
3400 static int waitforjob(struct job *);
3403 enum { doing_jobctl = 0 };
3404 #define setjobctl(on) do {} while (0)
3406 static smallint doing_jobctl; //references:8
3407 static void setjobctl(int);
3414 ignoresig(int signo)
3416 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3417 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3418 /* No, need to do it */
3419 signal(signo, SIG_IGN);
3421 sigmode[signo - 1] = S_HARD_IGN;
3425 * Only one usage site - in setsignal()
3428 signal_handler(int signo)
3430 gotsig[signo - 1] = 1;
3432 if (signo == SIGINT && !trap[SIGINT]) {
3433 if (!suppress_int) {
3435 raise_interrupt(); /* does not return */
3439 pending_sig = signo;
3444 * Set the signal handler for the specified signal. The routine figures
3445 * out what it should be set to.
3448 setsignal(int signo)
3451 char cur_act, new_act;
3452 struct sigaction act;
3456 if (t != NULL) { /* trap for this sig is set */
3458 if (t[0] == '\0') /* trap is "": ignore this sig */
3462 if (rootshell && new_act == S_DFL) {
3465 if (iflag || minusc || sflag == 0)
3474 * "In all cases, bash ignores SIGQUIT. Non-builtin
3475 * commands run by bash have signal handlers
3476 * set to the values inherited by the shell
3477 * from its parent". */
3493 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3494 //whereas we have to restore it to what shell got on entry
3495 //from the parent. See comment above
3497 t = &sigmode[signo - 1];
3500 /* current setting is not yet known */
3501 if (sigaction(signo, NULL, &act)) {
3502 /* pretend it worked; maybe we should give a warning,
3503 * but other shells don't. We don't alter sigmode,
3504 * so we retry every time.
3505 * btw, in Linux it never fails. --vda */
3508 if (act.sa_handler == SIG_IGN) {
3509 cur_act = S_HARD_IGN;
3511 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3513 cur_act = S_IGN; /* don't hard ignore these */
3517 if (cur_act == S_HARD_IGN || cur_act == new_act)
3520 act.sa_handler = SIG_DFL;
3523 act.sa_handler = signal_handler;
3526 act.sa_handler = SIG_IGN;
3530 /* flags and mask matter only if !DFL and !IGN, but we do it
3531 * for all cases for more deterministic behavior:
3534 sigfillset(&act.sa_mask);
3536 sigaction_set(signo, &act);
3541 /* mode flags for set_curjob */
3542 #define CUR_DELETE 2
3543 #define CUR_RUNNING 1
3544 #define CUR_STOPPED 0
3546 /* mode flags for dowait */
3547 #define DOWAIT_NONBLOCK WNOHANG
3548 #define DOWAIT_BLOCK 0
3551 /* pgrp of shell on invocation */
3552 static int initialpgrp; //references:2
3553 static int ttyfd = -1; //5
3556 static struct job *jobtab; //5
3558 static unsigned njobs; //4
3560 static struct job *curjob; //lots
3561 /* number of presumed living untracked jobs */
3562 static int jobless; //4
3565 set_curjob(struct job *jp, unsigned mode)
3568 struct job **jpp, **curp;
3570 /* first remove from list */
3571 jpp = curp = &curjob;
3576 jpp = &jp1->prev_job;
3578 *jpp = jp1->prev_job;
3580 /* Then re-insert in correct position */
3588 /* job being deleted */
3591 /* newly created job or backgrounded job,
3592 * put after all stopped jobs.
3597 if (!jp1 || jp1->state != JOBSTOPPED)
3600 jpp = &jp1->prev_job;
3606 /* newly stopped job - becomes curjob */
3607 jp->prev_job = *jpp;
3615 jobno(const struct job *jp)
3617 return jp - jobtab + 1;
3622 * Convert a job name to a job structure.
3625 #define getjob(name, getctl) getjob(name)
3628 getjob(const char *name, int getctl)
3632 const char *err_msg = "%s: no such job";
3636 char *(*match)(const char *, const char *);
3651 if (c == '+' || c == '%') {
3653 err_msg = "No current job";
3659 err_msg = "No previous job";
3669 if (num > 0 && num <= njobs) {
3670 jp = jobtab + num - 1;
3685 if (match(jp->ps[0].ps_cmd, p)) {
3689 err_msg = "%s: ambiguous";
3699 err_msg = "job %s not created under job control";
3700 if (getctl && jp->jobctl == 0)
3705 ash_msg_and_raise_error(err_msg, name);
3709 * Mark a job structure as unused.
3712 freejob(struct job *jp)
3714 struct procstat *ps;
3718 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3719 if (ps->ps_cmd != nullstr)
3722 if (jp->ps != &jp->ps0)
3725 set_curjob(jp, CUR_DELETE);
3731 xtcsetpgrp(int fd, pid_t pgrp)
3733 if (tcsetpgrp(fd, pgrp))
3734 ash_msg_and_raise_error("can't set tty process group (%m)");
3738 * Turn job control on and off.
3740 * Note: This code assumes that the third arg to ioctl is a character
3741 * pointer, which is true on Berkeley systems but not System V. Since
3742 * System V doesn't have job control yet, this isn't a problem now.
3744 * Called with interrupts off.
3752 if (on == doing_jobctl || rootshell == 0)
3756 ofd = fd = open(_PATH_TTY, O_RDWR);
3758 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3759 * That sometimes helps to acquire controlling tty.
3760 * Obviously, a workaround for bugs when someone
3761 * failed to provide a controlling tty to bash! :) */
3767 fd = fcntl(fd, F_DUPFD, 10);
3772 /* fd is a tty at this point */
3773 close_on_exec_on(fd);
3774 while (1) { /* while we are in the background */
3775 pgrp = tcgetpgrp(fd);
3778 ash_msg("can't access tty; job control turned off");
3782 if (pgrp == getpgrp())
3793 xtcsetpgrp(fd, pgrp);
3795 /* turning job control off */
3798 /* was xtcsetpgrp, but this can make exiting ash
3799 * loop forever if pty is already deleted */
3800 tcsetpgrp(fd, pgrp);
3814 static int FAST_FUNC
3815 killcmd(int argc, char **argv)
3817 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3820 if (argv[i][0] == '%') {
3822 * "kill %N" - job kill
3823 * Converting to pgrp / pid kill
3829 jp = getjob(argv[i], 0);
3831 * In jobs started under job control, we signal
3832 * entire process group by kill -PGRP_ID.
3833 * This happens, f.e., in interactive shell.
3835 * Otherwise, we signal each child via
3836 * kill PID1 PID2 PID3.
3838 * sh -c 'sleep 1|sleep 1 & kill %1'
3839 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3840 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3842 n = jp->nprocs; /* can't be 0 (I hope) */
3845 dst = alloca(n * sizeof(int)*4);
3847 for (j = 0; j < n; j++) {
3848 struct procstat *ps = &jp->ps[j];
3849 /* Skip non-running and not-stopped members
3850 * (i.e. dead members) of the job
3852 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3855 * kill_main has matching code to expect
3856 * leading space. Needed to not confuse
3857 * negative pids with "kill -SIGNAL_NO" syntax
3859 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3863 } while (argv[++i]);
3865 return kill_main(argc, argv);
3869 showpipe(struct job *jp /*, FILE *out*/)
3871 struct procstat *ps;
3872 struct procstat *psend;
3874 psend = jp->ps + jp->nprocs;
3875 for (ps = jp->ps + 1; ps < psend; ps++)
3876 printf(" | %s", ps->ps_cmd);
3877 newline_and_flush(stdout);
3878 flush_stdout_stderr();
3883 restartjob(struct job *jp, int mode)
3885 struct procstat *ps;
3891 if (jp->state == JOBDONE)
3893 jp->state = JOBRUNNING;
3894 pgid = jp->ps[0].ps_pid;
3895 if (mode == FORK_FG)
3896 xtcsetpgrp(ttyfd, pgid);
3897 killpg(pgid, SIGCONT);
3901 if (WIFSTOPPED(ps->ps_status)) {
3907 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3912 static int FAST_FUNC
3913 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3919 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3923 jp = getjob(*argv, 1);
3924 if (mode == FORK_BG) {
3925 set_curjob(jp, CUR_RUNNING);
3926 printf("[%d] ", jobno(jp));
3928 out1str(jp->ps[0].ps_cmd);
3929 showpipe(jp /*, stdout*/);
3930 retval = restartjob(jp, mode);
3931 } while (*argv && *++argv);
3937 sprint_status48(char *s, int status, int sigonly)
3943 if (!WIFEXITED(status)) {
3944 if (JOBS && WIFSTOPPED(status))
3945 st = WSTOPSIG(status);
3947 st = WTERMSIG(status);
3949 if (st == SIGINT || st == SIGPIPE)
3951 if (JOBS && WIFSTOPPED(status))
3955 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3956 col = fmtstr(s, 32, strsignal(st));
3957 if (WCOREDUMP(status)) {
3958 strcpy(s + col, " (core dumped)");
3959 col += sizeof(" (core dumped)")-1;
3961 } else if (!sigonly) {
3962 st = WEXITSTATUS(status);
3963 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
3970 dowait(int wait_flags, struct job *job)
3975 struct job *thisjob;
3977 TRACE(("dowait(0x%x) called\n", wait_flags));
3979 /* Do a wait system call. If job control is compiled in, we accept
3980 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3981 * NB: _not_ safe_waitpid, we need to detect EINTR */
3983 wait_flags |= WUNTRACED;
3984 pid = waitpid(-1, &status, wait_flags);
3985 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3986 pid, status, errno, strerror(errno)));
3992 for (jp = curjob; jp; jp = jp->prev_job) {
3994 struct procstat *ps;
3995 struct procstat *psend;
3996 if (jp->state == JOBDONE)
4000 psend = ps + jp->nprocs;
4002 if (ps->ps_pid == pid) {
4003 TRACE(("Job %d: changing status of proc %d "
4004 "from 0x%x to 0x%x\n",
4005 jobno(jp), pid, ps->ps_status, status));
4006 ps->ps_status = status;
4009 if (ps->ps_status == -1)
4010 jobstate = JOBRUNNING;
4012 if (jobstate == JOBRUNNING)
4014 if (WIFSTOPPED(ps->ps_status)) {
4015 jp->stopstatus = ps->ps_status;
4016 jobstate = JOBSTOPPED;
4019 } while (++ps < psend);
4023 /* Found the job where one of its processes changed its state.
4024 * Is there at least one live and running process in this job? */
4025 if (jobstate != JOBRUNNING) {
4026 /* No. All live processes in the job are stopped
4027 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4029 thisjob->changed = 1;
4030 if (thisjob->state != jobstate) {
4031 TRACE(("Job %d: changing state from %d to %d\n",
4032 jobno(thisjob), thisjob->state, jobstate));
4033 thisjob->state = jobstate;
4035 if (jobstate == JOBSTOPPED)
4036 set_curjob(thisjob, CUR_STOPPED);
4042 /* The process wasn't found in job list */
4043 if (JOBS && !WIFSTOPPED(status))
4048 if (thisjob && thisjob == job) {
4052 len = sprint_status48(s, status, 1);
4063 blocking_wait_with_raise_on_sig(void)
4065 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
4066 if (pid <= 0 && pending_sig)
4067 raise_exception(EXSIG);
4073 showjob(struct job *jp, int mode)
4075 struct procstat *ps;
4076 struct procstat *psend;
4079 char s[16 + 16 + 48];
4080 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4084 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4085 /* just output process (group) id of pipeline */
4086 fprintf(out, "%d\n", ps->ps_pid);
4090 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4095 else if (curjob && jp == curjob->prev_job)
4098 if (mode & SHOW_PIDS)
4099 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4101 psend = ps + jp->nprocs;
4103 if (jp->state == JOBRUNNING) {
4104 strcpy(s + col, "Running");
4105 col += sizeof("Running") - 1;
4107 int status = psend[-1].ps_status;
4108 if (jp->state == JOBSTOPPED)
4109 status = jp->stopstatus;
4110 col += sprint_status48(s + col, status, 0);
4112 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4114 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4115 * or prints several "PID | <cmdN>" lines,
4116 * depending on SHOW_PIDS bit.
4117 * We do not print status of individual processes
4118 * between PID and <cmdN>. bash does it, but not very well:
4119 * first line shows overall job status, not process status,
4120 * making it impossible to know 1st process status.
4124 /* for each process */
4127 if (mode & SHOW_PIDS)
4128 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4130 fprintf(out, "%s%*c%s%s",
4132 33 - col >= 0 ? 33 - col : 0, ' ',
4133 ps == jp->ps ? "" : "| ",
4136 } while (++ps != psend);
4137 newline_and_flush(out);
4141 if (jp->state == JOBDONE) {
4142 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4148 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4149 * statuses have changed since the last call to showjobs.
4156 TRACE(("showjobs(0x%x) called\n", mode));
4158 /* Handle all finished jobs */
4159 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4162 for (jp = curjob; jp; jp = jp->prev_job) {
4163 if (!(mode & SHOW_CHANGED) || jp->changed) {
4169 static int FAST_FUNC
4170 jobscmd(int argc UNUSED_PARAM, char **argv)
4175 while ((m = nextopt("lp")) != '\0') {
4179 mode |= SHOW_ONLY_PGID;
4185 showjob(getjob(*argv, 0), mode);
4195 /* Called only on finished or stopped jobs (no members are running) */
4197 getstatus(struct job *job)
4201 struct procstat *ps;
4203 /* Fetch last member's status */
4204 ps = job->ps + job->nprocs - 1;
4205 status = ps->ps_status;
4207 /* "set -o pipefail" mode: use last _nonzero_ status */
4208 while (status == 0 && --ps >= job->ps)
4209 status = ps->ps_status;
4212 retval = WEXITSTATUS(status);
4213 if (!WIFEXITED(status)) {
4215 retval = WSTOPSIG(status);
4216 if (!WIFSTOPPED(status))
4219 /* XXX: limits number of signals */
4220 retval = WTERMSIG(status);
4222 if (retval == SIGINT)
4228 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4229 jobno(job), job->nprocs, status, retval));
4233 static int FAST_FUNC
4234 waitcmd(int argc UNUSED_PARAM, char **argv)
4241 raise_exception(EXSIG);
4248 /* wait for all jobs */
4252 if (!jp) /* no running procs */
4254 if (jp->state == JOBRUNNING)
4259 blocking_wait_with_raise_on_sig();
4261 * "When bash is waiting for an asynchronous command via
4262 * the wait builtin, the reception of a signal for which a trap
4263 * has been set will cause the wait builtin to return immediately
4264 * with an exit status greater than 128, immediately after which
4265 * the trap is executed."
4267 * blocking_wait_with_raise_on_sig raises signal handlers
4268 * if it gets no pid (pid < 0). However,
4269 * if child sends us a signal *and immediately exits*,
4270 * blocking_wait_with_raise_on_sig gets pid > 0
4271 * and does not handle pending_sig. Check this case: */
4273 raise_exception(EXSIG);
4279 if (**argv != '%') {
4280 pid_t pid = number(*argv);
4285 if (job->ps[job->nprocs - 1].ps_pid == pid)
4287 job = job->prev_job;
4290 job = getjob(*argv, 0);
4292 /* loop until process terminated or stopped */
4293 while (job->state == JOBRUNNING)
4294 blocking_wait_with_raise_on_sig();
4296 retval = getstatus(job);
4309 struct job *jp, *jq;
4311 len = njobs * sizeof(*jp);
4313 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4315 offset = (char *)jp - (char *)jq;
4317 /* Relocate pointers */
4320 jq = (struct job *)((char *)jq + l);
4324 #define joff(p) ((struct job *)((char *)(p) + l))
4325 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4326 if (joff(jp)->ps == &jq->ps0)
4327 jmove(joff(jp)->ps);
4328 if (joff(jp)->prev_job)
4329 jmove(joff(jp)->prev_job);
4339 jp = (struct job *)((char *)jp + len);
4343 } while (--jq >= jp);
4348 * Return a new job structure.
4349 * Called with interrupts off.
4352 makejob(/*union node *node,*/ int nprocs)
4357 for (i = njobs, jp = jobtab; ; jp++) {
4364 if (jp->state != JOBDONE || !jp->waited)
4373 memset(jp, 0, sizeof(*jp));
4375 /* jp->jobctl is a bitfield.
4376 * "jp->jobctl |= jobctl" likely to give awful code */
4380 jp->prev_job = curjob;
4385 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4387 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4394 * Return a string identifying a command (to be printed by the
4397 static char *cmdnextc;
4400 cmdputs(const char *s)
4402 static const char vstype[VSTYPE + 1][3] = {
4403 "", "}", "-", "+", "?", "=",
4404 "%", "%%", "#", "##"
4405 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4408 const char *p, *str;
4412 unsigned char subtype = 0;
4416 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4418 while ((c = *p++) != '\0') {
4426 if ((subtype & VSTYPE) == VSLENGTH)
4432 str = "\"}" + !(quoted & 1);
4439 #if ENABLE_SH_MATH_SUPPORT
4454 if ((subtype & VSTYPE) != VSNORMAL)
4456 str = vstype[subtype & VSTYPE];
4457 if (subtype & VSNUL)
4466 /* These can only happen inside quotes */
4479 while ((c = *str++) != '\0') {
4482 } /* while *p++ not NUL */
4485 USTPUTC('"', nextc);
4491 /* cmdtxt() and cmdlist() call each other */
4492 static void cmdtxt(union node *n);
4495 cmdlist(union node *np, int sep)
4497 for (; np; np = np->narg.next) {
4501 if (sep && np->narg.next)
4507 cmdtxt(union node *n)
4510 struct nodelist *lp;
4521 lp = n->npipe.cmdlist;
4539 cmdtxt(n->nbinary.ch1);
4555 cmdtxt(n->nif.test);
4557 if (n->nif.elsepart) {
4558 cmdtxt(n->nif.ifpart);
4560 n = n->nif.elsepart;
4578 cmdtxt(n->nbinary.ch1);
4588 cmdputs(n->nfor.var);
4590 cmdlist(n->nfor.args, 1);
4595 cmdputs(n->narg.text);
4599 cmdlist(n->ncmd.args, 1);
4600 cmdlist(n->ncmd.redirect, 0);
4613 cmdputs(n->ncase.expr->narg.text);
4615 for (np = n->ncase.cases; np; np = np->nclist.next) {
4616 cmdtxt(np->nclist.pattern);
4618 cmdtxt(np->nclist.body);
4632 #if ENABLE_ASH_BASH_COMPAT
4647 cmdputs(utoa(n->nfile.fd));
4649 if (n->type == NTOFD || n->type == NFROMFD) {
4650 cmdputs(utoa(n->ndup.dupfd));
4659 commandtext(union node *n)
4663 STARTSTACKSTR(cmdnextc);
4665 name = stackblock();
4666 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4667 name, cmdnextc, cmdnextc));
4668 return ckstrdup(name);
4673 * Fork off a subshell. If we are doing job control, give the subshell its
4674 * own process group. Jp is a job structure that the job is to be added to.
4675 * N is the command that will be evaluated by the child. Both jp and n may
4676 * be NULL. The mode parameter can be one of the following:
4677 * FORK_FG - Fork off a foreground process.
4678 * FORK_BG - Fork off a background process.
4679 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4680 * process group even if job control is on.
4682 * When job control is turned off, background processes have their standard
4683 * input redirected to /dev/null (except for the second and later processes
4686 * Called with interrupts off.
4689 * Clear traps on a fork.
4696 for (tp = trap; tp < &trap[NSIG]; tp++) {
4697 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4699 if (trap_ptr == trap)
4701 /* else: it "belongs" to trap_ptr vector, don't free */
4703 if ((tp - trap) != 0)
4704 setsignal(tp - trap);
4711 /* Lives far away from here, needed for forkchild */
4712 static void closescript(void);
4714 /* Called after fork(), in child */
4715 static NOINLINE void
4716 forkchild(struct job *jp, union node *n, int mode)
4720 TRACE(("Child shell %d\n", getpid()));
4724 /* man bash: "Non-builtin commands run by bash have signal handlers
4725 * set to the values inherited by the shell from its parent".
4726 * Do we do it correctly? */
4730 if (mode == FORK_NOJOB /* is it `xxx` ? */
4731 && n && n->type == NCMD /* is it single cmd? */
4732 /* && n->ncmd.args->type == NARG - always true? */
4733 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4734 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4735 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4737 TRACE(("Trap hack\n"));
4738 /* Awful hack for `trap` or $(trap).
4740 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4741 * contains an example where "trap" is executed in a subshell:
4743 * save_traps=$(trap)
4745 * eval "$save_traps"
4747 * Standard does not say that "trap" in subshell shall print
4748 * parent shell's traps. It only says that its output
4749 * must have suitable form, but then, in the above example
4750 * (which is not supposed to be normative), it implies that.
4752 * bash (and probably other shell) does implement it
4753 * (traps are reset to defaults, but "trap" still shows them),
4754 * but as a result, "trap" logic is hopelessly messed up:
4757 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4758 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4759 * # true | trap <--- trap is in subshell - no output (ditto)
4760 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4761 * trap -- 'echo Ho' SIGWINCH
4762 * # echo `(trap)` <--- in subshell in subshell - output
4763 * trap -- 'echo Ho' SIGWINCH
4764 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4765 * trap -- 'echo Ho' SIGWINCH
4767 * The rules when to forget and when to not forget traps
4768 * get really complex and nonsensical.
4770 * Our solution: ONLY bare $(trap) or `trap` is special.
4772 /* Save trap handler strings for trap builtin to print */
4773 trap_ptr = xmemdup(trap, sizeof(trap));
4774 /* Fall through into clearing traps */
4778 /* do job control only in root shell */
4780 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4783 if (jp->nprocs == 0)
4786 pgrp = jp->ps[0].ps_pid;
4787 /* this can fail because we are doing it in the parent also */
4789 if (mode == FORK_FG)
4790 xtcsetpgrp(ttyfd, pgrp);
4795 if (mode == FORK_BG) {
4796 /* man bash: "When job control is not in effect,
4797 * asynchronous commands ignore SIGINT and SIGQUIT" */
4800 if (jp->nprocs == 0) {
4802 if (open(bb_dev_null, O_RDONLY) != 0)
4803 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4807 if (iflag) { /* why if iflag only? */
4812 * "In all cases, bash ignores SIGQUIT. Non-builtin
4813 * commands run by bash have signal handlers
4814 * set to the values inherited by the shell
4816 * Take care of the second rule: */
4820 if (n && n->type == NCMD
4821 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4823 TRACE(("Job hack\n"));
4824 /* "jobs": we do not want to clear job list for it,
4825 * instead we remove only _its_ own_ job from job list.
4826 * This makes "jobs .... | cat" more useful.
4832 for (jp = curjob; jp; jp = jp->prev_job)
4837 /* Called after fork(), in parent */
4839 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4842 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4844 TRACE(("In parent shell: child = %d\n", pid));
4846 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4852 if (mode != FORK_NOJOB && jp->jobctl) {
4855 if (jp->nprocs == 0)
4858 pgrp = jp->ps[0].ps_pid;
4859 /* This can fail because we are doing it in the child also */
4863 if (mode == FORK_BG) {
4864 backgndpid = pid; /* set $! */
4865 set_curjob(jp, CUR_RUNNING);
4868 struct procstat *ps = &jp->ps[jp->nprocs++];
4871 ps->ps_cmd = nullstr;
4873 if (doing_jobctl && n)
4874 ps->ps_cmd = commandtext(n);
4880 forkshell(struct job *jp, union node *n, int mode)
4884 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4887 TRACE(("Fork failed, errno=%d", errno));
4890 ash_msg_and_raise_error("can't fork");
4893 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4894 forkchild(jp, n, mode);
4896 forkparent(jp, n, mode, pid);
4902 * Wait for job to finish.
4904 * Under job control we have the problem that while a child process
4905 * is running interrupts generated by the user are sent to the child
4906 * but not to the shell. This means that an infinite loop started by
4907 * an interactive user may be hard to kill. With job control turned off,
4908 * an interactive user may place an interactive program inside a loop.
4909 * If the interactive program catches interrupts, the user doesn't want
4910 * these interrupts to also abort the loop. The approach we take here
4911 * is to have the shell ignore interrupt signals while waiting for a
4912 * foreground process to terminate, and then send itself an interrupt
4913 * signal if the child process was terminated by an interrupt signal.
4914 * Unfortunately, some programs want to do a bit of cleanup and then
4915 * exit on interrupt; unless these processes terminate themselves by
4916 * sending a signal to themselves (instead of calling exit) they will
4917 * confuse this approach.
4919 * Called with interrupts off.
4922 waitforjob(struct job *jp)
4926 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4929 while (jp->state == JOBRUNNING) {
4930 /* In non-interactive shells, we _can_ get
4931 * a keyboard signal here and be EINTRed,
4932 * but we just loop back, waiting for command to complete.
4935 * "If bash is waiting for a command to complete and receives
4936 * a signal for which a trap has been set, the trap
4937 * will not be executed until the command completes."
4939 * Reality is that even if trap is not set, bash
4940 * will not act on the signal until command completes.
4941 * Try this. sleep5intoff.c:
4942 * #include <signal.h>
4943 * #include <unistd.h>
4946 * sigemptyset(&set);
4947 * sigaddset(&set, SIGINT);
4948 * sigaddset(&set, SIGQUIT);
4949 * sigprocmask(SIG_BLOCK, &set, NULL);
4953 * $ bash -c './sleep5intoff; echo hi'
4954 * ^C^C^C^C <--- pressing ^C once a second
4956 * $ bash -c './sleep5intoff; echo hi'
4957 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4960 dowait(DOWAIT_BLOCK, jp);
4967 xtcsetpgrp(ttyfd, rootpid);
4969 * This is truly gross.
4970 * If we're doing job control, then we did a TIOCSPGRP which
4971 * caused us (the shell) to no longer be in the controlling
4972 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4973 * intuit from the subprocess exit status whether a SIGINT
4974 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4976 if (jp->sigint) /* TODO: do the same with all signals */
4977 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4979 if (jp->state == JOBDONE)
4986 * return 1 if there are stopped jobs, otherwise 0
4998 if (jp && jp->state == JOBSTOPPED) {
4999 out2str("You have stopped jobs.\n");
5008 /* ============ redir.c
5010 * Code for dealing with input/output redirection.
5015 #define EMPTY -2 /* marks an unused slot in redirtab */
5016 #define CLOSED -3 /* marks a slot of previously-closed fd */
5019 * Open a file in noclobber mode.
5020 * The code was copied from bash.
5023 noclobberopen(const char *fname)
5026 struct stat finfo, finfo2;
5029 * If the file exists and is a regular file, return an error
5032 r = stat(fname, &finfo);
5033 if (r == 0 && S_ISREG(finfo.st_mode)) {
5039 * If the file was not present (r != 0), make sure we open it
5040 * exclusively so that if it is created before we open it, our open
5041 * will fail. Make sure that we do not truncate an existing file.
5042 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5043 * file was not a regular file, we leave O_EXCL off.
5046 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5047 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5049 /* If the open failed, return the file descriptor right away. */
5054 * OK, the open succeeded, but the file may have been changed from a
5055 * non-regular file to a regular file between the stat and the open.
5056 * We are assuming that the O_EXCL open handles the case where FILENAME
5057 * did not exist and is symlinked to an existing file between the stat
5062 * If we can open it and fstat the file descriptor, and neither check
5063 * revealed that it was a regular file, and the file has not been
5064 * replaced, return the file descriptor.
5066 if (fstat(fd, &finfo2) == 0
5067 && !S_ISREG(finfo2.st_mode)
5068 && finfo.st_dev == finfo2.st_dev
5069 && finfo.st_ino == finfo2.st_ino
5074 /* The file has been replaced. badness. */
5081 * Handle here documents. Normally we fork off a process to write the
5082 * data to a pipe. If the document is short, we can stuff the data in
5083 * the pipe without forking.
5085 /* openhere needs this forward reference */
5086 static void expandhere(union node *arg, int fd);
5088 openhere(union node *redir)
5094 ash_msg_and_raise_error("pipe call failed");
5095 if (redir->type == NHERE) {
5096 len = strlen(redir->nhere.doc->narg.text);
5097 if (len <= PIPE_BUF) {
5098 full_write(pip[1], redir->nhere.doc->narg.text, len);
5102 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5105 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5106 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5107 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5108 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5109 signal(SIGPIPE, SIG_DFL);
5110 if (redir->type == NHERE)
5111 full_write(pip[1], redir->nhere.doc->narg.text, len);
5113 expandhere(redir->nhere.doc, pip[1]);
5114 _exit(EXIT_SUCCESS);
5122 openredirect(union node *redir)
5127 switch (redir->nfile.type) {
5128 /* Can't happen, our single caller does this itself */
5134 return openhere(redir);
5137 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5138 * allocated space. Do it only when we know it is safe.
5140 fname = redir->nfile.expfname;
5142 switch (redir->nfile.type) {
5148 f = open(fname, O_RDONLY);
5153 f = open(fname, O_RDWR|O_CREAT, 0666);
5158 #if ENABLE_ASH_BASH_COMPAT
5161 /* Take care of noclobber mode. */
5163 f = noclobberopen(fname);
5170 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5175 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5183 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5185 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5189 * Copy a file descriptor to be >= to. Returns -1
5190 * if the source file descriptor is closed, EMPTY if there are no unused
5191 * file descriptors left.
5193 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5194 * old code was doing close(to) prior to copyfd() to achieve the same */
5196 COPYFD_EXACT = (int)~(INT_MAX),
5197 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5200 copyfd(int from, int to)
5204 if (to & COPYFD_EXACT) {
5205 to &= ~COPYFD_EXACT;
5207 newfd = dup2(from, to);
5209 newfd = fcntl(from, F_DUPFD, to);
5212 if (errno == EMFILE)
5214 /* Happens when source fd is not open: try "echo >&99" */
5215 ash_msg_and_raise_error("%d: %m", from);
5220 /* Struct def and variable are moved down to the first usage site */
5225 struct redirtab *next;
5228 struct two_fd_t two_fd[];
5230 #define redirlist (G_var.redirlist)
5232 static int need_to_remember(struct redirtab *rp, int fd)
5236 if (!rp) /* remembering was not requested */
5239 for (i = 0; i < rp->pair_count; i++) {
5240 if (rp->two_fd[i].orig == fd) {
5241 /* already remembered */
5248 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5249 static int is_hidden_fd(struct redirtab *rp, int fd)
5252 struct parsefile *pf;
5256 /* Check open scripts' fds */
5259 /* We skip pf_fd == 0 case because of the following case:
5260 * $ ash # running ash interactively
5262 * and in script.sh: "exec 9>&0".
5263 * Even though top-level pf_fd _is_ 0,
5264 * it's still ok to use it: "read" builtin uses it,
5265 * why should we cripple "exec" builtin?
5267 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5275 /* Check saved fds of redirects */
5276 fd |= COPYFD_RESTORE;
5277 for (i = 0; i < rp->pair_count; i++) {
5278 if (rp->two_fd[i].copy == fd) {
5286 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5287 * old file descriptors are stashed away so that the redirection can be
5288 * undone by calling popredir.
5290 /* flags passed to redirect */
5291 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5292 #define REDIR_SAVEFD2 03 /* set preverrout */
5294 redirect(union node *redir, int flags)
5296 struct redirtab *sv;
5301 int copied_fd2 = -1;
5311 if (flags & REDIR_PUSH) {
5312 union node *tmp = redir;
5315 #if ENABLE_ASH_BASH_COMPAT
5316 if (tmp->nfile.type == NTO2)
5319 tmp = tmp->nfile.next;
5321 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5322 sv->next = redirlist;
5323 sv->pair_count = sv_pos;
5325 sv->nullredirs = g_nullredirs - 1;
5327 while (sv_pos > 0) {
5329 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5335 fd = redir->nfile.fd;
5336 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5337 right_fd = redir->ndup.dupfd;
5338 //bb_error_msg("doing %d > %d", fd, right_fd);
5339 /* redirect from/to same file descriptor? */
5342 /* "echo >&10" and 10 is a fd opened to a sh script? */
5343 if (is_hidden_fd(sv, right_fd)) {
5344 errno = EBADF; /* as if it is closed */
5345 ash_msg_and_raise_error("%d: %m", right_fd);
5349 newfd = openredirect(redir); /* always >= 0 */
5351 /* Descriptor wasn't open before redirect.
5352 * Mark it for close in the future */
5353 if (need_to_remember(sv, fd)) {
5354 goto remember_to_close;
5359 #if ENABLE_ASH_BASH_COMPAT
5362 if (need_to_remember(sv, fd)) {
5363 /* Copy old descriptor */
5364 /* Careful to not accidentally "save"
5365 * to the same fd as right side fd in N>&M */
5366 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5367 i = fcntl(fd, F_DUPFD, minfd);
5368 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5369 * are closed in popredir() in the child, preventing them from leaking
5370 * into child. (popredir() also cleans up the mess in case of failures)
5375 /* Strange error (e.g. "too many files" EMFILE?) */
5379 ash_msg_and_raise_error("%d: %m", fd);
5382 /* EBADF: it is not open - good, remember to close it */
5385 } else { /* fd is open, save its copy */
5386 /* "exec fd>&-" should not close fds
5387 * which point to script file(s).
5388 * Force them to be restored afterwards */
5389 if (is_hidden_fd(sv, fd))
5390 i |= COPYFD_RESTORE;
5394 sv->two_fd[sv_pos].orig = fd;
5395 sv->two_fd[sv_pos].copy = i;
5399 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5400 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5401 /* Don't want to trigger debugging */
5405 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5407 } else if (fd != newfd) { /* move newfd to fd */
5408 copyfd(newfd, fd | COPYFD_EXACT);
5409 #if ENABLE_ASH_BASH_COMPAT
5410 if (!(redir->nfile.type == NTO2 && fd == 2))
5414 #if ENABLE_ASH_BASH_COMPAT
5415 if (redir->nfile.type == NTO2 && fd == 1) {
5416 /* We already redirected it to fd 1, now copy it to 2 */
5422 } while ((redir = redir->nfile.next) != NULL);
5425 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5426 preverrout_fd = copied_fd2;
5430 * Undo the effects of the last redirection.
5433 popredir(int drop, int restore)
5435 struct redirtab *rp;
5438 if (--g_nullredirs >= 0 || redirlist == NULL)
5442 for (i = 0; i < rp->pair_count; i++) {
5443 int fd = rp->two_fd[i].orig;
5444 int copy = rp->two_fd[i].copy;
5445 if (copy == CLOSED) {
5450 if (copy != EMPTY) {
5451 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5452 copy &= ~COPYFD_RESTORE;
5454 copyfd(copy, fd | COPYFD_EXACT);
5456 close(copy & ~COPYFD_RESTORE);
5459 redirlist = rp->next;
5460 g_nullredirs = rp->nullredirs;
5466 * Undo all redirections. Called on error or interrupt.
5470 * Discard all saved file descriptors.
5473 clearredir(int drop)
5479 popredir(drop, /*restore:*/ 0);
5484 redirectsafe(union node *redir, int flags)
5487 volatile int saveint;
5488 struct jmploc *volatile savehandler = exception_handler;
5489 struct jmploc jmploc;
5492 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5493 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5495 exception_handler = &jmploc;
5496 redirect(redir, flags);
5498 exception_handler = savehandler;
5499 if (err && exception_type != EXERROR)
5500 longjmp(exception_handler->loc, 1);
5501 RESTORE_INT(saveint);
5506 /* ============ Routines to expand arguments to commands
5508 * We have to deal with backquotes, shell variables, and file metacharacters.
5511 #if ENABLE_SH_MATH_SUPPORT
5513 ash_arith(const char *s)
5515 arith_state_t math_state;
5518 math_state.lookupvar = lookupvar;
5519 math_state.setvar = setvar0;
5520 //math_state.endofname = endofname;
5523 result = arith(&math_state, s);
5524 if (math_state.errmsg)
5525 ash_msg_and_raise_error(math_state.errmsg);
5535 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5536 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5537 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5538 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5539 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5540 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5541 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5542 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5543 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5547 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5548 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5549 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5550 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5551 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5553 /* Add CTLESC when necessary. */
5554 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5555 /* Do not skip NUL characters. */
5556 #define QUOTES_KEEPNUL EXP_TILDE
5559 * Structure specifying which parts of the string should be searched
5560 * for IFS characters.
5563 struct ifsregion *next; /* next region in list */
5564 int begoff; /* offset of start of region */
5565 int endoff; /* offset of end of region */
5566 int nulonly; /* search for nul bytes only */
5570 struct strlist *list;
5571 struct strlist **lastp;
5574 /* output of current string */
5575 static char *expdest;
5576 /* list of back quote expressions */
5577 static struct nodelist *argbackq;
5578 /* first struct in list of ifs regions */
5579 static struct ifsregion ifsfirst;
5580 /* last struct in list */
5581 static struct ifsregion *ifslastp;
5582 /* holds expanded arg list */
5583 static struct arglist exparg;
5588 #if !ENABLE_SH_MATH_SUPPORT
5589 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5590 typedef long arith_t;
5591 # define ARITH_FMT "%ld"
5598 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5599 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5600 STADJUST(len, expdest);
5605 esclen(const char *start, const char *p)
5609 while (p > start && (unsigned char)*--p == CTLESC) {
5616 * Remove any CTLESC characters from a string.
5619 rmescapes(char *str, int flag)
5621 static const char qchars[] ALIGN1 = {
5622 IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
5626 unsigned protect_against_glob;
5628 IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
5630 p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
5636 if (flag & RMESCAPE_ALLOC) {
5637 size_t len = p - str;
5638 size_t fulllen = len + strlen(p) + 1;
5640 if (flag & RMESCAPE_GROW) {
5641 int strloc = str - (char *)stackblock();
5642 r = makestrspace(fulllen, expdest);
5643 /* p and str may be invalidated by makestrspace */
5644 str = (char *)stackblock() + strloc;
5646 } else if (flag & RMESCAPE_HEAP) {
5647 r = ckmalloc(fulllen);
5649 r = stalloc(fulllen);
5653 q = (char *)memcpy(q, str, len) + len;
5658 globbing = flag & RMESCAPE_GLOB;
5659 protect_against_glob = globbing;
5661 if ((unsigned char)*p == CTLQUOTEMARK) {
5662 // Note: both inquotes and protect_against_glob only affect whether
5663 inquotes = ~inquotes;
5665 protect_against_glob = globbing;
5668 if ((unsigned char)*p == CTLESC) {
5672 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5674 if (protect_against_glob) {
5677 } else if (*p == '\\' && !inquotes) {
5678 /* naked back slash */
5679 protect_against_glob = 0;
5682 #if ENABLE_ASH_BASH_COMPAT
5683 else if (*p == '/' && slash) {
5684 /* stop handling globbing and mark location of slash */
5685 globbing = slash = 0;
5689 protect_against_glob = globbing;
5694 if (flag & RMESCAPE_GROW) {
5696 STADJUST(q - r + 1, expdest);
5700 #define pmatch(a, b) !fnmatch((a), (b), 0)
5703 * Prepare a pattern for a expmeta (internal glob(3)) call.
5705 * Returns an stalloced string.
5708 preglob(const char *pattern, int flag)
5710 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5714 * Put a string on the stack.
5717 memtodest(const char *p, size_t len, int syntax, int quotes)
5724 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5727 unsigned char c = *p++;
5729 int n = SIT(c, syntax);
5730 if ((quotes & QUOTES_ESC)
5732 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
5738 } else if (!(quotes & QUOTES_KEEPNUL))
5747 strtodest(const char *p, int syntax, int quotes)
5749 size_t len = strlen(p);
5750 memtodest(p, len, syntax, quotes);
5755 * Record the fact that we have to scan this region of the
5756 * string for IFS characters.
5759 recordregion(int start, int end, int nulonly)
5761 struct ifsregion *ifsp;
5763 if (ifslastp == NULL) {
5767 ifsp = ckzalloc(sizeof(*ifsp));
5768 /*ifsp->next = NULL; - ckzalloc did it */
5769 ifslastp->next = ifsp;
5773 ifslastp->begoff = start;
5774 ifslastp->endoff = end;
5775 ifslastp->nulonly = nulonly;
5779 removerecordregions(int endoff)
5781 if (ifslastp == NULL)
5784 if (ifsfirst.endoff > endoff) {
5785 while (ifsfirst.next) {
5786 struct ifsregion *ifsp;
5788 ifsp = ifsfirst.next->next;
5789 free(ifsfirst.next);
5790 ifsfirst.next = ifsp;
5793 if (ifsfirst.begoff > endoff) {
5796 ifslastp = &ifsfirst;
5797 ifsfirst.endoff = endoff;
5802 ifslastp = &ifsfirst;
5803 while (ifslastp->next && ifslastp->next->begoff < endoff)
5804 ifslastp = ifslastp->next;
5805 while (ifslastp->next) {
5806 struct ifsregion *ifsp;
5808 ifsp = ifslastp->next->next;
5809 free(ifslastp->next);
5810 ifslastp->next = ifsp;
5813 if (ifslastp->endoff > endoff)
5814 ifslastp->endoff = endoff;
5818 exptilde(char *startp, char *p, int flags)
5824 int quotes = flags & QUOTES_ESC;
5828 while ((c = *++p) != '\0') {
5835 if (flags & EXP_VARTILDE)
5845 if (*name == '\0') {
5846 home = lookupvar("HOME");
5848 pw = getpwnam(name);
5853 if (!home || !*home)
5856 strtodest(home, SQSYNTAX, quotes);
5864 * Execute a command inside back quotes. If it's a builtin command, we
5865 * want to save its output in a block obtained from malloc. Otherwise
5866 * we fork off a subprocess and get the output of the command via a pipe.
5867 * Should be called with interrupts off.
5869 struct backcmd { /* result of evalbackcmd */
5870 int fd; /* file descriptor to read from */
5871 int nleft; /* number of chars in buffer */
5872 char *buf; /* buffer */
5873 struct job *jp; /* job structure for command */
5876 /* These forward decls are needed to use "eval" code for backticks handling: */
5877 static uint8_t back_exitstatus; /* exit status of backquoted command */
5878 #define EV_EXIT 01 /* exit after evaluating tree */
5879 static int evaltree(union node *, int);
5881 static void FAST_FUNC
5882 evalbackcmd(union node *n, struct backcmd *result)
5893 saveherefd = herefd;
5901 ash_msg_and_raise_error("pipe call failed");
5902 jp = makejob(/*n,*/ 1);
5903 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5908 copyfd(pip[1], 1 | COPYFD_EXACT);
5912 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5916 result->fd = pip[0];
5919 herefd = saveherefd;
5921 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5922 result->fd, result->buf, result->nleft, result->jp));
5926 * Expand stuff in backwards quotes.
5929 expbackq(union node *cmd, int flag)
5937 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
5938 struct stackmark smark;
5941 setstackmark(&smark);
5943 startloc = dest - (char *)stackblock();
5945 evalbackcmd(cmd, &in);
5946 popstackmark(&smark);
5953 memtodest(p, i, syntax, flag & QUOTES_ESC);
5957 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
5958 TRACE(("expbackq: read returns %d\n", i));
5967 back_exitstatus = waitforjob(in.jp);
5971 /* Eat all trailing newlines */
5973 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5977 if (!(flag & EXP_QUOTED))
5978 recordregion(startloc, dest - (char *)stackblock(), 0);
5979 TRACE(("evalbackq: size:%d:'%.*s'\n",
5980 (int)((dest - (char *)stackblock()) - startloc),
5981 (int)((dest - (char *)stackblock()) - startloc),
5982 stackblock() + startloc));
5985 #if ENABLE_SH_MATH_SUPPORT
5987 * Expand arithmetic expression. Backup to start of expression,
5988 * evaluate, place result in (backed up) result, adjust string position.
6000 * This routine is slightly over-complicated for
6001 * efficiency. Next we scan backwards looking for the
6002 * start of arithmetic.
6004 start = stackblock();
6011 while ((unsigned char)*p != CTLARI) {
6015 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6020 esc = esclen(start, p);
6030 removerecordregions(begoff);
6034 if (flag & QUOTES_ESC)
6035 rmescapes(p + 1, 0);
6037 len = cvtnum(ash_arith(p + 1));
6039 if (!(flag & EXP_QUOTED))
6040 recordregion(begoff, begoff + len, 0);
6044 /* argstr needs it */
6045 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6048 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6049 * characters to allow for further processing. Otherwise treat
6050 * $@ like $* since no splitting will be performed.
6052 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6053 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6054 * for correct expansion of "B=$A" word.
6057 argstr(char *p, int flags, struct strlist *var_str_list)
6059 static const char spclchars[] ALIGN1 = {
6067 #if ENABLE_SH_MATH_SUPPORT
6072 const char *reject = spclchars;
6073 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6078 if (!(flags & EXP_VARTILDE)) {
6080 } else if (flags & EXP_VARTILDE2) {
6085 if (flags & EXP_TILDE) {
6088 flags &= ~EXP_TILDE;
6092 p = exptilde(p, q, flags);
6095 startloc = expdest - (char *)stackblock();
6099 length += strcspn(p + length, reject);
6103 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6105 /* c == '=' || c == ':' || c == CTLENDARI */
6111 expdest = stack_nputstr(p, length, expdest);
6112 newloc = expdest - (char *)stackblock();
6113 if (breakall && !inquotes && newloc > startloc) {
6114 recordregion(startloc, newloc, 0);
6125 if (flags & EXP_VARTILDE2) {
6129 flags |= EXP_VARTILDE2;
6134 * sort of a hack - expand tildes in variable
6135 * assignments (after the first '=' and after ':'s).
6144 case CTLENDVAR: /* ??? */
6147 inquotes ^= EXP_QUOTED;
6148 /* "$@" syntax adherence hack */
6149 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6150 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6154 if (flags & QUOTES_ESC) {
6165 * Quoted parameter expansion pattern: remove quote
6166 * unless inside inner quotes or we have a literal
6169 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6170 EXP_QPAT && *p != '\\')
6175 TRACE(("argstr: evalvar('%s')\n", p));
6176 p = evalvar(p, flags | inquotes, var_str_list);
6177 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6180 expbackq(argbackq->n, flags | inquotes);
6181 argbackq = argbackq->next;
6183 #if ENABLE_SH_MATH_SUPPORT
6186 expari(flags | inquotes);
6195 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6196 char *pattern, int quotes, int zero)
6205 const char *s = loc2;
6212 match = pmatch(pattern, s);
6217 if (quotes && (unsigned char)*loc == CTLESC)
6226 scanright(char *startp, char *rmesc, char *rmescend,
6227 char *pattern, int quotes, int match_at_start)
6229 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6230 int try2optimize = match_at_start;
6236 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6237 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6238 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6240 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6241 * and on each iteration they go back two/one char until they reach the beginning.
6242 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6244 /* TODO: document in what other circumstances we are called. */
6246 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6249 const char *s = loc2;
6250 if (match_at_start) {
6254 match = pmatch(pattern, s);
6255 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6259 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6261 /* Maybe we can optimize this:
6262 * if pattern ends with unescaped *, we can avoid checking
6263 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6264 * it wont match truncated "raw_value_of_" strings too.
6266 unsigned plen = strlen(pattern);
6267 /* Does it end with "*"? */
6268 if (plen != 0 && pattern[--plen] == '*') {
6269 /* "xxxx*" is not escaped */
6270 /* "xxx\*" is escaped */
6271 /* "xx\\*" is not escaped */
6272 /* "x\\\*" is escaped */
6274 while (plen != 0 && pattern[--plen] == '\\')
6277 break; /* ends with unescaped "*" */
6285 esc = esclen(startp, loc);
6296 static void varunset(const char *, const char *, const char *, int) NORETURN;
6298 varunset(const char *end, const char *var, const char *umsg, int varflags)
6304 msg = "parameter not set";
6306 if ((unsigned char)*end == CTLENDVAR) {
6307 if (varflags & VSNUL)
6313 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6317 subevalvar(char *p, char *varname, int strloc, int subtype,
6318 int startloc, int varflags, int flag, struct strlist *var_str_list)
6320 struct nodelist *saveargbackq = argbackq;
6321 int quotes = flag & QUOTES_ESC;
6324 char *rmesc, *rmescend;
6326 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6327 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6328 int saveherefd = herefd;
6329 int amount, resetloc;
6330 IF_ASH_BASH_COMPAT(int workloc;)
6332 char *(*scan)(char*, char*, char*, char*, int, int);
6334 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6335 // p, varname, strloc, subtype, startloc, varflags, quotes);
6338 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6339 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6341 STPUTC('\0', expdest);
6342 herefd = saveherefd;
6343 argbackq = saveargbackq;
6344 startp = (char *)stackblock() + startloc;
6348 setvar0(varname, startp);
6349 amount = startp - expdest;
6350 STADJUST(amount, expdest);
6354 varunset(p, varname, startp, varflags);
6357 #if ENABLE_ASH_BASH_COMPAT
6359 //TODO: support more general format ${v:EXPR:EXPR},
6360 // where EXPR follows $(()) rules
6361 loc = str = stackblock() + strloc;
6362 /* Read POS in ${var:POS:LEN} */
6363 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6364 len = str - startp - 1;
6366 /* *loc != '\0', guaranteed by parser */
6370 /* Adjust the length by the number of escapes */
6371 for (ptr = startp; ptr < (str - 1); ptr++) {
6372 if ((unsigned char)*ptr == CTLESC) {
6380 if (*loc++ == ':') {
6384 /* Skip POS in ${var:POS:LEN} */
6386 while (*loc && *loc != ':') {
6388 * bash complains on: var=qwe; echo ${var:1a:123}
6390 ash_msg_and_raise_error(msg_illnum, str);
6394 if (*loc++ == ':') {
6399 /* ${VAR:$((-n)):l} starts n chars from the end */
6400 pos = orig_len + pos;
6402 if ((unsigned)pos >= orig_len) {
6403 /* apart from obvious ${VAR:999999:l},
6404 * covers ${VAR:$((-9999999)):l} - result is ""
6410 if (len > (orig_len - pos))
6411 len = orig_len - pos;
6413 for (str = startp; pos; str++, pos--) {
6414 if (quotes && (unsigned char)*str == CTLESC)
6417 for (loc = startp; len; len--) {
6418 if (quotes && (unsigned char)*str == CTLESC)
6423 amount = loc - expdest;
6424 STADJUST(amount, expdest);
6429 resetloc = expdest - (char *)stackblock();
6431 /* We'll comeback here if we grow the stack while handling
6432 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6433 * stack will need rebasing, and we'll need to remove our work
6436 IF_ASH_BASH_COMPAT(restart:)
6438 amount = expdest - ((char *)stackblock() + resetloc);
6439 STADJUST(-amount, expdest);
6440 startp = (char *)stackblock() + startloc;
6443 rmescend = (char *)stackblock() + strloc;
6445 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6446 if (rmesc != startp) {
6448 startp = (char *)stackblock() + startloc;
6452 str = (char *)stackblock() + strloc;
6454 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6455 * The result is a_\_z_c (not a\_\_z_c)!
6457 * The search pattern and replace string treat backslashes differently!
6458 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6459 * and string. It's only used on the first call.
6461 preglob(str, IF_ASH_BASH_COMPAT(
6462 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6463 RMESCAPE_SLASH :) 0);
6465 #if ENABLE_ASH_BASH_COMPAT
6466 workloc = expdest - (char *)stackblock();
6467 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6471 repl = strchr(str, CTLESC);
6477 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6479 /* If there's no pattern to match, return the expansion unmolested */
6488 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6489 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6491 /* No match, advance */
6492 char *restart_detect = stackblock();
6494 STPUTC(*idx, expdest);
6495 if (quotes && (unsigned char)*idx == CTLESC) {
6498 STPUTC(*idx, expdest);
6500 if (stackblock() != restart_detect)
6505 /* continue; - prone to quadratic behavior, smarter code: */
6508 if (str[0] == '*') {
6509 /* Pattern is "*foo". If "*foo" does not match "long_string",
6510 * it would never match "ong_string" etc, no point in trying.
6517 if (subtype == VSREPLACEALL) {
6519 if (quotes && (unsigned char)*idx == CTLESC)
6528 //bb_error_msg("repl:'%s'", repl);
6529 for (loc = (char*)repl; *loc; loc++) {
6530 char *restart_detect = stackblock();
6531 if (quotes && *loc == '\\') {
6532 STPUTC(CTLESC, expdest);
6535 STPUTC(*loc, expdest);
6536 if (stackblock() != restart_detect)
6541 if (subtype == VSREPLACE) {
6542 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6544 char *restart_detect = stackblock();
6545 STPUTC(*idx, expdest);
6546 if (stackblock() != restart_detect)
6555 /* We've put the replaced text into a buffer at workloc, now
6556 * move it to the right place and adjust the stack.
6558 STPUTC('\0', expdest);
6559 startp = (char *)stackblock() + startloc;
6560 memmove(startp, (char *)stackblock() + workloc, len + 1);
6561 //bb_error_msg("startp:'%s'", startp);
6562 amount = expdest - (startp + len);
6563 STADJUST(-amount, expdest);
6566 #endif /* ENABLE_ASH_BASH_COMPAT */
6568 subtype -= VSTRIMRIGHT;
6570 if (subtype < 0 || subtype > 7)
6573 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6574 zero = subtype >> 1;
6575 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6576 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6578 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6581 memmove(startp, loc, str - loc);
6582 loc = startp + (str - loc) - 1;
6585 amount = loc - expdest;
6586 STADJUST(amount, expdest);
6592 * Add the value of a specialized variable to the stack string.
6593 * name parameter (examples):
6594 * ash -c 'echo $1' name:'1='
6595 * ash -c 'echo $qwe' name:'qwe='
6596 * ash -c 'echo $$' name:'$='
6597 * ash -c 'echo ${$}' name:'$='
6598 * ash -c 'echo ${$##q}' name:'$=q'
6599 * ash -c 'echo ${#$}' name:'$='
6600 * note: examples with bad shell syntax:
6601 * ash -c 'echo ${#$1}' name:'$=1'
6602 * ash -c 'echo ${#1#}' name:'1=#'
6604 static NOINLINE ssize_t
6605 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6612 int quoted = flags & EXP_QUOTED;
6613 int subtype = varflags & VSTYPE;
6614 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6615 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6616 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6618 sep = quoted ? ((flags & EXP_FULL) << CHAR_BIT) : 0;
6628 num = shellparam.nparam;
6636 goto check_1char_name;
6638 expdest = makestrspace(NOPTS, expdest);
6639 for (i = NOPTS - 1; i >= 0; i--) {
6641 USTPUTC(optletters(i), expdest);
6647 /* handles cases similar to ${#$1} */
6648 if (name[2] != '\0')
6649 raise_error_syntax("bad substitution");
6656 if (quoted && (flags & EXP_FULL)) {
6657 /* note: this is not meant as PEOF value */
6658 sep = 1 << CHAR_BIT;
6663 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6669 while ((p = *ap++) != NULL) {
6670 len += strtodest(p, syntax, quotes);
6674 memtodest(&sepc, 1, syntax, quotes);
6678 } /* case '@' and '*' */
6689 num = atoi(name); /* number(name) fails on ${N#str} etc */
6690 if (num < 0 || num > shellparam.nparam)
6692 p = num ? shellparam.p[num - 1] : arg0;
6695 /* NB: name has form "VAR=..." */
6697 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6698 * which should be considered before we check variables. */
6700 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6704 str = var_str_list->text;
6705 eq = strchr(str, '=');
6706 if (!eq) /* stop at first non-assignment */
6709 if (name_len == (unsigned)(eq - str)
6710 && strncmp(str, name, name_len) == 0
6713 /* goto value; - WRONG! */
6714 /* think "A=1 A=2 B=$A" */
6716 var_str_list = var_str_list->next;
6717 } while (var_str_list);
6721 p = lookupvar(name);
6726 len = strtodest(p, syntax, quotes);
6727 #if ENABLE_UNICODE_SUPPORT
6728 if (subtype == VSLENGTH && len > 0) {
6729 reinit_unicode_for_ash();
6730 if (unicode_status == UNICODE_ON) {
6731 STADJUST(-len, expdest);
6733 len = unicode_strlen(p);
6741 STADJUST(-len, expdest);
6746 * Expand a variable, and return a pointer to the next character in the
6750 evalvar(char *p, int flags, struct strlist *var_str_list)
6761 varflags = (unsigned char) *p++;
6762 subtype = varflags & VSTYPE;
6763 quoted = flags & EXP_QUOTED;
6765 easy = (!quoted || (*var == '@' && shellparam.nparam));
6766 startloc = expdest - (char *)stackblock();
6767 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6770 varlen = varvalue(var, varflags, flags, var_str_list);
6771 if (varflags & VSNUL)
6774 if (subtype == VSPLUS) {
6775 varlen = -1 - varlen;
6779 if (subtype == VSMINUS) {
6784 flags | EXP_TILDE | EXP_WORD,
6794 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6796 if (subevalvar(p, var, /* strloc: */ 0,
6797 subtype, startloc, varflags,
6798 /* quotes: */ flags & ~QUOTES_ESC,
6803 * Remove any recorded regions beyond
6806 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) {
6835 case VSTRIMRIGHTMAX:
6836 #if ENABLE_ASH_BASH_COMPAT
6849 * Terminate the string and start recording the pattern
6852 STPUTC('\0', expdest);
6853 patloc = expdest - (char *)stackblock();
6854 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6855 startloc, varflags, flags, var_str_list)) {
6856 int amount = expdest - (
6857 (char *)stackblock() + patloc - 1
6859 STADJUST(-amount, expdest);
6861 /* Remove any recorded regions beyond start of variable */
6862 removerecordregions(startloc);
6864 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6868 if (subtype != VSNORMAL) { /* skip to end of alternative */
6871 unsigned char c = *p++;
6874 else if (c == CTLBACKQ) {
6876 argbackq = argbackq->next;
6877 } else if (c == CTLVAR) {
6878 if ((*p++ & VSTYPE) != VSNORMAL)
6880 } else if (c == CTLENDVAR) {
6890 * Break the argument string into pieces based upon IFS and add the
6891 * strings to the argument list. The regions of the string to be
6892 * searched for IFS characters have been stored by recordregion.
6895 ifsbreakup(char *string, struct arglist *arglist)
6897 struct ifsregion *ifsp;
6902 const char *ifs, *realifs;
6907 if (ifslastp != NULL) {
6910 realifs = ifsset() ? ifsval() : defifs;
6913 p = string + ifsp->begoff;
6914 nulonly = ifsp->nulonly;
6915 ifs = nulonly ? nullstr : realifs;
6917 while (p < string + ifsp->endoff) {
6919 if ((unsigned char)*p == CTLESC)
6921 if (!strchr(ifs, *p)) {
6926 ifsspc = (strchr(defifs, *p) != NULL);
6927 /* Ignore IFS whitespace at start */
6928 if (q == start && ifsspc) {
6934 sp = stzalloc(sizeof(*sp));
6936 *arglist->lastp = sp;
6937 arglist->lastp = &sp->next;
6941 if (p >= string + ifsp->endoff) {
6945 if ((unsigned char)*p == CTLESC)
6947 if (strchr(ifs, *p) == NULL) {
6951 if (strchr(defifs, *p) == NULL) {
6966 } while (ifsp != NULL);
6975 sp = stzalloc(sizeof(*sp));
6977 *arglist->lastp = sp;
6978 arglist->lastp = &sp->next;
6984 struct ifsregion *p;
6989 struct ifsregion *ifsp;
6995 ifsfirst.next = NULL;
7000 * Add a file name to the list.
7003 addfname(const char *name)
7007 sp = stzalloc(sizeof(*sp));
7008 sp->text = sstrdup(name);
7010 exparg.lastp = &sp->next;
7013 /* If we want to use glob() from libc... */
7016 /* Add the result of glob() to the list */
7018 addglob(const glob_t *pglob)
7020 char **p = pglob->gl_pathv;
7027 expandmeta(struct strlist *str /*, int flag*/)
7029 /* TODO - EXP_REDIR */
7039 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7041 * GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7042 * TODO?: GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7044 i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7049 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7050 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7061 *exparg.lastp = str;
7062 rmescapes(str->text, 0);
7063 exparg.lastp = &str->next;
7065 default: /* GLOB_NOSPACE */
7068 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7075 /* Homegrown globbing code. (dash also has both, uses homegrown one.) */
7078 * Do metacharacter (i.e. *, ?, [...]) expansion.
7081 expmeta(char *expdir, char *enddir, char *name)
7097 for (p = name; esc = 0, *p; p += esc + 1) {
7098 if (*p == '*' || *p == '?')
7100 else if (*p == '[') {
7107 if (*q == '/' || *q == '\0')
7117 if (p[esc] == '/') {
7120 start = p + esc + 1;
7124 if (metaflag == 0) { /* we've reached the end of the file name */
7125 if (enddir != expdir)
7133 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7144 } while (p < start);
7146 if (enddir == expdir) {
7148 } else if (enddir == expdir + 1 && *expdir == '/') {
7157 if (enddir != expdir)
7159 if (*endname == 0) {
7172 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7173 if (dp->d_name[0] == '.' && !matchdot)
7175 if (pmatch(start, dp->d_name)) {
7177 strcpy(enddir, dp->d_name);
7180 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7183 expmeta(expdir, p, endname);
7189 endname[-esc - 1] = esc ? '\\' : '/';
7192 static struct strlist *
7193 msort(struct strlist *list, int len)
7195 struct strlist *p, *q = NULL;
7196 struct strlist **lpp;
7204 for (n = half; --n >= 0;) {
7208 q->next = NULL; /* terminate first half of list */
7209 q = msort(list, half); /* sort first half of list */
7210 p = msort(p, len - half); /* sort second half */
7213 #if ENABLE_LOCALE_SUPPORT
7214 if (strcoll(p->text, q->text) < 0)
7216 if (strcmp(p->text, q->text) < 0)
7240 * Sort the results of file name expansion. It calculates the number of
7241 * strings to sort and then calls msort (short for merge sort) to do the
7244 static struct strlist *
7245 expsort(struct strlist *str)
7251 for (sp = str; sp; sp = sp->next)
7253 return msort(str, len);
7257 expandmeta(struct strlist *str /*, int flag*/)
7259 static const char metachars[] ALIGN1 = {
7262 /* TODO - EXP_REDIR */
7266 struct strlist **savelastp;
7272 if (!strpbrk(str->text, metachars))
7274 savelastp = exparg.lastp;
7277 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7279 int i = strlen(str->text);
7280 //BUGGY estimation of how long expanded name can be
7281 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7283 expmeta(expdir, expdir, p);
7288 if (exparg.lastp == savelastp) {
7293 *exparg.lastp = str;
7294 rmescapes(str->text, 0);
7295 exparg.lastp = &str->next;
7297 *exparg.lastp = NULL;
7298 *savelastp = sp = expsort(*savelastp);
7299 while (sp->next != NULL)
7301 exparg.lastp = &sp->next;
7306 #endif /* our globbing code */
7309 * Perform variable substitution and command substitution on an argument,
7310 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7311 * perform splitting and file name expansion. When arglist is NULL, perform
7312 * here document expansion.
7315 expandarg(union node *arg, struct arglist *arglist, int flag)
7320 argbackq = arg->narg.backquote;
7321 STARTSTACKSTR(expdest);
7322 ifsfirst.next = NULL;
7324 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7325 argstr(arg->narg.text, flag,
7326 /* var_str_list: */ arglist ? arglist->list : NULL);
7327 p = _STPUTC('\0', expdest);
7329 if (arglist == NULL) {
7330 return; /* here document expanded */
7332 p = grabstackstr(p);
7333 TRACE(("expandarg: p:'%s'\n", p));
7334 exparg.lastp = &exparg.list;
7338 if (flag & EXP_FULL) {
7339 ifsbreakup(p, &exparg);
7340 *exparg.lastp = NULL;
7341 exparg.lastp = &exparg.list;
7342 expandmeta(exparg.list /*, flag*/);
7344 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7346 TRACE(("expandarg: rmescapes:'%s'\n", p));
7348 sp = stzalloc(sizeof(*sp));
7351 exparg.lastp = &sp->next;
7355 *exparg.lastp = NULL;
7357 *arglist->lastp = exparg.list;
7358 arglist->lastp = exparg.lastp;
7363 * Expand shell variables and backquotes inside a here document.
7366 expandhere(union node *arg, int fd)
7369 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7370 full_write(fd, stackblock(), expdest - (char *)stackblock());
7374 * Returns true if the pattern matches the string.
7377 patmatch(char *pattern, const char *string)
7379 return pmatch(preglob(pattern, 0), string);
7383 * See if a pattern matches in a case statement.
7386 casematch(union node *pattern, char *val)
7388 struct stackmark smark;
7391 setstackmark(&smark);
7392 argbackq = pattern->narg.backquote;
7393 STARTSTACKSTR(expdest);
7395 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7396 /* var_str_list: */ NULL);
7397 STACKSTRNUL(expdest);
7398 result = patmatch(stackblock(), val);
7399 popstackmark(&smark);
7404 /* ============ find_command */
7408 int (*builtin)(int, char **) FAST_FUNC;
7409 /* unsigned flags; */
7411 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7412 /* "regular" builtins always take precedence over commands,
7413 * regardless of PATH=....%builtin... position */
7414 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7415 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7418 smallint cmdtype; /* CMDxxx */
7421 /* index >= 0 for commands without path (slashes) */
7422 /* (TODO: what exactly does the value mean? PATH position?) */
7423 /* index == -1 for commands with slashes */
7424 /* index == (-2 - applet_no) for NOFORK applets */
7425 const struct builtincmd *cmd;
7426 struct funcnode *func;
7429 /* values of cmdtype */
7430 #define CMDUNKNOWN -1 /* no entry in table for command */
7431 #define CMDNORMAL 0 /* command is an executable program */
7432 #define CMDFUNCTION 1 /* command is a shell function */
7433 #define CMDBUILTIN 2 /* command is a shell builtin */
7435 /* action to find_command() */
7436 #define DO_ERR 0x01 /* prints errors */
7437 #define DO_ABS 0x02 /* checks absolute paths */
7438 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7439 #define DO_ALTPATH 0x08 /* using alternate path */
7440 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7442 static void find_command(char *, struct cmdentry *, int, const char *);
7445 /* ============ Hashing commands */
7448 * When commands are first encountered, they are entered in a hash table.
7449 * This ensures that a full path search will not have to be done for them
7450 * on each invocation.
7452 * We should investigate converting to a linear search, even though that
7453 * would make the command name "hash" a misnomer.
7457 struct tblentry *next; /* next entry in hash chain */
7458 union param param; /* definition of builtin function */
7459 smallint cmdtype; /* CMDxxx */
7460 char rehash; /* if set, cd done since entry created */
7461 char cmdname[1]; /* name of command */
7464 static struct tblentry **cmdtable;
7465 #define INIT_G_cmdtable() do { \
7466 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7469 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7473 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7475 #if ENABLE_FEATURE_SH_STANDALONE
7476 if (applet_no >= 0) {
7477 if (APPLET_IS_NOEXEC(applet_no)) {
7481 run_applet_no_and_exit(applet_no, argv);
7483 /* re-exec ourselves with the new arguments */
7484 execve(bb_busybox_exec_path, argv, envp);
7485 /* If they called chroot or otherwise made the binary no longer
7486 * executable, fall through */
7493 execve(cmd, argv, envp);
7494 } while (errno == EINTR);
7496 execve(cmd, argv, envp);
7498 if (cmd == (char*) bb_busybox_exec_path) {
7499 /* We already visited ENOEXEC branch below, don't do it again */
7500 //TODO: try execve(initial_argv0_of_shell, argv, envp) before giving up?
7504 if (errno == ENOEXEC) {
7505 /* Run "cmd" as a shell script:
7506 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7507 * "If the execve() function fails with ENOEXEC, the shell
7508 * shall execute a command equivalent to having a shell invoked
7509 * with the command name as its first operand,
7510 * with any remaining arguments passed to the new shell"
7512 * That is, do not use $SHELL, user's shell, or /bin/sh;
7513 * just call ourselves.
7515 * Note that bash reads ~80 chars of the file, and if it sees
7516 * a zero byte before it sees newline, it doesn't try to
7517 * interpret it, but fails with "cannot execute binary file"
7518 * message and exit code 126. For one, this prevents attempts
7519 * to interpret foreign ELF binaries as shell scripts.
7524 for (ap = argv; *ap; ap++)
7526 new = ckmalloc((ap - argv + 2) * sizeof(new[0]));
7527 new[0] = (char*) "ash";
7530 while ((*ap++ = *++argv) != NULL)
7532 cmd = (char*) bb_busybox_exec_path;
7539 * Exec a program. Never returns. If you change this routine, you may
7540 * have to change the find_command routine as well.
7542 static void shellexec(char **, const char *, int) NORETURN;
7544 shellexec(char **argv, const char *path, int idx)
7550 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7552 clearredir(/*drop:*/ 1);
7553 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7554 if (strchr(argv[0], '/') != NULL
7555 #if ENABLE_FEATURE_SH_STANDALONE
7556 || (applet_no = find_applet_by_name(argv[0])) >= 0
7559 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7560 if (applet_no >= 0) {
7561 /* We tried execing ourself, but it didn't work.
7562 * Maybe /proc/self/exe doesn't exist?
7571 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7572 if (--idx < 0 && pathopt == NULL) {
7573 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7574 if (errno != ENOENT && errno != ENOTDIR)
7581 /* Map to POSIX errors */
7593 exitstatus = exerrno;
7594 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7595 argv[0], e, suppress_int));
7596 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7601 printentry(struct tblentry *cmdp)
7607 idx = cmdp->param.index;
7610 name = path_advance(&path, cmdp->cmdname);
7612 } while (--idx >= 0);
7613 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7617 * Clear out command entries. The argument specifies the first entry in
7618 * PATH which has changed.
7621 clearcmdentry(int firstchange)
7623 struct tblentry **tblp;
7624 struct tblentry **pp;
7625 struct tblentry *cmdp;
7628 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7630 while ((cmdp = *pp) != NULL) {
7631 if ((cmdp->cmdtype == CMDNORMAL &&
7632 cmdp->param.index >= firstchange)
7633 || (cmdp->cmdtype == CMDBUILTIN &&
7634 builtinloc >= firstchange)
7647 * Locate a command in the command hash table. If "add" is nonzero,
7648 * add the command to the table if it is not already present. The
7649 * variable "lastcmdentry" is set to point to the address of the link
7650 * pointing to the entry, so that delete_cmd_entry can delete the
7653 * Interrupts must be off if called with add != 0.
7655 static struct tblentry **lastcmdentry;
7657 static struct tblentry *
7658 cmdlookup(const char *name, int add)
7660 unsigned int hashval;
7662 struct tblentry *cmdp;
7663 struct tblentry **pp;
7666 hashval = (unsigned char)*p << 4;
7668 hashval += (unsigned char)*p++;
7670 pp = &cmdtable[hashval % CMDTABLESIZE];
7671 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7672 if (strcmp(cmdp->cmdname, name) == 0)
7676 if (add && cmdp == NULL) {
7677 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7679 /* + 1 - already done because
7680 * tblentry::cmdname is char[1] */);
7681 /*cmdp->next = NULL; - ckzalloc did it */
7682 cmdp->cmdtype = CMDUNKNOWN;
7683 strcpy(cmdp->cmdname, name);
7690 * Delete the command entry returned on the last lookup.
7693 delete_cmd_entry(void)
7695 struct tblentry *cmdp;
7698 cmdp = *lastcmdentry;
7699 *lastcmdentry = cmdp->next;
7700 if (cmdp->cmdtype == CMDFUNCTION)
7701 freefunc(cmdp->param.func);
7707 * Add a new command entry, replacing any existing command entry for
7708 * the same name - except special builtins.
7711 addcmdentry(char *name, struct cmdentry *entry)
7713 struct tblentry *cmdp;
7715 cmdp = cmdlookup(name, 1);
7716 if (cmdp->cmdtype == CMDFUNCTION) {
7717 freefunc(cmdp->param.func);
7719 cmdp->cmdtype = entry->cmdtype;
7720 cmdp->param = entry->u;
7724 static int FAST_FUNC
7725 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7727 struct tblentry **pp;
7728 struct tblentry *cmdp;
7730 struct cmdentry entry;
7733 if (nextopt("r") != '\0') {
7738 if (*argptr == NULL) {
7739 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7740 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7741 if (cmdp->cmdtype == CMDNORMAL)
7749 while ((name = *argptr) != NULL) {
7750 cmdp = cmdlookup(name, 0);
7752 && (cmdp->cmdtype == CMDNORMAL
7753 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7757 find_command(name, &entry, DO_ERR, pathval());
7758 if (entry.cmdtype == CMDUNKNOWN)
7766 * Called when a cd is done. Marks all commands so the next time they
7767 * are executed they will be rehashed.
7772 struct tblentry **pp;
7773 struct tblentry *cmdp;
7775 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7776 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7777 if (cmdp->cmdtype == CMDNORMAL
7778 || (cmdp->cmdtype == CMDBUILTIN
7779 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7789 * Fix command hash table when PATH changed.
7790 * Called before PATH is changed. The argument is the new value of PATH;
7791 * pathval() still returns the old value at this point.
7792 * Called with interrupts off.
7794 static void FAST_FUNC
7795 changepath(const char *new)
7803 firstchange = 9999; /* assume no change */
7809 if ((*old == '\0' && *new == ':')
7810 || (*old == ':' && *new == '\0')
7814 old = new; /* ignore subsequent differences */
7818 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7825 if (builtinloc < 0 && idx_bltin >= 0)
7826 builtinloc = idx_bltin; /* zap builtins */
7827 if (builtinloc >= 0 && idx_bltin < 0)
7829 clearcmdentry(firstchange);
7830 builtinloc = idx_bltin;
7855 #if ENABLE_ASH_BASH_COMPAT
7866 typedef smallint token_id_t;
7868 /* first char is indicating which tokens mark the end of a list */
7869 static const char *const tokname_array[] = {
7883 #define KWDOFFSET 13
7884 /* the following are keywords */
7894 #if ENABLE_ASH_BASH_COMPAT
7906 /* Wrapper around strcmp for qsort/bsearch/... */
7908 pstrcmp(const void *a, const void *b)
7910 return strcmp((char*) a, (*(char**) b) + 1);
7913 static const char *const *
7914 findkwd(const char *s)
7916 return bsearch(s, tokname_array + KWDOFFSET,
7917 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7918 sizeof(tokname_array[0]), pstrcmp);
7922 * Locate and print what a word is...
7925 describe_command(char *command, const char *path, int describe_command_verbose)
7927 struct cmdentry entry;
7928 struct tblentry *cmdp;
7929 #if ENABLE_ASH_ALIAS
7930 const struct alias *ap;
7933 path = path ? path : pathval();
7935 if (describe_command_verbose) {
7939 /* First look at the keywords */
7940 if (findkwd(command)) {
7941 out1str(describe_command_verbose ? " is a shell keyword" : command);
7945 #if ENABLE_ASH_ALIAS
7946 /* Then look at the aliases */
7947 ap = lookupalias(command, 0);
7949 if (!describe_command_verbose) {
7954 out1fmt(" is an alias for %s", ap->val);
7958 /* Then check if it is a tracked alias */
7959 cmdp = cmdlookup(command, 0);
7961 entry.cmdtype = cmdp->cmdtype;
7962 entry.u = cmdp->param;
7964 /* Finally use brute force */
7965 find_command(command, &entry, DO_ABS, path);
7968 switch (entry.cmdtype) {
7970 int j = entry.u.index;
7976 p = path_advance(&path, command);
7980 if (describe_command_verbose) {
7982 (cmdp ? " a tracked alias for" : nullstr), p
7991 if (describe_command_verbose) {
7992 out1str(" is a shell function");
7999 if (describe_command_verbose) {
8000 out1fmt(" is a %sshell builtin",
8001 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8002 "special " : nullstr
8010 if (describe_command_verbose) {
8011 out1str(": not found\n");
8020 static int FAST_FUNC
8021 typecmd(int argc UNUSED_PARAM, char **argv)
8027 /* type -p ... ? (we don't bother checking for 'p') */
8028 if (argv[1] && argv[1][0] == '-') {
8033 err |= describe_command(argv[i++], NULL, verbose);
8038 #if ENABLE_ASH_CMDCMD
8039 static int FAST_FUNC
8040 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8047 const char *path = NULL;
8049 while ((c = nextopt("pvV")) != '\0')
8051 verify |= VERIFY_VERBOSE;
8053 verify |= VERIFY_BRIEF;
8059 path = bb_default_path;
8060 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8061 if (verify && (*argptr != NULL)) {
8062 return describe_command(*argptr, path, verify - VERIFY_BRIEF);
8070 /* ============ eval.c */
8072 static int funcblocksize; /* size of structures in function */
8073 static int funcstringsize; /* size of strings in node */
8074 static void *funcblock; /* block to allocate function from */
8075 static char *funcstring; /* block to allocate strings from */
8077 /* flags in argument to evaltree */
8078 #define EV_EXIT 01 /* exit after evaluating tree */
8079 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8081 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8082 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8083 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8084 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8085 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8086 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8087 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8088 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8089 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8090 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8091 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8092 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8093 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8094 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8095 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8096 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8097 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8098 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8099 #if ENABLE_ASH_BASH_COMPAT
8100 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8102 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8103 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8104 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8105 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8106 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8107 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8108 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8109 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8110 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8113 static void calcsize(union node *n);
8116 sizenodelist(struct nodelist *lp)
8119 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8126 calcsize(union node *n)
8130 funcblocksize += nodesize[n->type];
8133 calcsize(n->ncmd.redirect);
8134 calcsize(n->ncmd.args);
8135 calcsize(n->ncmd.assign);
8138 sizenodelist(n->npipe.cmdlist);
8143 calcsize(n->nredir.redirect);
8144 calcsize(n->nredir.n);
8151 calcsize(n->nbinary.ch2);
8152 calcsize(n->nbinary.ch1);
8155 calcsize(n->nif.elsepart);
8156 calcsize(n->nif.ifpart);
8157 calcsize(n->nif.test);
8160 funcstringsize += strlen(n->nfor.var) + 1;
8161 calcsize(n->nfor.body);
8162 calcsize(n->nfor.args);
8165 calcsize(n->ncase.cases);
8166 calcsize(n->ncase.expr);
8169 calcsize(n->nclist.body);
8170 calcsize(n->nclist.pattern);
8171 calcsize(n->nclist.next);
8175 sizenodelist(n->narg.backquote);
8176 funcstringsize += strlen(n->narg.text) + 1;
8177 calcsize(n->narg.next);
8180 #if ENABLE_ASH_BASH_COMPAT
8187 calcsize(n->nfile.fname);
8188 calcsize(n->nfile.next);
8192 calcsize(n->ndup.vname);
8193 calcsize(n->ndup.next);
8197 calcsize(n->nhere.doc);
8198 calcsize(n->nhere.next);
8201 calcsize(n->nnot.com);
8207 nodeckstrdup(char *s)
8209 char *rtn = funcstring;
8211 strcpy(funcstring, s);
8212 funcstring += strlen(s) + 1;
8216 static union node *copynode(union node *);
8218 static struct nodelist *
8219 copynodelist(struct nodelist *lp)
8221 struct nodelist *start;
8222 struct nodelist **lpp;
8227 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8228 (*lpp)->n = copynode(lp->n);
8230 lpp = &(*lpp)->next;
8237 copynode(union node *n)
8244 funcblock = (char *) funcblock + nodesize[n->type];
8248 new->ncmd.redirect = copynode(n->ncmd.redirect);
8249 new->ncmd.args = copynode(n->ncmd.args);
8250 new->ncmd.assign = copynode(n->ncmd.assign);
8253 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8254 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8259 new->nredir.redirect = copynode(n->nredir.redirect);
8260 new->nredir.n = copynode(n->nredir.n);
8267 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8268 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8271 new->nif.elsepart = copynode(n->nif.elsepart);
8272 new->nif.ifpart = copynode(n->nif.ifpart);
8273 new->nif.test = copynode(n->nif.test);
8276 new->nfor.var = nodeckstrdup(n->nfor.var);
8277 new->nfor.body = copynode(n->nfor.body);
8278 new->nfor.args = copynode(n->nfor.args);
8281 new->ncase.cases = copynode(n->ncase.cases);
8282 new->ncase.expr = copynode(n->ncase.expr);
8285 new->nclist.body = copynode(n->nclist.body);
8286 new->nclist.pattern = copynode(n->nclist.pattern);
8287 new->nclist.next = copynode(n->nclist.next);
8291 new->narg.backquote = copynodelist(n->narg.backquote);
8292 new->narg.text = nodeckstrdup(n->narg.text);
8293 new->narg.next = copynode(n->narg.next);
8296 #if ENABLE_ASH_BASH_COMPAT
8303 new->nfile.fname = copynode(n->nfile.fname);
8304 new->nfile.fd = n->nfile.fd;
8305 new->nfile.next = copynode(n->nfile.next);
8309 new->ndup.vname = copynode(n->ndup.vname);
8310 new->ndup.dupfd = n->ndup.dupfd;
8311 new->ndup.fd = n->ndup.fd;
8312 new->ndup.next = copynode(n->ndup.next);
8316 new->nhere.doc = copynode(n->nhere.doc);
8317 new->nhere.fd = n->nhere.fd;
8318 new->nhere.next = copynode(n->nhere.next);
8321 new->nnot.com = copynode(n->nnot.com);
8324 new->type = n->type;
8329 * Make a copy of a parse tree.
8331 static struct funcnode *
8332 copyfunc(union node *n)
8337 funcblocksize = offsetof(struct funcnode, n);
8340 blocksize = funcblocksize;
8341 f = ckmalloc(blocksize + funcstringsize);
8342 funcblock = (char *) f + offsetof(struct funcnode, n);
8343 funcstring = (char *) f + blocksize;
8350 * Define a shell function.
8353 defun(char *name, union node *func)
8355 struct cmdentry entry;
8358 entry.cmdtype = CMDFUNCTION;
8359 entry.u.func = copyfunc(func);
8360 addcmdentry(name, &entry);
8364 /* Reasons for skipping commands (see comment on breakcmd routine) */
8365 #define SKIPBREAK (1 << 0)
8366 #define SKIPCONT (1 << 1)
8367 #define SKIPFUNC (1 << 2)
8368 #define SKIPFILE (1 << 3)
8369 #define SKIPEVAL (1 << 4)
8370 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8371 static int skipcount; /* number of levels to skip */
8372 static int funcnest; /* depth of function calls */
8373 static int loopnest; /* current loop nesting level */
8375 /* Forward decl way out to parsing code - dotrap needs it */
8376 static int evalstring(char *s, int mask);
8378 /* Called to execute a trap.
8379 * Single callsite - at the end of evaltree().
8380 * If we return non-zero, evaltree raises EXEXIT exception.
8382 * Perhaps we should avoid entering new trap handlers
8383 * while we are executing a trap handler. [is it a TODO?]
8392 savestatus = exitstatus;
8396 TRACE(("dotrap entered\n"));
8397 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8403 /* non-trapped SIGINT is handled separately by raise_interrupt,
8404 * don't upset it by resetting gotsig[SIGINT-1] */
8405 if (sig == SIGINT && !t)
8408 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8412 evalstring(t, SKIPEVAL);
8413 exitstatus = savestatus;
8415 TRACE(("dotrap returns %d\n", evalskip));
8420 TRACE(("dotrap returns 0\n"));
8424 /* forward declarations - evaluation is fairly recursive business... */
8425 static int evalloop(union node *, int);
8426 static int evalfor(union node *, int);
8427 static int evalcase(union node *, int);
8428 static int evalsubshell(union node *, int);
8429 static void expredir(union node *);
8430 static int evalpipe(union node *, int);
8431 static int evalcommand(union node *, int);
8432 static int evalbltin(const struct builtincmd *, int, char **);
8433 static void prehash(union node *);
8436 * Evaluate a parse tree. The value is left in the global variable
8440 evaltree(union node *n, int flags)
8442 struct jmploc *volatile savehandler = exception_handler;
8443 struct jmploc jmploc;
8445 int (*evalfn)(union node *, int);
8449 SAVE_INT(int_level);
8452 TRACE(("evaltree(NULL) called\n"));
8455 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8457 exception_handler = &jmploc;
8459 int err = setjmp(jmploc.loc);
8461 /* if it was a signal, check for trap handlers */
8462 if (exception_type == EXSIG) {
8463 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8464 exception_type, err));
8467 /* continue on the way out */
8468 TRACE(("exception %d in evaltree, propagating err=%d\n",
8469 exception_type, err));
8470 exception_handler = savehandler;
8471 longjmp(exception_handler->loc, err);
8478 out1fmt("Node type = %d\n", n->type);
8483 status = !evaltree(n->nnot.com, EV_TESTED);
8486 expredir(n->nredir.redirect);
8487 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8489 status = evaltree(n->nredir.n, flags & EV_TESTED);
8491 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8494 evalfn = evalcommand;
8496 if (eflag && !(flags & EV_TESTED))
8507 evalfn = evalsubshell;
8510 evalfn = evalsubshell;
8523 #error NAND + 1 != NOR
8525 #if NOR + 1 != NSEMI
8526 #error NOR + 1 != NSEMI
8528 unsigned is_or = n->type - NAND;
8531 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8533 if (!status == is_or || evalskip)
8539 status = evalfn(n, flags);
8543 status = evaltree(n->nif.test, EV_TESTED);
8550 if (n->nif.elsepart) {
8551 n = n->nif.elsepart;
8557 defun(n->narg.text, n->narg.next);
8558 /* Not necessary. To test it:
8559 * "false; f() { qwerty; }; echo $?" should print 0.
8563 exitstatus = status;
8568 exception_handler = savehandler;
8571 /* Order of checks below is important:
8572 * signal handlers trigger before exit caused by "set -e".
8574 if (pending_sig && dotrap())
8576 if (checkexit & status)
8577 evalskip |= SKIPEVAL;
8579 if (flags & EV_EXIT) {
8581 raise_exception(EXEXIT);
8584 RESTORE_INT(int_level);
8585 TRACE(("leaving evaltree (no interrupts)\n"));
8590 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8593 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8596 evalloop(union node *n, int flags)
8606 i = evaltree(n->nbinary.ch1, EV_TESTED);
8609 if (evalskip == SKIPCONT && --skipcount <= 0) {
8613 if (evalskip == SKIPBREAK && --skipcount <= 0)
8617 if (n->type != NWHILE)
8621 status = evaltree(n->nbinary.ch2, flags);
8625 exitstatus = status;
8632 evalfor(union node *n, int flags)
8634 struct arglist arglist;
8637 struct stackmark smark;
8640 setstackmark(&smark);
8641 arglist.list = NULL;
8642 arglist.lastp = &arglist.list;
8643 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8644 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8649 *arglist.lastp = NULL;
8653 for (sp = arglist.list; sp; sp = sp->next) {
8654 setvar0(n->nfor.var, sp->text);
8655 status = evaltree(n->nfor.body, flags);
8657 if (evalskip == SKIPCONT && --skipcount <= 0) {
8661 if (evalskip == SKIPBREAK && --skipcount <= 0)
8668 popstackmark(&smark);
8674 evalcase(union node *n, int flags)
8678 struct arglist arglist;
8679 struct stackmark smark;
8682 setstackmark(&smark);
8683 arglist.list = NULL;
8684 arglist.lastp = &arglist.list;
8685 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8686 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8687 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8688 if (casematch(patp, arglist.list->text)) {
8689 /* Ensure body is non-empty as otherwise
8690 * EV_EXIT may prevent us from setting the
8693 if (evalskip == 0 && cp->nclist.body) {
8694 status = evaltree(cp->nclist.body, flags);
8701 popstackmark(&smark);
8707 * Kick off a subshell to evaluate a tree.
8710 evalsubshell(union node *n, int flags)
8713 int backgnd = (n->type == NBACKGND);
8716 expredir(n->nredir.redirect);
8717 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8720 jp = makejob(/*n,*/ 1);
8721 if (forkshell(jp, n, backgnd) == 0) {
8726 flags &= ~EV_TESTED;
8728 redirect(n->nredir.redirect, 0);
8729 evaltreenr(n->nredir.n, flags);
8734 status = waitforjob(jp);
8740 * Compute the names of the files in a redirection list.
8742 static void fixredir(union node *, const char *, int);
8744 expredir(union node *n)
8748 for (redir = n; redir; redir = redir->nfile.next) {
8752 fn.lastp = &fn.list;
8753 switch (redir->type) {
8757 #if ENABLE_ASH_BASH_COMPAT
8762 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8763 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8764 #if ENABLE_ASH_BASH_COMPAT
8768 // By the design of stack allocator, the loop of this kind:
8769 // while true; do while true; do break; done </dev/null; done
8770 // will look like a memory leak: ash plans to free expfname's
8771 // of "/dev/null" as soon as it finishes running the loop
8772 // (in this case, never).
8773 // This "fix" is wrong:
8774 if (redir->nfile.expfname)
8775 stunalloc(redir->nfile.expfname);
8776 // It results in corrupted state of stacked allocations.
8778 redir->nfile.expfname = fn.list->text;
8781 case NTOFD: /* >& */
8782 if (redir->ndup.vname) {
8783 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8784 if (fn.list == NULL)
8785 ash_msg_and_raise_error("redir error");
8786 #if ENABLE_ASH_BASH_COMPAT
8787 //FIXME: we used expandarg with different args!
8788 if (!isdigit_str9(fn.list->text)) {
8789 /* >&file, not >&fd */
8790 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8791 ash_msg_and_raise_error("redir error");
8793 goto store_expfname;
8796 fixredir(redir, fn.list->text, 1);
8804 * Evaluate a pipeline. All the processes in the pipeline are children
8805 * of the process creating the pipeline. (This differs from some versions
8806 * of the shell, which make the last process in a pipeline the parent
8810 evalpipe(union node *n, int flags)
8813 struct nodelist *lp;
8819 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8821 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8825 jp = makejob(/*n,*/ pipelen);
8827 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8831 if (pipe(pip) < 0) {
8833 ash_msg_and_raise_error("pipe call failed");
8836 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8849 evaltreenr(lp->n, flags);
8855 /* Don't want to trigger debugging */
8859 if (n->npipe.pipe_backgnd == 0) {
8860 status = waitforjob(jp);
8861 TRACE(("evalpipe: job done exit status %d\n", status));
8869 * Controls whether the shell is interactive or not.
8872 setinteractive(int on)
8874 static smallint is_interactive;
8876 if (++on == is_interactive)
8878 is_interactive = on;
8882 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8883 if (is_interactive > 1) {
8884 /* Looks like they want an interactive shell */
8885 static smallint did_banner;
8888 /* note: ash and hush share this string */
8889 out1fmt("\n\n%s %s\n"
8890 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
8893 "built-in shell (ash)"
8907 setinteractive(iflag);
8909 #if ENABLE_FEATURE_EDITING_VI
8911 line_input_state->flags |= VI_MODE;
8913 line_input_state->flags &= ~VI_MODE;
8915 viflag = 0; /* forcibly keep the option off */
8919 static struct localvar *localvars;
8922 * Called after a function returns.
8923 * Interrupts must be off.
8928 struct localvar *lvp;
8931 while ((lvp = localvars) != NULL) {
8932 localvars = lvp->next;
8934 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
8935 if (vp == NULL) { /* $- saved */
8936 memcpy(optlist, lvp->text, sizeof(optlist));
8937 free((char*)lvp->text);
8939 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8940 unsetvar(vp->var_text);
8943 vp->var_func(var_end(lvp->text));
8944 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8945 free((char*)vp->var_text);
8946 vp->flags = lvp->flags;
8947 vp->var_text = lvp->text;
8954 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8956 volatile struct shparam saveparam;
8957 struct localvar *volatile savelocalvars;
8958 struct jmploc *volatile savehandler;
8959 struct jmploc jmploc;
8962 saveparam = shellparam;
8963 savelocalvars = localvars;
8964 e = setjmp(jmploc.loc);
8969 savehandler = exception_handler;
8970 exception_handler = &jmploc;
8972 shellparam.malloced = 0;
8976 shellparam.nparam = argc - 1;
8977 shellparam.p = argv + 1;
8978 #if ENABLE_ASH_GETOPTS
8979 shellparam.optind = 1;
8980 shellparam.optoff = -1;
8982 evaltree(&func->n, flags & EV_TESTED);
8988 localvars = savelocalvars;
8989 freeparam(&shellparam);
8990 shellparam = saveparam;
8991 exception_handler = savehandler;
8993 evalskip &= ~SKIPFUNC;
8997 #if ENABLE_ASH_CMDCMD
8999 parse_command_args(char **argv, const char **path)
9012 if (c == '-' && !*cp) {
9020 *path = bb_default_path;
9023 /* run 'typecmd' for other options */
9034 * Make a variable a local variable. When a variable is made local, it's
9035 * value and flags are saved in a localvar structure. The saved values
9036 * will be restored when the shell function returns. We handle the name
9037 * "-" as a special case: it makes changes to "set +-options" local
9038 * (options will be restored on return from the function).
9043 struct localvar *lvp;
9046 char *eq = strchr(name, '=');
9049 /* Cater for duplicate "local". Examples:
9050 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9051 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9055 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9059 * it's a duplicate "local VAR" declaration, do nothing
9066 lvp = ckzalloc(sizeof(*lvp));
9067 if (LONE_DASH(name)) {
9069 p = ckmalloc(sizeof(optlist));
9070 lvp->text = memcpy(p, optlist, sizeof(optlist));
9073 vpp = hashvar(name);
9074 vp = *findvar(vpp, name);
9076 /* variable did not exist yet */
9078 setvareq(name, VSTRFIXED);
9080 setvar(name, NULL, VSTRFIXED);
9081 vp = *vpp; /* the new variable */
9082 lvp->flags = VUNSET;
9084 lvp->text = vp->var_text;
9085 lvp->flags = vp->flags;
9086 /* make sure neither "struct var" nor string gets freed
9087 * during (un)setting:
9089 vp->flags |= VSTRFIXED|VTEXTFIXED;
9093 /* "local VAR" unsets VAR: */
9094 setvar0(name, NULL);
9098 lvp->next = localvars;
9104 * The "local" command.
9106 static int FAST_FUNC
9107 localcmd(int argc UNUSED_PARAM, char **argv)
9112 ash_msg_and_raise_error("not in a function");
9115 while ((name = *argv++) != NULL) {
9121 static int FAST_FUNC
9122 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9127 static int FAST_FUNC
9128 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9133 static int FAST_FUNC
9134 execcmd(int argc UNUSED_PARAM, char **argv)
9137 iflag = 0; /* exit on error */
9140 /* We should set up signals for "exec CMD"
9141 * the same way as for "CMD" without "exec".
9142 * But optschanged->setinteractive->setsignal
9143 * still thought we are a root shell. Therefore, for example,
9144 * SIGQUIT is still set to IGN. Fix it:
9148 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9149 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9150 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9152 shellexec(argv + 1, pathval(), 0);
9159 * The return command.
9161 static int FAST_FUNC
9162 returncmd(int argc UNUSED_PARAM, char **argv)
9165 * If called outside a function, do what ksh does;
9166 * skip the rest of the file.
9168 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
9169 return argv[1] ? number(argv[1]) : exitstatus;
9172 /* Forward declarations for builtintab[] */
9173 static int breakcmd(int, char **) FAST_FUNC;
9174 static int dotcmd(int, char **) FAST_FUNC;
9175 static int evalcmd(int, char **) FAST_FUNC;
9176 static int exitcmd(int, char **) FAST_FUNC;
9177 static int exportcmd(int, char **) FAST_FUNC;
9178 #if ENABLE_ASH_GETOPTS
9179 static int getoptscmd(int, char **) FAST_FUNC;
9182 static int helpcmd(int, char **) FAST_FUNC;
9185 static int historycmd(int, char **) FAST_FUNC;
9187 #if ENABLE_SH_MATH_SUPPORT
9188 static int letcmd(int, char **) FAST_FUNC;
9190 static int readcmd(int, char **) FAST_FUNC;
9191 static int setcmd(int, char **) FAST_FUNC;
9192 static int shiftcmd(int, char **) FAST_FUNC;
9193 static int timescmd(int, char **) FAST_FUNC;
9194 static int trapcmd(int, char **) FAST_FUNC;
9195 static int umaskcmd(int, char **) FAST_FUNC;
9196 static int unsetcmd(int, char **) FAST_FUNC;
9197 static int ulimitcmd(int, char **) FAST_FUNC;
9199 #define BUILTIN_NOSPEC "0"
9200 #define BUILTIN_SPECIAL "1"
9201 #define BUILTIN_REGULAR "2"
9202 #define BUILTIN_SPEC_REG "3"
9203 #define BUILTIN_ASSIGN "4"
9204 #define BUILTIN_SPEC_ASSG "5"
9205 #define BUILTIN_REG_ASSG "6"
9206 #define BUILTIN_SPEC_REG_ASSG "7"
9208 /* Stubs for calling non-FAST_FUNC's */
9209 #if ENABLE_ASH_BUILTIN_ECHO
9210 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9212 #if ENABLE_ASH_BUILTIN_PRINTF
9213 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9215 #if ENABLE_ASH_BUILTIN_TEST
9216 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9219 /* Keep these in proper order since it is searched via bsearch() */
9220 static const struct builtincmd builtintab[] = {
9221 { BUILTIN_SPEC_REG "." , dotcmd },
9222 { BUILTIN_SPEC_REG ":" , truecmd },
9223 #if ENABLE_ASH_BUILTIN_TEST
9224 { BUILTIN_REGULAR "[" , testcmd },
9225 #if ENABLE_ASH_BASH_COMPAT
9226 { BUILTIN_REGULAR "[[" , testcmd },
9229 #if ENABLE_ASH_ALIAS
9230 { BUILTIN_REG_ASSG "alias" , aliascmd },
9233 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9235 { BUILTIN_SPEC_REG "break" , breakcmd },
9236 { BUILTIN_REGULAR "cd" , cdcmd },
9237 { BUILTIN_NOSPEC "chdir" , cdcmd },
9238 #if ENABLE_ASH_CMDCMD
9239 { BUILTIN_REGULAR "command" , commandcmd },
9241 { BUILTIN_SPEC_REG "continue", breakcmd },
9242 #if ENABLE_ASH_BUILTIN_ECHO
9243 { BUILTIN_REGULAR "echo" , echocmd },
9245 { BUILTIN_SPEC_REG "eval" , evalcmd },
9246 { BUILTIN_SPEC_REG "exec" , execcmd },
9247 { BUILTIN_SPEC_REG "exit" , exitcmd },
9248 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9249 { BUILTIN_REGULAR "false" , falsecmd },
9251 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9253 #if ENABLE_ASH_GETOPTS
9254 { BUILTIN_REGULAR "getopts" , getoptscmd },
9256 { BUILTIN_NOSPEC "hash" , hashcmd },
9258 { BUILTIN_NOSPEC "help" , helpcmd },
9261 { BUILTIN_NOSPEC "history" , historycmd },
9264 { BUILTIN_REGULAR "jobs" , jobscmd },
9265 { BUILTIN_REGULAR "kill" , killcmd },
9267 #if ENABLE_SH_MATH_SUPPORT
9268 { BUILTIN_NOSPEC "let" , letcmd },
9270 { BUILTIN_ASSIGN "local" , localcmd },
9271 #if ENABLE_ASH_BUILTIN_PRINTF
9272 { BUILTIN_REGULAR "printf" , printfcmd },
9274 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9275 { BUILTIN_REGULAR "read" , readcmd },
9276 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9277 { BUILTIN_SPEC_REG "return" , returncmd },
9278 { BUILTIN_SPEC_REG "set" , setcmd },
9279 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9280 #if ENABLE_ASH_BASH_COMPAT
9281 { BUILTIN_SPEC_REG "source" , dotcmd },
9283 #if ENABLE_ASH_BUILTIN_TEST
9284 { BUILTIN_REGULAR "test" , testcmd },
9286 { BUILTIN_SPEC_REG "times" , timescmd },
9287 { BUILTIN_SPEC_REG "trap" , trapcmd },
9288 { BUILTIN_REGULAR "true" , truecmd },
9289 { BUILTIN_NOSPEC "type" , typecmd },
9290 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9291 { BUILTIN_REGULAR "umask" , umaskcmd },
9292 #if ENABLE_ASH_ALIAS
9293 { BUILTIN_REGULAR "unalias" , unaliascmd },
9295 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9296 { BUILTIN_REGULAR "wait" , waitcmd },
9299 /* Should match the above table! */
9300 #define COMMANDCMD (builtintab + \
9302 /* [ */ 1 * ENABLE_ASH_BUILTIN_TEST + \
9303 /* [[ */ 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9304 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9305 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9306 /* break cd cddir */ 3)
9307 #define EVALCMD (COMMANDCMD + \
9308 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9309 /* continue */ 1 + \
9310 /* echo */ 1 * ENABLE_ASH_BUILTIN_ECHO + \
9312 #define EXECCMD (EVALCMD + \
9316 * Search the table of builtin commands.
9318 static struct builtincmd *
9319 find_builtin(const char *name)
9321 struct builtincmd *bp;
9324 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9331 * Execute a simple command.
9334 isassignment(const char *p)
9336 const char *q = endofname(p);
9341 static int FAST_FUNC
9342 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9344 /* Preserve exitstatus of a previous possible redirection
9345 * as POSIX mandates */
9346 return back_exitstatus;
9349 evalcommand(union node *cmd, int flags)
9351 static const struct builtincmd null_bltin = {
9352 "\0\0", bltincmd /* why three NULs? */
9354 struct stackmark smark;
9356 struct arglist arglist;
9357 struct arglist varlist;
9360 const struct strlist *sp;
9361 struct cmdentry cmdentry;
9368 struct builtincmd *bcmd;
9369 smallint cmd_is_exec;
9370 smallint pseudovarflag = 0;
9372 /* First expand the arguments. */
9373 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9374 setstackmark(&smark);
9375 back_exitstatus = 0;
9377 cmdentry.cmdtype = CMDBUILTIN;
9378 cmdentry.u.cmd = &null_bltin;
9379 varlist.lastp = &varlist.list;
9380 *varlist.lastp = NULL;
9381 arglist.lastp = &arglist.list;
9382 *arglist.lastp = NULL;
9385 if (cmd->ncmd.args) {
9386 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9387 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9390 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9391 struct strlist **spp;
9393 spp = arglist.lastp;
9394 if (pseudovarflag && isassignment(argp->narg.text))
9395 expandarg(argp, &arglist, EXP_VARTILDE);
9397 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9399 for (sp = *spp; sp; sp = sp->next)
9403 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9404 for (sp = arglist.list; sp; sp = sp->next) {
9405 TRACE(("evalcommand arg: %s\n", sp->text));
9406 *nargv++ = sp->text;
9411 if (iflag && funcnest == 0 && argc > 0)
9412 lastarg = nargv[-1];
9415 expredir(cmd->ncmd.redirect);
9416 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9418 path = vpath.var_text;
9419 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9420 struct strlist **spp;
9423 spp = varlist.lastp;
9424 expandarg(argp, &varlist, EXP_VARTILDE);
9427 * Modify the command lookup path, if a PATH= assignment
9431 if (varcmp(p, path) == 0)
9435 /* Print the command if xflag is set. */
9438 const char *p = " %s" + 1;
9440 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9442 for (n = 0; n < 2; n++) {
9444 fdprintf(preverrout_fd, p, sp->text);
9450 safe_write(preverrout_fd, "\n", 1);
9456 /* Now locate the command. */
9458 int cmd_flag = DO_ERR;
9459 #if ENABLE_ASH_CMDCMD
9460 const char *oldpath = path + 5;
9464 find_command(argv[0], &cmdentry, cmd_flag, path);
9465 if (cmdentry.cmdtype == CMDUNKNOWN) {
9466 flush_stdout_stderr();
9471 /* implement bltin and command here */
9472 if (cmdentry.cmdtype != CMDBUILTIN)
9475 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9476 if (cmdentry.u.cmd == EXECCMD)
9478 #if ENABLE_ASH_CMDCMD
9479 if (cmdentry.u.cmd == COMMANDCMD) {
9481 nargv = parse_command_args(argv, &path);
9484 argc -= nargv - argv;
9486 cmd_flag |= DO_NOFUNC;
9494 /* We have a redirection error. */
9496 raise_exception(EXERROR);
9498 exitstatus = status;
9502 /* Execute the command. */
9503 switch (cmdentry.cmdtype) {
9506 #if ENABLE_FEATURE_SH_NOFORK
9507 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9508 * around run_nofork_applet() call.
9509 * (2) Should this check also be done in forkshell()?
9510 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9512 /* find_command() encodes applet_no as (-2 - applet_no) */
9513 int applet_no = (- cmdentry.u.index - 2);
9514 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9515 listsetvar(varlist.list, VEXPORT|VSTACK);
9516 /* run <applet>_main() */
9517 exitstatus = run_nofork_applet(applet_no, argv);
9521 /* Can we avoid forking off? For example, very last command
9522 * in a script or a subshell does not need forking,
9523 * we can just exec it.
9525 if (!(flags & EV_EXIT) || may_have_traps) {
9526 /* No, forking off a child is necessary */
9528 jp = makejob(/*cmd,*/ 1);
9529 if (forkshell(jp, cmd, FORK_FG) != 0) {
9531 status = waitforjob(jp);
9533 TRACE(("forked child exited with %d\n", status));
9538 /* fall through to exec'ing external program */
9540 listsetvar(varlist.list, VEXPORT|VSTACK);
9541 shellexec(argv, path, cmdentry.u.index);
9545 cmdenviron = varlist.list;
9547 struct strlist *list = cmdenviron;
9549 if (spclbltin > 0 || argc == 0) {
9551 if (cmd_is_exec && argc > 1)
9554 listsetvar(list, i);
9556 /* Tight loop with builtins only:
9557 * "while kill -0 $child; do true; done"
9558 * will never exit even if $child died, unless we do this
9559 * to reap the zombie and make kill detect that it's gone: */
9560 dowait(DOWAIT_NONBLOCK, NULL);
9562 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9564 int i = exception_type;
9565 if (i == EXEXIT || i == EXEXEC)
9569 exit_status = 128 + SIGINT;
9571 exit_status = 128 + pending_sig;
9572 exitstatus = exit_status;
9573 if (i == EXINT || spclbltin > 0) {
9575 longjmp(exception_handler->loc, 1);
9582 listsetvar(varlist.list, 0);
9583 /* See above for the rationale */
9584 dowait(DOWAIT_NONBLOCK, NULL);
9585 if (evalfun(cmdentry.u.func, argc, argv, flags))
9588 status = exitstatus;
9593 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9595 /* dsl: I think this is intended to be used to support
9596 * '_' in 'vi' command mode during line editing...
9597 * However I implemented that within libedit itself.
9599 setvar0("_", lastarg);
9601 popstackmark(&smark);
9607 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9609 char *volatile savecmdname;
9610 struct jmploc *volatile savehandler;
9611 struct jmploc jmploc;
9614 savecmdname = commandname;
9615 i = setjmp(jmploc.loc);
9618 savehandler = exception_handler;
9619 exception_handler = &jmploc;
9620 commandname = argv[0];
9622 optptr = NULL; /* initialize nextopt */
9623 exitstatus = (*cmd->builtin)(argc, argv);
9624 flush_stdout_stderr();
9626 exitstatus |= ferror(stdout);
9628 commandname = savecmdname;
9629 exception_handler = savehandler;
9635 goodname(const char *p)
9637 return endofname(p)[0] == '\0';
9642 * Search for a command. This is called before we fork so that the
9643 * location of the command will be available in the parent as well as
9644 * the child. The check for "goodname" is an overly conservative
9645 * check that the name will not be subject to expansion.
9648 prehash(union node *n)
9650 struct cmdentry entry;
9652 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9653 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9657 /* ============ Builtin commands
9659 * Builtin commands whose functions are closely tied to evaluation
9660 * are implemented here.
9664 * Handle break and continue commands. Break, continue, and return are
9665 * all handled by setting the evalskip flag. The evaluation routines
9666 * above all check this flag, and if it is set they start skipping
9667 * commands rather than executing them. The variable skipcount is
9668 * the number of loops to break/continue, or the number of function
9669 * levels to return. (The latter is always 1.) It should probably
9670 * be an error to break out of more loops than exist, but it isn't
9671 * in the standard shell so we don't make it one here.
9673 static int FAST_FUNC
9674 breakcmd(int argc UNUSED_PARAM, char **argv)
9676 int n = argv[1] ? number(argv[1]) : 1;
9679 ash_msg_and_raise_error(msg_illnum, argv[1]);
9683 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9690 /* ============ input.c
9692 * This implements the input routines used by the parser.
9696 INPUT_PUSH_FILE = 1,
9697 INPUT_NOFILE_OK = 2,
9700 static smallint checkkwd;
9701 /* values of checkkwd variable */
9702 #define CHKALIAS 0x1
9707 * Push a string back onto the input at this current parsefile level.
9708 * We handle aliases this way.
9710 #if !ENABLE_ASH_ALIAS
9711 #define pushstring(s, ap) pushstring(s)
9714 pushstring(char *s, struct alias *ap)
9721 if (g_parsefile->strpush) {
9722 sp = ckzalloc(sizeof(*sp));
9723 sp->prev = g_parsefile->strpush;
9725 sp = &(g_parsefile->basestrpush);
9727 g_parsefile->strpush = sp;
9728 sp->prev_string = g_parsefile->next_to_pgetc;
9729 sp->prev_left_in_line = g_parsefile->left_in_line;
9730 sp->unget = g_parsefile->unget;
9731 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9732 #if ENABLE_ASH_ALIAS
9735 ap->flag |= ALIASINUSE;
9739 g_parsefile->next_to_pgetc = s;
9740 g_parsefile->left_in_line = len;
9741 g_parsefile->unget = 0;
9748 struct strpush *sp = g_parsefile->strpush;
9751 #if ENABLE_ASH_ALIAS
9753 if (g_parsefile->next_to_pgetc[-1] == ' '
9754 || g_parsefile->next_to_pgetc[-1] == '\t'
9756 checkkwd |= CHKALIAS;
9758 if (sp->string != sp->ap->val) {
9761 sp->ap->flag &= ~ALIASINUSE;
9762 if (sp->ap->flag & ALIASDEAD) {
9763 unalias(sp->ap->name);
9767 g_parsefile->next_to_pgetc = sp->prev_string;
9768 g_parsefile->left_in_line = sp->prev_left_in_line;
9769 g_parsefile->unget = sp->unget;
9770 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
9771 g_parsefile->strpush = sp->prev;
9772 if (sp != &(g_parsefile->basestrpush))
9781 char *buf = g_parsefile->buf;
9783 g_parsefile->next_to_pgetc = buf;
9784 #if ENABLE_FEATURE_EDITING
9786 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9787 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9790 # if ENABLE_ASH_IDLE_TIMEOUT
9792 const char *tmout_var = lookupvar("TMOUT");
9794 timeout = atoi(tmout_var) * 1000;
9800 # if ENABLE_FEATURE_TAB_COMPLETION
9801 line_input_state->path_lookup = pathval();
9803 reinit_unicode_for_ash();
9804 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9806 /* Ctrl+C pressed */
9817 /* Ctrl+D pressed */
9820 # if ENABLE_ASH_IDLE_TIMEOUT
9821 else if (errno == EAGAIN && timeout > 0) {
9822 puts("\007timed out waiting for input: auto-logout");
9829 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9832 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9834 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9835 int flags = fcntl(0, F_GETFL);
9836 if (flags >= 0 && (flags & O_NONBLOCK)) {
9837 flags &= ~O_NONBLOCK;
9838 if (fcntl(0, F_SETFL, flags) >= 0) {
9839 out2str("sh: turning off NDELAY mode\n");
9850 * Refill the input buffer and return the next input character:
9852 * 1) If a string was pushed back on the input, pop it;
9853 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9854 * or we are reading from a string so we can't refill the buffer,
9856 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9857 * 4) Process input up to the next newline, deleting nul characters.
9859 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9860 #define pgetc_debug(...) ((void)0)
9861 static int pgetc(void);
9868 if (g_parsefile->strpush) {
9869 #if ENABLE_ASH_ALIAS
9870 if (g_parsefile->left_in_line == -1
9871 && g_parsefile->strpush->ap
9872 && g_parsefile->next_to_pgetc[-1] != ' '
9873 && g_parsefile->next_to_pgetc[-1] != '\t'
9875 pgetc_debug("preadbuffer PEOA");
9882 /* on both branches above g_parsefile->left_in_line < 0.
9883 * "pgetc" needs refilling.
9886 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9887 * pungetc() may increment it a few times.
9888 * Assuming it won't increment it to less than -90.
9890 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9891 pgetc_debug("preadbuffer PEOF1");
9892 /* even in failure keep left_in_line and next_to_pgetc
9893 * in lock step, for correct multi-layer pungetc.
9894 * left_in_line was decremented before preadbuffer(),
9895 * must inc next_to_pgetc: */
9896 g_parsefile->next_to_pgetc++;
9900 more = g_parsefile->left_in_buffer;
9902 flush_stdout_stderr();
9906 /* don't try reading again */
9907 g_parsefile->left_in_line = -99;
9908 pgetc_debug("preadbuffer PEOF2");
9909 g_parsefile->next_to_pgetc++;
9914 /* Find out where's the end of line.
9915 * Set g_parsefile->left_in_line
9916 * and g_parsefile->left_in_buffer acordingly.
9917 * NUL chars are deleted.
9919 q = g_parsefile->next_to_pgetc;
9927 memmove(q, q + 1, more);
9931 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9937 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9938 if (g_parsefile->left_in_line < 0)
9943 g_parsefile->left_in_buffer = more;
9948 out2str(g_parsefile->next_to_pgetc);
9952 pgetc_debug("preadbuffer at %d:%p'%s'",
9953 g_parsefile->left_in_line,
9954 g_parsefile->next_to_pgetc,
9955 g_parsefile->next_to_pgetc);
9956 return (unsigned char)*g_parsefile->next_to_pgetc++;
9964 pgetc_debug("pgetc at %d:%p'%s'",
9965 g_parsefile->left_in_line,
9966 g_parsefile->next_to_pgetc,
9967 g_parsefile->next_to_pgetc);
9968 if (g_parsefile->unget)
9969 return g_parsefile->lastc[--g_parsefile->unget];
9971 if (--g_parsefile->left_in_line >= 0)
9972 c = (signed char)*g_parsefile->next_to_pgetc++;
9976 g_parsefile->lastc[1] = g_parsefile->lastc[0];
9977 g_parsefile->lastc[0] = c;
9982 #if ENABLE_ASH_ALIAS
9984 pgetc_without_PEOA(void)
9988 pgetc_debug("pgetc at %d:%p'%s'",
9989 g_parsefile->left_in_line,
9990 g_parsefile->next_to_pgetc,
9991 g_parsefile->next_to_pgetc);
9993 } while (c == PEOA);
9997 # define pgetc_without_PEOA() pgetc()
10001 * Read a line from the script.
10004 pfgets(char *line, int len)
10010 while (--nleft > 0) {
10011 c = pgetc_without_PEOA();
10026 * Undo a call to pgetc. Only two characters may be pushed back.
10027 * PEOF may be pushed back.
10032 g_parsefile->unget++;
10035 /* This one eats backslash+newline */
10041 while ((c = pgetc()) == '\\') {
10042 if (pgetc() != '\n') {
10047 g_parsefile->linno++;
10048 setprompt_if(doprompt, 2);
10055 * To handle the "." command, a stack of input files is used. Pushfile
10056 * adds a new entry to the stack and popfile restores the previous level.
10061 struct parsefile *pf;
10063 pf = ckzalloc(sizeof(*pf));
10064 pf->prev = g_parsefile;
10066 /*pf->strpush = NULL; - ckzalloc did it */
10067 /*pf->basestrpush.prev = NULL;*/
10075 struct parsefile *pf = g_parsefile;
10078 if (pf->pf_fd >= 0)
10081 while (pf->strpush)
10083 g_parsefile = pf->prev;
10089 * Return to top level.
10094 while (g_parsefile != &basepf)
10099 * Close the file(s) that the shell is reading commands from. Called
10100 * after a fork is done.
10106 if (g_parsefile->pf_fd > 0) {
10107 close(g_parsefile->pf_fd);
10108 g_parsefile->pf_fd = 0;
10113 * Like setinputfile, but takes an open file descriptor. Call this with
10117 setinputfd(int fd, int push)
10119 close_on_exec_on(fd);
10122 g_parsefile->buf = NULL;
10124 g_parsefile->pf_fd = fd;
10125 if (g_parsefile->buf == NULL)
10126 g_parsefile->buf = ckmalloc(IBUFSIZ);
10127 g_parsefile->left_in_buffer = 0;
10128 g_parsefile->left_in_line = 0;
10129 g_parsefile->linno = 1;
10133 * Set the input to take input from a file. If push is set, push the
10134 * old input onto the stack first.
10137 setinputfile(const char *fname, int flags)
10143 fd = open(fname, O_RDONLY);
10145 if (flags & INPUT_NOFILE_OK)
10147 ash_msg_and_raise_error("can't open '%s'", fname);
10150 fd2 = copyfd(fd, 10);
10153 ash_msg_and_raise_error("out of file descriptors");
10156 setinputfd(fd, flags & INPUT_PUSH_FILE);
10163 * Like setinputfile, but takes input from a string.
10166 setinputstring(char *string)
10170 g_parsefile->next_to_pgetc = string;
10171 g_parsefile->left_in_line = strlen(string);
10172 g_parsefile->buf = NULL;
10173 g_parsefile->linno = 1;
10178 /* ============ mail.c
10180 * Routines to check for mail.
10183 #if ENABLE_ASH_MAIL
10185 /* Hash of mtimes of mailboxes */
10186 static unsigned mailtime_hash;
10187 /* Set if MAIL or MAILPATH is changed. */
10188 static smallint mail_var_path_changed;
10191 * Print appropriate message(s) if mail has arrived.
10192 * If mail_var_path_changed is set,
10193 * then the value of MAIL has mail_var_path_changed,
10194 * so we just update the values.
10203 struct stackmark smark;
10206 setstackmark(&smark);
10207 mpath = mpathset() ? mpathval() : mailval();
10210 p = path_advance(&mpath, nullstr);
10215 for (q = p; *q; q++)
10221 q[-1] = '\0'; /* delete trailing '/' */
10222 if (stat(p, &statb) < 0) {
10225 /* Very simplistic "hash": just a sum of all mtimes */
10226 new_hash += (unsigned)statb.st_mtime;
10228 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10229 if (mailtime_hash != 0)
10230 out2str("you have mail\n");
10231 mailtime_hash = new_hash;
10233 mail_var_path_changed = 0;
10234 popstackmark(&smark);
10237 static void FAST_FUNC
10238 changemail(const char *val UNUSED_PARAM)
10240 mail_var_path_changed = 1;
10243 #endif /* ASH_MAIL */
10246 /* ============ ??? */
10249 * Set the shell parameters.
10252 setparam(char **argv)
10258 for (nparam = 0; argv[nparam]; nparam++)
10260 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10262 *ap++ = ckstrdup(*argv++);
10265 freeparam(&shellparam);
10266 shellparam.malloced = 1;
10267 shellparam.nparam = nparam;
10268 shellparam.p = newparam;
10269 #if ENABLE_ASH_GETOPTS
10270 shellparam.optind = 1;
10271 shellparam.optoff = -1;
10276 * Process shell options. The global variable argptr contains a pointer
10277 * to the argument list; we advance it past the options.
10279 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10280 * For a non-interactive shell, an error condition encountered
10281 * by a special built-in ... shall cause the shell to write a diagnostic message
10282 * to standard error and exit as shown in the following table:
10283 * Error Special Built-In
10285 * Utility syntax error (option or operand error) Shall exit
10287 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10288 * we see that bash does not do that (set "finishes" with error code 1 instead,
10289 * and shell continues), and people rely on this behavior!
10291 * set -o barfoo 2>/dev/null
10294 * Oh well. Let's mimic that.
10297 plus_minus_o(char *name, int val)
10302 for (i = 0; i < NOPTS; i++) {
10303 if (strcmp(name, optnames(i)) == 0) {
10308 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10311 for (i = 0; i < NOPTS; i++) {
10313 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10315 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10321 setoption(int flag, int val)
10325 for (i = 0; i < NOPTS; i++) {
10326 if (optletters(i) == flag) {
10331 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10335 options(int cmdline)
10343 while ((p = *argptr) != NULL) {
10345 if (c != '-' && c != '+')
10348 val = 0; /* val = 0 if c == '+' */
10351 if (p[0] == '\0' || LONE_DASH(p)) {
10353 /* "-" means turn off -x and -v */
10356 /* "--" means reset params */
10357 else if (*argptr == NULL)
10360 break; /* "-" or "--" terminates options */
10363 /* first char was + or - */
10364 while ((c = *p++) != '\0') {
10365 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10366 if (c == 'c' && cmdline) {
10367 minusc = p; /* command is after shell args */
10368 } else if (c == 'o') {
10369 if (plus_minus_o(*argptr, val)) {
10370 /* it already printed err message */
10371 return 1; /* error */
10375 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10377 /* bash does not accept +-login, we also won't */
10378 } else if (cmdline && val && (c == '-')) { /* long options */
10379 if (strcmp(p, "login") == 0)
10391 * The shift builtin command.
10393 static int FAST_FUNC
10394 shiftcmd(int argc UNUSED_PARAM, char **argv)
10401 n = number(argv[1]);
10402 if (n > shellparam.nparam)
10403 n = 0; /* bash compat, was = shellparam.nparam; */
10405 shellparam.nparam -= n;
10406 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10407 if (shellparam.malloced)
10410 ap2 = shellparam.p;
10411 while ((*ap2++ = *ap1++) != NULL)
10413 #if ENABLE_ASH_GETOPTS
10414 shellparam.optind = 1;
10415 shellparam.optoff = -1;
10422 * POSIX requires that 'set' (but not export or readonly) output the
10423 * variables in lexicographic order - by the locale's collating order (sigh).
10424 * Maybe we could keep them in an ordered balanced binary tree
10425 * instead of hashed lists.
10426 * For now just roll 'em through qsort for printing...
10429 showvars(const char *sep_prefix, int on, int off)
10432 char **ep, **epend;
10434 ep = listvars(on, off, &epend);
10435 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10437 sep = *sep_prefix ? " " : sep_prefix;
10439 for (; ep < epend; ep++) {
10443 p = strchrnul(*ep, '=');
10446 q = single_quote(++p);
10447 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10453 * The set command builtin.
10455 static int FAST_FUNC
10456 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10461 return showvars(nullstr, 0, VUNSET);
10464 retval = options(/*cmdline:*/ 0);
10465 if (retval == 0) { /* if no parse error... */
10467 if (*argptr != NULL) {
10475 #if ENABLE_ASH_RANDOM_SUPPORT
10476 static void FAST_FUNC
10477 change_random(const char *value)
10481 if (value == NULL) {
10482 /* "get", generate */
10483 t = next_random(&random_gen);
10484 /* set without recursion */
10485 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10486 vrandom.flags &= ~VNOFUNC;
10489 t = strtoul(value, NULL, 10);
10490 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10495 #if ENABLE_ASH_GETOPTS
10497 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10508 if (*param_optind < 1)
10510 optnext = optfirst + *param_optind - 1;
10512 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10515 p = optnext[-1] + *optoff;
10516 if (p == NULL || *p == '\0') {
10517 /* Current word is done, advance */
10519 if (p == NULL || *p != '-' || *++p == '\0') {
10526 if (LONE_DASH(p)) /* check for "--" */
10531 for (q = optstr; *q != c;) {
10533 if (optstr[0] == ':') {
10535 /*sbuf[1] = '\0'; - already is */
10536 err |= setvarsafe("OPTARG", sbuf, 0);
10538 fprintf(stderr, "Illegal option -%c\n", c);
10539 unsetvar("OPTARG");
10549 if (*p == '\0' && (p = *optnext) == NULL) {
10550 if (optstr[0] == ':') {
10552 /*sbuf[1] = '\0'; - already is */
10553 err |= setvarsafe("OPTARG", sbuf, 0);
10556 fprintf(stderr, "No arg for -%c option\n", c);
10557 unsetvar("OPTARG");
10565 err |= setvarsafe("OPTARG", p, 0);
10568 err |= setvarsafe("OPTARG", nullstr, 0);
10570 *optoff = p ? p - *(optnext - 1) : -1;
10571 *param_optind = optnext - optfirst + 1;
10572 err |= setvarsafe("OPTIND", itoa(*param_optind), VNOFUNC);
10574 /*sbuf[1] = '\0'; - already is */
10575 err |= setvarsafe(optvar, sbuf, 0);
10579 flush_stdout_stderr();
10580 raise_exception(EXERROR);
10586 * The getopts builtin. Shellparam.optnext points to the next argument
10587 * to be processed. Shellparam.optptr points to the next character to
10588 * be processed in the current argument. If shellparam.optnext is NULL,
10589 * then it's the first time getopts has been called.
10591 static int FAST_FUNC
10592 getoptscmd(int argc, char **argv)
10597 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10599 optbase = shellparam.p;
10600 if (shellparam.optind > shellparam.nparam + 1) {
10601 shellparam.optind = 1;
10602 shellparam.optoff = -1;
10605 optbase = &argv[3];
10606 if (shellparam.optind > argc - 2) {
10607 shellparam.optind = 1;
10608 shellparam.optoff = -1;
10612 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10613 &shellparam.optoff);
10615 #endif /* ASH_GETOPTS */
10618 /* ============ Shell parser */
10621 struct heredoc *next; /* next here document in list */
10622 union node *here; /* redirection node */
10623 char *eofmark; /* string indicating end of input */
10624 smallint striptabs; /* if set, strip leading tabs */
10627 static smallint tokpushback; /* last token pushed back */
10628 static smallint quoteflag; /* set if (part of) last token was quoted */
10629 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10630 static struct heredoc *heredoclist; /* list of here documents to read */
10631 static char *wordtext; /* text of last word returned by readtoken */
10632 static struct nodelist *backquotelist;
10633 static union node *redirnode;
10634 static struct heredoc *heredoc;
10636 static const char *
10637 tokname(char *buf, int tok)
10640 return tokname_array[tok] + 1;
10641 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10645 /* raise_error_unexpected_syntax:
10646 * Called when an unexpected token is read during the parse. The argument
10647 * is the token that is expected, or -1 if more than one type of token can
10648 * occur at this point.
10650 static void raise_error_unexpected_syntax(int) NORETURN;
10652 raise_error_unexpected_syntax(int token)
10658 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10660 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10661 raise_error_syntax(msg);
10665 #define EOFMARKLEN 79
10667 /* parsing is heavily cross-recursive, need these forward decls */
10668 static union node *andor(void);
10669 static union node *pipeline(void);
10670 static union node *parse_command(void);
10671 static void parseheredoc(void);
10672 static int peektoken(void);
10673 static int readtoken(void);
10675 static union node *
10678 union node *n1, *n2, *n3;
10683 switch (peektoken()) {
10691 if (!n1 && (nlflag & 1))
10697 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10698 if (nlflag == 2 && tokname_array[peektoken()][0])
10704 if (tok == TBACKGND) {
10705 if (n2->type == NPIPE) {
10706 n2->npipe.pipe_backgnd = 1;
10708 if (n2->type != NREDIR) {
10709 n3 = stzalloc(sizeof(struct nredir));
10711 /*n3->nredir.redirect = NULL; - stzalloc did it */
10714 n2->type = NBACKGND;
10720 n3 = stzalloc(sizeof(struct nbinary));
10722 n3->nbinary.ch1 = n1;
10723 n3->nbinary.ch2 = n2;
10736 raise_error_unexpected_syntax(-1);
10743 static union node *
10746 union node *n1, *n2, *n3;
10754 } else if (t == TOR) {
10760 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10762 n3 = stzalloc(sizeof(struct nbinary));
10764 n3->nbinary.ch1 = n1;
10765 n3->nbinary.ch2 = n2;
10770 static union node *
10773 union node *n1, *n2, *pipenode;
10774 struct nodelist *lp, *prev;
10778 TRACE(("pipeline: entered\n"));
10779 if (readtoken() == TNOT) {
10781 checkkwd = CHKKWD | CHKALIAS;
10784 n1 = parse_command();
10785 if (readtoken() == TPIPE) {
10786 pipenode = stzalloc(sizeof(struct npipe));
10787 pipenode->type = NPIPE;
10788 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10789 lp = stzalloc(sizeof(struct nodelist));
10790 pipenode->npipe.cmdlist = lp;
10794 lp = stzalloc(sizeof(struct nodelist));
10795 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10796 lp->n = parse_command();
10798 } while (readtoken() == TPIPE);
10804 n2 = stzalloc(sizeof(struct nnot));
10812 static union node *
10817 n = stzalloc(sizeof(struct narg));
10819 /*n->narg.next = NULL; - stzalloc did it */
10820 n->narg.text = wordtext;
10821 n->narg.backquote = backquotelist;
10826 fixredir(union node *n, const char *text, int err)
10830 TRACE(("Fix redir %s %d\n", text, err));
10832 n->ndup.vname = NULL;
10834 fd = bb_strtou(text, NULL, 10);
10835 if (!errno && fd >= 0)
10836 n->ndup.dupfd = fd;
10837 else if (LONE_DASH(text))
10838 n->ndup.dupfd = -1;
10841 raise_error_syntax("bad fd number");
10842 n->ndup.vname = makename();
10847 * Returns true if the text contains nothing to expand (no dollar signs
10851 noexpand(const char *text)
10855 while ((c = *text++) != '\0') {
10856 if (c == CTLQUOTEMARK)
10860 else if (SIT(c, BASESYNTAX) == CCTL)
10869 union node *n = redirnode;
10871 if (readtoken() != TWORD)
10872 raise_error_unexpected_syntax(-1);
10873 if (n->type == NHERE) {
10874 struct heredoc *here = heredoc;
10878 if (quoteflag == 0)
10880 TRACE(("Here document %d\n", n->type));
10881 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10882 raise_error_syntax("illegal eof marker for << redirection");
10883 rmescapes(wordtext, 0);
10884 here->eofmark = wordtext;
10886 if (heredoclist == NULL)
10887 heredoclist = here;
10889 for (p = heredoclist; p->next; p = p->next)
10893 } else if (n->type == NTOFD || n->type == NFROMFD) {
10894 fixredir(n, wordtext, 0);
10896 n->nfile.fname = makename();
10900 static union node *
10903 union node *args, **app;
10904 union node *n = NULL;
10905 union node *vars, **vpp;
10906 union node **rpp, *redir;
10908 #if ENABLE_ASH_BASH_COMPAT
10909 smallint double_brackets_flag = 0;
10910 smallint function_flag = 0;
10920 savecheckkwd = CHKALIAS;
10923 checkkwd = savecheckkwd;
10926 #if ENABLE_ASH_BASH_COMPAT
10928 if (peektoken() != TWORD)
10929 raise_error_unexpected_syntax(TWORD);
10932 case TAND: /* "&&" */
10933 case TOR: /* "||" */
10934 if (!double_brackets_flag) {
10938 wordtext = (char *) (t == TAND ? "-a" : "-o");
10941 n = stzalloc(sizeof(struct narg));
10943 /*n->narg.next = NULL; - stzalloc did it */
10944 n->narg.text = wordtext;
10945 #if ENABLE_ASH_BASH_COMPAT
10946 if (strcmp("[[", wordtext) == 0)
10947 double_brackets_flag = 1;
10948 else if (strcmp("]]", wordtext) == 0)
10949 double_brackets_flag = 0;
10951 n->narg.backquote = backquotelist;
10952 if (savecheckkwd && isassignment(wordtext)) {
10954 vpp = &n->narg.next;
10957 app = &n->narg.next;
10960 #if ENABLE_ASH_BASH_COMPAT
10961 if (function_flag) {
10962 checkkwd = CHKNL | CHKKWD;
10963 switch (peektoken()) {
10975 if (strcmp("[[", wordtext) == 0)
10979 raise_error_unexpected_syntax(-1);
10985 *rpp = n = redirnode;
10986 rpp = &n->nfile.next;
10987 parsefname(); /* read name of redirection file */
10990 IF_ASH_BASH_COMPAT(do_func:)
10991 if (args && app == &args->narg.next
10994 struct builtincmd *bcmd;
10997 /* We have a function */
10998 if (IF_ASH_BASH_COMPAT(!function_flag &&) readtoken() != TRP)
10999 raise_error_unexpected_syntax(TRP);
11000 name = n->narg.text;
11001 if (!goodname(name)
11002 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11004 raise_error_syntax("bad function name");
11007 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11008 n->narg.next = parse_command();
11011 IF_ASH_BASH_COMPAT(function_flag = 0;)
11022 n = stzalloc(sizeof(struct ncmd));
11024 n->ncmd.args = args;
11025 n->ncmd.assign = vars;
11026 n->ncmd.redirect = redir;
11030 static union node *
11031 parse_command(void)
11033 union node *n1, *n2;
11034 union node *ap, **app;
11035 union node *cp, **cpp;
11036 union node *redir, **rpp;
11043 switch (readtoken()) {
11045 raise_error_unexpected_syntax(-1);
11048 n1 = stzalloc(sizeof(struct nif));
11050 n1->nif.test = list(0);
11051 if (readtoken() != TTHEN)
11052 raise_error_unexpected_syntax(TTHEN);
11053 n1->nif.ifpart = list(0);
11055 while (readtoken() == TELIF) {
11056 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11057 n2 = n2->nif.elsepart;
11059 n2->nif.test = list(0);
11060 if (readtoken() != TTHEN)
11061 raise_error_unexpected_syntax(TTHEN);
11062 n2->nif.ifpart = list(0);
11064 if (lasttoken == TELSE)
11065 n2->nif.elsepart = list(0);
11067 n2->nif.elsepart = NULL;
11075 n1 = stzalloc(sizeof(struct nbinary));
11076 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11077 n1->nbinary.ch1 = list(0);
11080 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
11081 got == TWORD ? wordtext : ""));
11082 raise_error_unexpected_syntax(TDO);
11084 n1->nbinary.ch2 = list(0);
11089 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11090 raise_error_syntax("bad for loop variable");
11091 n1 = stzalloc(sizeof(struct nfor));
11093 n1->nfor.var = wordtext;
11094 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11095 if (readtoken() == TIN) {
11097 while (readtoken() == TWORD) {
11098 n2 = stzalloc(sizeof(struct narg));
11100 /*n2->narg.next = NULL; - stzalloc did it */
11101 n2->narg.text = wordtext;
11102 n2->narg.backquote = backquotelist;
11104 app = &n2->narg.next;
11107 n1->nfor.args = ap;
11108 if (lasttoken != TNL && lasttoken != TSEMI)
11109 raise_error_unexpected_syntax(-1);
11111 n2 = stzalloc(sizeof(struct narg));
11113 /*n2->narg.next = NULL; - stzalloc did it */
11114 n2->narg.text = (char *)dolatstr;
11115 /*n2->narg.backquote = NULL;*/
11116 n1->nfor.args = n2;
11118 * Newline or semicolon here is optional (but note
11119 * that the original Bourne shell only allowed NL).
11121 if (lasttoken != TSEMI)
11124 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11125 if (readtoken() != TDO)
11126 raise_error_unexpected_syntax(TDO);
11127 n1->nfor.body = list(0);
11131 n1 = stzalloc(sizeof(struct ncase));
11133 if (readtoken() != TWORD)
11134 raise_error_unexpected_syntax(TWORD);
11135 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11137 /*n2->narg.next = NULL; - stzalloc did it */
11138 n2->narg.text = wordtext;
11139 n2->narg.backquote = backquotelist;
11140 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11141 if (readtoken() != TIN)
11142 raise_error_unexpected_syntax(TIN);
11143 cpp = &n1->ncase.cases;
11145 checkkwd = CHKNL | CHKKWD;
11147 while (t != TESAC) {
11148 if (lasttoken == TLP)
11150 *cpp = cp = stzalloc(sizeof(struct nclist));
11152 app = &cp->nclist.pattern;
11154 *app = ap = stzalloc(sizeof(struct narg));
11156 /*ap->narg.next = NULL; - stzalloc did it */
11157 ap->narg.text = wordtext;
11158 ap->narg.backquote = backquotelist;
11159 if (readtoken() != TPIPE)
11161 app = &ap->narg.next;
11164 //ap->narg.next = NULL;
11165 if (lasttoken != TRP)
11166 raise_error_unexpected_syntax(TRP);
11167 cp->nclist.body = list(2);
11169 cpp = &cp->nclist.next;
11171 checkkwd = CHKNL | CHKKWD;
11175 raise_error_unexpected_syntax(TENDCASE);
11182 n1 = stzalloc(sizeof(struct nredir));
11183 n1->type = NSUBSHELL;
11184 n1->nredir.n = list(0);
11185 /*n1->nredir.redirect = NULL; - stzalloc did it */
11192 IF_ASH_BASH_COMPAT(case TFUNCTION:)
11196 return simplecmd();
11199 if (readtoken() != t)
11200 raise_error_unexpected_syntax(t);
11203 /* Now check for redirection which may follow command */
11204 checkkwd = CHKKWD | CHKALIAS;
11206 while (readtoken() == TREDIR) {
11207 *rpp = n2 = redirnode;
11208 rpp = &n2->nfile.next;
11214 if (n1->type != NSUBSHELL) {
11215 n2 = stzalloc(sizeof(struct nredir));
11220 n1->nredir.redirect = redir;
11225 #if ENABLE_ASH_BASH_COMPAT
11226 static int decode_dollar_squote(void)
11228 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11234 p = strchr(C_escapes, c);
11239 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11243 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11245 } else if (c == 'x') { /* \xHH */
11249 } while (isxdigit(c) && --cnt);
11251 if (cnt == 3) { /* \x but next char is "bad" */
11255 } else { /* simple seq like \\ or \t */
11260 c = bb_process_escape_sequence((void*)&p);
11261 } else { /* unrecognized "\z": print both chars unless ' or " */
11262 if (c != '\'' && c != '"') {
11264 c |= 0x100; /* "please encode \, then me" */
11272 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11273 * is not NULL, read a here document. In the latter case, eofmark is the
11274 * word which marks the end of the document and striptabs is true if
11275 * leading tabs should be stripped from the document. The argument c
11276 * is the first character of the input token or document.
11278 * Because C does not have internal subroutines, I have simulated them
11279 * using goto's to implement the subroutine linkage. The following macros
11280 * will run code that appears at the end of readtoken1.
11282 #define CHECKEND() {goto checkend; checkend_return:;}
11283 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11284 #define PARSESUB() {goto parsesub; parsesub_return:;}
11285 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11286 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11287 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11289 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11291 /* NB: syntax parameter fits into smallint */
11292 /* c parameter is an unsigned char or PEOF or PEOA */
11295 char line[EOFMARKLEN + 1];
11296 struct nodelist *bqlist;
11300 smallint prevsyntax; /* syntax before arithmetic */
11301 #if ENABLE_ASH_EXPAND_PRMT
11302 smallint pssyntax; /* we are expanding a prompt string */
11304 int varnest; /* levels of variables expansion */
11305 int arinest; /* levels of arithmetic expansion */
11306 int parenlevel; /* levels of parens in arithmetic */
11307 int dqvarnest; /* levels of variables expansion within double quotes */
11309 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11311 startlinno = g_parsefile->linno;
11315 #if ENABLE_ASH_EXPAND_PRMT
11316 pssyntax = (syntax == PSSYNTAX);
11320 dblquote = (syntax == DQSYNTAX);
11326 STARTSTACKSTR(out);
11328 /* For each line, until end of word */
11329 CHECKEND(); /* set c to PEOF if at end of here document */
11330 for (;;) { /* until end of line or end of word */
11331 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11332 switch (SIT(c, syntax)) {
11333 case CNL: /* '\n' */
11334 if (syntax == BASESYNTAX)
11335 goto endword; /* exit outer loop */
11337 g_parsefile->linno++;
11338 setprompt_if(doprompt, 2);
11340 goto loop; /* continue outer loop */
11345 #if ENABLE_ASH_BASH_COMPAT
11346 if (c == '\\' && bash_dollar_squote) {
11347 c = decode_dollar_squote();
11349 /* skip $'\000', $'\x00' (like bash) */
11353 /* Unknown escape. Encode as '\z' */
11354 c = (unsigned char)c;
11355 if (eofmark == NULL || dblquote)
11356 USTPUTC(CTLESC, out);
11357 USTPUTC('\\', out);
11361 if (eofmark == NULL || dblquote)
11362 USTPUTC(CTLESC, out);
11365 case CBACK: /* backslash */
11366 c = pgetc_without_PEOA();
11368 USTPUTC(CTLESC, out);
11369 USTPUTC('\\', out);
11371 } else if (c == '\n') {
11372 setprompt_if(doprompt, 2);
11374 #if ENABLE_ASH_EXPAND_PRMT
11375 if (c == '$' && pssyntax) {
11376 USTPUTC(CTLESC, out);
11377 USTPUTC('\\', out);
11380 /* Backslash is retained if we are in "str" and next char isn't special */
11385 && (c != '"' || eofmark != NULL)
11387 USTPUTC('\\', out);
11389 USTPUTC(CTLESC, out);
11397 if (eofmark == NULL) {
11398 USTPUTC(CTLQUOTEMARK, out);
11406 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11407 if (eofmark != NULL && varnest == 0) {
11410 if (dqvarnest == 0) {
11411 syntax = BASESYNTAX;
11418 case CVAR: /* '$' */
11419 PARSESUB(); /* parse substitution */
11421 case CENDVAR: /* '}' */
11424 if (dqvarnest > 0) {
11431 #if ENABLE_SH_MATH_SUPPORT
11432 case CLP: /* '(' in arithmetic */
11436 case CRP: /* ')' in arithmetic */
11437 if (parenlevel > 0) {
11440 if (pgetc() == ')') {
11442 if (--arinest == 0) {
11443 syntax = prevsyntax;
11447 * unbalanced parens
11448 * (don't 2nd guess - no error)
11456 case CBQUOTE: /* '`' */
11460 goto endword; /* exit outer loop */
11464 if (varnest == 0) {
11465 #if ENABLE_ASH_BASH_COMPAT
11467 if (pgetc() == '>')
11468 c = 0x100 + '>'; /* flag &> */
11472 goto endword; /* exit outer loop */
11474 IF_ASH_ALIAS(if (c != PEOA))
11481 #if ENABLE_SH_MATH_SUPPORT
11482 if (syntax == ARISYNTAX)
11483 raise_error_syntax("missing '))'");
11485 if (syntax != BASESYNTAX && eofmark == NULL)
11486 raise_error_syntax("unterminated quoted string");
11487 if (varnest != 0) {
11488 startlinno = g_parsefile->linno;
11490 raise_error_syntax("missing '}'");
11492 USTPUTC('\0', out);
11493 len = out - (char *)stackblock();
11494 out = stackblock();
11495 if (eofmark == NULL) {
11496 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11499 if (isdigit_str9(out)) {
11500 PARSEREDIR(); /* passed as params: out, c */
11501 lasttoken = TREDIR;
11504 /* else: non-number X seen, interpret it
11505 * as "NNNX>file" = "NNNX >file" */
11509 quoteflag = quotef;
11510 backquotelist = bqlist;
11511 grabstackblock(len);
11515 /* end of readtoken routine */
11518 * Check to see whether we are at the end of the here document. When this
11519 * is called, c is set to the first character of the next input line. If
11520 * we are at the end of the here document, this routine sets the c to PEOF.
11524 #if ENABLE_ASH_ALIAS
11526 c = pgetc_without_PEOA();
11529 while (c == '\t') {
11530 c = pgetc_without_PEOA();
11533 if (c == *eofmark) {
11534 if (pfgets(line, sizeof(line)) != NULL) {
11538 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11540 if (*p == '\n' && *q == '\0') {
11542 g_parsefile->linno++;
11543 needprompt = doprompt;
11545 pushstring(line, NULL);
11550 goto checkend_return;
11554 * Parse a redirection operator. The variable "out" points to a string
11555 * specifying the fd to be redirected. The variable "c" contains the
11556 * first character of the redirection operator.
11559 /* out is already checked to be a valid number or "" */
11560 int fd = (*out == '\0' ? -1 : atoi(out));
11563 np = stzalloc(sizeof(struct nfile));
11568 np->type = NAPPEND;
11570 np->type = NCLOBBER;
11573 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11579 #if ENABLE_ASH_BASH_COMPAT
11580 else if (c == 0x100 + '>') { /* this flags &> redirection */
11582 pgetc(); /* this is '>', no need to check */
11586 else { /* c == '<' */
11587 /*np->nfile.fd = 0; - stzalloc did it */
11591 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11592 np = stzalloc(sizeof(struct nhere));
11593 /*np->nfile.fd = 0; - stzalloc did it */
11596 heredoc = stzalloc(sizeof(struct heredoc));
11597 heredoc->here = np;
11600 heredoc->striptabs = 1;
11602 /*heredoc->striptabs = 0; - stzalloc did it */
11608 np->type = NFROMFD;
11612 np->type = NFROMTO;
11624 goto parseredir_return;
11628 * Parse a substitution. At this point, we have read the dollar sign
11629 * and nothing else.
11632 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11633 * (assuming ascii char codes, as the original implementation did) */
11634 #define is_special(c) \
11635 (((unsigned)(c) - 33 < 32) \
11636 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11638 unsigned char subtype;
11642 c = pgetc_eatbnl();
11643 if (c > 255 /* PEOA or PEOF */
11644 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11646 #if ENABLE_ASH_BASH_COMPAT
11647 if (syntax != DQSYNTAX && c == '\'')
11648 bash_dollar_squote = 1;
11653 } else if (c == '(') {
11654 /* $(command) or $((arith)) */
11655 if (pgetc_eatbnl() == '(') {
11656 #if ENABLE_SH_MATH_SUPPORT
11659 raise_error_syntax("you disabled math support for $((arith)) syntax");
11666 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11667 USTPUTC(CTLVAR, out);
11668 typeloc = out - (char *)stackblock();
11669 USTPUTC(VSNORMAL, out);
11670 subtype = VSNORMAL;
11672 c = pgetc_eatbnl();
11674 c = pgetc_eatbnl();
11676 c = '#'; /* ${#} - same as $# */
11678 subtype = VSLENGTH; /* ${#VAR} */
11683 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11684 /* $[{[#]]NAME[}] */
11687 c = pgetc_eatbnl();
11688 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11689 } else if (isdigit(c)) {
11690 /* $[{[#]]NUM[}] */
11693 c = pgetc_eatbnl();
11694 } while (isdigit(c));
11695 } else if (is_special(c)) {
11696 /* $[{[#]]<specialchar>[}] */
11698 c = pgetc_eatbnl();
11701 raise_error_syntax("bad substitution");
11703 if (c != '}' && subtype == VSLENGTH) {
11704 /* ${#VAR didn't end with } */
11710 if (subtype == 0) {
11711 static const char types[] ALIGN1 = "}-+?=";
11712 /* ${VAR...} but not $VAR or ${#VAR} */
11713 /* c == first char after VAR */
11716 c = pgetc_eatbnl();
11717 #if ENABLE_ASH_BASH_COMPAT
11718 /* This check is only needed to not misinterpret
11719 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11722 if (!strchr(types, c)) {
11723 subtype = VSSUBSTR;
11725 break; /* "goto do_pungetc" is bigger (!) */
11731 const char *p = strchr(types, c);
11734 subtype = p - types + VSNORMAL;
11740 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11741 c = pgetc_eatbnl();
11747 #if ENABLE_ASH_BASH_COMPAT
11749 /* ${v/[/]pattern/repl} */
11750 //TODO: encode pattern and repl separately.
11751 // Currently ${v/$var_with_slash/repl} is horribly broken
11752 subtype = VSREPLACE;
11753 c = pgetc_eatbnl();
11756 subtype++; /* VSREPLACEALL */
11764 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11765 if (subtype != VSNORMAL) {
11772 goto parsesub_return;
11776 * Called to parse command substitutions. Newstyle is set if the command
11777 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11778 * list of commands (passed by reference), and savelen is the number of
11779 * characters on the top of the stack which must be preserved.
11782 struct nodelist **nlpp;
11786 smallint saveprompt = 0;
11789 savelen = out - (char *)stackblock();
11792 * FIXME: this can allocate very large block on stack and SEGV.
11794 * echo "..<100kbytes>..`true` $(true) `true` ..."
11795 * allocates 100kb for every command subst. With about
11796 * a hundred command substitutions stack overflows.
11797 * With larger prepended string, SEGV happens sooner.
11799 str = alloca(savelen);
11800 memcpy(str, stackblock(), savelen);
11804 /* We must read until the closing backquote, giving special
11805 * treatment to some slashes, and then push the string and
11806 * reread it as input, interpreting it normally.
11812 STARTSTACKSTR(pout);
11816 setprompt_if(needprompt, 2);
11825 g_parsefile->linno++;
11826 setprompt_if(doprompt, 2);
11828 * If eating a newline, avoid putting
11829 * the newline into the new character
11830 * stream (via the STPUTC after the
11835 if (pc != '\\' && pc != '`' && pc != '$'
11836 && (!dblquote || pc != '"')
11838 STPUTC('\\', pout);
11840 if (pc <= 255 /* not PEOA or PEOF */) {
11846 IF_ASH_ALIAS(case PEOA:)
11847 startlinno = g_parsefile->linno;
11848 raise_error_syntax("EOF in backquote substitution");
11851 g_parsefile->linno++;
11852 needprompt = doprompt;
11861 STPUTC('\0', pout);
11862 psavelen = pout - (char *)stackblock();
11863 if (psavelen > 0) {
11864 pstr = grabstackstr(pout);
11865 setinputstring(pstr);
11870 nlpp = &(*nlpp)->next;
11871 *nlpp = stzalloc(sizeof(**nlpp));
11872 /* (*nlpp)->next = NULL; - stzalloc did it */
11875 saveprompt = doprompt;
11882 doprompt = saveprompt;
11883 else if (readtoken() != TRP)
11884 raise_error_unexpected_syntax(TRP);
11889 * Start reading from old file again, ignoring any pushed back
11890 * tokens left from the backquote parsing
11895 while (stackblocksize() <= savelen)
11897 STARTSTACKSTR(out);
11899 memcpy(out, str, savelen);
11900 STADJUST(savelen, out);
11902 USTPUTC(CTLBACKQ, out);
11904 goto parsebackq_oldreturn;
11905 goto parsebackq_newreturn;
11908 #if ENABLE_SH_MATH_SUPPORT
11910 * Parse an arithmetic expansion (indicate start of one and set state)
11913 if (++arinest == 1) {
11914 prevsyntax = syntax;
11915 syntax = ARISYNTAX;
11917 USTPUTC(CTLARI, out);
11918 goto parsearith_return;
11921 } /* end of readtoken */
11924 * Read the next input token.
11925 * If the token is a word, we set backquotelist to the list of cmds in
11926 * backquotes. We set quoteflag to true if any part of the word was
11928 * If the token is TREDIR, then we set redirnode to a structure containing
11930 * In all cases, the variable startlinno is set to the number of the line
11931 * on which the token starts.
11933 * [Change comment: here documents and internal procedures]
11934 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11935 * word parsing code into a separate routine. In this case, readtoken
11936 * doesn't need to have any internal procedures, but parseword does.
11937 * We could also make parseoperator in essence the main routine, and
11938 * have parseword (readtoken1?) handle both words and redirection.]
11940 #define NEW_xxreadtoken
11941 #ifdef NEW_xxreadtoken
11942 /* singles must be first! */
11943 static const char xxreadtoken_chars[7] ALIGN1 = {
11944 '\n', '(', ')', /* singles */
11945 '&', '|', ';', /* doubles */
11949 #define xxreadtoken_singles 3
11950 #define xxreadtoken_doubles 3
11952 static const char xxreadtoken_tokens[] ALIGN1 = {
11953 TNL, TLP, TRP, /* only single occurrence allowed */
11954 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11955 TEOF, /* corresponds to trailing nul */
11956 TAND, TOR, TENDCASE /* if double occurrence */
11968 setprompt_if(needprompt, 2);
11969 startlinno = g_parsefile->linno;
11970 for (;;) { /* until token or start of word found */
11972 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11976 while ((c = pgetc()) != '\n' && c != PEOF)
11979 } else if (c == '\\') {
11980 if (pgetc() != '\n') {
11982 break; /* return readtoken1(...) */
11984 startlinno = ++g_parsefile->linno;
11985 setprompt_if(doprompt, 2);
11989 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11992 g_parsefile->linno++;
11993 needprompt = doprompt;
11996 p = strchr(xxreadtoken_chars, c);
11998 break; /* return readtoken1(...) */
12000 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12002 if (cc == c) { /* double occurrence? */
12003 p += xxreadtoken_doubles + 1;
12006 #if ENABLE_ASH_BASH_COMPAT
12007 if (c == '&' && cc == '>') /* &> */
12008 break; /* return readtoken1(...) */
12013 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12018 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12020 #else /* old xxreadtoken */
12021 #define RETURN(token) return lasttoken = token
12031 setprompt_if(needprompt, 2);
12032 startlinno = g_parsefile->linno;
12033 for (;;) { /* until token or start of word found */
12036 case ' ': case '\t':
12037 IF_ASH_ALIAS(case PEOA:)
12040 while ((c = pgetc()) != '\n' && c != PEOF)
12045 if (pgetc() == '\n') {
12046 startlinno = ++g_parsefile->linno;
12047 setprompt_if(doprompt, 2);
12053 g_parsefile->linno++;
12054 needprompt = doprompt;
12059 if (pgetc() == '&')
12064 if (pgetc() == '|')
12069 if (pgetc() == ';')
12082 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12085 #endif /* old xxreadtoken */
12091 int kwd = checkkwd;
12093 smallint alreadyseen = tokpushback;
12096 #if ENABLE_ASH_ALIAS
12112 if (t != TWORD || quoteflag) {
12117 * check for keywords
12119 if (kwd & CHKKWD) {
12120 const char *const *pp;
12122 pp = findkwd(wordtext);
12124 lasttoken = t = pp - tokname_array;
12125 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
12130 if (checkkwd & CHKALIAS) {
12131 #if ENABLE_ASH_ALIAS
12133 ap = lookupalias(wordtext, 1);
12136 pushstring(ap->val, ap);
12146 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
12148 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
12164 * Read and parse a command. Returns NODE_EOF on end of file.
12165 * (NULL is a valid parse tree indicating a blank line.)
12167 static union node *
12168 parsecmd(int interact)
12173 doprompt = interact;
12174 setprompt_if(doprompt, doprompt);
12180 * Input any here documents.
12185 struct heredoc *here;
12188 here = heredoclist;
12189 heredoclist = NULL;
12192 setprompt_if(needprompt, 2);
12193 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12194 here->eofmark, here->striptabs);
12195 n = stzalloc(sizeof(struct narg));
12196 n->narg.type = NARG;
12197 /*n->narg.next = NULL; - stzalloc did it */
12198 n->narg.text = wordtext;
12199 n->narg.backquote = backquotelist;
12200 here->here->nhere.doc = n;
12207 * called by editline -- any expansions to the prompt should be added here.
12209 #if ENABLE_ASH_EXPAND_PRMT
12210 static const char *
12211 expandstr(const char *ps)
12215 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12216 * and token processing _can_ alter it (delete NULs etc). */
12217 setinputstring((char *)ps);
12218 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12221 n.narg.type = NARG;
12222 n.narg.next = NULL;
12223 n.narg.text = wordtext;
12224 n.narg.backquote = backquotelist;
12226 expandarg(&n, NULL, EXP_QUOTED);
12227 return stackblock();
12232 * Execute a command or commands contained in a string.
12235 evalstring(char *s, int mask)
12238 struct stackmark smark;
12243 setstackmark(&smark);
12246 while ((n = parsecmd(0)) != NODE_EOF) {
12249 i = evaltree(n, 0);
12252 popstackmark(&smark);
12256 popstackmark(&smark);
12265 * The eval command.
12267 static int FAST_FUNC
12268 evalcmd(int argc UNUSED_PARAM, char **argv)
12277 STARTSTACKSTR(concat);
12279 concat = stack_putstr(p, concat);
12283 STPUTC(' ', concat);
12285 STPUTC('\0', concat);
12286 p = grabstackstr(concat);
12288 return evalstring(p, ~SKIPEVAL);
12294 * Read and execute commands.
12295 * "Top" is nonzero for the top level command loop;
12296 * it turns on prompting if the shell is interactive.
12302 struct stackmark smark;
12307 TRACE(("cmdloop(%d) called\n", top));
12311 setstackmark(&smark);
12314 showjobs(SHOW_CHANGED|SHOW_STDERR);
12317 if (iflag && top) {
12321 n = parsecmd(inter);
12323 if (DEBUG > 2 && debug && (n != NODE_EOF))
12326 if (n == NODE_EOF) {
12327 if (!top || numeof >= 50)
12329 if (!stoppedjobs()) {
12332 out2str("\nUse \"exit\" to leave shell.\n");
12335 } else if (nflag == 0) {
12338 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12341 i = evaltree(n, 0);
12345 popstackmark(&smark);
12350 return skip & SKIPEVAL;
12357 * Take commands from a file. To be compatible we should do a path
12358 * search for the file, which is necessary to find sub-commands.
12361 find_dot_file(char *name)
12364 const char *path = pathval();
12367 /* don't try this for absolute or relative paths */
12368 if (strchr(name, '/'))
12371 /* IIRC standards do not say whether . is to be searched.
12372 * And it is even smaller this way, making it unconditional for now:
12374 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12379 while ((fullname = path_advance(&path, name)) != NULL) {
12381 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12383 * Don't bother freeing here, since it will
12384 * be freed by the caller.
12388 if (fullname != name)
12389 stunalloc(fullname);
12392 /* not found in the PATH */
12393 ash_msg_and_raise_error("%s: not found", name);
12397 static int FAST_FUNC
12398 dotcmd(int argc, char **argv)
12401 struct strlist *sp;
12402 volatile struct shparam saveparam;
12404 for (sp = cmdenviron; sp; sp = sp->next)
12405 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12408 /* bash says: "bash: .: filename argument required" */
12409 return 2; /* bash compat */
12412 /* "false; . empty_file; echo $?" should print 0, not 1: */
12415 /* This aborts if file isn't found, which is POSIXly correct.
12416 * bash returns exitcode 1 instead.
12418 fullname = find_dot_file(argv[1]);
12421 if (argc) { /* argc > 0, argv[0] != NULL */
12422 saveparam = shellparam;
12423 shellparam.malloced = 0;
12424 shellparam.nparam = argc;
12425 shellparam.p = argv;
12428 /* This aborts if file can't be opened, which is POSIXly correct.
12429 * bash returns exitcode 1 instead.
12431 setinputfile(fullname, INPUT_PUSH_FILE);
12432 commandname = fullname;
12437 freeparam(&shellparam);
12438 shellparam = saveparam;
12444 static int FAST_FUNC
12445 exitcmd(int argc UNUSED_PARAM, char **argv)
12450 exitstatus = number(argv[1]);
12451 raise_exception(EXEXIT);
12456 * Read a file containing shell functions.
12459 readcmdfile(char *name)
12461 setinputfile(name, INPUT_PUSH_FILE);
12467 /* ============ find_command inplementation */
12470 * Resolve a command name. If you change this routine, you may have to
12471 * change the shellexec routine as well.
12474 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12476 struct tblentry *cmdp;
12483 struct builtincmd *bcmd;
12485 /* If name contains a slash, don't use PATH or hash table */
12486 if (strchr(name, '/') != NULL) {
12487 entry->u.index = -1;
12488 if (act & DO_ABS) {
12489 while (stat(name, &statb) < 0) {
12491 if (errno == EINTR)
12494 entry->cmdtype = CMDUNKNOWN;
12498 entry->cmdtype = CMDNORMAL;
12502 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12504 updatetbl = (path == pathval());
12507 if (strstr(path, "%builtin") != NULL)
12508 act |= DO_ALTBLTIN;
12511 /* If name is in the table, check answer will be ok */
12512 cmdp = cmdlookup(name, 0);
12513 if (cmdp != NULL) {
12516 switch (cmdp->cmdtype) {
12534 } else if (cmdp->rehash == 0)
12535 /* if not invalidated by cd, we're done */
12539 /* If %builtin not in path, check for builtin next */
12540 bcmd = find_builtin(name);
12542 if (IS_BUILTIN_REGULAR(bcmd))
12543 goto builtin_success;
12544 if (act & DO_ALTPATH) {
12545 if (!(act & DO_ALTBLTIN))
12546 goto builtin_success;
12547 } else if (builtinloc <= 0) {
12548 goto builtin_success;
12552 #if ENABLE_FEATURE_SH_STANDALONE
12554 int applet_no = find_applet_by_name(name);
12555 if (applet_no >= 0) {
12556 entry->cmdtype = CMDNORMAL;
12557 entry->u.index = -2 - applet_no;
12563 /* We have to search path. */
12564 prev = -1; /* where to start */
12565 if (cmdp && cmdp->rehash) { /* doing a rehash */
12566 if (cmdp->cmdtype == CMDBUILTIN)
12569 prev = cmdp->param.index;
12575 while ((fullname = path_advance(&path, name)) != NULL) {
12576 stunalloc(fullname);
12577 /* NB: code below will still use fullname
12578 * despite it being "unallocated" */
12581 if (prefix(pathopt, "builtin")) {
12583 goto builtin_success;
12586 if ((act & DO_NOFUNC)
12587 || !prefix(pathopt, "func")
12588 ) { /* ignore unimplemented options */
12592 /* if rehash, don't redo absolute path names */
12593 if (fullname[0] == '/' && idx <= prev) {
12596 TRACE(("searchexec \"%s\": no change\n", name));
12599 while (stat(fullname, &statb) < 0) {
12601 if (errno == EINTR)
12604 if (errno != ENOENT && errno != ENOTDIR)
12608 e = EACCES; /* if we fail, this will be the error */
12609 if (!S_ISREG(statb.st_mode))
12611 if (pathopt) { /* this is a %func directory */
12612 stalloc(strlen(fullname) + 1);
12613 /* NB: stalloc will return space pointed by fullname
12614 * (because we don't have any intervening allocations
12615 * between stunalloc above and this stalloc) */
12616 readcmdfile(fullname);
12617 cmdp = cmdlookup(name, 0);
12618 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12619 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12620 stunalloc(fullname);
12623 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12625 entry->cmdtype = CMDNORMAL;
12626 entry->u.index = idx;
12630 cmdp = cmdlookup(name, 1);
12631 cmdp->cmdtype = CMDNORMAL;
12632 cmdp->param.index = idx;
12637 /* We failed. If there was an entry for this command, delete it */
12638 if (cmdp && updatetbl)
12639 delete_cmd_entry();
12641 ash_msg("%s: %s", name, errmsg(e, "not found"));
12642 entry->cmdtype = CMDUNKNOWN;
12647 entry->cmdtype = CMDBUILTIN;
12648 entry->u.cmd = bcmd;
12652 cmdp = cmdlookup(name, 1);
12653 cmdp->cmdtype = CMDBUILTIN;
12654 cmdp->param.cmd = bcmd;
12658 entry->cmdtype = cmdp->cmdtype;
12659 entry->u = cmdp->param;
12663 /* ============ trap.c */
12666 * The trap builtin.
12668 static int FAST_FUNC
12669 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12673 int signo, exitcode;
12678 for (signo = 0; signo < NSIG; signo++) {
12679 char *tr = trap_ptr[signo];
12681 /* note: bash adds "SIG", but only if invoked
12682 * as "bash". If called as "sh", or if set -o posix,
12683 * then it prints short signal names.
12684 * We are printing short names: */
12685 out1fmt("trap -- %s %s\n",
12687 get_signame(signo));
12688 /* trap_ptr != trap only if we are in special-cased `trap` code.
12689 * In this case, we will exit very soon, no need to free(). */
12690 /* if (trap_ptr != trap && tp[0]) */
12695 if (trap_ptr != trap) {
12708 signo = get_signum(*ap);
12710 /* Mimic bash message exactly */
12711 ash_msg("%s: invalid signal specification", *ap);
12717 if (LONE_DASH(action))
12720 action = ckstrdup(action);
12724 may_have_traps = 1;
12725 trap[signo] = action;
12736 /* ============ Builtins */
12738 #if ENABLE_ASH_HELP
12739 static int FAST_FUNC
12740 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12746 "Built-in commands:\n"
12747 "------------------\n");
12748 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12749 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12750 builtintab[i].name + 1);
12756 # if ENABLE_FEATURE_SH_STANDALONE
12758 const char *a = applet_names;
12760 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12765 while (*a++ != '\0')
12771 return EXIT_SUCCESS;
12776 static int FAST_FUNC
12777 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12779 show_history(line_input_state);
12780 return EXIT_SUCCESS;
12785 * The export and readonly commands.
12787 static int FAST_FUNC
12788 exportcmd(int argc UNUSED_PARAM, char **argv)
12798 /* "readonly" in bash accepts, but ignores -n.
12799 * We do the same: it saves a conditional in nextopt's param.
12802 while ((opt = nextopt("np")) != '\0') {
12804 flag_off = VEXPORT;
12807 if (argv[0][0] == 'r') {
12809 flag_off = 0; /* readonly ignores -n */
12811 flag_off = ~flag_off;
12813 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12819 p = strchr(name, '=');
12823 vp = *findvar(hashvar(name), name);
12825 vp->flags = ((vp->flags | flag) & flag_off);
12829 setvar(name, p, (flag & flag_off));
12830 } while ((name = *++aptr) != NULL);
12835 /* No arguments. Show the list of exported or readonly vars.
12838 showvars(argv[0], flag, 0);
12843 * Delete a function if it exists.
12846 unsetfunc(const char *name)
12848 struct tblentry *cmdp;
12850 cmdp = cmdlookup(name, 0);
12851 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12852 delete_cmd_entry();
12856 * The unset builtin command. We unset the function before we unset the
12857 * variable to allow a function to be unset when there is a readonly variable
12858 * with the same name.
12860 static int FAST_FUNC
12861 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12868 while ((i = nextopt("vf")) != 0) {
12872 for (ap = argptr; *ap; ap++) {
12885 static const unsigned char timescmd_str[] ALIGN1 = {
12886 ' ', offsetof(struct tms, tms_utime),
12887 '\n', offsetof(struct tms, tms_stime),
12888 ' ', offsetof(struct tms, tms_cutime),
12889 '\n', offsetof(struct tms, tms_cstime),
12892 static int FAST_FUNC
12893 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12895 unsigned long clk_tck, s, t;
12896 const unsigned char *p;
12899 clk_tck = bb_clk_tck();
12904 t = *(clock_t *)(((char *) &buf) + p[1]);
12907 out1fmt("%lum%lu.%03lus%c",
12909 (t * 1000) / clk_tck,
12917 #if ENABLE_SH_MATH_SUPPORT
12919 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12920 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12922 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12924 static int FAST_FUNC
12925 letcmd(int argc UNUSED_PARAM, char **argv)
12931 ash_msg_and_raise_error("expression expected");
12933 i = ash_arith(*argv);
12941 * The read builtin. Options:
12942 * -r Do not interpret '\' specially
12943 * -s Turn off echo (tty only)
12944 * -n NCHARS Read NCHARS max
12945 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12946 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12947 * -u FD Read from given FD instead of fd 0
12948 * This uses unbuffered input, which may be avoidable in some cases.
12949 * TODO: bash also has:
12950 * -a ARRAY Read into array[0],[1],etc
12951 * -d DELIM End on DELIM char, not newline
12952 * -e Use line editing (tty only)
12954 static int FAST_FUNC
12955 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12957 char *opt_n = NULL;
12958 char *opt_p = NULL;
12959 char *opt_t = NULL;
12960 char *opt_u = NULL;
12961 int read_flags = 0;
12965 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12974 read_flags |= BUILTIN_READ_SILENT;
12980 read_flags |= BUILTIN_READ_RAW;
12990 /* "read -s" needs to save/restore termios, can't allow ^C
12991 * to jump out of it.
12994 r = shell_builtin_read(setvar0,
12996 bltinlookup("IFS"), /* can be NULL */
13005 if ((uintptr_t)r > 1)
13006 ash_msg_and_raise_error(r);
13008 return (uintptr_t)r;
13011 static int FAST_FUNC
13012 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13014 static const char permuser[3] ALIGN1 = "ogu";
13017 int symbolic_mode = 0;
13019 while (nextopt("S") != '\0') {
13028 if (*argptr == NULL) {
13029 if (symbolic_mode) {
13030 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13037 *p++ = permuser[i];
13039 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13040 if (!(mask & 0400)) *p++ = 'r';
13041 if (!(mask & 0200)) *p++ = 'w';
13042 if (!(mask & 0100)) *p++ = 'x';
13050 out1fmt("%04o\n", mask);
13053 char *modestr = *argptr;
13054 /* numeric umasks are taken as-is */
13055 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13056 if (!isdigit(modestr[0]))
13058 mask = bb_parse_mode(modestr, mask);
13059 if ((unsigned)mask > 0777) {
13060 ash_msg_and_raise_error("illegal mode: %s", modestr);
13062 if (!isdigit(modestr[0]))
13069 static int FAST_FUNC
13070 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13072 return shell_builtin_ulimit(argv);
13075 /* ============ main() and helpers */
13078 * Called to exit the shell.
13087 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13088 save_history(line_input_state);
13091 status = exitstatus;
13092 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13093 if (setjmp(loc.loc)) {
13094 if (exception_type == EXEXIT)
13095 /* dash bug: it just does _exit(exitstatus) here
13096 * but we have to do setjobctl(0) first!
13097 * (bug is still not fixed in dash-0.5.3 - if you run dash
13098 * under Midnight Commander, on exit from dash MC is backgrounded) */
13099 status = exitstatus;
13102 exception_handler = &loc;
13109 flush_stdout_stderr();
13119 /* from input.c: */
13120 /* we will never free this */
13121 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13124 signal(SIGCHLD, SIG_DFL);
13125 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13126 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13128 signal(SIGHUP, SIG_DFL);
13134 struct stat st1, st2;
13137 for (envp = environ; envp && *envp; envp++) {
13138 if (strchr(*envp, '=')) {
13139 setvareq(*envp, VEXPORT|VTEXTFIXED);
13143 setvar0("PPID", utoa(getppid()));
13144 #if ENABLE_ASH_BASH_COMPAT
13145 p = lookupvar("SHLVL");
13146 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13147 if (!lookupvar("HOSTNAME")) {
13148 struct utsname uts;
13150 setvar0("HOSTNAME", uts.nodename);
13153 p = lookupvar("PWD");
13155 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13156 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13166 //usage:#define ash_trivial_usage
13167 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13168 //usage:#define ash_full_usage "\n\n"
13169 //usage: "Unix shell interpreter"
13171 //usage:#if ENABLE_FEATURE_SH_IS_ASH
13172 //usage:# define sh_trivial_usage ash_trivial_usage
13173 //usage:# define sh_full_usage ash_full_usage
13175 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
13176 //usage:# define bash_trivial_usage ash_trivial_usage
13177 //usage:# define bash_full_usage ash_full_usage
13181 * Process the shell command line arguments.
13184 procargs(char **argv)
13187 const char *xminusc;
13192 /* if (xargv[0]) - mmm, this is always true! */
13194 for (i = 0; i < NOPTS; i++)
13197 if (options(/*cmdline:*/ 1)) {
13198 /* it already printed err message */
13199 raise_exception(EXERROR);
13203 if (*xargv == NULL) {
13205 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13208 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13212 for (i = 0; i < NOPTS; i++)
13213 if (optlist[i] == 2)
13218 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13223 } else if (!sflag) {
13224 setinputfile(*xargv, 0);
13227 commandname = arg0;
13230 shellparam.p = xargv;
13231 #if ENABLE_ASH_GETOPTS
13232 shellparam.optind = 1;
13233 shellparam.optoff = -1;
13235 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13237 shellparam.nparam++;
13244 * Read /etc/profile or .profile.
13247 read_profile(const char *name)
13251 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13260 * This routine is called when an error or an interrupt occurs in an
13261 * interactive shell and control is returned to the main command loop.
13269 /* from input.c: */
13270 g_parsefile->left_in_buffer = 0;
13271 g_parsefile->left_in_line = 0; /* clear input buffer */
13273 /* from parser.c: */
13276 /* from redir.c: */
13277 clearredir(/*drop:*/ 0);
13281 static short profile_buf[16384];
13282 extern int etext();
13286 * Main routine. We initialize things, parse the arguments, execute
13287 * profiles if we're a login shell, and then call cmdloop to execute
13288 * commands. The setjmp call sets up the location to jump to when an
13289 * exception occurs. When an exception occurs the variable "state"
13290 * is used to figure out how far we had gotten.
13292 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13293 int ash_main(int argc UNUSED_PARAM, char **argv)
13295 const char *shinit;
13296 volatile smallint state;
13297 struct jmploc jmploc;
13298 struct stackmark smark;
13300 /* Initialize global data */
13304 #if ENABLE_ASH_ALIAS
13310 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13313 #if ENABLE_FEATURE_EDITING
13314 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13317 if (setjmp(jmploc.loc)) {
13323 e = exception_type;
13327 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13331 newline_and_flush(stderr);
13334 popstackmark(&smark);
13335 FORCE_INT_ON; /* enable interrupts */
13344 exception_handler = &jmploc;
13347 TRACE(("Shell args: "));
13348 trace_puts_args(argv);
13350 rootpid = getpid();
13353 setstackmark(&smark);
13356 if (argv[0] && argv[0][0] == '-')
13362 read_profile("/etc/profile");
13365 hp = lookupvar("HOME");
13367 hp = concat_path_file(hp, ".profile");
13376 getuid() == geteuid() && getgid() == getegid() &&
13380 shinit = lookupvar("ENV");
13381 if (shinit != NULL && *shinit != '\0') {
13382 read_profile(shinit);
13388 /* evalstring pushes parsefile stack.
13389 * Ensure we don't falsely claim that 0 (stdin)
13390 * is one of stacked source fds.
13391 * Testcase: ash -c 'exec 1>&0' must not complain. */
13392 // if (!sflag) g_parsefile->pf_fd = -1;
13393 // ^^ not necessary since now we special-case fd 0
13394 // in is_hidden_fd() to not be considered "hidden fd"
13395 evalstring(minusc, 0);
13398 if (sflag || minusc == NULL) {
13399 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13401 const char *hp = lookupvar("HISTFILE");
13403 hp = lookupvar("HOME");
13405 hp = concat_path_file(hp, ".ash_history");
13406 setvar0("HISTFILE", hp);
13408 hp = lookupvar("HISTFILE");
13412 line_input_state->hist_file = hp;
13413 # if ENABLE_FEATURE_SH_HISTFILESIZE
13414 hp = lookupvar("HISTFILESIZE");
13415 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13419 state4: /* XXX ??? - why isn't this before the "if" statement */
13427 extern void _mcleanup(void);
13431 TRACE(("End of main reached\n"));
13438 * Copyright (c) 1989, 1991, 1993, 1994
13439 * The Regents of the University of California. All rights reserved.
13441 * This code is derived from software contributed to Berkeley by
13442 * Kenneth Almquist.
13444 * Redistribution and use in source and binary forms, with or without
13445 * modification, are permitted provided that the following conditions
13447 * 1. Redistributions of source code must retain the above copyright
13448 * notice, this list of conditions and the following disclaimer.
13449 * 2. Redistributions in binary form must reproduce the above copyright
13450 * notice, this list of conditions and the following disclaimer in the
13451 * documentation and/or other materials provided with the distribution.
13452 * 3. Neither the name of the University nor the names of its contributors
13453 * may be used to endorse or promote products derived from this software
13454 * without specific prior written permission.
13456 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13457 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13458 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13459 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13460 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13461 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13462 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13463 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13464 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13465 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF