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 */
1174 struct parsefile *prev; /* preceding file on stack */
1175 int linno; /* current line */
1176 int pf_fd; /* file descriptor (or -1 if string) */
1177 int left_in_line; /* number of chars left in this line */
1178 int left_in_buffer; /* number of chars left in this buffer past the line */
1179 char *next_to_pgetc; /* next char in buffer */
1180 char *buf; /* input buffer */
1181 struct strpush *strpush; /* for pushing strings at this level */
1182 struct strpush basestrpush; /* so pushing one is fast */
1185 static struct parsefile basepf; /* top level input file */
1186 static struct parsefile *g_parsefile = &basepf; /* current input file */
1187 static int startlinno; /* line # where last token started */
1188 static char *commandname; /* currently executing command */
1189 static struct strlist *cmdenviron; /* environment for builtin command */
1190 static uint8_t exitstatus; /* exit status of last command */
1193 /* ============ Message printing */
1196 ash_vmsg(const char *msg, va_list ap)
1198 fprintf(stderr, "%s: ", arg0);
1200 if (strcmp(arg0, commandname))
1201 fprintf(stderr, "%s: ", commandname);
1202 if (!iflag || g_parsefile->pf_fd > 0)
1203 fprintf(stderr, "line %d: ", startlinno);
1205 vfprintf(stderr, msg, ap);
1206 newline_and_flush(stderr);
1210 * Exverror is called to raise the error exception. If the second argument
1211 * is not NULL then error prints an error message using printf style
1212 * formatting. It then raises the error exception.
1214 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1216 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1220 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1222 TRACE(("\") pid=%d\n", getpid()));
1224 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1229 flush_stdout_stderr();
1230 raise_exception(cond);
1234 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1236 ash_msg_and_raise_error(const char *msg, ...)
1241 ash_vmsg_and_raise(EXERROR, msg, ap);
1246 static void raise_error_syntax(const char *) NORETURN;
1248 raise_error_syntax(const char *msg)
1250 ash_msg_and_raise_error("syntax error: %s", msg);
1254 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1256 ash_msg_and_raise(int cond, const char *msg, ...)
1261 ash_vmsg_and_raise(cond, msg, ap);
1267 * error/warning routines for external builtins
1270 ash_msg(const char *fmt, ...)
1280 * Return a string describing an error. The returned string may be a
1281 * pointer to a static buffer that will be overwritten on the next call.
1282 * Action describes the operation that got the error.
1285 errmsg(int e, const char *em)
1287 if (e == ENOENT || e == ENOTDIR) {
1294 /* ============ Memory allocation */
1297 /* I consider these wrappers nearly useless:
1298 * ok, they return you to nearest exception handler, but
1299 * how much memory do you leak in the process, making
1300 * memory starvation worse?
1303 ckrealloc(void * p, size_t nbytes)
1305 p = realloc(p, nbytes);
1307 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1312 ckmalloc(size_t nbytes)
1314 return ckrealloc(NULL, nbytes);
1318 ckzalloc(size_t nbytes)
1320 return memset(ckmalloc(nbytes), 0, nbytes);
1324 ckstrdup(const char *s)
1326 char *p = strdup(s);
1328 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1332 /* Using bbox equivalents. They exit if out of memory */
1333 # define ckrealloc xrealloc
1334 # define ckmalloc xmalloc
1335 # define ckzalloc xzalloc
1336 # define ckstrdup xstrdup
1340 * It appears that grabstackstr() will barf with such alignments
1341 * because stalloc() will return a string allocated in a new stackblock.
1343 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1345 /* Most machines require the value returned from malloc to be aligned
1346 * in some way. The following macro will get this right
1347 * on many machines. */
1348 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1349 /* Minimum size of a block */
1350 MINSIZE = SHELL_ALIGN(504),
1353 struct stack_block {
1354 struct stack_block *prev;
1355 char space[MINSIZE];
1359 struct stack_block *stackp;
1362 struct stackmark *marknext;
1366 struct globals_memstack {
1367 struct stack_block *g_stackp; // = &stackbase;
1368 struct stackmark *markp;
1369 char *g_stacknxt; // = stackbase.space;
1370 char *sstrend; // = stackbase.space + MINSIZE;
1371 size_t g_stacknleft; // = MINSIZE;
1372 int herefd; // = -1;
1373 struct stack_block stackbase;
1375 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1376 #define G_memstack (*ash_ptr_to_globals_memstack)
1377 #define g_stackp (G_memstack.g_stackp )
1378 #define markp (G_memstack.markp )
1379 #define g_stacknxt (G_memstack.g_stacknxt )
1380 #define sstrend (G_memstack.sstrend )
1381 #define g_stacknleft (G_memstack.g_stacknleft)
1382 #define herefd (G_memstack.herefd )
1383 #define stackbase (G_memstack.stackbase )
1384 #define INIT_G_memstack() do { \
1385 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1387 g_stackp = &stackbase; \
1388 g_stacknxt = stackbase.space; \
1389 g_stacknleft = MINSIZE; \
1390 sstrend = stackbase.space + MINSIZE; \
1395 #define stackblock() ((void *)g_stacknxt)
1396 #define stackblocksize() g_stacknleft
1399 * Parse trees for commands are allocated in lifo order, so we use a stack
1400 * to make this more efficient, and also to avoid all sorts of exception
1401 * handling code to handle interrupts in the middle of a parse.
1403 * The size 504 was chosen because the Ultrix malloc handles that size
1407 stalloc(size_t nbytes)
1412 aligned = SHELL_ALIGN(nbytes);
1413 if (aligned > g_stacknleft) {
1416 struct stack_block *sp;
1418 blocksize = aligned;
1419 if (blocksize < MINSIZE)
1420 blocksize = MINSIZE;
1421 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1422 if (len < blocksize)
1423 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1426 sp->prev = g_stackp;
1427 g_stacknxt = sp->space;
1428 g_stacknleft = blocksize;
1429 sstrend = g_stacknxt + blocksize;
1434 g_stacknxt += aligned;
1435 g_stacknleft -= aligned;
1440 stzalloc(size_t nbytes)
1442 return memset(stalloc(nbytes), 0, nbytes);
1449 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1450 write(STDERR_FILENO, "stunalloc\n", 10);
1454 g_stacknleft += g_stacknxt - (char *)p;
1459 * Like strdup but works with the ash stack.
1462 sstrdup(const char *p)
1464 size_t len = strlen(p) + 1;
1465 return memcpy(stalloc(len), p, len);
1469 setstackmark(struct stackmark *mark)
1471 mark->stackp = g_stackp;
1472 mark->stacknxt = g_stacknxt;
1473 mark->stacknleft = g_stacknleft;
1474 mark->marknext = markp;
1479 popstackmark(struct stackmark *mark)
1481 struct stack_block *sp;
1487 markp = mark->marknext;
1488 while (g_stackp != mark->stackp) {
1490 g_stackp = sp->prev;
1493 g_stacknxt = mark->stacknxt;
1494 g_stacknleft = mark->stacknleft;
1495 sstrend = mark->stacknxt + mark->stacknleft;
1500 * When the parser reads in a string, it wants to stick the string on the
1501 * stack and only adjust the stack pointer when it knows how big the
1502 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1503 * of space on top of the stack and stackblocklen returns the length of
1504 * this block. Growstackblock will grow this space by at least one byte,
1505 * possibly moving it (like realloc). Grabstackblock actually allocates the
1506 * part of the block that has been used.
1509 growstackblock(void)
1513 newlen = g_stacknleft * 2;
1514 if (newlen < g_stacknleft)
1515 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1519 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1520 struct stack_block *oldstackp;
1521 struct stackmark *xmark;
1522 struct stack_block *sp;
1523 struct stack_block *prevstackp;
1527 oldstackp = g_stackp;
1529 prevstackp = sp->prev;
1530 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1531 sp = ckrealloc(sp, grosslen);
1532 sp->prev = prevstackp;
1534 g_stacknxt = sp->space;
1535 g_stacknleft = newlen;
1536 sstrend = sp->space + newlen;
1539 * Stack marks pointing to the start of the old block
1540 * must be relocated to point to the new block
1543 while (xmark != NULL && xmark->stackp == oldstackp) {
1544 xmark->stackp = g_stackp;
1545 xmark->stacknxt = g_stacknxt;
1546 xmark->stacknleft = g_stacknleft;
1547 xmark = xmark->marknext;
1551 char *oldspace = g_stacknxt;
1552 size_t oldlen = g_stacknleft;
1553 char *p = stalloc(newlen);
1555 /* free the space we just allocated */
1556 g_stacknxt = memcpy(p, oldspace, oldlen);
1557 g_stacknleft += newlen;
1562 grabstackblock(size_t len)
1564 len = SHELL_ALIGN(len);
1566 g_stacknleft -= len;
1570 * The following routines are somewhat easier to use than the above.
1571 * The user declares a variable of type STACKSTR, which may be declared
1572 * to be a register. The macro STARTSTACKSTR initializes things. Then
1573 * the user uses the macro STPUTC to add characters to the string. In
1574 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1575 * grown as necessary. When the user is done, she can just leave the
1576 * string there and refer to it using stackblock(). Or she can allocate
1577 * the space for it using grabstackstr(). If it is necessary to allow
1578 * someone else to use the stack temporarily and then continue to grow
1579 * the string, the user should use grabstack to allocate the space, and
1580 * then call ungrabstr(p) to return to the previous mode of operation.
1582 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1583 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1584 * is space for at least one character.
1589 size_t len = stackblocksize();
1590 if (herefd >= 0 && len >= 1024) {
1591 full_write(herefd, stackblock(), len);
1592 return stackblock();
1595 return (char *)stackblock() + len;
1599 * Called from CHECKSTRSPACE.
1602 makestrspace(size_t newlen, char *p)
1604 size_t len = p - g_stacknxt;
1605 size_t size = stackblocksize();
1610 size = stackblocksize();
1612 if (nleft >= newlen)
1616 return (char *)stackblock() + len;
1620 stack_nputstr(const char *s, size_t n, char *p)
1622 p = makestrspace(n, p);
1623 p = (char *)memcpy(p, s, n) + n;
1628 stack_putstr(const char *s, char *p)
1630 return stack_nputstr(s, strlen(s), p);
1634 _STPUTC(int c, char *p)
1642 #define STARTSTACKSTR(p) ((p) = stackblock())
1643 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1644 #define CHECKSTRSPACE(n, p) do { \
1647 size_t m = sstrend - q; \
1649 (p) = makestrspace(l, q); \
1651 #define USTPUTC(c, p) (*(p)++ = (c))
1652 #define STACKSTRNUL(p) do { \
1653 if ((p) == sstrend) \
1654 (p) = growstackstr(); \
1657 #define STUNPUTC(p) (--(p))
1658 #define STTOPC(p) ((p)[-1])
1659 #define STADJUST(amount, p) ((p) += (amount))
1661 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1662 #define ungrabstackstr(s, p) stunalloc(s)
1663 #define stackstrend() ((void *)sstrend)
1666 /* ============ String helpers */
1669 * prefix -- see if pfx is a prefix of string.
1672 prefix(const char *string, const char *pfx)
1675 if (*pfx++ != *string++)
1678 return (char *) string;
1682 * Check for a valid number. This should be elsewhere.
1685 is_number(const char *p)
1690 } while (*++p != '\0');
1695 * Convert a string of digits to an integer, printing an error message on
1699 number(const char *s)
1702 ash_msg_and_raise_error(msg_illnum, s);
1707 * Produce a possibly single quoted string suitable as input to the shell.
1708 * The return string is allocated on the stack.
1711 single_quote(const char *s)
1721 len = strchrnul(s, '\'') - s;
1723 q = p = makestrspace(len + 3, p);
1726 q = (char *)memcpy(q, s, len) + len;
1735 do len++; while (*++s == '\'');
1737 q = p = makestrspace(len + 3, p);
1740 q = (char *)memcpy(q, s - len, len) + len;
1748 return stackblock();
1752 /* ============ nextopt */
1754 static char **argptr; /* argument list for builtin commands */
1755 static char *optionarg; /* set by nextopt (like getopt) */
1756 static char *optptr; /* used by nextopt */
1759 * XXX - should get rid of. Have all builtins use getopt(3).
1760 * The library getopt must have the BSD extension static variable
1761 * "optreset", otherwise it can't be used within the shell safely.
1763 * Standard option processing (a la getopt) for builtin routines.
1764 * The only argument that is passed to nextopt is the option string;
1765 * the other arguments are unnecessary. It returns the character,
1766 * or '\0' on end of input.
1769 nextopt(const char *optstring)
1776 if (p == NULL || *p == '\0') {
1777 /* We ate entire "-param", take next one */
1783 if (*++p == '\0') /* just "-" ? */
1786 if (LONE_DASH(p)) /* "--" ? */
1788 /* p => next "-param" */
1790 /* p => some option char in the middle of a "-param" */
1792 for (q = optstring; *q != c;) {
1794 ash_msg_and_raise_error("illegal option -%c", c);
1802 ash_msg_and_raise_error("no arg for -%c option", c);
1812 /* ============ Shell variables */
1815 * The parsefile structure pointed to by the global variable parsefile
1816 * contains information about the current file being read.
1819 int nparam; /* # of positional parameters (without $0) */
1820 #if ENABLE_ASH_GETOPTS
1821 int optind; /* next parameter to be processed by getopts */
1822 int optoff; /* used by getopts */
1824 unsigned char malloced; /* if parameter list dynamically allocated */
1825 char **p; /* parameter list */
1829 * Free the list of positional parameters.
1832 freeparam(volatile struct shparam *param)
1834 if (param->malloced) {
1836 ap = ap1 = param->p;
1843 #if ENABLE_ASH_GETOPTS
1844 static void FAST_FUNC getoptsreset(const char *value);
1848 struct var *next; /* next entry in hash list */
1849 int flags; /* flags are defined above */
1850 const char *var_text; /* name=value */
1851 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1852 /* the variable gets set/unset */
1856 struct localvar *next; /* next local variable in list */
1857 struct var *vp; /* the variable that was made local */
1858 int flags; /* saved flags */
1859 const char *text; /* saved text */
1863 #define VEXPORT 0x01 /* variable is exported */
1864 #define VREADONLY 0x02 /* variable cannot be modified */
1865 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1866 #define VTEXTFIXED 0x08 /* text is statically allocated */
1867 #define VSTACK 0x10 /* text is allocated on the stack */
1868 #define VUNSET 0x20 /* the variable is not set */
1869 #define VNOFUNC 0x40 /* don't call the callback function */
1870 #define VNOSET 0x80 /* do not set variable - just readonly test */
1871 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1872 #if ENABLE_ASH_RANDOM_SUPPORT
1873 # define VDYNAMIC 0x200 /* dynamic variable */
1879 /* Need to be before varinit_data[] */
1880 #if ENABLE_LOCALE_SUPPORT
1881 static void FAST_FUNC
1882 change_lc_all(const char *value)
1884 if (value && *value != '\0')
1885 setlocale(LC_ALL, value);
1887 static void FAST_FUNC
1888 change_lc_ctype(const char *value)
1890 if (value && *value != '\0')
1891 setlocale(LC_CTYPE, value);
1895 static void chkmail(void);
1896 static void changemail(const char *var_value) FAST_FUNC;
1898 # define chkmail() ((void)0)
1900 static void changepath(const char *) FAST_FUNC;
1901 #if ENABLE_ASH_RANDOM_SUPPORT
1902 static void change_random(const char *) FAST_FUNC;
1905 static const struct {
1907 const char *var_text;
1908 void (*var_func)(const char *) FAST_FUNC;
1909 } varinit_data[] = {
1911 * Note: VEXPORT would not work correctly here for NOFORK applets:
1912 * some environment strings may be constant.
1914 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1916 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1917 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1919 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1920 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1921 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1922 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1923 #if ENABLE_ASH_GETOPTS
1924 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1926 #if ENABLE_ASH_RANDOM_SUPPORT
1927 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1929 #if ENABLE_LOCALE_SUPPORT
1930 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1931 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1933 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1934 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1940 struct globals_var {
1941 struct shparam shellparam; /* $@ current positional parameters */
1942 struct redirtab *redirlist;
1944 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1945 struct var *vartab[VTABSIZE];
1946 struct var varinit[ARRAY_SIZE(varinit_data)];
1948 extern struct globals_var *const ash_ptr_to_globals_var;
1949 #define G_var (*ash_ptr_to_globals_var)
1950 #define shellparam (G_var.shellparam )
1951 //#define redirlist (G_var.redirlist )
1952 #define g_nullredirs (G_var.g_nullredirs )
1953 #define preverrout_fd (G_var.preverrout_fd)
1954 #define vartab (G_var.vartab )
1955 #define varinit (G_var.varinit )
1956 #define INIT_G_var() do { \
1958 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1960 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1961 varinit[i].flags = varinit_data[i].flags; \
1962 varinit[i].var_text = varinit_data[i].var_text; \
1963 varinit[i].var_func = varinit_data[i].var_func; \
1967 #define vifs varinit[0]
1969 # define vmail (&vifs)[1]
1970 # define vmpath (&vmail)[1]
1971 # define vpath (&vmpath)[1]
1973 # define vpath (&vifs)[1]
1975 #define vps1 (&vpath)[1]
1976 #define vps2 (&vps1)[1]
1977 #define vps4 (&vps2)[1]
1978 #if ENABLE_ASH_GETOPTS
1979 # define voptind (&vps4)[1]
1980 # if ENABLE_ASH_RANDOM_SUPPORT
1981 # define vrandom (&voptind)[1]
1984 # if ENABLE_ASH_RANDOM_SUPPORT
1985 # define vrandom (&vps4)[1]
1990 * The following macros access the values of the above variables.
1991 * They have to skip over the name. They return the null string
1992 * for unset variables.
1994 #define ifsval() (vifs.var_text + 4)
1995 #define ifsset() ((vifs.flags & VUNSET) == 0)
1997 # define mailval() (vmail.var_text + 5)
1998 # define mpathval() (vmpath.var_text + 9)
1999 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2001 #define pathval() (vpath.var_text + 5)
2002 #define ps1val() (vps1.var_text + 4)
2003 #define ps2val() (vps2.var_text + 4)
2004 #define ps4val() (vps4.var_text + 4)
2005 #if ENABLE_ASH_GETOPTS
2006 # define optindval() (voptind.var_text + 7)
2009 #if ENABLE_ASH_GETOPTS
2010 static void FAST_FUNC
2011 getoptsreset(const char *value)
2013 shellparam.optind = number(value);
2014 shellparam.optoff = -1;
2019 * Compares two strings up to the first = or '\0'. The first
2020 * string must be terminated by '='; the second may be terminated by
2021 * either '=' or '\0'.
2024 varcmp(const char *p, const char *q)
2028 while ((c = *p) == (d = *q)) {
2029 if (c == '\0' || c == '=')
2043 * Find the appropriate entry in the hash table from the name.
2045 static struct var **
2046 hashvar(const char *p)
2050 hashval = ((unsigned char) *p) << 4;
2051 while (*p && *p != '=')
2052 hashval += (unsigned char) *p++;
2053 return &vartab[hashval % VTABSIZE];
2057 vpcmp(const void *a, const void *b)
2059 return varcmp(*(const char **)a, *(const char **)b);
2063 * This routine initializes the builtin variables.
2073 * PS1 depends on uid
2075 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2076 vps1.var_text = "PS1=\\w \\$ ";
2079 vps1.var_text = "PS1=# ";
2082 end = vp + ARRAY_SIZE(varinit);
2084 vpp = hashvar(vp->var_text);
2087 } while (++vp < end);
2090 static struct var **
2091 findvar(struct var **vpp, const char *name)
2093 for (; *vpp; vpp = &(*vpp)->next) {
2094 if (varcmp((*vpp)->var_text, name) == 0) {
2102 * Find the value of a variable. Returns NULL if not set.
2104 static const char* FAST_FUNC
2105 lookupvar(const char *name)
2109 v = *findvar(hashvar(name), name);
2111 #if ENABLE_ASH_RANDOM_SUPPORT
2113 * Dynamic variables are implemented roughly the same way they are
2114 * in bash. Namely, they're "special" so long as they aren't unset.
2115 * As soon as they're unset, they're no longer dynamic, and dynamic
2116 * lookup will no longer happen at that point. -- PFM.
2118 if (v->flags & VDYNAMIC)
2121 if (!(v->flags & VUNSET))
2122 return var_end(v->var_text);
2127 static void reinit_unicode_for_ash(void)
2129 /* Unicode support should be activated even if LANG is set
2130 * _during_ shell execution, not only if it was set when
2131 * shell was started. Therefore, re-check LANG every time:
2133 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2134 || ENABLE_UNICODE_USING_LOCALE
2136 const char *s = lookupvar("LC_ALL");
2137 if (!s) s = lookupvar("LC_CTYPE");
2138 if (!s) s = lookupvar("LANG");
2144 * Search the environment of a builtin command.
2147 bltinlookup(const char *name)
2151 for (sp = cmdenviron; sp; sp = sp->next) {
2152 if (varcmp(sp->text, name) == 0)
2153 return var_end(sp->text);
2155 return lookupvar(name);
2159 * Same as setvar except that the variable and value are passed in
2160 * the first argument as name=value. Since the first argument will
2161 * be actually stored in the table, it should not be a string that
2163 * Called with interrupts off.
2166 setvareq(char *s, int flags)
2168 struct var *vp, **vpp;
2171 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2172 vp = *findvar(vpp, s);
2174 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2177 if (flags & VNOSAVE)
2180 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2186 if (vp->var_func && !(flags & VNOFUNC))
2187 vp->var_func(var_end(s));
2189 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2190 free((char*)vp->var_text);
2192 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2194 /* variable s is not found */
2197 vp = ckzalloc(sizeof(*vp));
2199 /*vp->func = NULL; - ckzalloc did it */
2202 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2209 * Set the value of a variable. The flags argument is ored with the
2210 * flags of the variable. If val is NULL, the variable is unset.
2213 setvar(const char *name, const char *val, int flags)
2221 q = endofname(name);
2222 p = strchrnul(q, '=');
2224 if (!namelen || p != q)
2225 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2230 vallen = strlen(val);
2234 nameeq = ckmalloc(namelen + vallen + 2);
2235 p = memcpy(nameeq, name, namelen) + namelen;
2238 p = memcpy(p, val, vallen) + vallen;
2241 setvareq(nameeq, flags | VNOSAVE);
2245 static void FAST_FUNC
2246 setvar0(const char *name, const char *val)
2248 setvar(name, val, 0);
2251 #if ENABLE_ASH_GETOPTS
2253 * Safe version of setvar, returns 1 on success 0 on failure.
2256 setvarsafe(const char *name, const char *val, int flags)
2259 volatile int saveint;
2260 struct jmploc *volatile savehandler = exception_handler;
2261 struct jmploc jmploc;
2264 if (setjmp(jmploc.loc))
2267 exception_handler = &jmploc;
2268 setvar(name, val, flags);
2271 exception_handler = savehandler;
2272 RESTORE_INT(saveint);
2278 * Unset the specified variable.
2281 unsetvar(const char *s)
2287 vpp = findvar(hashvar(s), s);
2291 int flags = vp->flags;
2294 if (flags & VREADONLY)
2296 #if ENABLE_ASH_RANDOM_SUPPORT
2297 vp->flags &= ~VDYNAMIC;
2301 if ((flags & VSTRFIXED) == 0) {
2303 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2304 free((char*)vp->var_text);
2310 vp->flags &= ~VEXPORT;
2320 * Process a linked list of variable assignments.
2323 listsetvar(struct strlist *list_set_var, int flags)
2325 struct strlist *lp = list_set_var;
2331 setvareq(lp->text, flags);
2338 * Generate a list of variables satisfying the given conditions.
2341 listvars(int on, int off, char ***end)
2352 for (vp = *vpp; vp; vp = vp->next) {
2353 if ((vp->flags & mask) == on) {
2354 if (ep == stackstrend())
2355 ep = growstackstr();
2356 *ep++ = (char*)vp->var_text;
2359 } while (++vpp < vartab + VTABSIZE);
2360 if (ep == stackstrend())
2361 ep = growstackstr();
2365 return grabstackstr(ep);
2369 /* ============ Path search helper
2371 * The variable path (passed by reference) should be set to the start
2372 * of the path before the first call; path_advance will update
2373 * this value as it proceeds. Successive calls to path_advance will return
2374 * the possible path expansions in sequence. If an option (indicated by
2375 * a percent sign) appears in the path entry then the global variable
2376 * pathopt will be set to point to it; otherwise pathopt will be set to
2379 static const char *pathopt; /* set by path_advance */
2382 path_advance(const char **path, const char *name)
2392 for (p = start; *p && *p != ':' && *p != '%'; p++)
2394 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2395 while (stackblocksize() < len)
2399 memcpy(q, start, p - start);
2407 while (*p && *p != ':')
2414 return stalloc(len);
2418 /* ============ Prompt */
2420 static smallint doprompt; /* if set, prompt the user */
2421 static smallint needprompt; /* true if interactive and at start of line */
2423 #if ENABLE_FEATURE_EDITING
2424 static line_input_t *line_input_state;
2425 static const char *cmdedit_prompt;
2427 putprompt(const char *s)
2429 if (ENABLE_ASH_EXPAND_PRMT) {
2430 free((char*)cmdedit_prompt);
2431 cmdedit_prompt = ckstrdup(s);
2438 putprompt(const char *s)
2444 #if ENABLE_ASH_EXPAND_PRMT
2445 /* expandstr() needs parsing machinery, so it is far away ahead... */
2446 static const char *expandstr(const char *ps);
2448 #define expandstr(s) s
2452 setprompt_if(smallint do_set, int whichprompt)
2455 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2462 switch (whichprompt) {
2472 #if ENABLE_ASH_EXPAND_PRMT
2473 setstackmark(&smark);
2474 stalloc(stackblocksize());
2476 putprompt(expandstr(prompt));
2477 #if ENABLE_ASH_EXPAND_PRMT
2478 popstackmark(&smark);
2483 /* ============ The cd and pwd commands */
2485 #define CD_PHYSICAL 1
2495 while ((i = nextopt("LP")) != '\0') {
2497 flags ^= CD_PHYSICAL;
2506 * Update curdir (the name of the current directory) in response to a
2510 updatepwd(const char *dir)
2517 cdcomppath = sstrdup(dir);
2520 if (curdir == nullstr)
2522 new = stack_putstr(curdir, new);
2524 new = makestrspace(strlen(dir) + 2, new);
2525 lim = (char *)stackblock() + 1;
2529 if (new > lim && *lim == '/')
2534 if (dir[1] == '/' && dir[2] != '/') {
2540 p = strtok(cdcomppath, "/");
2544 if (p[1] == '.' && p[2] == '\0') {
2556 new = stack_putstr(p, new);
2559 p = strtok(NULL, "/");
2564 return stackblock();
2568 * Find out what the current directory is. If we already know the current
2569 * directory, this routine returns immediately.
2574 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2575 return dir ? dir : nullstr;
2579 setpwd(const char *val, int setold)
2583 oldcur = dir = curdir;
2586 setvar("OLDPWD", oldcur, VEXPORT);
2589 if (physdir != nullstr) {
2590 if (physdir != oldcur)
2594 if (oldcur == val || !val) {
2600 dir = ckstrdup(val);
2601 if (oldcur != dir && oldcur != nullstr) {
2606 setvar("PWD", dir, VEXPORT);
2609 static void hashcd(void);
2612 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2613 * know that the current directory has changed.
2616 docd(const char *dest, int flags)
2618 const char *dir = NULL;
2621 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2624 if (!(flags & CD_PHYSICAL)) {
2625 dir = updatepwd(dest);
2639 static int FAST_FUNC
2640 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2652 dest = bltinlookup("HOME");
2653 else if (LONE_DASH(dest)) {
2654 dest = bltinlookup("OLDPWD");
2676 path = bltinlookup("CDPATH");
2685 p = path_advance(&path, dest);
2686 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2690 if (!docd(p, flags))
2695 ash_msg_and_raise_error("can't cd to %s", dest);
2698 if (flags & CD_PRINT)
2699 out1fmt("%s\n", curdir);
2703 static int FAST_FUNC
2704 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2707 const char *dir = curdir;
2711 if (physdir == nullstr)
2715 out1fmt("%s\n", dir);
2720 /* ============ ... */
2723 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2725 /* Syntax classes */
2726 #define CWORD 0 /* character is nothing special */
2727 #define CNL 1 /* newline character */
2728 #define CBACK 2 /* a backslash character */
2729 #define CSQUOTE 3 /* single quote */
2730 #define CDQUOTE 4 /* double quote */
2731 #define CENDQUOTE 5 /* a terminating quote */
2732 #define CBQUOTE 6 /* backwards single quote */
2733 #define CVAR 7 /* a dollar sign */
2734 #define CENDVAR 8 /* a '}' character */
2735 #define CLP 9 /* a left paren in arithmetic */
2736 #define CRP 10 /* a right paren in arithmetic */
2737 #define CENDFILE 11 /* end of file */
2738 #define CCTL 12 /* like CWORD, except it must be escaped */
2739 #define CSPCL 13 /* these terminate a word */
2740 #define CIGN 14 /* character should be ignored */
2743 #if ENABLE_ASH_ALIAS
2747 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2749 #if ENABLE_SH_MATH_SUPPORT
2750 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2752 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2754 static const uint16_t S_I_T[] ALIGN2 = {
2755 #if ENABLE_ASH_ALIAS
2756 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2758 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2759 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2760 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2761 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2762 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2763 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2764 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2765 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2766 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2767 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2768 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2769 #if !USE_SIT_FUNCTION
2770 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2771 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2772 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2776 /* Constants below must match table above */
2778 #if ENABLE_ASH_ALIAS
2779 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2781 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2782 CNL_CNL_CNL_CNL , /* 2 */
2783 CWORD_CCTL_CCTL_CWORD , /* 3 */
2784 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2785 CVAR_CVAR_CWORD_CVAR , /* 5 */
2786 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2787 CSPCL_CWORD_CWORD_CLP , /* 7 */
2788 CSPCL_CWORD_CWORD_CRP , /* 8 */
2789 CBACK_CBACK_CCTL_CBACK , /* 9 */
2790 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2791 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2792 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2793 CWORD_CWORD_CWORD_CWORD , /* 13 */
2794 CCTL_CCTL_CCTL_CCTL , /* 14 */
2797 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2798 * caller must ensure proper cast on it if c is *char_ptr!
2800 /* Values for syntax param */
2801 #define BASESYNTAX 0 /* not in quotes */
2802 #define DQSYNTAX 1 /* in double quotes */
2803 #define SQSYNTAX 2 /* in single quotes */
2804 #define ARISYNTAX 3 /* in arithmetic */
2805 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2807 #if USE_SIT_FUNCTION
2810 SIT(int c, int syntax)
2812 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2813 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2815 * This causes '/' to be prepended with CTLESC in dquoted string,
2816 * making "./file"* treated incorrectly because we feed
2817 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2818 * The "homegrown" glob implementation is okay with that,
2819 * but glibc one isn't. With '/' always treated as CWORD,
2822 # if ENABLE_ASH_ALIAS
2823 static const uint8_t syntax_index_table[] ALIGN1 = {
2824 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2825 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2826 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2830 static const uint8_t syntax_index_table[] ALIGN1 = {
2831 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2832 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2833 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2842 # if ENABLE_ASH_ALIAS
2848 /* Cast is purely for paranoia here,
2849 * just in case someone passed signed char to us */
2850 if ((unsigned char)c >= CTL_FIRST
2851 && (unsigned char)c <= CTL_LAST
2855 s = strchrnul(spec_symbls, c);
2858 indx = syntax_index_table[s - spec_symbls];
2860 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2863 #else /* !USE_SIT_FUNCTION */
2865 static const uint8_t syntax_index_table[] ALIGN1 = {
2866 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2867 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2877 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2878 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2900 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2901 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2902 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2903 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2904 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2905 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2906 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2907 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2908 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2909 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2910 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2911 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2912 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2913 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2914 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2915 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2916 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2918 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2927 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2928 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2929 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2930 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2931 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2932 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2960 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2961 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2962 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2965 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2993 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2994 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2995 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2996 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2997 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2998 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2999 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3000 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3001 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3002 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3003 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3004 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3005 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3120 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3121 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3122 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3123 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3124 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3125 # if ENABLE_ASH_ALIAS
3126 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3130 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3132 #endif /* !USE_SIT_FUNCTION */
3135 /* ============ Alias handling */
3137 #if ENABLE_ASH_ALIAS
3139 #define ALIASINUSE 1
3150 static struct alias **atab; // [ATABSIZE];
3151 #define INIT_G_alias() do { \
3152 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3156 static struct alias **
3157 __lookupalias(const char *name) {
3158 unsigned int hashval;
3165 ch = (unsigned char)*p;
3169 ch = (unsigned char)*++p;
3171 app = &atab[hashval % ATABSIZE];
3173 for (; *app; app = &(*app)->next) {
3174 if (strcmp(name, (*app)->name) == 0) {
3182 static struct alias *
3183 lookupalias(const char *name, int check)
3185 struct alias *ap = *__lookupalias(name);
3187 if (check && ap && (ap->flag & ALIASINUSE))
3192 static struct alias *
3193 freealias(struct alias *ap)
3197 if (ap->flag & ALIASINUSE) {
3198 ap->flag |= ALIASDEAD;
3210 setalias(const char *name, const char *val)
3212 struct alias *ap, **app;
3214 app = __lookupalias(name);
3218 if (!(ap->flag & ALIASINUSE)) {
3221 ap->val = ckstrdup(val);
3222 ap->flag &= ~ALIASDEAD;
3225 ap = ckzalloc(sizeof(struct alias));
3226 ap->name = ckstrdup(name);
3227 ap->val = ckstrdup(val);
3228 /*ap->flag = 0; - ckzalloc did it */
3229 /*ap->next = NULL;*/
3236 unalias(const char *name)
3240 app = __lookupalias(name);
3244 *app = freealias(*app);
3255 struct alias *ap, **app;
3259 for (i = 0; i < ATABSIZE; i++) {
3261 for (ap = *app; ap; ap = *app) {
3262 *app = freealias(*app);
3272 printalias(const struct alias *ap)
3274 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3278 * TODO - sort output
3280 static int FAST_FUNC
3281 aliascmd(int argc UNUSED_PARAM, char **argv)
3290 for (i = 0; i < ATABSIZE; i++) {
3291 for (ap = atab[i]; ap; ap = ap->next) {
3297 while ((n = *++argv) != NULL) {
3298 v = strchr(n+1, '=');
3299 if (v == NULL) { /* n+1: funny ksh stuff */
3300 ap = *__lookupalias(n);
3302 fprintf(stderr, "%s: %s not found\n", "alias", n);
3315 static int FAST_FUNC
3316 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3320 while ((i = nextopt("a")) != '\0') {
3326 for (i = 0; *argptr; argptr++) {
3327 if (unalias(*argptr)) {
3328 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3336 #endif /* ASH_ALIAS */
3339 /* ============ jobs.c */
3341 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3344 #define FORK_NOJOB 2
3346 /* mode flags for showjob(s) */
3347 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3348 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3349 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3350 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3353 * A job structure contains information about a job. A job is either a
3354 * single process or a set of processes contained in a pipeline. In the
3355 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3359 pid_t ps_pid; /* process id */
3360 int ps_status; /* last process status from wait() */
3361 char *ps_cmd; /* text of command being run */
3365 struct procstat ps0; /* status of process */
3366 struct procstat *ps; /* status or processes when more than one */
3368 int stopstatus; /* status of a stopped job */
3371 nprocs: 16, /* number of processes */
3373 #define JOBRUNNING 0 /* at least one proc running */
3374 #define JOBSTOPPED 1 /* all procs are stopped */
3375 #define JOBDONE 2 /* all procs are completed */
3377 sigint: 1, /* job was killed by SIGINT */
3378 jobctl: 1, /* job running under job control */
3380 waited: 1, /* true if this entry has been waited for */
3381 used: 1, /* true if this entry is in used */
3382 changed: 1; /* true if status has changed */
3383 struct job *prev_job; /* previous job */
3386 static struct job *makejob(/*union node *,*/ int);
3387 static int forkshell(struct job *, union node *, int);
3388 static int waitforjob(struct job *);
3391 enum { doing_jobctl = 0 };
3392 #define setjobctl(on) do {} while (0)
3394 static smallint doing_jobctl; //references:8
3395 static void setjobctl(int);
3402 ignoresig(int signo)
3404 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3405 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3406 /* No, need to do it */
3407 signal(signo, SIG_IGN);
3409 sigmode[signo - 1] = S_HARD_IGN;
3413 * Only one usage site - in setsignal()
3416 signal_handler(int signo)
3418 gotsig[signo - 1] = 1;
3420 if (signo == SIGINT && !trap[SIGINT]) {
3421 if (!suppress_int) {
3423 raise_interrupt(); /* does not return */
3427 pending_sig = signo;
3432 * Set the signal handler for the specified signal. The routine figures
3433 * out what it should be set to.
3436 setsignal(int signo)
3439 char cur_act, new_act;
3440 struct sigaction act;
3444 if (t != NULL) { /* trap for this sig is set */
3446 if (t[0] == '\0') /* trap is "": ignore this sig */
3450 if (rootshell && new_act == S_DFL) {
3453 if (iflag || minusc || sflag == 0)
3462 * "In all cases, bash ignores SIGQUIT. Non-builtin
3463 * commands run by bash have signal handlers
3464 * set to the values inherited by the shell
3465 * from its parent". */
3481 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3482 //whereas we have to restore it to what shell got on entry
3483 //from the parent. See comment above
3485 t = &sigmode[signo - 1];
3488 /* current setting is not yet known */
3489 if (sigaction(signo, NULL, &act)) {
3490 /* pretend it worked; maybe we should give a warning,
3491 * but other shells don't. We don't alter sigmode,
3492 * so we retry every time.
3493 * btw, in Linux it never fails. --vda */
3496 if (act.sa_handler == SIG_IGN) {
3497 cur_act = S_HARD_IGN;
3499 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3501 cur_act = S_IGN; /* don't hard ignore these */
3505 if (cur_act == S_HARD_IGN || cur_act == new_act)
3508 act.sa_handler = SIG_DFL;
3511 act.sa_handler = signal_handler;
3514 act.sa_handler = SIG_IGN;
3518 /* flags and mask matter only if !DFL and !IGN, but we do it
3519 * for all cases for more deterministic behavior:
3522 sigfillset(&act.sa_mask);
3524 sigaction_set(signo, &act);
3529 /* mode flags for set_curjob */
3530 #define CUR_DELETE 2
3531 #define CUR_RUNNING 1
3532 #define CUR_STOPPED 0
3534 /* mode flags for dowait */
3535 #define DOWAIT_NONBLOCK WNOHANG
3536 #define DOWAIT_BLOCK 0
3539 /* pgrp of shell on invocation */
3540 static int initialpgrp; //references:2
3541 static int ttyfd = -1; //5
3544 static struct job *jobtab; //5
3546 static unsigned njobs; //4
3548 static struct job *curjob; //lots
3549 /* number of presumed living untracked jobs */
3550 static int jobless; //4
3553 set_curjob(struct job *jp, unsigned mode)
3556 struct job **jpp, **curp;
3558 /* first remove from list */
3559 jpp = curp = &curjob;
3564 jpp = &jp1->prev_job;
3566 *jpp = jp1->prev_job;
3568 /* Then re-insert in correct position */
3576 /* job being deleted */
3579 /* newly created job or backgrounded job,
3580 * put after all stopped jobs.
3585 if (!jp1 || jp1->state != JOBSTOPPED)
3588 jpp = &jp1->prev_job;
3594 /* newly stopped job - becomes curjob */
3595 jp->prev_job = *jpp;
3603 jobno(const struct job *jp)
3605 return jp - jobtab + 1;
3610 * Convert a job name to a job structure.
3613 #define getjob(name, getctl) getjob(name)
3616 getjob(const char *name, int getctl)
3620 const char *err_msg = "%s: no such job";
3624 char *(*match)(const char *, const char *);
3639 if (c == '+' || c == '%') {
3641 err_msg = "No current job";
3647 err_msg = "No previous job";
3658 jp = jobtab + num - 1;
3673 if (match(jp->ps[0].ps_cmd, p)) {
3677 err_msg = "%s: ambiguous";
3687 err_msg = "job %s not created under job control";
3688 if (getctl && jp->jobctl == 0)
3693 ash_msg_and_raise_error(err_msg, name);
3697 * Mark a job structure as unused.
3700 freejob(struct job *jp)
3702 struct procstat *ps;
3706 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3707 if (ps->ps_cmd != nullstr)
3710 if (jp->ps != &jp->ps0)
3713 set_curjob(jp, CUR_DELETE);
3719 xtcsetpgrp(int fd, pid_t pgrp)
3721 if (tcsetpgrp(fd, pgrp))
3722 ash_msg_and_raise_error("can't set tty process group (%m)");
3726 * Turn job control on and off.
3728 * Note: This code assumes that the third arg to ioctl is a character
3729 * pointer, which is true on Berkeley systems but not System V. Since
3730 * System V doesn't have job control yet, this isn't a problem now.
3732 * Called with interrupts off.
3740 if (on == doing_jobctl || rootshell == 0)
3744 ofd = fd = open(_PATH_TTY, O_RDWR);
3746 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3747 * That sometimes helps to acquire controlling tty.
3748 * Obviously, a workaround for bugs when someone
3749 * failed to provide a controlling tty to bash! :) */
3755 fd = fcntl(fd, F_DUPFD, 10);
3760 /* fd is a tty at this point */
3761 close_on_exec_on(fd);
3762 while (1) { /* while we are in the background */
3763 pgrp = tcgetpgrp(fd);
3766 ash_msg("can't access tty; job control turned off");
3770 if (pgrp == getpgrp())
3781 xtcsetpgrp(fd, pgrp);
3783 /* turning job control off */
3786 /* was xtcsetpgrp, but this can make exiting ash
3787 * loop forever if pty is already deleted */
3788 tcsetpgrp(fd, pgrp);
3802 static int FAST_FUNC
3803 killcmd(int argc, char **argv)
3805 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3808 if (argv[i][0] == '%') {
3810 * "kill %N" - job kill
3811 * Converting to pgrp / pid kill
3817 jp = getjob(argv[i], 0);
3819 * In jobs started under job control, we signal
3820 * entire process group by kill -PGRP_ID.
3821 * This happens, f.e., in interactive shell.
3823 * Otherwise, we signal each child via
3824 * kill PID1 PID2 PID3.
3826 * sh -c 'sleep 1|sleep 1 & kill %1'
3827 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3828 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3830 n = jp->nprocs; /* can't be 0 (I hope) */
3833 dst = alloca(n * sizeof(int)*4);
3835 for (j = 0; j < n; j++) {
3836 struct procstat *ps = &jp->ps[j];
3837 /* Skip non-running and not-stopped members
3838 * (i.e. dead members) of the job
3840 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3843 * kill_main has matching code to expect
3844 * leading space. Needed to not confuse
3845 * negative pids with "kill -SIGNAL_NO" syntax
3847 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3851 } while (argv[++i]);
3853 return kill_main(argc, argv);
3857 showpipe(struct job *jp /*, FILE *out*/)
3859 struct procstat *ps;
3860 struct procstat *psend;
3862 psend = jp->ps + jp->nprocs;
3863 for (ps = jp->ps + 1; ps < psend; ps++)
3864 printf(" | %s", ps->ps_cmd);
3865 newline_and_flush(stdout);
3866 flush_stdout_stderr();
3871 restartjob(struct job *jp, int mode)
3873 struct procstat *ps;
3879 if (jp->state == JOBDONE)
3881 jp->state = JOBRUNNING;
3882 pgid = jp->ps[0].ps_pid;
3883 if (mode == FORK_FG)
3884 xtcsetpgrp(ttyfd, pgid);
3885 killpg(pgid, SIGCONT);
3889 if (WIFSTOPPED(ps->ps_status)) {
3895 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3900 static int FAST_FUNC
3901 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3907 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3911 jp = getjob(*argv, 1);
3912 if (mode == FORK_BG) {
3913 set_curjob(jp, CUR_RUNNING);
3914 printf("[%d] ", jobno(jp));
3916 out1str(jp->ps[0].ps_cmd);
3917 showpipe(jp /*, stdout*/);
3918 retval = restartjob(jp, mode);
3919 } while (*argv && *++argv);
3925 sprint_status48(char *s, int status, int sigonly)
3931 if (!WIFEXITED(status)) {
3932 if (JOBS && WIFSTOPPED(status))
3933 st = WSTOPSIG(status);
3935 st = WTERMSIG(status);
3937 if (st == SIGINT || st == SIGPIPE)
3939 if (JOBS && WIFSTOPPED(status))
3943 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3944 col = fmtstr(s, 32, strsignal(st));
3945 if (WCOREDUMP(status)) {
3946 strcpy(s + col, " (core dumped)");
3947 col += sizeof(" (core dumped)")-1;
3949 } else if (!sigonly) {
3950 st = WEXITSTATUS(status);
3951 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
3958 dowait(int wait_flags, struct job *job)
3963 struct job *thisjob;
3965 TRACE(("dowait(0x%x) called\n", wait_flags));
3967 /* Do a wait system call. If job control is compiled in, we accept
3968 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3969 * NB: _not_ safe_waitpid, we need to detect EINTR */
3971 wait_flags |= WUNTRACED;
3972 pid = waitpid(-1, &status, wait_flags);
3973 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3974 pid, status, errno, strerror(errno)));
3980 for (jp = curjob; jp; jp = jp->prev_job) {
3982 struct procstat *ps;
3983 struct procstat *psend;
3984 if (jp->state == JOBDONE)
3988 psend = ps + jp->nprocs;
3990 if (ps->ps_pid == pid) {
3991 TRACE(("Job %d: changing status of proc %d "
3992 "from 0x%x to 0x%x\n",
3993 jobno(jp), pid, ps->ps_status, status));
3994 ps->ps_status = status;
3997 if (ps->ps_status == -1)
3998 jobstate = JOBRUNNING;
4000 if (jobstate == JOBRUNNING)
4002 if (WIFSTOPPED(ps->ps_status)) {
4003 jp->stopstatus = ps->ps_status;
4004 jobstate = JOBSTOPPED;
4007 } while (++ps < psend);
4011 /* Found the job where one of its processes changed its state.
4012 * Is there at least one live and running process in this job? */
4013 if (jobstate != JOBRUNNING) {
4014 /* No. All live processes in the job are stopped
4015 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4017 thisjob->changed = 1;
4018 if (thisjob->state != jobstate) {
4019 TRACE(("Job %d: changing state from %d to %d\n",
4020 jobno(thisjob), thisjob->state, jobstate));
4021 thisjob->state = jobstate;
4023 if (jobstate == JOBSTOPPED)
4024 set_curjob(thisjob, CUR_STOPPED);
4030 /* The process wasn't found in job list */
4031 if (JOBS && !WIFSTOPPED(status))
4036 if (thisjob && thisjob == job) {
4040 len = sprint_status48(s, status, 1);
4051 blocking_wait_with_raise_on_sig(void)
4053 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
4054 if (pid <= 0 && pending_sig)
4055 raise_exception(EXSIG);
4061 showjob(struct job *jp, int mode)
4063 struct procstat *ps;
4064 struct procstat *psend;
4067 char s[16 + 16 + 48];
4068 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4072 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4073 /* just output process (group) id of pipeline */
4074 fprintf(out, "%d\n", ps->ps_pid);
4078 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4083 else if (curjob && jp == curjob->prev_job)
4086 if (mode & SHOW_PIDS)
4087 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4089 psend = ps + jp->nprocs;
4091 if (jp->state == JOBRUNNING) {
4092 strcpy(s + col, "Running");
4093 col += sizeof("Running") - 1;
4095 int status = psend[-1].ps_status;
4096 if (jp->state == JOBSTOPPED)
4097 status = jp->stopstatus;
4098 col += sprint_status48(s + col, status, 0);
4100 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4102 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4103 * or prints several "PID | <cmdN>" lines,
4104 * depending on SHOW_PIDS bit.
4105 * We do not print status of individual processes
4106 * between PID and <cmdN>. bash does it, but not very well:
4107 * first line shows overall job status, not process status,
4108 * making it impossible to know 1st process status.
4112 /* for each process */
4115 if (mode & SHOW_PIDS)
4116 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4118 fprintf(out, "%s%*c%s%s",
4120 33 - col >= 0 ? 33 - col : 0, ' ',
4121 ps == jp->ps ? "" : "| ",
4124 } while (++ps != psend);
4125 newline_and_flush(out);
4129 if (jp->state == JOBDONE) {
4130 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4136 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4137 * statuses have changed since the last call to showjobs.
4144 TRACE(("showjobs(0x%x) called\n", mode));
4146 /* Handle all finished jobs */
4147 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4150 for (jp = curjob; jp; jp = jp->prev_job) {
4151 if (!(mode & SHOW_CHANGED) || jp->changed) {
4157 static int FAST_FUNC
4158 jobscmd(int argc UNUSED_PARAM, char **argv)
4163 while ((m = nextopt("lp")) != '\0') {
4167 mode |= SHOW_ONLY_PGID;
4173 showjob(getjob(*argv, 0), mode);
4183 /* Called only on finished or stopped jobs (no members are running) */
4185 getstatus(struct job *job)
4189 struct procstat *ps;
4191 /* Fetch last member's status */
4192 ps = job->ps + job->nprocs - 1;
4193 status = ps->ps_status;
4195 /* "set -o pipefail" mode: use last _nonzero_ status */
4196 while (status == 0 && --ps >= job->ps)
4197 status = ps->ps_status;
4200 retval = WEXITSTATUS(status);
4201 if (!WIFEXITED(status)) {
4203 retval = WSTOPSIG(status);
4204 if (!WIFSTOPPED(status))
4207 /* XXX: limits number of signals */
4208 retval = WTERMSIG(status);
4210 if (retval == SIGINT)
4216 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4217 jobno(job), job->nprocs, status, retval));
4221 static int FAST_FUNC
4222 waitcmd(int argc UNUSED_PARAM, char **argv)
4229 raise_exception(EXSIG);
4236 /* wait for all jobs */
4240 if (!jp) /* no running procs */
4242 if (jp->state == JOBRUNNING)
4247 blocking_wait_with_raise_on_sig();
4249 * "When bash is waiting for an asynchronous command via
4250 * the wait builtin, the reception of a signal for which a trap
4251 * has been set will cause the wait builtin to return immediately
4252 * with an exit status greater than 128, immediately after which
4253 * the trap is executed."
4255 * blocking_wait_with_raise_on_sig raises signal handlers
4256 * if it gets no pid (pid < 0). However,
4257 * if child sends us a signal *and immediately exits*,
4258 * blocking_wait_with_raise_on_sig gets pid > 0
4259 * and does not handle pending_sig. Check this case: */
4261 raise_exception(EXSIG);
4267 if (**argv != '%') {
4268 pid_t pid = number(*argv);
4273 if (job->ps[job->nprocs - 1].ps_pid == pid)
4275 job = job->prev_job;
4278 job = getjob(*argv, 0);
4280 /* loop until process terminated or stopped */
4281 while (job->state == JOBRUNNING)
4282 blocking_wait_with_raise_on_sig();
4284 retval = getstatus(job);
4297 struct job *jp, *jq;
4299 len = njobs * sizeof(*jp);
4301 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4303 offset = (char *)jp - (char *)jq;
4305 /* Relocate pointers */
4308 jq = (struct job *)((char *)jq + l);
4312 #define joff(p) ((struct job *)((char *)(p) + l))
4313 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4314 if (joff(jp)->ps == &jq->ps0)
4315 jmove(joff(jp)->ps);
4316 if (joff(jp)->prev_job)
4317 jmove(joff(jp)->prev_job);
4327 jp = (struct job *)((char *)jp + len);
4331 } while (--jq >= jp);
4336 * Return a new job structure.
4337 * Called with interrupts off.
4340 makejob(/*union node *node,*/ int nprocs)
4345 for (i = njobs, jp = jobtab; ; jp++) {
4352 if (jp->state != JOBDONE || !jp->waited)
4361 memset(jp, 0, sizeof(*jp));
4363 /* jp->jobctl is a bitfield.
4364 * "jp->jobctl |= jobctl" likely to give awful code */
4368 jp->prev_job = curjob;
4373 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4375 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4382 * Return a string identifying a command (to be printed by the
4385 static char *cmdnextc;
4388 cmdputs(const char *s)
4390 static const char vstype[VSTYPE + 1][3] = {
4391 "", "}", "-", "+", "?", "=",
4392 "%", "%%", "#", "##"
4393 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4396 const char *p, *str;
4400 unsigned char subtype = 0;
4404 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4406 while ((c = *p++) != '\0') {
4414 if ((subtype & VSTYPE) == VSLENGTH)
4420 str = "\"}" + !(quoted & 1);
4427 #if ENABLE_SH_MATH_SUPPORT
4442 if ((subtype & VSTYPE) != VSNORMAL)
4444 str = vstype[subtype & VSTYPE];
4445 if (subtype & VSNUL)
4454 /* These can only happen inside quotes */
4467 while ((c = *str++) != '\0') {
4470 } /* while *p++ not NUL */
4473 USTPUTC('"', nextc);
4479 /* cmdtxt() and cmdlist() call each other */
4480 static void cmdtxt(union node *n);
4483 cmdlist(union node *np, int sep)
4485 for (; np; np = np->narg.next) {
4489 if (sep && np->narg.next)
4495 cmdtxt(union node *n)
4498 struct nodelist *lp;
4509 lp = n->npipe.cmdlist;
4527 cmdtxt(n->nbinary.ch1);
4543 cmdtxt(n->nif.test);
4545 if (n->nif.elsepart) {
4546 cmdtxt(n->nif.ifpart);
4548 n = n->nif.elsepart;
4566 cmdtxt(n->nbinary.ch1);
4576 cmdputs(n->nfor.var);
4578 cmdlist(n->nfor.args, 1);
4583 cmdputs(n->narg.text);
4587 cmdlist(n->ncmd.args, 1);
4588 cmdlist(n->ncmd.redirect, 0);
4601 cmdputs(n->ncase.expr->narg.text);
4603 for (np = n->ncase.cases; np; np = np->nclist.next) {
4604 cmdtxt(np->nclist.pattern);
4606 cmdtxt(np->nclist.body);
4620 #if ENABLE_ASH_BASH_COMPAT
4635 cmdputs(utoa(n->nfile.fd));
4637 if (n->type == NTOFD || n->type == NFROMFD) {
4638 cmdputs(utoa(n->ndup.dupfd));
4647 commandtext(union node *n)
4651 STARTSTACKSTR(cmdnextc);
4653 name = stackblock();
4654 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4655 name, cmdnextc, cmdnextc));
4656 return ckstrdup(name);
4661 * Fork off a subshell. If we are doing job control, give the subshell its
4662 * own process group. Jp is a job structure that the job is to be added to.
4663 * N is the command that will be evaluated by the child. Both jp and n may
4664 * be NULL. The mode parameter can be one of the following:
4665 * FORK_FG - Fork off a foreground process.
4666 * FORK_BG - Fork off a background process.
4667 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4668 * process group even if job control is on.
4670 * When job control is turned off, background processes have their standard
4671 * input redirected to /dev/null (except for the second and later processes
4674 * Called with interrupts off.
4677 * Clear traps on a fork.
4684 for (tp = trap; tp < &trap[NSIG]; tp++) {
4685 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4687 if (trap_ptr == trap)
4689 /* else: it "belongs" to trap_ptr vector, don't free */
4691 if ((tp - trap) != 0)
4692 setsignal(tp - trap);
4699 /* Lives far away from here, needed for forkchild */
4700 static void closescript(void);
4702 /* Called after fork(), in child */
4703 static NOINLINE void
4704 forkchild(struct job *jp, union node *n, int mode)
4708 TRACE(("Child shell %d\n", getpid()));
4712 /* man bash: "Non-builtin commands run by bash have signal handlers
4713 * set to the values inherited by the shell from its parent".
4714 * Do we do it correctly? */
4718 if (mode == FORK_NOJOB /* is it `xxx` ? */
4719 && n && n->type == NCMD /* is it single cmd? */
4720 /* && n->ncmd.args->type == NARG - always true? */
4721 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4722 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4723 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4725 TRACE(("Trap hack\n"));
4726 /* Awful hack for `trap` or $(trap).
4728 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4729 * contains an example where "trap" is executed in a subshell:
4731 * save_traps=$(trap)
4733 * eval "$save_traps"
4735 * Standard does not say that "trap" in subshell shall print
4736 * parent shell's traps. It only says that its output
4737 * must have suitable form, but then, in the above example
4738 * (which is not supposed to be normative), it implies that.
4740 * bash (and probably other shell) does implement it
4741 * (traps are reset to defaults, but "trap" still shows them),
4742 * but as a result, "trap" logic is hopelessly messed up:
4745 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4746 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4747 * # true | trap <--- trap is in subshell - no output (ditto)
4748 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4749 * trap -- 'echo Ho' SIGWINCH
4750 * # echo `(trap)` <--- in subshell in subshell - output
4751 * trap -- 'echo Ho' SIGWINCH
4752 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4753 * trap -- 'echo Ho' SIGWINCH
4755 * The rules when to forget and when to not forget traps
4756 * get really complex and nonsensical.
4758 * Our solution: ONLY bare $(trap) or `trap` is special.
4760 /* Save trap handler strings for trap builtin to print */
4761 trap_ptr = xmemdup(trap, sizeof(trap));
4762 /* Fall through into clearing traps */
4766 /* do job control only in root shell */
4768 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4771 if (jp->nprocs == 0)
4774 pgrp = jp->ps[0].ps_pid;
4775 /* this can fail because we are doing it in the parent also */
4777 if (mode == FORK_FG)
4778 xtcsetpgrp(ttyfd, pgrp);
4783 if (mode == FORK_BG) {
4784 /* man bash: "When job control is not in effect,
4785 * asynchronous commands ignore SIGINT and SIGQUIT" */
4788 if (jp->nprocs == 0) {
4790 if (open(bb_dev_null, O_RDONLY) != 0)
4791 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4795 if (iflag) { /* why if iflag only? */
4800 * "In all cases, bash ignores SIGQUIT. Non-builtin
4801 * commands run by bash have signal handlers
4802 * set to the values inherited by the shell
4804 * Take care of the second rule: */
4808 if (n && n->type == NCMD
4809 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4811 TRACE(("Job hack\n"));
4812 /* "jobs": we do not want to clear job list for it,
4813 * instead we remove only _its_ own_ job from job list.
4814 * This makes "jobs .... | cat" more useful.
4820 for (jp = curjob; jp; jp = jp->prev_job)
4825 /* Called after fork(), in parent */
4827 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4830 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4832 TRACE(("In parent shell: child = %d\n", pid));
4834 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4840 if (mode != FORK_NOJOB && jp->jobctl) {
4843 if (jp->nprocs == 0)
4846 pgrp = jp->ps[0].ps_pid;
4847 /* This can fail because we are doing it in the child also */
4851 if (mode == FORK_BG) {
4852 backgndpid = pid; /* set $! */
4853 set_curjob(jp, CUR_RUNNING);
4856 struct procstat *ps = &jp->ps[jp->nprocs++];
4859 ps->ps_cmd = nullstr;
4861 if (doing_jobctl && n)
4862 ps->ps_cmd = commandtext(n);
4868 forkshell(struct job *jp, union node *n, int mode)
4872 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4875 TRACE(("Fork failed, errno=%d", errno));
4878 ash_msg_and_raise_error("can't fork");
4881 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4882 forkchild(jp, n, mode);
4884 forkparent(jp, n, mode, pid);
4890 * Wait for job to finish.
4892 * Under job control we have the problem that while a child process
4893 * is running interrupts generated by the user are sent to the child
4894 * but not to the shell. This means that an infinite loop started by
4895 * an interactive user may be hard to kill. With job control turned off,
4896 * an interactive user may place an interactive program inside a loop.
4897 * If the interactive program catches interrupts, the user doesn't want
4898 * these interrupts to also abort the loop. The approach we take here
4899 * is to have the shell ignore interrupt signals while waiting for a
4900 * foreground process to terminate, and then send itself an interrupt
4901 * signal if the child process was terminated by an interrupt signal.
4902 * Unfortunately, some programs want to do a bit of cleanup and then
4903 * exit on interrupt; unless these processes terminate themselves by
4904 * sending a signal to themselves (instead of calling exit) they will
4905 * confuse this approach.
4907 * Called with interrupts off.
4910 waitforjob(struct job *jp)
4914 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4917 while (jp->state == JOBRUNNING) {
4918 /* In non-interactive shells, we _can_ get
4919 * a keyboard signal here and be EINTRed,
4920 * but we just loop back, waiting for command to complete.
4923 * "If bash is waiting for a command to complete and receives
4924 * a signal for which a trap has been set, the trap
4925 * will not be executed until the command completes."
4927 * Reality is that even if trap is not set, bash
4928 * will not act on the signal until command completes.
4929 * Try this. sleep5intoff.c:
4930 * #include <signal.h>
4931 * #include <unistd.h>
4934 * sigemptyset(&set);
4935 * sigaddset(&set, SIGINT);
4936 * sigaddset(&set, SIGQUIT);
4937 * sigprocmask(SIG_BLOCK, &set, NULL);
4941 * $ bash -c './sleep5intoff; echo hi'
4942 * ^C^C^C^C <--- pressing ^C once a second
4944 * $ bash -c './sleep5intoff; echo hi'
4945 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4948 dowait(DOWAIT_BLOCK, jp);
4955 xtcsetpgrp(ttyfd, rootpid);
4957 * This is truly gross.
4958 * If we're doing job control, then we did a TIOCSPGRP which
4959 * caused us (the shell) to no longer be in the controlling
4960 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4961 * intuit from the subprocess exit status whether a SIGINT
4962 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4964 if (jp->sigint) /* TODO: do the same with all signals */
4965 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4967 if (jp->state == JOBDONE)
4974 * return 1 if there are stopped jobs, otherwise 0
4986 if (jp && jp->state == JOBSTOPPED) {
4987 out2str("You have stopped jobs.\n");
4996 /* ============ redir.c
4998 * Code for dealing with input/output redirection.
5003 #define EMPTY -2 /* marks an unused slot in redirtab */
5004 #define CLOSED -3 /* marks a slot of previously-closed fd */
5007 * Open a file in noclobber mode.
5008 * The code was copied from bash.
5011 noclobberopen(const char *fname)
5014 struct stat finfo, finfo2;
5017 * If the file exists and is a regular file, return an error
5020 r = stat(fname, &finfo);
5021 if (r == 0 && S_ISREG(finfo.st_mode)) {
5027 * If the file was not present (r != 0), make sure we open it
5028 * exclusively so that if it is created before we open it, our open
5029 * will fail. Make sure that we do not truncate an existing file.
5030 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5031 * file was not a regular file, we leave O_EXCL off.
5034 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5035 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5037 /* If the open failed, return the file descriptor right away. */
5042 * OK, the open succeeded, but the file may have been changed from a
5043 * non-regular file to a regular file between the stat and the open.
5044 * We are assuming that the O_EXCL open handles the case where FILENAME
5045 * did not exist and is symlinked to an existing file between the stat
5050 * If we can open it and fstat the file descriptor, and neither check
5051 * revealed that it was a regular file, and the file has not been
5052 * replaced, return the file descriptor.
5054 if (fstat(fd, &finfo2) == 0
5055 && !S_ISREG(finfo2.st_mode)
5056 && finfo.st_dev == finfo2.st_dev
5057 && finfo.st_ino == finfo2.st_ino
5062 /* The file has been replaced. badness. */
5069 * Handle here documents. Normally we fork off a process to write the
5070 * data to a pipe. If the document is short, we can stuff the data in
5071 * the pipe without forking.
5073 /* openhere needs this forward reference */
5074 static void expandhere(union node *arg, int fd);
5076 openhere(union node *redir)
5082 ash_msg_and_raise_error("pipe call failed");
5083 if (redir->type == NHERE) {
5084 len = strlen(redir->nhere.doc->narg.text);
5085 if (len <= PIPE_BUF) {
5086 full_write(pip[1], redir->nhere.doc->narg.text, len);
5090 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5093 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5094 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5095 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5096 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5097 signal(SIGPIPE, SIG_DFL);
5098 if (redir->type == NHERE)
5099 full_write(pip[1], redir->nhere.doc->narg.text, len);
5101 expandhere(redir->nhere.doc, pip[1]);
5102 _exit(EXIT_SUCCESS);
5110 openredirect(union node *redir)
5115 switch (redir->nfile.type) {
5116 /* Can't happen, our single caller does this itself */
5122 return openhere(redir);
5125 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5126 * allocated space. Do it only when we know it is safe.
5128 fname = redir->nfile.expfname;
5130 switch (redir->nfile.type) {
5136 f = open(fname, O_RDONLY);
5141 f = open(fname, O_RDWR|O_CREAT, 0666);
5146 #if ENABLE_ASH_BASH_COMPAT
5149 /* Take care of noclobber mode. */
5151 f = noclobberopen(fname);
5158 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5163 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5171 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5173 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5177 * Copy a file descriptor to be >= to. Returns -1
5178 * if the source file descriptor is closed, EMPTY if there are no unused
5179 * file descriptors left.
5181 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5182 * old code was doing close(to) prior to copyfd() to achieve the same */
5184 COPYFD_EXACT = (int)~(INT_MAX),
5185 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5188 copyfd(int from, int to)
5192 if (to & COPYFD_EXACT) {
5193 to &= ~COPYFD_EXACT;
5195 newfd = dup2(from, to);
5197 newfd = fcntl(from, F_DUPFD, to);
5200 if (errno == EMFILE)
5202 /* Happens when source fd is not open: try "echo >&99" */
5203 ash_msg_and_raise_error("%d: %m", from);
5208 /* Struct def and variable are moved down to the first usage site */
5213 struct redirtab *next;
5216 struct two_fd_t two_fd[];
5218 #define redirlist (G_var.redirlist)
5220 static int need_to_remember(struct redirtab *rp, int fd)
5224 if (!rp) /* remembering was not requested */
5227 for (i = 0; i < rp->pair_count; i++) {
5228 if (rp->two_fd[i].orig == fd) {
5229 /* already remembered */
5236 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5237 static int is_hidden_fd(struct redirtab *rp, int fd)
5240 struct parsefile *pf;
5244 /* Check open scripts' fds */
5247 /* We skip pf_fd == 0 case because of the following case:
5248 * $ ash # running ash interactively
5250 * and in script.sh: "exec 9>&0".
5251 * Even though top-level pf_fd _is_ 0,
5252 * it's still ok to use it: "read" builtin uses it,
5253 * why should we cripple "exec" builtin?
5255 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5263 /* Check saved fds of redirects */
5264 fd |= COPYFD_RESTORE;
5265 for (i = 0; i < rp->pair_count; i++) {
5266 if (rp->two_fd[i].copy == fd) {
5274 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5275 * old file descriptors are stashed away so that the redirection can be
5276 * undone by calling popredir.
5278 /* flags passed to redirect */
5279 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5280 #define REDIR_SAVEFD2 03 /* set preverrout */
5282 redirect(union node *redir, int flags)
5284 struct redirtab *sv;
5289 int copied_fd2 = -1;
5299 if (flags & REDIR_PUSH) {
5300 union node *tmp = redir;
5303 #if ENABLE_ASH_BASH_COMPAT
5304 if (tmp->nfile.type == NTO2)
5307 tmp = tmp->nfile.next;
5309 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5310 sv->next = redirlist;
5311 sv->pair_count = sv_pos;
5313 sv->nullredirs = g_nullredirs - 1;
5315 while (sv_pos > 0) {
5317 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5323 fd = redir->nfile.fd;
5324 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5325 right_fd = redir->ndup.dupfd;
5326 //bb_error_msg("doing %d > %d", fd, right_fd);
5327 /* redirect from/to same file descriptor? */
5330 /* "echo >&10" and 10 is a fd opened to a sh script? */
5331 if (is_hidden_fd(sv, right_fd)) {
5332 errno = EBADF; /* as if it is closed */
5333 ash_msg_and_raise_error("%d: %m", right_fd);
5337 newfd = openredirect(redir); /* always >= 0 */
5339 /* Descriptor wasn't open before redirect.
5340 * Mark it for close in the future */
5341 if (need_to_remember(sv, fd)) {
5342 goto remember_to_close;
5347 #if ENABLE_ASH_BASH_COMPAT
5350 if (need_to_remember(sv, fd)) {
5351 /* Copy old descriptor */
5352 /* Careful to not accidentally "save"
5353 * to the same fd as right side fd in N>&M */
5354 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5355 i = fcntl(fd, F_DUPFD, minfd);
5356 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5357 * are closed in popredir() in the child, preventing them from leaking
5358 * into child. (popredir() also cleans up the mess in case of failures)
5363 /* Strange error (e.g. "too many files" EMFILE?) */
5367 ash_msg_and_raise_error("%d: %m", fd);
5370 /* EBADF: it is not open - good, remember to close it */
5373 } else { /* fd is open, save its copy */
5374 /* "exec fd>&-" should not close fds
5375 * which point to script file(s).
5376 * Force them to be restored afterwards */
5377 if (is_hidden_fd(sv, fd))
5378 i |= COPYFD_RESTORE;
5382 sv->two_fd[sv_pos].orig = fd;
5383 sv->two_fd[sv_pos].copy = i;
5387 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5388 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5389 /* Don't want to trigger debugging */
5393 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5395 } else if (fd != newfd) { /* move newfd to fd */
5396 copyfd(newfd, fd | COPYFD_EXACT);
5397 #if ENABLE_ASH_BASH_COMPAT
5398 if (!(redir->nfile.type == NTO2 && fd == 2))
5402 #if ENABLE_ASH_BASH_COMPAT
5403 if (redir->nfile.type == NTO2 && fd == 1) {
5404 /* We already redirected it to fd 1, now copy it to 2 */
5410 } while ((redir = redir->nfile.next) != NULL);
5413 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5414 preverrout_fd = copied_fd2;
5418 * Undo the effects of the last redirection.
5421 popredir(int drop, int restore)
5423 struct redirtab *rp;
5426 if (--g_nullredirs >= 0 || redirlist == NULL)
5430 for (i = 0; i < rp->pair_count; i++) {
5431 int fd = rp->two_fd[i].orig;
5432 int copy = rp->two_fd[i].copy;
5433 if (copy == CLOSED) {
5438 if (copy != EMPTY) {
5439 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5440 copy &= ~COPYFD_RESTORE;
5442 copyfd(copy, fd | COPYFD_EXACT);
5444 close(copy & ~COPYFD_RESTORE);
5447 redirlist = rp->next;
5448 g_nullredirs = rp->nullredirs;
5454 * Undo all redirections. Called on error or interrupt.
5458 * Discard all saved file descriptors.
5461 clearredir(int drop)
5467 popredir(drop, /*restore:*/ 0);
5472 redirectsafe(union node *redir, int flags)
5475 volatile int saveint;
5476 struct jmploc *volatile savehandler = exception_handler;
5477 struct jmploc jmploc;
5480 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5481 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5483 exception_handler = &jmploc;
5484 redirect(redir, flags);
5486 exception_handler = savehandler;
5487 if (err && exception_type != EXERROR)
5488 longjmp(exception_handler->loc, 1);
5489 RESTORE_INT(saveint);
5494 /* ============ Routines to expand arguments to commands
5496 * We have to deal with backquotes, shell variables, and file metacharacters.
5499 #if ENABLE_SH_MATH_SUPPORT
5501 ash_arith(const char *s)
5503 arith_state_t math_state;
5506 math_state.lookupvar = lookupvar;
5507 math_state.setvar = setvar0;
5508 //math_state.endofname = endofname;
5511 result = arith(&math_state, s);
5512 if (math_state.errmsg)
5513 ash_msg_and_raise_error(math_state.errmsg);
5523 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5524 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5525 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5526 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5527 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5528 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5529 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5530 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5531 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5535 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5536 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5537 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5538 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5539 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5541 /* Add CTLESC when necessary. */
5542 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5543 /* Do not skip NUL characters. */
5544 #define QUOTES_KEEPNUL EXP_TILDE
5547 * Structure specifying which parts of the string should be searched
5548 * for IFS characters.
5551 struct ifsregion *next; /* next region in list */
5552 int begoff; /* offset of start of region */
5553 int endoff; /* offset of end of region */
5554 int nulonly; /* search for nul bytes only */
5558 struct strlist *list;
5559 struct strlist **lastp;
5562 /* output of current string */
5563 static char *expdest;
5564 /* list of back quote expressions */
5565 static struct nodelist *argbackq;
5566 /* first struct in list of ifs regions */
5567 static struct ifsregion ifsfirst;
5568 /* last struct in list */
5569 static struct ifsregion *ifslastp;
5570 /* holds expanded arg list */
5571 static struct arglist exparg;
5576 #if !ENABLE_SH_MATH_SUPPORT
5577 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5578 typedef long arith_t;
5579 # define ARITH_FMT "%ld"
5586 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5587 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5588 STADJUST(len, expdest);
5593 esclen(const char *start, const char *p)
5597 while (p > start && (unsigned char)*--p == CTLESC) {
5604 * Remove any CTLESC characters from a string.
5607 rmescapes(char *str, int flag)
5609 static const char qchars[] ALIGN1 = {
5610 IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
5614 unsigned protect_against_glob;
5616 IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
5618 p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
5624 if (flag & RMESCAPE_ALLOC) {
5625 size_t len = p - str;
5626 size_t fulllen = len + strlen(p) + 1;
5628 if (flag & RMESCAPE_GROW) {
5629 int strloc = str - (char *)stackblock();
5630 r = makestrspace(fulllen, expdest);
5631 /* p and str may be invalidated by makestrspace */
5632 str = (char *)stackblock() + strloc;
5634 } else if (flag & RMESCAPE_HEAP) {
5635 r = ckmalloc(fulllen);
5637 r = stalloc(fulllen);
5641 q = (char *)memcpy(q, str, len) + len;
5646 globbing = flag & RMESCAPE_GLOB;
5647 protect_against_glob = globbing;
5649 if ((unsigned char)*p == CTLQUOTEMARK) {
5650 // Note: both inquotes and protect_against_glob only affect whether
5651 inquotes = ~inquotes;
5653 protect_against_glob = globbing;
5656 if ((unsigned char)*p == CTLESC) {
5660 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5662 if (protect_against_glob) {
5665 } else if (*p == '\\' && !inquotes) {
5666 /* naked back slash */
5667 protect_against_glob = 0;
5670 #if ENABLE_ASH_BASH_COMPAT
5671 else if (*p == '/' && slash) {
5672 /* stop handling globbing and mark location of slash */
5673 globbing = slash = 0;
5677 protect_against_glob = globbing;
5682 if (flag & RMESCAPE_GROW) {
5684 STADJUST(q - r + 1, expdest);
5688 #define pmatch(a, b) !fnmatch((a), (b), 0)
5691 * Prepare a pattern for a expmeta (internal glob(3)) call.
5693 * Returns an stalloced string.
5696 preglob(const char *pattern, int flag)
5698 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5702 * Put a string on the stack.
5705 memtodest(const char *p, size_t len, int syntax, int quotes)
5712 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5715 unsigned char c = *p++;
5717 int n = SIT(c, syntax);
5718 if ((quotes & QUOTES_ESC)
5720 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
5726 } else if (!(quotes & QUOTES_KEEPNUL))
5735 strtodest(const char *p, int syntax, int quotes)
5737 size_t len = strlen(p);
5738 memtodest(p, len, syntax, quotes);
5743 * Record the fact that we have to scan this region of the
5744 * string for IFS characters.
5747 recordregion(int start, int end, int nulonly)
5749 struct ifsregion *ifsp;
5751 if (ifslastp == NULL) {
5755 ifsp = ckzalloc(sizeof(*ifsp));
5756 /*ifsp->next = NULL; - ckzalloc did it */
5757 ifslastp->next = ifsp;
5761 ifslastp->begoff = start;
5762 ifslastp->endoff = end;
5763 ifslastp->nulonly = nulonly;
5767 removerecordregions(int endoff)
5769 if (ifslastp == NULL)
5772 if (ifsfirst.endoff > endoff) {
5773 while (ifsfirst.next) {
5774 struct ifsregion *ifsp;
5776 ifsp = ifsfirst.next->next;
5777 free(ifsfirst.next);
5778 ifsfirst.next = ifsp;
5781 if (ifsfirst.begoff > endoff) {
5784 ifslastp = &ifsfirst;
5785 ifsfirst.endoff = endoff;
5790 ifslastp = &ifsfirst;
5791 while (ifslastp->next && ifslastp->next->begoff < endoff)
5792 ifslastp = ifslastp->next;
5793 while (ifslastp->next) {
5794 struct ifsregion *ifsp;
5796 ifsp = ifslastp->next->next;
5797 free(ifslastp->next);
5798 ifslastp->next = ifsp;
5801 if (ifslastp->endoff > endoff)
5802 ifslastp->endoff = endoff;
5806 exptilde(char *startp, char *p, int flags)
5812 int quotes = flags & QUOTES_ESC;
5816 while ((c = *++p) != '\0') {
5823 if (flags & EXP_VARTILDE)
5833 if (*name == '\0') {
5834 home = lookupvar("HOME");
5836 pw = getpwnam(name);
5841 if (!home || !*home)
5844 strtodest(home, SQSYNTAX, quotes);
5852 * Execute a command inside back quotes. If it's a builtin command, we
5853 * want to save its output in a block obtained from malloc. Otherwise
5854 * we fork off a subprocess and get the output of the command via a pipe.
5855 * Should be called with interrupts off.
5857 struct backcmd { /* result of evalbackcmd */
5858 int fd; /* file descriptor to read from */
5859 int nleft; /* number of chars in buffer */
5860 char *buf; /* buffer */
5861 struct job *jp; /* job structure for command */
5864 /* These forward decls are needed to use "eval" code for backticks handling: */
5865 static uint8_t back_exitstatus; /* exit status of backquoted command */
5866 #define EV_EXIT 01 /* exit after evaluating tree */
5867 static int evaltree(union node *, int);
5869 static void FAST_FUNC
5870 evalbackcmd(union node *n, struct backcmd *result)
5881 saveherefd = herefd;
5889 ash_msg_and_raise_error("pipe call failed");
5890 jp = makejob(/*n,*/ 1);
5891 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5896 copyfd(pip[1], 1 | COPYFD_EXACT);
5900 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5904 result->fd = pip[0];
5907 herefd = saveherefd;
5909 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5910 result->fd, result->buf, result->nleft, result->jp));
5914 * Expand stuff in backwards quotes.
5917 expbackq(union node *cmd, int flag)
5925 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
5926 struct stackmark smark;
5929 setstackmark(&smark);
5931 startloc = dest - (char *)stackblock();
5933 evalbackcmd(cmd, &in);
5934 popstackmark(&smark);
5941 memtodest(p, i, syntax, flag & QUOTES_ESC);
5945 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
5946 TRACE(("expbackq: read returns %d\n", i));
5955 back_exitstatus = waitforjob(in.jp);
5959 /* Eat all trailing newlines */
5961 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5965 if (!(flag & EXP_QUOTED))
5966 recordregion(startloc, dest - (char *)stackblock(), 0);
5967 TRACE(("evalbackq: size:%d:'%.*s'\n",
5968 (int)((dest - (char *)stackblock()) - startloc),
5969 (int)((dest - (char *)stackblock()) - startloc),
5970 stackblock() + startloc));
5973 #if ENABLE_SH_MATH_SUPPORT
5975 * Expand arithmetic expression. Backup to start of expression,
5976 * evaluate, place result in (backed up) result, adjust string position.
5988 * This routine is slightly over-complicated for
5989 * efficiency. Next we scan backwards looking for the
5990 * start of arithmetic.
5992 start = stackblock();
5999 while ((unsigned char)*p != CTLARI) {
6003 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6008 esc = esclen(start, p);
6018 removerecordregions(begoff);
6022 if (flag & QUOTES_ESC)
6023 rmescapes(p + 1, 0);
6025 len = cvtnum(ash_arith(p + 1));
6027 if (!(flag & EXP_QUOTED))
6028 recordregion(begoff, begoff + len, 0);
6032 /* argstr needs it */
6033 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6036 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6037 * characters to allow for further processing. Otherwise treat
6038 * $@ like $* since no splitting will be performed.
6040 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6041 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6042 * for correct expansion of "B=$A" word.
6045 argstr(char *p, int flags, struct strlist *var_str_list)
6047 static const char spclchars[] ALIGN1 = {
6055 #if ENABLE_SH_MATH_SUPPORT
6060 const char *reject = spclchars;
6061 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6066 if (!(flags & EXP_VARTILDE)) {
6068 } else if (flags & EXP_VARTILDE2) {
6073 if (flags & EXP_TILDE) {
6076 flags &= ~EXP_TILDE;
6080 p = exptilde(p, q, flags);
6083 startloc = expdest - (char *)stackblock();
6087 length += strcspn(p + length, reject);
6091 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6093 /* c == '=' || c == ':' || c == CTLENDARI */
6099 expdest = stack_nputstr(p, length, expdest);
6100 newloc = expdest - (char *)stackblock();
6101 if (breakall && !inquotes && newloc > startloc) {
6102 recordregion(startloc, newloc, 0);
6113 if (flags & EXP_VARTILDE2) {
6117 flags |= EXP_VARTILDE2;
6122 * sort of a hack - expand tildes in variable
6123 * assignments (after the first '=' and after ':'s).
6132 case CTLENDVAR: /* ??? */
6135 inquotes ^= EXP_QUOTED;
6136 /* "$@" syntax adherence hack */
6137 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6138 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6142 if (flags & QUOTES_ESC) {
6153 * Quoted parameter expansion pattern: remove quote
6154 * unless inside inner quotes or we have a literal
6157 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6158 EXP_QPAT && *p != '\\')
6163 TRACE(("argstr: evalvar('%s')\n", p));
6164 p = evalvar(p, flags | inquotes, var_str_list);
6165 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6168 expbackq(argbackq->n, flags | inquotes);
6169 argbackq = argbackq->next;
6171 #if ENABLE_SH_MATH_SUPPORT
6174 expari(flags | inquotes);
6183 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6184 char *pattern, int quotes, int zero)
6193 const char *s = loc2;
6200 match = pmatch(pattern, s);
6205 if (quotes && (unsigned char)*loc == CTLESC)
6214 scanright(char *startp, char *rmesc, char *rmescend,
6215 char *pattern, int quotes, int match_at_start)
6217 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6218 int try2optimize = match_at_start;
6224 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6225 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6226 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6228 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6229 * and on each iteration they go back two/one char until they reach the beginning.
6230 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6232 /* TODO: document in what other circumstances we are called. */
6234 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6237 const char *s = loc2;
6238 if (match_at_start) {
6242 match = pmatch(pattern, s);
6243 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6247 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6249 /* Maybe we can optimize this:
6250 * if pattern ends with unescaped *, we can avoid checking
6251 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6252 * it wont match truncated "raw_value_of_" strings too.
6254 unsigned plen = strlen(pattern);
6255 /* Does it end with "*"? */
6256 if (plen != 0 && pattern[--plen] == '*') {
6257 /* "xxxx*" is not escaped */
6258 /* "xxx\*" is escaped */
6259 /* "xx\\*" is not escaped */
6260 /* "x\\\*" is escaped */
6262 while (plen != 0 && pattern[--plen] == '\\')
6265 break; /* ends with unescaped "*" */
6273 esc = esclen(startp, loc);
6284 static void varunset(const char *, const char *, const char *, int) NORETURN;
6286 varunset(const char *end, const char *var, const char *umsg, int varflags)
6292 msg = "parameter not set";
6294 if ((unsigned char)*end == CTLENDVAR) {
6295 if (varflags & VSNUL)
6301 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6305 subevalvar(char *p, char *varname, int strloc, int subtype,
6306 int startloc, int varflags, int flag, struct strlist *var_str_list)
6308 struct nodelist *saveargbackq = argbackq;
6309 int quotes = flag & QUOTES_ESC;
6312 char *rmesc, *rmescend;
6314 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6315 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6316 int saveherefd = herefd;
6317 int amount, resetloc;
6318 IF_ASH_BASH_COMPAT(int workloc;)
6320 char *(*scan)(char*, char*, char*, char*, int, int);
6322 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6323 // p, varname, strloc, subtype, startloc, varflags, quotes);
6326 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6327 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6329 STPUTC('\0', expdest);
6330 herefd = saveherefd;
6331 argbackq = saveargbackq;
6332 startp = (char *)stackblock() + startloc;
6336 setvar0(varname, startp);
6337 amount = startp - expdest;
6338 STADJUST(amount, expdest);
6342 varunset(p, varname, startp, varflags);
6345 #if ENABLE_ASH_BASH_COMPAT
6347 //TODO: support more general format ${v:EXPR:EXPR},
6348 // where EXPR follows $(()) rules
6349 loc = str = stackblock() + strloc;
6350 /* Read POS in ${var:POS:LEN} */
6351 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6352 len = str - startp - 1;
6354 /* *loc != '\0', guaranteed by parser */
6358 /* Adjust the length by the number of escapes */
6359 for (ptr = startp; ptr < (str - 1); ptr++) {
6360 if ((unsigned char)*ptr == CTLESC) {
6368 if (*loc++ == ':') {
6372 /* Skip POS in ${var:POS:LEN} */
6374 while (*loc && *loc != ':') {
6376 * bash complains on: var=qwe; echo ${var:1a:123}
6378 ash_msg_and_raise_error(msg_illnum, str);
6382 if (*loc++ == ':') {
6387 /* ${VAR:$((-n)):l} starts n chars from the end */
6388 pos = orig_len + pos;
6390 if ((unsigned)pos >= orig_len) {
6391 /* apart from obvious ${VAR:999999:l},
6392 * covers ${VAR:$((-9999999)):l} - result is ""
6398 if (len > (orig_len - pos))
6399 len = orig_len - pos;
6401 for (str = startp; pos; str++, pos--) {
6402 if (quotes && (unsigned char)*str == CTLESC)
6405 for (loc = startp; len; len--) {
6406 if (quotes && (unsigned char)*str == CTLESC)
6411 amount = loc - expdest;
6412 STADJUST(amount, expdest);
6417 resetloc = expdest - (char *)stackblock();
6419 /* We'll comeback here if we grow the stack while handling
6420 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6421 * stack will need rebasing, and we'll need to remove our work
6424 IF_ASH_BASH_COMPAT(restart:)
6426 amount = expdest - ((char *)stackblock() + resetloc);
6427 STADJUST(-amount, expdest);
6428 startp = (char *)stackblock() + startloc;
6431 rmescend = (char *)stackblock() + strloc;
6433 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6434 if (rmesc != startp) {
6436 startp = (char *)stackblock() + startloc;
6440 str = (char *)stackblock() + strloc;
6442 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6443 * The result is a_\_z_c (not a\_\_z_c)!
6445 * The search pattern and replace string treat backslashes differently!
6446 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6447 * and string. It's only used on the first call.
6449 preglob(str, IF_ASH_BASH_COMPAT(
6450 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6451 RMESCAPE_SLASH :) 0);
6453 #if ENABLE_ASH_BASH_COMPAT
6454 workloc = expdest - (char *)stackblock();
6455 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6459 repl = strchr(str, CTLESC);
6465 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6467 /* If there's no pattern to match, return the expansion unmolested */
6476 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6477 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6479 /* No match, advance */
6480 char *restart_detect = stackblock();
6482 STPUTC(*idx, expdest);
6483 if (quotes && (unsigned char)*idx == CTLESC) {
6486 STPUTC(*idx, expdest);
6488 if (stackblock() != restart_detect)
6493 /* continue; - prone to quadratic behavior, smarter code: */
6496 if (str[0] == '*') {
6497 /* Pattern is "*foo". If "*foo" does not match "long_string",
6498 * it would never match "ong_string" etc, no point in trying.
6505 if (subtype == VSREPLACEALL) {
6507 if (quotes && (unsigned char)*idx == CTLESC)
6516 //bb_error_msg("repl:'%s'", repl);
6517 for (loc = (char*)repl; *loc; loc++) {
6518 char *restart_detect = stackblock();
6519 if (quotes && *loc == '\\') {
6520 STPUTC(CTLESC, expdest);
6523 STPUTC(*loc, expdest);
6524 if (stackblock() != restart_detect)
6529 if (subtype == VSREPLACE) {
6530 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6532 char *restart_detect = stackblock();
6533 STPUTC(*idx, expdest);
6534 if (stackblock() != restart_detect)
6543 /* We've put the replaced text into a buffer at workloc, now
6544 * move it to the right place and adjust the stack.
6546 STPUTC('\0', expdest);
6547 startp = (char *)stackblock() + startloc;
6548 memmove(startp, (char *)stackblock() + workloc, len + 1);
6549 //bb_error_msg("startp:'%s'", startp);
6550 amount = expdest - (startp + len);
6551 STADJUST(-amount, expdest);
6554 #endif /* ENABLE_ASH_BASH_COMPAT */
6556 subtype -= VSTRIMRIGHT;
6558 if (subtype < 0 || subtype > 7)
6561 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6562 zero = subtype >> 1;
6563 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6564 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6566 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6569 memmove(startp, loc, str - loc);
6570 loc = startp + (str - loc) - 1;
6573 amount = loc - expdest;
6574 STADJUST(amount, expdest);
6580 * Add the value of a specialized variable to the stack string.
6581 * name parameter (examples):
6582 * ash -c 'echo $1' name:'1='
6583 * ash -c 'echo $qwe' name:'qwe='
6584 * ash -c 'echo $$' name:'$='
6585 * ash -c 'echo ${$}' name:'$='
6586 * ash -c 'echo ${$##q}' name:'$=q'
6587 * ash -c 'echo ${#$}' name:'$='
6588 * note: examples with bad shell syntax:
6589 * ash -c 'echo ${#$1}' name:'$=1'
6590 * ash -c 'echo ${#1#}' name:'1=#'
6592 static NOINLINE ssize_t
6593 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6600 int quoted = flags & EXP_QUOTED;
6601 int subtype = varflags & VSTYPE;
6602 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6603 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6604 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6606 sep = quoted ? ((flags & EXP_FULL) << CHAR_BIT) : 0;
6616 num = shellparam.nparam;
6624 goto check_1char_name;
6626 expdest = makestrspace(NOPTS, expdest);
6627 for (i = NOPTS - 1; i >= 0; i--) {
6629 USTPUTC(optletters(i), expdest);
6635 /* handles cases similar to ${#$1} */
6636 if (name[2] != '\0')
6637 raise_error_syntax("bad substitution");
6644 if (quoted && (flags & EXP_FULL)) {
6645 /* note: this is not meant as PEOF value */
6646 sep = 1 << CHAR_BIT;
6651 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6657 while ((p = *ap++) != NULL) {
6658 len += strtodest(p, syntax, quotes);
6662 memtodest(&sepc, 1, syntax, quotes);
6666 } /* case '@' and '*' */
6677 num = atoi(name); /* number(name) fails on ${N#str} etc */
6678 if (num < 0 || num > shellparam.nparam)
6680 p = num ? shellparam.p[num - 1] : arg0;
6683 /* NB: name has form "VAR=..." */
6685 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6686 * which should be considered before we check variables. */
6688 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6692 str = var_str_list->text;
6693 eq = strchr(str, '=');
6694 if (!eq) /* stop at first non-assignment */
6697 if (name_len == (unsigned)(eq - str)
6698 && strncmp(str, name, name_len) == 0
6701 /* goto value; - WRONG! */
6702 /* think "A=1 A=2 B=$A" */
6704 var_str_list = var_str_list->next;
6705 } while (var_str_list);
6709 p = lookupvar(name);
6714 len = strtodest(p, syntax, quotes);
6715 #if ENABLE_UNICODE_SUPPORT
6716 if (subtype == VSLENGTH && len > 0) {
6717 reinit_unicode_for_ash();
6718 if (unicode_status == UNICODE_ON) {
6719 STADJUST(-len, expdest);
6721 len = unicode_strlen(p);
6729 STADJUST(-len, expdest);
6734 * Expand a variable, and return a pointer to the next character in the
6738 evalvar(char *p, int flags, struct strlist *var_str_list)
6749 varflags = (unsigned char) *p++;
6750 subtype = varflags & VSTYPE;
6751 quoted = flags & EXP_QUOTED;
6753 easy = (!quoted || (*var == '@' && shellparam.nparam));
6754 startloc = expdest - (char *)stackblock();
6755 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6758 varlen = varvalue(var, varflags, flags, var_str_list);
6759 if (varflags & VSNUL)
6762 if (subtype == VSPLUS) {
6763 varlen = -1 - varlen;
6767 if (subtype == VSMINUS) {
6772 flags | EXP_TILDE | EXP_WORD,
6782 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6784 if (subevalvar(p, var, /* strloc: */ 0,
6785 subtype, startloc, varflags,
6786 /* quotes: */ flags & ~QUOTES_ESC,
6791 * Remove any recorded regions beyond
6794 removerecordregions(startloc);
6804 if (varlen < 0 && uflag)
6805 varunset(p, var, 0, 0);
6807 if (subtype == VSLENGTH) {
6808 cvtnum(varlen > 0 ? varlen : 0);
6812 if (subtype == VSNORMAL) {
6823 case VSTRIMRIGHTMAX:
6824 #if ENABLE_ASH_BASH_COMPAT
6837 * Terminate the string and start recording the pattern
6840 STPUTC('\0', expdest);
6841 patloc = expdest - (char *)stackblock();
6842 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6843 startloc, varflags, flags, var_str_list)) {
6844 int amount = expdest - (
6845 (char *)stackblock() + patloc - 1
6847 STADJUST(-amount, expdest);
6849 /* Remove any recorded regions beyond start of variable */
6850 removerecordregions(startloc);
6852 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6856 if (subtype != VSNORMAL) { /* skip to end of alternative */
6859 unsigned char c = *p++;
6862 else if (c == CTLBACKQ) {
6864 argbackq = argbackq->next;
6865 } else if (c == CTLVAR) {
6866 if ((*p++ & VSTYPE) != VSNORMAL)
6868 } else if (c == CTLENDVAR) {
6878 * Break the argument string into pieces based upon IFS and add the
6879 * strings to the argument list. The regions of the string to be
6880 * searched for IFS characters have been stored by recordregion.
6883 ifsbreakup(char *string, struct arglist *arglist)
6885 struct ifsregion *ifsp;
6890 const char *ifs, *realifs;
6895 if (ifslastp != NULL) {
6898 realifs = ifsset() ? ifsval() : defifs;
6901 p = string + ifsp->begoff;
6902 nulonly = ifsp->nulonly;
6903 ifs = nulonly ? nullstr : realifs;
6905 while (p < string + ifsp->endoff) {
6907 if ((unsigned char)*p == CTLESC)
6909 if (!strchr(ifs, *p)) {
6914 ifsspc = (strchr(defifs, *p) != NULL);
6915 /* Ignore IFS whitespace at start */
6916 if (q == start && ifsspc) {
6922 sp = stzalloc(sizeof(*sp));
6924 *arglist->lastp = sp;
6925 arglist->lastp = &sp->next;
6929 if (p >= string + ifsp->endoff) {
6933 if ((unsigned char)*p == CTLESC)
6935 if (strchr(ifs, *p) == NULL) {
6939 if (strchr(defifs, *p) == NULL) {
6954 } while (ifsp != NULL);
6963 sp = stzalloc(sizeof(*sp));
6965 *arglist->lastp = sp;
6966 arglist->lastp = &sp->next;
6972 struct ifsregion *p;
6977 struct ifsregion *ifsp;
6983 ifsfirst.next = NULL;
6988 * Add a file name to the list.
6991 addfname(const char *name)
6995 sp = stzalloc(sizeof(*sp));
6996 sp->text = sstrdup(name);
6998 exparg.lastp = &sp->next;
7001 /* If we want to use glob() from libc... */
7004 /* Add the result of glob() to the list */
7006 addglob(const glob_t *pglob)
7008 char **p = pglob->gl_pathv;
7015 expandmeta(struct strlist *str /*, int flag*/)
7017 /* TODO - EXP_REDIR */
7027 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7029 * GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7030 * TODO?: GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7032 i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7037 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7038 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7049 *exparg.lastp = str;
7050 rmescapes(str->text, 0);
7051 exparg.lastp = &str->next;
7053 default: /* GLOB_NOSPACE */
7056 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7063 /* Homegrown globbing code. (dash also has both, uses homegrown one.) */
7066 * Do metacharacter (i.e. *, ?, [...]) expansion.
7069 expmeta(char *expdir, char *enddir, char *name)
7085 for (p = name; esc = 0, *p; p += esc + 1) {
7086 if (*p == '*' || *p == '?')
7088 else if (*p == '[') {
7095 if (*q == '/' || *q == '\0')
7105 if (p[esc] == '/') {
7108 start = p + esc + 1;
7112 if (metaflag == 0) { /* we've reached the end of the file name */
7113 if (enddir != expdir)
7121 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7132 } while (p < start);
7134 if (enddir == expdir) {
7136 } else if (enddir == expdir + 1 && *expdir == '/') {
7145 if (enddir != expdir)
7147 if (*endname == 0) {
7160 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7161 if (dp->d_name[0] == '.' && !matchdot)
7163 if (pmatch(start, dp->d_name)) {
7165 strcpy(enddir, dp->d_name);
7168 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7171 expmeta(expdir, p, endname);
7177 endname[-esc - 1] = esc ? '\\' : '/';
7180 static struct strlist *
7181 msort(struct strlist *list, int len)
7183 struct strlist *p, *q = NULL;
7184 struct strlist **lpp;
7192 for (n = half; --n >= 0;) {
7196 q->next = NULL; /* terminate first half of list */
7197 q = msort(list, half); /* sort first half of list */
7198 p = msort(p, len - half); /* sort second half */
7201 #if ENABLE_LOCALE_SUPPORT
7202 if (strcoll(p->text, q->text) < 0)
7204 if (strcmp(p->text, q->text) < 0)
7228 * Sort the results of file name expansion. It calculates the number of
7229 * strings to sort and then calls msort (short for merge sort) to do the
7232 static struct strlist *
7233 expsort(struct strlist *str)
7239 for (sp = str; sp; sp = sp->next)
7241 return msort(str, len);
7245 expandmeta(struct strlist *str /*, int flag*/)
7247 static const char metachars[] ALIGN1 = {
7250 /* TODO - EXP_REDIR */
7254 struct strlist **savelastp;
7260 if (!strpbrk(str->text, metachars))
7262 savelastp = exparg.lastp;
7265 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7267 int i = strlen(str->text);
7268 //BUGGY estimation of how long expanded name can be
7269 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7271 expmeta(expdir, expdir, p);
7276 if (exparg.lastp == savelastp) {
7281 *exparg.lastp = str;
7282 rmescapes(str->text, 0);
7283 exparg.lastp = &str->next;
7285 *exparg.lastp = NULL;
7286 *savelastp = sp = expsort(*savelastp);
7287 while (sp->next != NULL)
7289 exparg.lastp = &sp->next;
7294 #endif /* our globbing code */
7297 * Perform variable substitution and command substitution on an argument,
7298 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7299 * perform splitting and file name expansion. When arglist is NULL, perform
7300 * here document expansion.
7303 expandarg(union node *arg, struct arglist *arglist, int flag)
7308 argbackq = arg->narg.backquote;
7309 STARTSTACKSTR(expdest);
7310 ifsfirst.next = NULL;
7312 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7313 argstr(arg->narg.text, flag,
7314 /* var_str_list: */ arglist ? arglist->list : NULL);
7315 p = _STPUTC('\0', expdest);
7317 if (arglist == NULL) {
7318 return; /* here document expanded */
7320 p = grabstackstr(p);
7321 TRACE(("expandarg: p:'%s'\n", p));
7322 exparg.lastp = &exparg.list;
7326 if (flag & EXP_FULL) {
7327 ifsbreakup(p, &exparg);
7328 *exparg.lastp = NULL;
7329 exparg.lastp = &exparg.list;
7330 expandmeta(exparg.list /*, flag*/);
7332 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7334 TRACE(("expandarg: rmescapes:'%s'\n", p));
7336 sp = stzalloc(sizeof(*sp));
7339 exparg.lastp = &sp->next;
7343 *exparg.lastp = NULL;
7345 *arglist->lastp = exparg.list;
7346 arglist->lastp = exparg.lastp;
7351 * Expand shell variables and backquotes inside a here document.
7354 expandhere(union node *arg, int fd)
7357 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7358 full_write(fd, stackblock(), expdest - (char *)stackblock());
7362 * Returns true if the pattern matches the string.
7365 patmatch(char *pattern, const char *string)
7367 return pmatch(preglob(pattern, 0), string);
7371 * See if a pattern matches in a case statement.
7374 casematch(union node *pattern, char *val)
7376 struct stackmark smark;
7379 setstackmark(&smark);
7380 argbackq = pattern->narg.backquote;
7381 STARTSTACKSTR(expdest);
7383 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7384 /* var_str_list: */ NULL);
7385 STACKSTRNUL(expdest);
7386 result = patmatch(stackblock(), val);
7387 popstackmark(&smark);
7392 /* ============ find_command */
7396 int (*builtin)(int, char **) FAST_FUNC;
7397 /* unsigned flags; */
7399 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7400 /* "regular" builtins always take precedence over commands,
7401 * regardless of PATH=....%builtin... position */
7402 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7403 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7406 smallint cmdtype; /* CMDxxx */
7409 /* index >= 0 for commands without path (slashes) */
7410 /* (TODO: what exactly does the value mean? PATH position?) */
7411 /* index == -1 for commands with slashes */
7412 /* index == (-2 - applet_no) for NOFORK applets */
7413 const struct builtincmd *cmd;
7414 struct funcnode *func;
7417 /* values of cmdtype */
7418 #define CMDUNKNOWN -1 /* no entry in table for command */
7419 #define CMDNORMAL 0 /* command is an executable program */
7420 #define CMDFUNCTION 1 /* command is a shell function */
7421 #define CMDBUILTIN 2 /* command is a shell builtin */
7423 /* action to find_command() */
7424 #define DO_ERR 0x01 /* prints errors */
7425 #define DO_ABS 0x02 /* checks absolute paths */
7426 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7427 #define DO_ALTPATH 0x08 /* using alternate path */
7428 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7430 static void find_command(char *, struct cmdentry *, int, const char *);
7433 /* ============ Hashing commands */
7436 * When commands are first encountered, they are entered in a hash table.
7437 * This ensures that a full path search will not have to be done for them
7438 * on each invocation.
7440 * We should investigate converting to a linear search, even though that
7441 * would make the command name "hash" a misnomer.
7445 struct tblentry *next; /* next entry in hash chain */
7446 union param param; /* definition of builtin function */
7447 smallint cmdtype; /* CMDxxx */
7448 char rehash; /* if set, cd done since entry created */
7449 char cmdname[1]; /* name of command */
7452 static struct tblentry **cmdtable;
7453 #define INIT_G_cmdtable() do { \
7454 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7457 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7461 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7463 #if ENABLE_FEATURE_SH_STANDALONE
7464 if (applet_no >= 0) {
7465 if (APPLET_IS_NOEXEC(applet_no)) {
7469 run_applet_no_and_exit(applet_no, argv);
7471 /* re-exec ourselves with the new arguments */
7472 execve(bb_busybox_exec_path, argv, envp);
7473 /* If they called chroot or otherwise made the binary no longer
7474 * executable, fall through */
7481 execve(cmd, argv, envp);
7482 } while (errno == EINTR);
7484 execve(cmd, argv, envp);
7486 if (cmd == (char*) bb_busybox_exec_path) {
7487 /* We already visited ENOEXEC branch below, don't do it again */
7488 //TODO: try execve(initial_argv0_of_shell, argv, envp) before giving up?
7492 if (errno == ENOEXEC) {
7493 /* Run "cmd" as a shell script:
7494 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7495 * "If the execve() function fails with ENOEXEC, the shell
7496 * shall execute a command equivalent to having a shell invoked
7497 * with the command name as its first operand,
7498 * with any remaining arguments passed to the new shell"
7500 * That is, do not use $SHELL, user's shell, or /bin/sh;
7501 * just call ourselves.
7503 * Note that bash reads ~80 chars of the file, and if it sees
7504 * a zero byte before it sees newline, it doesn't try to
7505 * interpret it, but fails with "cannot execute binary file"
7506 * message and exit code 126. For one, this prevents attempts
7507 * to interpret foreign ELF binaries as shell scripts.
7512 for (ap = argv; *ap; ap++)
7514 new = ckmalloc((ap - argv + 2) * sizeof(new[0]));
7515 new[0] = (char*) "ash";
7518 while ((*ap++ = *++argv) != NULL)
7520 cmd = (char*) bb_busybox_exec_path;
7527 * Exec a program. Never returns. If you change this routine, you may
7528 * have to change the find_command routine as well.
7530 static void shellexec(char **, const char *, int) NORETURN;
7532 shellexec(char **argv, const char *path, int idx)
7538 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7540 clearredir(/*drop:*/ 1);
7541 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7542 if (strchr(argv[0], '/') != NULL
7543 #if ENABLE_FEATURE_SH_STANDALONE
7544 || (applet_no = find_applet_by_name(argv[0])) >= 0
7547 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7548 if (applet_no >= 0) {
7549 /* We tried execing ourself, but it didn't work.
7550 * Maybe /proc/self/exe doesn't exist?
7559 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7560 if (--idx < 0 && pathopt == NULL) {
7561 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7562 if (errno != ENOENT && errno != ENOTDIR)
7569 /* Map to POSIX errors */
7581 exitstatus = exerrno;
7582 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7583 argv[0], e, suppress_int));
7584 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7589 printentry(struct tblentry *cmdp)
7595 idx = cmdp->param.index;
7598 name = path_advance(&path, cmdp->cmdname);
7600 } while (--idx >= 0);
7601 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7605 * Clear out command entries. The argument specifies the first entry in
7606 * PATH which has changed.
7609 clearcmdentry(int firstchange)
7611 struct tblentry **tblp;
7612 struct tblentry **pp;
7613 struct tblentry *cmdp;
7616 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7618 while ((cmdp = *pp) != NULL) {
7619 if ((cmdp->cmdtype == CMDNORMAL &&
7620 cmdp->param.index >= firstchange)
7621 || (cmdp->cmdtype == CMDBUILTIN &&
7622 builtinloc >= firstchange)
7635 * Locate a command in the command hash table. If "add" is nonzero,
7636 * add the command to the table if it is not already present. The
7637 * variable "lastcmdentry" is set to point to the address of the link
7638 * pointing to the entry, so that delete_cmd_entry can delete the
7641 * Interrupts must be off if called with add != 0.
7643 static struct tblentry **lastcmdentry;
7645 static struct tblentry *
7646 cmdlookup(const char *name, int add)
7648 unsigned int hashval;
7650 struct tblentry *cmdp;
7651 struct tblentry **pp;
7654 hashval = (unsigned char)*p << 4;
7656 hashval += (unsigned char)*p++;
7658 pp = &cmdtable[hashval % CMDTABLESIZE];
7659 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7660 if (strcmp(cmdp->cmdname, name) == 0)
7664 if (add && cmdp == NULL) {
7665 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7667 /* + 1 - already done because
7668 * tblentry::cmdname is char[1] */);
7669 /*cmdp->next = NULL; - ckzalloc did it */
7670 cmdp->cmdtype = CMDUNKNOWN;
7671 strcpy(cmdp->cmdname, name);
7678 * Delete the command entry returned on the last lookup.
7681 delete_cmd_entry(void)
7683 struct tblentry *cmdp;
7686 cmdp = *lastcmdentry;
7687 *lastcmdentry = cmdp->next;
7688 if (cmdp->cmdtype == CMDFUNCTION)
7689 freefunc(cmdp->param.func);
7695 * Add a new command entry, replacing any existing command entry for
7696 * the same name - except special builtins.
7699 addcmdentry(char *name, struct cmdentry *entry)
7701 struct tblentry *cmdp;
7703 cmdp = cmdlookup(name, 1);
7704 if (cmdp->cmdtype == CMDFUNCTION) {
7705 freefunc(cmdp->param.func);
7707 cmdp->cmdtype = entry->cmdtype;
7708 cmdp->param = entry->u;
7712 static int FAST_FUNC
7713 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7715 struct tblentry **pp;
7716 struct tblentry *cmdp;
7718 struct cmdentry entry;
7721 if (nextopt("r") != '\0') {
7726 if (*argptr == NULL) {
7727 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7728 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7729 if (cmdp->cmdtype == CMDNORMAL)
7737 while ((name = *argptr) != NULL) {
7738 cmdp = cmdlookup(name, 0);
7740 && (cmdp->cmdtype == CMDNORMAL
7741 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7745 find_command(name, &entry, DO_ERR, pathval());
7746 if (entry.cmdtype == CMDUNKNOWN)
7754 * Called when a cd is done. Marks all commands so the next time they
7755 * are executed they will be rehashed.
7760 struct tblentry **pp;
7761 struct tblentry *cmdp;
7763 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7764 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7765 if (cmdp->cmdtype == CMDNORMAL
7766 || (cmdp->cmdtype == CMDBUILTIN
7767 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7777 * Fix command hash table when PATH changed.
7778 * Called before PATH is changed. The argument is the new value of PATH;
7779 * pathval() still returns the old value at this point.
7780 * Called with interrupts off.
7782 static void FAST_FUNC
7783 changepath(const char *new)
7791 firstchange = 9999; /* assume no change */
7797 if ((*old == '\0' && *new == ':')
7798 || (*old == ':' && *new == '\0')
7802 old = new; /* ignore subsequent differences */
7806 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7813 if (builtinloc < 0 && idx_bltin >= 0)
7814 builtinloc = idx_bltin; /* zap builtins */
7815 if (builtinloc >= 0 && idx_bltin < 0)
7817 clearcmdentry(firstchange);
7818 builtinloc = idx_bltin;
7843 #if ENABLE_ASH_BASH_COMPAT
7854 typedef smallint token_id_t;
7856 /* first char is indicating which tokens mark the end of a list */
7857 static const char *const tokname_array[] = {
7871 #define KWDOFFSET 13
7872 /* the following are keywords */
7882 #if ENABLE_ASH_BASH_COMPAT
7894 /* Wrapper around strcmp for qsort/bsearch/... */
7896 pstrcmp(const void *a, const void *b)
7898 return strcmp((char*) a, (*(char**) b) + 1);
7901 static const char *const *
7902 findkwd(const char *s)
7904 return bsearch(s, tokname_array + KWDOFFSET,
7905 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7906 sizeof(tokname_array[0]), pstrcmp);
7910 * Locate and print what a word is...
7913 describe_command(char *command, const char *path, int describe_command_verbose)
7915 struct cmdentry entry;
7916 struct tblentry *cmdp;
7917 #if ENABLE_ASH_ALIAS
7918 const struct alias *ap;
7921 path = path ? path : pathval();
7923 if (describe_command_verbose) {
7927 /* First look at the keywords */
7928 if (findkwd(command)) {
7929 out1str(describe_command_verbose ? " is a shell keyword" : command);
7933 #if ENABLE_ASH_ALIAS
7934 /* Then look at the aliases */
7935 ap = lookupalias(command, 0);
7937 if (!describe_command_verbose) {
7942 out1fmt(" is an alias for %s", ap->val);
7946 /* Then check if it is a tracked alias */
7947 cmdp = cmdlookup(command, 0);
7949 entry.cmdtype = cmdp->cmdtype;
7950 entry.u = cmdp->param;
7952 /* Finally use brute force */
7953 find_command(command, &entry, DO_ABS, path);
7956 switch (entry.cmdtype) {
7958 int j = entry.u.index;
7964 p = path_advance(&path, command);
7968 if (describe_command_verbose) {
7970 (cmdp ? " a tracked alias for" : nullstr), p
7979 if (describe_command_verbose) {
7980 out1str(" is a shell function");
7987 if (describe_command_verbose) {
7988 out1fmt(" is a %sshell builtin",
7989 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7990 "special " : nullstr
7998 if (describe_command_verbose) {
7999 out1str(": not found\n");
8008 static int FAST_FUNC
8009 typecmd(int argc UNUSED_PARAM, char **argv)
8015 /* type -p ... ? (we don't bother checking for 'p') */
8016 if (argv[1] && argv[1][0] == '-') {
8021 err |= describe_command(argv[i++], NULL, verbose);
8026 #if ENABLE_ASH_CMDCMD
8027 static int FAST_FUNC
8028 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8035 const char *path = NULL;
8037 while ((c = nextopt("pvV")) != '\0')
8039 verify |= VERIFY_VERBOSE;
8041 verify |= VERIFY_BRIEF;
8047 path = bb_default_path;
8048 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8049 if (verify && (*argptr != NULL)) {
8050 return describe_command(*argptr, path, verify - VERIFY_BRIEF);
8058 /* ============ eval.c */
8060 static int funcblocksize; /* size of structures in function */
8061 static int funcstringsize; /* size of strings in node */
8062 static void *funcblock; /* block to allocate function from */
8063 static char *funcstring; /* block to allocate strings from */
8065 /* flags in argument to evaltree */
8066 #define EV_EXIT 01 /* exit after evaluating tree */
8067 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8069 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8070 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8071 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8072 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8073 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8074 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8075 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8076 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8077 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8078 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8079 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8080 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8081 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8082 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8083 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8084 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8085 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8086 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8087 #if ENABLE_ASH_BASH_COMPAT
8088 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8090 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8091 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8092 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8093 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8094 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8095 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8096 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8097 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8098 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8101 static void calcsize(union node *n);
8104 sizenodelist(struct nodelist *lp)
8107 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8114 calcsize(union node *n)
8118 funcblocksize += nodesize[n->type];
8121 calcsize(n->ncmd.redirect);
8122 calcsize(n->ncmd.args);
8123 calcsize(n->ncmd.assign);
8126 sizenodelist(n->npipe.cmdlist);
8131 calcsize(n->nredir.redirect);
8132 calcsize(n->nredir.n);
8139 calcsize(n->nbinary.ch2);
8140 calcsize(n->nbinary.ch1);
8143 calcsize(n->nif.elsepart);
8144 calcsize(n->nif.ifpart);
8145 calcsize(n->nif.test);
8148 funcstringsize += strlen(n->nfor.var) + 1;
8149 calcsize(n->nfor.body);
8150 calcsize(n->nfor.args);
8153 calcsize(n->ncase.cases);
8154 calcsize(n->ncase.expr);
8157 calcsize(n->nclist.body);
8158 calcsize(n->nclist.pattern);
8159 calcsize(n->nclist.next);
8163 sizenodelist(n->narg.backquote);
8164 funcstringsize += strlen(n->narg.text) + 1;
8165 calcsize(n->narg.next);
8168 #if ENABLE_ASH_BASH_COMPAT
8175 calcsize(n->nfile.fname);
8176 calcsize(n->nfile.next);
8180 calcsize(n->ndup.vname);
8181 calcsize(n->ndup.next);
8185 calcsize(n->nhere.doc);
8186 calcsize(n->nhere.next);
8189 calcsize(n->nnot.com);
8195 nodeckstrdup(char *s)
8197 char *rtn = funcstring;
8199 strcpy(funcstring, s);
8200 funcstring += strlen(s) + 1;
8204 static union node *copynode(union node *);
8206 static struct nodelist *
8207 copynodelist(struct nodelist *lp)
8209 struct nodelist *start;
8210 struct nodelist **lpp;
8215 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8216 (*lpp)->n = copynode(lp->n);
8218 lpp = &(*lpp)->next;
8225 copynode(union node *n)
8232 funcblock = (char *) funcblock + nodesize[n->type];
8236 new->ncmd.redirect = copynode(n->ncmd.redirect);
8237 new->ncmd.args = copynode(n->ncmd.args);
8238 new->ncmd.assign = copynode(n->ncmd.assign);
8241 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8242 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8247 new->nredir.redirect = copynode(n->nredir.redirect);
8248 new->nredir.n = copynode(n->nredir.n);
8255 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8256 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8259 new->nif.elsepart = copynode(n->nif.elsepart);
8260 new->nif.ifpart = copynode(n->nif.ifpart);
8261 new->nif.test = copynode(n->nif.test);
8264 new->nfor.var = nodeckstrdup(n->nfor.var);
8265 new->nfor.body = copynode(n->nfor.body);
8266 new->nfor.args = copynode(n->nfor.args);
8269 new->ncase.cases = copynode(n->ncase.cases);
8270 new->ncase.expr = copynode(n->ncase.expr);
8273 new->nclist.body = copynode(n->nclist.body);
8274 new->nclist.pattern = copynode(n->nclist.pattern);
8275 new->nclist.next = copynode(n->nclist.next);
8279 new->narg.backquote = copynodelist(n->narg.backquote);
8280 new->narg.text = nodeckstrdup(n->narg.text);
8281 new->narg.next = copynode(n->narg.next);
8284 #if ENABLE_ASH_BASH_COMPAT
8291 new->nfile.fname = copynode(n->nfile.fname);
8292 new->nfile.fd = n->nfile.fd;
8293 new->nfile.next = copynode(n->nfile.next);
8297 new->ndup.vname = copynode(n->ndup.vname);
8298 new->ndup.dupfd = n->ndup.dupfd;
8299 new->ndup.fd = n->ndup.fd;
8300 new->ndup.next = copynode(n->ndup.next);
8304 new->nhere.doc = copynode(n->nhere.doc);
8305 new->nhere.fd = n->nhere.fd;
8306 new->nhere.next = copynode(n->nhere.next);
8309 new->nnot.com = copynode(n->nnot.com);
8312 new->type = n->type;
8317 * Make a copy of a parse tree.
8319 static struct funcnode *
8320 copyfunc(union node *n)
8325 funcblocksize = offsetof(struct funcnode, n);
8328 blocksize = funcblocksize;
8329 f = ckmalloc(blocksize + funcstringsize);
8330 funcblock = (char *) f + offsetof(struct funcnode, n);
8331 funcstring = (char *) f + blocksize;
8338 * Define a shell function.
8341 defun(char *name, union node *func)
8343 struct cmdentry entry;
8346 entry.cmdtype = CMDFUNCTION;
8347 entry.u.func = copyfunc(func);
8348 addcmdentry(name, &entry);
8352 /* Reasons for skipping commands (see comment on breakcmd routine) */
8353 #define SKIPBREAK (1 << 0)
8354 #define SKIPCONT (1 << 1)
8355 #define SKIPFUNC (1 << 2)
8356 #define SKIPFILE (1 << 3)
8357 #define SKIPEVAL (1 << 4)
8358 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8359 static int skipcount; /* number of levels to skip */
8360 static int funcnest; /* depth of function calls */
8361 static int loopnest; /* current loop nesting level */
8363 /* Forward decl way out to parsing code - dotrap needs it */
8364 static int evalstring(char *s, int mask);
8366 /* Called to execute a trap.
8367 * Single callsite - at the end of evaltree().
8368 * If we return non-zero, evaltree raises EXEXIT exception.
8370 * Perhaps we should avoid entering new trap handlers
8371 * while we are executing a trap handler. [is it a TODO?]
8380 savestatus = exitstatus;
8384 TRACE(("dotrap entered\n"));
8385 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8391 /* non-trapped SIGINT is handled separately by raise_interrupt,
8392 * don't upset it by resetting gotsig[SIGINT-1] */
8393 if (sig == SIGINT && !t)
8396 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8400 evalstring(t, SKIPEVAL);
8401 exitstatus = savestatus;
8403 TRACE(("dotrap returns %d\n", evalskip));
8408 TRACE(("dotrap returns 0\n"));
8412 /* forward declarations - evaluation is fairly recursive business... */
8413 static int evalloop(union node *, int);
8414 static int evalfor(union node *, int);
8415 static int evalcase(union node *, int);
8416 static int evalsubshell(union node *, int);
8417 static void expredir(union node *);
8418 static int evalpipe(union node *, int);
8419 static int evalcommand(union node *, int);
8420 static int evalbltin(const struct builtincmd *, int, char **);
8421 static void prehash(union node *);
8424 * Evaluate a parse tree. The value is left in the global variable
8428 evaltree(union node *n, int flags)
8430 struct jmploc *volatile savehandler = exception_handler;
8431 struct jmploc jmploc;
8433 int (*evalfn)(union node *, int);
8437 SAVE_INT(int_level);
8440 TRACE(("evaltree(NULL) called\n"));
8443 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8445 exception_handler = &jmploc;
8447 int err = setjmp(jmploc.loc);
8449 /* if it was a signal, check for trap handlers */
8450 if (exception_type == EXSIG) {
8451 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8452 exception_type, err));
8455 /* continue on the way out */
8456 TRACE(("exception %d in evaltree, propagating err=%d\n",
8457 exception_type, err));
8458 exception_handler = savehandler;
8459 longjmp(exception_handler->loc, err);
8466 out1fmt("Node type = %d\n", n->type);
8471 status = !evaltree(n->nnot.com, EV_TESTED);
8474 expredir(n->nredir.redirect);
8475 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8477 status = evaltree(n->nredir.n, flags & EV_TESTED);
8479 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8482 evalfn = evalcommand;
8484 if (eflag && !(flags & EV_TESTED))
8495 evalfn = evalsubshell;
8498 evalfn = evalsubshell;
8511 #error NAND + 1 != NOR
8513 #if NOR + 1 != NSEMI
8514 #error NOR + 1 != NSEMI
8516 unsigned is_or = n->type - NAND;
8519 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8521 if (!status == is_or || evalskip)
8527 status = evalfn(n, flags);
8531 status = evaltree(n->nif.test, EV_TESTED);
8538 if (n->nif.elsepart) {
8539 n = n->nif.elsepart;
8545 defun(n->narg.text, n->narg.next);
8546 /* Not necessary. To test it:
8547 * "false; f() { qwerty; }; echo $?" should print 0.
8551 exitstatus = status;
8556 exception_handler = savehandler;
8559 /* Order of checks below is important:
8560 * signal handlers trigger before exit caused by "set -e".
8562 if (pending_sig && dotrap())
8564 if (checkexit & status)
8565 evalskip |= SKIPEVAL;
8567 if (flags & EV_EXIT) {
8569 raise_exception(EXEXIT);
8572 RESTORE_INT(int_level);
8573 TRACE(("leaving evaltree (no interrupts)\n"));
8578 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8581 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8584 evalloop(union node *n, int flags)
8594 i = evaltree(n->nbinary.ch1, EV_TESTED);
8597 if (evalskip == SKIPCONT && --skipcount <= 0) {
8601 if (evalskip == SKIPBREAK && --skipcount <= 0)
8605 if (n->type != NWHILE)
8609 status = evaltree(n->nbinary.ch2, flags);
8613 exitstatus = status;
8620 evalfor(union node *n, int flags)
8622 struct arglist arglist;
8625 struct stackmark smark;
8628 setstackmark(&smark);
8629 arglist.list = NULL;
8630 arglist.lastp = &arglist.list;
8631 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8632 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8637 *arglist.lastp = NULL;
8641 for (sp = arglist.list; sp; sp = sp->next) {
8642 setvar0(n->nfor.var, sp->text);
8643 status = evaltree(n->nfor.body, flags);
8645 if (evalskip == SKIPCONT && --skipcount <= 0) {
8649 if (evalskip == SKIPBREAK && --skipcount <= 0)
8656 popstackmark(&smark);
8662 evalcase(union node *n, int flags)
8666 struct arglist arglist;
8667 struct stackmark smark;
8670 setstackmark(&smark);
8671 arglist.list = NULL;
8672 arglist.lastp = &arglist.list;
8673 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8674 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8675 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8676 if (casematch(patp, arglist.list->text)) {
8677 /* Ensure body is non-empty as otherwise
8678 * EV_EXIT may prevent us from setting the
8681 if (evalskip == 0 && cp->nclist.body) {
8682 status = evaltree(cp->nclist.body, flags);
8689 popstackmark(&smark);
8695 * Kick off a subshell to evaluate a tree.
8698 evalsubshell(union node *n, int flags)
8701 int backgnd = (n->type == NBACKGND);
8704 expredir(n->nredir.redirect);
8705 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8708 jp = makejob(/*n,*/ 1);
8709 if (forkshell(jp, n, backgnd) == 0) {
8714 flags &= ~EV_TESTED;
8716 redirect(n->nredir.redirect, 0);
8717 evaltreenr(n->nredir.n, flags);
8722 status = waitforjob(jp);
8728 * Compute the names of the files in a redirection list.
8730 static void fixredir(union node *, const char *, int);
8732 expredir(union node *n)
8736 for (redir = n; redir; redir = redir->nfile.next) {
8740 fn.lastp = &fn.list;
8741 switch (redir->type) {
8745 #if ENABLE_ASH_BASH_COMPAT
8750 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8751 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8752 #if ENABLE_ASH_BASH_COMPAT
8756 // By the design of stack allocator, the loop of this kind:
8757 // while true; do while true; do break; done </dev/null; done
8758 // will look like a memory leak: ash plans to free expfname's
8759 // of "/dev/null" as soon as it finishes running the loop
8760 // (in this case, never).
8761 // This "fix" is wrong:
8762 if (redir->nfile.expfname)
8763 stunalloc(redir->nfile.expfname);
8764 // It results in corrupted state of stacked allocations.
8766 redir->nfile.expfname = fn.list->text;
8769 case NTOFD: /* >& */
8770 if (redir->ndup.vname) {
8771 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8772 if (fn.list == NULL)
8773 ash_msg_and_raise_error("redir error");
8774 #if ENABLE_ASH_BASH_COMPAT
8775 //FIXME: we used expandarg with different args!
8776 if (!isdigit_str9(fn.list->text)) {
8777 /* >&file, not >&fd */
8778 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8779 ash_msg_and_raise_error("redir error");
8781 goto store_expfname;
8784 fixredir(redir, fn.list->text, 1);
8792 * Evaluate a pipeline. All the processes in the pipeline are children
8793 * of the process creating the pipeline. (This differs from some versions
8794 * of the shell, which make the last process in a pipeline the parent
8798 evalpipe(union node *n, int flags)
8801 struct nodelist *lp;
8807 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8809 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8813 jp = makejob(/*n,*/ pipelen);
8815 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8819 if (pipe(pip) < 0) {
8821 ash_msg_and_raise_error("pipe call failed");
8824 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8837 evaltreenr(lp->n, flags);
8843 /* Don't want to trigger debugging */
8847 if (n->npipe.pipe_backgnd == 0) {
8848 status = waitforjob(jp);
8849 TRACE(("evalpipe: job done exit status %d\n", status));
8857 * Controls whether the shell is interactive or not.
8860 setinteractive(int on)
8862 static smallint is_interactive;
8864 if (++on == is_interactive)
8866 is_interactive = on;
8870 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8871 if (is_interactive > 1) {
8872 /* Looks like they want an interactive shell */
8873 static smallint did_banner;
8876 /* note: ash and hush share this string */
8877 out1fmt("\n\n%s %s\n"
8878 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
8881 "built-in shell (ash)"
8895 setinteractive(iflag);
8897 #if ENABLE_FEATURE_EDITING_VI
8899 line_input_state->flags |= VI_MODE;
8901 line_input_state->flags &= ~VI_MODE;
8903 viflag = 0; /* forcibly keep the option off */
8907 static struct localvar *localvars;
8910 * Called after a function returns.
8911 * Interrupts must be off.
8916 struct localvar *lvp;
8919 while ((lvp = localvars) != NULL) {
8920 localvars = lvp->next;
8922 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
8923 if (vp == NULL) { /* $- saved */
8924 memcpy(optlist, lvp->text, sizeof(optlist));
8925 free((char*)lvp->text);
8927 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8928 unsetvar(vp->var_text);
8931 vp->var_func(var_end(lvp->text));
8932 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8933 free((char*)vp->var_text);
8934 vp->flags = lvp->flags;
8935 vp->var_text = lvp->text;
8942 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8944 volatile struct shparam saveparam;
8945 struct localvar *volatile savelocalvars;
8946 struct jmploc *volatile savehandler;
8947 struct jmploc jmploc;
8950 saveparam = shellparam;
8951 savelocalvars = localvars;
8952 e = setjmp(jmploc.loc);
8957 savehandler = exception_handler;
8958 exception_handler = &jmploc;
8960 shellparam.malloced = 0;
8964 shellparam.nparam = argc - 1;
8965 shellparam.p = argv + 1;
8966 #if ENABLE_ASH_GETOPTS
8967 shellparam.optind = 1;
8968 shellparam.optoff = -1;
8970 evaltree(&func->n, flags & EV_TESTED);
8976 localvars = savelocalvars;
8977 freeparam(&shellparam);
8978 shellparam = saveparam;
8979 exception_handler = savehandler;
8981 evalskip &= ~SKIPFUNC;
8985 #if ENABLE_ASH_CMDCMD
8987 parse_command_args(char **argv, const char **path)
9000 if (c == '-' && !*cp) {
9008 *path = bb_default_path;
9011 /* run 'typecmd' for other options */
9022 * Make a variable a local variable. When a variable is made local, it's
9023 * value and flags are saved in a localvar structure. The saved values
9024 * will be restored when the shell function returns. We handle the name
9025 * "-" as a special case: it makes changes to "set +-options" local
9026 * (options will be restored on return from the function).
9031 struct localvar *lvp;
9034 char *eq = strchr(name, '=');
9037 /* Cater for duplicate "local". Examples:
9038 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9039 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9043 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9047 * it's a duplicate "local VAR" declaration, do nothing
9054 lvp = ckzalloc(sizeof(*lvp));
9055 if (LONE_DASH(name)) {
9057 p = ckmalloc(sizeof(optlist));
9058 lvp->text = memcpy(p, optlist, sizeof(optlist));
9061 vpp = hashvar(name);
9062 vp = *findvar(vpp, name);
9064 /* variable did not exist yet */
9066 setvareq(name, VSTRFIXED);
9068 setvar(name, NULL, VSTRFIXED);
9069 vp = *vpp; /* the new variable */
9070 lvp->flags = VUNSET;
9072 lvp->text = vp->var_text;
9073 lvp->flags = vp->flags;
9074 /* make sure neither "struct var" nor string gets freed
9075 * during (un)setting:
9077 vp->flags |= VSTRFIXED|VTEXTFIXED;
9081 /* "local VAR" unsets VAR: */
9082 setvar0(name, NULL);
9086 lvp->next = localvars;
9092 * The "local" command.
9094 static int FAST_FUNC
9095 localcmd(int argc UNUSED_PARAM, char **argv)
9100 ash_msg_and_raise_error("not in a function");
9103 while ((name = *argv++) != NULL) {
9109 static int FAST_FUNC
9110 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9115 static int FAST_FUNC
9116 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9121 static int FAST_FUNC
9122 execcmd(int argc UNUSED_PARAM, char **argv)
9125 iflag = 0; /* exit on error */
9128 /* We should set up signals for "exec CMD"
9129 * the same way as for "CMD" without "exec".
9130 * But optschanged->setinteractive->setsignal
9131 * still thought we are a root shell. Therefore, for example,
9132 * SIGQUIT is still set to IGN. Fix it:
9136 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9137 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9138 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9140 shellexec(argv + 1, pathval(), 0);
9147 * The return command.
9149 static int FAST_FUNC
9150 returncmd(int argc UNUSED_PARAM, char **argv)
9153 * If called outside a function, do what ksh does;
9154 * skip the rest of the file.
9156 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
9157 return argv[1] ? number(argv[1]) : exitstatus;
9160 /* Forward declarations for builtintab[] */
9161 static int breakcmd(int, char **) FAST_FUNC;
9162 static int dotcmd(int, char **) FAST_FUNC;
9163 static int evalcmd(int, char **) FAST_FUNC;
9164 static int exitcmd(int, char **) FAST_FUNC;
9165 static int exportcmd(int, char **) FAST_FUNC;
9166 #if ENABLE_ASH_GETOPTS
9167 static int getoptscmd(int, char **) FAST_FUNC;
9170 static int helpcmd(int, char **) FAST_FUNC;
9173 static int historycmd(int, char **) FAST_FUNC;
9175 #if ENABLE_SH_MATH_SUPPORT
9176 static int letcmd(int, char **) FAST_FUNC;
9178 static int readcmd(int, char **) FAST_FUNC;
9179 static int setcmd(int, char **) FAST_FUNC;
9180 static int shiftcmd(int, char **) FAST_FUNC;
9181 static int timescmd(int, char **) FAST_FUNC;
9182 static int trapcmd(int, char **) FAST_FUNC;
9183 static int umaskcmd(int, char **) FAST_FUNC;
9184 static int unsetcmd(int, char **) FAST_FUNC;
9185 static int ulimitcmd(int, char **) FAST_FUNC;
9187 #define BUILTIN_NOSPEC "0"
9188 #define BUILTIN_SPECIAL "1"
9189 #define BUILTIN_REGULAR "2"
9190 #define BUILTIN_SPEC_REG "3"
9191 #define BUILTIN_ASSIGN "4"
9192 #define BUILTIN_SPEC_ASSG "5"
9193 #define BUILTIN_REG_ASSG "6"
9194 #define BUILTIN_SPEC_REG_ASSG "7"
9196 /* Stubs for calling non-FAST_FUNC's */
9197 #if ENABLE_ASH_BUILTIN_ECHO
9198 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9200 #if ENABLE_ASH_BUILTIN_PRINTF
9201 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9203 #if ENABLE_ASH_BUILTIN_TEST
9204 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9207 /* Keep these in proper order since it is searched via bsearch() */
9208 static const struct builtincmd builtintab[] = {
9209 { BUILTIN_SPEC_REG "." , dotcmd },
9210 { BUILTIN_SPEC_REG ":" , truecmd },
9211 #if ENABLE_ASH_BUILTIN_TEST
9212 { BUILTIN_REGULAR "[" , testcmd },
9213 #if ENABLE_ASH_BASH_COMPAT
9214 { BUILTIN_REGULAR "[[" , testcmd },
9217 #if ENABLE_ASH_ALIAS
9218 { BUILTIN_REG_ASSG "alias" , aliascmd },
9221 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9223 { BUILTIN_SPEC_REG "break" , breakcmd },
9224 { BUILTIN_REGULAR "cd" , cdcmd },
9225 { BUILTIN_NOSPEC "chdir" , cdcmd },
9226 #if ENABLE_ASH_CMDCMD
9227 { BUILTIN_REGULAR "command" , commandcmd },
9229 { BUILTIN_SPEC_REG "continue", breakcmd },
9230 #if ENABLE_ASH_BUILTIN_ECHO
9231 { BUILTIN_REGULAR "echo" , echocmd },
9233 { BUILTIN_SPEC_REG "eval" , evalcmd },
9234 { BUILTIN_SPEC_REG "exec" , execcmd },
9235 { BUILTIN_SPEC_REG "exit" , exitcmd },
9236 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9237 { BUILTIN_REGULAR "false" , falsecmd },
9239 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9241 #if ENABLE_ASH_GETOPTS
9242 { BUILTIN_REGULAR "getopts" , getoptscmd },
9244 { BUILTIN_NOSPEC "hash" , hashcmd },
9246 { BUILTIN_NOSPEC "help" , helpcmd },
9249 { BUILTIN_NOSPEC "history" , historycmd },
9252 { BUILTIN_REGULAR "jobs" , jobscmd },
9253 { BUILTIN_REGULAR "kill" , killcmd },
9255 #if ENABLE_SH_MATH_SUPPORT
9256 { BUILTIN_NOSPEC "let" , letcmd },
9258 { BUILTIN_ASSIGN "local" , localcmd },
9259 #if ENABLE_ASH_BUILTIN_PRINTF
9260 { BUILTIN_REGULAR "printf" , printfcmd },
9262 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9263 { BUILTIN_REGULAR "read" , readcmd },
9264 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9265 { BUILTIN_SPEC_REG "return" , returncmd },
9266 { BUILTIN_SPEC_REG "set" , setcmd },
9267 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9268 #if ENABLE_ASH_BASH_COMPAT
9269 { BUILTIN_SPEC_REG "source" , dotcmd },
9271 #if ENABLE_ASH_BUILTIN_TEST
9272 { BUILTIN_REGULAR "test" , testcmd },
9274 { BUILTIN_SPEC_REG "times" , timescmd },
9275 { BUILTIN_SPEC_REG "trap" , trapcmd },
9276 { BUILTIN_REGULAR "true" , truecmd },
9277 { BUILTIN_NOSPEC "type" , typecmd },
9278 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9279 { BUILTIN_REGULAR "umask" , umaskcmd },
9280 #if ENABLE_ASH_ALIAS
9281 { BUILTIN_REGULAR "unalias" , unaliascmd },
9283 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9284 { BUILTIN_REGULAR "wait" , waitcmd },
9287 /* Should match the above table! */
9288 #define COMMANDCMD (builtintab + \
9290 /* [ */ 1 * ENABLE_ASH_BUILTIN_TEST + \
9291 /* [[ */ 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9292 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9293 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9294 /* break cd cddir */ 3)
9295 #define EVALCMD (COMMANDCMD + \
9296 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9297 /* continue */ 1 + \
9298 /* echo */ 1 * ENABLE_ASH_BUILTIN_ECHO + \
9300 #define EXECCMD (EVALCMD + \
9304 * Search the table of builtin commands.
9306 static struct builtincmd *
9307 find_builtin(const char *name)
9309 struct builtincmd *bp;
9312 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9319 * Execute a simple command.
9322 isassignment(const char *p)
9324 const char *q = endofname(p);
9329 static int FAST_FUNC
9330 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9332 /* Preserve exitstatus of a previous possible redirection
9333 * as POSIX mandates */
9334 return back_exitstatus;
9337 evalcommand(union node *cmd, int flags)
9339 static const struct builtincmd null_bltin = {
9340 "\0\0", bltincmd /* why three NULs? */
9342 struct stackmark smark;
9344 struct arglist arglist;
9345 struct arglist varlist;
9348 const struct strlist *sp;
9349 struct cmdentry cmdentry;
9356 struct builtincmd *bcmd;
9357 smallint cmd_is_exec;
9358 smallint pseudovarflag = 0;
9360 /* First expand the arguments. */
9361 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9362 setstackmark(&smark);
9363 back_exitstatus = 0;
9365 cmdentry.cmdtype = CMDBUILTIN;
9366 cmdentry.u.cmd = &null_bltin;
9367 varlist.lastp = &varlist.list;
9368 *varlist.lastp = NULL;
9369 arglist.lastp = &arglist.list;
9370 *arglist.lastp = NULL;
9373 if (cmd->ncmd.args) {
9374 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9375 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9378 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9379 struct strlist **spp;
9381 spp = arglist.lastp;
9382 if (pseudovarflag && isassignment(argp->narg.text))
9383 expandarg(argp, &arglist, EXP_VARTILDE);
9385 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9387 for (sp = *spp; sp; sp = sp->next)
9391 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9392 for (sp = arglist.list; sp; sp = sp->next) {
9393 TRACE(("evalcommand arg: %s\n", sp->text));
9394 *nargv++ = sp->text;
9399 if (iflag && funcnest == 0 && argc > 0)
9400 lastarg = nargv[-1];
9403 expredir(cmd->ncmd.redirect);
9404 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9406 path = vpath.var_text;
9407 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9408 struct strlist **spp;
9411 spp = varlist.lastp;
9412 expandarg(argp, &varlist, EXP_VARTILDE);
9415 * Modify the command lookup path, if a PATH= assignment
9419 if (varcmp(p, path) == 0)
9423 /* Print the command if xflag is set. */
9426 const char *p = " %s" + 1;
9428 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9430 for (n = 0; n < 2; n++) {
9432 fdprintf(preverrout_fd, p, sp->text);
9438 safe_write(preverrout_fd, "\n", 1);
9444 /* Now locate the command. */
9446 int cmd_flag = DO_ERR;
9447 #if ENABLE_ASH_CMDCMD
9448 const char *oldpath = path + 5;
9452 find_command(argv[0], &cmdentry, cmd_flag, path);
9453 if (cmdentry.cmdtype == CMDUNKNOWN) {
9454 flush_stdout_stderr();
9459 /* implement bltin and command here */
9460 if (cmdentry.cmdtype != CMDBUILTIN)
9463 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9464 if (cmdentry.u.cmd == EXECCMD)
9466 #if ENABLE_ASH_CMDCMD
9467 if (cmdentry.u.cmd == COMMANDCMD) {
9469 nargv = parse_command_args(argv, &path);
9472 argc -= nargv - argv;
9474 cmd_flag |= DO_NOFUNC;
9482 /* We have a redirection error. */
9484 raise_exception(EXERROR);
9486 exitstatus = status;
9490 /* Execute the command. */
9491 switch (cmdentry.cmdtype) {
9494 #if ENABLE_FEATURE_SH_NOFORK
9495 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9496 * around run_nofork_applet() call.
9497 * (2) Should this check also be done in forkshell()?
9498 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9500 /* find_command() encodes applet_no as (-2 - applet_no) */
9501 int applet_no = (- cmdentry.u.index - 2);
9502 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9503 listsetvar(varlist.list, VEXPORT|VSTACK);
9504 /* run <applet>_main() */
9505 exitstatus = run_nofork_applet(applet_no, argv);
9509 /* Can we avoid forking off? For example, very last command
9510 * in a script or a subshell does not need forking,
9511 * we can just exec it.
9513 if (!(flags & EV_EXIT) || may_have_traps) {
9514 /* No, forking off a child is necessary */
9516 jp = makejob(/*cmd,*/ 1);
9517 if (forkshell(jp, cmd, FORK_FG) != 0) {
9519 status = waitforjob(jp);
9521 TRACE(("forked child exited with %d\n", status));
9526 /* fall through to exec'ing external program */
9528 listsetvar(varlist.list, VEXPORT|VSTACK);
9529 shellexec(argv, path, cmdentry.u.index);
9533 cmdenviron = varlist.list;
9535 struct strlist *list = cmdenviron;
9537 if (spclbltin > 0 || argc == 0) {
9539 if (cmd_is_exec && argc > 1)
9542 listsetvar(list, i);
9544 /* Tight loop with builtins only:
9545 * "while kill -0 $child; do true; done"
9546 * will never exit even if $child died, unless we do this
9547 * to reap the zombie and make kill detect that it's gone: */
9548 dowait(DOWAIT_NONBLOCK, NULL);
9550 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9552 int i = exception_type;
9553 if (i == EXEXIT || i == EXEXEC)
9557 exit_status = 128 + SIGINT;
9559 exit_status = 128 + pending_sig;
9560 exitstatus = exit_status;
9561 if (i == EXINT || spclbltin > 0) {
9563 longjmp(exception_handler->loc, 1);
9570 listsetvar(varlist.list, 0);
9571 /* See above for the rationale */
9572 dowait(DOWAIT_NONBLOCK, NULL);
9573 if (evalfun(cmdentry.u.func, argc, argv, flags))
9576 status = exitstatus;
9581 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9583 /* dsl: I think this is intended to be used to support
9584 * '_' in 'vi' command mode during line editing...
9585 * However I implemented that within libedit itself.
9587 setvar0("_", lastarg);
9589 popstackmark(&smark);
9595 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9597 char *volatile savecmdname;
9598 struct jmploc *volatile savehandler;
9599 struct jmploc jmploc;
9602 savecmdname = commandname;
9603 i = setjmp(jmploc.loc);
9606 savehandler = exception_handler;
9607 exception_handler = &jmploc;
9608 commandname = argv[0];
9610 optptr = NULL; /* initialize nextopt */
9611 exitstatus = (*cmd->builtin)(argc, argv);
9612 flush_stdout_stderr();
9614 exitstatus |= ferror(stdout);
9616 commandname = savecmdname;
9617 exception_handler = savehandler;
9623 goodname(const char *p)
9625 return endofname(p)[0] == '\0';
9630 * Search for a command. This is called before we fork so that the
9631 * location of the command will be available in the parent as well as
9632 * the child. The check for "goodname" is an overly conservative
9633 * check that the name will not be subject to expansion.
9636 prehash(union node *n)
9638 struct cmdentry entry;
9640 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9641 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9645 /* ============ Builtin commands
9647 * Builtin commands whose functions are closely tied to evaluation
9648 * are implemented here.
9652 * Handle break and continue commands. Break, continue, and return are
9653 * all handled by setting the evalskip flag. The evaluation routines
9654 * above all check this flag, and if it is set they start skipping
9655 * commands rather than executing them. The variable skipcount is
9656 * the number of loops to break/continue, or the number of function
9657 * levels to return. (The latter is always 1.) It should probably
9658 * be an error to break out of more loops than exist, but it isn't
9659 * in the standard shell so we don't make it one here.
9661 static int FAST_FUNC
9662 breakcmd(int argc UNUSED_PARAM, char **argv)
9664 int n = argv[1] ? number(argv[1]) : 1;
9667 ash_msg_and_raise_error(msg_illnum, argv[1]);
9671 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9678 /* ============ input.c
9680 * This implements the input routines used by the parser.
9684 INPUT_PUSH_FILE = 1,
9685 INPUT_NOFILE_OK = 2,
9688 static smallint checkkwd;
9689 /* values of checkkwd variable */
9690 #define CHKALIAS 0x1
9695 * Push a string back onto the input at this current parsefile level.
9696 * We handle aliases this way.
9698 #if !ENABLE_ASH_ALIAS
9699 #define pushstring(s, ap) pushstring(s)
9702 pushstring(char *s, struct alias *ap)
9709 if (g_parsefile->strpush) {
9710 sp = ckzalloc(sizeof(*sp));
9711 sp->prev = g_parsefile->strpush;
9713 sp = &(g_parsefile->basestrpush);
9715 g_parsefile->strpush = sp;
9716 sp->prev_string = g_parsefile->next_to_pgetc;
9717 sp->prev_left_in_line = g_parsefile->left_in_line;
9718 #if ENABLE_ASH_ALIAS
9721 ap->flag |= ALIASINUSE;
9725 g_parsefile->next_to_pgetc = s;
9726 g_parsefile->left_in_line = len;
9733 struct strpush *sp = g_parsefile->strpush;
9736 #if ENABLE_ASH_ALIAS
9738 if (g_parsefile->next_to_pgetc[-1] == ' '
9739 || g_parsefile->next_to_pgetc[-1] == '\t'
9741 checkkwd |= CHKALIAS;
9743 if (sp->string != sp->ap->val) {
9746 sp->ap->flag &= ~ALIASINUSE;
9747 if (sp->ap->flag & ALIASDEAD) {
9748 unalias(sp->ap->name);
9752 g_parsefile->next_to_pgetc = sp->prev_string;
9753 g_parsefile->left_in_line = sp->prev_left_in_line;
9754 g_parsefile->strpush = sp->prev;
9755 if (sp != &(g_parsefile->basestrpush))
9760 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9761 //it peeks whether it is &>, and then pushes back both chars.
9762 //This function needs to save last *next_to_pgetc to buf[0]
9763 //to make two pungetc() reliable. Currently,
9764 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9769 char *buf = g_parsefile->buf;
9771 g_parsefile->next_to_pgetc = buf;
9772 #if ENABLE_FEATURE_EDITING
9774 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9775 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9778 # if ENABLE_ASH_IDLE_TIMEOUT
9780 const char *tmout_var = lookupvar("TMOUT");
9782 timeout = atoi(tmout_var) * 1000;
9788 # if ENABLE_FEATURE_TAB_COMPLETION
9789 line_input_state->path_lookup = pathval();
9791 reinit_unicode_for_ash();
9792 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9794 /* Ctrl+C pressed */
9805 /* Ctrl+D pressed */
9808 # if ENABLE_ASH_IDLE_TIMEOUT
9809 else if (errno == EAGAIN && timeout > 0) {
9810 puts("\007timed out waiting for input: auto-logout");
9817 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9820 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9822 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9823 int flags = fcntl(0, F_GETFL);
9824 if (flags >= 0 && (flags & O_NONBLOCK)) {
9825 flags &= ~O_NONBLOCK;
9826 if (fcntl(0, F_SETFL, flags) >= 0) {
9827 out2str("sh: turning off NDELAY mode\n");
9838 * Refill the input buffer and return the next input character:
9840 * 1) If a string was pushed back on the input, pop it;
9841 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9842 * or we are reading from a string so we can't refill the buffer,
9844 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9845 * 4) Process input up to the next newline, deleting nul characters.
9847 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9848 #define pgetc_debug(...) ((void)0)
9855 while (g_parsefile->strpush) {
9856 #if ENABLE_ASH_ALIAS
9857 if (g_parsefile->left_in_line == -1
9858 && g_parsefile->strpush->ap
9859 && g_parsefile->next_to_pgetc[-1] != ' '
9860 && g_parsefile->next_to_pgetc[-1] != '\t'
9862 pgetc_debug("preadbuffer PEOA");
9867 /* try "pgetc" now: */
9868 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9869 g_parsefile->left_in_line,
9870 g_parsefile->next_to_pgetc,
9871 g_parsefile->next_to_pgetc);
9872 if (--g_parsefile->left_in_line >= 0)
9873 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9875 /* on both branches above g_parsefile->left_in_line < 0.
9876 * "pgetc" needs refilling.
9879 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9880 * pungetc() may increment it a few times.
9881 * Assuming it won't increment it to less than -90.
9883 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9884 pgetc_debug("preadbuffer PEOF1");
9885 /* even in failure keep left_in_line and next_to_pgetc
9886 * in lock step, for correct multi-layer pungetc.
9887 * left_in_line was decremented before preadbuffer(),
9888 * must inc next_to_pgetc: */
9889 g_parsefile->next_to_pgetc++;
9893 more = g_parsefile->left_in_buffer;
9895 flush_stdout_stderr();
9899 /* don't try reading again */
9900 g_parsefile->left_in_line = -99;
9901 pgetc_debug("preadbuffer PEOF2");
9902 g_parsefile->next_to_pgetc++;
9907 /* Find out where's the end of line.
9908 * Set g_parsefile->left_in_line
9909 * and g_parsefile->left_in_buffer acordingly.
9910 * NUL chars are deleted.
9912 q = g_parsefile->next_to_pgetc;
9920 memmove(q, q + 1, more);
9924 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9930 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9931 if (g_parsefile->left_in_line < 0)
9936 g_parsefile->left_in_buffer = more;
9941 out2str(g_parsefile->next_to_pgetc);
9945 pgetc_debug("preadbuffer at %d:%p'%s'",
9946 g_parsefile->left_in_line,
9947 g_parsefile->next_to_pgetc,
9948 g_parsefile->next_to_pgetc);
9949 return (unsigned char)*g_parsefile->next_to_pgetc++;
9952 #define pgetc_as_macro() \
9953 (--g_parsefile->left_in_line >= 0 \
9954 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9961 pgetc_debug("pgetc_fast at %d:%p'%s'",
9962 g_parsefile->left_in_line,
9963 g_parsefile->next_to_pgetc,
9964 g_parsefile->next_to_pgetc);
9965 return pgetc_as_macro();
9968 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9969 # define pgetc_fast() pgetc()
9971 # define pgetc_fast() pgetc_as_macro()
9974 #if ENABLE_ASH_ALIAS
9976 pgetc_without_PEOA(void)
9980 pgetc_debug("pgetc_fast at %d:%p'%s'",
9981 g_parsefile->left_in_line,
9982 g_parsefile->next_to_pgetc,
9983 g_parsefile->next_to_pgetc);
9985 } while (c == PEOA);
9989 # define pgetc_without_PEOA() pgetc()
9993 * Read a line from the script.
9996 pfgets(char *line, int len)
10002 while (--nleft > 0) {
10003 c = pgetc_without_PEOA();
10018 * Undo the last call to pgetc. Only one character may be pushed back.
10019 * PEOF may be pushed back.
10024 g_parsefile->left_in_line++;
10025 g_parsefile->next_to_pgetc--;
10026 pgetc_debug("pushed back to %d:%p'%s'",
10027 g_parsefile->left_in_line,
10028 g_parsefile->next_to_pgetc,
10029 g_parsefile->next_to_pgetc);
10033 * To handle the "." command, a stack of input files is used. Pushfile
10034 * adds a new entry to the stack and popfile restores the previous level.
10039 struct parsefile *pf;
10041 pf = ckzalloc(sizeof(*pf));
10042 pf->prev = g_parsefile;
10044 /*pf->strpush = NULL; - ckzalloc did it */
10045 /*pf->basestrpush.prev = NULL;*/
10052 struct parsefile *pf = g_parsefile;
10055 if (pf->pf_fd >= 0)
10058 while (pf->strpush)
10060 g_parsefile = pf->prev;
10066 * Return to top level.
10071 while (g_parsefile != &basepf)
10076 * Close the file(s) that the shell is reading commands from. Called
10077 * after a fork is done.
10083 if (g_parsefile->pf_fd > 0) {
10084 close(g_parsefile->pf_fd);
10085 g_parsefile->pf_fd = 0;
10090 * Like setinputfile, but takes an open file descriptor. Call this with
10094 setinputfd(int fd, int push)
10096 close_on_exec_on(fd);
10099 g_parsefile->buf = NULL;
10101 g_parsefile->pf_fd = fd;
10102 if (g_parsefile->buf == NULL)
10103 g_parsefile->buf = ckmalloc(IBUFSIZ);
10104 g_parsefile->left_in_buffer = 0;
10105 g_parsefile->left_in_line = 0;
10106 g_parsefile->linno = 1;
10110 * Set the input to take input from a file. If push is set, push the
10111 * old input onto the stack first.
10114 setinputfile(const char *fname, int flags)
10120 fd = open(fname, O_RDONLY);
10122 if (flags & INPUT_NOFILE_OK)
10124 ash_msg_and_raise_error("can't open '%s'", fname);
10127 fd2 = copyfd(fd, 10);
10130 ash_msg_and_raise_error("out of file descriptors");
10133 setinputfd(fd, flags & INPUT_PUSH_FILE);
10140 * Like setinputfile, but takes input from a string.
10143 setinputstring(char *string)
10147 g_parsefile->next_to_pgetc = string;
10148 g_parsefile->left_in_line = strlen(string);
10149 g_parsefile->buf = NULL;
10150 g_parsefile->linno = 1;
10155 /* ============ mail.c
10157 * Routines to check for mail.
10160 #if ENABLE_ASH_MAIL
10162 /* Hash of mtimes of mailboxes */
10163 static unsigned mailtime_hash;
10164 /* Set if MAIL or MAILPATH is changed. */
10165 static smallint mail_var_path_changed;
10168 * Print appropriate message(s) if mail has arrived.
10169 * If mail_var_path_changed is set,
10170 * then the value of MAIL has mail_var_path_changed,
10171 * so we just update the values.
10180 struct stackmark smark;
10183 setstackmark(&smark);
10184 mpath = mpathset() ? mpathval() : mailval();
10187 p = path_advance(&mpath, nullstr);
10192 for (q = p; *q; q++)
10198 q[-1] = '\0'; /* delete trailing '/' */
10199 if (stat(p, &statb) < 0) {
10202 /* Very simplistic "hash": just a sum of all mtimes */
10203 new_hash += (unsigned)statb.st_mtime;
10205 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10206 if (mailtime_hash != 0)
10207 out2str("you have mail\n");
10208 mailtime_hash = new_hash;
10210 mail_var_path_changed = 0;
10211 popstackmark(&smark);
10214 static void FAST_FUNC
10215 changemail(const char *val UNUSED_PARAM)
10217 mail_var_path_changed = 1;
10220 #endif /* ASH_MAIL */
10223 /* ============ ??? */
10226 * Set the shell parameters.
10229 setparam(char **argv)
10235 for (nparam = 0; argv[nparam]; nparam++)
10237 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10239 *ap++ = ckstrdup(*argv++);
10242 freeparam(&shellparam);
10243 shellparam.malloced = 1;
10244 shellparam.nparam = nparam;
10245 shellparam.p = newparam;
10246 #if ENABLE_ASH_GETOPTS
10247 shellparam.optind = 1;
10248 shellparam.optoff = -1;
10253 * Process shell options. The global variable argptr contains a pointer
10254 * to the argument list; we advance it past the options.
10256 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10257 * For a non-interactive shell, an error condition encountered
10258 * by a special built-in ... shall cause the shell to write a diagnostic message
10259 * to standard error and exit as shown in the following table:
10260 * Error Special Built-In
10262 * Utility syntax error (option or operand error) Shall exit
10264 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10265 * we see that bash does not do that (set "finishes" with error code 1 instead,
10266 * and shell continues), and people rely on this behavior!
10268 * set -o barfoo 2>/dev/null
10271 * Oh well. Let's mimic that.
10274 plus_minus_o(char *name, int val)
10279 for (i = 0; i < NOPTS; i++) {
10280 if (strcmp(name, optnames(i)) == 0) {
10285 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10288 for (i = 0; i < NOPTS; i++) {
10290 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10292 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10298 setoption(int flag, int val)
10302 for (i = 0; i < NOPTS; i++) {
10303 if (optletters(i) == flag) {
10308 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10312 options(int cmdline)
10320 while ((p = *argptr) != NULL) {
10322 if (c != '-' && c != '+')
10325 val = 0; /* val = 0 if c == '+' */
10328 if (p[0] == '\0' || LONE_DASH(p)) {
10330 /* "-" means turn off -x and -v */
10333 /* "--" means reset params */
10334 else if (*argptr == NULL)
10337 break; /* "-" or "--" terminates options */
10340 /* first char was + or - */
10341 while ((c = *p++) != '\0') {
10342 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10343 if (c == 'c' && cmdline) {
10344 minusc = p; /* command is after shell args */
10345 } else if (c == 'o') {
10346 if (plus_minus_o(*argptr, val)) {
10347 /* it already printed err message */
10348 return 1; /* error */
10352 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10354 /* bash does not accept +-login, we also won't */
10355 } else if (cmdline && val && (c == '-')) { /* long options */
10356 if (strcmp(p, "login") == 0)
10368 * The shift builtin command.
10370 static int FAST_FUNC
10371 shiftcmd(int argc UNUSED_PARAM, char **argv)
10378 n = number(argv[1]);
10379 if (n > shellparam.nparam)
10380 n = 0; /* bash compat, was = shellparam.nparam; */
10382 shellparam.nparam -= n;
10383 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10384 if (shellparam.malloced)
10387 ap2 = shellparam.p;
10388 while ((*ap2++ = *ap1++) != NULL)
10390 #if ENABLE_ASH_GETOPTS
10391 shellparam.optind = 1;
10392 shellparam.optoff = -1;
10399 * POSIX requires that 'set' (but not export or readonly) output the
10400 * variables in lexicographic order - by the locale's collating order (sigh).
10401 * Maybe we could keep them in an ordered balanced binary tree
10402 * instead of hashed lists.
10403 * For now just roll 'em through qsort for printing...
10406 showvars(const char *sep_prefix, int on, int off)
10409 char **ep, **epend;
10411 ep = listvars(on, off, &epend);
10412 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10414 sep = *sep_prefix ? " " : sep_prefix;
10416 for (; ep < epend; ep++) {
10420 p = strchrnul(*ep, '=');
10423 q = single_quote(++p);
10424 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10430 * The set command builtin.
10432 static int FAST_FUNC
10433 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10438 return showvars(nullstr, 0, VUNSET);
10441 retval = options(/*cmdline:*/ 0);
10442 if (retval == 0) { /* if no parse error... */
10444 if (*argptr != NULL) {
10452 #if ENABLE_ASH_RANDOM_SUPPORT
10453 static void FAST_FUNC
10454 change_random(const char *value)
10458 if (value == NULL) {
10459 /* "get", generate */
10460 t = next_random(&random_gen);
10461 /* set without recursion */
10462 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10463 vrandom.flags &= ~VNOFUNC;
10466 t = strtoul(value, NULL, 10);
10467 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10472 #if ENABLE_ASH_GETOPTS
10474 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10485 if (*param_optind < 1)
10487 optnext = optfirst + *param_optind - 1;
10489 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10492 p = optnext[-1] + *optoff;
10493 if (p == NULL || *p == '\0') {
10494 /* Current word is done, advance */
10496 if (p == NULL || *p != '-' || *++p == '\0') {
10503 if (LONE_DASH(p)) /* check for "--" */
10508 for (q = optstr; *q != c;) {
10510 if (optstr[0] == ':') {
10512 /*sbuf[1] = '\0'; - already is */
10513 err |= setvarsafe("OPTARG", sbuf, 0);
10515 fprintf(stderr, "Illegal option -%c\n", c);
10516 unsetvar("OPTARG");
10526 if (*p == '\0' && (p = *optnext) == NULL) {
10527 if (optstr[0] == ':') {
10529 /*sbuf[1] = '\0'; - already is */
10530 err |= setvarsafe("OPTARG", sbuf, 0);
10533 fprintf(stderr, "No arg for -%c option\n", c);
10534 unsetvar("OPTARG");
10542 err |= setvarsafe("OPTARG", p, 0);
10545 err |= setvarsafe("OPTARG", nullstr, 0);
10547 *optoff = p ? p - *(optnext - 1) : -1;
10548 *param_optind = optnext - optfirst + 1;
10549 err |= setvarsafe("OPTIND", itoa(*param_optind), VNOFUNC);
10551 /*sbuf[1] = '\0'; - already is */
10552 err |= setvarsafe(optvar, sbuf, 0);
10556 flush_stdout_stderr();
10557 raise_exception(EXERROR);
10563 * The getopts builtin. Shellparam.optnext points to the next argument
10564 * to be processed. Shellparam.optptr points to the next character to
10565 * be processed in the current argument. If shellparam.optnext is NULL,
10566 * then it's the first time getopts has been called.
10568 static int FAST_FUNC
10569 getoptscmd(int argc, char **argv)
10574 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10576 optbase = shellparam.p;
10577 if (shellparam.optind > shellparam.nparam + 1) {
10578 shellparam.optind = 1;
10579 shellparam.optoff = -1;
10582 optbase = &argv[3];
10583 if (shellparam.optind > argc - 2) {
10584 shellparam.optind = 1;
10585 shellparam.optoff = -1;
10589 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10590 &shellparam.optoff);
10592 #endif /* ASH_GETOPTS */
10595 /* ============ Shell parser */
10598 struct heredoc *next; /* next here document in list */
10599 union node *here; /* redirection node */
10600 char *eofmark; /* string indicating end of input */
10601 smallint striptabs; /* if set, strip leading tabs */
10604 static smallint tokpushback; /* last token pushed back */
10605 static smallint quoteflag; /* set if (part of) last token was quoted */
10606 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10607 static struct heredoc *heredoclist; /* list of here documents to read */
10608 static char *wordtext; /* text of last word returned by readtoken */
10609 static struct nodelist *backquotelist;
10610 static union node *redirnode;
10611 static struct heredoc *heredoc;
10613 static const char *
10614 tokname(char *buf, int tok)
10617 return tokname_array[tok] + 1;
10618 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10622 /* raise_error_unexpected_syntax:
10623 * Called when an unexpected token is read during the parse. The argument
10624 * is the token that is expected, or -1 if more than one type of token can
10625 * occur at this point.
10627 static void raise_error_unexpected_syntax(int) NORETURN;
10629 raise_error_unexpected_syntax(int token)
10635 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10637 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10638 raise_error_syntax(msg);
10642 #define EOFMARKLEN 79
10644 /* parsing is heavily cross-recursive, need these forward decls */
10645 static union node *andor(void);
10646 static union node *pipeline(void);
10647 static union node *parse_command(void);
10648 static void parseheredoc(void);
10649 static int peektoken(void);
10650 static int readtoken(void);
10652 static union node *
10655 union node *n1, *n2, *n3;
10660 switch (peektoken()) {
10668 if (!n1 && (nlflag & 1))
10674 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10675 if (nlflag == 2 && tokname_array[peektoken()][0])
10681 if (tok == TBACKGND) {
10682 if (n2->type == NPIPE) {
10683 n2->npipe.pipe_backgnd = 1;
10685 if (n2->type != NREDIR) {
10686 n3 = stzalloc(sizeof(struct nredir));
10688 /*n3->nredir.redirect = NULL; - stzalloc did it */
10691 n2->type = NBACKGND;
10697 n3 = stzalloc(sizeof(struct nbinary));
10699 n3->nbinary.ch1 = n1;
10700 n3->nbinary.ch2 = n2;
10713 raise_error_unexpected_syntax(-1);
10720 static union node *
10723 union node *n1, *n2, *n3;
10731 } else if (t == TOR) {
10737 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10739 n3 = stzalloc(sizeof(struct nbinary));
10741 n3->nbinary.ch1 = n1;
10742 n3->nbinary.ch2 = n2;
10747 static union node *
10750 union node *n1, *n2, *pipenode;
10751 struct nodelist *lp, *prev;
10755 TRACE(("pipeline: entered\n"));
10756 if (readtoken() == TNOT) {
10758 checkkwd = CHKKWD | CHKALIAS;
10761 n1 = parse_command();
10762 if (readtoken() == TPIPE) {
10763 pipenode = stzalloc(sizeof(struct npipe));
10764 pipenode->type = NPIPE;
10765 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10766 lp = stzalloc(sizeof(struct nodelist));
10767 pipenode->npipe.cmdlist = lp;
10771 lp = stzalloc(sizeof(struct nodelist));
10772 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10773 lp->n = parse_command();
10775 } while (readtoken() == TPIPE);
10781 n2 = stzalloc(sizeof(struct nnot));
10789 static union node *
10794 n = stzalloc(sizeof(struct narg));
10796 /*n->narg.next = NULL; - stzalloc did it */
10797 n->narg.text = wordtext;
10798 n->narg.backquote = backquotelist;
10803 fixredir(union node *n, const char *text, int err)
10807 TRACE(("Fix redir %s %d\n", text, err));
10809 n->ndup.vname = NULL;
10811 fd = bb_strtou(text, NULL, 10);
10812 if (!errno && fd >= 0)
10813 n->ndup.dupfd = fd;
10814 else if (LONE_DASH(text))
10815 n->ndup.dupfd = -1;
10818 raise_error_syntax("bad fd number");
10819 n->ndup.vname = makename();
10824 * Returns true if the text contains nothing to expand (no dollar signs
10828 noexpand(const char *text)
10832 while ((c = *text++) != '\0') {
10833 if (c == CTLQUOTEMARK)
10837 else if (SIT(c, BASESYNTAX) == CCTL)
10846 union node *n = redirnode;
10848 if (readtoken() != TWORD)
10849 raise_error_unexpected_syntax(-1);
10850 if (n->type == NHERE) {
10851 struct heredoc *here = heredoc;
10855 if (quoteflag == 0)
10857 TRACE(("Here document %d\n", n->type));
10858 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10859 raise_error_syntax("illegal eof marker for << redirection");
10860 rmescapes(wordtext, 0);
10861 here->eofmark = wordtext;
10863 if (heredoclist == NULL)
10864 heredoclist = here;
10866 for (p = heredoclist; p->next; p = p->next)
10870 } else if (n->type == NTOFD || n->type == NFROMFD) {
10871 fixredir(n, wordtext, 0);
10873 n->nfile.fname = makename();
10877 static union node *
10880 union node *args, **app;
10881 union node *n = NULL;
10882 union node *vars, **vpp;
10883 union node **rpp, *redir;
10885 #if ENABLE_ASH_BASH_COMPAT
10886 smallint double_brackets_flag = 0;
10887 smallint function_flag = 0;
10897 savecheckkwd = CHKALIAS;
10900 checkkwd = savecheckkwd;
10903 #if ENABLE_ASH_BASH_COMPAT
10905 if (peektoken() != TWORD)
10906 raise_error_unexpected_syntax(TWORD);
10909 case TAND: /* "&&" */
10910 case TOR: /* "||" */
10911 if (!double_brackets_flag) {
10915 wordtext = (char *) (t == TAND ? "-a" : "-o");
10918 n = stzalloc(sizeof(struct narg));
10920 /*n->narg.next = NULL; - stzalloc did it */
10921 n->narg.text = wordtext;
10922 #if ENABLE_ASH_BASH_COMPAT
10923 if (strcmp("[[", wordtext) == 0)
10924 double_brackets_flag = 1;
10925 else if (strcmp("]]", wordtext) == 0)
10926 double_brackets_flag = 0;
10928 n->narg.backquote = backquotelist;
10929 if (savecheckkwd && isassignment(wordtext)) {
10931 vpp = &n->narg.next;
10934 app = &n->narg.next;
10937 #if ENABLE_ASH_BASH_COMPAT
10938 if (function_flag) {
10939 checkkwd = CHKNL | CHKKWD;
10940 switch (peektoken()) {
10952 if (strcmp("[[", wordtext) == 0)
10956 raise_error_unexpected_syntax(-1);
10962 *rpp = n = redirnode;
10963 rpp = &n->nfile.next;
10964 parsefname(); /* read name of redirection file */
10967 IF_ASH_BASH_COMPAT(do_func:)
10968 if (args && app == &args->narg.next
10971 struct builtincmd *bcmd;
10974 /* We have a function */
10975 if (IF_ASH_BASH_COMPAT(!function_flag &&) readtoken() != TRP)
10976 raise_error_unexpected_syntax(TRP);
10977 name = n->narg.text;
10978 if (!goodname(name)
10979 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10981 raise_error_syntax("bad function name");
10984 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10985 n->narg.next = parse_command();
10988 IF_ASH_BASH_COMPAT(function_flag = 0;)
10999 n = stzalloc(sizeof(struct ncmd));
11001 n->ncmd.args = args;
11002 n->ncmd.assign = vars;
11003 n->ncmd.redirect = redir;
11007 static union node *
11008 parse_command(void)
11010 union node *n1, *n2;
11011 union node *ap, **app;
11012 union node *cp, **cpp;
11013 union node *redir, **rpp;
11020 switch (readtoken()) {
11022 raise_error_unexpected_syntax(-1);
11025 n1 = stzalloc(sizeof(struct nif));
11027 n1->nif.test = list(0);
11028 if (readtoken() != TTHEN)
11029 raise_error_unexpected_syntax(TTHEN);
11030 n1->nif.ifpart = list(0);
11032 while (readtoken() == TELIF) {
11033 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11034 n2 = n2->nif.elsepart;
11036 n2->nif.test = list(0);
11037 if (readtoken() != TTHEN)
11038 raise_error_unexpected_syntax(TTHEN);
11039 n2->nif.ifpart = list(0);
11041 if (lasttoken == TELSE)
11042 n2->nif.elsepart = list(0);
11044 n2->nif.elsepart = NULL;
11052 n1 = stzalloc(sizeof(struct nbinary));
11053 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11054 n1->nbinary.ch1 = list(0);
11057 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
11058 got == TWORD ? wordtext : ""));
11059 raise_error_unexpected_syntax(TDO);
11061 n1->nbinary.ch2 = list(0);
11066 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11067 raise_error_syntax("bad for loop variable");
11068 n1 = stzalloc(sizeof(struct nfor));
11070 n1->nfor.var = wordtext;
11071 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11072 if (readtoken() == TIN) {
11074 while (readtoken() == TWORD) {
11075 n2 = stzalloc(sizeof(struct narg));
11077 /*n2->narg.next = NULL; - stzalloc did it */
11078 n2->narg.text = wordtext;
11079 n2->narg.backquote = backquotelist;
11081 app = &n2->narg.next;
11084 n1->nfor.args = ap;
11085 if (lasttoken != TNL && lasttoken != TSEMI)
11086 raise_error_unexpected_syntax(-1);
11088 n2 = stzalloc(sizeof(struct narg));
11090 /*n2->narg.next = NULL; - stzalloc did it */
11091 n2->narg.text = (char *)dolatstr;
11092 /*n2->narg.backquote = NULL;*/
11093 n1->nfor.args = n2;
11095 * Newline or semicolon here is optional (but note
11096 * that the original Bourne shell only allowed NL).
11098 if (lasttoken != TSEMI)
11101 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11102 if (readtoken() != TDO)
11103 raise_error_unexpected_syntax(TDO);
11104 n1->nfor.body = list(0);
11108 n1 = stzalloc(sizeof(struct ncase));
11110 if (readtoken() != TWORD)
11111 raise_error_unexpected_syntax(TWORD);
11112 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11114 /*n2->narg.next = NULL; - stzalloc did it */
11115 n2->narg.text = wordtext;
11116 n2->narg.backquote = backquotelist;
11117 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11118 if (readtoken() != TIN)
11119 raise_error_unexpected_syntax(TIN);
11120 cpp = &n1->ncase.cases;
11122 checkkwd = CHKNL | CHKKWD;
11124 while (t != TESAC) {
11125 if (lasttoken == TLP)
11127 *cpp = cp = stzalloc(sizeof(struct nclist));
11129 app = &cp->nclist.pattern;
11131 *app = ap = stzalloc(sizeof(struct narg));
11133 /*ap->narg.next = NULL; - stzalloc did it */
11134 ap->narg.text = wordtext;
11135 ap->narg.backquote = backquotelist;
11136 if (readtoken() != TPIPE)
11138 app = &ap->narg.next;
11141 //ap->narg.next = NULL;
11142 if (lasttoken != TRP)
11143 raise_error_unexpected_syntax(TRP);
11144 cp->nclist.body = list(2);
11146 cpp = &cp->nclist.next;
11148 checkkwd = CHKNL | CHKKWD;
11152 raise_error_unexpected_syntax(TENDCASE);
11159 n1 = stzalloc(sizeof(struct nredir));
11160 n1->type = NSUBSHELL;
11161 n1->nredir.n = list(0);
11162 /*n1->nredir.redirect = NULL; - stzalloc did it */
11169 IF_ASH_BASH_COMPAT(case TFUNCTION:)
11173 return simplecmd();
11176 if (readtoken() != t)
11177 raise_error_unexpected_syntax(t);
11180 /* Now check for redirection which may follow command */
11181 checkkwd = CHKKWD | CHKALIAS;
11183 while (readtoken() == TREDIR) {
11184 *rpp = n2 = redirnode;
11185 rpp = &n2->nfile.next;
11191 if (n1->type != NSUBSHELL) {
11192 n2 = stzalloc(sizeof(struct nredir));
11197 n1->nredir.redirect = redir;
11202 #if ENABLE_ASH_BASH_COMPAT
11203 static int decode_dollar_squote(void)
11205 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11211 p = strchr(C_escapes, c);
11216 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11220 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11222 } else if (c == 'x') { /* \xHH */
11226 } while (isxdigit(c) && --cnt);
11228 if (cnt == 3) { /* \x but next char is "bad" */
11232 } else { /* simple seq like \\ or \t */
11237 c = bb_process_escape_sequence((void*)&p);
11238 } else { /* unrecognized "\z": print both chars unless ' or " */
11239 if (c != '\'' && c != '"') {
11241 c |= 0x100; /* "please encode \, then me" */
11249 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11250 * is not NULL, read a here document. In the latter case, eofmark is the
11251 * word which marks the end of the document and striptabs is true if
11252 * leading tabs should be stripped from the document. The argument c
11253 * is the first character of the input token or document.
11255 * Because C does not have internal subroutines, I have simulated them
11256 * using goto's to implement the subroutine linkage. The following macros
11257 * will run code that appears at the end of readtoken1.
11259 #define CHECKEND() {goto checkend; checkend_return:;}
11260 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11261 #define PARSESUB() {goto parsesub; parsesub_return:;}
11262 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11263 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11264 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11266 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11268 /* NB: syntax parameter fits into smallint */
11269 /* c parameter is an unsigned char or PEOF or PEOA */
11272 char line[EOFMARKLEN + 1];
11273 struct nodelist *bqlist;
11277 smallint prevsyntax; /* syntax before arithmetic */
11278 #if ENABLE_ASH_EXPAND_PRMT
11279 smallint pssyntax; /* we are expanding a prompt string */
11281 int varnest; /* levels of variables expansion */
11282 int arinest; /* levels of arithmetic expansion */
11283 int parenlevel; /* levels of parens in arithmetic */
11284 int dqvarnest; /* levels of variables expansion within double quotes */
11286 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11288 startlinno = g_parsefile->linno;
11292 #if ENABLE_ASH_EXPAND_PRMT
11293 pssyntax = (syntax == PSSYNTAX);
11297 dblquote = (syntax == DQSYNTAX);
11303 STARTSTACKSTR(out);
11305 /* For each line, until end of word */
11306 CHECKEND(); /* set c to PEOF if at end of here document */
11307 for (;;) { /* until end of line or end of word */
11308 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11309 switch (SIT(c, syntax)) {
11310 case CNL: /* '\n' */
11311 if (syntax == BASESYNTAX)
11312 goto endword; /* exit outer loop */
11314 g_parsefile->linno++;
11315 setprompt_if(doprompt, 2);
11317 goto loop; /* continue outer loop */
11322 #if ENABLE_ASH_BASH_COMPAT
11323 if (c == '\\' && bash_dollar_squote) {
11324 c = decode_dollar_squote();
11326 /* skip $'\000', $'\x00' (like bash) */
11330 /* Unknown escape. Encode as '\z' */
11331 c = (unsigned char)c;
11332 if (eofmark == NULL || dblquote)
11333 USTPUTC(CTLESC, out);
11334 USTPUTC('\\', out);
11338 if (eofmark == NULL || dblquote)
11339 USTPUTC(CTLESC, out);
11342 case CBACK: /* backslash */
11343 c = pgetc_without_PEOA();
11345 USTPUTC(CTLESC, out);
11346 USTPUTC('\\', out);
11348 } else if (c == '\n') {
11349 setprompt_if(doprompt, 2);
11351 #if ENABLE_ASH_EXPAND_PRMT
11352 if (c == '$' && pssyntax) {
11353 USTPUTC(CTLESC, out);
11354 USTPUTC('\\', out);
11357 /* Backslash is retained if we are in "str" and next char isn't special */
11362 && (c != '"' || eofmark != NULL)
11364 USTPUTC('\\', out);
11366 USTPUTC(CTLESC, out);
11374 if (eofmark == NULL) {
11375 USTPUTC(CTLQUOTEMARK, out);
11383 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11384 if (eofmark != NULL && varnest == 0) {
11387 if (dqvarnest == 0) {
11388 syntax = BASESYNTAX;
11395 case CVAR: /* '$' */
11396 PARSESUB(); /* parse substitution */
11398 case CENDVAR: /* '}' */
11401 if (dqvarnest > 0) {
11408 #if ENABLE_SH_MATH_SUPPORT
11409 case CLP: /* '(' in arithmetic */
11413 case CRP: /* ')' in arithmetic */
11414 if (parenlevel > 0) {
11417 if (pgetc() == ')') {
11419 if (--arinest == 0) {
11420 syntax = prevsyntax;
11424 * unbalanced parens
11425 * (don't 2nd guess - no error)
11433 case CBQUOTE: /* '`' */
11437 goto endword; /* exit outer loop */
11441 if (varnest == 0) {
11442 #if ENABLE_ASH_BASH_COMPAT
11444 if (pgetc() == '>')
11445 c = 0x100 + '>'; /* flag &> */
11449 goto endword; /* exit outer loop */
11451 IF_ASH_ALIAS(if (c != PEOA))
11458 #if ENABLE_SH_MATH_SUPPORT
11459 if (syntax == ARISYNTAX)
11460 raise_error_syntax("missing '))'");
11462 if (syntax != BASESYNTAX && eofmark == NULL)
11463 raise_error_syntax("unterminated quoted string");
11464 if (varnest != 0) {
11465 startlinno = g_parsefile->linno;
11467 raise_error_syntax("missing '}'");
11469 USTPUTC('\0', out);
11470 len = out - (char *)stackblock();
11471 out = stackblock();
11472 if (eofmark == NULL) {
11473 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11476 if (isdigit_str9(out)) {
11477 PARSEREDIR(); /* passed as params: out, c */
11478 lasttoken = TREDIR;
11481 /* else: non-number X seen, interpret it
11482 * as "NNNX>file" = "NNNX >file" */
11486 quoteflag = quotef;
11487 backquotelist = bqlist;
11488 grabstackblock(len);
11492 /* end of readtoken routine */
11495 * Check to see whether we are at the end of the here document. When this
11496 * is called, c is set to the first character of the next input line. If
11497 * we are at the end of the here document, this routine sets the c to PEOF.
11501 #if ENABLE_ASH_ALIAS
11503 c = pgetc_without_PEOA();
11506 while (c == '\t') {
11507 c = pgetc_without_PEOA();
11510 if (c == *eofmark) {
11511 if (pfgets(line, sizeof(line)) != NULL) {
11515 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11517 if (*p == '\n' && *q == '\0') {
11519 g_parsefile->linno++;
11520 needprompt = doprompt;
11522 pushstring(line, NULL);
11527 goto checkend_return;
11531 * Parse a redirection operator. The variable "out" points to a string
11532 * specifying the fd to be redirected. The variable "c" contains the
11533 * first character of the redirection operator.
11536 /* out is already checked to be a valid number or "" */
11537 int fd = (*out == '\0' ? -1 : atoi(out));
11540 np = stzalloc(sizeof(struct nfile));
11545 np->type = NAPPEND;
11547 np->type = NCLOBBER;
11550 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11556 #if ENABLE_ASH_BASH_COMPAT
11557 else if (c == 0x100 + '>') { /* this flags &> redirection */
11559 pgetc(); /* this is '>', no need to check */
11563 else { /* c == '<' */
11564 /*np->nfile.fd = 0; - stzalloc did it */
11568 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11569 np = stzalloc(sizeof(struct nhere));
11570 /*np->nfile.fd = 0; - stzalloc did it */
11573 heredoc = stzalloc(sizeof(struct heredoc));
11574 heredoc->here = np;
11577 heredoc->striptabs = 1;
11579 /*heredoc->striptabs = 0; - stzalloc did it */
11585 np->type = NFROMFD;
11589 np->type = NFROMTO;
11601 goto parseredir_return;
11605 * Parse a substitution. At this point, we have read the dollar sign
11606 * and nothing else.
11609 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11610 * (assuming ascii char codes, as the original implementation did) */
11611 #define is_special(c) \
11612 (((unsigned)(c) - 33 < 32) \
11613 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11615 unsigned char subtype;
11620 if (c > 255 /* PEOA or PEOF */
11621 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11623 #if ENABLE_ASH_BASH_COMPAT
11624 if (syntax != DQSYNTAX && c == '\'')
11625 bash_dollar_squote = 1;
11630 } else if (c == '(') {
11631 /* $(command) or $((arith)) */
11632 if (pgetc() == '(') {
11633 #if ENABLE_SH_MATH_SUPPORT
11636 raise_error_syntax("you disabled math support for $((arith)) syntax");
11643 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11644 USTPUTC(CTLVAR, out);
11645 typeloc = out - (char *)stackblock();
11646 USTPUTC(VSNORMAL, out);
11647 subtype = VSNORMAL;
11653 c = '#'; /* ${#} - same as $# */
11655 subtype = VSLENGTH; /* ${#VAR} */
11660 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11661 /* $[{[#]]NAME[}] */
11665 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11666 } else if (isdigit(c)) {
11667 /* $[{[#]]NUM[}] */
11671 } while (isdigit(c));
11672 } else if (is_special(c)) {
11673 /* $[{[#]]<specialchar>[}] */
11678 raise_error_syntax("bad substitution");
11680 if (c != '}' && subtype == VSLENGTH) {
11681 /* ${#VAR didn't end with } */
11687 if (subtype == 0) {
11688 static const char types[] ALIGN1 = "}-+?=";
11689 /* ${VAR...} but not $VAR or ${#VAR} */
11690 /* c == first char after VAR */
11694 #if ENABLE_ASH_BASH_COMPAT
11695 /* This check is only needed to not misinterpret
11696 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11699 if (!strchr(types, c)) {
11700 subtype = VSSUBSTR;
11702 break; /* "goto do_pungetc" is bigger (!) */
11708 const char *p = strchr(types, c);
11711 subtype = p - types + VSNORMAL;
11717 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11724 #if ENABLE_ASH_BASH_COMPAT
11726 /* ${v/[/]pattern/repl} */
11727 //TODO: encode pattern and repl separately.
11728 // Currently ${v/$var_with_slash/repl} is horribly broken
11729 subtype = VSREPLACE;
11733 subtype++; /* VSREPLACEALL */
11741 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11742 if (subtype != VSNORMAL) {
11749 goto parsesub_return;
11753 * Called to parse command substitutions. Newstyle is set if the command
11754 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11755 * list of commands (passed by reference), and savelen is the number of
11756 * characters on the top of the stack which must be preserved.
11759 struct nodelist **nlpp;
11763 smallint saveprompt = 0;
11766 savelen = out - (char *)stackblock();
11769 * FIXME: this can allocate very large block on stack and SEGV.
11771 * echo "..<100kbytes>..`true` $(true) `true` ..."
11772 * allocates 100kb for every command subst. With about
11773 * a hundred command substitutions stack overflows.
11774 * With larger prepended string, SEGV happens sooner.
11776 str = alloca(savelen);
11777 memcpy(str, stackblock(), savelen);
11781 /* We must read until the closing backquote, giving special
11782 * treatment to some slashes, and then push the string and
11783 * reread it as input, interpreting it normally.
11789 STARTSTACKSTR(pout);
11793 setprompt_if(needprompt, 2);
11802 g_parsefile->linno++;
11803 setprompt_if(doprompt, 2);
11805 * If eating a newline, avoid putting
11806 * the newline into the new character
11807 * stream (via the STPUTC after the
11812 if (pc != '\\' && pc != '`' && pc != '$'
11813 && (!dblquote || pc != '"')
11815 STPUTC('\\', pout);
11817 if (pc <= 255 /* not PEOA or PEOF */) {
11823 IF_ASH_ALIAS(case PEOA:)
11824 startlinno = g_parsefile->linno;
11825 raise_error_syntax("EOF in backquote substitution");
11828 g_parsefile->linno++;
11829 needprompt = doprompt;
11838 STPUTC('\0', pout);
11839 psavelen = pout - (char *)stackblock();
11840 if (psavelen > 0) {
11841 pstr = grabstackstr(pout);
11842 setinputstring(pstr);
11847 nlpp = &(*nlpp)->next;
11848 *nlpp = stzalloc(sizeof(**nlpp));
11849 /* (*nlpp)->next = NULL; - stzalloc did it */
11852 saveprompt = doprompt;
11859 doprompt = saveprompt;
11860 else if (readtoken() != TRP)
11861 raise_error_unexpected_syntax(TRP);
11866 * Start reading from old file again, ignoring any pushed back
11867 * tokens left from the backquote parsing
11872 while (stackblocksize() <= savelen)
11874 STARTSTACKSTR(out);
11876 memcpy(out, str, savelen);
11877 STADJUST(savelen, out);
11879 USTPUTC(CTLBACKQ, out);
11881 goto parsebackq_oldreturn;
11882 goto parsebackq_newreturn;
11885 #if ENABLE_SH_MATH_SUPPORT
11887 * Parse an arithmetic expansion (indicate start of one and set state)
11890 if (++arinest == 1) {
11891 prevsyntax = syntax;
11892 syntax = ARISYNTAX;
11894 USTPUTC(CTLARI, out);
11895 goto parsearith_return;
11898 } /* end of readtoken */
11901 * Read the next input token.
11902 * If the token is a word, we set backquotelist to the list of cmds in
11903 * backquotes. We set quoteflag to true if any part of the word was
11905 * If the token is TREDIR, then we set redirnode to a structure containing
11907 * In all cases, the variable startlinno is set to the number of the line
11908 * on which the token starts.
11910 * [Change comment: here documents and internal procedures]
11911 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11912 * word parsing code into a separate routine. In this case, readtoken
11913 * doesn't need to have any internal procedures, but parseword does.
11914 * We could also make parseoperator in essence the main routine, and
11915 * have parseword (readtoken1?) handle both words and redirection.]
11917 #define NEW_xxreadtoken
11918 #ifdef NEW_xxreadtoken
11919 /* singles must be first! */
11920 static const char xxreadtoken_chars[7] ALIGN1 = {
11921 '\n', '(', ')', /* singles */
11922 '&', '|', ';', /* doubles */
11926 #define xxreadtoken_singles 3
11927 #define xxreadtoken_doubles 3
11929 static const char xxreadtoken_tokens[] ALIGN1 = {
11930 TNL, TLP, TRP, /* only single occurrence allowed */
11931 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11932 TEOF, /* corresponds to trailing nul */
11933 TAND, TOR, TENDCASE /* if double occurrence */
11945 setprompt_if(needprompt, 2);
11946 startlinno = g_parsefile->linno;
11947 for (;;) { /* until token or start of word found */
11949 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11953 while ((c = pgetc()) != '\n' && c != PEOF)
11956 } else if (c == '\\') {
11957 if (pgetc() != '\n') {
11959 break; /* return readtoken1(...) */
11961 startlinno = ++g_parsefile->linno;
11962 setprompt_if(doprompt, 2);
11966 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11969 g_parsefile->linno++;
11970 needprompt = doprompt;
11973 p = strchr(xxreadtoken_chars, c);
11975 break; /* return readtoken1(...) */
11977 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11979 if (cc == c) { /* double occurrence? */
11980 p += xxreadtoken_doubles + 1;
11983 #if ENABLE_ASH_BASH_COMPAT
11984 if (c == '&' && cc == '>') /* &> */
11985 break; /* return readtoken1(...) */
11990 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11995 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11997 #else /* old xxreadtoken */
11998 #define RETURN(token) return lasttoken = token
12008 setprompt_if(needprompt, 2);
12009 startlinno = g_parsefile->linno;
12010 for (;;) { /* until token or start of word found */
12013 case ' ': case '\t':
12014 IF_ASH_ALIAS(case PEOA:)
12017 while ((c = pgetc()) != '\n' && c != PEOF)
12022 if (pgetc() == '\n') {
12023 startlinno = ++g_parsefile->linno;
12024 setprompt_if(doprompt, 2);
12030 g_parsefile->linno++;
12031 needprompt = doprompt;
12036 if (pgetc() == '&')
12041 if (pgetc() == '|')
12046 if (pgetc() == ';')
12059 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12062 #endif /* old xxreadtoken */
12068 int kwd = checkkwd;
12070 smallint alreadyseen = tokpushback;
12073 #if ENABLE_ASH_ALIAS
12089 if (t != TWORD || quoteflag) {
12094 * check for keywords
12096 if (kwd & CHKKWD) {
12097 const char *const *pp;
12099 pp = findkwd(wordtext);
12101 lasttoken = t = pp - tokname_array;
12102 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
12107 if (checkkwd & CHKALIAS) {
12108 #if ENABLE_ASH_ALIAS
12110 ap = lookupalias(wordtext, 1);
12113 pushstring(ap->val, ap);
12123 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
12125 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
12141 * Read and parse a command. Returns NODE_EOF on end of file.
12142 * (NULL is a valid parse tree indicating a blank line.)
12144 static union node *
12145 parsecmd(int interact)
12150 doprompt = interact;
12151 setprompt_if(doprompt, doprompt);
12157 * Input any here documents.
12162 struct heredoc *here;
12165 here = heredoclist;
12166 heredoclist = NULL;
12169 setprompt_if(needprompt, 2);
12170 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12171 here->eofmark, here->striptabs);
12172 n = stzalloc(sizeof(struct narg));
12173 n->narg.type = NARG;
12174 /*n->narg.next = NULL; - stzalloc did it */
12175 n->narg.text = wordtext;
12176 n->narg.backquote = backquotelist;
12177 here->here->nhere.doc = n;
12184 * called by editline -- any expansions to the prompt should be added here.
12186 #if ENABLE_ASH_EXPAND_PRMT
12187 static const char *
12188 expandstr(const char *ps)
12192 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12193 * and token processing _can_ alter it (delete NULs etc). */
12194 setinputstring((char *)ps);
12195 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12198 n.narg.type = NARG;
12199 n.narg.next = NULL;
12200 n.narg.text = wordtext;
12201 n.narg.backquote = backquotelist;
12203 expandarg(&n, NULL, EXP_QUOTED);
12204 return stackblock();
12209 * Execute a command or commands contained in a string.
12212 evalstring(char *s, int mask)
12215 struct stackmark smark;
12220 setstackmark(&smark);
12223 while ((n = parsecmd(0)) != NODE_EOF) {
12226 i = evaltree(n, 0);
12229 popstackmark(&smark);
12233 popstackmark(&smark);
12242 * The eval command.
12244 static int FAST_FUNC
12245 evalcmd(int argc UNUSED_PARAM, char **argv)
12254 STARTSTACKSTR(concat);
12256 concat = stack_putstr(p, concat);
12260 STPUTC(' ', concat);
12262 STPUTC('\0', concat);
12263 p = grabstackstr(concat);
12265 return evalstring(p, ~SKIPEVAL);
12271 * Read and execute commands.
12272 * "Top" is nonzero for the top level command loop;
12273 * it turns on prompting if the shell is interactive.
12279 struct stackmark smark;
12284 TRACE(("cmdloop(%d) called\n", top));
12288 setstackmark(&smark);
12291 showjobs(SHOW_CHANGED|SHOW_STDERR);
12294 if (iflag && top) {
12298 n = parsecmd(inter);
12300 if (DEBUG > 2 && debug && (n != NODE_EOF))
12303 if (n == NODE_EOF) {
12304 if (!top || numeof >= 50)
12306 if (!stoppedjobs()) {
12309 out2str("\nUse \"exit\" to leave shell.\n");
12312 } else if (nflag == 0) {
12315 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12318 i = evaltree(n, 0);
12322 popstackmark(&smark);
12327 return skip & SKIPEVAL;
12334 * Take commands from a file. To be compatible we should do a path
12335 * search for the file, which is necessary to find sub-commands.
12338 find_dot_file(char *name)
12341 const char *path = pathval();
12344 /* don't try this for absolute or relative paths */
12345 if (strchr(name, '/'))
12348 /* IIRC standards do not say whether . is to be searched.
12349 * And it is even smaller this way, making it unconditional for now:
12351 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12356 while ((fullname = path_advance(&path, name)) != NULL) {
12358 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12360 * Don't bother freeing here, since it will
12361 * be freed by the caller.
12365 if (fullname != name)
12366 stunalloc(fullname);
12369 /* not found in the PATH */
12370 ash_msg_and_raise_error("%s: not found", name);
12374 static int FAST_FUNC
12375 dotcmd(int argc, char **argv)
12378 struct strlist *sp;
12379 volatile struct shparam saveparam;
12381 for (sp = cmdenviron; sp; sp = sp->next)
12382 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12385 /* bash says: "bash: .: filename argument required" */
12386 return 2; /* bash compat */
12389 /* "false; . empty_file; echo $?" should print 0, not 1: */
12392 /* This aborts if file isn't found, which is POSIXly correct.
12393 * bash returns exitcode 1 instead.
12395 fullname = find_dot_file(argv[1]);
12398 if (argc) { /* argc > 0, argv[0] != NULL */
12399 saveparam = shellparam;
12400 shellparam.malloced = 0;
12401 shellparam.nparam = argc;
12402 shellparam.p = argv;
12405 /* This aborts if file can't be opened, which is POSIXly correct.
12406 * bash returns exitcode 1 instead.
12408 setinputfile(fullname, INPUT_PUSH_FILE);
12409 commandname = fullname;
12414 freeparam(&shellparam);
12415 shellparam = saveparam;
12421 static int FAST_FUNC
12422 exitcmd(int argc UNUSED_PARAM, char **argv)
12427 exitstatus = number(argv[1]);
12428 raise_exception(EXEXIT);
12433 * Read a file containing shell functions.
12436 readcmdfile(char *name)
12438 setinputfile(name, INPUT_PUSH_FILE);
12444 /* ============ find_command inplementation */
12447 * Resolve a command name. If you change this routine, you may have to
12448 * change the shellexec routine as well.
12451 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12453 struct tblentry *cmdp;
12460 struct builtincmd *bcmd;
12462 /* If name contains a slash, don't use PATH or hash table */
12463 if (strchr(name, '/') != NULL) {
12464 entry->u.index = -1;
12465 if (act & DO_ABS) {
12466 while (stat(name, &statb) < 0) {
12468 if (errno == EINTR)
12471 entry->cmdtype = CMDUNKNOWN;
12475 entry->cmdtype = CMDNORMAL;
12479 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12481 updatetbl = (path == pathval());
12484 if (strstr(path, "%builtin") != NULL)
12485 act |= DO_ALTBLTIN;
12488 /* If name is in the table, check answer will be ok */
12489 cmdp = cmdlookup(name, 0);
12490 if (cmdp != NULL) {
12493 switch (cmdp->cmdtype) {
12511 } else if (cmdp->rehash == 0)
12512 /* if not invalidated by cd, we're done */
12516 /* If %builtin not in path, check for builtin next */
12517 bcmd = find_builtin(name);
12519 if (IS_BUILTIN_REGULAR(bcmd))
12520 goto builtin_success;
12521 if (act & DO_ALTPATH) {
12522 if (!(act & DO_ALTBLTIN))
12523 goto builtin_success;
12524 } else if (builtinloc <= 0) {
12525 goto builtin_success;
12529 #if ENABLE_FEATURE_SH_STANDALONE
12531 int applet_no = find_applet_by_name(name);
12532 if (applet_no >= 0) {
12533 entry->cmdtype = CMDNORMAL;
12534 entry->u.index = -2 - applet_no;
12540 /* We have to search path. */
12541 prev = -1; /* where to start */
12542 if (cmdp && cmdp->rehash) { /* doing a rehash */
12543 if (cmdp->cmdtype == CMDBUILTIN)
12546 prev = cmdp->param.index;
12552 while ((fullname = path_advance(&path, name)) != NULL) {
12553 stunalloc(fullname);
12554 /* NB: code below will still use fullname
12555 * despite it being "unallocated" */
12558 if (prefix(pathopt, "builtin")) {
12560 goto builtin_success;
12563 if ((act & DO_NOFUNC)
12564 || !prefix(pathopt, "func")
12565 ) { /* ignore unimplemented options */
12569 /* if rehash, don't redo absolute path names */
12570 if (fullname[0] == '/' && idx <= prev) {
12573 TRACE(("searchexec \"%s\": no change\n", name));
12576 while (stat(fullname, &statb) < 0) {
12578 if (errno == EINTR)
12581 if (errno != ENOENT && errno != ENOTDIR)
12585 e = EACCES; /* if we fail, this will be the error */
12586 if (!S_ISREG(statb.st_mode))
12588 if (pathopt) { /* this is a %func directory */
12589 stalloc(strlen(fullname) + 1);
12590 /* NB: stalloc will return space pointed by fullname
12591 * (because we don't have any intervening allocations
12592 * between stunalloc above and this stalloc) */
12593 readcmdfile(fullname);
12594 cmdp = cmdlookup(name, 0);
12595 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12596 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12597 stunalloc(fullname);
12600 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12602 entry->cmdtype = CMDNORMAL;
12603 entry->u.index = idx;
12607 cmdp = cmdlookup(name, 1);
12608 cmdp->cmdtype = CMDNORMAL;
12609 cmdp->param.index = idx;
12614 /* We failed. If there was an entry for this command, delete it */
12615 if (cmdp && updatetbl)
12616 delete_cmd_entry();
12618 ash_msg("%s: %s", name, errmsg(e, "not found"));
12619 entry->cmdtype = CMDUNKNOWN;
12624 entry->cmdtype = CMDBUILTIN;
12625 entry->u.cmd = bcmd;
12629 cmdp = cmdlookup(name, 1);
12630 cmdp->cmdtype = CMDBUILTIN;
12631 cmdp->param.cmd = bcmd;
12635 entry->cmdtype = cmdp->cmdtype;
12636 entry->u = cmdp->param;
12640 /* ============ trap.c */
12643 * The trap builtin.
12645 static int FAST_FUNC
12646 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12650 int signo, exitcode;
12655 for (signo = 0; signo < NSIG; signo++) {
12656 char *tr = trap_ptr[signo];
12658 /* note: bash adds "SIG", but only if invoked
12659 * as "bash". If called as "sh", or if set -o posix,
12660 * then it prints short signal names.
12661 * We are printing short names: */
12662 out1fmt("trap -- %s %s\n",
12664 get_signame(signo));
12665 /* trap_ptr != trap only if we are in special-cased `trap` code.
12666 * In this case, we will exit very soon, no need to free(). */
12667 /* if (trap_ptr != trap && tp[0]) */
12672 if (trap_ptr != trap) {
12685 signo = get_signum(*ap);
12687 /* Mimic bash message exactly */
12688 ash_msg("%s: invalid signal specification", *ap);
12694 if (LONE_DASH(action))
12697 action = ckstrdup(action);
12701 may_have_traps = 1;
12702 trap[signo] = action;
12713 /* ============ Builtins */
12715 #if ENABLE_ASH_HELP
12716 static int FAST_FUNC
12717 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12723 "Built-in commands:\n"
12724 "------------------\n");
12725 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12726 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12727 builtintab[i].name + 1);
12733 # if ENABLE_FEATURE_SH_STANDALONE
12735 const char *a = applet_names;
12737 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12742 while (*a++ != '\0')
12748 return EXIT_SUCCESS;
12753 static int FAST_FUNC
12754 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12756 show_history(line_input_state);
12757 return EXIT_SUCCESS;
12762 * The export and readonly commands.
12764 static int FAST_FUNC
12765 exportcmd(int argc UNUSED_PARAM, char **argv)
12775 /* "readonly" in bash accepts, but ignores -n.
12776 * We do the same: it saves a conditional in nextopt's param.
12779 while ((opt = nextopt("np")) != '\0') {
12781 flag_off = VEXPORT;
12784 if (argv[0][0] == 'r') {
12786 flag_off = 0; /* readonly ignores -n */
12788 flag_off = ~flag_off;
12790 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12796 p = strchr(name, '=');
12800 vp = *findvar(hashvar(name), name);
12802 vp->flags = ((vp->flags | flag) & flag_off);
12806 setvar(name, p, (flag & flag_off));
12807 } while ((name = *++aptr) != NULL);
12812 /* No arguments. Show the list of exported or readonly vars.
12815 showvars(argv[0], flag, 0);
12820 * Delete a function if it exists.
12823 unsetfunc(const char *name)
12825 struct tblentry *cmdp;
12827 cmdp = cmdlookup(name, 0);
12828 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12829 delete_cmd_entry();
12833 * The unset builtin command. We unset the function before we unset the
12834 * variable to allow a function to be unset when there is a readonly variable
12835 * with the same name.
12837 static int FAST_FUNC
12838 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12845 while ((i = nextopt("vf")) != 0) {
12849 for (ap = argptr; *ap; ap++) {
12862 static const unsigned char timescmd_str[] ALIGN1 = {
12863 ' ', offsetof(struct tms, tms_utime),
12864 '\n', offsetof(struct tms, tms_stime),
12865 ' ', offsetof(struct tms, tms_cutime),
12866 '\n', offsetof(struct tms, tms_cstime),
12869 static int FAST_FUNC
12870 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12872 unsigned long clk_tck, s, t;
12873 const unsigned char *p;
12876 clk_tck = bb_clk_tck();
12881 t = *(clock_t *)(((char *) &buf) + p[1]);
12884 out1fmt("%lum%lu.%03lus%c",
12886 (t * 1000) / clk_tck,
12894 #if ENABLE_SH_MATH_SUPPORT
12896 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12897 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12899 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12901 static int FAST_FUNC
12902 letcmd(int argc UNUSED_PARAM, char **argv)
12908 ash_msg_and_raise_error("expression expected");
12910 i = ash_arith(*argv);
12918 * The read builtin. Options:
12919 * -r Do not interpret '\' specially
12920 * -s Turn off echo (tty only)
12921 * -n NCHARS Read NCHARS max
12922 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12923 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12924 * -u FD Read from given FD instead of fd 0
12925 * This uses unbuffered input, which may be avoidable in some cases.
12926 * TODO: bash also has:
12927 * -a ARRAY Read into array[0],[1],etc
12928 * -d DELIM End on DELIM char, not newline
12929 * -e Use line editing (tty only)
12931 static int FAST_FUNC
12932 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12934 char *opt_n = NULL;
12935 char *opt_p = NULL;
12936 char *opt_t = NULL;
12937 char *opt_u = NULL;
12938 int read_flags = 0;
12942 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12951 read_flags |= BUILTIN_READ_SILENT;
12957 read_flags |= BUILTIN_READ_RAW;
12967 /* "read -s" needs to save/restore termios, can't allow ^C
12968 * to jump out of it.
12971 r = shell_builtin_read(setvar0,
12973 bltinlookup("IFS"), /* can be NULL */
12982 if ((uintptr_t)r > 1)
12983 ash_msg_and_raise_error(r);
12985 return (uintptr_t)r;
12988 static int FAST_FUNC
12989 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12991 static const char permuser[3] ALIGN1 = "ogu";
12994 int symbolic_mode = 0;
12996 while (nextopt("S") != '\0') {
13005 if (*argptr == NULL) {
13006 if (symbolic_mode) {
13007 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13014 *p++ = permuser[i];
13016 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13017 if (!(mask & 0400)) *p++ = 'r';
13018 if (!(mask & 0200)) *p++ = 'w';
13019 if (!(mask & 0100)) *p++ = 'x';
13027 out1fmt("%04o\n", mask);
13030 char *modestr = *argptr;
13031 /* numeric umasks are taken as-is */
13032 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13033 if (!isdigit(modestr[0]))
13035 mask = bb_parse_mode(modestr, mask);
13036 if ((unsigned)mask > 0777) {
13037 ash_msg_and_raise_error("illegal mode: %s", modestr);
13039 if (!isdigit(modestr[0]))
13046 static int FAST_FUNC
13047 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13049 return shell_builtin_ulimit(argv);
13052 /* ============ main() and helpers */
13055 * Called to exit the shell.
13064 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13065 save_history(line_input_state);
13068 status = exitstatus;
13069 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13070 if (setjmp(loc.loc)) {
13071 if (exception_type == EXEXIT)
13072 /* dash bug: it just does _exit(exitstatus) here
13073 * but we have to do setjobctl(0) first!
13074 * (bug is still not fixed in dash-0.5.3 - if you run dash
13075 * under Midnight Commander, on exit from dash MC is backgrounded) */
13076 status = exitstatus;
13079 exception_handler = &loc;
13086 flush_stdout_stderr();
13096 /* from input.c: */
13097 /* we will never free this */
13098 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13101 signal(SIGCHLD, SIG_DFL);
13102 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13103 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13105 signal(SIGHUP, SIG_DFL);
13111 struct stat st1, st2;
13114 for (envp = environ; envp && *envp; envp++) {
13115 if (strchr(*envp, '=')) {
13116 setvareq(*envp, VEXPORT|VTEXTFIXED);
13120 setvar0("PPID", utoa(getppid()));
13121 #if ENABLE_ASH_BASH_COMPAT
13122 p = lookupvar("SHLVL");
13123 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13124 if (!lookupvar("HOSTNAME")) {
13125 struct utsname uts;
13127 setvar0("HOSTNAME", uts.nodename);
13130 p = lookupvar("PWD");
13132 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13133 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13143 //usage:#define ash_trivial_usage
13144 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13145 //usage:#define ash_full_usage "\n\n"
13146 //usage: "Unix shell interpreter"
13148 //usage:#if ENABLE_FEATURE_SH_IS_ASH
13149 //usage:# define sh_trivial_usage ash_trivial_usage
13150 //usage:# define sh_full_usage ash_full_usage
13152 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
13153 //usage:# define bash_trivial_usage ash_trivial_usage
13154 //usage:# define bash_full_usage ash_full_usage
13158 * Process the shell command line arguments.
13161 procargs(char **argv)
13164 const char *xminusc;
13169 /* if (xargv[0]) - mmm, this is always true! */
13171 for (i = 0; i < NOPTS; i++)
13174 if (options(/*cmdline:*/ 1)) {
13175 /* it already printed err message */
13176 raise_exception(EXERROR);
13180 if (*xargv == NULL) {
13182 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13185 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13189 for (i = 0; i < NOPTS; i++)
13190 if (optlist[i] == 2)
13195 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13200 } else if (!sflag) {
13201 setinputfile(*xargv, 0);
13204 commandname = arg0;
13207 shellparam.p = xargv;
13208 #if ENABLE_ASH_GETOPTS
13209 shellparam.optind = 1;
13210 shellparam.optoff = -1;
13212 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13214 shellparam.nparam++;
13221 * Read /etc/profile or .profile.
13224 read_profile(const char *name)
13228 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13237 * This routine is called when an error or an interrupt occurs in an
13238 * interactive shell and control is returned to the main command loop.
13246 /* from input.c: */
13247 g_parsefile->left_in_buffer = 0;
13248 g_parsefile->left_in_line = 0; /* clear input buffer */
13250 /* from parser.c: */
13253 /* from redir.c: */
13254 clearredir(/*drop:*/ 0);
13258 static short profile_buf[16384];
13259 extern int etext();
13263 * Main routine. We initialize things, parse the arguments, execute
13264 * profiles if we're a login shell, and then call cmdloop to execute
13265 * commands. The setjmp call sets up the location to jump to when an
13266 * exception occurs. When an exception occurs the variable "state"
13267 * is used to figure out how far we had gotten.
13269 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13270 int ash_main(int argc UNUSED_PARAM, char **argv)
13272 const char *shinit;
13273 volatile smallint state;
13274 struct jmploc jmploc;
13275 struct stackmark smark;
13277 /* Initialize global data */
13281 #if ENABLE_ASH_ALIAS
13287 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13290 #if ENABLE_FEATURE_EDITING
13291 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13294 if (setjmp(jmploc.loc)) {
13300 e = exception_type;
13304 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13308 newline_and_flush(stderr);
13311 popstackmark(&smark);
13312 FORCE_INT_ON; /* enable interrupts */
13321 exception_handler = &jmploc;
13324 TRACE(("Shell args: "));
13325 trace_puts_args(argv);
13327 rootpid = getpid();
13330 setstackmark(&smark);
13333 if (argv[0] && argv[0][0] == '-')
13339 read_profile("/etc/profile");
13342 hp = lookupvar("HOME");
13344 hp = concat_path_file(hp, ".profile");
13353 getuid() == geteuid() && getgid() == getegid() &&
13357 shinit = lookupvar("ENV");
13358 if (shinit != NULL && *shinit != '\0') {
13359 read_profile(shinit);
13365 /* evalstring pushes parsefile stack.
13366 * Ensure we don't falsely claim that 0 (stdin)
13367 * is one of stacked source fds.
13368 * Testcase: ash -c 'exec 1>&0' must not complain. */
13369 // if (!sflag) g_parsefile->pf_fd = -1;
13370 // ^^ not necessary since now we special-case fd 0
13371 // in is_hidden_fd() to not be considered "hidden fd"
13372 evalstring(minusc, 0);
13375 if (sflag || minusc == NULL) {
13376 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13378 const char *hp = lookupvar("HISTFILE");
13380 hp = lookupvar("HOME");
13382 hp = concat_path_file(hp, ".ash_history");
13383 setvar0("HISTFILE", hp);
13385 hp = lookupvar("HISTFILE");
13389 line_input_state->hist_file = hp;
13390 # if ENABLE_FEATURE_SH_HISTFILESIZE
13391 hp = lookupvar("HISTFILESIZE");
13392 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13396 state4: /* XXX ??? - why isn't this before the "if" statement */
13404 extern void _mcleanup(void);
13408 TRACE(("End of main reached\n"));
13415 * Copyright (c) 1989, 1991, 1993, 1994
13416 * The Regents of the University of California. All rights reserved.
13418 * This code is derived from software contributed to Berkeley by
13419 * Kenneth Almquist.
13421 * Redistribution and use in source and binary forms, with or without
13422 * modification, are permitted provided that the following conditions
13424 * 1. Redistributions of source code must retain the above copyright
13425 * notice, this list of conditions and the following disclaimer.
13426 * 2. Redistributions in binary form must reproduce the above copyright
13427 * notice, this list of conditions and the following disclaimer in the
13428 * documentation and/or other materials provided with the distribution.
13429 * 3. Neither the name of the University nor the names of its contributors
13430 * may be used to endorse or promote products derived from this software
13431 * without specific prior written permission.
13433 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13434 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13435 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13436 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13437 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13438 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13439 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13440 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13441 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13442 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF