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;
1377 struct globals_memstack {
1378 struct stack_block *g_stackp; // = &stackbase;
1379 char *g_stacknxt; // = stackbase.space;
1380 char *sstrend; // = stackbase.space + MINSIZE;
1381 size_t g_stacknleft; // = MINSIZE;
1382 int herefd; // = -1;
1383 struct stack_block stackbase;
1385 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1386 #define G_memstack (*ash_ptr_to_globals_memstack)
1387 #define g_stackp (G_memstack.g_stackp )
1388 #define g_stacknxt (G_memstack.g_stacknxt )
1389 #define sstrend (G_memstack.sstrend )
1390 #define g_stacknleft (G_memstack.g_stacknleft)
1391 #define herefd (G_memstack.herefd )
1392 #define stackbase (G_memstack.stackbase )
1393 #define INIT_G_memstack() do { \
1394 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1396 g_stackp = &stackbase; \
1397 g_stacknxt = stackbase.space; \
1398 g_stacknleft = MINSIZE; \
1399 sstrend = stackbase.space + MINSIZE; \
1404 #define stackblock() ((void *)g_stacknxt)
1405 #define stackblocksize() g_stacknleft
1408 * Parse trees for commands are allocated in lifo order, so we use a stack
1409 * to make this more efficient, and also to avoid all sorts of exception
1410 * handling code to handle interrupts in the middle of a parse.
1412 * The size 504 was chosen because the Ultrix malloc handles that size
1416 stalloc(size_t nbytes)
1421 aligned = SHELL_ALIGN(nbytes);
1422 if (aligned > g_stacknleft) {
1425 struct stack_block *sp;
1427 blocksize = aligned;
1428 if (blocksize < MINSIZE)
1429 blocksize = MINSIZE;
1430 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1431 if (len < blocksize)
1432 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1435 sp->prev = g_stackp;
1436 g_stacknxt = sp->space;
1437 g_stacknleft = blocksize;
1438 sstrend = g_stacknxt + blocksize;
1443 g_stacknxt += aligned;
1444 g_stacknleft -= aligned;
1449 stzalloc(size_t nbytes)
1451 return memset(stalloc(nbytes), 0, nbytes);
1458 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1459 write(STDERR_FILENO, "stunalloc\n", 10);
1463 g_stacknleft += g_stacknxt - (char *)p;
1468 * Like strdup but works with the ash stack.
1471 sstrdup(const char *p)
1473 size_t len = strlen(p) + 1;
1474 return memcpy(stalloc(len), p, len);
1478 grabstackblock(size_t len)
1480 len = SHELL_ALIGN(len);
1482 g_stacknleft -= len;
1486 pushstackmark(struct stackmark *mark, size_t len)
1488 mark->stackp = g_stackp;
1489 mark->stacknxt = g_stacknxt;
1490 mark->stacknleft = g_stacknleft;
1491 grabstackblock(len);
1495 setstackmark(struct stackmark *mark)
1497 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1501 popstackmark(struct stackmark *mark)
1503 struct stack_block *sp;
1509 while (g_stackp != mark->stackp) {
1511 g_stackp = sp->prev;
1514 g_stacknxt = mark->stacknxt;
1515 g_stacknleft = mark->stacknleft;
1516 sstrend = mark->stacknxt + mark->stacknleft;
1521 * When the parser reads in a string, it wants to stick the string on the
1522 * stack and only adjust the stack pointer when it knows how big the
1523 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1524 * of space on top of the stack and stackblocklen returns the length of
1525 * this block. Growstackblock will grow this space by at least one byte,
1526 * possibly moving it (like realloc). Grabstackblock actually allocates the
1527 * part of the block that has been used.
1530 growstackblock(void)
1534 newlen = g_stacknleft * 2;
1535 if (newlen < g_stacknleft)
1536 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1540 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1541 struct stack_block *sp;
1542 struct stack_block *prevstackp;
1547 prevstackp = sp->prev;
1548 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1549 sp = ckrealloc(sp, grosslen);
1550 sp->prev = prevstackp;
1552 g_stacknxt = sp->space;
1553 g_stacknleft = newlen;
1554 sstrend = sp->space + newlen;
1557 char *oldspace = g_stacknxt;
1558 size_t oldlen = g_stacknleft;
1559 char *p = stalloc(newlen);
1561 /* free the space we just allocated */
1562 g_stacknxt = memcpy(p, oldspace, oldlen);
1563 g_stacknleft += newlen;
1568 * The following routines are somewhat easier to use than the above.
1569 * The user declares a variable of type STACKSTR, which may be declared
1570 * to be a register. The macro STARTSTACKSTR initializes things. Then
1571 * the user uses the macro STPUTC to add characters to the string. In
1572 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1573 * grown as necessary. When the user is done, she can just leave the
1574 * string there and refer to it using stackblock(). Or she can allocate
1575 * the space for it using grabstackstr(). If it is necessary to allow
1576 * someone else to use the stack temporarily and then continue to grow
1577 * the string, the user should use grabstack to allocate the space, and
1578 * then call ungrabstr(p) to return to the previous mode of operation.
1580 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1581 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1582 * is space for at least one character.
1587 size_t len = stackblocksize();
1588 if (herefd >= 0 && len >= 1024) {
1589 full_write(herefd, stackblock(), len);
1590 return stackblock();
1593 return (char *)stackblock() + len;
1597 * Called from CHECKSTRSPACE.
1600 makestrspace(size_t newlen, char *p)
1602 size_t len = p - g_stacknxt;
1608 size = stackblocksize();
1610 if (nleft >= newlen)
1614 return (char *)stackblock() + len;
1618 stack_nputstr(const char *s, size_t n, char *p)
1620 p = makestrspace(n, p);
1621 p = (char *)memcpy(p, s, n) + n;
1626 stack_putstr(const char *s, char *p)
1628 return stack_nputstr(s, strlen(s), p);
1632 _STPUTC(int c, char *p)
1640 #define STARTSTACKSTR(p) ((p) = stackblock())
1641 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1642 #define CHECKSTRSPACE(n, p) do { \
1645 size_t m = sstrend - q; \
1647 (p) = makestrspace(l, q); \
1649 #define USTPUTC(c, p) (*(p)++ = (c))
1650 #define STACKSTRNUL(p) do { \
1651 if ((p) == sstrend) \
1652 (p) = growstackstr(); \
1655 #define STUNPUTC(p) (--(p))
1656 #define STTOPC(p) ((p)[-1])
1657 #define STADJUST(amount, p) ((p) += (amount))
1659 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1660 #define ungrabstackstr(s, p) stunalloc(s)
1661 #define stackstrend() ((void *)sstrend)
1664 /* ============ String helpers */
1667 * prefix -- see if pfx is a prefix of string.
1670 prefix(const char *string, const char *pfx)
1673 if (*pfx++ != *string++)
1676 return (char *) string;
1680 * Check for a valid number. This should be elsewhere.
1683 is_number(const char *p)
1688 } while (*++p != '\0');
1693 * Convert a string of digits to an integer, printing an error message on
1697 number(const char *s)
1700 ash_msg_and_raise_error(msg_illnum, s);
1705 * Produce a possibly single quoted string suitable as input to the shell.
1706 * The return string is allocated on the stack.
1709 single_quote(const char *s)
1719 len = strchrnul(s, '\'') - s;
1721 q = p = makestrspace(len + 3, p);
1724 q = (char *)memcpy(q, s, len) + len;
1733 do len++; while (*++s == '\'');
1735 q = p = makestrspace(len + 3, p);
1738 q = (char *)memcpy(q, s - len, len) + len;
1746 return stackblock();
1750 /* ============ nextopt */
1752 static char **argptr; /* argument list for builtin commands */
1753 static char *optionarg; /* set by nextopt (like getopt) */
1754 static char *optptr; /* used by nextopt */
1757 * XXX - should get rid of. Have all builtins use getopt(3).
1758 * The library getopt must have the BSD extension static variable
1759 * "optreset", otherwise it can't be used within the shell safely.
1761 * Standard option processing (a la getopt) for builtin routines.
1762 * The only argument that is passed to nextopt is the option string;
1763 * the other arguments are unnecessary. It returns the character,
1764 * or '\0' on end of input.
1767 nextopt(const char *optstring)
1774 if (p == NULL || *p == '\0') {
1775 /* We ate entire "-param", take next one */
1781 if (*++p == '\0') /* just "-" ? */
1784 if (LONE_DASH(p)) /* "--" ? */
1786 /* p => next "-param" */
1788 /* p => some option char in the middle of a "-param" */
1790 for (q = optstring; *q != c;) {
1792 ash_msg_and_raise_error("illegal option -%c", c);
1800 ash_msg_and_raise_error("no arg for -%c option", c);
1810 /* ============ Shell variables */
1813 * The parsefile structure pointed to by the global variable parsefile
1814 * contains information about the current file being read.
1817 int nparam; /* # of positional parameters (without $0) */
1818 #if ENABLE_ASH_GETOPTS
1819 int optind; /* next parameter to be processed by getopts */
1820 int optoff; /* used by getopts */
1822 unsigned char malloced; /* if parameter list dynamically allocated */
1823 char **p; /* parameter list */
1827 * Free the list of positional parameters.
1830 freeparam(volatile struct shparam *param)
1832 if (param->malloced) {
1834 ap = ap1 = param->p;
1841 #if ENABLE_ASH_GETOPTS
1842 static void FAST_FUNC getoptsreset(const char *value);
1846 struct var *next; /* next entry in hash list */
1847 int flags; /* flags are defined above */
1848 const char *var_text; /* name=value */
1849 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1850 /* the variable gets set/unset */
1854 struct localvar *next; /* next local variable in list */
1855 struct var *vp; /* the variable that was made local */
1856 int flags; /* saved flags */
1857 const char *text; /* saved text */
1861 #define VEXPORT 0x01 /* variable is exported */
1862 #define VREADONLY 0x02 /* variable cannot be modified */
1863 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1864 #define VTEXTFIXED 0x08 /* text is statically allocated */
1865 #define VSTACK 0x10 /* text is allocated on the stack */
1866 #define VUNSET 0x20 /* the variable is not set */
1867 #define VNOFUNC 0x40 /* don't call the callback function */
1868 #define VNOSET 0x80 /* do not set variable - just readonly test */
1869 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1870 #if ENABLE_ASH_RANDOM_SUPPORT
1871 # define VDYNAMIC 0x200 /* dynamic variable */
1877 /* Need to be before varinit_data[] */
1878 #if ENABLE_LOCALE_SUPPORT
1879 static void FAST_FUNC
1880 change_lc_all(const char *value)
1882 if (value && *value != '\0')
1883 setlocale(LC_ALL, value);
1885 static void FAST_FUNC
1886 change_lc_ctype(const char *value)
1888 if (value && *value != '\0')
1889 setlocale(LC_CTYPE, value);
1893 static void chkmail(void);
1894 static void changemail(const char *var_value) FAST_FUNC;
1896 # define chkmail() ((void)0)
1898 static void changepath(const char *) FAST_FUNC;
1899 #if ENABLE_ASH_RANDOM_SUPPORT
1900 static void change_random(const char *) FAST_FUNC;
1903 static const struct {
1905 const char *var_text;
1906 void (*var_func)(const char *) FAST_FUNC;
1907 } varinit_data[] = {
1909 * Note: VEXPORT would not work correctly here for NOFORK applets:
1910 * some environment strings may be constant.
1912 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1914 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1915 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1917 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1918 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1919 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1920 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1921 #if ENABLE_ASH_GETOPTS
1922 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1924 #if ENABLE_ASH_RANDOM_SUPPORT
1925 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1927 #if ENABLE_LOCALE_SUPPORT
1928 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1929 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1931 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1932 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1938 struct globals_var {
1939 struct shparam shellparam; /* $@ current positional parameters */
1940 struct redirtab *redirlist;
1942 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1943 struct var *vartab[VTABSIZE];
1944 struct var varinit[ARRAY_SIZE(varinit_data)];
1946 extern struct globals_var *const ash_ptr_to_globals_var;
1947 #define G_var (*ash_ptr_to_globals_var)
1948 #define shellparam (G_var.shellparam )
1949 //#define redirlist (G_var.redirlist )
1950 #define g_nullredirs (G_var.g_nullredirs )
1951 #define preverrout_fd (G_var.preverrout_fd)
1952 #define vartab (G_var.vartab )
1953 #define varinit (G_var.varinit )
1954 #define INIT_G_var() do { \
1956 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1958 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1959 varinit[i].flags = varinit_data[i].flags; \
1960 varinit[i].var_text = varinit_data[i].var_text; \
1961 varinit[i].var_func = varinit_data[i].var_func; \
1965 #define vifs varinit[0]
1967 # define vmail (&vifs)[1]
1968 # define vmpath (&vmail)[1]
1969 # define vpath (&vmpath)[1]
1971 # define vpath (&vifs)[1]
1973 #define vps1 (&vpath)[1]
1974 #define vps2 (&vps1)[1]
1975 #define vps4 (&vps2)[1]
1976 #if ENABLE_ASH_GETOPTS
1977 # define voptind (&vps4)[1]
1978 # if ENABLE_ASH_RANDOM_SUPPORT
1979 # define vrandom (&voptind)[1]
1982 # if ENABLE_ASH_RANDOM_SUPPORT
1983 # define vrandom (&vps4)[1]
1988 * The following macros access the values of the above variables.
1989 * They have to skip over the name. They return the null string
1990 * for unset variables.
1992 #define ifsval() (vifs.var_text + 4)
1993 #define ifsset() ((vifs.flags & VUNSET) == 0)
1995 # define mailval() (vmail.var_text + 5)
1996 # define mpathval() (vmpath.var_text + 9)
1997 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1999 #define pathval() (vpath.var_text + 5)
2000 #define ps1val() (vps1.var_text + 4)
2001 #define ps2val() (vps2.var_text + 4)
2002 #define ps4val() (vps4.var_text + 4)
2003 #if ENABLE_ASH_GETOPTS
2004 # define optindval() (voptind.var_text + 7)
2007 #if ENABLE_ASH_GETOPTS
2008 static void FAST_FUNC
2009 getoptsreset(const char *value)
2011 shellparam.optind = number(value);
2012 shellparam.optoff = -1;
2017 * Compares two strings up to the first = or '\0'. The first
2018 * string must be terminated by '='; the second may be terminated by
2019 * either '=' or '\0'.
2022 varcmp(const char *p, const char *q)
2026 while ((c = *p) == (d = *q)) {
2027 if (c == '\0' || c == '=')
2041 * Find the appropriate entry in the hash table from the name.
2043 static struct var **
2044 hashvar(const char *p)
2048 hashval = ((unsigned char) *p) << 4;
2049 while (*p && *p != '=')
2050 hashval += (unsigned char) *p++;
2051 return &vartab[hashval % VTABSIZE];
2055 vpcmp(const void *a, const void *b)
2057 return varcmp(*(const char **)a, *(const char **)b);
2061 * This routine initializes the builtin variables.
2071 * PS1 depends on uid
2073 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2074 vps1.var_text = "PS1=\\w \\$ ";
2077 vps1.var_text = "PS1=# ";
2080 end = vp + ARRAY_SIZE(varinit);
2082 vpp = hashvar(vp->var_text);
2085 } while (++vp < end);
2088 static struct var **
2089 findvar(struct var **vpp, const char *name)
2091 for (; *vpp; vpp = &(*vpp)->next) {
2092 if (varcmp((*vpp)->var_text, name) == 0) {
2100 * Find the value of a variable. Returns NULL if not set.
2102 static const char* FAST_FUNC
2103 lookupvar(const char *name)
2107 v = *findvar(hashvar(name), name);
2109 #if ENABLE_ASH_RANDOM_SUPPORT
2111 * Dynamic variables are implemented roughly the same way they are
2112 * in bash. Namely, they're "special" so long as they aren't unset.
2113 * As soon as they're unset, they're no longer dynamic, and dynamic
2114 * lookup will no longer happen at that point. -- PFM.
2116 if (v->flags & VDYNAMIC)
2119 if (!(v->flags & VUNSET))
2120 return var_end(v->var_text);
2125 static void reinit_unicode_for_ash(void)
2127 /* Unicode support should be activated even if LANG is set
2128 * _during_ shell execution, not only if it was set when
2129 * shell was started. Therefore, re-check LANG every time:
2131 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2132 || ENABLE_UNICODE_USING_LOCALE
2134 const char *s = lookupvar("LC_ALL");
2135 if (!s) s = lookupvar("LC_CTYPE");
2136 if (!s) s = lookupvar("LANG");
2142 * Search the environment of a builtin command.
2145 bltinlookup(const char *name)
2149 for (sp = cmdenviron; sp; sp = sp->next) {
2150 if (varcmp(sp->text, name) == 0)
2151 return var_end(sp->text);
2153 return lookupvar(name);
2157 * Same as setvar except that the variable and value are passed in
2158 * the first argument as name=value. Since the first argument will
2159 * be actually stored in the table, it should not be a string that
2161 * Called with interrupts off.
2164 setvareq(char *s, int flags)
2166 struct var *vp, **vpp;
2169 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2170 vp = *findvar(vpp, s);
2172 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2175 if (flags & VNOSAVE)
2178 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2184 if (vp->var_func && !(flags & VNOFUNC))
2185 vp->var_func(var_end(s));
2187 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2188 free((char*)vp->var_text);
2190 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2192 /* variable s is not found */
2195 vp = ckzalloc(sizeof(*vp));
2197 /*vp->func = NULL; - ckzalloc did it */
2200 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2207 * Set the value of a variable. The flags argument is ored with the
2208 * flags of the variable. If val is NULL, the variable is unset.
2211 setvar(const char *name, const char *val, int flags)
2219 q = endofname(name);
2220 p = strchrnul(q, '=');
2222 if (!namelen || p != q)
2223 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2228 vallen = strlen(val);
2232 nameeq = ckmalloc(namelen + vallen + 2);
2233 p = memcpy(nameeq, name, namelen) + namelen;
2236 p = memcpy(p, val, vallen) + vallen;
2239 setvareq(nameeq, flags | VNOSAVE);
2243 static void FAST_FUNC
2244 setvar0(const char *name, const char *val)
2246 setvar(name, val, 0);
2249 #if ENABLE_ASH_GETOPTS
2251 * Safe version of setvar, returns 1 on success 0 on failure.
2254 setvarsafe(const char *name, const char *val, int flags)
2257 volatile int saveint;
2258 struct jmploc *volatile savehandler = exception_handler;
2259 struct jmploc jmploc;
2262 if (setjmp(jmploc.loc))
2265 exception_handler = &jmploc;
2266 setvar(name, val, flags);
2269 exception_handler = savehandler;
2270 RESTORE_INT(saveint);
2276 * Unset the specified variable.
2279 unsetvar(const char *s)
2285 vpp = findvar(hashvar(s), s);
2289 int flags = vp->flags;
2292 if (flags & VREADONLY)
2294 #if ENABLE_ASH_RANDOM_SUPPORT
2295 vp->flags &= ~VDYNAMIC;
2299 if ((flags & VSTRFIXED) == 0) {
2301 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2302 free((char*)vp->var_text);
2308 vp->flags &= ~VEXPORT;
2318 * Process a linked list of variable assignments.
2321 listsetvar(struct strlist *list_set_var, int flags)
2323 struct strlist *lp = list_set_var;
2329 setvareq(lp->text, flags);
2336 * Generate a list of variables satisfying the given conditions.
2339 listvars(int on, int off, char ***end)
2350 for (vp = *vpp; vp; vp = vp->next) {
2351 if ((vp->flags & mask) == on) {
2352 if (ep == stackstrend())
2353 ep = growstackstr();
2354 *ep++ = (char*)vp->var_text;
2357 } while (++vpp < vartab + VTABSIZE);
2358 if (ep == stackstrend())
2359 ep = growstackstr();
2363 return grabstackstr(ep);
2367 /* ============ Path search helper
2369 * The variable path (passed by reference) should be set to the start
2370 * of the path before the first call; path_advance will update
2371 * this value as it proceeds. Successive calls to path_advance will return
2372 * the possible path expansions in sequence. If an option (indicated by
2373 * a percent sign) appears in the path entry then the global variable
2374 * pathopt will be set to point to it; otherwise pathopt will be set to
2377 static const char *pathopt; /* set by path_advance */
2380 path_advance(const char **path, const char *name)
2390 for (p = start; *p && *p != ':' && *p != '%'; p++)
2392 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2393 while (stackblocksize() < len)
2397 memcpy(q, start, p - start);
2405 while (*p && *p != ':')
2412 return stalloc(len);
2416 /* ============ Prompt */
2418 static smallint doprompt; /* if set, prompt the user */
2419 static smallint needprompt; /* true if interactive and at start of line */
2421 #if ENABLE_FEATURE_EDITING
2422 static line_input_t *line_input_state;
2423 static const char *cmdedit_prompt;
2425 putprompt(const char *s)
2427 if (ENABLE_ASH_EXPAND_PRMT) {
2428 free((char*)cmdedit_prompt);
2429 cmdedit_prompt = ckstrdup(s);
2436 putprompt(const char *s)
2442 #if ENABLE_ASH_EXPAND_PRMT
2443 /* expandstr() needs parsing machinery, so it is far away ahead... */
2444 static const char *expandstr(const char *ps);
2446 #define expandstr(s) s
2450 setprompt_if(smallint do_set, int whichprompt)
2453 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2460 switch (whichprompt) {
2470 #if ENABLE_ASH_EXPAND_PRMT
2471 pushstackmark(&smark, stackblocksize());
2473 putprompt(expandstr(prompt));
2474 #if ENABLE_ASH_EXPAND_PRMT
2475 popstackmark(&smark);
2480 /* ============ The cd and pwd commands */
2482 #define CD_PHYSICAL 1
2492 while ((i = nextopt("LP")) != '\0') {
2494 flags ^= CD_PHYSICAL;
2503 * Update curdir (the name of the current directory) in response to a
2507 updatepwd(const char *dir)
2514 cdcomppath = sstrdup(dir);
2517 if (curdir == nullstr)
2519 new = stack_putstr(curdir, new);
2521 new = makestrspace(strlen(dir) + 2, new);
2522 lim = (char *)stackblock() + 1;
2526 if (new > lim && *lim == '/')
2531 if (dir[1] == '/' && dir[2] != '/') {
2537 p = strtok(cdcomppath, "/");
2541 if (p[1] == '.' && p[2] == '\0') {
2553 new = stack_putstr(p, new);
2556 p = strtok(NULL, "/");
2561 return stackblock();
2565 * Find out what the current directory is. If we already know the current
2566 * directory, this routine returns immediately.
2571 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2572 return dir ? dir : nullstr;
2576 setpwd(const char *val, int setold)
2580 oldcur = dir = curdir;
2583 setvar("OLDPWD", oldcur, VEXPORT);
2586 if (physdir != nullstr) {
2587 if (physdir != oldcur)
2591 if (oldcur == val || !val) {
2597 dir = ckstrdup(val);
2598 if (oldcur != dir && oldcur != nullstr) {
2603 setvar("PWD", dir, VEXPORT);
2606 static void hashcd(void);
2609 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2610 * know that the current directory has changed.
2613 docd(const char *dest, int flags)
2615 const char *dir = NULL;
2618 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2621 if (!(flags & CD_PHYSICAL)) {
2622 dir = updatepwd(dest);
2636 static int FAST_FUNC
2637 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2649 dest = bltinlookup("HOME");
2650 else if (LONE_DASH(dest)) {
2651 dest = bltinlookup("OLDPWD");
2673 path = bltinlookup("CDPATH");
2682 p = path_advance(&path, dest);
2683 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2687 if (!docd(p, flags))
2692 ash_msg_and_raise_error("can't cd to %s", dest);
2695 if (flags & CD_PRINT)
2696 out1fmt("%s\n", curdir);
2700 static int FAST_FUNC
2701 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2704 const char *dir = curdir;
2708 if (physdir == nullstr)
2712 out1fmt("%s\n", dir);
2717 /* ============ ... */
2720 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2722 /* Syntax classes */
2723 #define CWORD 0 /* character is nothing special */
2724 #define CNL 1 /* newline character */
2725 #define CBACK 2 /* a backslash character */
2726 #define CSQUOTE 3 /* single quote */
2727 #define CDQUOTE 4 /* double quote */
2728 #define CENDQUOTE 5 /* a terminating quote */
2729 #define CBQUOTE 6 /* backwards single quote */
2730 #define CVAR 7 /* a dollar sign */
2731 #define CENDVAR 8 /* a '}' character */
2732 #define CLP 9 /* a left paren in arithmetic */
2733 #define CRP 10 /* a right paren in arithmetic */
2734 #define CENDFILE 11 /* end of file */
2735 #define CCTL 12 /* like CWORD, except it must be escaped */
2736 #define CSPCL 13 /* these terminate a word */
2737 #define CIGN 14 /* character should be ignored */
2740 #if ENABLE_ASH_ALIAS
2744 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2746 #if ENABLE_SH_MATH_SUPPORT
2747 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2749 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2751 static const uint16_t S_I_T[] ALIGN2 = {
2752 #if ENABLE_ASH_ALIAS
2753 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2755 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2756 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2757 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2758 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2759 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2760 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2761 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2762 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2763 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2764 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2765 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2766 #if !USE_SIT_FUNCTION
2767 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2768 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2769 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2773 /* Constants below must match table above */
2775 #if ENABLE_ASH_ALIAS
2776 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2778 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2779 CNL_CNL_CNL_CNL , /* 2 */
2780 CWORD_CCTL_CCTL_CWORD , /* 3 */
2781 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2782 CVAR_CVAR_CWORD_CVAR , /* 5 */
2783 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2784 CSPCL_CWORD_CWORD_CLP , /* 7 */
2785 CSPCL_CWORD_CWORD_CRP , /* 8 */
2786 CBACK_CBACK_CCTL_CBACK , /* 9 */
2787 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2788 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2789 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2790 CWORD_CWORD_CWORD_CWORD , /* 13 */
2791 CCTL_CCTL_CCTL_CCTL , /* 14 */
2794 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2795 * caller must ensure proper cast on it if c is *char_ptr!
2797 /* Values for syntax param */
2798 #define BASESYNTAX 0 /* not in quotes */
2799 #define DQSYNTAX 1 /* in double quotes */
2800 #define SQSYNTAX 2 /* in single quotes */
2801 #define ARISYNTAX 3 /* in arithmetic */
2802 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2804 #if USE_SIT_FUNCTION
2807 SIT(int c, int syntax)
2809 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2810 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2812 * This causes '/' to be prepended with CTLESC in dquoted string,
2813 * making "./file"* treated incorrectly because we feed
2814 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2815 * The "homegrown" glob implementation is okay with that,
2816 * but glibc one isn't. With '/' always treated as CWORD,
2819 # if ENABLE_ASH_ALIAS
2820 static const uint8_t syntax_index_table[] ALIGN1 = {
2821 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2822 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2823 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2827 static const uint8_t syntax_index_table[] ALIGN1 = {
2828 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2829 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2830 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2839 # if ENABLE_ASH_ALIAS
2845 /* Cast is purely for paranoia here,
2846 * just in case someone passed signed char to us */
2847 if ((unsigned char)c >= CTL_FIRST
2848 && (unsigned char)c <= CTL_LAST
2852 s = strchrnul(spec_symbls, c);
2855 indx = syntax_index_table[s - spec_symbls];
2857 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2860 #else /* !USE_SIT_FUNCTION */
2862 static const uint8_t syntax_index_table[] ALIGN1 = {
2863 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2864 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2874 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2875 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2897 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2898 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2899 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2900 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2901 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2902 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2903 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2904 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2905 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2906 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2907 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2908 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2909 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2910 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2911 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2912 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2913 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2916 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2918 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2924 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2925 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2926 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2927 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2928 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2929 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2957 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2958 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2959 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2962 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2990 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2991 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2992 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2993 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2994 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2995 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2996 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2997 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2998 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2999 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3000 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3001 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3002 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3120 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3121 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3122 # if ENABLE_ASH_ALIAS
3123 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3127 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3129 #endif /* !USE_SIT_FUNCTION */
3132 /* ============ Alias handling */
3134 #if ENABLE_ASH_ALIAS
3136 #define ALIASINUSE 1
3147 static struct alias **atab; // [ATABSIZE];
3148 #define INIT_G_alias() do { \
3149 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3153 static struct alias **
3154 __lookupalias(const char *name) {
3155 unsigned int hashval;
3162 ch = (unsigned char)*p;
3166 ch = (unsigned char)*++p;
3168 app = &atab[hashval % ATABSIZE];
3170 for (; *app; app = &(*app)->next) {
3171 if (strcmp(name, (*app)->name) == 0) {
3179 static struct alias *
3180 lookupalias(const char *name, int check)
3182 struct alias *ap = *__lookupalias(name);
3184 if (check && ap && (ap->flag & ALIASINUSE))
3189 static struct alias *
3190 freealias(struct alias *ap)
3194 if (ap->flag & ALIASINUSE) {
3195 ap->flag |= ALIASDEAD;
3207 setalias(const char *name, const char *val)
3209 struct alias *ap, **app;
3211 app = __lookupalias(name);
3215 if (!(ap->flag & ALIASINUSE)) {
3218 ap->val = ckstrdup(val);
3219 ap->flag &= ~ALIASDEAD;
3222 ap = ckzalloc(sizeof(struct alias));
3223 ap->name = ckstrdup(name);
3224 ap->val = ckstrdup(val);
3225 /*ap->flag = 0; - ckzalloc did it */
3226 /*ap->next = NULL;*/
3233 unalias(const char *name)
3237 app = __lookupalias(name);
3241 *app = freealias(*app);
3252 struct alias *ap, **app;
3256 for (i = 0; i < ATABSIZE; i++) {
3258 for (ap = *app; ap; ap = *app) {
3259 *app = freealias(*app);
3269 printalias(const struct alias *ap)
3271 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3275 * TODO - sort output
3277 static int FAST_FUNC
3278 aliascmd(int argc UNUSED_PARAM, char **argv)
3287 for (i = 0; i < ATABSIZE; i++) {
3288 for (ap = atab[i]; ap; ap = ap->next) {
3294 while ((n = *++argv) != NULL) {
3295 v = strchr(n+1, '=');
3296 if (v == NULL) { /* n+1: funny ksh stuff */
3297 ap = *__lookupalias(n);
3299 fprintf(stderr, "%s: %s not found\n", "alias", n);
3312 static int FAST_FUNC
3313 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3317 while ((i = nextopt("a")) != '\0') {
3323 for (i = 0; *argptr; argptr++) {
3324 if (unalias(*argptr)) {
3325 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3333 #endif /* ASH_ALIAS */
3336 /* ============ jobs.c */
3338 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3341 #define FORK_NOJOB 2
3343 /* mode flags for showjob(s) */
3344 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3345 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3346 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3347 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3350 * A job structure contains information about a job. A job is either a
3351 * single process or a set of processes contained in a pipeline. In the
3352 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3356 pid_t ps_pid; /* process id */
3357 int ps_status; /* last process status from wait() */
3358 char *ps_cmd; /* text of command being run */
3362 struct procstat ps0; /* status of process */
3363 struct procstat *ps; /* status or processes when more than one */
3365 int stopstatus; /* status of a stopped job */
3368 nprocs: 16, /* number of processes */
3370 #define JOBRUNNING 0 /* at least one proc running */
3371 #define JOBSTOPPED 1 /* all procs are stopped */
3372 #define JOBDONE 2 /* all procs are completed */
3374 sigint: 1, /* job was killed by SIGINT */
3375 jobctl: 1, /* job running under job control */
3377 waited: 1, /* true if this entry has been waited for */
3378 used: 1, /* true if this entry is in used */
3379 changed: 1; /* true if status has changed */
3380 struct job *prev_job; /* previous job */
3383 static struct job *makejob(/*union node *,*/ int);
3384 static int forkshell(struct job *, union node *, int);
3385 static int waitforjob(struct job *);
3388 enum { doing_jobctl = 0 };
3389 #define setjobctl(on) do {} while (0)
3391 static smallint doing_jobctl; //references:8
3392 static void setjobctl(int);
3399 ignoresig(int signo)
3401 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3402 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3403 /* No, need to do it */
3404 signal(signo, SIG_IGN);
3406 sigmode[signo - 1] = S_HARD_IGN;
3410 * Only one usage site - in setsignal()
3413 signal_handler(int signo)
3415 gotsig[signo - 1] = 1;
3417 if (signo == SIGINT && !trap[SIGINT]) {
3418 if (!suppress_int) {
3420 raise_interrupt(); /* does not return */
3424 pending_sig = signo;
3429 * Set the signal handler for the specified signal. The routine figures
3430 * out what it should be set to.
3433 setsignal(int signo)
3436 char cur_act, new_act;
3437 struct sigaction act;
3441 if (t != NULL) { /* trap for this sig is set */
3443 if (t[0] == '\0') /* trap is "": ignore this sig */
3447 if (rootshell && new_act == S_DFL) {
3450 if (iflag || minusc || sflag == 0)
3459 * "In all cases, bash ignores SIGQUIT. Non-builtin
3460 * commands run by bash have signal handlers
3461 * set to the values inherited by the shell
3462 * from its parent". */
3478 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3479 //whereas we have to restore it to what shell got on entry
3480 //from the parent. See comment above
3482 t = &sigmode[signo - 1];
3485 /* current setting is not yet known */
3486 if (sigaction(signo, NULL, &act)) {
3487 /* pretend it worked; maybe we should give a warning,
3488 * but other shells don't. We don't alter sigmode,
3489 * so we retry every time.
3490 * btw, in Linux it never fails. --vda */
3493 if (act.sa_handler == SIG_IGN) {
3494 cur_act = S_HARD_IGN;
3496 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3498 cur_act = S_IGN; /* don't hard ignore these */
3502 if (cur_act == S_HARD_IGN || cur_act == new_act)
3505 act.sa_handler = SIG_DFL;
3508 act.sa_handler = signal_handler;
3511 act.sa_handler = SIG_IGN;
3515 /* flags and mask matter only if !DFL and !IGN, but we do it
3516 * for all cases for more deterministic behavior:
3519 sigfillset(&act.sa_mask);
3521 sigaction_set(signo, &act);
3526 /* mode flags for set_curjob */
3527 #define CUR_DELETE 2
3528 #define CUR_RUNNING 1
3529 #define CUR_STOPPED 0
3531 /* mode flags for dowait */
3532 #define DOWAIT_NONBLOCK WNOHANG
3533 #define DOWAIT_BLOCK 0
3536 /* pgrp of shell on invocation */
3537 static int initialpgrp; //references:2
3538 static int ttyfd = -1; //5
3541 static struct job *jobtab; //5
3543 static unsigned njobs; //4
3545 static struct job *curjob; //lots
3546 /* number of presumed living untracked jobs */
3547 static int jobless; //4
3550 set_curjob(struct job *jp, unsigned mode)
3553 struct job **jpp, **curp;
3555 /* first remove from list */
3556 jpp = curp = &curjob;
3561 jpp = &jp1->prev_job;
3563 *jpp = jp1->prev_job;
3565 /* Then re-insert in correct position */
3573 /* job being deleted */
3576 /* newly created job or backgrounded job,
3577 * put after all stopped jobs.
3582 if (!jp1 || jp1->state != JOBSTOPPED)
3585 jpp = &jp1->prev_job;
3591 /* newly stopped job - becomes curjob */
3592 jp->prev_job = *jpp;
3600 jobno(const struct job *jp)
3602 return jp - jobtab + 1;
3607 * Convert a job name to a job structure.
3610 #define getjob(name, getctl) getjob(name)
3613 getjob(const char *name, int getctl)
3617 const char *err_msg = "%s: no such job";
3621 char *(*match)(const char *, const char *);
3636 if (c == '+' || c == '%') {
3638 err_msg = "No current job";
3644 err_msg = "No previous job";
3654 if (num > 0 && num <= njobs) {
3655 jp = jobtab + num - 1;
3670 if (match(jp->ps[0].ps_cmd, p)) {
3674 err_msg = "%s: ambiguous";
3684 err_msg = "job %s not created under job control";
3685 if (getctl && jp->jobctl == 0)
3690 ash_msg_and_raise_error(err_msg, name);
3694 * Mark a job structure as unused.
3697 freejob(struct job *jp)
3699 struct procstat *ps;
3703 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3704 if (ps->ps_cmd != nullstr)
3707 if (jp->ps != &jp->ps0)
3710 set_curjob(jp, CUR_DELETE);
3716 xtcsetpgrp(int fd, pid_t pgrp)
3718 if (tcsetpgrp(fd, pgrp))
3719 ash_msg_and_raise_error("can't set tty process group (%m)");
3723 * Turn job control on and off.
3725 * Note: This code assumes that the third arg to ioctl is a character
3726 * pointer, which is true on Berkeley systems but not System V. Since
3727 * System V doesn't have job control yet, this isn't a problem now.
3729 * Called with interrupts off.
3737 if (on == doing_jobctl || rootshell == 0)
3741 ofd = fd = open(_PATH_TTY, O_RDWR);
3743 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3744 * That sometimes helps to acquire controlling tty.
3745 * Obviously, a workaround for bugs when someone
3746 * failed to provide a controlling tty to bash! :) */
3752 fd = fcntl(fd, F_DUPFD, 10);
3757 /* fd is a tty at this point */
3758 close_on_exec_on(fd);
3759 while (1) { /* while we are in the background */
3760 pgrp = tcgetpgrp(fd);
3763 ash_msg("can't access tty; job control turned off");
3767 if (pgrp == getpgrp())
3778 xtcsetpgrp(fd, pgrp);
3780 /* turning job control off */
3783 /* was xtcsetpgrp, but this can make exiting ash
3784 * loop forever if pty is already deleted */
3785 tcsetpgrp(fd, pgrp);
3799 static int FAST_FUNC
3800 killcmd(int argc, char **argv)
3802 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3805 if (argv[i][0] == '%') {
3807 * "kill %N" - job kill
3808 * Converting to pgrp / pid kill
3814 jp = getjob(argv[i], 0);
3816 * In jobs started under job control, we signal
3817 * entire process group by kill -PGRP_ID.
3818 * This happens, f.e., in interactive shell.
3820 * Otherwise, we signal each child via
3821 * kill PID1 PID2 PID3.
3823 * sh -c 'sleep 1|sleep 1 & kill %1'
3824 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3825 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3827 n = jp->nprocs; /* can't be 0 (I hope) */
3830 dst = alloca(n * sizeof(int)*4);
3832 for (j = 0; j < n; j++) {
3833 struct procstat *ps = &jp->ps[j];
3834 /* Skip non-running and not-stopped members
3835 * (i.e. dead members) of the job
3837 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3840 * kill_main has matching code to expect
3841 * leading space. Needed to not confuse
3842 * negative pids with "kill -SIGNAL_NO" syntax
3844 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3848 } while (argv[++i]);
3850 return kill_main(argc, argv);
3854 showpipe(struct job *jp /*, FILE *out*/)
3856 struct procstat *ps;
3857 struct procstat *psend;
3859 psend = jp->ps + jp->nprocs;
3860 for (ps = jp->ps + 1; ps < psend; ps++)
3861 printf(" | %s", ps->ps_cmd);
3862 newline_and_flush(stdout);
3863 flush_stdout_stderr();
3868 restartjob(struct job *jp, int mode)
3870 struct procstat *ps;
3876 if (jp->state == JOBDONE)
3878 jp->state = JOBRUNNING;
3879 pgid = jp->ps[0].ps_pid;
3880 if (mode == FORK_FG)
3881 xtcsetpgrp(ttyfd, pgid);
3882 killpg(pgid, SIGCONT);
3886 if (WIFSTOPPED(ps->ps_status)) {
3892 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3897 static int FAST_FUNC
3898 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3904 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3908 jp = getjob(*argv, 1);
3909 if (mode == FORK_BG) {
3910 set_curjob(jp, CUR_RUNNING);
3911 printf("[%d] ", jobno(jp));
3913 out1str(jp->ps[0].ps_cmd);
3914 showpipe(jp /*, stdout*/);
3915 retval = restartjob(jp, mode);
3916 } while (*argv && *++argv);
3922 sprint_status48(char *s, int status, int sigonly)
3928 if (!WIFEXITED(status)) {
3929 if (JOBS && WIFSTOPPED(status))
3930 st = WSTOPSIG(status);
3932 st = WTERMSIG(status);
3934 if (st == SIGINT || st == SIGPIPE)
3936 if (JOBS && WIFSTOPPED(status))
3940 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3941 col = fmtstr(s, 32, strsignal(st));
3942 if (WCOREDUMP(status)) {
3943 strcpy(s + col, " (core dumped)");
3944 col += sizeof(" (core dumped)")-1;
3946 } else if (!sigonly) {
3947 st = WEXITSTATUS(status);
3948 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
3955 dowait(int wait_flags, struct job *job)
3960 struct job *thisjob;
3962 TRACE(("dowait(0x%x) called\n", wait_flags));
3964 /* Do a wait system call. If job control is compiled in, we accept
3965 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3966 * NB: _not_ safe_waitpid, we need to detect EINTR */
3968 wait_flags |= WUNTRACED;
3969 pid = waitpid(-1, &status, wait_flags);
3970 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3971 pid, status, errno, strerror(errno)));
3977 for (jp = curjob; jp; jp = jp->prev_job) {
3979 struct procstat *ps;
3980 struct procstat *psend;
3981 if (jp->state == JOBDONE)
3985 psend = ps + jp->nprocs;
3987 if (ps->ps_pid == pid) {
3988 TRACE(("Job %d: changing status of proc %d "
3989 "from 0x%x to 0x%x\n",
3990 jobno(jp), pid, ps->ps_status, status));
3991 ps->ps_status = status;
3994 if (ps->ps_status == -1)
3995 jobstate = JOBRUNNING;
3997 if (jobstate == JOBRUNNING)
3999 if (WIFSTOPPED(ps->ps_status)) {
4000 jp->stopstatus = ps->ps_status;
4001 jobstate = JOBSTOPPED;
4004 } while (++ps < psend);
4008 /* Found the job where one of its processes changed its state.
4009 * Is there at least one live and running process in this job? */
4010 if (jobstate != JOBRUNNING) {
4011 /* No. All live processes in the job are stopped
4012 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4014 thisjob->changed = 1;
4015 if (thisjob->state != jobstate) {
4016 TRACE(("Job %d: changing state from %d to %d\n",
4017 jobno(thisjob), thisjob->state, jobstate));
4018 thisjob->state = jobstate;
4020 if (jobstate == JOBSTOPPED)
4021 set_curjob(thisjob, CUR_STOPPED);
4027 /* The process wasn't found in job list */
4028 if (JOBS && !WIFSTOPPED(status))
4033 if (thisjob && thisjob == job) {
4037 len = sprint_status48(s, status, 1);
4048 blocking_wait_with_raise_on_sig(void)
4050 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
4051 if (pid <= 0 && pending_sig)
4052 raise_exception(EXSIG);
4058 showjob(struct job *jp, int mode)
4060 struct procstat *ps;
4061 struct procstat *psend;
4064 char s[16 + 16 + 48];
4065 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4069 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4070 /* just output process (group) id of pipeline */
4071 fprintf(out, "%d\n", ps->ps_pid);
4075 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4080 else if (curjob && jp == curjob->prev_job)
4083 if (mode & SHOW_PIDS)
4084 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4086 psend = ps + jp->nprocs;
4088 if (jp->state == JOBRUNNING) {
4089 strcpy(s + col, "Running");
4090 col += sizeof("Running") - 1;
4092 int status = psend[-1].ps_status;
4093 if (jp->state == JOBSTOPPED)
4094 status = jp->stopstatus;
4095 col += sprint_status48(s + col, status, 0);
4097 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4099 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4100 * or prints several "PID | <cmdN>" lines,
4101 * depending on SHOW_PIDS bit.
4102 * We do not print status of individual processes
4103 * between PID and <cmdN>. bash does it, but not very well:
4104 * first line shows overall job status, not process status,
4105 * making it impossible to know 1st process status.
4109 /* for each process */
4112 if (mode & SHOW_PIDS)
4113 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4115 fprintf(out, "%s%*c%s%s",
4117 33 - col >= 0 ? 33 - col : 0, ' ',
4118 ps == jp->ps ? "" : "| ",
4121 } while (++ps != psend);
4122 newline_and_flush(out);
4126 if (jp->state == JOBDONE) {
4127 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4133 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4134 * statuses have changed since the last call to showjobs.
4141 TRACE(("showjobs(0x%x) called\n", mode));
4143 /* Handle all finished jobs */
4144 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4147 for (jp = curjob; jp; jp = jp->prev_job) {
4148 if (!(mode & SHOW_CHANGED) || jp->changed) {
4154 static int FAST_FUNC
4155 jobscmd(int argc UNUSED_PARAM, char **argv)
4160 while ((m = nextopt("lp")) != '\0') {
4164 mode |= SHOW_ONLY_PGID;
4170 showjob(getjob(*argv, 0), mode);
4180 /* Called only on finished or stopped jobs (no members are running) */
4182 getstatus(struct job *job)
4186 struct procstat *ps;
4188 /* Fetch last member's status */
4189 ps = job->ps + job->nprocs - 1;
4190 status = ps->ps_status;
4192 /* "set -o pipefail" mode: use last _nonzero_ status */
4193 while (status == 0 && --ps >= job->ps)
4194 status = ps->ps_status;
4197 retval = WEXITSTATUS(status);
4198 if (!WIFEXITED(status)) {
4200 retval = WSTOPSIG(status);
4201 if (!WIFSTOPPED(status))
4204 /* XXX: limits number of signals */
4205 retval = WTERMSIG(status);
4207 if (retval == SIGINT)
4213 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4214 jobno(job), job->nprocs, status, retval));
4218 static int FAST_FUNC
4219 waitcmd(int argc UNUSED_PARAM, char **argv)
4226 raise_exception(EXSIG);
4233 /* wait for all jobs */
4237 if (!jp) /* no running procs */
4239 if (jp->state == JOBRUNNING)
4244 blocking_wait_with_raise_on_sig();
4246 * "When bash is waiting for an asynchronous command via
4247 * the wait builtin, the reception of a signal for which a trap
4248 * has been set will cause the wait builtin to return immediately
4249 * with an exit status greater than 128, immediately after which
4250 * the trap is executed."
4252 * blocking_wait_with_raise_on_sig raises signal handlers
4253 * if it gets no pid (pid < 0). However,
4254 * if child sends us a signal *and immediately exits*,
4255 * blocking_wait_with_raise_on_sig gets pid > 0
4256 * and does not handle pending_sig. Check this case: */
4258 raise_exception(EXSIG);
4264 if (**argv != '%') {
4265 pid_t pid = number(*argv);
4270 if (job->ps[job->nprocs - 1].ps_pid == pid)
4272 job = job->prev_job;
4275 job = getjob(*argv, 0);
4277 /* loop until process terminated or stopped */
4278 while (job->state == JOBRUNNING)
4279 blocking_wait_with_raise_on_sig();
4281 retval = getstatus(job);
4294 struct job *jp, *jq;
4296 len = njobs * sizeof(*jp);
4298 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4300 offset = (char *)jp - (char *)jq;
4302 /* Relocate pointers */
4305 jq = (struct job *)((char *)jq + l);
4309 #define joff(p) ((struct job *)((char *)(p) + l))
4310 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4311 if (joff(jp)->ps == &jq->ps0)
4312 jmove(joff(jp)->ps);
4313 if (joff(jp)->prev_job)
4314 jmove(joff(jp)->prev_job);
4324 jp = (struct job *)((char *)jp + len);
4328 } while (--jq >= jp);
4333 * Return a new job structure.
4334 * Called with interrupts off.
4337 makejob(/*union node *node,*/ int nprocs)
4342 for (i = njobs, jp = jobtab; ; jp++) {
4349 if (jp->state != JOBDONE || !jp->waited)
4358 memset(jp, 0, sizeof(*jp));
4360 /* jp->jobctl is a bitfield.
4361 * "jp->jobctl |= jobctl" likely to give awful code */
4365 jp->prev_job = curjob;
4370 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4372 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4379 * Return a string identifying a command (to be printed by the
4382 static char *cmdnextc;
4385 cmdputs(const char *s)
4387 static const char vstype[VSTYPE + 1][3] = {
4388 "", "}", "-", "+", "?", "=",
4389 "%", "%%", "#", "##"
4390 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4393 const char *p, *str;
4397 unsigned char subtype = 0;
4401 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4403 while ((c = *p++) != '\0') {
4411 if ((subtype & VSTYPE) == VSLENGTH)
4417 str = "\"}" + !(quoted & 1);
4424 #if ENABLE_SH_MATH_SUPPORT
4439 if ((subtype & VSTYPE) != VSNORMAL)
4441 str = vstype[subtype & VSTYPE];
4442 if (subtype & VSNUL)
4451 /* These can only happen inside quotes */
4464 while ((c = *str++) != '\0') {
4467 } /* while *p++ not NUL */
4470 USTPUTC('"', nextc);
4476 /* cmdtxt() and cmdlist() call each other */
4477 static void cmdtxt(union node *n);
4480 cmdlist(union node *np, int sep)
4482 for (; np; np = np->narg.next) {
4486 if (sep && np->narg.next)
4492 cmdtxt(union node *n)
4495 struct nodelist *lp;
4506 lp = n->npipe.cmdlist;
4524 cmdtxt(n->nbinary.ch1);
4540 cmdtxt(n->nif.test);
4542 if (n->nif.elsepart) {
4543 cmdtxt(n->nif.ifpart);
4545 n = n->nif.elsepart;
4563 cmdtxt(n->nbinary.ch1);
4573 cmdputs(n->nfor.var);
4575 cmdlist(n->nfor.args, 1);
4580 cmdputs(n->narg.text);
4584 cmdlist(n->ncmd.args, 1);
4585 cmdlist(n->ncmd.redirect, 0);
4598 cmdputs(n->ncase.expr->narg.text);
4600 for (np = n->ncase.cases; np; np = np->nclist.next) {
4601 cmdtxt(np->nclist.pattern);
4603 cmdtxt(np->nclist.body);
4617 #if ENABLE_ASH_BASH_COMPAT
4632 cmdputs(utoa(n->nfile.fd));
4634 if (n->type == NTOFD || n->type == NFROMFD) {
4635 cmdputs(utoa(n->ndup.dupfd));
4644 commandtext(union node *n)
4648 STARTSTACKSTR(cmdnextc);
4650 name = stackblock();
4651 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4652 name, cmdnextc, cmdnextc));
4653 return ckstrdup(name);
4658 * Fork off a subshell. If we are doing job control, give the subshell its
4659 * own process group. Jp is a job structure that the job is to be added to.
4660 * N is the command that will be evaluated by the child. Both jp and n may
4661 * be NULL. The mode parameter can be one of the following:
4662 * FORK_FG - Fork off a foreground process.
4663 * FORK_BG - Fork off a background process.
4664 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4665 * process group even if job control is on.
4667 * When job control is turned off, background processes have their standard
4668 * input redirected to /dev/null (except for the second and later processes
4671 * Called with interrupts off.
4674 * Clear traps on a fork.
4681 for (tp = trap; tp < &trap[NSIG]; tp++) {
4682 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4684 if (trap_ptr == trap)
4686 /* else: it "belongs" to trap_ptr vector, don't free */
4688 if ((tp - trap) != 0)
4689 setsignal(tp - trap);
4696 /* Lives far away from here, needed for forkchild */
4697 static void closescript(void);
4699 /* Called after fork(), in child */
4700 static NOINLINE void
4701 forkchild(struct job *jp, union node *n, int mode)
4705 TRACE(("Child shell %d\n", getpid()));
4709 /* man bash: "Non-builtin commands run by bash have signal handlers
4710 * set to the values inherited by the shell from its parent".
4711 * Do we do it correctly? */
4715 if (mode == FORK_NOJOB /* is it `xxx` ? */
4716 && n && n->type == NCMD /* is it single cmd? */
4717 /* && n->ncmd.args->type == NARG - always true? */
4718 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4719 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4720 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4722 TRACE(("Trap hack\n"));
4723 /* Awful hack for `trap` or $(trap).
4725 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4726 * contains an example where "trap" is executed in a subshell:
4728 * save_traps=$(trap)
4730 * eval "$save_traps"
4732 * Standard does not say that "trap" in subshell shall print
4733 * parent shell's traps. It only says that its output
4734 * must have suitable form, but then, in the above example
4735 * (which is not supposed to be normative), it implies that.
4737 * bash (and probably other shell) does implement it
4738 * (traps are reset to defaults, but "trap" still shows them),
4739 * but as a result, "trap" logic is hopelessly messed up:
4742 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4743 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4744 * # true | trap <--- trap is in subshell - no output (ditto)
4745 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4746 * trap -- 'echo Ho' SIGWINCH
4747 * # echo `(trap)` <--- in subshell in subshell - output
4748 * trap -- 'echo Ho' SIGWINCH
4749 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4750 * trap -- 'echo Ho' SIGWINCH
4752 * The rules when to forget and when to not forget traps
4753 * get really complex and nonsensical.
4755 * Our solution: ONLY bare $(trap) or `trap` is special.
4757 /* Save trap handler strings for trap builtin to print */
4758 trap_ptr = xmemdup(trap, sizeof(trap));
4759 /* Fall through into clearing traps */
4763 /* do job control only in root shell */
4765 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4768 if (jp->nprocs == 0)
4771 pgrp = jp->ps[0].ps_pid;
4772 /* this can fail because we are doing it in the parent also */
4774 if (mode == FORK_FG)
4775 xtcsetpgrp(ttyfd, pgrp);
4780 if (mode == FORK_BG) {
4781 /* man bash: "When job control is not in effect,
4782 * asynchronous commands ignore SIGINT and SIGQUIT" */
4785 if (jp->nprocs == 0) {
4787 if (open(bb_dev_null, O_RDONLY) != 0)
4788 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4792 if (iflag) { /* why if iflag only? */
4797 * "In all cases, bash ignores SIGQUIT. Non-builtin
4798 * commands run by bash have signal handlers
4799 * set to the values inherited by the shell
4801 * Take care of the second rule: */
4805 if (n && n->type == NCMD
4806 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4808 TRACE(("Job hack\n"));
4809 /* "jobs": we do not want to clear job list for it,
4810 * instead we remove only _its_ own_ job from job list.
4811 * This makes "jobs .... | cat" more useful.
4817 for (jp = curjob; jp; jp = jp->prev_job)
4822 /* Called after fork(), in parent */
4824 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4827 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4829 TRACE(("In parent shell: child = %d\n", pid));
4831 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4837 if (mode != FORK_NOJOB && jp->jobctl) {
4840 if (jp->nprocs == 0)
4843 pgrp = jp->ps[0].ps_pid;
4844 /* This can fail because we are doing it in the child also */
4848 if (mode == FORK_BG) {
4849 backgndpid = pid; /* set $! */
4850 set_curjob(jp, CUR_RUNNING);
4853 struct procstat *ps = &jp->ps[jp->nprocs++];
4856 ps->ps_cmd = nullstr;
4858 if (doing_jobctl && n)
4859 ps->ps_cmd = commandtext(n);
4865 forkshell(struct job *jp, union node *n, int mode)
4869 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4872 TRACE(("Fork failed, errno=%d", errno));
4875 ash_msg_and_raise_error("can't fork");
4878 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4879 forkchild(jp, n, mode);
4881 forkparent(jp, n, mode, pid);
4887 * Wait for job to finish.
4889 * Under job control we have the problem that while a child process
4890 * is running interrupts generated by the user are sent to the child
4891 * but not to the shell. This means that an infinite loop started by
4892 * an interactive user may be hard to kill. With job control turned off,
4893 * an interactive user may place an interactive program inside a loop.
4894 * If the interactive program catches interrupts, the user doesn't want
4895 * these interrupts to also abort the loop. The approach we take here
4896 * is to have the shell ignore interrupt signals while waiting for a
4897 * foreground process to terminate, and then send itself an interrupt
4898 * signal if the child process was terminated by an interrupt signal.
4899 * Unfortunately, some programs want to do a bit of cleanup and then
4900 * exit on interrupt; unless these processes terminate themselves by
4901 * sending a signal to themselves (instead of calling exit) they will
4902 * confuse this approach.
4904 * Called with interrupts off.
4907 waitforjob(struct job *jp)
4911 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4914 while (jp->state == JOBRUNNING) {
4915 /* In non-interactive shells, we _can_ get
4916 * a keyboard signal here and be EINTRed,
4917 * but we just loop back, waiting for command to complete.
4920 * "If bash is waiting for a command to complete and receives
4921 * a signal for which a trap has been set, the trap
4922 * will not be executed until the command completes."
4924 * Reality is that even if trap is not set, bash
4925 * will not act on the signal until command completes.
4926 * Try this. sleep5intoff.c:
4927 * #include <signal.h>
4928 * #include <unistd.h>
4931 * sigemptyset(&set);
4932 * sigaddset(&set, SIGINT);
4933 * sigaddset(&set, SIGQUIT);
4934 * sigprocmask(SIG_BLOCK, &set, NULL);
4938 * $ bash -c './sleep5intoff; echo hi'
4939 * ^C^C^C^C <--- pressing ^C once a second
4941 * $ bash -c './sleep5intoff; echo hi'
4942 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4945 dowait(DOWAIT_BLOCK, jp);
4952 xtcsetpgrp(ttyfd, rootpid);
4954 * This is truly gross.
4955 * If we're doing job control, then we did a TIOCSPGRP which
4956 * caused us (the shell) to no longer be in the controlling
4957 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4958 * intuit from the subprocess exit status whether a SIGINT
4959 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4961 if (jp->sigint) /* TODO: do the same with all signals */
4962 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4964 if (jp->state == JOBDONE)
4971 * return 1 if there are stopped jobs, otherwise 0
4983 if (jp && jp->state == JOBSTOPPED) {
4984 out2str("You have stopped jobs.\n");
4993 /* ============ redir.c
4995 * Code for dealing with input/output redirection.
5000 #define EMPTY -2 /* marks an unused slot in redirtab */
5001 #define CLOSED -3 /* marks a slot of previously-closed fd */
5004 * Open a file in noclobber mode.
5005 * The code was copied from bash.
5008 noclobberopen(const char *fname)
5011 struct stat finfo, finfo2;
5014 * If the file exists and is a regular file, return an error
5017 r = stat(fname, &finfo);
5018 if (r == 0 && S_ISREG(finfo.st_mode)) {
5024 * If the file was not present (r != 0), make sure we open it
5025 * exclusively so that if it is created before we open it, our open
5026 * will fail. Make sure that we do not truncate an existing file.
5027 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5028 * file was not a regular file, we leave O_EXCL off.
5031 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5032 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5034 /* If the open failed, return the file descriptor right away. */
5039 * OK, the open succeeded, but the file may have been changed from a
5040 * non-regular file to a regular file between the stat and the open.
5041 * We are assuming that the O_EXCL open handles the case where FILENAME
5042 * did not exist and is symlinked to an existing file between the stat
5047 * If we can open it and fstat the file descriptor, and neither check
5048 * revealed that it was a regular file, and the file has not been
5049 * replaced, return the file descriptor.
5051 if (fstat(fd, &finfo2) == 0
5052 && !S_ISREG(finfo2.st_mode)
5053 && finfo.st_dev == finfo2.st_dev
5054 && finfo.st_ino == finfo2.st_ino
5059 /* The file has been replaced. badness. */
5066 * Handle here documents. Normally we fork off a process to write the
5067 * data to a pipe. If the document is short, we can stuff the data in
5068 * the pipe without forking.
5070 /* openhere needs this forward reference */
5071 static void expandhere(union node *arg, int fd);
5073 openhere(union node *redir)
5079 ash_msg_and_raise_error("pipe call failed");
5080 if (redir->type == NHERE) {
5081 len = strlen(redir->nhere.doc->narg.text);
5082 if (len <= PIPE_BUF) {
5083 full_write(pip[1], redir->nhere.doc->narg.text, len);
5087 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5090 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5091 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5092 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5093 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5094 signal(SIGPIPE, SIG_DFL);
5095 if (redir->type == NHERE)
5096 full_write(pip[1], redir->nhere.doc->narg.text, len);
5098 expandhere(redir->nhere.doc, pip[1]);
5099 _exit(EXIT_SUCCESS);
5107 openredirect(union node *redir)
5112 switch (redir->nfile.type) {
5113 /* Can't happen, our single caller does this itself */
5119 return openhere(redir);
5122 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5123 * allocated space. Do it only when we know it is safe.
5125 fname = redir->nfile.expfname;
5127 switch (redir->nfile.type) {
5133 f = open(fname, O_RDONLY);
5138 f = open(fname, O_RDWR|O_CREAT, 0666);
5143 #if ENABLE_ASH_BASH_COMPAT
5146 /* Take care of noclobber mode. */
5148 f = noclobberopen(fname);
5155 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5160 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5168 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5170 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5174 * Copy a file descriptor to be >= to. Returns -1
5175 * if the source file descriptor is closed, EMPTY if there are no unused
5176 * file descriptors left.
5178 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5179 * old code was doing close(to) prior to copyfd() to achieve the same */
5181 COPYFD_EXACT = (int)~(INT_MAX),
5182 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5185 copyfd(int from, int to)
5189 if (to & COPYFD_EXACT) {
5190 to &= ~COPYFD_EXACT;
5192 newfd = dup2(from, to);
5194 newfd = fcntl(from, F_DUPFD, to);
5197 if (errno == EMFILE)
5199 /* Happens when source fd is not open: try "echo >&99" */
5200 ash_msg_and_raise_error("%d: %m", from);
5205 /* Struct def and variable are moved down to the first usage site */
5210 struct redirtab *next;
5213 struct two_fd_t two_fd[];
5215 #define redirlist (G_var.redirlist)
5217 static int need_to_remember(struct redirtab *rp, int fd)
5221 if (!rp) /* remembering was not requested */
5224 for (i = 0; i < rp->pair_count; i++) {
5225 if (rp->two_fd[i].orig == fd) {
5226 /* already remembered */
5233 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5234 static int is_hidden_fd(struct redirtab *rp, int fd)
5237 struct parsefile *pf;
5241 /* Check open scripts' fds */
5244 /* We skip pf_fd == 0 case because of the following case:
5245 * $ ash # running ash interactively
5247 * and in script.sh: "exec 9>&0".
5248 * Even though top-level pf_fd _is_ 0,
5249 * it's still ok to use it: "read" builtin uses it,
5250 * why should we cripple "exec" builtin?
5252 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5260 /* Check saved fds of redirects */
5261 fd |= COPYFD_RESTORE;
5262 for (i = 0; i < rp->pair_count; i++) {
5263 if (rp->two_fd[i].copy == fd) {
5271 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5272 * old file descriptors are stashed away so that the redirection can be
5273 * undone by calling popredir.
5275 /* flags passed to redirect */
5276 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5277 #define REDIR_SAVEFD2 03 /* set preverrout */
5279 redirect(union node *redir, int flags)
5281 struct redirtab *sv;
5286 int copied_fd2 = -1;
5296 if (flags & REDIR_PUSH) {
5297 union node *tmp = redir;
5300 #if ENABLE_ASH_BASH_COMPAT
5301 if (tmp->nfile.type == NTO2)
5304 tmp = tmp->nfile.next;
5306 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5307 sv->next = redirlist;
5308 sv->pair_count = sv_pos;
5310 sv->nullredirs = g_nullredirs - 1;
5312 while (sv_pos > 0) {
5314 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5320 fd = redir->nfile.fd;
5321 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5322 right_fd = redir->ndup.dupfd;
5323 //bb_error_msg("doing %d > %d", fd, right_fd);
5324 /* redirect from/to same file descriptor? */
5327 /* "echo >&10" and 10 is a fd opened to a sh script? */
5328 if (is_hidden_fd(sv, right_fd)) {
5329 errno = EBADF; /* as if it is closed */
5330 ash_msg_and_raise_error("%d: %m", right_fd);
5334 newfd = openredirect(redir); /* always >= 0 */
5336 /* Descriptor wasn't open before redirect.
5337 * Mark it for close in the future */
5338 if (need_to_remember(sv, fd)) {
5339 goto remember_to_close;
5344 #if ENABLE_ASH_BASH_COMPAT
5347 if (need_to_remember(sv, fd)) {
5348 /* Copy old descriptor */
5349 /* Careful to not accidentally "save"
5350 * to the same fd as right side fd in N>&M */
5351 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5352 i = fcntl(fd, F_DUPFD, minfd);
5353 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5354 * are closed in popredir() in the child, preventing them from leaking
5355 * into child. (popredir() also cleans up the mess in case of failures)
5360 /* Strange error (e.g. "too many files" EMFILE?) */
5364 ash_msg_and_raise_error("%d: %m", fd);
5367 /* EBADF: it is not open - good, remember to close it */
5370 } else { /* fd is open, save its copy */
5371 /* "exec fd>&-" should not close fds
5372 * which point to script file(s).
5373 * Force them to be restored afterwards */
5374 if (is_hidden_fd(sv, fd))
5375 i |= COPYFD_RESTORE;
5379 sv->two_fd[sv_pos].orig = fd;
5380 sv->two_fd[sv_pos].copy = i;
5384 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5385 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5386 /* Don't want to trigger debugging */
5390 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5392 } else if (fd != newfd) { /* move newfd to fd */
5393 copyfd(newfd, fd | COPYFD_EXACT);
5394 #if ENABLE_ASH_BASH_COMPAT
5395 if (!(redir->nfile.type == NTO2 && fd == 2))
5399 #if ENABLE_ASH_BASH_COMPAT
5400 if (redir->nfile.type == NTO2 && fd == 1) {
5401 /* We already redirected it to fd 1, now copy it to 2 */
5407 } while ((redir = redir->nfile.next) != NULL);
5410 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5411 preverrout_fd = copied_fd2;
5415 * Undo the effects of the last redirection.
5418 popredir(int drop, int restore)
5420 struct redirtab *rp;
5423 if (--g_nullredirs >= 0 || redirlist == NULL)
5427 for (i = 0; i < rp->pair_count; i++) {
5428 int fd = rp->two_fd[i].orig;
5429 int copy = rp->two_fd[i].copy;
5430 if (copy == CLOSED) {
5435 if (copy != EMPTY) {
5436 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5437 copy &= ~COPYFD_RESTORE;
5439 copyfd(copy, fd | COPYFD_EXACT);
5441 close(copy & ~COPYFD_RESTORE);
5444 redirlist = rp->next;
5445 g_nullredirs = rp->nullredirs;
5451 * Undo all redirections. Called on error or interrupt.
5455 * Discard all saved file descriptors.
5458 clearredir(int drop)
5464 popredir(drop, /*restore:*/ 0);
5469 redirectsafe(union node *redir, int flags)
5472 volatile int saveint;
5473 struct jmploc *volatile savehandler = exception_handler;
5474 struct jmploc jmploc;
5477 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5478 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5480 exception_handler = &jmploc;
5481 redirect(redir, flags);
5483 exception_handler = savehandler;
5484 if (err && exception_type != EXERROR)
5485 longjmp(exception_handler->loc, 1);
5486 RESTORE_INT(saveint);
5491 /* ============ Routines to expand arguments to commands
5493 * We have to deal with backquotes, shell variables, and file metacharacters.
5496 #if ENABLE_SH_MATH_SUPPORT
5498 ash_arith(const char *s)
5500 arith_state_t math_state;
5503 math_state.lookupvar = lookupvar;
5504 math_state.setvar = setvar0;
5505 //math_state.endofname = endofname;
5508 result = arith(&math_state, s);
5509 if (math_state.errmsg)
5510 ash_msg_and_raise_error(math_state.errmsg);
5520 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5521 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5522 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5523 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5524 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5525 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5526 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5527 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5528 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5532 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5533 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5534 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5535 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5536 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5538 /* Add CTLESC when necessary. */
5539 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5540 /* Do not skip NUL characters. */
5541 #define QUOTES_KEEPNUL EXP_TILDE
5544 * Structure specifying which parts of the string should be searched
5545 * for IFS characters.
5548 struct ifsregion *next; /* next region in list */
5549 int begoff; /* offset of start of region */
5550 int endoff; /* offset of end of region */
5551 int nulonly; /* search for nul bytes only */
5555 struct strlist *list;
5556 struct strlist **lastp;
5559 /* output of current string */
5560 static char *expdest;
5561 /* list of back quote expressions */
5562 static struct nodelist *argbackq;
5563 /* first struct in list of ifs regions */
5564 static struct ifsregion ifsfirst;
5565 /* last struct in list */
5566 static struct ifsregion *ifslastp;
5567 /* holds expanded arg list */
5568 static struct arglist exparg;
5573 #if !ENABLE_SH_MATH_SUPPORT
5574 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5575 typedef long arith_t;
5576 # define ARITH_FMT "%ld"
5583 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5584 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5585 STADJUST(len, expdest);
5590 esclen(const char *start, const char *p)
5594 while (p > start && (unsigned char)*--p == CTLESC) {
5601 * Remove any CTLESC characters from a string.
5604 rmescapes(char *str, int flag)
5606 static const char qchars[] ALIGN1 = {
5607 IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
5611 unsigned protect_against_glob;
5613 IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
5615 p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
5621 if (flag & RMESCAPE_ALLOC) {
5622 size_t len = p - str;
5623 size_t fulllen = len + strlen(p) + 1;
5625 if (flag & RMESCAPE_GROW) {
5626 int strloc = str - (char *)stackblock();
5627 r = makestrspace(fulllen, expdest);
5628 /* p and str may be invalidated by makestrspace */
5629 str = (char *)stackblock() + strloc;
5631 } else if (flag & RMESCAPE_HEAP) {
5632 r = ckmalloc(fulllen);
5634 r = stalloc(fulllen);
5638 q = (char *)memcpy(q, str, len) + len;
5643 globbing = flag & RMESCAPE_GLOB;
5644 protect_against_glob = globbing;
5646 if ((unsigned char)*p == CTLQUOTEMARK) {
5647 // Note: both inquotes and protect_against_glob only affect whether
5648 inquotes = ~inquotes;
5650 protect_against_glob = globbing;
5653 if ((unsigned char)*p == CTLESC) {
5657 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5659 if (protect_against_glob) {
5662 } else if (*p == '\\' && !inquotes) {
5663 /* naked back slash */
5664 protect_against_glob = 0;
5667 #if ENABLE_ASH_BASH_COMPAT
5668 else if (*p == '/' && slash) {
5669 /* stop handling globbing and mark location of slash */
5670 globbing = slash = 0;
5674 protect_against_glob = globbing;
5679 if (flag & RMESCAPE_GROW) {
5681 STADJUST(q - r + 1, expdest);
5685 #define pmatch(a, b) !fnmatch((a), (b), 0)
5688 * Prepare a pattern for a expmeta (internal glob(3)) call.
5690 * Returns an stalloced string.
5693 preglob(const char *pattern, int flag)
5695 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5699 * Put a string on the stack.
5702 memtodest(const char *p, size_t len, int syntax, int quotes)
5709 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5712 unsigned char c = *p++;
5714 int n = SIT(c, syntax);
5715 if ((quotes & QUOTES_ESC)
5717 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
5723 } else if (!(quotes & QUOTES_KEEPNUL))
5732 strtodest(const char *p, int syntax, int quotes)
5734 size_t len = strlen(p);
5735 memtodest(p, len, syntax, quotes);
5740 * Record the fact that we have to scan this region of the
5741 * string for IFS characters.
5744 recordregion(int start, int end, int nulonly)
5746 struct ifsregion *ifsp;
5748 if (ifslastp == NULL) {
5752 ifsp = ckzalloc(sizeof(*ifsp));
5753 /*ifsp->next = NULL; - ckzalloc did it */
5754 ifslastp->next = ifsp;
5758 ifslastp->begoff = start;
5759 ifslastp->endoff = end;
5760 ifslastp->nulonly = nulonly;
5764 removerecordregions(int endoff)
5766 if (ifslastp == NULL)
5769 if (ifsfirst.endoff > endoff) {
5770 while (ifsfirst.next) {
5771 struct ifsregion *ifsp;
5773 ifsp = ifsfirst.next->next;
5774 free(ifsfirst.next);
5775 ifsfirst.next = ifsp;
5778 if (ifsfirst.begoff > endoff) {
5781 ifslastp = &ifsfirst;
5782 ifsfirst.endoff = endoff;
5787 ifslastp = &ifsfirst;
5788 while (ifslastp->next && ifslastp->next->begoff < endoff)
5789 ifslastp = ifslastp->next;
5790 while (ifslastp->next) {
5791 struct ifsregion *ifsp;
5793 ifsp = ifslastp->next->next;
5794 free(ifslastp->next);
5795 ifslastp->next = ifsp;
5798 if (ifslastp->endoff > endoff)
5799 ifslastp->endoff = endoff;
5803 exptilde(char *startp, char *p, int flags)
5809 int quotes = flags & QUOTES_ESC;
5813 while ((c = *++p) != '\0') {
5820 if (flags & EXP_VARTILDE)
5830 if (*name == '\0') {
5831 home = lookupvar("HOME");
5833 pw = getpwnam(name);
5838 if (!home || !*home)
5841 strtodest(home, SQSYNTAX, quotes);
5849 * Execute a command inside back quotes. If it's a builtin command, we
5850 * want to save its output in a block obtained from malloc. Otherwise
5851 * we fork off a subprocess and get the output of the command via a pipe.
5852 * Should be called with interrupts off.
5854 struct backcmd { /* result of evalbackcmd */
5855 int fd; /* file descriptor to read from */
5856 int nleft; /* number of chars in buffer */
5857 char *buf; /* buffer */
5858 struct job *jp; /* job structure for command */
5861 /* These forward decls are needed to use "eval" code for backticks handling: */
5862 static uint8_t back_exitstatus; /* exit status of backquoted command */
5863 #define EV_EXIT 01 /* exit after evaluating tree */
5864 static int evaltree(union node *, int);
5866 static void FAST_FUNC
5867 evalbackcmd(union node *n, struct backcmd *result)
5878 saveherefd = herefd;
5886 ash_msg_and_raise_error("pipe call failed");
5887 jp = makejob(/*n,*/ 1);
5888 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5893 copyfd(pip[1], 1 | COPYFD_EXACT);
5897 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5901 result->fd = pip[0];
5904 herefd = saveherefd;
5906 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5907 result->fd, result->buf, result->nleft, result->jp));
5911 * Expand stuff in backwards quotes.
5914 expbackq(union node *cmd, int flag)
5922 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
5923 struct stackmark smark;
5926 startloc = expdest - (char *)stackblock();
5927 pushstackmark(&smark, startloc);
5928 evalbackcmd(cmd, &in);
5929 popstackmark(&smark);
5936 memtodest(p, i, syntax, flag & QUOTES_ESC);
5940 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
5941 TRACE(("expbackq: read returns %d\n", i));
5950 back_exitstatus = waitforjob(in.jp);
5954 /* Eat all trailing newlines */
5956 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5960 if (!(flag & EXP_QUOTED))
5961 recordregion(startloc, dest - (char *)stackblock(), 0);
5962 TRACE(("evalbackq: size:%d:'%.*s'\n",
5963 (int)((dest - (char *)stackblock()) - startloc),
5964 (int)((dest - (char *)stackblock()) - startloc),
5965 stackblock() + startloc));
5968 #if ENABLE_SH_MATH_SUPPORT
5970 * Expand arithmetic expression. Backup to start of expression,
5971 * evaluate, place result in (backed up) result, adjust string position.
5983 * This routine is slightly over-complicated for
5984 * efficiency. Next we scan backwards looking for the
5985 * start of arithmetic.
5987 start = stackblock();
5994 while ((unsigned char)*p != CTLARI) {
5998 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6003 esc = esclen(start, p);
6013 removerecordregions(begoff);
6017 if (flag & QUOTES_ESC)
6018 rmescapes(p + 1, 0);
6020 len = cvtnum(ash_arith(p + 1));
6022 if (!(flag & EXP_QUOTED))
6023 recordregion(begoff, begoff + len, 0);
6027 /* argstr needs it */
6028 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6031 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6032 * characters to allow for further processing. Otherwise treat
6033 * $@ like $* since no splitting will be performed.
6035 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6036 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6037 * for correct expansion of "B=$A" word.
6040 argstr(char *p, int flags, struct strlist *var_str_list)
6042 static const char spclchars[] ALIGN1 = {
6050 #if ENABLE_SH_MATH_SUPPORT
6055 const char *reject = spclchars;
6056 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6061 if (!(flags & EXP_VARTILDE)) {
6063 } else if (flags & EXP_VARTILDE2) {
6068 if (flags & EXP_TILDE) {
6071 flags &= ~EXP_TILDE;
6075 p = exptilde(p, q, flags);
6078 startloc = expdest - (char *)stackblock();
6082 length += strcspn(p + length, reject);
6086 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6088 /* c == '=' || c == ':' || c == CTLENDARI */
6094 expdest = stack_nputstr(p, length, expdest);
6095 newloc = expdest - (char *)stackblock();
6096 if (breakall && !inquotes && newloc > startloc) {
6097 recordregion(startloc, newloc, 0);
6108 if (flags & EXP_VARTILDE2) {
6112 flags |= EXP_VARTILDE2;
6117 * sort of a hack - expand tildes in variable
6118 * assignments (after the first '=' and after ':'s).
6127 case CTLENDVAR: /* ??? */
6130 inquotes ^= EXP_QUOTED;
6131 /* "$@" syntax adherence hack */
6132 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6133 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6137 if (flags & QUOTES_ESC) {
6148 * Quoted parameter expansion pattern: remove quote
6149 * unless inside inner quotes or we have a literal
6152 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6153 EXP_QPAT && *p != '\\')
6158 TRACE(("argstr: evalvar('%s')\n", p));
6159 p = evalvar(p, flags | inquotes, var_str_list);
6160 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6163 expbackq(argbackq->n, flags | inquotes);
6164 argbackq = argbackq->next;
6166 #if ENABLE_SH_MATH_SUPPORT
6169 expari(flags | inquotes);
6178 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6179 char *pattern, int quotes, int zero)
6188 const char *s = loc2;
6195 match = pmatch(pattern, s);
6200 if (quotes && (unsigned char)*loc == CTLESC)
6209 scanright(char *startp, char *rmesc, char *rmescend,
6210 char *pattern, int quotes, int match_at_start)
6212 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6213 int try2optimize = match_at_start;
6219 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6220 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6221 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6223 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6224 * and on each iteration they go back two/one char until they reach the beginning.
6225 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6227 /* TODO: document in what other circumstances we are called. */
6229 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6232 const char *s = loc2;
6233 if (match_at_start) {
6237 match = pmatch(pattern, s);
6238 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6242 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6244 /* Maybe we can optimize this:
6245 * if pattern ends with unescaped *, we can avoid checking
6246 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6247 * it wont match truncated "raw_value_of_" strings too.
6249 unsigned plen = strlen(pattern);
6250 /* Does it end with "*"? */
6251 if (plen != 0 && pattern[--plen] == '*') {
6252 /* "xxxx*" is not escaped */
6253 /* "xxx\*" is escaped */
6254 /* "xx\\*" is not escaped */
6255 /* "x\\\*" is escaped */
6257 while (plen != 0 && pattern[--plen] == '\\')
6260 break; /* ends with unescaped "*" */
6268 esc = esclen(startp, loc);
6279 static void varunset(const char *, const char *, const char *, int) NORETURN;
6281 varunset(const char *end, const char *var, const char *umsg, int varflags)
6287 msg = "parameter not set";
6289 if ((unsigned char)*end == CTLENDVAR) {
6290 if (varflags & VSNUL)
6296 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6300 subevalvar(char *p, char *varname, int strloc, int subtype,
6301 int startloc, int varflags, int flag, struct strlist *var_str_list)
6303 struct nodelist *saveargbackq = argbackq;
6304 int quotes = flag & QUOTES_ESC;
6307 char *rmesc, *rmescend;
6309 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6310 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6311 int saveherefd = herefd;
6312 int amount, resetloc;
6313 IF_ASH_BASH_COMPAT(int workloc;)
6315 char *(*scan)(char*, char*, char*, char*, int, int);
6317 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6318 // p, varname, strloc, subtype, startloc, varflags, quotes);
6321 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6322 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6324 STPUTC('\0', expdest);
6325 herefd = saveherefd;
6326 argbackq = saveargbackq;
6327 startp = (char *)stackblock() + startloc;
6331 setvar0(varname, startp);
6332 amount = startp - expdest;
6333 STADJUST(amount, expdest);
6337 varunset(p, varname, startp, varflags);
6340 #if ENABLE_ASH_BASH_COMPAT
6342 //TODO: support more general format ${v:EXPR:EXPR},
6343 // where EXPR follows $(()) rules
6344 loc = str = stackblock() + strloc;
6345 /* Read POS in ${var:POS:LEN} */
6346 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6347 len = str - startp - 1;
6349 /* *loc != '\0', guaranteed by parser */
6353 /* Adjust the length by the number of escapes */
6354 for (ptr = startp; ptr < (str - 1); ptr++) {
6355 if ((unsigned char)*ptr == CTLESC) {
6363 if (*loc++ == ':') {
6367 /* Skip POS in ${var:POS:LEN} */
6369 while (*loc && *loc != ':') {
6371 * bash complains on: var=qwe; echo ${var:1a:123}
6373 ash_msg_and_raise_error(msg_illnum, str);
6377 if (*loc++ == ':') {
6382 /* ${VAR:$((-n)):l} starts n chars from the end */
6383 pos = orig_len + pos;
6385 if ((unsigned)pos >= orig_len) {
6386 /* apart from obvious ${VAR:999999:l},
6387 * covers ${VAR:$((-9999999)):l} - result is ""
6393 if (len > (orig_len - pos))
6394 len = orig_len - pos;
6396 for (str = startp; pos; str++, pos--) {
6397 if (quotes && (unsigned char)*str == CTLESC)
6400 for (loc = startp; len; len--) {
6401 if (quotes && (unsigned char)*str == CTLESC)
6406 amount = loc - expdest;
6407 STADJUST(amount, expdest);
6412 resetloc = expdest - (char *)stackblock();
6414 /* We'll comeback here if we grow the stack while handling
6415 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6416 * stack will need rebasing, and we'll need to remove our work
6419 IF_ASH_BASH_COMPAT(restart:)
6421 amount = expdest - ((char *)stackblock() + resetloc);
6422 STADJUST(-amount, expdest);
6423 startp = (char *)stackblock() + startloc;
6426 rmescend = (char *)stackblock() + strloc;
6428 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6429 if (rmesc != startp) {
6431 startp = (char *)stackblock() + startloc;
6435 str = (char *)stackblock() + strloc;
6437 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6438 * The result is a_\_z_c (not a\_\_z_c)!
6440 * The search pattern and replace string treat backslashes differently!
6441 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6442 * and string. It's only used on the first call.
6444 preglob(str, IF_ASH_BASH_COMPAT(
6445 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6446 RMESCAPE_SLASH :) 0);
6448 #if ENABLE_ASH_BASH_COMPAT
6449 workloc = expdest - (char *)stackblock();
6450 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6454 repl = strchr(str, CTLESC);
6460 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6462 /* If there's no pattern to match, return the expansion unmolested */
6471 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6472 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6474 /* No match, advance */
6475 char *restart_detect = stackblock();
6477 STPUTC(*idx, expdest);
6478 if (quotes && (unsigned char)*idx == CTLESC) {
6481 STPUTC(*idx, expdest);
6483 if (stackblock() != restart_detect)
6488 /* continue; - prone to quadratic behavior, smarter code: */
6491 if (str[0] == '*') {
6492 /* Pattern is "*foo". If "*foo" does not match "long_string",
6493 * it would never match "ong_string" etc, no point in trying.
6500 if (subtype == VSREPLACEALL) {
6502 if (quotes && (unsigned char)*idx == CTLESC)
6511 //bb_error_msg("repl:'%s'", repl);
6512 for (loc = (char*)repl; *loc; loc++) {
6513 char *restart_detect = stackblock();
6514 if (quotes && *loc == '\\') {
6515 STPUTC(CTLESC, expdest);
6518 STPUTC(*loc, expdest);
6519 if (stackblock() != restart_detect)
6524 if (subtype == VSREPLACE) {
6525 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6527 char *restart_detect = stackblock();
6528 STPUTC(*idx, expdest);
6529 if (stackblock() != restart_detect)
6538 /* We've put the replaced text into a buffer at workloc, now
6539 * move it to the right place and adjust the stack.
6541 STPUTC('\0', expdest);
6542 startp = (char *)stackblock() + startloc;
6543 memmove(startp, (char *)stackblock() + workloc, len + 1);
6544 //bb_error_msg("startp:'%s'", startp);
6545 amount = expdest - (startp + len);
6546 STADJUST(-amount, expdest);
6549 #endif /* ENABLE_ASH_BASH_COMPAT */
6551 subtype -= VSTRIMRIGHT;
6553 if (subtype < 0 || subtype > 7)
6556 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6557 zero = subtype >> 1;
6558 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6559 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6561 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6564 memmove(startp, loc, str - loc);
6565 loc = startp + (str - loc) - 1;
6568 amount = loc - expdest;
6569 STADJUST(amount, expdest);
6575 * Add the value of a specialized variable to the stack string.
6576 * name parameter (examples):
6577 * ash -c 'echo $1' name:'1='
6578 * ash -c 'echo $qwe' name:'qwe='
6579 * ash -c 'echo $$' name:'$='
6580 * ash -c 'echo ${$}' name:'$='
6581 * ash -c 'echo ${$##q}' name:'$=q'
6582 * ash -c 'echo ${#$}' name:'$='
6583 * note: examples with bad shell syntax:
6584 * ash -c 'echo ${#$1}' name:'$=1'
6585 * ash -c 'echo ${#1#}' name:'1=#'
6587 static NOINLINE ssize_t
6588 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6595 int quoted = flags & EXP_QUOTED;
6596 int subtype = varflags & VSTYPE;
6597 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6598 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6599 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6601 sep = quoted ? ((flags & EXP_FULL) << CHAR_BIT) : 0;
6611 num = shellparam.nparam;
6619 goto check_1char_name;
6621 expdest = makestrspace(NOPTS, expdest);
6622 for (i = NOPTS - 1; i >= 0; i--) {
6624 USTPUTC(optletters(i), expdest);
6630 /* handles cases similar to ${#$1} */
6631 if (name[2] != '\0')
6632 raise_error_syntax("bad substitution");
6639 if (quoted && (flags & EXP_FULL)) {
6640 /* note: this is not meant as PEOF value */
6641 sep = 1 << CHAR_BIT;
6646 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6652 while ((p = *ap++) != NULL) {
6653 len += strtodest(p, syntax, quotes);
6657 memtodest(&sepc, 1, syntax, quotes);
6661 } /* case '@' and '*' */
6672 num = atoi(name); /* number(name) fails on ${N#str} etc */
6673 if (num < 0 || num > shellparam.nparam)
6675 p = num ? shellparam.p[num - 1] : arg0;
6678 /* NB: name has form "VAR=..." */
6680 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6681 * which should be considered before we check variables. */
6683 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6687 str = var_str_list->text;
6688 eq = strchr(str, '=');
6689 if (!eq) /* stop at first non-assignment */
6692 if (name_len == (unsigned)(eq - str)
6693 && strncmp(str, name, name_len) == 0
6696 /* goto value; - WRONG! */
6697 /* think "A=1 A=2 B=$A" */
6699 var_str_list = var_str_list->next;
6700 } while (var_str_list);
6704 p = lookupvar(name);
6709 len = strtodest(p, syntax, quotes);
6710 #if ENABLE_UNICODE_SUPPORT
6711 if (subtype == VSLENGTH && len > 0) {
6712 reinit_unicode_for_ash();
6713 if (unicode_status == UNICODE_ON) {
6714 STADJUST(-len, expdest);
6716 len = unicode_strlen(p);
6724 STADJUST(-len, expdest);
6729 * Expand a variable, and return a pointer to the next character in the
6733 evalvar(char *p, int flags, struct strlist *var_str_list)
6744 varflags = (unsigned char) *p++;
6745 subtype = varflags & VSTYPE;
6746 quoted = flags & EXP_QUOTED;
6748 easy = (!quoted || (*var == '@' && shellparam.nparam));
6749 startloc = expdest - (char *)stackblock();
6750 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6753 varlen = varvalue(var, varflags, flags, var_str_list);
6754 if (varflags & VSNUL)
6757 if (subtype == VSPLUS) {
6758 varlen = -1 - varlen;
6762 if (subtype == VSMINUS) {
6767 flags | EXP_TILDE | EXP_WORD,
6777 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6779 if (subevalvar(p, var, /* strloc: */ 0,
6780 subtype, startloc, varflags,
6781 /* quotes: */ flags & ~QUOTES_ESC,
6786 * Remove any recorded regions beyond
6789 removerecordregions(startloc);
6799 if (varlen < 0 && uflag)
6800 varunset(p, var, 0, 0);
6802 if (subtype == VSLENGTH) {
6803 cvtnum(varlen > 0 ? varlen : 0);
6807 if (subtype == VSNORMAL) {
6818 case VSTRIMRIGHTMAX:
6819 #if ENABLE_ASH_BASH_COMPAT
6832 * Terminate the string and start recording the pattern
6835 STPUTC('\0', expdest);
6836 patloc = expdest - (char *)stackblock();
6837 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6838 startloc, varflags, flags, var_str_list)) {
6839 int amount = expdest - (
6840 (char *)stackblock() + patloc - 1
6842 STADJUST(-amount, expdest);
6844 /* Remove any recorded regions beyond start of variable */
6845 removerecordregions(startloc);
6847 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6851 if (subtype != VSNORMAL) { /* skip to end of alternative */
6854 unsigned char c = *p++;
6857 else if (c == CTLBACKQ) {
6859 argbackq = argbackq->next;
6860 } else if (c == CTLVAR) {
6861 if ((*p++ & VSTYPE) != VSNORMAL)
6863 } else if (c == CTLENDVAR) {
6873 * Break the argument string into pieces based upon IFS and add the
6874 * strings to the argument list. The regions of the string to be
6875 * searched for IFS characters have been stored by recordregion.
6878 ifsbreakup(char *string, struct arglist *arglist)
6880 struct ifsregion *ifsp;
6885 const char *ifs, *realifs;
6890 if (ifslastp != NULL) {
6893 realifs = ifsset() ? ifsval() : defifs;
6896 p = string + ifsp->begoff;
6897 nulonly = ifsp->nulonly;
6898 ifs = nulonly ? nullstr : realifs;
6900 while (p < string + ifsp->endoff) {
6902 if ((unsigned char)*p == CTLESC)
6904 if (!strchr(ifs, *p)) {
6909 ifsspc = (strchr(defifs, *p) != NULL);
6910 /* Ignore IFS whitespace at start */
6911 if (q == start && ifsspc) {
6917 sp = stzalloc(sizeof(*sp));
6919 *arglist->lastp = sp;
6920 arglist->lastp = &sp->next;
6924 if (p >= string + ifsp->endoff) {
6928 if ((unsigned char)*p == CTLESC)
6930 if (strchr(ifs, *p) == NULL) {
6934 if (strchr(defifs, *p) == NULL) {
6949 } while (ifsp != NULL);
6958 sp = stzalloc(sizeof(*sp));
6960 *arglist->lastp = sp;
6961 arglist->lastp = &sp->next;
6967 struct ifsregion *p;
6972 struct ifsregion *ifsp;
6978 ifsfirst.next = NULL;
6983 * Add a file name to the list.
6986 addfname(const char *name)
6990 sp = stzalloc(sizeof(*sp));
6991 sp->text = sstrdup(name);
6993 exparg.lastp = &sp->next;
6996 /* If we want to use glob() from libc... */
6999 /* Add the result of glob() to the list */
7001 addglob(const glob_t *pglob)
7003 char **p = pglob->gl_pathv;
7010 expandmeta(struct strlist *str /*, int flag*/)
7012 /* TODO - EXP_REDIR */
7022 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7024 * GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7025 * TODO?: GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7027 i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7032 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7033 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7044 *exparg.lastp = str;
7045 rmescapes(str->text, 0);
7046 exparg.lastp = &str->next;
7048 default: /* GLOB_NOSPACE */
7051 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7058 /* Homegrown globbing code. (dash also has both, uses homegrown one.) */
7061 * Do metacharacter (i.e. *, ?, [...]) expansion.
7064 expmeta(char *expdir, char *enddir, char *name)
7080 for (p = name; esc = 0, *p; p += esc + 1) {
7081 if (*p == '*' || *p == '?')
7083 else if (*p == '[') {
7090 if (*q == '/' || *q == '\0')
7100 if (p[esc] == '/') {
7103 start = p + esc + 1;
7107 if (metaflag == 0) { /* we've reached the end of the file name */
7108 if (enddir != expdir)
7116 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7127 } while (p < start);
7129 if (enddir == expdir) {
7131 } else if (enddir == expdir + 1 && *expdir == '/') {
7140 if (enddir != expdir)
7142 if (*endname == 0) {
7155 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7156 if (dp->d_name[0] == '.' && !matchdot)
7158 if (pmatch(start, dp->d_name)) {
7160 strcpy(enddir, dp->d_name);
7163 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7166 expmeta(expdir, p, endname);
7172 endname[-esc - 1] = esc ? '\\' : '/';
7175 static struct strlist *
7176 msort(struct strlist *list, int len)
7178 struct strlist *p, *q = NULL;
7179 struct strlist **lpp;
7187 for (n = half; --n >= 0;) {
7191 q->next = NULL; /* terminate first half of list */
7192 q = msort(list, half); /* sort first half of list */
7193 p = msort(p, len - half); /* sort second half */
7196 #if ENABLE_LOCALE_SUPPORT
7197 if (strcoll(p->text, q->text) < 0)
7199 if (strcmp(p->text, q->text) < 0)
7223 * Sort the results of file name expansion. It calculates the number of
7224 * strings to sort and then calls msort (short for merge sort) to do the
7227 static struct strlist *
7228 expsort(struct strlist *str)
7234 for (sp = str; sp; sp = sp->next)
7236 return msort(str, len);
7240 expandmeta(struct strlist *str /*, int flag*/)
7242 static const char metachars[] ALIGN1 = {
7245 /* TODO - EXP_REDIR */
7249 struct strlist **savelastp;
7255 if (!strpbrk(str->text, metachars))
7257 savelastp = exparg.lastp;
7260 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7262 int i = strlen(str->text);
7263 //BUGGY estimation of how long expanded name can be
7264 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7266 expmeta(expdir, expdir, p);
7271 if (exparg.lastp == savelastp) {
7276 *exparg.lastp = str;
7277 rmescapes(str->text, 0);
7278 exparg.lastp = &str->next;
7280 *exparg.lastp = NULL;
7281 *savelastp = sp = expsort(*savelastp);
7282 while (sp->next != NULL)
7284 exparg.lastp = &sp->next;
7289 #endif /* our globbing code */
7292 * Perform variable substitution and command substitution on an argument,
7293 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7294 * perform splitting and file name expansion. When arglist is NULL, perform
7295 * here document expansion.
7298 expandarg(union node *arg, struct arglist *arglist, int flag)
7303 argbackq = arg->narg.backquote;
7304 STARTSTACKSTR(expdest);
7305 ifsfirst.next = NULL;
7307 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7308 argstr(arg->narg.text, flag,
7309 /* var_str_list: */ arglist ? arglist->list : NULL);
7310 p = _STPUTC('\0', expdest);
7312 if (arglist == NULL) {
7313 return; /* here document expanded */
7315 p = grabstackstr(p);
7316 TRACE(("expandarg: p:'%s'\n", p));
7317 exparg.lastp = &exparg.list;
7321 if (flag & EXP_FULL) {
7322 ifsbreakup(p, &exparg);
7323 *exparg.lastp = NULL;
7324 exparg.lastp = &exparg.list;
7325 expandmeta(exparg.list /*, flag*/);
7327 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7329 TRACE(("expandarg: rmescapes:'%s'\n", p));
7331 sp = stzalloc(sizeof(*sp));
7334 exparg.lastp = &sp->next;
7338 *exparg.lastp = NULL;
7340 *arglist->lastp = exparg.list;
7341 arglist->lastp = exparg.lastp;
7346 * Expand shell variables and backquotes inside a here document.
7349 expandhere(union node *arg, int fd)
7352 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7353 full_write(fd, stackblock(), expdest - (char *)stackblock());
7357 * Returns true if the pattern matches the string.
7360 patmatch(char *pattern, const char *string)
7362 return pmatch(preglob(pattern, 0), string);
7366 * See if a pattern matches in a case statement.
7369 casematch(union node *pattern, char *val)
7371 struct stackmark smark;
7374 setstackmark(&smark);
7375 argbackq = pattern->narg.backquote;
7376 STARTSTACKSTR(expdest);
7378 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7379 /* var_str_list: */ NULL);
7380 STACKSTRNUL(expdest);
7381 result = patmatch(stackblock(), val);
7382 popstackmark(&smark);
7387 /* ============ find_command */
7391 int (*builtin)(int, char **) FAST_FUNC;
7392 /* unsigned flags; */
7394 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7395 /* "regular" builtins always take precedence over commands,
7396 * regardless of PATH=....%builtin... position */
7397 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7398 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7401 smallint cmdtype; /* CMDxxx */
7404 /* index >= 0 for commands without path (slashes) */
7405 /* (TODO: what exactly does the value mean? PATH position?) */
7406 /* index == -1 for commands with slashes */
7407 /* index == (-2 - applet_no) for NOFORK applets */
7408 const struct builtincmd *cmd;
7409 struct funcnode *func;
7412 /* values of cmdtype */
7413 #define CMDUNKNOWN -1 /* no entry in table for command */
7414 #define CMDNORMAL 0 /* command is an executable program */
7415 #define CMDFUNCTION 1 /* command is a shell function */
7416 #define CMDBUILTIN 2 /* command is a shell builtin */
7418 /* action to find_command() */
7419 #define DO_ERR 0x01 /* prints errors */
7420 #define DO_ABS 0x02 /* checks absolute paths */
7421 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7422 #define DO_ALTPATH 0x08 /* using alternate path */
7423 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7425 static void find_command(char *, struct cmdentry *, int, const char *);
7428 /* ============ Hashing commands */
7431 * When commands are first encountered, they are entered in a hash table.
7432 * This ensures that a full path search will not have to be done for them
7433 * on each invocation.
7435 * We should investigate converting to a linear search, even though that
7436 * would make the command name "hash" a misnomer.
7440 struct tblentry *next; /* next entry in hash chain */
7441 union param param; /* definition of builtin function */
7442 smallint cmdtype; /* CMDxxx */
7443 char rehash; /* if set, cd done since entry created */
7444 char cmdname[1]; /* name of command */
7447 static struct tblentry **cmdtable;
7448 #define INIT_G_cmdtable() do { \
7449 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7452 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7456 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7458 #if ENABLE_FEATURE_SH_STANDALONE
7459 if (applet_no >= 0) {
7460 if (APPLET_IS_NOEXEC(applet_no)) {
7464 run_applet_no_and_exit(applet_no, argv);
7466 /* re-exec ourselves with the new arguments */
7467 execve(bb_busybox_exec_path, argv, envp);
7468 /* If they called chroot or otherwise made the binary no longer
7469 * executable, fall through */
7476 execve(cmd, argv, envp);
7477 } while (errno == EINTR);
7479 execve(cmd, argv, envp);
7481 if (cmd == (char*) bb_busybox_exec_path) {
7482 /* We already visited ENOEXEC branch below, don't do it again */
7483 //TODO: try execve(initial_argv0_of_shell, argv, envp) before giving up?
7487 if (errno == ENOEXEC) {
7488 /* Run "cmd" as a shell script:
7489 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7490 * "If the execve() function fails with ENOEXEC, the shell
7491 * shall execute a command equivalent to having a shell invoked
7492 * with the command name as its first operand,
7493 * with any remaining arguments passed to the new shell"
7495 * That is, do not use $SHELL, user's shell, or /bin/sh;
7496 * just call ourselves.
7498 * Note that bash reads ~80 chars of the file, and if it sees
7499 * a zero byte before it sees newline, it doesn't try to
7500 * interpret it, but fails with "cannot execute binary file"
7501 * message and exit code 126. For one, this prevents attempts
7502 * to interpret foreign ELF binaries as shell scripts.
7507 for (ap = argv; *ap; ap++)
7509 new = ckmalloc((ap - argv + 2) * sizeof(new[0]));
7510 new[0] = (char*) "ash";
7513 while ((*ap++ = *++argv) != NULL)
7515 cmd = (char*) bb_busybox_exec_path;
7522 * Exec a program. Never returns. If you change this routine, you may
7523 * have to change the find_command routine as well.
7525 static void shellexec(char **, const char *, int) NORETURN;
7527 shellexec(char **argv, const char *path, int idx)
7533 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7535 clearredir(/*drop:*/ 1);
7536 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7537 if (strchr(argv[0], '/') != NULL
7538 #if ENABLE_FEATURE_SH_STANDALONE
7539 || (applet_no = find_applet_by_name(argv[0])) >= 0
7542 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7543 if (applet_no >= 0) {
7544 /* We tried execing ourself, but it didn't work.
7545 * Maybe /proc/self/exe doesn't exist?
7554 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7555 if (--idx < 0 && pathopt == NULL) {
7556 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7557 if (errno != ENOENT && errno != ENOTDIR)
7564 /* Map to POSIX errors */
7576 exitstatus = exerrno;
7577 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7578 argv[0], e, suppress_int));
7579 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7584 printentry(struct tblentry *cmdp)
7590 idx = cmdp->param.index;
7593 name = path_advance(&path, cmdp->cmdname);
7595 } while (--idx >= 0);
7596 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7600 * Clear out command entries. The argument specifies the first entry in
7601 * PATH which has changed.
7604 clearcmdentry(int firstchange)
7606 struct tblentry **tblp;
7607 struct tblentry **pp;
7608 struct tblentry *cmdp;
7611 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7613 while ((cmdp = *pp) != NULL) {
7614 if ((cmdp->cmdtype == CMDNORMAL &&
7615 cmdp->param.index >= firstchange)
7616 || (cmdp->cmdtype == CMDBUILTIN &&
7617 builtinloc >= firstchange)
7630 * Locate a command in the command hash table. If "add" is nonzero,
7631 * add the command to the table if it is not already present. The
7632 * variable "lastcmdentry" is set to point to the address of the link
7633 * pointing to the entry, so that delete_cmd_entry can delete the
7636 * Interrupts must be off if called with add != 0.
7638 static struct tblentry **lastcmdentry;
7640 static struct tblentry *
7641 cmdlookup(const char *name, int add)
7643 unsigned int hashval;
7645 struct tblentry *cmdp;
7646 struct tblentry **pp;
7649 hashval = (unsigned char)*p << 4;
7651 hashval += (unsigned char)*p++;
7653 pp = &cmdtable[hashval % CMDTABLESIZE];
7654 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7655 if (strcmp(cmdp->cmdname, name) == 0)
7659 if (add && cmdp == NULL) {
7660 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7662 /* + 1 - already done because
7663 * tblentry::cmdname is char[1] */);
7664 /*cmdp->next = NULL; - ckzalloc did it */
7665 cmdp->cmdtype = CMDUNKNOWN;
7666 strcpy(cmdp->cmdname, name);
7673 * Delete the command entry returned on the last lookup.
7676 delete_cmd_entry(void)
7678 struct tblentry *cmdp;
7681 cmdp = *lastcmdentry;
7682 *lastcmdentry = cmdp->next;
7683 if (cmdp->cmdtype == CMDFUNCTION)
7684 freefunc(cmdp->param.func);
7690 * Add a new command entry, replacing any existing command entry for
7691 * the same name - except special builtins.
7694 addcmdentry(char *name, struct cmdentry *entry)
7696 struct tblentry *cmdp;
7698 cmdp = cmdlookup(name, 1);
7699 if (cmdp->cmdtype == CMDFUNCTION) {
7700 freefunc(cmdp->param.func);
7702 cmdp->cmdtype = entry->cmdtype;
7703 cmdp->param = entry->u;
7707 static int FAST_FUNC
7708 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7710 struct tblentry **pp;
7711 struct tblentry *cmdp;
7713 struct cmdentry entry;
7716 if (nextopt("r") != '\0') {
7721 if (*argptr == NULL) {
7722 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7723 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7724 if (cmdp->cmdtype == CMDNORMAL)
7732 while ((name = *argptr) != NULL) {
7733 cmdp = cmdlookup(name, 0);
7735 && (cmdp->cmdtype == CMDNORMAL
7736 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7740 find_command(name, &entry, DO_ERR, pathval());
7741 if (entry.cmdtype == CMDUNKNOWN)
7749 * Called when a cd is done. Marks all commands so the next time they
7750 * are executed they will be rehashed.
7755 struct tblentry **pp;
7756 struct tblentry *cmdp;
7758 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7759 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7760 if (cmdp->cmdtype == CMDNORMAL
7761 || (cmdp->cmdtype == CMDBUILTIN
7762 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7772 * Fix command hash table when PATH changed.
7773 * Called before PATH is changed. The argument is the new value of PATH;
7774 * pathval() still returns the old value at this point.
7775 * Called with interrupts off.
7777 static void FAST_FUNC
7778 changepath(const char *new)
7786 firstchange = 9999; /* assume no change */
7792 if ((*old == '\0' && *new == ':')
7793 || (*old == ':' && *new == '\0')
7797 old = new; /* ignore subsequent differences */
7801 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7808 if (builtinloc < 0 && idx_bltin >= 0)
7809 builtinloc = idx_bltin; /* zap builtins */
7810 if (builtinloc >= 0 && idx_bltin < 0)
7812 clearcmdentry(firstchange);
7813 builtinloc = idx_bltin;
7838 #if ENABLE_ASH_BASH_COMPAT
7849 typedef smallint token_id_t;
7851 /* first char is indicating which tokens mark the end of a list */
7852 static const char *const tokname_array[] = {
7866 #define KWDOFFSET 13
7867 /* the following are keywords */
7877 #if ENABLE_ASH_BASH_COMPAT
7889 /* Wrapper around strcmp for qsort/bsearch/... */
7891 pstrcmp(const void *a, const void *b)
7893 return strcmp((char*) a, (*(char**) b) + 1);
7896 static const char *const *
7897 findkwd(const char *s)
7899 return bsearch(s, tokname_array + KWDOFFSET,
7900 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7901 sizeof(tokname_array[0]), pstrcmp);
7905 * Locate and print what a word is...
7908 describe_command(char *command, const char *path, int describe_command_verbose)
7910 struct cmdentry entry;
7911 struct tblentry *cmdp;
7912 #if ENABLE_ASH_ALIAS
7913 const struct alias *ap;
7916 path = path ? path : pathval();
7918 if (describe_command_verbose) {
7922 /* First look at the keywords */
7923 if (findkwd(command)) {
7924 out1str(describe_command_verbose ? " is a shell keyword" : command);
7928 #if ENABLE_ASH_ALIAS
7929 /* Then look at the aliases */
7930 ap = lookupalias(command, 0);
7932 if (!describe_command_verbose) {
7937 out1fmt(" is an alias for %s", ap->val);
7941 /* Then check if it is a tracked alias */
7942 cmdp = cmdlookup(command, 0);
7944 entry.cmdtype = cmdp->cmdtype;
7945 entry.u = cmdp->param;
7947 /* Finally use brute force */
7948 find_command(command, &entry, DO_ABS, path);
7951 switch (entry.cmdtype) {
7953 int j = entry.u.index;
7959 p = path_advance(&path, command);
7963 if (describe_command_verbose) {
7965 (cmdp ? " a tracked alias for" : nullstr), p
7974 if (describe_command_verbose) {
7975 out1str(" is a shell function");
7982 if (describe_command_verbose) {
7983 out1fmt(" is a %sshell builtin",
7984 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7985 "special " : nullstr
7993 if (describe_command_verbose) {
7994 out1str(": not found\n");
8003 static int FAST_FUNC
8004 typecmd(int argc UNUSED_PARAM, char **argv)
8010 /* type -p ... ? (we don't bother checking for 'p') */
8011 if (argv[1] && argv[1][0] == '-') {
8016 err |= describe_command(argv[i++], NULL, verbose);
8021 #if ENABLE_ASH_CMDCMD
8022 static int FAST_FUNC
8023 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8030 const char *path = NULL;
8032 while ((c = nextopt("pvV")) != '\0')
8034 verify |= VERIFY_VERBOSE;
8036 verify |= VERIFY_BRIEF;
8042 path = bb_default_path;
8043 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8044 if (verify && (*argptr != NULL)) {
8045 return describe_command(*argptr, path, verify - VERIFY_BRIEF);
8053 /* ============ eval.c */
8055 static int funcblocksize; /* size of structures in function */
8056 static int funcstringsize; /* size of strings in node */
8057 static void *funcblock; /* block to allocate function from */
8058 static char *funcstring; /* block to allocate strings from */
8060 /* flags in argument to evaltree */
8061 #define EV_EXIT 01 /* exit after evaluating tree */
8062 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8064 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8065 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8066 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8067 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8068 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8069 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8070 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8071 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8072 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8073 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8074 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8075 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8076 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8077 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8078 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8079 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8080 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8081 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8082 #if ENABLE_ASH_BASH_COMPAT
8083 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8085 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8086 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8087 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8088 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8089 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8090 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8091 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8092 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8093 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8096 static void calcsize(union node *n);
8099 sizenodelist(struct nodelist *lp)
8102 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8109 calcsize(union node *n)
8113 funcblocksize += nodesize[n->type];
8116 calcsize(n->ncmd.redirect);
8117 calcsize(n->ncmd.args);
8118 calcsize(n->ncmd.assign);
8121 sizenodelist(n->npipe.cmdlist);
8126 calcsize(n->nredir.redirect);
8127 calcsize(n->nredir.n);
8134 calcsize(n->nbinary.ch2);
8135 calcsize(n->nbinary.ch1);
8138 calcsize(n->nif.elsepart);
8139 calcsize(n->nif.ifpart);
8140 calcsize(n->nif.test);
8143 funcstringsize += strlen(n->nfor.var) + 1;
8144 calcsize(n->nfor.body);
8145 calcsize(n->nfor.args);
8148 calcsize(n->ncase.cases);
8149 calcsize(n->ncase.expr);
8152 calcsize(n->nclist.body);
8153 calcsize(n->nclist.pattern);
8154 calcsize(n->nclist.next);
8158 sizenodelist(n->narg.backquote);
8159 funcstringsize += strlen(n->narg.text) + 1;
8160 calcsize(n->narg.next);
8163 #if ENABLE_ASH_BASH_COMPAT
8170 calcsize(n->nfile.fname);
8171 calcsize(n->nfile.next);
8175 calcsize(n->ndup.vname);
8176 calcsize(n->ndup.next);
8180 calcsize(n->nhere.doc);
8181 calcsize(n->nhere.next);
8184 calcsize(n->nnot.com);
8190 nodeckstrdup(char *s)
8192 char *rtn = funcstring;
8194 strcpy(funcstring, s);
8195 funcstring += strlen(s) + 1;
8199 static union node *copynode(union node *);
8201 static struct nodelist *
8202 copynodelist(struct nodelist *lp)
8204 struct nodelist *start;
8205 struct nodelist **lpp;
8210 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8211 (*lpp)->n = copynode(lp->n);
8213 lpp = &(*lpp)->next;
8220 copynode(union node *n)
8227 funcblock = (char *) funcblock + nodesize[n->type];
8231 new->ncmd.redirect = copynode(n->ncmd.redirect);
8232 new->ncmd.args = copynode(n->ncmd.args);
8233 new->ncmd.assign = copynode(n->ncmd.assign);
8236 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8237 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8242 new->nredir.redirect = copynode(n->nredir.redirect);
8243 new->nredir.n = copynode(n->nredir.n);
8250 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8251 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8254 new->nif.elsepart = copynode(n->nif.elsepart);
8255 new->nif.ifpart = copynode(n->nif.ifpart);
8256 new->nif.test = copynode(n->nif.test);
8259 new->nfor.var = nodeckstrdup(n->nfor.var);
8260 new->nfor.body = copynode(n->nfor.body);
8261 new->nfor.args = copynode(n->nfor.args);
8264 new->ncase.cases = copynode(n->ncase.cases);
8265 new->ncase.expr = copynode(n->ncase.expr);
8268 new->nclist.body = copynode(n->nclist.body);
8269 new->nclist.pattern = copynode(n->nclist.pattern);
8270 new->nclist.next = copynode(n->nclist.next);
8274 new->narg.backquote = copynodelist(n->narg.backquote);
8275 new->narg.text = nodeckstrdup(n->narg.text);
8276 new->narg.next = copynode(n->narg.next);
8279 #if ENABLE_ASH_BASH_COMPAT
8286 new->nfile.fname = copynode(n->nfile.fname);
8287 new->nfile.fd = n->nfile.fd;
8288 new->nfile.next = copynode(n->nfile.next);
8292 new->ndup.vname = copynode(n->ndup.vname);
8293 new->ndup.dupfd = n->ndup.dupfd;
8294 new->ndup.fd = n->ndup.fd;
8295 new->ndup.next = copynode(n->ndup.next);
8299 new->nhere.doc = copynode(n->nhere.doc);
8300 new->nhere.fd = n->nhere.fd;
8301 new->nhere.next = copynode(n->nhere.next);
8304 new->nnot.com = copynode(n->nnot.com);
8307 new->type = n->type;
8312 * Make a copy of a parse tree.
8314 static struct funcnode *
8315 copyfunc(union node *n)
8320 funcblocksize = offsetof(struct funcnode, n);
8323 blocksize = funcblocksize;
8324 f = ckmalloc(blocksize + funcstringsize);
8325 funcblock = (char *) f + offsetof(struct funcnode, n);
8326 funcstring = (char *) f + blocksize;
8333 * Define a shell function.
8336 defun(char *name, union node *func)
8338 struct cmdentry entry;
8341 entry.cmdtype = CMDFUNCTION;
8342 entry.u.func = copyfunc(func);
8343 addcmdentry(name, &entry);
8347 /* Reasons for skipping commands (see comment on breakcmd routine) */
8348 #define SKIPBREAK (1 << 0)
8349 #define SKIPCONT (1 << 1)
8350 #define SKIPFUNC (1 << 2)
8351 #define SKIPFILE (1 << 3)
8352 #define SKIPEVAL (1 << 4)
8353 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8354 static int skipcount; /* number of levels to skip */
8355 static int funcnest; /* depth of function calls */
8356 static int loopnest; /* current loop nesting level */
8358 /* Forward decl way out to parsing code - dotrap needs it */
8359 static int evalstring(char *s, int mask);
8361 /* Called to execute a trap.
8362 * Single callsite - at the end of evaltree().
8363 * If we return non-zero, evaltree raises EXEXIT exception.
8365 * Perhaps we should avoid entering new trap handlers
8366 * while we are executing a trap handler. [is it a TODO?]
8375 savestatus = exitstatus;
8379 TRACE(("dotrap entered\n"));
8380 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8386 /* non-trapped SIGINT is handled separately by raise_interrupt,
8387 * don't upset it by resetting gotsig[SIGINT-1] */
8388 if (sig == SIGINT && !t)
8391 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8395 evalstring(t, SKIPEVAL);
8396 exitstatus = savestatus;
8398 TRACE(("dotrap returns %d\n", evalskip));
8403 TRACE(("dotrap returns 0\n"));
8407 /* forward declarations - evaluation is fairly recursive business... */
8408 static int evalloop(union node *, int);
8409 static int evalfor(union node *, int);
8410 static int evalcase(union node *, int);
8411 static int evalsubshell(union node *, int);
8412 static void expredir(union node *);
8413 static int evalpipe(union node *, int);
8414 static int evalcommand(union node *, int);
8415 static int evalbltin(const struct builtincmd *, int, char **);
8416 static void prehash(union node *);
8419 * Evaluate a parse tree. The value is left in the global variable
8423 evaltree(union node *n, int flags)
8425 struct jmploc *volatile savehandler = exception_handler;
8426 struct jmploc jmploc;
8428 int (*evalfn)(union node *, int);
8432 SAVE_INT(int_level);
8435 TRACE(("evaltree(NULL) called\n"));
8438 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8440 exception_handler = &jmploc;
8442 int err = setjmp(jmploc.loc);
8444 /* if it was a signal, check for trap handlers */
8445 if (exception_type == EXSIG) {
8446 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8447 exception_type, err));
8450 /* continue on the way out */
8451 TRACE(("exception %d in evaltree, propagating err=%d\n",
8452 exception_type, err));
8453 exception_handler = savehandler;
8454 longjmp(exception_handler->loc, err);
8461 out1fmt("Node type = %d\n", n->type);
8466 status = !evaltree(n->nnot.com, EV_TESTED);
8469 expredir(n->nredir.redirect);
8470 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8472 status = evaltree(n->nredir.n, flags & EV_TESTED);
8474 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8477 evalfn = evalcommand;
8479 if (eflag && !(flags & EV_TESTED))
8490 evalfn = evalsubshell;
8493 evalfn = evalsubshell;
8506 #error NAND + 1 != NOR
8508 #if NOR + 1 != NSEMI
8509 #error NOR + 1 != NSEMI
8511 unsigned is_or = n->type - NAND;
8514 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8516 if (!status == is_or || evalskip)
8522 status = evalfn(n, flags);
8526 status = evaltree(n->nif.test, EV_TESTED);
8533 if (n->nif.elsepart) {
8534 n = n->nif.elsepart;
8540 defun(n->narg.text, n->narg.next);
8541 /* Not necessary. To test it:
8542 * "false; f() { qwerty; }; echo $?" should print 0.
8546 exitstatus = status;
8551 exception_handler = savehandler;
8554 /* Order of checks below is important:
8555 * signal handlers trigger before exit caused by "set -e".
8557 if (pending_sig && dotrap())
8559 if (checkexit & status)
8560 evalskip |= SKIPEVAL;
8562 if (flags & EV_EXIT) {
8564 raise_exception(EXEXIT);
8567 RESTORE_INT(int_level);
8568 TRACE(("leaving evaltree (no interrupts)\n"));
8573 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8576 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8579 evalloop(union node *n, int flags)
8589 i = evaltree(n->nbinary.ch1, EV_TESTED);
8592 if (evalskip == SKIPCONT && --skipcount <= 0) {
8596 if (evalskip == SKIPBREAK && --skipcount <= 0)
8600 if (n->type != NWHILE)
8604 status = evaltree(n->nbinary.ch2, flags);
8608 exitstatus = status;
8615 evalfor(union node *n, int flags)
8617 struct arglist arglist;
8620 struct stackmark smark;
8623 setstackmark(&smark);
8624 arglist.list = NULL;
8625 arglist.lastp = &arglist.list;
8626 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8627 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8632 *arglist.lastp = NULL;
8636 for (sp = arglist.list; sp; sp = sp->next) {
8637 setvar0(n->nfor.var, sp->text);
8638 status = evaltree(n->nfor.body, flags);
8640 if (evalskip == SKIPCONT && --skipcount <= 0) {
8644 if (evalskip == SKIPBREAK && --skipcount <= 0)
8651 popstackmark(&smark);
8657 evalcase(union node *n, int flags)
8661 struct arglist arglist;
8662 struct stackmark smark;
8665 setstackmark(&smark);
8666 arglist.list = NULL;
8667 arglist.lastp = &arglist.list;
8668 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8669 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8670 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8671 if (casematch(patp, arglist.list->text)) {
8672 /* Ensure body is non-empty as otherwise
8673 * EV_EXIT may prevent us from setting the
8676 if (evalskip == 0 && cp->nclist.body) {
8677 status = evaltree(cp->nclist.body, flags);
8684 popstackmark(&smark);
8690 * Kick off a subshell to evaluate a tree.
8693 evalsubshell(union node *n, int flags)
8696 int backgnd = (n->type == NBACKGND);
8699 expredir(n->nredir.redirect);
8700 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8703 jp = makejob(/*n,*/ 1);
8704 if (forkshell(jp, n, backgnd) == 0) {
8709 flags &= ~EV_TESTED;
8711 redirect(n->nredir.redirect, 0);
8712 evaltreenr(n->nredir.n, flags);
8717 status = waitforjob(jp);
8723 * Compute the names of the files in a redirection list.
8725 static void fixredir(union node *, const char *, int);
8727 expredir(union node *n)
8731 for (redir = n; redir; redir = redir->nfile.next) {
8735 fn.lastp = &fn.list;
8736 switch (redir->type) {
8740 #if ENABLE_ASH_BASH_COMPAT
8745 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8746 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8747 #if ENABLE_ASH_BASH_COMPAT
8751 // By the design of stack allocator, the loop of this kind:
8752 // while true; do while true; do break; done </dev/null; done
8753 // will look like a memory leak: ash plans to free expfname's
8754 // of "/dev/null" as soon as it finishes running the loop
8755 // (in this case, never).
8756 // This "fix" is wrong:
8757 if (redir->nfile.expfname)
8758 stunalloc(redir->nfile.expfname);
8759 // It results in corrupted state of stacked allocations.
8761 redir->nfile.expfname = fn.list->text;
8764 case NTOFD: /* >& */
8765 if (redir->ndup.vname) {
8766 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8767 if (fn.list == NULL)
8768 ash_msg_and_raise_error("redir error");
8769 #if ENABLE_ASH_BASH_COMPAT
8770 //FIXME: we used expandarg with different args!
8771 if (!isdigit_str9(fn.list->text)) {
8772 /* >&file, not >&fd */
8773 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8774 ash_msg_and_raise_error("redir error");
8776 goto store_expfname;
8779 fixredir(redir, fn.list->text, 1);
8787 * Evaluate a pipeline. All the processes in the pipeline are children
8788 * of the process creating the pipeline. (This differs from some versions
8789 * of the shell, which make the last process in a pipeline the parent
8793 evalpipe(union node *n, int flags)
8796 struct nodelist *lp;
8802 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8804 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8808 jp = makejob(/*n,*/ pipelen);
8810 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8814 if (pipe(pip) < 0) {
8816 ash_msg_and_raise_error("pipe call failed");
8819 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8832 evaltreenr(lp->n, flags);
8838 /* Don't want to trigger debugging */
8842 if (n->npipe.pipe_backgnd == 0) {
8843 status = waitforjob(jp);
8844 TRACE(("evalpipe: job done exit status %d\n", status));
8852 * Controls whether the shell is interactive or not.
8855 setinteractive(int on)
8857 static smallint is_interactive;
8859 if (++on == is_interactive)
8861 is_interactive = on;
8865 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8866 if (is_interactive > 1) {
8867 /* Looks like they want an interactive shell */
8868 static smallint did_banner;
8871 /* note: ash and hush share this string */
8872 out1fmt("\n\n%s %s\n"
8873 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
8876 "built-in shell (ash)"
8890 setinteractive(iflag);
8892 #if ENABLE_FEATURE_EDITING_VI
8894 line_input_state->flags |= VI_MODE;
8896 line_input_state->flags &= ~VI_MODE;
8898 viflag = 0; /* forcibly keep the option off */
8902 static struct localvar *localvars;
8905 * Called after a function returns.
8906 * Interrupts must be off.
8911 struct localvar *lvp;
8914 while ((lvp = localvars) != NULL) {
8915 localvars = lvp->next;
8917 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
8918 if (vp == NULL) { /* $- saved */
8919 memcpy(optlist, lvp->text, sizeof(optlist));
8920 free((char*)lvp->text);
8922 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8923 unsetvar(vp->var_text);
8926 vp->var_func(var_end(lvp->text));
8927 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8928 free((char*)vp->var_text);
8929 vp->flags = lvp->flags;
8930 vp->var_text = lvp->text;
8937 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8939 volatile struct shparam saveparam;
8940 struct localvar *volatile savelocalvars;
8941 struct jmploc *volatile savehandler;
8942 struct jmploc jmploc;
8945 saveparam = shellparam;
8946 savelocalvars = localvars;
8947 e = setjmp(jmploc.loc);
8952 savehandler = exception_handler;
8953 exception_handler = &jmploc;
8955 shellparam.malloced = 0;
8959 shellparam.nparam = argc - 1;
8960 shellparam.p = argv + 1;
8961 #if ENABLE_ASH_GETOPTS
8962 shellparam.optind = 1;
8963 shellparam.optoff = -1;
8965 evaltree(&func->n, flags & EV_TESTED);
8971 localvars = savelocalvars;
8972 freeparam(&shellparam);
8973 shellparam = saveparam;
8974 exception_handler = savehandler;
8976 evalskip &= ~SKIPFUNC;
8980 #if ENABLE_ASH_CMDCMD
8982 parse_command_args(char **argv, const char **path)
8995 if (c == '-' && !*cp) {
9003 *path = bb_default_path;
9006 /* run 'typecmd' for other options */
9017 * Make a variable a local variable. When a variable is made local, it's
9018 * value and flags are saved in a localvar structure. The saved values
9019 * will be restored when the shell function returns. We handle the name
9020 * "-" as a special case: it makes changes to "set +-options" local
9021 * (options will be restored on return from the function).
9026 struct localvar *lvp;
9029 char *eq = strchr(name, '=');
9032 /* Cater for duplicate "local". Examples:
9033 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9034 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9038 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9042 * it's a duplicate "local VAR" declaration, do nothing
9049 lvp = ckzalloc(sizeof(*lvp));
9050 if (LONE_DASH(name)) {
9052 p = ckmalloc(sizeof(optlist));
9053 lvp->text = memcpy(p, optlist, sizeof(optlist));
9056 vpp = hashvar(name);
9057 vp = *findvar(vpp, name);
9059 /* variable did not exist yet */
9061 setvareq(name, VSTRFIXED);
9063 setvar(name, NULL, VSTRFIXED);
9064 vp = *vpp; /* the new variable */
9065 lvp->flags = VUNSET;
9067 lvp->text = vp->var_text;
9068 lvp->flags = vp->flags;
9069 /* make sure neither "struct var" nor string gets freed
9070 * during (un)setting:
9072 vp->flags |= VSTRFIXED|VTEXTFIXED;
9076 /* "local VAR" unsets VAR: */
9077 setvar0(name, NULL);
9081 lvp->next = localvars;
9087 * The "local" command.
9089 static int FAST_FUNC
9090 localcmd(int argc UNUSED_PARAM, char **argv)
9095 ash_msg_and_raise_error("not in a function");
9098 while ((name = *argv++) != NULL) {
9104 static int FAST_FUNC
9105 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9110 static int FAST_FUNC
9111 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9116 static int FAST_FUNC
9117 execcmd(int argc UNUSED_PARAM, char **argv)
9120 iflag = 0; /* exit on error */
9123 /* We should set up signals for "exec CMD"
9124 * the same way as for "CMD" without "exec".
9125 * But optschanged->setinteractive->setsignal
9126 * still thought we are a root shell. Therefore, for example,
9127 * SIGQUIT is still set to IGN. Fix it:
9131 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9132 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9133 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9135 shellexec(argv + 1, pathval(), 0);
9142 * The return command.
9144 static int FAST_FUNC
9145 returncmd(int argc UNUSED_PARAM, char **argv)
9148 * If called outside a function, do what ksh does;
9149 * skip the rest of the file.
9151 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
9152 return argv[1] ? number(argv[1]) : exitstatus;
9155 /* Forward declarations for builtintab[] */
9156 static int breakcmd(int, char **) FAST_FUNC;
9157 static int dotcmd(int, char **) FAST_FUNC;
9158 static int evalcmd(int, char **) FAST_FUNC;
9159 static int exitcmd(int, char **) FAST_FUNC;
9160 static int exportcmd(int, char **) FAST_FUNC;
9161 #if ENABLE_ASH_GETOPTS
9162 static int getoptscmd(int, char **) FAST_FUNC;
9165 static int helpcmd(int, char **) FAST_FUNC;
9168 static int historycmd(int, char **) FAST_FUNC;
9170 #if ENABLE_SH_MATH_SUPPORT
9171 static int letcmd(int, char **) FAST_FUNC;
9173 static int readcmd(int, char **) FAST_FUNC;
9174 static int setcmd(int, char **) FAST_FUNC;
9175 static int shiftcmd(int, char **) FAST_FUNC;
9176 static int timescmd(int, char **) FAST_FUNC;
9177 static int trapcmd(int, char **) FAST_FUNC;
9178 static int umaskcmd(int, char **) FAST_FUNC;
9179 static int unsetcmd(int, char **) FAST_FUNC;
9180 static int ulimitcmd(int, char **) FAST_FUNC;
9182 #define BUILTIN_NOSPEC "0"
9183 #define BUILTIN_SPECIAL "1"
9184 #define BUILTIN_REGULAR "2"
9185 #define BUILTIN_SPEC_REG "3"
9186 #define BUILTIN_ASSIGN "4"
9187 #define BUILTIN_SPEC_ASSG "5"
9188 #define BUILTIN_REG_ASSG "6"
9189 #define BUILTIN_SPEC_REG_ASSG "7"
9191 /* Stubs for calling non-FAST_FUNC's */
9192 #if ENABLE_ASH_BUILTIN_ECHO
9193 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9195 #if ENABLE_ASH_BUILTIN_PRINTF
9196 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9198 #if ENABLE_ASH_BUILTIN_TEST
9199 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9202 /* Keep these in proper order since it is searched via bsearch() */
9203 static const struct builtincmd builtintab[] = {
9204 { BUILTIN_SPEC_REG "." , dotcmd },
9205 { BUILTIN_SPEC_REG ":" , truecmd },
9206 #if ENABLE_ASH_BUILTIN_TEST
9207 { BUILTIN_REGULAR "[" , testcmd },
9208 #if ENABLE_ASH_BASH_COMPAT
9209 { BUILTIN_REGULAR "[[" , testcmd },
9212 #if ENABLE_ASH_ALIAS
9213 { BUILTIN_REG_ASSG "alias" , aliascmd },
9216 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9218 { BUILTIN_SPEC_REG "break" , breakcmd },
9219 { BUILTIN_REGULAR "cd" , cdcmd },
9220 { BUILTIN_NOSPEC "chdir" , cdcmd },
9221 #if ENABLE_ASH_CMDCMD
9222 { BUILTIN_REGULAR "command" , commandcmd },
9224 { BUILTIN_SPEC_REG "continue", breakcmd },
9225 #if ENABLE_ASH_BUILTIN_ECHO
9226 { BUILTIN_REGULAR "echo" , echocmd },
9228 { BUILTIN_SPEC_REG "eval" , evalcmd },
9229 { BUILTIN_SPEC_REG "exec" , execcmd },
9230 { BUILTIN_SPEC_REG "exit" , exitcmd },
9231 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9232 { BUILTIN_REGULAR "false" , falsecmd },
9234 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9236 #if ENABLE_ASH_GETOPTS
9237 { BUILTIN_REGULAR "getopts" , getoptscmd },
9239 { BUILTIN_NOSPEC "hash" , hashcmd },
9241 { BUILTIN_NOSPEC "help" , helpcmd },
9244 { BUILTIN_NOSPEC "history" , historycmd },
9247 { BUILTIN_REGULAR "jobs" , jobscmd },
9248 { BUILTIN_REGULAR "kill" , killcmd },
9250 #if ENABLE_SH_MATH_SUPPORT
9251 { BUILTIN_NOSPEC "let" , letcmd },
9253 { BUILTIN_ASSIGN "local" , localcmd },
9254 #if ENABLE_ASH_BUILTIN_PRINTF
9255 { BUILTIN_REGULAR "printf" , printfcmd },
9257 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9258 { BUILTIN_REGULAR "read" , readcmd },
9259 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9260 { BUILTIN_SPEC_REG "return" , returncmd },
9261 { BUILTIN_SPEC_REG "set" , setcmd },
9262 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9263 #if ENABLE_ASH_BASH_COMPAT
9264 { BUILTIN_SPEC_REG "source" , dotcmd },
9266 #if ENABLE_ASH_BUILTIN_TEST
9267 { BUILTIN_REGULAR "test" , testcmd },
9269 { BUILTIN_SPEC_REG "times" , timescmd },
9270 { BUILTIN_SPEC_REG "trap" , trapcmd },
9271 { BUILTIN_REGULAR "true" , truecmd },
9272 { BUILTIN_NOSPEC "type" , typecmd },
9273 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9274 { BUILTIN_REGULAR "umask" , umaskcmd },
9275 #if ENABLE_ASH_ALIAS
9276 { BUILTIN_REGULAR "unalias" , unaliascmd },
9278 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9279 { BUILTIN_REGULAR "wait" , waitcmd },
9282 /* Should match the above table! */
9283 #define COMMANDCMD (builtintab + \
9285 /* [ */ 1 * ENABLE_ASH_BUILTIN_TEST + \
9286 /* [[ */ 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9287 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9288 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9289 /* break cd cddir */ 3)
9290 #define EVALCMD (COMMANDCMD + \
9291 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9292 /* continue */ 1 + \
9293 /* echo */ 1 * ENABLE_ASH_BUILTIN_ECHO + \
9295 #define EXECCMD (EVALCMD + \
9299 * Search the table of builtin commands.
9301 static struct builtincmd *
9302 find_builtin(const char *name)
9304 struct builtincmd *bp;
9307 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9314 * Execute a simple command.
9317 isassignment(const char *p)
9319 const char *q = endofname(p);
9324 static int FAST_FUNC
9325 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9327 /* Preserve exitstatus of a previous possible redirection
9328 * as POSIX mandates */
9329 return back_exitstatus;
9332 evalcommand(union node *cmd, int flags)
9334 static const struct builtincmd null_bltin = {
9335 "\0\0", bltincmd /* why three NULs? */
9337 struct stackmark smark;
9339 struct arglist arglist;
9340 struct arglist varlist;
9343 const struct strlist *sp;
9344 struct cmdentry cmdentry;
9351 struct builtincmd *bcmd;
9352 smallint cmd_is_exec;
9353 smallint pseudovarflag = 0;
9355 /* First expand the arguments. */
9356 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9357 setstackmark(&smark);
9358 back_exitstatus = 0;
9360 cmdentry.cmdtype = CMDBUILTIN;
9361 cmdentry.u.cmd = &null_bltin;
9362 varlist.lastp = &varlist.list;
9363 *varlist.lastp = NULL;
9364 arglist.lastp = &arglist.list;
9365 *arglist.lastp = NULL;
9368 if (cmd->ncmd.args) {
9369 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9370 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9373 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9374 struct strlist **spp;
9376 spp = arglist.lastp;
9377 if (pseudovarflag && isassignment(argp->narg.text))
9378 expandarg(argp, &arglist, EXP_VARTILDE);
9380 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9382 for (sp = *spp; sp; sp = sp->next)
9386 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9387 for (sp = arglist.list; sp; sp = sp->next) {
9388 TRACE(("evalcommand arg: %s\n", sp->text));
9389 *nargv++ = sp->text;
9394 if (iflag && funcnest == 0 && argc > 0)
9395 lastarg = nargv[-1];
9398 expredir(cmd->ncmd.redirect);
9399 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9401 path = vpath.var_text;
9402 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9403 struct strlist **spp;
9406 spp = varlist.lastp;
9407 expandarg(argp, &varlist, EXP_VARTILDE);
9410 * Modify the command lookup path, if a PATH= assignment
9414 if (varcmp(p, path) == 0)
9418 /* Print the command if xflag is set. */
9421 const char *p = " %s" + 1;
9423 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9425 for (n = 0; n < 2; n++) {
9427 fdprintf(preverrout_fd, p, sp->text);
9433 safe_write(preverrout_fd, "\n", 1);
9439 /* Now locate the command. */
9441 int cmd_flag = DO_ERR;
9442 #if ENABLE_ASH_CMDCMD
9443 const char *oldpath = path + 5;
9447 find_command(argv[0], &cmdentry, cmd_flag, path);
9448 if (cmdentry.cmdtype == CMDUNKNOWN) {
9449 flush_stdout_stderr();
9454 /* implement bltin and command here */
9455 if (cmdentry.cmdtype != CMDBUILTIN)
9458 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9459 if (cmdentry.u.cmd == EXECCMD)
9461 #if ENABLE_ASH_CMDCMD
9462 if (cmdentry.u.cmd == COMMANDCMD) {
9464 nargv = parse_command_args(argv, &path);
9467 argc -= nargv - argv;
9469 cmd_flag |= DO_NOFUNC;
9477 /* We have a redirection error. */
9479 raise_exception(EXERROR);
9481 exitstatus = status;
9485 /* Execute the command. */
9486 switch (cmdentry.cmdtype) {
9489 #if ENABLE_FEATURE_SH_NOFORK
9490 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9491 * around run_nofork_applet() call.
9492 * (2) Should this check also be done in forkshell()?
9493 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9495 /* find_command() encodes applet_no as (-2 - applet_no) */
9496 int applet_no = (- cmdentry.u.index - 2);
9497 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9498 listsetvar(varlist.list, VEXPORT|VSTACK);
9499 /* run <applet>_main() */
9500 exitstatus = run_nofork_applet(applet_no, argv);
9504 /* Can we avoid forking off? For example, very last command
9505 * in a script or a subshell does not need forking,
9506 * we can just exec it.
9508 if (!(flags & EV_EXIT) || may_have_traps) {
9509 /* No, forking off a child is necessary */
9511 jp = makejob(/*cmd,*/ 1);
9512 if (forkshell(jp, cmd, FORK_FG) != 0) {
9514 status = waitforjob(jp);
9516 TRACE(("forked child exited with %d\n", status));
9521 /* fall through to exec'ing external program */
9523 listsetvar(varlist.list, VEXPORT|VSTACK);
9524 shellexec(argv, path, cmdentry.u.index);
9528 cmdenviron = varlist.list;
9530 struct strlist *list = cmdenviron;
9532 if (spclbltin > 0 || argc == 0) {
9534 if (cmd_is_exec && argc > 1)
9537 listsetvar(list, i);
9539 /* Tight loop with builtins only:
9540 * "while kill -0 $child; do true; done"
9541 * will never exit even if $child died, unless we do this
9542 * to reap the zombie and make kill detect that it's gone: */
9543 dowait(DOWAIT_NONBLOCK, NULL);
9545 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9547 int i = exception_type;
9548 if (i == EXEXIT || i == EXEXEC)
9552 exit_status = 128 + SIGINT;
9554 exit_status = 128 + pending_sig;
9555 exitstatus = exit_status;
9556 if (i == EXINT || spclbltin > 0) {
9558 longjmp(exception_handler->loc, 1);
9565 listsetvar(varlist.list, 0);
9566 /* See above for the rationale */
9567 dowait(DOWAIT_NONBLOCK, NULL);
9568 if (evalfun(cmdentry.u.func, argc, argv, flags))
9571 status = exitstatus;
9576 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9578 /* dsl: I think this is intended to be used to support
9579 * '_' in 'vi' command mode during line editing...
9580 * However I implemented that within libedit itself.
9582 setvar0("_", lastarg);
9584 popstackmark(&smark);
9590 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9592 char *volatile savecmdname;
9593 struct jmploc *volatile savehandler;
9594 struct jmploc jmploc;
9597 savecmdname = commandname;
9598 i = setjmp(jmploc.loc);
9601 savehandler = exception_handler;
9602 exception_handler = &jmploc;
9603 commandname = argv[0];
9605 optptr = NULL; /* initialize nextopt */
9606 exitstatus = (*cmd->builtin)(argc, argv);
9607 flush_stdout_stderr();
9609 exitstatus |= ferror(stdout);
9611 commandname = savecmdname;
9612 exception_handler = savehandler;
9618 goodname(const char *p)
9620 return endofname(p)[0] == '\0';
9625 * Search for a command. This is called before we fork so that the
9626 * location of the command will be available in the parent as well as
9627 * the child. The check for "goodname" is an overly conservative
9628 * check that the name will not be subject to expansion.
9631 prehash(union node *n)
9633 struct cmdentry entry;
9635 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9636 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9640 /* ============ Builtin commands
9642 * Builtin commands whose functions are closely tied to evaluation
9643 * are implemented here.
9647 * Handle break and continue commands. Break, continue, and return are
9648 * all handled by setting the evalskip flag. The evaluation routines
9649 * above all check this flag, and if it is set they start skipping
9650 * commands rather than executing them. The variable skipcount is
9651 * the number of loops to break/continue, or the number of function
9652 * levels to return. (The latter is always 1.) It should probably
9653 * be an error to break out of more loops than exist, but it isn't
9654 * in the standard shell so we don't make it one here.
9656 static int FAST_FUNC
9657 breakcmd(int argc UNUSED_PARAM, char **argv)
9659 int n = argv[1] ? number(argv[1]) : 1;
9662 ash_msg_and_raise_error(msg_illnum, argv[1]);
9666 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9673 /* ============ input.c
9675 * This implements the input routines used by the parser.
9679 INPUT_PUSH_FILE = 1,
9680 INPUT_NOFILE_OK = 2,
9683 static smallint checkkwd;
9684 /* values of checkkwd variable */
9685 #define CHKALIAS 0x1
9690 * Push a string back onto the input at this current parsefile level.
9691 * We handle aliases this way.
9693 #if !ENABLE_ASH_ALIAS
9694 #define pushstring(s, ap) pushstring(s)
9697 pushstring(char *s, struct alias *ap)
9704 if (g_parsefile->strpush) {
9705 sp = ckzalloc(sizeof(*sp));
9706 sp->prev = g_parsefile->strpush;
9708 sp = &(g_parsefile->basestrpush);
9710 g_parsefile->strpush = sp;
9711 sp->prev_string = g_parsefile->next_to_pgetc;
9712 sp->prev_left_in_line = g_parsefile->left_in_line;
9713 sp->unget = g_parsefile->unget;
9714 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9715 #if ENABLE_ASH_ALIAS
9718 ap->flag |= ALIASINUSE;
9722 g_parsefile->next_to_pgetc = s;
9723 g_parsefile->left_in_line = len;
9724 g_parsefile->unget = 0;
9731 struct strpush *sp = g_parsefile->strpush;
9734 #if ENABLE_ASH_ALIAS
9736 if (g_parsefile->next_to_pgetc[-1] == ' '
9737 || g_parsefile->next_to_pgetc[-1] == '\t'
9739 checkkwd |= CHKALIAS;
9741 if (sp->string != sp->ap->val) {
9744 sp->ap->flag &= ~ALIASINUSE;
9745 if (sp->ap->flag & ALIASDEAD) {
9746 unalias(sp->ap->name);
9750 g_parsefile->next_to_pgetc = sp->prev_string;
9751 g_parsefile->left_in_line = sp->prev_left_in_line;
9752 g_parsefile->unget = sp->unget;
9753 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
9754 g_parsefile->strpush = sp->prev;
9755 if (sp != &(g_parsefile->basestrpush))
9764 char *buf = g_parsefile->buf;
9766 g_parsefile->next_to_pgetc = buf;
9767 #if ENABLE_FEATURE_EDITING
9769 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9770 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9773 # if ENABLE_ASH_IDLE_TIMEOUT
9775 const char *tmout_var = lookupvar("TMOUT");
9777 timeout = atoi(tmout_var) * 1000;
9783 # if ENABLE_FEATURE_TAB_COMPLETION
9784 line_input_state->path_lookup = pathval();
9786 reinit_unicode_for_ash();
9787 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9789 /* Ctrl+C pressed */
9800 /* Ctrl+D pressed */
9803 # if ENABLE_ASH_IDLE_TIMEOUT
9804 else if (errno == EAGAIN && timeout > 0) {
9805 puts("\007timed out waiting for input: auto-logout");
9812 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9815 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9817 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9818 int flags = fcntl(0, F_GETFL);
9819 if (flags >= 0 && (flags & O_NONBLOCK)) {
9820 flags &= ~O_NONBLOCK;
9821 if (fcntl(0, F_SETFL, flags) >= 0) {
9822 out2str("sh: turning off NDELAY mode\n");
9833 * Refill the input buffer and return the next input character:
9835 * 1) If a string was pushed back on the input, pop it;
9836 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9837 * or we are reading from a string so we can't refill the buffer,
9839 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9840 * 4) Process input up to the next newline, deleting nul characters.
9842 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9843 #define pgetc_debug(...) ((void)0)
9844 static int pgetc(void);
9851 if (g_parsefile->strpush) {
9852 #if ENABLE_ASH_ALIAS
9853 if (g_parsefile->left_in_line == -1
9854 && g_parsefile->strpush->ap
9855 && g_parsefile->next_to_pgetc[-1] != ' '
9856 && g_parsefile->next_to_pgetc[-1] != '\t'
9858 pgetc_debug("preadbuffer PEOA");
9865 /* on both branches above g_parsefile->left_in_line < 0.
9866 * "pgetc" needs refilling.
9869 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9870 * pungetc() may increment it a few times.
9871 * Assuming it won't increment it to less than -90.
9873 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9874 pgetc_debug("preadbuffer PEOF1");
9875 /* even in failure keep left_in_line and next_to_pgetc
9876 * in lock step, for correct multi-layer pungetc.
9877 * left_in_line was decremented before preadbuffer(),
9878 * must inc next_to_pgetc: */
9879 g_parsefile->next_to_pgetc++;
9883 more = g_parsefile->left_in_buffer;
9885 flush_stdout_stderr();
9889 /* don't try reading again */
9890 g_parsefile->left_in_line = -99;
9891 pgetc_debug("preadbuffer PEOF2");
9892 g_parsefile->next_to_pgetc++;
9897 /* Find out where's the end of line.
9898 * Set g_parsefile->left_in_line
9899 * and g_parsefile->left_in_buffer acordingly.
9900 * NUL chars are deleted.
9902 q = g_parsefile->next_to_pgetc;
9910 memmove(q, q + 1, more);
9914 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9920 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9921 if (g_parsefile->left_in_line < 0)
9926 g_parsefile->left_in_buffer = more;
9931 out2str(g_parsefile->next_to_pgetc);
9935 pgetc_debug("preadbuffer at %d:%p'%s'",
9936 g_parsefile->left_in_line,
9937 g_parsefile->next_to_pgetc,
9938 g_parsefile->next_to_pgetc);
9939 return (unsigned char)*g_parsefile->next_to_pgetc++;
9947 pgetc_debug("pgetc at %d:%p'%s'",
9948 g_parsefile->left_in_line,
9949 g_parsefile->next_to_pgetc,
9950 g_parsefile->next_to_pgetc);
9951 if (g_parsefile->unget)
9952 return g_parsefile->lastc[--g_parsefile->unget];
9954 if (--g_parsefile->left_in_line >= 0)
9955 c = (signed char)*g_parsefile->next_to_pgetc++;
9959 g_parsefile->lastc[1] = g_parsefile->lastc[0];
9960 g_parsefile->lastc[0] = c;
9965 #if ENABLE_ASH_ALIAS
9967 pgetc_without_PEOA(void)
9971 pgetc_debug("pgetc at %d:%p'%s'",
9972 g_parsefile->left_in_line,
9973 g_parsefile->next_to_pgetc,
9974 g_parsefile->next_to_pgetc);
9976 } while (c == PEOA);
9980 # define pgetc_without_PEOA() pgetc()
9984 * Read a line from the script.
9987 pfgets(char *line, int len)
9993 while (--nleft > 0) {
9994 c = pgetc_without_PEOA();
10009 * Undo a call to pgetc. Only two characters may be pushed back.
10010 * PEOF may be pushed back.
10015 g_parsefile->unget++;
10018 /* This one eats backslash+newline */
10024 while ((c = pgetc()) == '\\') {
10025 if (pgetc() != '\n') {
10030 g_parsefile->linno++;
10031 setprompt_if(doprompt, 2);
10038 * To handle the "." command, a stack of input files is used. Pushfile
10039 * adds a new entry to the stack and popfile restores the previous level.
10044 struct parsefile *pf;
10046 pf = ckzalloc(sizeof(*pf));
10047 pf->prev = g_parsefile;
10049 /*pf->strpush = NULL; - ckzalloc did it */
10050 /*pf->basestrpush.prev = NULL;*/
10058 struct parsefile *pf = g_parsefile;
10061 if (pf->pf_fd >= 0)
10064 while (pf->strpush)
10066 g_parsefile = pf->prev;
10072 * Return to top level.
10077 while (g_parsefile != &basepf)
10082 * Close the file(s) that the shell is reading commands from. Called
10083 * after a fork is done.
10089 if (g_parsefile->pf_fd > 0) {
10090 close(g_parsefile->pf_fd);
10091 g_parsefile->pf_fd = 0;
10096 * Like setinputfile, but takes an open file descriptor. Call this with
10100 setinputfd(int fd, int push)
10102 close_on_exec_on(fd);
10105 g_parsefile->buf = NULL;
10107 g_parsefile->pf_fd = fd;
10108 if (g_parsefile->buf == NULL)
10109 g_parsefile->buf = ckmalloc(IBUFSIZ);
10110 g_parsefile->left_in_buffer = 0;
10111 g_parsefile->left_in_line = 0;
10112 g_parsefile->linno = 1;
10116 * Set the input to take input from a file. If push is set, push the
10117 * old input onto the stack first.
10120 setinputfile(const char *fname, int flags)
10126 fd = open(fname, O_RDONLY);
10128 if (flags & INPUT_NOFILE_OK)
10130 ash_msg_and_raise_error("can't open '%s'", fname);
10133 fd2 = copyfd(fd, 10);
10136 ash_msg_and_raise_error("out of file descriptors");
10139 setinputfd(fd, flags & INPUT_PUSH_FILE);
10146 * Like setinputfile, but takes input from a string.
10149 setinputstring(char *string)
10153 g_parsefile->next_to_pgetc = string;
10154 g_parsefile->left_in_line = strlen(string);
10155 g_parsefile->buf = NULL;
10156 g_parsefile->linno = 1;
10161 /* ============ mail.c
10163 * Routines to check for mail.
10166 #if ENABLE_ASH_MAIL
10168 /* Hash of mtimes of mailboxes */
10169 static unsigned mailtime_hash;
10170 /* Set if MAIL or MAILPATH is changed. */
10171 static smallint mail_var_path_changed;
10174 * Print appropriate message(s) if mail has arrived.
10175 * If mail_var_path_changed is set,
10176 * then the value of MAIL has mail_var_path_changed,
10177 * so we just update the values.
10186 struct stackmark smark;
10189 setstackmark(&smark);
10190 mpath = mpathset() ? mpathval() : mailval();
10193 p = path_advance(&mpath, nullstr);
10198 for (q = p; *q; q++)
10204 q[-1] = '\0'; /* delete trailing '/' */
10205 if (stat(p, &statb) < 0) {
10208 /* Very simplistic "hash": just a sum of all mtimes */
10209 new_hash += (unsigned)statb.st_mtime;
10211 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10212 if (mailtime_hash != 0)
10213 out2str("you have mail\n");
10214 mailtime_hash = new_hash;
10216 mail_var_path_changed = 0;
10217 popstackmark(&smark);
10220 static void FAST_FUNC
10221 changemail(const char *val UNUSED_PARAM)
10223 mail_var_path_changed = 1;
10226 #endif /* ASH_MAIL */
10229 /* ============ ??? */
10232 * Set the shell parameters.
10235 setparam(char **argv)
10241 for (nparam = 0; argv[nparam]; nparam++)
10243 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10245 *ap++ = ckstrdup(*argv++);
10248 freeparam(&shellparam);
10249 shellparam.malloced = 1;
10250 shellparam.nparam = nparam;
10251 shellparam.p = newparam;
10252 #if ENABLE_ASH_GETOPTS
10253 shellparam.optind = 1;
10254 shellparam.optoff = -1;
10259 * Process shell options. The global variable argptr contains a pointer
10260 * to the argument list; we advance it past the options.
10262 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10263 * For a non-interactive shell, an error condition encountered
10264 * by a special built-in ... shall cause the shell to write a diagnostic message
10265 * to standard error and exit as shown in the following table:
10266 * Error Special Built-In
10268 * Utility syntax error (option or operand error) Shall exit
10270 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10271 * we see that bash does not do that (set "finishes" with error code 1 instead,
10272 * and shell continues), and people rely on this behavior!
10274 * set -o barfoo 2>/dev/null
10277 * Oh well. Let's mimic that.
10280 plus_minus_o(char *name, int val)
10285 for (i = 0; i < NOPTS; i++) {
10286 if (strcmp(name, optnames(i)) == 0) {
10291 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10294 for (i = 0; i < NOPTS; i++) {
10296 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10298 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10304 setoption(int flag, int val)
10308 for (i = 0; i < NOPTS; i++) {
10309 if (optletters(i) == flag) {
10314 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10318 options(int cmdline)
10326 while ((p = *argptr) != NULL) {
10328 if (c != '-' && c != '+')
10331 val = 0; /* val = 0 if c == '+' */
10334 if (p[0] == '\0' || LONE_DASH(p)) {
10336 /* "-" means turn off -x and -v */
10339 /* "--" means reset params */
10340 else if (*argptr == NULL)
10343 break; /* "-" or "--" terminates options */
10346 /* first char was + or - */
10347 while ((c = *p++) != '\0') {
10348 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10349 if (c == 'c' && cmdline) {
10350 minusc = p; /* command is after shell args */
10351 } else if (c == 'o') {
10352 if (plus_minus_o(*argptr, val)) {
10353 /* it already printed err message */
10354 return 1; /* error */
10358 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10360 /* bash does not accept +-login, we also won't */
10361 } else if (cmdline && val && (c == '-')) { /* long options */
10362 if (strcmp(p, "login") == 0)
10374 * The shift builtin command.
10376 static int FAST_FUNC
10377 shiftcmd(int argc UNUSED_PARAM, char **argv)
10384 n = number(argv[1]);
10385 if (n > shellparam.nparam)
10386 n = 0; /* bash compat, was = shellparam.nparam; */
10388 shellparam.nparam -= n;
10389 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10390 if (shellparam.malloced)
10393 ap2 = shellparam.p;
10394 while ((*ap2++ = *ap1++) != NULL)
10396 #if ENABLE_ASH_GETOPTS
10397 shellparam.optind = 1;
10398 shellparam.optoff = -1;
10405 * POSIX requires that 'set' (but not export or readonly) output the
10406 * variables in lexicographic order - by the locale's collating order (sigh).
10407 * Maybe we could keep them in an ordered balanced binary tree
10408 * instead of hashed lists.
10409 * For now just roll 'em through qsort for printing...
10412 showvars(const char *sep_prefix, int on, int off)
10415 char **ep, **epend;
10417 ep = listvars(on, off, &epend);
10418 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10420 sep = *sep_prefix ? " " : sep_prefix;
10422 for (; ep < epend; ep++) {
10426 p = strchrnul(*ep, '=');
10429 q = single_quote(++p);
10430 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10436 * The set command builtin.
10438 static int FAST_FUNC
10439 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10444 return showvars(nullstr, 0, VUNSET);
10447 retval = options(/*cmdline:*/ 0);
10448 if (retval == 0) { /* if no parse error... */
10450 if (*argptr != NULL) {
10458 #if ENABLE_ASH_RANDOM_SUPPORT
10459 static void FAST_FUNC
10460 change_random(const char *value)
10464 if (value == NULL) {
10465 /* "get", generate */
10466 t = next_random(&random_gen);
10467 /* set without recursion */
10468 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10469 vrandom.flags &= ~VNOFUNC;
10472 t = strtoul(value, NULL, 10);
10473 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10478 #if ENABLE_ASH_GETOPTS
10480 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10491 if (*param_optind < 1)
10493 optnext = optfirst + *param_optind - 1;
10495 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10498 p = optnext[-1] + *optoff;
10499 if (p == NULL || *p == '\0') {
10500 /* Current word is done, advance */
10502 if (p == NULL || *p != '-' || *++p == '\0') {
10509 if (LONE_DASH(p)) /* check for "--" */
10514 for (q = optstr; *q != c;) {
10516 if (optstr[0] == ':') {
10518 /*sbuf[1] = '\0'; - already is */
10519 err |= setvarsafe("OPTARG", sbuf, 0);
10521 fprintf(stderr, "Illegal option -%c\n", c);
10522 unsetvar("OPTARG");
10532 if (*p == '\0' && (p = *optnext) == NULL) {
10533 if (optstr[0] == ':') {
10535 /*sbuf[1] = '\0'; - already is */
10536 err |= setvarsafe("OPTARG", sbuf, 0);
10539 fprintf(stderr, "No arg for -%c option\n", c);
10540 unsetvar("OPTARG");
10548 err |= setvarsafe("OPTARG", p, 0);
10551 err |= setvarsafe("OPTARG", nullstr, 0);
10553 *optoff = p ? p - *(optnext - 1) : -1;
10554 *param_optind = optnext - optfirst + 1;
10555 err |= setvarsafe("OPTIND", itoa(*param_optind), VNOFUNC);
10557 /*sbuf[1] = '\0'; - already is */
10558 err |= setvarsafe(optvar, sbuf, 0);
10562 flush_stdout_stderr();
10563 raise_exception(EXERROR);
10569 * The getopts builtin. Shellparam.optnext points to the next argument
10570 * to be processed. Shellparam.optptr points to the next character to
10571 * be processed in the current argument. If shellparam.optnext is NULL,
10572 * then it's the first time getopts has been called.
10574 static int FAST_FUNC
10575 getoptscmd(int argc, char **argv)
10580 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10582 optbase = shellparam.p;
10583 if (shellparam.optind > shellparam.nparam + 1) {
10584 shellparam.optind = 1;
10585 shellparam.optoff = -1;
10588 optbase = &argv[3];
10589 if (shellparam.optind > argc - 2) {
10590 shellparam.optind = 1;
10591 shellparam.optoff = -1;
10595 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10596 &shellparam.optoff);
10598 #endif /* ASH_GETOPTS */
10601 /* ============ Shell parser */
10604 struct heredoc *next; /* next here document in list */
10605 union node *here; /* redirection node */
10606 char *eofmark; /* string indicating end of input */
10607 smallint striptabs; /* if set, strip leading tabs */
10610 static smallint tokpushback; /* last token pushed back */
10611 static smallint quoteflag; /* set if (part of) last token was quoted */
10612 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10613 static struct heredoc *heredoclist; /* list of here documents to read */
10614 static char *wordtext; /* text of last word returned by readtoken */
10615 static struct nodelist *backquotelist;
10616 static union node *redirnode;
10617 static struct heredoc *heredoc;
10619 static const char *
10620 tokname(char *buf, int tok)
10623 return tokname_array[tok] + 1;
10624 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10628 /* raise_error_unexpected_syntax:
10629 * Called when an unexpected token is read during the parse. The argument
10630 * is the token that is expected, or -1 if more than one type of token can
10631 * occur at this point.
10633 static void raise_error_unexpected_syntax(int) NORETURN;
10635 raise_error_unexpected_syntax(int token)
10641 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10643 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10644 raise_error_syntax(msg);
10648 #define EOFMARKLEN 79
10650 /* parsing is heavily cross-recursive, need these forward decls */
10651 static union node *andor(void);
10652 static union node *pipeline(void);
10653 static union node *parse_command(void);
10654 static void parseheredoc(void);
10655 static int peektoken(void);
10656 static int readtoken(void);
10658 static union node *
10661 union node *n1, *n2, *n3;
10666 switch (peektoken()) {
10674 if (!n1 && (nlflag & 1))
10680 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10681 if (nlflag == 2 && tokname_array[peektoken()][0])
10687 if (tok == TBACKGND) {
10688 if (n2->type == NPIPE) {
10689 n2->npipe.pipe_backgnd = 1;
10691 if (n2->type != NREDIR) {
10692 n3 = stzalloc(sizeof(struct nredir));
10694 /*n3->nredir.redirect = NULL; - stzalloc did it */
10697 n2->type = NBACKGND;
10703 n3 = stzalloc(sizeof(struct nbinary));
10705 n3->nbinary.ch1 = n1;
10706 n3->nbinary.ch2 = n2;
10719 raise_error_unexpected_syntax(-1);
10726 static union node *
10729 union node *n1, *n2, *n3;
10737 } else if (t == TOR) {
10743 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10745 n3 = stzalloc(sizeof(struct nbinary));
10747 n3->nbinary.ch1 = n1;
10748 n3->nbinary.ch2 = n2;
10753 static union node *
10756 union node *n1, *n2, *pipenode;
10757 struct nodelist *lp, *prev;
10761 TRACE(("pipeline: entered\n"));
10762 if (readtoken() == TNOT) {
10764 checkkwd = CHKKWD | CHKALIAS;
10767 n1 = parse_command();
10768 if (readtoken() == TPIPE) {
10769 pipenode = stzalloc(sizeof(struct npipe));
10770 pipenode->type = NPIPE;
10771 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10772 lp = stzalloc(sizeof(struct nodelist));
10773 pipenode->npipe.cmdlist = lp;
10777 lp = stzalloc(sizeof(struct nodelist));
10778 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10779 lp->n = parse_command();
10781 } while (readtoken() == TPIPE);
10787 n2 = stzalloc(sizeof(struct nnot));
10795 static union node *
10800 n = stzalloc(sizeof(struct narg));
10802 /*n->narg.next = NULL; - stzalloc did it */
10803 n->narg.text = wordtext;
10804 n->narg.backquote = backquotelist;
10809 fixredir(union node *n, const char *text, int err)
10813 TRACE(("Fix redir %s %d\n", text, err));
10815 n->ndup.vname = NULL;
10817 fd = bb_strtou(text, NULL, 10);
10818 if (!errno && fd >= 0)
10819 n->ndup.dupfd = fd;
10820 else if (LONE_DASH(text))
10821 n->ndup.dupfd = -1;
10824 raise_error_syntax("bad fd number");
10825 n->ndup.vname = makename();
10830 * Returns true if the text contains nothing to expand (no dollar signs
10834 noexpand(const char *text)
10838 while ((c = *text++) != '\0') {
10839 if (c == CTLQUOTEMARK)
10843 else if (SIT(c, BASESYNTAX) == CCTL)
10852 union node *n = redirnode;
10854 if (readtoken() != TWORD)
10855 raise_error_unexpected_syntax(-1);
10856 if (n->type == NHERE) {
10857 struct heredoc *here = heredoc;
10861 if (quoteflag == 0)
10863 TRACE(("Here document %d\n", n->type));
10864 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10865 raise_error_syntax("illegal eof marker for << redirection");
10866 rmescapes(wordtext, 0);
10867 here->eofmark = wordtext;
10869 if (heredoclist == NULL)
10870 heredoclist = here;
10872 for (p = heredoclist; p->next; p = p->next)
10876 } else if (n->type == NTOFD || n->type == NFROMFD) {
10877 fixredir(n, wordtext, 0);
10879 n->nfile.fname = makename();
10883 static union node *
10886 union node *args, **app;
10887 union node *n = NULL;
10888 union node *vars, **vpp;
10889 union node **rpp, *redir;
10891 #if ENABLE_ASH_BASH_COMPAT
10892 smallint double_brackets_flag = 0;
10893 smallint function_flag = 0;
10903 savecheckkwd = CHKALIAS;
10906 checkkwd = savecheckkwd;
10909 #if ENABLE_ASH_BASH_COMPAT
10911 if (peektoken() != TWORD)
10912 raise_error_unexpected_syntax(TWORD);
10915 case TAND: /* "&&" */
10916 case TOR: /* "||" */
10917 if (!double_brackets_flag) {
10921 wordtext = (char *) (t == TAND ? "-a" : "-o");
10924 n = stzalloc(sizeof(struct narg));
10926 /*n->narg.next = NULL; - stzalloc did it */
10927 n->narg.text = wordtext;
10928 #if ENABLE_ASH_BASH_COMPAT
10929 if (strcmp("[[", wordtext) == 0)
10930 double_brackets_flag = 1;
10931 else if (strcmp("]]", wordtext) == 0)
10932 double_brackets_flag = 0;
10934 n->narg.backquote = backquotelist;
10935 if (savecheckkwd && isassignment(wordtext)) {
10937 vpp = &n->narg.next;
10940 app = &n->narg.next;
10943 #if ENABLE_ASH_BASH_COMPAT
10944 if (function_flag) {
10945 checkkwd = CHKNL | CHKKWD;
10946 switch (peektoken()) {
10958 if (strcmp("[[", wordtext) == 0)
10962 raise_error_unexpected_syntax(-1);
10968 *rpp = n = redirnode;
10969 rpp = &n->nfile.next;
10970 parsefname(); /* read name of redirection file */
10973 IF_ASH_BASH_COMPAT(do_func:)
10974 if (args && app == &args->narg.next
10977 struct builtincmd *bcmd;
10980 /* We have a function */
10981 if (IF_ASH_BASH_COMPAT(!function_flag &&) readtoken() != TRP)
10982 raise_error_unexpected_syntax(TRP);
10983 name = n->narg.text;
10984 if (!goodname(name)
10985 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10987 raise_error_syntax("bad function name");
10990 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10991 n->narg.next = parse_command();
10994 IF_ASH_BASH_COMPAT(function_flag = 0;)
11005 n = stzalloc(sizeof(struct ncmd));
11007 n->ncmd.args = args;
11008 n->ncmd.assign = vars;
11009 n->ncmd.redirect = redir;
11013 static union node *
11014 parse_command(void)
11016 union node *n1, *n2;
11017 union node *ap, **app;
11018 union node *cp, **cpp;
11019 union node *redir, **rpp;
11026 switch (readtoken()) {
11028 raise_error_unexpected_syntax(-1);
11031 n1 = stzalloc(sizeof(struct nif));
11033 n1->nif.test = list(0);
11034 if (readtoken() != TTHEN)
11035 raise_error_unexpected_syntax(TTHEN);
11036 n1->nif.ifpart = list(0);
11038 while (readtoken() == TELIF) {
11039 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11040 n2 = n2->nif.elsepart;
11042 n2->nif.test = list(0);
11043 if (readtoken() != TTHEN)
11044 raise_error_unexpected_syntax(TTHEN);
11045 n2->nif.ifpart = list(0);
11047 if (lasttoken == TELSE)
11048 n2->nif.elsepart = list(0);
11050 n2->nif.elsepart = NULL;
11058 n1 = stzalloc(sizeof(struct nbinary));
11059 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11060 n1->nbinary.ch1 = list(0);
11063 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
11064 got == TWORD ? wordtext : ""));
11065 raise_error_unexpected_syntax(TDO);
11067 n1->nbinary.ch2 = list(0);
11072 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11073 raise_error_syntax("bad for loop variable");
11074 n1 = stzalloc(sizeof(struct nfor));
11076 n1->nfor.var = wordtext;
11077 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11078 if (readtoken() == TIN) {
11080 while (readtoken() == TWORD) {
11081 n2 = stzalloc(sizeof(struct narg));
11083 /*n2->narg.next = NULL; - stzalloc did it */
11084 n2->narg.text = wordtext;
11085 n2->narg.backquote = backquotelist;
11087 app = &n2->narg.next;
11090 n1->nfor.args = ap;
11091 if (lasttoken != TNL && lasttoken != TSEMI)
11092 raise_error_unexpected_syntax(-1);
11094 n2 = stzalloc(sizeof(struct narg));
11096 /*n2->narg.next = NULL; - stzalloc did it */
11097 n2->narg.text = (char *)dolatstr;
11098 /*n2->narg.backquote = NULL;*/
11099 n1->nfor.args = n2;
11101 * Newline or semicolon here is optional (but note
11102 * that the original Bourne shell only allowed NL).
11104 if (lasttoken != TSEMI)
11107 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11108 if (readtoken() != TDO)
11109 raise_error_unexpected_syntax(TDO);
11110 n1->nfor.body = list(0);
11114 n1 = stzalloc(sizeof(struct ncase));
11116 if (readtoken() != TWORD)
11117 raise_error_unexpected_syntax(TWORD);
11118 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11120 /*n2->narg.next = NULL; - stzalloc did it */
11121 n2->narg.text = wordtext;
11122 n2->narg.backquote = backquotelist;
11123 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11124 if (readtoken() != TIN)
11125 raise_error_unexpected_syntax(TIN);
11126 cpp = &n1->ncase.cases;
11128 checkkwd = CHKNL | CHKKWD;
11130 while (t != TESAC) {
11131 if (lasttoken == TLP)
11133 *cpp = cp = stzalloc(sizeof(struct nclist));
11135 app = &cp->nclist.pattern;
11137 *app = ap = stzalloc(sizeof(struct narg));
11139 /*ap->narg.next = NULL; - stzalloc did it */
11140 ap->narg.text = wordtext;
11141 ap->narg.backquote = backquotelist;
11142 if (readtoken() != TPIPE)
11144 app = &ap->narg.next;
11147 //ap->narg.next = NULL;
11148 if (lasttoken != TRP)
11149 raise_error_unexpected_syntax(TRP);
11150 cp->nclist.body = list(2);
11152 cpp = &cp->nclist.next;
11154 checkkwd = CHKNL | CHKKWD;
11158 raise_error_unexpected_syntax(TENDCASE);
11165 n1 = stzalloc(sizeof(struct nredir));
11166 n1->type = NSUBSHELL;
11167 n1->nredir.n = list(0);
11168 /*n1->nredir.redirect = NULL; - stzalloc did it */
11175 IF_ASH_BASH_COMPAT(case TFUNCTION:)
11179 return simplecmd();
11182 if (readtoken() != t)
11183 raise_error_unexpected_syntax(t);
11186 /* Now check for redirection which may follow command */
11187 checkkwd = CHKKWD | CHKALIAS;
11189 while (readtoken() == TREDIR) {
11190 *rpp = n2 = redirnode;
11191 rpp = &n2->nfile.next;
11197 if (n1->type != NSUBSHELL) {
11198 n2 = stzalloc(sizeof(struct nredir));
11203 n1->nredir.redirect = redir;
11208 #if ENABLE_ASH_BASH_COMPAT
11209 static int decode_dollar_squote(void)
11211 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11217 p = strchr(C_escapes, c);
11222 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11226 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11228 } else if (c == 'x') { /* \xHH */
11232 } while (isxdigit(c) && --cnt);
11234 if (cnt == 3) { /* \x but next char is "bad" */
11238 } else { /* simple seq like \\ or \t */
11243 c = bb_process_escape_sequence((void*)&p);
11244 } else { /* unrecognized "\z": print both chars unless ' or " */
11245 if (c != '\'' && c != '"') {
11247 c |= 0x100; /* "please encode \, then me" */
11255 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11256 * is not NULL, read a here document. In the latter case, eofmark is the
11257 * word which marks the end of the document and striptabs is true if
11258 * leading tabs should be stripped from the document. The argument c
11259 * is the first character of the input token or document.
11261 * Because C does not have internal subroutines, I have simulated them
11262 * using goto's to implement the subroutine linkage. The following macros
11263 * will run code that appears at the end of readtoken1.
11265 #define CHECKEND() {goto checkend; checkend_return:;}
11266 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11267 #define PARSESUB() {goto parsesub; parsesub_return:;}
11268 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11269 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11270 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11272 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11274 /* NB: syntax parameter fits into smallint */
11275 /* c parameter is an unsigned char or PEOF or PEOA */
11278 char line[EOFMARKLEN + 1];
11279 struct nodelist *bqlist;
11283 smallint prevsyntax; /* syntax before arithmetic */
11284 #if ENABLE_ASH_EXPAND_PRMT
11285 smallint pssyntax; /* we are expanding a prompt string */
11287 int varnest; /* levels of variables expansion */
11288 int arinest; /* levels of arithmetic expansion */
11289 int parenlevel; /* levels of parens in arithmetic */
11290 int dqvarnest; /* levels of variables expansion within double quotes */
11292 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11294 startlinno = g_parsefile->linno;
11298 #if ENABLE_ASH_EXPAND_PRMT
11299 pssyntax = (syntax == PSSYNTAX);
11303 dblquote = (syntax == DQSYNTAX);
11309 STARTSTACKSTR(out);
11311 /* For each line, until end of word */
11312 CHECKEND(); /* set c to PEOF if at end of here document */
11313 for (;;) { /* until end of line or end of word */
11314 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11315 switch (SIT(c, syntax)) {
11316 case CNL: /* '\n' */
11317 if (syntax == BASESYNTAX)
11318 goto endword; /* exit outer loop */
11320 g_parsefile->linno++;
11321 setprompt_if(doprompt, 2);
11323 goto loop; /* continue outer loop */
11328 #if ENABLE_ASH_BASH_COMPAT
11329 if (c == '\\' && bash_dollar_squote) {
11330 c = decode_dollar_squote();
11332 /* skip $'\000', $'\x00' (like bash) */
11336 /* Unknown escape. Encode as '\z' */
11337 c = (unsigned char)c;
11338 if (eofmark == NULL || dblquote)
11339 USTPUTC(CTLESC, out);
11340 USTPUTC('\\', out);
11344 if (eofmark == NULL || dblquote)
11345 USTPUTC(CTLESC, out);
11348 case CBACK: /* backslash */
11349 c = pgetc_without_PEOA();
11351 USTPUTC(CTLESC, out);
11352 USTPUTC('\\', out);
11354 } else if (c == '\n') {
11355 setprompt_if(doprompt, 2);
11357 #if ENABLE_ASH_EXPAND_PRMT
11358 if (c == '$' && pssyntax) {
11359 USTPUTC(CTLESC, out);
11360 USTPUTC('\\', out);
11363 /* Backslash is retained if we are in "str" and next char isn't special */
11368 && (c != '"' || eofmark != NULL)
11370 USTPUTC('\\', out);
11372 USTPUTC(CTLESC, out);
11380 if (eofmark == NULL) {
11381 USTPUTC(CTLQUOTEMARK, out);
11389 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11390 if (eofmark != NULL && varnest == 0) {
11393 if (dqvarnest == 0) {
11394 syntax = BASESYNTAX;
11401 case CVAR: /* '$' */
11402 PARSESUB(); /* parse substitution */
11404 case CENDVAR: /* '}' */
11407 if (dqvarnest > 0) {
11414 #if ENABLE_SH_MATH_SUPPORT
11415 case CLP: /* '(' in arithmetic */
11419 case CRP: /* ')' in arithmetic */
11420 if (parenlevel > 0) {
11423 if (pgetc_eatbnl() == ')') {
11425 if (--arinest == 0) {
11426 syntax = prevsyntax;
11430 * unbalanced parens
11431 * (don't 2nd guess - no error)
11439 case CBQUOTE: /* '`' */
11443 goto endword; /* exit outer loop */
11447 if (varnest == 0) {
11448 #if ENABLE_ASH_BASH_COMPAT
11450 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11451 if (pgetc() == '>')
11452 c = 0x100 + '>'; /* flag &> */
11456 goto endword; /* exit outer loop */
11458 IF_ASH_ALIAS(if (c != PEOA))
11465 #if ENABLE_SH_MATH_SUPPORT
11466 if (syntax == ARISYNTAX)
11467 raise_error_syntax("missing '))'");
11469 if (syntax != BASESYNTAX && eofmark == NULL)
11470 raise_error_syntax("unterminated quoted string");
11471 if (varnest != 0) {
11472 startlinno = g_parsefile->linno;
11474 raise_error_syntax("missing '}'");
11476 USTPUTC('\0', out);
11477 len = out - (char *)stackblock();
11478 out = stackblock();
11479 if (eofmark == NULL) {
11480 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11483 if (isdigit_str9(out)) {
11484 PARSEREDIR(); /* passed as params: out, c */
11485 lasttoken = TREDIR;
11488 /* else: non-number X seen, interpret it
11489 * as "NNNX>file" = "NNNX >file" */
11493 quoteflag = quotef;
11494 backquotelist = bqlist;
11495 grabstackblock(len);
11499 /* end of readtoken routine */
11502 * Check to see whether we are at the end of the here document. When this
11503 * is called, c is set to the first character of the next input line. If
11504 * we are at the end of the here document, this routine sets the c to PEOF.
11508 #if ENABLE_ASH_ALIAS
11510 c = pgetc_without_PEOA();
11513 while (c == '\t') {
11514 c = pgetc_without_PEOA();
11517 if (c == *eofmark) {
11518 if (pfgets(line, sizeof(line)) != NULL) {
11522 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11524 if (*p == '\n' && *q == '\0') {
11526 g_parsefile->linno++;
11527 needprompt = doprompt;
11529 pushstring(line, NULL);
11534 goto checkend_return;
11538 * Parse a redirection operator. The variable "out" points to a string
11539 * specifying the fd to be redirected. The variable "c" contains the
11540 * first character of the redirection operator.
11543 /* out is already checked to be a valid number or "" */
11544 int fd = (*out == '\0' ? -1 : atoi(out));
11547 np = stzalloc(sizeof(struct nfile));
11552 np->type = NAPPEND;
11554 np->type = NCLOBBER;
11557 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11563 #if ENABLE_ASH_BASH_COMPAT
11564 else if (c == 0x100 + '>') { /* this flags &> redirection */
11566 pgetc(); /* this is '>', no need to check */
11570 else { /* c == '<' */
11571 /*np->nfile.fd = 0; - stzalloc did it */
11575 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11576 np = stzalloc(sizeof(struct nhere));
11577 /*np->nfile.fd = 0; - stzalloc did it */
11580 heredoc = stzalloc(sizeof(struct heredoc));
11581 heredoc->here = np;
11584 heredoc->striptabs = 1;
11586 /*heredoc->striptabs = 0; - stzalloc did it */
11592 np->type = NFROMFD;
11596 np->type = NFROMTO;
11608 goto parseredir_return;
11612 * Parse a substitution. At this point, we have read the dollar sign
11613 * and nothing else.
11616 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11617 * (assuming ascii char codes, as the original implementation did) */
11618 #define is_special(c) \
11619 (((unsigned)(c) - 33 < 32) \
11620 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11622 unsigned char subtype;
11626 c = pgetc_eatbnl();
11627 if (c > 255 /* PEOA or PEOF */
11628 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11630 #if ENABLE_ASH_BASH_COMPAT
11631 if (syntax != DQSYNTAX && c == '\'')
11632 bash_dollar_squote = 1;
11637 } else if (c == '(') {
11638 /* $(command) or $((arith)) */
11639 if (pgetc_eatbnl() == '(') {
11640 #if ENABLE_SH_MATH_SUPPORT
11643 raise_error_syntax("you disabled math support for $((arith)) syntax");
11650 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11651 USTPUTC(CTLVAR, out);
11652 typeloc = out - (char *)stackblock();
11653 USTPUTC(VSNORMAL, out);
11654 subtype = VSNORMAL;
11656 c = pgetc_eatbnl();
11658 c = pgetc_eatbnl();
11660 c = '#'; /* ${#} - same as $# */
11662 subtype = VSLENGTH; /* ${#VAR} */
11667 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11668 /* $[{[#]]NAME[}] */
11671 c = pgetc_eatbnl();
11672 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11673 } else if (isdigit(c)) {
11674 /* $[{[#]]NUM[}] */
11677 c = pgetc_eatbnl();
11678 } while (isdigit(c));
11679 } else if (is_special(c)) {
11680 /* $[{[#]]<specialchar>[}] */
11682 c = pgetc_eatbnl();
11685 raise_error_syntax("bad substitution");
11687 if (c != '}' && subtype == VSLENGTH) {
11688 /* ${#VAR didn't end with } */
11694 if (subtype == 0) {
11695 static const char types[] ALIGN1 = "}-+?=";
11696 /* ${VAR...} but not $VAR or ${#VAR} */
11697 /* c == first char after VAR */
11700 c = pgetc_eatbnl();
11701 #if ENABLE_ASH_BASH_COMPAT
11702 /* This check is only needed to not misinterpret
11703 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11706 if (!strchr(types, c)) {
11707 subtype = VSSUBSTR;
11709 break; /* "goto do_pungetc" is bigger (!) */
11715 const char *p = strchr(types, c);
11718 subtype = p - types + VSNORMAL;
11724 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11725 c = pgetc_eatbnl();
11731 #if ENABLE_ASH_BASH_COMPAT
11733 /* ${v/[/]pattern/repl} */
11734 //TODO: encode pattern and repl separately.
11735 // Currently ${v/$var_with_slash/repl} is horribly broken
11736 subtype = VSREPLACE;
11737 c = pgetc_eatbnl();
11740 subtype++; /* VSREPLACEALL */
11748 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11749 if (subtype != VSNORMAL) {
11756 goto parsesub_return;
11760 * Called to parse command substitutions. Newstyle is set if the command
11761 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11762 * list of commands (passed by reference), and savelen is the number of
11763 * characters on the top of the stack which must be preserved.
11766 struct nodelist **nlpp;
11770 smallint saveprompt = 0;
11773 savelen = out - (char *)stackblock();
11776 * FIXME: this can allocate very large block on stack and SEGV.
11778 * echo "..<100kbytes>..`true` $(true) `true` ..."
11779 * allocates 100kb for every command subst. With about
11780 * a hundred command substitutions stack overflows.
11781 * With larger prepended string, SEGV happens sooner.
11783 str = alloca(savelen);
11784 memcpy(str, stackblock(), savelen);
11788 /* We must read until the closing backquote, giving special
11789 * treatment to some slashes, and then push the string and
11790 * reread it as input, interpreting it normally.
11796 STARTSTACKSTR(pout);
11800 setprompt_if(needprompt, 2);
11809 g_parsefile->linno++;
11810 setprompt_if(doprompt, 2);
11812 * If eating a newline, avoid putting
11813 * the newline into the new character
11814 * stream (via the STPUTC after the
11819 if (pc != '\\' && pc != '`' && pc != '$'
11820 && (!dblquote || pc != '"')
11822 STPUTC('\\', pout);
11824 if (pc <= 255 /* not PEOA or PEOF */) {
11830 IF_ASH_ALIAS(case PEOA:)
11831 startlinno = g_parsefile->linno;
11832 raise_error_syntax("EOF in backquote substitution");
11835 g_parsefile->linno++;
11836 needprompt = doprompt;
11845 STPUTC('\0', pout);
11846 psavelen = pout - (char *)stackblock();
11847 if (psavelen > 0) {
11848 pstr = grabstackstr(pout);
11849 setinputstring(pstr);
11854 nlpp = &(*nlpp)->next;
11855 *nlpp = stzalloc(sizeof(**nlpp));
11856 /* (*nlpp)->next = NULL; - stzalloc did it */
11859 saveprompt = doprompt;
11866 doprompt = saveprompt;
11867 else if (readtoken() != TRP)
11868 raise_error_unexpected_syntax(TRP);
11873 * Start reading from old file again, ignoring any pushed back
11874 * tokens left from the backquote parsing
11879 while (stackblocksize() <= savelen)
11881 STARTSTACKSTR(out);
11883 memcpy(out, str, savelen);
11884 STADJUST(savelen, out);
11886 USTPUTC(CTLBACKQ, out);
11888 goto parsebackq_oldreturn;
11889 goto parsebackq_newreturn;
11892 #if ENABLE_SH_MATH_SUPPORT
11894 * Parse an arithmetic expansion (indicate start of one and set state)
11897 if (++arinest == 1) {
11898 prevsyntax = syntax;
11899 syntax = ARISYNTAX;
11901 USTPUTC(CTLARI, out);
11902 goto parsearith_return;
11905 } /* end of readtoken */
11908 * Read the next input token.
11909 * If the token is a word, we set backquotelist to the list of cmds in
11910 * backquotes. We set quoteflag to true if any part of the word was
11912 * If the token is TREDIR, then we set redirnode to a structure containing
11914 * In all cases, the variable startlinno is set to the number of the line
11915 * on which the token starts.
11917 * [Change comment: here documents and internal procedures]
11918 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11919 * word parsing code into a separate routine. In this case, readtoken
11920 * doesn't need to have any internal procedures, but parseword does.
11921 * We could also make parseoperator in essence the main routine, and
11922 * have parseword (readtoken1?) handle both words and redirection.]
11924 #define NEW_xxreadtoken
11925 #ifdef NEW_xxreadtoken
11926 /* singles must be first! */
11927 static const char xxreadtoken_chars[7] ALIGN1 = {
11928 '\n', '(', ')', /* singles */
11929 '&', '|', ';', /* doubles */
11933 #define xxreadtoken_singles 3
11934 #define xxreadtoken_doubles 3
11936 static const char xxreadtoken_tokens[] ALIGN1 = {
11937 TNL, TLP, TRP, /* only single occurrence allowed */
11938 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11939 TEOF, /* corresponds to trailing nul */
11940 TAND, TOR, TENDCASE /* if double occurrence */
11952 setprompt_if(needprompt, 2);
11953 startlinno = g_parsefile->linno;
11954 for (;;) { /* until token or start of word found */
11956 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11960 while ((c = pgetc()) != '\n' && c != PEOF)
11963 } else if (c == '\\') {
11964 if (pgetc() != '\n') {
11966 break; /* return readtoken1(...) */
11968 startlinno = ++g_parsefile->linno;
11969 setprompt_if(doprompt, 2);
11973 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11976 g_parsefile->linno++;
11977 needprompt = doprompt;
11980 p = strchr(xxreadtoken_chars, c);
11982 break; /* return readtoken1(...) */
11984 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11986 if (cc == c) { /* double occurrence? */
11987 p += xxreadtoken_doubles + 1;
11990 #if ENABLE_ASH_BASH_COMPAT
11991 if (c == '&' && cc == '>') /* &> */
11992 break; /* return readtoken1(...) */
11997 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12002 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12004 #else /* old xxreadtoken */
12005 #define RETURN(token) return lasttoken = token
12015 setprompt_if(needprompt, 2);
12016 startlinno = g_parsefile->linno;
12017 for (;;) { /* until token or start of word found */
12020 case ' ': case '\t':
12021 IF_ASH_ALIAS(case PEOA:)
12024 while ((c = pgetc()) != '\n' && c != PEOF)
12029 if (pgetc() == '\n') {
12030 startlinno = ++g_parsefile->linno;
12031 setprompt_if(doprompt, 2);
12037 g_parsefile->linno++;
12038 needprompt = doprompt;
12043 if (pgetc() == '&')
12048 if (pgetc() == '|')
12053 if (pgetc() == ';')
12066 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12069 #endif /* old xxreadtoken */
12075 int kwd = checkkwd;
12077 smallint alreadyseen = tokpushback;
12080 #if ENABLE_ASH_ALIAS
12096 if (t != TWORD || quoteflag) {
12101 * check for keywords
12103 if (kwd & CHKKWD) {
12104 const char *const *pp;
12106 pp = findkwd(wordtext);
12108 lasttoken = t = pp - tokname_array;
12109 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
12114 if (checkkwd & CHKALIAS) {
12115 #if ENABLE_ASH_ALIAS
12117 ap = lookupalias(wordtext, 1);
12120 pushstring(ap->val, ap);
12130 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
12132 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
12148 * Read and parse a command. Returns NODE_EOF on end of file.
12149 * (NULL is a valid parse tree indicating a blank line.)
12151 static union node *
12152 parsecmd(int interact)
12157 doprompt = interact;
12158 setprompt_if(doprompt, doprompt);
12164 * Input any here documents.
12169 struct heredoc *here;
12172 here = heredoclist;
12173 heredoclist = NULL;
12176 setprompt_if(needprompt, 2);
12177 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12178 here->eofmark, here->striptabs);
12179 n = stzalloc(sizeof(struct narg));
12180 n->narg.type = NARG;
12181 /*n->narg.next = NULL; - stzalloc did it */
12182 n->narg.text = wordtext;
12183 n->narg.backquote = backquotelist;
12184 here->here->nhere.doc = n;
12191 * called by editline -- any expansions to the prompt should be added here.
12193 #if ENABLE_ASH_EXPAND_PRMT
12194 static const char *
12195 expandstr(const char *ps)
12199 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12200 * and token processing _can_ alter it (delete NULs etc). */
12201 setinputstring((char *)ps);
12202 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12205 n.narg.type = NARG;
12206 n.narg.next = NULL;
12207 n.narg.text = wordtext;
12208 n.narg.backquote = backquotelist;
12210 expandarg(&n, NULL, EXP_QUOTED);
12211 return stackblock();
12216 * Execute a command or commands contained in a string.
12219 evalstring(char *s, int mask)
12222 struct stackmark smark;
12227 setstackmark(&smark);
12230 while ((n = parsecmd(0)) != NODE_EOF) {
12233 i = evaltree(n, 0);
12236 popstackmark(&smark);
12240 popstackmark(&smark);
12249 * The eval command.
12251 static int FAST_FUNC
12252 evalcmd(int argc UNUSED_PARAM, char **argv)
12261 STARTSTACKSTR(concat);
12263 concat = stack_putstr(p, concat);
12267 STPUTC(' ', concat);
12269 STPUTC('\0', concat);
12270 p = grabstackstr(concat);
12272 return evalstring(p, ~SKIPEVAL);
12278 * Read and execute commands.
12279 * "Top" is nonzero for the top level command loop;
12280 * it turns on prompting if the shell is interactive.
12286 struct stackmark smark;
12291 TRACE(("cmdloop(%d) called\n", top));
12295 setstackmark(&smark);
12298 showjobs(SHOW_CHANGED|SHOW_STDERR);
12301 if (iflag && top) {
12305 n = parsecmd(inter);
12307 if (DEBUG > 2 && debug && (n != NODE_EOF))
12310 if (n == NODE_EOF) {
12311 if (!top || numeof >= 50)
12313 if (!stoppedjobs()) {
12316 out2str("\nUse \"exit\" to leave shell.\n");
12319 } else if (nflag == 0) {
12322 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12325 i = evaltree(n, 0);
12329 popstackmark(&smark);
12334 return skip & SKIPEVAL;
12341 * Take commands from a file. To be compatible we should do a path
12342 * search for the file, which is necessary to find sub-commands.
12345 find_dot_file(char *name)
12348 const char *path = pathval();
12351 /* don't try this for absolute or relative paths */
12352 if (strchr(name, '/'))
12355 /* IIRC standards do not say whether . is to be searched.
12356 * And it is even smaller this way, making it unconditional for now:
12358 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12363 while ((fullname = path_advance(&path, name)) != NULL) {
12365 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12367 * Don't bother freeing here, since it will
12368 * be freed by the caller.
12372 if (fullname != name)
12373 stunalloc(fullname);
12376 /* not found in the PATH */
12377 ash_msg_and_raise_error("%s: not found", name);
12381 static int FAST_FUNC
12382 dotcmd(int argc, char **argv)
12385 struct strlist *sp;
12386 volatile struct shparam saveparam;
12388 for (sp = cmdenviron; sp; sp = sp->next)
12389 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12392 /* bash says: "bash: .: filename argument required" */
12393 return 2; /* bash compat */
12396 /* "false; . empty_file; echo $?" should print 0, not 1: */
12399 /* This aborts if file isn't found, which is POSIXly correct.
12400 * bash returns exitcode 1 instead.
12402 fullname = find_dot_file(argv[1]);
12405 if (argc) { /* argc > 0, argv[0] != NULL */
12406 saveparam = shellparam;
12407 shellparam.malloced = 0;
12408 shellparam.nparam = argc;
12409 shellparam.p = argv;
12412 /* This aborts if file can't be opened, which is POSIXly correct.
12413 * bash returns exitcode 1 instead.
12415 setinputfile(fullname, INPUT_PUSH_FILE);
12416 commandname = fullname;
12421 freeparam(&shellparam);
12422 shellparam = saveparam;
12428 static int FAST_FUNC
12429 exitcmd(int argc UNUSED_PARAM, char **argv)
12434 exitstatus = number(argv[1]);
12435 raise_exception(EXEXIT);
12440 * Read a file containing shell functions.
12443 readcmdfile(char *name)
12445 setinputfile(name, INPUT_PUSH_FILE);
12451 /* ============ find_command inplementation */
12454 * Resolve a command name. If you change this routine, you may have to
12455 * change the shellexec routine as well.
12458 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12460 struct tblentry *cmdp;
12467 struct builtincmd *bcmd;
12469 /* If name contains a slash, don't use PATH or hash table */
12470 if (strchr(name, '/') != NULL) {
12471 entry->u.index = -1;
12472 if (act & DO_ABS) {
12473 while (stat(name, &statb) < 0) {
12475 if (errno == EINTR)
12478 entry->cmdtype = CMDUNKNOWN;
12482 entry->cmdtype = CMDNORMAL;
12486 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12488 updatetbl = (path == pathval());
12491 if (strstr(path, "%builtin") != NULL)
12492 act |= DO_ALTBLTIN;
12495 /* If name is in the table, check answer will be ok */
12496 cmdp = cmdlookup(name, 0);
12497 if (cmdp != NULL) {
12500 switch (cmdp->cmdtype) {
12518 } else if (cmdp->rehash == 0)
12519 /* if not invalidated by cd, we're done */
12523 /* If %builtin not in path, check for builtin next */
12524 bcmd = find_builtin(name);
12526 if (IS_BUILTIN_REGULAR(bcmd))
12527 goto builtin_success;
12528 if (act & DO_ALTPATH) {
12529 if (!(act & DO_ALTBLTIN))
12530 goto builtin_success;
12531 } else if (builtinloc <= 0) {
12532 goto builtin_success;
12536 #if ENABLE_FEATURE_SH_STANDALONE
12538 int applet_no = find_applet_by_name(name);
12539 if (applet_no >= 0) {
12540 entry->cmdtype = CMDNORMAL;
12541 entry->u.index = -2 - applet_no;
12547 /* We have to search path. */
12548 prev = -1; /* where to start */
12549 if (cmdp && cmdp->rehash) { /* doing a rehash */
12550 if (cmdp->cmdtype == CMDBUILTIN)
12553 prev = cmdp->param.index;
12559 while ((fullname = path_advance(&path, name)) != NULL) {
12560 stunalloc(fullname);
12561 /* NB: code below will still use fullname
12562 * despite it being "unallocated" */
12565 if (prefix(pathopt, "builtin")) {
12567 goto builtin_success;
12570 if ((act & DO_NOFUNC)
12571 || !prefix(pathopt, "func")
12572 ) { /* ignore unimplemented options */
12576 /* if rehash, don't redo absolute path names */
12577 if (fullname[0] == '/' && idx <= prev) {
12580 TRACE(("searchexec \"%s\": no change\n", name));
12583 while (stat(fullname, &statb) < 0) {
12585 if (errno == EINTR)
12588 if (errno != ENOENT && errno != ENOTDIR)
12592 e = EACCES; /* if we fail, this will be the error */
12593 if (!S_ISREG(statb.st_mode))
12595 if (pathopt) { /* this is a %func directory */
12596 stalloc(strlen(fullname) + 1);
12597 /* NB: stalloc will return space pointed by fullname
12598 * (because we don't have any intervening allocations
12599 * between stunalloc above and this stalloc) */
12600 readcmdfile(fullname);
12601 cmdp = cmdlookup(name, 0);
12602 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12603 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12604 stunalloc(fullname);
12607 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12609 entry->cmdtype = CMDNORMAL;
12610 entry->u.index = idx;
12614 cmdp = cmdlookup(name, 1);
12615 cmdp->cmdtype = CMDNORMAL;
12616 cmdp->param.index = idx;
12621 /* We failed. If there was an entry for this command, delete it */
12622 if (cmdp && updatetbl)
12623 delete_cmd_entry();
12625 ash_msg("%s: %s", name, errmsg(e, "not found"));
12626 entry->cmdtype = CMDUNKNOWN;
12631 entry->cmdtype = CMDBUILTIN;
12632 entry->u.cmd = bcmd;
12636 cmdp = cmdlookup(name, 1);
12637 cmdp->cmdtype = CMDBUILTIN;
12638 cmdp->param.cmd = bcmd;
12642 entry->cmdtype = cmdp->cmdtype;
12643 entry->u = cmdp->param;
12647 /* ============ trap.c */
12650 * The trap builtin.
12652 static int FAST_FUNC
12653 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12657 int signo, exitcode;
12662 for (signo = 0; signo < NSIG; signo++) {
12663 char *tr = trap_ptr[signo];
12665 /* note: bash adds "SIG", but only if invoked
12666 * as "bash". If called as "sh", or if set -o posix,
12667 * then it prints short signal names.
12668 * We are printing short names: */
12669 out1fmt("trap -- %s %s\n",
12671 get_signame(signo));
12672 /* trap_ptr != trap only if we are in special-cased `trap` code.
12673 * In this case, we will exit very soon, no need to free(). */
12674 /* if (trap_ptr != trap && tp[0]) */
12679 if (trap_ptr != trap) {
12692 signo = get_signum(*ap);
12694 /* Mimic bash message exactly */
12695 ash_msg("%s: invalid signal specification", *ap);
12701 if (LONE_DASH(action))
12704 action = ckstrdup(action);
12708 may_have_traps = 1;
12709 trap[signo] = action;
12720 /* ============ Builtins */
12722 #if ENABLE_ASH_HELP
12723 static int FAST_FUNC
12724 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12730 "Built-in commands:\n"
12731 "------------------\n");
12732 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12733 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12734 builtintab[i].name + 1);
12740 # if ENABLE_FEATURE_SH_STANDALONE
12742 const char *a = applet_names;
12744 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12749 while (*a++ != '\0')
12755 return EXIT_SUCCESS;
12760 static int FAST_FUNC
12761 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12763 show_history(line_input_state);
12764 return EXIT_SUCCESS;
12769 * The export and readonly commands.
12771 static int FAST_FUNC
12772 exportcmd(int argc UNUSED_PARAM, char **argv)
12782 /* "readonly" in bash accepts, but ignores -n.
12783 * We do the same: it saves a conditional in nextopt's param.
12786 while ((opt = nextopt("np")) != '\0') {
12788 flag_off = VEXPORT;
12791 if (argv[0][0] == 'r') {
12793 flag_off = 0; /* readonly ignores -n */
12795 flag_off = ~flag_off;
12797 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12803 p = strchr(name, '=');
12807 vp = *findvar(hashvar(name), name);
12809 vp->flags = ((vp->flags | flag) & flag_off);
12813 setvar(name, p, (flag & flag_off));
12814 } while ((name = *++aptr) != NULL);
12819 /* No arguments. Show the list of exported or readonly vars.
12822 showvars(argv[0], flag, 0);
12827 * Delete a function if it exists.
12830 unsetfunc(const char *name)
12832 struct tblentry *cmdp;
12834 cmdp = cmdlookup(name, 0);
12835 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12836 delete_cmd_entry();
12840 * The unset builtin command. We unset the function before we unset the
12841 * variable to allow a function to be unset when there is a readonly variable
12842 * with the same name.
12844 static int FAST_FUNC
12845 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12852 while ((i = nextopt("vf")) != 0) {
12856 for (ap = argptr; *ap; ap++) {
12869 static const unsigned char timescmd_str[] ALIGN1 = {
12870 ' ', offsetof(struct tms, tms_utime),
12871 '\n', offsetof(struct tms, tms_stime),
12872 ' ', offsetof(struct tms, tms_cutime),
12873 '\n', offsetof(struct tms, tms_cstime),
12876 static int FAST_FUNC
12877 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12879 unsigned long clk_tck, s, t;
12880 const unsigned char *p;
12883 clk_tck = bb_clk_tck();
12888 t = *(clock_t *)(((char *) &buf) + p[1]);
12891 out1fmt("%lum%lu.%03lus%c",
12893 (t * 1000) / clk_tck,
12901 #if ENABLE_SH_MATH_SUPPORT
12903 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12904 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12906 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12908 static int FAST_FUNC
12909 letcmd(int argc UNUSED_PARAM, char **argv)
12915 ash_msg_and_raise_error("expression expected");
12917 i = ash_arith(*argv);
12925 * The read builtin. Options:
12926 * -r Do not interpret '\' specially
12927 * -s Turn off echo (tty only)
12928 * -n NCHARS Read NCHARS max
12929 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12930 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12931 * -u FD Read from given FD instead of fd 0
12932 * This uses unbuffered input, which may be avoidable in some cases.
12933 * TODO: bash also has:
12934 * -a ARRAY Read into array[0],[1],etc
12935 * -d DELIM End on DELIM char, not newline
12936 * -e Use line editing (tty only)
12938 static int FAST_FUNC
12939 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12941 char *opt_n = NULL;
12942 char *opt_p = NULL;
12943 char *opt_t = NULL;
12944 char *opt_u = NULL;
12945 int read_flags = 0;
12949 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12958 read_flags |= BUILTIN_READ_SILENT;
12964 read_flags |= BUILTIN_READ_RAW;
12974 /* "read -s" needs to save/restore termios, can't allow ^C
12975 * to jump out of it.
12978 r = shell_builtin_read(setvar0,
12980 bltinlookup("IFS"), /* can be NULL */
12989 if ((uintptr_t)r > 1)
12990 ash_msg_and_raise_error(r);
12992 return (uintptr_t)r;
12995 static int FAST_FUNC
12996 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12998 static const char permuser[3] ALIGN1 = "ogu";
13001 int symbolic_mode = 0;
13003 while (nextopt("S") != '\0') {
13012 if (*argptr == NULL) {
13013 if (symbolic_mode) {
13014 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13021 *p++ = permuser[i];
13023 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13024 if (!(mask & 0400)) *p++ = 'r';
13025 if (!(mask & 0200)) *p++ = 'w';
13026 if (!(mask & 0100)) *p++ = 'x';
13034 out1fmt("%04o\n", mask);
13037 char *modestr = *argptr;
13038 /* numeric umasks are taken as-is */
13039 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13040 if (!isdigit(modestr[0]))
13042 mask = bb_parse_mode(modestr, mask);
13043 if ((unsigned)mask > 0777) {
13044 ash_msg_and_raise_error("illegal mode: %s", modestr);
13046 if (!isdigit(modestr[0]))
13053 static int FAST_FUNC
13054 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13056 return shell_builtin_ulimit(argv);
13059 /* ============ main() and helpers */
13062 * Called to exit the shell.
13071 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13072 save_history(line_input_state);
13075 status = exitstatus;
13076 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13077 if (setjmp(loc.loc)) {
13078 if (exception_type == EXEXIT)
13079 /* dash bug: it just does _exit(exitstatus) here
13080 * but we have to do setjobctl(0) first!
13081 * (bug is still not fixed in dash-0.5.3 - if you run dash
13082 * under Midnight Commander, on exit from dash MC is backgrounded) */
13083 status = exitstatus;
13086 exception_handler = &loc;
13093 flush_stdout_stderr();
13103 /* from input.c: */
13104 /* we will never free this */
13105 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13108 signal(SIGCHLD, SIG_DFL);
13109 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13110 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13112 signal(SIGHUP, SIG_DFL);
13118 struct stat st1, st2;
13121 for (envp = environ; envp && *envp; envp++) {
13122 if (strchr(*envp, '=')) {
13123 setvareq(*envp, VEXPORT|VTEXTFIXED);
13127 setvar0("PPID", utoa(getppid()));
13128 #if ENABLE_ASH_BASH_COMPAT
13129 p = lookupvar("SHLVL");
13130 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13131 if (!lookupvar("HOSTNAME")) {
13132 struct utsname uts;
13134 setvar0("HOSTNAME", uts.nodename);
13137 p = lookupvar("PWD");
13139 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13140 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13150 //usage:#define ash_trivial_usage
13151 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13152 //usage:#define ash_full_usage "\n\n"
13153 //usage: "Unix shell interpreter"
13155 //usage:#if ENABLE_FEATURE_SH_IS_ASH
13156 //usage:# define sh_trivial_usage ash_trivial_usage
13157 //usage:# define sh_full_usage ash_full_usage
13159 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
13160 //usage:# define bash_trivial_usage ash_trivial_usage
13161 //usage:# define bash_full_usage ash_full_usage
13165 * Process the shell command line arguments.
13168 procargs(char **argv)
13171 const char *xminusc;
13176 /* if (xargv[0]) - mmm, this is always true! */
13178 for (i = 0; i < NOPTS; i++)
13181 if (options(/*cmdline:*/ 1)) {
13182 /* it already printed err message */
13183 raise_exception(EXERROR);
13187 if (*xargv == NULL) {
13189 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13192 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13196 for (i = 0; i < NOPTS; i++)
13197 if (optlist[i] == 2)
13202 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13207 } else if (!sflag) {
13208 setinputfile(*xargv, 0);
13211 commandname = arg0;
13214 shellparam.p = xargv;
13215 #if ENABLE_ASH_GETOPTS
13216 shellparam.optind = 1;
13217 shellparam.optoff = -1;
13219 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13221 shellparam.nparam++;
13228 * Read /etc/profile or .profile.
13231 read_profile(const char *name)
13235 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13244 * This routine is called when an error or an interrupt occurs in an
13245 * interactive shell and control is returned to the main command loop.
13253 /* from input.c: */
13254 g_parsefile->left_in_buffer = 0;
13255 g_parsefile->left_in_line = 0; /* clear input buffer */
13257 /* from parser.c: */
13260 /* from redir.c: */
13261 clearredir(/*drop:*/ 0);
13265 static short profile_buf[16384];
13266 extern int etext();
13270 * Main routine. We initialize things, parse the arguments, execute
13271 * profiles if we're a login shell, and then call cmdloop to execute
13272 * commands. The setjmp call sets up the location to jump to when an
13273 * exception occurs. When an exception occurs the variable "state"
13274 * is used to figure out how far we had gotten.
13276 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13277 int ash_main(int argc UNUSED_PARAM, char **argv)
13279 const char *shinit;
13280 volatile smallint state;
13281 struct jmploc jmploc;
13282 struct stackmark smark;
13284 /* Initialize global data */
13288 #if ENABLE_ASH_ALIAS
13294 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13297 #if ENABLE_FEATURE_EDITING
13298 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13301 if (setjmp(jmploc.loc)) {
13307 e = exception_type;
13311 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13315 newline_and_flush(stderr);
13318 popstackmark(&smark);
13319 FORCE_INT_ON; /* enable interrupts */
13328 exception_handler = &jmploc;
13331 TRACE(("Shell args: "));
13332 trace_puts_args(argv);
13334 rootpid = getpid();
13337 setstackmark(&smark);
13340 if (argv[0] && argv[0][0] == '-')
13346 read_profile("/etc/profile");
13349 hp = lookupvar("HOME");
13351 hp = concat_path_file(hp, ".profile");
13360 getuid() == geteuid() && getgid() == getegid() &&
13364 shinit = lookupvar("ENV");
13365 if (shinit != NULL && *shinit != '\0') {
13366 read_profile(shinit);
13372 /* evalstring pushes parsefile stack.
13373 * Ensure we don't falsely claim that 0 (stdin)
13374 * is one of stacked source fds.
13375 * Testcase: ash -c 'exec 1>&0' must not complain. */
13376 // if (!sflag) g_parsefile->pf_fd = -1;
13377 // ^^ not necessary since now we special-case fd 0
13378 // in is_hidden_fd() to not be considered "hidden fd"
13379 evalstring(minusc, 0);
13382 if (sflag || minusc == NULL) {
13383 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13385 const char *hp = lookupvar("HISTFILE");
13387 hp = lookupvar("HOME");
13389 hp = concat_path_file(hp, ".ash_history");
13390 setvar0("HISTFILE", hp);
13392 hp = lookupvar("HISTFILE");
13396 line_input_state->hist_file = hp;
13397 # if ENABLE_FEATURE_SH_HISTFILESIZE
13398 hp = lookupvar("HISTFILESIZE");
13399 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13403 state4: /* XXX ??? - why isn't this before the "if" statement */
13411 extern void _mcleanup(void);
13415 TRACE(("End of main reached\n"));
13422 * Copyright (c) 1989, 1991, 1993, 1994
13423 * The Regents of the University of California. All rights reserved.
13425 * This code is derived from software contributed to Berkeley by
13426 * Kenneth Almquist.
13428 * Redistribution and use in source and binary forms, with or without
13429 * modification, are permitted provided that the following conditions
13431 * 1. Redistributions of source code must retain the above copyright
13432 * notice, this list of conditions and the following disclaimer.
13433 * 2. Redistributions in binary form must reproduce the above copyright
13434 * notice, this list of conditions and the following disclaimer in the
13435 * documentation and/or other materials provided with the distribution.
13436 * 3. Neither the name of the University nor the names of its contributors
13437 * may be used to endorse or promote products derived from this software
13438 * without specific prior written permission.
13440 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13441 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13442 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13443 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13444 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13445 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13446 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13447 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13448 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13449 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF