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 permenantly */
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 ststrdup(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 = ststrdup(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[] = {
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 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2813 # if ENABLE_ASH_ALIAS
2814 static const uint8_t syntax_index_table[] ALIGN1 = {
2815 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2816 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2817 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2821 static const uint8_t syntax_index_table[] ALIGN1 = {
2822 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2823 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2824 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2833 # if ENABLE_ASH_ALIAS
2839 /* Cast is purely for paranoia here,
2840 * just in case someone passed signed char to us */
2841 if ((unsigned char)c >= CTL_FIRST
2842 && (unsigned char)c <= CTL_LAST
2846 s = strchrnul(spec_symbls, c);
2849 indx = syntax_index_table[s - spec_symbls];
2851 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2854 #else /* !USE_SIT_FUNCTION */
2856 static const uint8_t syntax_index_table[] = {
2857 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2858 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2868 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2869 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2891 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2892 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2893 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2894 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2895 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2896 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2897 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2898 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2899 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2900 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2901 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2902 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2903 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2904 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2905 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2906 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2907 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2908 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2909 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2910 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2911 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2912 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2913 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2916 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2917 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2918 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2919 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2920 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2921 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2922 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2950 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2951 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2952 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2955 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2983 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2984 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2985 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2986 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2987 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2988 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2989 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2990 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2991 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2992 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2993 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2994 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2995 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2996 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2997 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2998 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2999 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3000 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3001 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3002 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3114 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3115 # if ENABLE_ASH_ALIAS
3116 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3120 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3122 #endif /* !USE_SIT_FUNCTION */
3125 /* ============ Alias handling */
3127 #if ENABLE_ASH_ALIAS
3129 #define ALIASINUSE 1
3140 static struct alias **atab; // [ATABSIZE];
3141 #define INIT_G_alias() do { \
3142 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3146 static struct alias **
3147 __lookupalias(const char *name) {
3148 unsigned int hashval;
3155 ch = (unsigned char)*p;
3159 ch = (unsigned char)*++p;
3161 app = &atab[hashval % ATABSIZE];
3163 for (; *app; app = &(*app)->next) {
3164 if (strcmp(name, (*app)->name) == 0) {
3172 static struct alias *
3173 lookupalias(const char *name, int check)
3175 struct alias *ap = *__lookupalias(name);
3177 if (check && ap && (ap->flag & ALIASINUSE))
3182 static struct alias *
3183 freealias(struct alias *ap)
3187 if (ap->flag & ALIASINUSE) {
3188 ap->flag |= ALIASDEAD;
3200 setalias(const char *name, const char *val)
3202 struct alias *ap, **app;
3204 app = __lookupalias(name);
3208 if (!(ap->flag & ALIASINUSE)) {
3211 ap->val = ckstrdup(val);
3212 ap->flag &= ~ALIASDEAD;
3215 ap = ckzalloc(sizeof(struct alias));
3216 ap->name = ckstrdup(name);
3217 ap->val = ckstrdup(val);
3218 /*ap->flag = 0; - ckzalloc did it */
3219 /*ap->next = NULL;*/
3226 unalias(const char *name)
3230 app = __lookupalias(name);
3234 *app = freealias(*app);
3245 struct alias *ap, **app;
3249 for (i = 0; i < ATABSIZE; i++) {
3251 for (ap = *app; ap; ap = *app) {
3252 *app = freealias(*app);
3262 printalias(const struct alias *ap)
3264 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3268 * TODO - sort output
3270 static int FAST_FUNC
3271 aliascmd(int argc UNUSED_PARAM, char **argv)
3280 for (i = 0; i < ATABSIZE; i++) {
3281 for (ap = atab[i]; ap; ap = ap->next) {
3287 while ((n = *++argv) != NULL) {
3288 v = strchr(n+1, '=');
3289 if (v == NULL) { /* n+1: funny ksh stuff */
3290 ap = *__lookupalias(n);
3292 fprintf(stderr, "%s: %s not found\n", "alias", n);
3305 static int FAST_FUNC
3306 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3310 while ((i = nextopt("a")) != '\0') {
3316 for (i = 0; *argptr; argptr++) {
3317 if (unalias(*argptr)) {
3318 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3326 #endif /* ASH_ALIAS */
3329 /* ============ jobs.c */
3331 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3334 #define FORK_NOJOB 2
3336 /* mode flags for showjob(s) */
3337 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3338 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3339 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3340 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3343 * A job structure contains information about a job. A job is either a
3344 * single process or a set of processes contained in a pipeline. In the
3345 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3349 pid_t ps_pid; /* process id */
3350 int ps_status; /* last process status from wait() */
3351 char *ps_cmd; /* text of command being run */
3355 struct procstat ps0; /* status of process */
3356 struct procstat *ps; /* status or processes when more than one */
3358 int stopstatus; /* status of a stopped job */
3361 nprocs: 16, /* number of processes */
3363 #define JOBRUNNING 0 /* at least one proc running */
3364 #define JOBSTOPPED 1 /* all procs are stopped */
3365 #define JOBDONE 2 /* all procs are completed */
3367 sigint: 1, /* job was killed by SIGINT */
3368 jobctl: 1, /* job running under job control */
3370 waited: 1, /* true if this entry has been waited for */
3371 used: 1, /* true if this entry is in used */
3372 changed: 1; /* true if status has changed */
3373 struct job *prev_job; /* previous job */
3376 static struct job *makejob(/*union node *,*/ int);
3377 static int forkshell(struct job *, union node *, int);
3378 static int waitforjob(struct job *);
3381 enum { doing_jobctl = 0 };
3382 #define setjobctl(on) do {} while (0)
3384 static smallint doing_jobctl; //references:8
3385 static void setjobctl(int);
3392 ignoresig(int signo)
3394 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3395 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3396 /* No, need to do it */
3397 signal(signo, SIG_IGN);
3399 sigmode[signo - 1] = S_HARD_IGN;
3403 * Only one usage site - in setsignal()
3406 signal_handler(int signo)
3408 gotsig[signo - 1] = 1;
3410 if (signo == SIGINT && !trap[SIGINT]) {
3411 if (!suppress_int) {
3413 raise_interrupt(); /* does not return */
3417 pending_sig = signo;
3422 * Set the signal handler for the specified signal. The routine figures
3423 * out what it should be set to.
3426 setsignal(int signo)
3429 char cur_act, new_act;
3430 struct sigaction act;
3434 if (t != NULL) { /* trap for this sig is set */
3436 if (t[0] == '\0') /* trap is "": ignore this sig */
3440 if (rootshell && new_act == S_DFL) {
3443 if (iflag || minusc || sflag == 0)
3452 * "In all cases, bash ignores SIGQUIT. Non-builtin
3453 * commands run by bash have signal handlers
3454 * set to the values inherited by the shell
3455 * from its parent". */
3471 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3472 //whereas we have to restore it to what shell got on entry
3473 //from the parent. See comment above
3475 t = &sigmode[signo - 1];
3478 /* current setting is not yet known */
3479 if (sigaction(signo, NULL, &act)) {
3480 /* pretend it worked; maybe we should give a warning,
3481 * but other shells don't. We don't alter sigmode,
3482 * so we retry every time.
3483 * btw, in Linux it never fails. --vda */
3486 if (act.sa_handler == SIG_IGN) {
3487 cur_act = S_HARD_IGN;
3489 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3491 cur_act = S_IGN; /* don't hard ignore these */
3495 if (cur_act == S_HARD_IGN || cur_act == new_act)
3498 act.sa_handler = SIG_DFL;
3501 act.sa_handler = signal_handler;
3504 act.sa_handler = SIG_IGN;
3508 /* flags and mask matter only if !DFL and !IGN, but we do it
3509 * for all cases for more deterministic behavior:
3512 sigfillset(&act.sa_mask);
3514 sigaction_set(signo, &act);
3519 /* mode flags for set_curjob */
3520 #define CUR_DELETE 2
3521 #define CUR_RUNNING 1
3522 #define CUR_STOPPED 0
3524 /* mode flags for dowait */
3525 #define DOWAIT_NONBLOCK WNOHANG
3526 #define DOWAIT_BLOCK 0
3529 /* pgrp of shell on invocation */
3530 static int initialpgrp; //references:2
3531 static int ttyfd = -1; //5
3534 static struct job *jobtab; //5
3536 static unsigned njobs; //4
3538 static struct job *curjob; //lots
3539 /* number of presumed living untracked jobs */
3540 static int jobless; //4
3543 set_curjob(struct job *jp, unsigned mode)
3546 struct job **jpp, **curp;
3548 /* first remove from list */
3549 jpp = curp = &curjob;
3554 jpp = &jp1->prev_job;
3556 *jpp = jp1->prev_job;
3558 /* Then re-insert in correct position */
3566 /* job being deleted */
3569 /* newly created job or backgrounded job,
3570 * put after all stopped jobs.
3575 if (!jp1 || jp1->state != JOBSTOPPED)
3578 jpp = &jp1->prev_job;
3584 /* newly stopped job - becomes curjob */
3585 jp->prev_job = *jpp;
3593 jobno(const struct job *jp)
3595 return jp - jobtab + 1;
3600 * Convert a job name to a job structure.
3603 #define getjob(name, getctl) getjob(name)
3606 getjob(const char *name, int getctl)
3610 const char *err_msg = "%s: no such job";
3614 char *(*match)(const char *, const char *);
3629 if (c == '+' || c == '%') {
3631 err_msg = "No current job";
3637 err_msg = "No previous job";
3648 jp = jobtab + num - 1;
3663 if (match(jp->ps[0].ps_cmd, p)) {
3667 err_msg = "%s: ambiguous";
3677 err_msg = "job %s not created under job control";
3678 if (getctl && jp->jobctl == 0)
3683 ash_msg_and_raise_error(err_msg, name);
3687 * Mark a job structure as unused.
3690 freejob(struct job *jp)
3692 struct procstat *ps;
3696 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3697 if (ps->ps_cmd != nullstr)
3700 if (jp->ps != &jp->ps0)
3703 set_curjob(jp, CUR_DELETE);
3709 xtcsetpgrp(int fd, pid_t pgrp)
3711 if (tcsetpgrp(fd, pgrp))
3712 ash_msg_and_raise_error("can't set tty process group (%m)");
3716 * Turn job control on and off.
3718 * Note: This code assumes that the third arg to ioctl is a character
3719 * pointer, which is true on Berkeley systems but not System V. Since
3720 * System V doesn't have job control yet, this isn't a problem now.
3722 * Called with interrupts off.
3730 if (on == doing_jobctl || rootshell == 0)
3734 ofd = fd = open(_PATH_TTY, O_RDWR);
3736 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3737 * That sometimes helps to acquire controlling tty.
3738 * Obviously, a workaround for bugs when someone
3739 * failed to provide a controlling tty to bash! :) */
3745 fd = fcntl(fd, F_DUPFD, 10);
3750 /* fd is a tty at this point */
3751 close_on_exec_on(fd);
3752 while (1) { /* while we are in the background */
3753 pgrp = tcgetpgrp(fd);
3756 ash_msg("can't access tty; job control turned off");
3760 if (pgrp == getpgrp())
3771 xtcsetpgrp(fd, pgrp);
3773 /* turning job control off */
3776 /* was xtcsetpgrp, but this can make exiting ash
3777 * loop forever if pty is already deleted */
3778 tcsetpgrp(fd, pgrp);
3792 static int FAST_FUNC
3793 killcmd(int argc, char **argv)
3795 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3798 if (argv[i][0] == '%') {
3800 * "kill %N" - job kill
3801 * Converting to pgrp / pid kill
3807 jp = getjob(argv[i], 0);
3809 * In jobs started under job control, we signal
3810 * entire process group by kill -PGRP_ID.
3811 * This happens, f.e., in interactive shell.
3813 * Otherwise, we signal each child via
3814 * kill PID1 PID2 PID3.
3816 * sh -c 'sleep 1|sleep 1 & kill %1'
3817 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3818 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3820 n = jp->nprocs; /* can't be 0 (I hope) */
3823 dst = alloca(n * sizeof(int)*4);
3825 for (j = 0; j < n; j++) {
3826 struct procstat *ps = &jp->ps[j];
3827 /* Skip non-running and not-stopped members
3828 * (i.e. dead members) of the job
3830 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3833 * kill_main has matching code to expect
3834 * leading space. Needed to not confuse
3835 * negative pids with "kill -SIGNAL_NO" syntax
3837 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3841 } while (argv[++i]);
3843 return kill_main(argc, argv);
3847 showpipe(struct job *jp /*, FILE *out*/)
3849 struct procstat *ps;
3850 struct procstat *psend;
3852 psend = jp->ps + jp->nprocs;
3853 for (ps = jp->ps + 1; ps < psend; ps++)
3854 printf(" | %s", ps->ps_cmd);
3855 newline_and_flush(stdout);
3856 flush_stdout_stderr();
3861 restartjob(struct job *jp, int mode)
3863 struct procstat *ps;
3869 if (jp->state == JOBDONE)
3871 jp->state = JOBRUNNING;
3872 pgid = jp->ps[0].ps_pid;
3873 if (mode == FORK_FG)
3874 xtcsetpgrp(ttyfd, pgid);
3875 killpg(pgid, SIGCONT);
3879 if (WIFSTOPPED(ps->ps_status)) {
3885 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3890 static int FAST_FUNC
3891 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3897 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3901 jp = getjob(*argv, 1);
3902 if (mode == FORK_BG) {
3903 set_curjob(jp, CUR_RUNNING);
3904 printf("[%d] ", jobno(jp));
3906 out1str(jp->ps[0].ps_cmd);
3907 showpipe(jp /*, stdout*/);
3908 retval = restartjob(jp, mode);
3909 } while (*argv && *++argv);
3915 sprint_status48(char *s, int status, int sigonly)
3921 if (!WIFEXITED(status)) {
3922 if (JOBS && WIFSTOPPED(status))
3923 st = WSTOPSIG(status);
3925 st = WTERMSIG(status);
3927 if (st == SIGINT || st == SIGPIPE)
3929 if (JOBS && WIFSTOPPED(status))
3933 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3934 col = fmtstr(s, 32, strsignal(st));
3935 if (WCOREDUMP(status)) {
3936 strcpy(s + col, " (core dumped)");
3937 col += sizeof(" (core dumped)")-1;
3939 } else if (!sigonly) {
3940 st = WEXITSTATUS(status);
3941 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
3948 dowait(int wait_flags, struct job *job)
3953 struct job *thisjob;
3955 TRACE(("dowait(0x%x) called\n", wait_flags));
3957 /* Do a wait system call. If job control is compiled in, we accept
3958 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3959 * NB: _not_ safe_waitpid, we need to detect EINTR */
3961 wait_flags |= WUNTRACED;
3962 pid = waitpid(-1, &status, wait_flags);
3963 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3964 pid, status, errno, strerror(errno)));
3970 for (jp = curjob; jp; jp = jp->prev_job) {
3972 struct procstat *ps;
3973 struct procstat *psend;
3974 if (jp->state == JOBDONE)
3978 psend = ps + jp->nprocs;
3980 if (ps->ps_pid == pid) {
3981 TRACE(("Job %d: changing status of proc %d "
3982 "from 0x%x to 0x%x\n",
3983 jobno(jp), pid, ps->ps_status, status));
3984 ps->ps_status = status;
3987 if (ps->ps_status == -1)
3988 jobstate = JOBRUNNING;
3990 if (jobstate == JOBRUNNING)
3992 if (WIFSTOPPED(ps->ps_status)) {
3993 jp->stopstatus = ps->ps_status;
3994 jobstate = JOBSTOPPED;
3997 } while (++ps < psend);
4001 /* Found the job where one of its processes changed its state.
4002 * Is there at least one live and running process in this job? */
4003 if (jobstate != JOBRUNNING) {
4004 /* No. All live processes in the job are stopped
4005 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4007 thisjob->changed = 1;
4008 if (thisjob->state != jobstate) {
4009 TRACE(("Job %d: changing state from %d to %d\n",
4010 jobno(thisjob), thisjob->state, jobstate));
4011 thisjob->state = jobstate;
4013 if (jobstate == JOBSTOPPED)
4014 set_curjob(thisjob, CUR_STOPPED);
4020 /* The process wasn't found in job list */
4021 if (JOBS && !WIFSTOPPED(status))
4026 if (thisjob && thisjob == job) {
4030 len = sprint_status48(s, status, 1);
4041 blocking_wait_with_raise_on_sig(void)
4043 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
4044 if (pid <= 0 && pending_sig)
4045 raise_exception(EXSIG);
4051 showjob(struct job *jp, int mode)
4053 struct procstat *ps;
4054 struct procstat *psend;
4057 char s[16 + 16 + 48];
4058 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4062 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4063 /* just output process (group) id of pipeline */
4064 fprintf(out, "%d\n", ps->ps_pid);
4068 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4073 else if (curjob && jp == curjob->prev_job)
4076 if (mode & SHOW_PIDS)
4077 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4079 psend = ps + jp->nprocs;
4081 if (jp->state == JOBRUNNING) {
4082 strcpy(s + col, "Running");
4083 col += sizeof("Running") - 1;
4085 int status = psend[-1].ps_status;
4086 if (jp->state == JOBSTOPPED)
4087 status = jp->stopstatus;
4088 col += sprint_status48(s + col, status, 0);
4090 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4092 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4093 * or prints several "PID | <cmdN>" lines,
4094 * depending on SHOW_PIDS bit.
4095 * We do not print status of individual processes
4096 * between PID and <cmdN>. bash does it, but not very well:
4097 * first line shows overall job status, not process status,
4098 * making it impossible to know 1st process status.
4102 /* for each process */
4105 if (mode & SHOW_PIDS)
4106 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4108 fprintf(out, "%s%*c%s%s",
4110 33 - col >= 0 ? 33 - col : 0, ' ',
4111 ps == jp->ps ? "" : "| ",
4114 } while (++ps != psend);
4115 newline_and_flush(out);
4119 if (jp->state == JOBDONE) {
4120 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4126 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4127 * statuses have changed since the last call to showjobs.
4134 TRACE(("showjobs(0x%x) called\n", mode));
4136 /* Handle all finished jobs */
4137 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4140 for (jp = curjob; jp; jp = jp->prev_job) {
4141 if (!(mode & SHOW_CHANGED) || jp->changed) {
4147 static int FAST_FUNC
4148 jobscmd(int argc UNUSED_PARAM, char **argv)
4153 while ((m = nextopt("lp")) != '\0') {
4157 mode |= SHOW_ONLY_PGID;
4163 showjob(getjob(*argv, 0), mode);
4173 /* Called only on finished or stopped jobs (no members are running) */
4175 getstatus(struct job *job)
4179 struct procstat *ps;
4181 /* Fetch last member's status */
4182 ps = job->ps + job->nprocs - 1;
4183 status = ps->ps_status;
4185 /* "set -o pipefail" mode: use last _nonzero_ status */
4186 while (status == 0 && --ps >= job->ps)
4187 status = ps->ps_status;
4190 retval = WEXITSTATUS(status);
4191 if (!WIFEXITED(status)) {
4193 retval = WSTOPSIG(status);
4194 if (!WIFSTOPPED(status))
4197 /* XXX: limits number of signals */
4198 retval = WTERMSIG(status);
4200 if (retval == SIGINT)
4206 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4207 jobno(job), job->nprocs, status, retval));
4211 static int FAST_FUNC
4212 waitcmd(int argc UNUSED_PARAM, char **argv)
4219 raise_exception(EXSIG);
4226 /* wait for all jobs */
4230 if (!jp) /* no running procs */
4232 if (jp->state == JOBRUNNING)
4237 blocking_wait_with_raise_on_sig();
4239 * "When bash is waiting for an asynchronous command via
4240 * the wait builtin, the reception of a signal for which a trap
4241 * has been set will cause the wait builtin to return immediately
4242 * with an exit status greater than 128, immediately after which
4243 * the trap is executed."
4245 * blocking_wait_with_raise_on_sig raises signal handlers
4246 * if it gets no pid (pid < 0). However,
4247 * if child sends us a signal *and immediately exits*,
4248 * blocking_wait_with_raise_on_sig gets pid > 0
4249 * and does not handle pending_sig. Check this case: */
4251 raise_exception(EXSIG);
4257 if (**argv != '%') {
4258 pid_t pid = number(*argv);
4263 if (job->ps[job->nprocs - 1].ps_pid == pid)
4265 job = job->prev_job;
4268 job = getjob(*argv, 0);
4270 /* loop until process terminated or stopped */
4271 while (job->state == JOBRUNNING)
4272 blocking_wait_with_raise_on_sig();
4274 retval = getstatus(job);
4287 struct job *jp, *jq;
4289 len = njobs * sizeof(*jp);
4291 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4293 offset = (char *)jp - (char *)jq;
4295 /* Relocate pointers */
4298 jq = (struct job *)((char *)jq + l);
4302 #define joff(p) ((struct job *)((char *)(p) + l))
4303 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4304 if (joff(jp)->ps == &jq->ps0)
4305 jmove(joff(jp)->ps);
4306 if (joff(jp)->prev_job)
4307 jmove(joff(jp)->prev_job);
4317 jp = (struct job *)((char *)jp + len);
4321 } while (--jq >= jp);
4326 * Return a new job structure.
4327 * Called with interrupts off.
4330 makejob(/*union node *node,*/ int nprocs)
4335 for (i = njobs, jp = jobtab; ; jp++) {
4342 if (jp->state != JOBDONE || !jp->waited)
4351 memset(jp, 0, sizeof(*jp));
4353 /* jp->jobctl is a bitfield.
4354 * "jp->jobctl |= jobctl" likely to give awful code */
4358 jp->prev_job = curjob;
4363 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4365 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4372 * Return a string identifying a command (to be printed by the
4375 static char *cmdnextc;
4378 cmdputs(const char *s)
4380 static const char vstype[VSTYPE + 1][3] = {
4381 "", "}", "-", "+", "?", "=",
4382 "%", "%%", "#", "##"
4383 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4386 const char *p, *str;
4390 unsigned char subtype = 0;
4394 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4396 while ((c = *p++) != '\0') {
4404 if ((subtype & VSTYPE) == VSLENGTH)
4410 str = "\"}" + !(quoted & 1);
4417 #if ENABLE_SH_MATH_SUPPORT
4432 if ((subtype & VSTYPE) != VSNORMAL)
4434 str = vstype[subtype & VSTYPE];
4435 if (subtype & VSNUL)
4444 /* These can only happen inside quotes */
4457 while ((c = *str++) != '\0') {
4460 } /* while *p++ not NUL */
4463 USTPUTC('"', nextc);
4469 /* cmdtxt() and cmdlist() call each other */
4470 static void cmdtxt(union node *n);
4473 cmdlist(union node *np, int sep)
4475 for (; np; np = np->narg.next) {
4479 if (sep && np->narg.next)
4485 cmdtxt(union node *n)
4488 struct nodelist *lp;
4499 lp = n->npipe.cmdlist;
4517 cmdtxt(n->nbinary.ch1);
4533 cmdtxt(n->nif.test);
4535 if (n->nif.elsepart) {
4536 cmdtxt(n->nif.ifpart);
4538 n = n->nif.elsepart;
4556 cmdtxt(n->nbinary.ch1);
4566 cmdputs(n->nfor.var);
4568 cmdlist(n->nfor.args, 1);
4573 cmdputs(n->narg.text);
4577 cmdlist(n->ncmd.args, 1);
4578 cmdlist(n->ncmd.redirect, 0);
4591 cmdputs(n->ncase.expr->narg.text);
4593 for (np = n->ncase.cases; np; np = np->nclist.next) {
4594 cmdtxt(np->nclist.pattern);
4596 cmdtxt(np->nclist.body);
4610 #if ENABLE_ASH_BASH_COMPAT
4625 cmdputs(utoa(n->nfile.fd));
4627 if (n->type == NTOFD || n->type == NFROMFD) {
4628 cmdputs(utoa(n->ndup.dupfd));
4637 commandtext(union node *n)
4641 STARTSTACKSTR(cmdnextc);
4643 name = stackblock();
4644 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4645 name, cmdnextc, cmdnextc));
4646 return ckstrdup(name);
4651 * Fork off a subshell. If we are doing job control, give the subshell its
4652 * own process group. Jp is a job structure that the job is to be added to.
4653 * N is the command that will be evaluated by the child. Both jp and n may
4654 * be NULL. The mode parameter can be one of the following:
4655 * FORK_FG - Fork off a foreground process.
4656 * FORK_BG - Fork off a background process.
4657 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4658 * process group even if job control is on.
4660 * When job control is turned off, background processes have their standard
4661 * input redirected to /dev/null (except for the second and later processes
4664 * Called with interrupts off.
4667 * Clear traps on a fork.
4674 for (tp = trap; tp < &trap[NSIG]; tp++) {
4675 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4677 if (trap_ptr == trap)
4679 /* else: it "belongs" to trap_ptr vector, don't free */
4681 if ((tp - trap) != 0)
4682 setsignal(tp - trap);
4689 /* Lives far away from here, needed for forkchild */
4690 static void closescript(void);
4692 /* Called after fork(), in child */
4693 static NOINLINE void
4694 forkchild(struct job *jp, union node *n, int mode)
4698 TRACE(("Child shell %d\n", getpid()));
4702 /* man bash: "Non-builtin commands run by bash have signal handlers
4703 * set to the values inherited by the shell from its parent".
4704 * Do we do it correctly? */
4708 if (mode == FORK_NOJOB /* is it `xxx` ? */
4709 && n && n->type == NCMD /* is it single cmd? */
4710 /* && n->ncmd.args->type == NARG - always true? */
4711 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4712 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4713 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4715 TRACE(("Trap hack\n"));
4716 /* Awful hack for `trap` or $(trap).
4718 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4719 * contains an example where "trap" is executed in a subshell:
4721 * save_traps=$(trap)
4723 * eval "$save_traps"
4725 * Standard does not say that "trap" in subshell shall print
4726 * parent shell's traps. It only says that its output
4727 * must have suitable form, but then, in the above example
4728 * (which is not supposed to be normative), it implies that.
4730 * bash (and probably other shell) does implement it
4731 * (traps are reset to defaults, but "trap" still shows them),
4732 * but as a result, "trap" logic is hopelessly messed up:
4735 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4736 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4737 * # true | trap <--- trap is in subshell - no output (ditto)
4738 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4739 * trap -- 'echo Ho' SIGWINCH
4740 * # echo `(trap)` <--- in subshell in subshell - output
4741 * trap -- 'echo Ho' SIGWINCH
4742 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4743 * trap -- 'echo Ho' SIGWINCH
4745 * The rules when to forget and when to not forget traps
4746 * get really complex and nonsensical.
4748 * Our solution: ONLY bare $(trap) or `trap` is special.
4750 /* Save trap handler strings for trap builtin to print */
4751 trap_ptr = xmemdup(trap, sizeof(trap));
4752 /* Fall through into clearing traps */
4756 /* do job control only in root shell */
4758 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4761 if (jp->nprocs == 0)
4764 pgrp = jp->ps[0].ps_pid;
4765 /* this can fail because we are doing it in the parent also */
4767 if (mode == FORK_FG)
4768 xtcsetpgrp(ttyfd, pgrp);
4773 if (mode == FORK_BG) {
4774 /* man bash: "When job control is not in effect,
4775 * asynchronous commands ignore SIGINT and SIGQUIT" */
4778 if (jp->nprocs == 0) {
4780 if (open(bb_dev_null, O_RDONLY) != 0)
4781 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4785 if (iflag) { /* why if iflag only? */
4790 * "In all cases, bash ignores SIGQUIT. Non-builtin
4791 * commands run by bash have signal handlers
4792 * set to the values inherited by the shell
4794 * Take care of the second rule: */
4798 if (n && n->type == NCMD
4799 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4801 TRACE(("Job hack\n"));
4802 /* "jobs": we do not want to clear job list for it,
4803 * instead we remove only _its_ own_ job from job list.
4804 * This makes "jobs .... | cat" more useful.
4810 for (jp = curjob; jp; jp = jp->prev_job)
4815 /* Called after fork(), in parent */
4817 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4820 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4822 TRACE(("In parent shell: child = %d\n", pid));
4824 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4830 if (mode != FORK_NOJOB && jp->jobctl) {
4833 if (jp->nprocs == 0)
4836 pgrp = jp->ps[0].ps_pid;
4837 /* This can fail because we are doing it in the child also */
4841 if (mode == FORK_BG) {
4842 backgndpid = pid; /* set $! */
4843 set_curjob(jp, CUR_RUNNING);
4846 struct procstat *ps = &jp->ps[jp->nprocs++];
4849 ps->ps_cmd = nullstr;
4851 if (doing_jobctl && n)
4852 ps->ps_cmd = commandtext(n);
4858 forkshell(struct job *jp, union node *n, int mode)
4862 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4865 TRACE(("Fork failed, errno=%d", errno));
4868 ash_msg_and_raise_error("can't fork");
4871 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4872 forkchild(jp, n, mode);
4874 forkparent(jp, n, mode, pid);
4880 * Wait for job to finish.
4882 * Under job control we have the problem that while a child process
4883 * is running interrupts generated by the user are sent to the child
4884 * but not to the shell. This means that an infinite loop started by
4885 * an interactive user may be hard to kill. With job control turned off,
4886 * an interactive user may place an interactive program inside a loop.
4887 * If the interactive program catches interrupts, the user doesn't want
4888 * these interrupts to also abort the loop. The approach we take here
4889 * is to have the shell ignore interrupt signals while waiting for a
4890 * foreground process to terminate, and then send itself an interrupt
4891 * signal if the child process was terminated by an interrupt signal.
4892 * Unfortunately, some programs want to do a bit of cleanup and then
4893 * exit on interrupt; unless these processes terminate themselves by
4894 * sending a signal to themselves (instead of calling exit) they will
4895 * confuse this approach.
4897 * Called with interrupts off.
4900 waitforjob(struct job *jp)
4904 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4907 while (jp->state == JOBRUNNING) {
4908 /* In non-interactive shells, we _can_ get
4909 * a keyboard signal here and be EINTRed,
4910 * but we just loop back, waiting for command to complete.
4913 * "If bash is waiting for a command to complete and receives
4914 * a signal for which a trap has been set, the trap
4915 * will not be executed until the command completes."
4917 * Reality is that even if trap is not set, bash
4918 * will not act on the signal until command completes.
4919 * Try this. sleep5intoff.c:
4920 * #include <signal.h>
4921 * #include <unistd.h>
4924 * sigemptyset(&set);
4925 * sigaddset(&set, SIGINT);
4926 * sigaddset(&set, SIGQUIT);
4927 * sigprocmask(SIG_BLOCK, &set, NULL);
4931 * $ bash -c './sleep5intoff; echo hi'
4932 * ^C^C^C^C <--- pressing ^C once a second
4934 * $ bash -c './sleep5intoff; echo hi'
4935 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4938 dowait(DOWAIT_BLOCK, jp);
4945 xtcsetpgrp(ttyfd, rootpid);
4947 * This is truly gross.
4948 * If we're doing job control, then we did a TIOCSPGRP which
4949 * caused us (the shell) to no longer be in the controlling
4950 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4951 * intuit from the subprocess exit status whether a SIGINT
4952 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4954 if (jp->sigint) /* TODO: do the same with all signals */
4955 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4957 if (jp->state == JOBDONE)
4964 * return 1 if there are stopped jobs, otherwise 0
4976 if (jp && jp->state == JOBSTOPPED) {
4977 out2str("You have stopped jobs.\n");
4986 /* ============ redir.c
4988 * Code for dealing with input/output redirection.
4993 #define EMPTY -2 /* marks an unused slot in redirtab */
4994 #define CLOSED -3 /* marks a slot of previously-closed fd */
4997 * Open a file in noclobber mode.
4998 * The code was copied from bash.
5001 noclobberopen(const char *fname)
5004 struct stat finfo, finfo2;
5007 * If the file exists and is a regular file, return an error
5010 r = stat(fname, &finfo);
5011 if (r == 0 && S_ISREG(finfo.st_mode)) {
5017 * If the file was not present (r != 0), make sure we open it
5018 * exclusively so that if it is created before we open it, our open
5019 * will fail. Make sure that we do not truncate an existing file.
5020 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5021 * file was not a regular file, we leave O_EXCL off.
5024 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5025 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5027 /* If the open failed, return the file descriptor right away. */
5032 * OK, the open succeeded, but the file may have been changed from a
5033 * non-regular file to a regular file between the stat and the open.
5034 * We are assuming that the O_EXCL open handles the case where FILENAME
5035 * did not exist and is symlinked to an existing file between the stat
5040 * If we can open it and fstat the file descriptor, and neither check
5041 * revealed that it was a regular file, and the file has not been
5042 * replaced, return the file descriptor.
5044 if (fstat(fd, &finfo2) == 0
5045 && !S_ISREG(finfo2.st_mode)
5046 && finfo.st_dev == finfo2.st_dev
5047 && finfo.st_ino == finfo2.st_ino
5052 /* The file has been replaced. badness. */
5059 * Handle here documents. Normally we fork off a process to write the
5060 * data to a pipe. If the document is short, we can stuff the data in
5061 * the pipe without forking.
5063 /* openhere needs this forward reference */
5064 static void expandhere(union node *arg, int fd);
5066 openhere(union node *redir)
5072 ash_msg_and_raise_error("pipe call failed");
5073 if (redir->type == NHERE) {
5074 len = strlen(redir->nhere.doc->narg.text);
5075 if (len <= PIPE_BUF) {
5076 full_write(pip[1], redir->nhere.doc->narg.text, len);
5080 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5083 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5084 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5085 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5086 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5087 signal(SIGPIPE, SIG_DFL);
5088 if (redir->type == NHERE)
5089 full_write(pip[1], redir->nhere.doc->narg.text, len);
5091 expandhere(redir->nhere.doc, pip[1]);
5092 _exit(EXIT_SUCCESS);
5100 openredirect(union node *redir)
5105 fname = redir->nfile.expfname;
5106 switch (redir->nfile.type) {
5108 f = open(fname, O_RDONLY);
5113 f = open(fname, O_RDWR|O_CREAT, 0666);
5118 #if ENABLE_ASH_BASH_COMPAT
5121 /* Take care of noclobber mode. */
5123 f = noclobberopen(fname);
5130 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5135 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5143 /* Fall through to eliminate warning. */
5144 /* Our single caller does this itself */
5151 f = openhere(redir);
5157 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5159 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5163 * Copy a file descriptor to be >= to. Returns -1
5164 * if the source file descriptor is closed, EMPTY if there are no unused
5165 * file descriptors left.
5167 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5168 * old code was doing close(to) prior to copyfd() to achieve the same */
5170 COPYFD_EXACT = (int)~(INT_MAX),
5171 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5174 copyfd(int from, int to)
5178 if (to & COPYFD_EXACT) {
5179 to &= ~COPYFD_EXACT;
5181 newfd = dup2(from, to);
5183 newfd = fcntl(from, F_DUPFD, to);
5186 if (errno == EMFILE)
5188 /* Happens when source fd is not open: try "echo >&99" */
5189 ash_msg_and_raise_error("%d: %m", from);
5194 /* Struct def and variable are moved down to the first usage site */
5199 struct redirtab *next;
5202 struct two_fd_t two_fd[];
5204 #define redirlist (G_var.redirlist)
5206 static int need_to_remember(struct redirtab *rp, int fd)
5210 if (!rp) /* remembering was not requested */
5213 for (i = 0; i < rp->pair_count; i++) {
5214 if (rp->two_fd[i].orig == fd) {
5215 /* already remembered */
5222 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5223 static int is_hidden_fd(struct redirtab *rp, int fd)
5226 struct parsefile *pf;
5230 /* Check open scripts' fds */
5233 /* We skip pf_fd == 0 case because of the following case:
5234 * $ ash # running ash interactively
5236 * and in script.sh: "exec 9>&0".
5237 * Even though top-level pf_fd _is_ 0,
5238 * it's still ok to use it: "read" builtin uses it,
5239 * why should we cripple "exec" builtin?
5241 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5249 /* Check saved fds of redirects */
5250 fd |= COPYFD_RESTORE;
5251 for (i = 0; i < rp->pair_count; i++) {
5252 if (rp->two_fd[i].copy == fd) {
5260 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5261 * old file descriptors are stashed away so that the redirection can be
5262 * undone by calling popredir.
5264 /* flags passed to redirect */
5265 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5266 #define REDIR_SAVEFD2 03 /* set preverrout */
5268 redirect(union node *redir, int flags)
5270 struct redirtab *sv;
5275 int copied_fd2 = -1;
5285 if (flags & REDIR_PUSH) {
5286 union node *tmp = redir;
5289 #if ENABLE_ASH_BASH_COMPAT
5290 if (tmp->nfile.type == NTO2)
5293 tmp = tmp->nfile.next;
5295 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5296 sv->next = redirlist;
5297 sv->pair_count = sv_pos;
5299 sv->nullredirs = g_nullredirs - 1;
5301 while (sv_pos > 0) {
5303 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5309 fd = redir->nfile.fd;
5310 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5311 right_fd = redir->ndup.dupfd;
5312 //bb_error_msg("doing %d > %d", fd, right_fd);
5313 /* redirect from/to same file descriptor? */
5316 /* "echo >&10" and 10 is a fd opened to a sh script? */
5317 if (is_hidden_fd(sv, right_fd)) {
5318 errno = EBADF; /* as if it is closed */
5319 ash_msg_and_raise_error("%d: %m", right_fd);
5323 newfd = openredirect(redir); /* always >= 0 */
5325 /* Descriptor wasn't open before redirect.
5326 * Mark it for close in the future */
5327 if (need_to_remember(sv, fd)) {
5328 goto remember_to_close;
5333 #if ENABLE_ASH_BASH_COMPAT
5336 if (need_to_remember(sv, fd)) {
5337 /* Copy old descriptor */
5338 /* Careful to not accidentally "save"
5339 * to the same fd as right side fd in N>&M */
5340 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5341 i = fcntl(fd, F_DUPFD, minfd);
5342 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5343 * are closed in popredir() in the child, preventing them from leaking
5344 * into child. (popredir() also cleans up the mess in case of failures)
5349 /* Strange error (e.g. "too many files" EMFILE?) */
5353 ash_msg_and_raise_error("%d: %m", fd);
5356 /* EBADF: it is not open - good, remember to close it */
5359 } else { /* fd is open, save its copy */
5360 /* "exec fd>&-" should not close fds
5361 * which point to script file(s).
5362 * Force them to be restored afterwards */
5363 if (is_hidden_fd(sv, fd))
5364 i |= COPYFD_RESTORE;
5368 sv->two_fd[sv_pos].orig = fd;
5369 sv->two_fd[sv_pos].copy = i;
5373 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5374 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5375 /* Don't want to trigger debugging */
5379 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5381 } else if (fd != newfd) { /* move newfd to fd */
5382 copyfd(newfd, fd | COPYFD_EXACT);
5383 #if ENABLE_ASH_BASH_COMPAT
5384 if (!(redir->nfile.type == NTO2 && fd == 2))
5388 #if ENABLE_ASH_BASH_COMPAT
5389 if (redir->nfile.type == NTO2 && fd == 1) {
5390 /* We already redirected it to fd 1, now copy it to 2 */
5396 } while ((redir = redir->nfile.next) != NULL);
5399 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5400 preverrout_fd = copied_fd2;
5404 * Undo the effects of the last redirection.
5407 popredir(int drop, int restore)
5409 struct redirtab *rp;
5412 if (--g_nullredirs >= 0 || redirlist == NULL)
5416 for (i = 0; i < rp->pair_count; i++) {
5417 int fd = rp->two_fd[i].orig;
5418 int copy = rp->two_fd[i].copy;
5419 if (copy == CLOSED) {
5424 if (copy != EMPTY) {
5425 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5426 copy &= ~COPYFD_RESTORE;
5428 copyfd(copy, fd | COPYFD_EXACT);
5430 close(copy & ~COPYFD_RESTORE);
5433 redirlist = rp->next;
5434 g_nullredirs = rp->nullredirs;
5440 * Undo all redirections. Called on error or interrupt.
5444 * Discard all saved file descriptors.
5447 clearredir(int drop)
5453 popredir(drop, /*restore:*/ 0);
5458 redirectsafe(union node *redir, int flags)
5461 volatile int saveint;
5462 struct jmploc *volatile savehandler = exception_handler;
5463 struct jmploc jmploc;
5466 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5467 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5469 exception_handler = &jmploc;
5470 redirect(redir, flags);
5472 exception_handler = savehandler;
5473 if (err && exception_type != EXERROR)
5474 longjmp(exception_handler->loc, 1);
5475 RESTORE_INT(saveint);
5480 /* ============ Routines to expand arguments to commands
5482 * We have to deal with backquotes, shell variables, and file metacharacters.
5485 #if ENABLE_SH_MATH_SUPPORT
5487 ash_arith(const char *s)
5489 arith_state_t math_state;
5492 math_state.lookupvar = lookupvar;
5493 math_state.setvar = setvar0;
5494 //math_state.endofname = endofname;
5497 result = arith(&math_state, s);
5498 if (math_state.errmsg)
5499 ash_msg_and_raise_error(math_state.errmsg);
5509 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5510 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5511 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5512 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5513 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5514 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5515 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5516 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5517 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5521 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5522 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5523 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5524 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5525 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5527 /* Add CTLESC when necessary. */
5528 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5529 /* Do not skip NUL characters. */
5530 #define QUOTES_KEEPNUL EXP_TILDE
5533 * Structure specifying which parts of the string should be searched
5534 * for IFS characters.
5537 struct ifsregion *next; /* next region in list */
5538 int begoff; /* offset of start of region */
5539 int endoff; /* offset of end of region */
5540 int nulonly; /* search for nul bytes only */
5544 struct strlist *list;
5545 struct strlist **lastp;
5548 /* output of current string */
5549 static char *expdest;
5550 /* list of back quote expressions */
5551 static struct nodelist *argbackq;
5552 /* first struct in list of ifs regions */
5553 static struct ifsregion ifsfirst;
5554 /* last struct in list */
5555 static struct ifsregion *ifslastp;
5556 /* holds expanded arg list */
5557 static struct arglist exparg;
5562 #if !ENABLE_SH_MATH_SUPPORT
5563 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5564 typedef long arith_t;
5565 # define ARITH_FMT "%ld"
5572 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5573 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5574 STADJUST(len, expdest);
5579 esclen(const char *start, const char *p)
5583 while (p > start && (unsigned char)*--p == CTLESC) {
5590 * Remove any CTLESC characters from a string.
5593 rmescapes(char *str, int flag)
5595 static const char qchars[] ALIGN1 = {
5596 IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
5600 unsigned protect_against_glob;
5602 IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
5604 p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
5610 if (flag & RMESCAPE_ALLOC) {
5611 size_t len = p - str;
5612 size_t fulllen = len + strlen(p) + 1;
5614 if (flag & RMESCAPE_GROW) {
5615 int strloc = str - (char *)stackblock();
5616 r = makestrspace(fulllen, expdest);
5617 /* p and str may be invalidated by makestrspace */
5618 str = (char *)stackblock() + strloc;
5620 } else if (flag & RMESCAPE_HEAP) {
5621 r = ckmalloc(fulllen);
5623 r = stalloc(fulllen);
5627 q = (char *)memcpy(q, str, len) + len;
5632 globbing = flag & RMESCAPE_GLOB;
5633 protect_against_glob = globbing;
5635 if ((unsigned char)*p == CTLQUOTEMARK) {
5636 // Note: both inquotes and protect_against_glob only affect whether
5637 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5638 inquotes = ~inquotes;
5640 protect_against_glob = globbing;
5643 if ((unsigned char)*p == CTLESC) {
5645 if (protect_against_glob) {
5648 } else if (*p == '\\' && !inquotes) {
5649 /* naked back slash */
5650 protect_against_glob = 0;
5653 #if ENABLE_ASH_BASH_COMPAT
5654 else if (*p == '/' && slash) {
5655 /* stop handling globbing and mark location of slash */
5656 globbing = slash = 0;
5660 protect_against_glob = globbing;
5665 if (flag & RMESCAPE_GROW) {
5667 STADJUST(q - r + 1, expdest);
5671 #define pmatch(a, b) !fnmatch((a), (b), 0)
5674 * Prepare a pattern for a expmeta (internal glob(3)) call.
5676 * Returns an stalloced string.
5679 preglob(const char *pattern, int flag)
5681 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5685 * Put a string on the stack.
5688 memtodest(const char *p, size_t len, int syntax, int quotes)
5695 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5698 unsigned char c = *p++;
5700 int n = SIT(c, syntax);
5701 if ((quotes & QUOTES_ESC) &&
5703 (((quotes & EXP_FULL) || syntax != BASESYNTAX) &&
5706 } else if (!(quotes & QUOTES_KEEPNUL))
5715 strtodest(const char *p, int syntax, int quotes)
5717 size_t len = strlen(p);
5718 memtodest(p, len, syntax, quotes);
5723 * Record the fact that we have to scan this region of the
5724 * string for IFS characters.
5727 recordregion(int start, int end, int nulonly)
5729 struct ifsregion *ifsp;
5731 if (ifslastp == NULL) {
5735 ifsp = ckzalloc(sizeof(*ifsp));
5736 /*ifsp->next = NULL; - ckzalloc did it */
5737 ifslastp->next = ifsp;
5741 ifslastp->begoff = start;
5742 ifslastp->endoff = end;
5743 ifslastp->nulonly = nulonly;
5747 removerecordregions(int endoff)
5749 if (ifslastp == NULL)
5752 if (ifsfirst.endoff > endoff) {
5753 while (ifsfirst.next) {
5754 struct ifsregion *ifsp;
5756 ifsp = ifsfirst.next->next;
5757 free(ifsfirst.next);
5758 ifsfirst.next = ifsp;
5761 if (ifsfirst.begoff > endoff) {
5764 ifslastp = &ifsfirst;
5765 ifsfirst.endoff = endoff;
5770 ifslastp = &ifsfirst;
5771 while (ifslastp->next && ifslastp->next->begoff < endoff)
5772 ifslastp = ifslastp->next;
5773 while (ifslastp->next) {
5774 struct ifsregion *ifsp;
5776 ifsp = ifslastp->next->next;
5777 free(ifslastp->next);
5778 ifslastp->next = ifsp;
5781 if (ifslastp->endoff > endoff)
5782 ifslastp->endoff = endoff;
5786 exptilde(char *startp, char *p, int flags)
5792 int quotes = flags & QUOTES_ESC;
5796 while ((c = *++p) != '\0') {
5803 if (flags & EXP_VARTILDE)
5813 if (*name == '\0') {
5814 home = lookupvar("HOME");
5816 pw = getpwnam(name);
5821 if (!home || !*home)
5824 strtodest(home, SQSYNTAX, quotes);
5832 * Execute a command inside back quotes. If it's a builtin command, we
5833 * want to save its output in a block obtained from malloc. Otherwise
5834 * we fork off a subprocess and get the output of the command via a pipe.
5835 * Should be called with interrupts off.
5837 struct backcmd { /* result of evalbackcmd */
5838 int fd; /* file descriptor to read from */
5839 int nleft; /* number of chars in buffer */
5840 char *buf; /* buffer */
5841 struct job *jp; /* job structure for command */
5844 /* These forward decls are needed to use "eval" code for backticks handling: */
5845 static uint8_t back_exitstatus; /* exit status of backquoted command */
5846 #define EV_EXIT 01 /* exit after evaluating tree */
5847 static void evaltree(union node *, int);
5849 static void FAST_FUNC
5850 evalbackcmd(union node *n, struct backcmd *result)
5861 saveherefd = herefd;
5869 ash_msg_and_raise_error("pipe call failed");
5870 jp = makejob(/*n,*/ 1);
5871 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5876 copyfd(pip[1], 1 | COPYFD_EXACT);
5880 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5884 result->fd = pip[0];
5887 herefd = saveherefd;
5889 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5890 result->fd, result->buf, result->nleft, result->jp));
5894 * Expand stuff in backwards quotes.
5897 expbackq(union node *cmd, int flag)
5905 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
5906 struct stackmark smark;
5909 setstackmark(&smark);
5911 startloc = dest - (char *)stackblock();
5913 evalbackcmd(cmd, &in);
5914 popstackmark(&smark);
5921 memtodest(p, i, syntax, flag & QUOTES_ESC);
5925 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
5926 TRACE(("expbackq: read returns %d\n", i));
5935 back_exitstatus = waitforjob(in.jp);
5939 /* Eat all trailing newlines */
5941 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5945 if (!(flag & EXP_QUOTED))
5946 recordregion(startloc, dest - (char *)stackblock(), 0);
5947 TRACE(("evalbackq: size:%d:'%.*s'\n",
5948 (int)((dest - (char *)stackblock()) - startloc),
5949 (int)((dest - (char *)stackblock()) - startloc),
5950 stackblock() + startloc));
5953 #if ENABLE_SH_MATH_SUPPORT
5955 * Expand arithmetic expression. Backup to start of expression,
5956 * evaluate, place result in (backed up) result, adjust string position.
5968 * This routine is slightly over-complicated for
5969 * efficiency. Next we scan backwards looking for the
5970 * start of arithmetic.
5972 start = stackblock();
5979 while ((unsigned char)*p != CTLARI) {
5983 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5988 esc = esclen(start, p);
5998 removerecordregions(begoff);
6002 if (flag & QUOTES_ESC)
6003 rmescapes(p + 1, 0);
6005 len = cvtnum(ash_arith(p + 1));
6007 if (!(flag & EXP_QUOTED))
6008 recordregion(begoff, begoff + len, 0);
6012 /* argstr needs it */
6013 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6016 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6017 * characters to allow for further processing. Otherwise treat
6018 * $@ like $* since no splitting will be performed.
6020 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6021 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6022 * for correct expansion of "B=$A" word.
6025 argstr(char *p, int flags, struct strlist *var_str_list)
6027 static const char spclchars[] ALIGN1 = {
6035 #if ENABLE_SH_MATH_SUPPORT
6040 const char *reject = spclchars;
6041 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6046 if (!(flags & EXP_VARTILDE)) {
6048 } else if (flags & EXP_VARTILDE2) {
6053 if (flags & EXP_TILDE) {
6056 flags &= ~EXP_TILDE;
6060 p = exptilde(p, q, flags);
6063 startloc = expdest - (char *)stackblock();
6067 length += strcspn(p + length, reject);
6071 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6073 /* c == '=' || c == ':' || c == CTLENDARI */
6079 expdest = stack_nputstr(p, length, expdest);
6080 newloc = expdest - (char *)stackblock();
6081 if (breakall && !inquotes && newloc > startloc) {
6082 recordregion(startloc, newloc, 0);
6093 if (flags & EXP_VARTILDE2) {
6097 flags |= EXP_VARTILDE2;
6102 * sort of a hack - expand tildes in variable
6103 * assignments (after the first '=' and after ':'s).
6112 case CTLENDVAR: /* ??? */
6115 inquotes ^= EXP_QUOTED;
6116 /* "$@" syntax adherence hack */
6117 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6118 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6122 if (flags & QUOTES_ESC) {
6133 * Quoted parameter expansion pattern: remove quote
6134 * unless inside inner quotes or we have a literal
6137 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6138 EXP_QPAT && *p != '\\')
6143 TRACE(("argstr: evalvar('%s')\n", p));
6144 p = evalvar(p, flags | inquotes, var_str_list);
6145 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6148 expbackq(argbackq->n, flags | inquotes);
6149 argbackq = argbackq->next;
6151 #if ENABLE_SH_MATH_SUPPORT
6154 expari(flags | inquotes);
6163 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6164 char *pattern, int quotes, int zero)
6173 const char *s = loc2;
6180 match = pmatch(pattern, s);
6185 if (quotes && (unsigned char)*loc == CTLESC)
6194 scanright(char *startp, char *rmesc, char *rmescend,
6195 char *pattern, int quotes, int match_at_start)
6197 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6198 int try2optimize = match_at_start;
6204 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6205 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6206 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6208 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6209 * and on each iteration they go back two/one char until they reach the beginning.
6210 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6212 /* TODO: document in what other circumstances we are called. */
6214 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6217 const char *s = loc2;
6218 if (match_at_start) {
6222 match = pmatch(pattern, s);
6223 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6227 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6229 /* Maybe we can optimize this:
6230 * if pattern ends with unescaped *, we can avoid checking
6231 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6232 * it wont match truncated "raw_value_of_" strings too.
6234 unsigned plen = strlen(pattern);
6235 /* Does it end with "*"? */
6236 if (plen != 0 && pattern[--plen] == '*') {
6237 /* "xxxx*" is not escaped */
6238 /* "xxx\*" is escaped */
6239 /* "xx\\*" is not escaped */
6240 /* "x\\\*" is escaped */
6242 while (plen != 0 && pattern[--plen] == '\\')
6245 break; /* ends with unescaped "*" */
6253 esc = esclen(startp, loc);
6264 static void varunset(const char *, const char *, const char *, int) NORETURN;
6266 varunset(const char *end, const char *var, const char *umsg, int varflags)
6272 msg = "parameter not set";
6274 if ((unsigned char)*end == CTLENDVAR) {
6275 if (varflags & VSNUL)
6281 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6285 subevalvar(char *p, char *varname, int strloc, int subtype,
6286 int startloc, int varflags, int flag, struct strlist *var_str_list)
6288 struct nodelist *saveargbackq = argbackq;
6289 int quotes = flag & QUOTES_ESC;
6292 char *rmesc, *rmescend;
6294 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6295 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6296 int saveherefd = herefd;
6297 int amount, resetloc;
6298 IF_ASH_BASH_COMPAT(int workloc;)
6300 char *(*scan)(char*, char*, char*, char*, int, int);
6302 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6303 // p, varname, strloc, subtype, startloc, varflags, quotes);
6306 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6307 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6309 STPUTC('\0', expdest);
6310 herefd = saveherefd;
6311 argbackq = saveargbackq;
6312 startp = (char *)stackblock() + startloc;
6316 setvar0(varname, startp);
6317 amount = startp - expdest;
6318 STADJUST(amount, expdest);
6322 varunset(p, varname, startp, varflags);
6325 #if ENABLE_ASH_BASH_COMPAT
6327 loc = str = stackblock() + strloc;
6328 /* Read POS in ${var:POS:LEN} */
6329 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6330 len = str - startp - 1;
6332 /* *loc != '\0', guaranteed by parser */
6336 /* Adjust the length by the number of escapes */
6337 for (ptr = startp; ptr < (str - 1); ptr++) {
6338 if ((unsigned char)*ptr == CTLESC) {
6346 if (*loc++ == ':') {
6350 /* Skip POS in ${var:POS:LEN} */
6352 while (*loc && *loc != ':') {
6354 * bash complains on: var=qwe; echo ${var:1a:123}
6356 ash_msg_and_raise_error(msg_illnum, str);
6360 if (*loc++ == ':') {
6365 /* ${VAR:$((-n)):l} starts n chars from the end */
6366 pos = orig_len + pos;
6368 if ((unsigned)pos >= orig_len) {
6369 /* apart from obvious ${VAR:999999:l},
6370 * covers ${VAR:$((-9999999)):l} - result is ""
6376 if (len > (orig_len - pos))
6377 len = orig_len - pos;
6379 for (str = startp; pos; str++, pos--) {
6380 if (quotes && (unsigned char)*str == CTLESC)
6383 for (loc = startp; len; len--) {
6384 if (quotes && (unsigned char)*str == CTLESC)
6389 amount = loc - expdest;
6390 STADJUST(amount, expdest);
6395 resetloc = expdest - (char *)stackblock();
6397 /* We'll comeback here if we grow the stack while handling
6398 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6399 * stack will need rebasing, and we'll need to remove our work
6402 IF_ASH_BASH_COMPAT(restart:)
6404 amount = expdest - ((char *)stackblock() + resetloc);
6405 STADJUST(-amount, expdest);
6406 startp = (char *)stackblock() + startloc;
6409 rmescend = (char *)stackblock() + strloc;
6411 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6412 if (rmesc != startp) {
6414 startp = (char *)stackblock() + startloc;
6418 str = (char *)stackblock() + strloc;
6420 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6421 * The result is a_\_z_c (not a\_\_z_c)!
6423 * The search pattern and replace string treat backslashes differently!
6424 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6425 * and string. It's only used on the first call.
6427 preglob(str, IF_ASH_BASH_COMPAT(
6428 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6429 RMESCAPE_SLASH :) 0);
6431 #if ENABLE_ASH_BASH_COMPAT
6432 workloc = expdest - (char *)stackblock();
6433 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6437 if ((repl=strchr(str, CTLESC)))
6442 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6444 /* If there's no pattern to match, return the expansion unmolested */
6453 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6454 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6456 /* No match, advance */
6457 char *restart_detect = stackblock();
6459 STPUTC(*idx, expdest);
6460 if (quotes && (unsigned char)*idx == CTLESC) {
6463 STPUTC(*idx, expdest);
6465 if (stackblock() != restart_detect)
6470 /* continue; - prone to quadratic behavior, smarter code: */
6473 if (str[0] == '*') {
6474 /* Pattern is "*foo". If "*foo" does not match "long_string",
6475 * it would never match "ong_string" etc, no point in trying.
6482 if (subtype == VSREPLACEALL) {
6484 if (quotes && (unsigned char)*idx == CTLESC)
6493 //bb_error_msg("repl:'%s'", repl);
6494 for (loc = (char*)repl; *loc; loc++) {
6495 char *restart_detect = stackblock();
6496 if (quotes && *loc == '\\') {
6497 STPUTC(CTLESC, expdest);
6500 STPUTC(*loc, expdest);
6501 if (stackblock() != restart_detect)
6506 if (subtype == VSREPLACE) {
6507 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6509 char *restart_detect = stackblock();
6510 STPUTC(*idx, expdest);
6511 if (stackblock() != restart_detect)
6520 /* We've put the replaced text into a buffer at workloc, now
6521 * move it to the right place and adjust the stack.
6523 STPUTC('\0', expdest);
6524 startp = (char *)stackblock() + startloc;
6525 memmove(startp, (char *)stackblock() + workloc, len + 1);
6526 //bb_error_msg("startp:'%s'", startp);
6527 amount = expdest - (startp + len);
6528 STADJUST(-amount, expdest);
6531 #endif /* ENABLE_ASH_BASH_COMPAT */
6533 subtype -= VSTRIMRIGHT;
6535 if (subtype < 0 || subtype > 7)
6538 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6539 zero = subtype >> 1;
6540 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6541 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6543 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6546 memmove(startp, loc, str - loc);
6547 loc = startp + (str - loc) - 1;
6550 amount = loc - expdest;
6551 STADJUST(amount, expdest);
6557 * Add the value of a specialized variable to the stack string.
6558 * name parameter (examples):
6559 * ash -c 'echo $1' name:'1='
6560 * ash -c 'echo $qwe' name:'qwe='
6561 * ash -c 'echo $$' name:'$='
6562 * ash -c 'echo ${$}' name:'$='
6563 * ash -c 'echo ${$##q}' name:'$=q'
6564 * ash -c 'echo ${#$}' name:'$='
6565 * note: examples with bad shell syntax:
6566 * ash -c 'echo ${#$1}' name:'$=1'
6567 * ash -c 'echo ${#1#}' name:'1=#'
6569 static NOINLINE ssize_t
6570 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6577 int quoted = flags & EXP_QUOTED;
6578 int subtype = varflags & VSTYPE;
6579 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6580 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6581 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6583 sep = quoted ? ((flags & EXP_FULL) << CHAR_BIT) : 0;
6593 num = shellparam.nparam;
6601 goto check_1char_name;
6603 expdest = makestrspace(NOPTS, expdest);
6604 for (i = NOPTS - 1; i >= 0; i--) {
6606 USTPUTC(optletters(i), expdest);
6612 /* handles cases similar to ${#$1} */
6613 if (name[2] != '\0')
6614 raise_error_syntax("bad substitution");
6621 if (quoted && (flags & EXP_FULL)) {
6622 /* note: this is not meant as PEOF value */
6623 sep = 1 << CHAR_BIT;
6628 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6634 while ((p = *ap++) != NULL) {
6635 len += strtodest(p, syntax, quotes);
6639 memtodest(&sepc, 1, syntax, quotes);
6643 } /* case '@' and '*' */
6654 num = atoi(name); /* number(name) fails on ${N#str} etc */
6655 if (num < 0 || num > shellparam.nparam)
6657 p = num ? shellparam.p[num - 1] : arg0;
6660 /* NB: name has form "VAR=..." */
6662 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6663 * which should be considered before we check variables. */
6665 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6669 str = var_str_list->text;
6670 eq = strchr(str, '=');
6671 if (!eq) /* stop at first non-assignment */
6674 if (name_len == (unsigned)(eq - str)
6675 && strncmp(str, name, name_len) == 0
6678 /* goto value; - WRONG! */
6679 /* think "A=1 A=2 B=$A" */
6681 var_str_list = var_str_list->next;
6682 } while (var_str_list);
6686 p = lookupvar(name);
6691 len = strtodest(p, syntax, quotes);
6692 #if ENABLE_UNICODE_SUPPORT
6693 if (subtype == VSLENGTH && len > 0) {
6694 reinit_unicode_for_ash();
6695 if (unicode_status == UNICODE_ON) {
6696 len = unicode_strlen(p);
6704 STADJUST(-len, expdest);
6709 * Expand a variable, and return a pointer to the next character in the
6713 evalvar(char *p, int flags, struct strlist *var_str_list)
6724 varflags = (unsigned char) *p++;
6725 subtype = varflags & VSTYPE;
6726 quoted = flags & EXP_QUOTED;
6728 easy = (!quoted || (*var == '@' && shellparam.nparam));
6729 startloc = expdest - (char *)stackblock();
6730 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6733 varlen = varvalue(var, varflags, flags, var_str_list);
6734 if (varflags & VSNUL)
6737 if (subtype == VSPLUS) {
6738 varlen = -1 - varlen;
6742 if (subtype == VSMINUS) {
6747 flags | EXP_TILDE | EXP_WORD,
6757 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6759 if (subevalvar(p, var, /* strloc: */ 0,
6760 subtype, startloc, varflags,
6761 /* quotes: */ flags & ~QUOTES_ESC,
6766 * Remove any recorded regions beyond
6769 removerecordregions(startloc);
6779 if (varlen < 0 && uflag)
6780 varunset(p, var, 0, 0);
6782 if (subtype == VSLENGTH) {
6783 cvtnum(varlen > 0 ? varlen : 0);
6787 if (subtype == VSNORMAL) {
6798 case VSTRIMRIGHTMAX:
6799 #if ENABLE_ASH_BASH_COMPAT
6812 * Terminate the string and start recording the pattern
6815 STPUTC('\0', expdest);
6816 patloc = expdest - (char *)stackblock();
6817 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6818 startloc, varflags, flags, var_str_list)) {
6819 int amount = expdest - (
6820 (char *)stackblock() + patloc - 1
6822 STADJUST(-amount, expdest);
6824 /* Remove any recorded regions beyond start of variable */
6825 removerecordregions(startloc);
6827 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6831 if (subtype != VSNORMAL) { /* skip to end of alternative */
6834 unsigned char c = *p++;
6837 else if (c == CTLBACKQ) {
6839 argbackq = argbackq->next;
6840 } else if (c == CTLVAR) {
6841 if ((*p++ & VSTYPE) != VSNORMAL)
6843 } else if (c == CTLENDVAR) {
6853 * Break the argument string into pieces based upon IFS and add the
6854 * strings to the argument list. The regions of the string to be
6855 * searched for IFS characters have been stored by recordregion.
6858 ifsbreakup(char *string, struct arglist *arglist)
6860 struct ifsregion *ifsp;
6865 const char *ifs, *realifs;
6870 if (ifslastp != NULL) {
6873 realifs = ifsset() ? ifsval() : defifs;
6876 p = string + ifsp->begoff;
6877 nulonly = ifsp->nulonly;
6878 ifs = nulonly ? nullstr : realifs;
6880 while (p < string + ifsp->endoff) {
6882 if ((unsigned char)*p == CTLESC)
6884 if (!strchr(ifs, *p)) {
6889 ifsspc = (strchr(defifs, *p) != NULL);
6890 /* Ignore IFS whitespace at start */
6891 if (q == start && ifsspc) {
6897 sp = stzalloc(sizeof(*sp));
6899 *arglist->lastp = sp;
6900 arglist->lastp = &sp->next;
6904 if (p >= string + ifsp->endoff) {
6908 if ((unsigned char)*p == CTLESC)
6910 if (strchr(ifs, *p) == NULL) {
6914 if (strchr(defifs, *p) == NULL) {
6929 } while (ifsp != NULL);
6938 sp = stzalloc(sizeof(*sp));
6940 *arglist->lastp = sp;
6941 arglist->lastp = &sp->next;
6947 struct ifsregion *p;
6952 struct ifsregion *ifsp;
6958 ifsfirst.next = NULL;
6963 * Add a file name to the list.
6966 addfname(const char *name)
6970 sp = stzalloc(sizeof(*sp));
6971 sp->text = ststrdup(name);
6973 exparg.lastp = &sp->next;
6977 * Do metacharacter (i.e. *, ?, [...]) expansion.
6980 expmeta(char *expdir, char *enddir, char *name)
6996 for (p = name; esc = 0, *p; p += esc + 1) {
6997 if (*p == '*' || *p == '?')
6999 else if (*p == '[') {
7006 if (*q == '/' || *q == '\0')
7016 if (p[esc] == '/') {
7019 start = p + esc + 1;
7023 if (metaflag == 0) { /* we've reached the end of the file name */
7024 if (enddir != expdir)
7032 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7043 } while (p < start);
7045 if (enddir == expdir) {
7047 } else if (enddir == expdir + 1 && *expdir == '/') {
7056 if (enddir != expdir)
7058 if (*endname == 0) {
7071 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7072 if (dp->d_name[0] == '.' && !matchdot)
7074 if (pmatch(start, dp->d_name)) {
7076 strcpy(enddir, dp->d_name);
7079 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7082 expmeta(expdir, p, endname);
7088 endname[-esc - 1] = esc ? '\\' : '/';
7091 static struct strlist *
7092 msort(struct strlist *list, int len)
7094 struct strlist *p, *q = NULL;
7095 struct strlist **lpp;
7103 for (n = half; --n >= 0;) {
7107 q->next = NULL; /* terminate first half of list */
7108 q = msort(list, half); /* sort first half of list */
7109 p = msort(p, len - half); /* sort second half */
7112 #if ENABLE_LOCALE_SUPPORT
7113 if (strcoll(p->text, q->text) < 0)
7115 if (strcmp(p->text, q->text) < 0)
7139 * Sort the results of file name expansion. It calculates the number of
7140 * strings to sort and then calls msort (short for merge sort) to do the
7143 static struct strlist *
7144 expsort(struct strlist *str)
7150 for (sp = str; sp; sp = sp->next)
7152 return msort(str, len);
7156 expandmeta(struct strlist *str /*, int flag*/)
7158 static const char metachars[] ALIGN1 = {
7161 /* TODO - EXP_REDIR */
7165 struct strlist **savelastp;
7171 if (!strpbrk(str->text, metachars))
7173 savelastp = exparg.lastp;
7176 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7178 int i = strlen(str->text);
7179 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7181 expmeta(expdir, expdir, p);
7186 if (exparg.lastp == savelastp) {
7191 *exparg.lastp = str;
7192 rmescapes(str->text, 0);
7193 exparg.lastp = &str->next;
7195 *exparg.lastp = NULL;
7196 *savelastp = sp = expsort(*savelastp);
7197 while (sp->next != NULL)
7199 exparg.lastp = &sp->next;
7206 * Perform variable substitution and command substitution on an argument,
7207 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7208 * perform splitting and file name expansion. When arglist is NULL, perform
7209 * here document expansion.
7212 expandarg(union node *arg, struct arglist *arglist, int flag)
7217 argbackq = arg->narg.backquote;
7218 STARTSTACKSTR(expdest);
7219 ifsfirst.next = NULL;
7221 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7222 argstr(arg->narg.text, flag,
7223 /* var_str_list: */ arglist ? arglist->list : NULL);
7224 p = _STPUTC('\0', expdest);
7226 if (arglist == NULL) {
7227 return; /* here document expanded */
7229 p = grabstackstr(p);
7230 TRACE(("expandarg: p:'%s'\n", p));
7231 exparg.lastp = &exparg.list;
7235 if (flag & EXP_FULL) {
7236 ifsbreakup(p, &exparg);
7237 *exparg.lastp = NULL;
7238 exparg.lastp = &exparg.list;
7239 expandmeta(exparg.list /*, flag*/);
7241 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7243 TRACE(("expandarg: rmescapes:'%s'\n", p));
7245 sp = stzalloc(sizeof(*sp));
7248 exparg.lastp = &sp->next;
7252 *exparg.lastp = NULL;
7254 *arglist->lastp = exparg.list;
7255 arglist->lastp = exparg.lastp;
7260 * Expand shell variables and backquotes inside a here document.
7263 expandhere(union node *arg, int fd)
7266 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7267 full_write(fd, stackblock(), expdest - (char *)stackblock());
7271 * Returns true if the pattern matches the string.
7274 patmatch(char *pattern, const char *string)
7276 return pmatch(preglob(pattern, 0), string);
7280 * See if a pattern matches in a case statement.
7283 casematch(union node *pattern, char *val)
7285 struct stackmark smark;
7288 setstackmark(&smark);
7289 argbackq = pattern->narg.backquote;
7290 STARTSTACKSTR(expdest);
7292 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7293 /* var_str_list: */ NULL);
7294 STACKSTRNUL(expdest);
7295 result = patmatch(stackblock(), val);
7296 popstackmark(&smark);
7301 /* ============ find_command */
7305 int (*builtin)(int, char **) FAST_FUNC;
7306 /* unsigned flags; */
7308 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7309 /* "regular" builtins always take precedence over commands,
7310 * regardless of PATH=....%builtin... position */
7311 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7312 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7315 smallint cmdtype; /* CMDxxx */
7318 /* index >= 0 for commands without path (slashes) */
7319 /* (TODO: what exactly does the value mean? PATH position?) */
7320 /* index == -1 for commands with slashes */
7321 /* index == (-2 - applet_no) for NOFORK applets */
7322 const struct builtincmd *cmd;
7323 struct funcnode *func;
7326 /* values of cmdtype */
7327 #define CMDUNKNOWN -1 /* no entry in table for command */
7328 #define CMDNORMAL 0 /* command is an executable program */
7329 #define CMDFUNCTION 1 /* command is a shell function */
7330 #define CMDBUILTIN 2 /* command is a shell builtin */
7332 /* action to find_command() */
7333 #define DO_ERR 0x01 /* prints errors */
7334 #define DO_ABS 0x02 /* checks absolute paths */
7335 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7336 #define DO_ALTPATH 0x08 /* using alternate path */
7337 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7339 static void find_command(char *, struct cmdentry *, int, const char *);
7342 /* ============ Hashing commands */
7345 * When commands are first encountered, they are entered in a hash table.
7346 * This ensures that a full path search will not have to be done for them
7347 * on each invocation.
7349 * We should investigate converting to a linear search, even though that
7350 * would make the command name "hash" a misnomer.
7354 struct tblentry *next; /* next entry in hash chain */
7355 union param param; /* definition of builtin function */
7356 smallint cmdtype; /* CMDxxx */
7357 char rehash; /* if set, cd done since entry created */
7358 char cmdname[1]; /* name of command */
7361 static struct tblentry **cmdtable;
7362 #define INIT_G_cmdtable() do { \
7363 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7366 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7370 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7372 #if ENABLE_FEATURE_SH_STANDALONE
7373 if (applet_no >= 0) {
7374 if (APPLET_IS_NOEXEC(applet_no)) {
7378 run_applet_no_and_exit(applet_no, argv);
7380 /* re-exec ourselves with the new arguments */
7381 execve(bb_busybox_exec_path, argv, envp);
7382 /* If they called chroot or otherwise made the binary no longer
7383 * executable, fall through */
7390 execve(cmd, argv, envp);
7391 } while (errno == EINTR);
7393 execve(cmd, argv, envp);
7395 if (cmd == (char*) bb_busybox_exec_path) {
7396 /* We already visited ENOEXEC branch below, don't do it again */
7397 //TODO: try execve(initial_argv0_of_shell, argv, envp) before giving up?
7401 if (errno == ENOEXEC) {
7402 /* Run "cmd" as a shell script:
7403 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7404 * "If the execve() function fails with ENOEXEC, the shell
7405 * shall execute a command equivalent to having a shell invoked
7406 * with the command name as its first operand,
7407 * with any remaining arguments passed to the new shell"
7409 * That is, do not use $SHELL, user's shell, or /bin/sh;
7410 * just call ourselves.
7412 * Note that bash reads ~80 chars of the file, and if it sees
7413 * a zero byte before it sees newline, it doesn't try to
7414 * interpret it, but fails with "cannot execute binary file"
7415 * message and exit code 126. For one, this prevents attempts
7416 * to interpret foreign ELF binaries as shell scripts.
7421 for (ap = argv; *ap; ap++)
7423 new = ckmalloc((ap - argv + 2) * sizeof(new[0]));
7424 new[0] = (char*) "ash";
7427 while ((*ap++ = *++argv) != NULL)
7429 cmd = (char*) bb_busybox_exec_path;
7436 * Exec a program. Never returns. If you change this routine, you may
7437 * have to change the find_command routine as well.
7439 static void shellexec(char **, const char *, int) NORETURN;
7441 shellexec(char **argv, const char *path, int idx)
7447 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7449 clearredir(/*drop:*/ 1);
7450 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7451 if (strchr(argv[0], '/') != NULL
7452 #if ENABLE_FEATURE_SH_STANDALONE
7453 || (applet_no = find_applet_by_name(argv[0])) >= 0
7456 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7457 if (applet_no >= 0) {
7458 /* We tried execing ourself, but it didn't work.
7459 * Maybe /proc/self/exe doesn't exist?
7468 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7469 if (--idx < 0 && pathopt == NULL) {
7470 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7471 if (errno != ENOENT && errno != ENOTDIR)
7478 /* Map to POSIX errors */
7490 exitstatus = exerrno;
7491 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7492 argv[0], e, suppress_int));
7493 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7498 printentry(struct tblentry *cmdp)
7504 idx = cmdp->param.index;
7507 name = path_advance(&path, cmdp->cmdname);
7509 } while (--idx >= 0);
7510 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7514 * Clear out command entries. The argument specifies the first entry in
7515 * PATH which has changed.
7518 clearcmdentry(int firstchange)
7520 struct tblentry **tblp;
7521 struct tblentry **pp;
7522 struct tblentry *cmdp;
7525 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7527 while ((cmdp = *pp) != NULL) {
7528 if ((cmdp->cmdtype == CMDNORMAL &&
7529 cmdp->param.index >= firstchange)
7530 || (cmdp->cmdtype == CMDBUILTIN &&
7531 builtinloc >= firstchange)
7544 * Locate a command in the command hash table. If "add" is nonzero,
7545 * add the command to the table if it is not already present. The
7546 * variable "lastcmdentry" is set to point to the address of the link
7547 * pointing to the entry, so that delete_cmd_entry can delete the
7550 * Interrupts must be off if called with add != 0.
7552 static struct tblentry **lastcmdentry;
7554 static struct tblentry *
7555 cmdlookup(const char *name, int add)
7557 unsigned int hashval;
7559 struct tblentry *cmdp;
7560 struct tblentry **pp;
7563 hashval = (unsigned char)*p << 4;
7565 hashval += (unsigned char)*p++;
7567 pp = &cmdtable[hashval % CMDTABLESIZE];
7568 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7569 if (strcmp(cmdp->cmdname, name) == 0)
7573 if (add && cmdp == NULL) {
7574 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7576 /* + 1 - already done because
7577 * tblentry::cmdname is char[1] */);
7578 /*cmdp->next = NULL; - ckzalloc did it */
7579 cmdp->cmdtype = CMDUNKNOWN;
7580 strcpy(cmdp->cmdname, name);
7587 * Delete the command entry returned on the last lookup.
7590 delete_cmd_entry(void)
7592 struct tblentry *cmdp;
7595 cmdp = *lastcmdentry;
7596 *lastcmdentry = cmdp->next;
7597 if (cmdp->cmdtype == CMDFUNCTION)
7598 freefunc(cmdp->param.func);
7604 * Add a new command entry, replacing any existing command entry for
7605 * the same name - except special builtins.
7608 addcmdentry(char *name, struct cmdentry *entry)
7610 struct tblentry *cmdp;
7612 cmdp = cmdlookup(name, 1);
7613 if (cmdp->cmdtype == CMDFUNCTION) {
7614 freefunc(cmdp->param.func);
7616 cmdp->cmdtype = entry->cmdtype;
7617 cmdp->param = entry->u;
7621 static int FAST_FUNC
7622 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7624 struct tblentry **pp;
7625 struct tblentry *cmdp;
7627 struct cmdentry entry;
7630 if (nextopt("r") != '\0') {
7635 if (*argptr == NULL) {
7636 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7637 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7638 if (cmdp->cmdtype == CMDNORMAL)
7646 while ((name = *argptr) != NULL) {
7647 cmdp = cmdlookup(name, 0);
7649 && (cmdp->cmdtype == CMDNORMAL
7650 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7654 find_command(name, &entry, DO_ERR, pathval());
7655 if (entry.cmdtype == CMDUNKNOWN)
7663 * Called when a cd is done. Marks all commands so the next time they
7664 * are executed they will be rehashed.
7669 struct tblentry **pp;
7670 struct tblentry *cmdp;
7672 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7673 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7674 if (cmdp->cmdtype == CMDNORMAL
7675 || (cmdp->cmdtype == CMDBUILTIN
7676 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7686 * Fix command hash table when PATH changed.
7687 * Called before PATH is changed. The argument is the new value of PATH;
7688 * pathval() still returns the old value at this point.
7689 * Called with interrupts off.
7691 static void FAST_FUNC
7692 changepath(const char *new)
7700 firstchange = 9999; /* assume no change */
7706 if ((*old == '\0' && *new == ':')
7707 || (*old == ':' && *new == '\0')
7711 old = new; /* ignore subsequent differences */
7715 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7722 if (builtinloc < 0 && idx_bltin >= 0)
7723 builtinloc = idx_bltin; /* zap builtins */
7724 if (builtinloc >= 0 && idx_bltin < 0)
7726 clearcmdentry(firstchange);
7727 builtinloc = idx_bltin;
7752 #if ENABLE_ASH_BASH_COMPAT
7763 typedef smallint token_id_t;
7765 /* first char is indicating which tokens mark the end of a list */
7766 static const char *const tokname_array[] = {
7780 #define KWDOFFSET 13
7781 /* the following are keywords */
7791 #if ENABLE_ASH_BASH_COMPAT
7803 /* Wrapper around strcmp for qsort/bsearch/... */
7805 pstrcmp(const void *a, const void *b)
7807 return strcmp((char*) a, (*(char**) b) + 1);
7810 static const char *const *
7811 findkwd(const char *s)
7813 return bsearch(s, tokname_array + KWDOFFSET,
7814 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7815 sizeof(tokname_array[0]), pstrcmp);
7819 * Locate and print what a word is...
7822 describe_command(char *command, const char *path, int describe_command_verbose)
7824 struct cmdentry entry;
7825 struct tblentry *cmdp;
7826 #if ENABLE_ASH_ALIAS
7827 const struct alias *ap;
7830 path = path ? path : pathval();
7832 if (describe_command_verbose) {
7836 /* First look at the keywords */
7837 if (findkwd(command)) {
7838 out1str(describe_command_verbose ? " is a shell keyword" : command);
7842 #if ENABLE_ASH_ALIAS
7843 /* Then look at the aliases */
7844 ap = lookupalias(command, 0);
7846 if (!describe_command_verbose) {
7851 out1fmt(" is an alias for %s", ap->val);
7855 /* Then check if it is a tracked alias */
7856 cmdp = cmdlookup(command, 0);
7858 entry.cmdtype = cmdp->cmdtype;
7859 entry.u = cmdp->param;
7861 /* Finally use brute force */
7862 find_command(command, &entry, DO_ABS, path);
7865 switch (entry.cmdtype) {
7867 int j = entry.u.index;
7873 p = path_advance(&path, command);
7877 if (describe_command_verbose) {
7879 (cmdp ? " a tracked alias for" : nullstr), p
7888 if (describe_command_verbose) {
7889 out1str(" is a shell function");
7896 if (describe_command_verbose) {
7897 out1fmt(" is a %sshell builtin",
7898 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7899 "special " : nullstr
7907 if (describe_command_verbose) {
7908 out1str(": not found\n");
7917 static int FAST_FUNC
7918 typecmd(int argc UNUSED_PARAM, char **argv)
7924 /* type -p ... ? (we don't bother checking for 'p') */
7925 if (argv[1] && argv[1][0] == '-') {
7930 err |= describe_command(argv[i++], NULL, verbose);
7935 #if ENABLE_ASH_CMDCMD
7936 static int FAST_FUNC
7937 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7944 const char *path = NULL;
7946 while ((c = nextopt("pvV")) != '\0')
7948 verify |= VERIFY_VERBOSE;
7950 verify |= VERIFY_BRIEF;
7956 path = bb_default_path;
7957 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7958 if (verify && (*argptr != NULL)) {
7959 return describe_command(*argptr, path, verify - VERIFY_BRIEF);
7967 /* ============ eval.c */
7969 static int funcblocksize; /* size of structures in function */
7970 static int funcstringsize; /* size of strings in node */
7971 static void *funcblock; /* block to allocate function from */
7972 static char *funcstring; /* block to allocate strings from */
7974 /* flags in argument to evaltree */
7975 #define EV_EXIT 01 /* exit after evaluating tree */
7976 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7977 #define EV_BACKCMD 04 /* command executing within back quotes */
7979 static const uint8_t nodesize[N_NUMBER] = {
7980 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7981 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7982 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7983 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7984 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7985 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7986 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7987 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7988 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7989 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7990 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7991 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7992 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7993 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7994 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7995 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7996 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7997 #if ENABLE_ASH_BASH_COMPAT
7998 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8000 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8001 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8002 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8003 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8004 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8005 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8006 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8007 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8008 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8011 static void calcsize(union node *n);
8014 sizenodelist(struct nodelist *lp)
8017 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8024 calcsize(union node *n)
8028 funcblocksize += nodesize[n->type];
8031 calcsize(n->ncmd.redirect);
8032 calcsize(n->ncmd.args);
8033 calcsize(n->ncmd.assign);
8036 sizenodelist(n->npipe.cmdlist);
8041 calcsize(n->nredir.redirect);
8042 calcsize(n->nredir.n);
8049 calcsize(n->nbinary.ch2);
8050 calcsize(n->nbinary.ch1);
8053 calcsize(n->nif.elsepart);
8054 calcsize(n->nif.ifpart);
8055 calcsize(n->nif.test);
8058 funcstringsize += strlen(n->nfor.var) + 1;
8059 calcsize(n->nfor.body);
8060 calcsize(n->nfor.args);
8063 calcsize(n->ncase.cases);
8064 calcsize(n->ncase.expr);
8067 calcsize(n->nclist.body);
8068 calcsize(n->nclist.pattern);
8069 calcsize(n->nclist.next);
8073 sizenodelist(n->narg.backquote);
8074 funcstringsize += strlen(n->narg.text) + 1;
8075 calcsize(n->narg.next);
8078 #if ENABLE_ASH_BASH_COMPAT
8085 calcsize(n->nfile.fname);
8086 calcsize(n->nfile.next);
8090 calcsize(n->ndup.vname);
8091 calcsize(n->ndup.next);
8095 calcsize(n->nhere.doc);
8096 calcsize(n->nhere.next);
8099 calcsize(n->nnot.com);
8105 nodeckstrdup(char *s)
8107 char *rtn = funcstring;
8109 strcpy(funcstring, s);
8110 funcstring += strlen(s) + 1;
8114 static union node *copynode(union node *);
8116 static struct nodelist *
8117 copynodelist(struct nodelist *lp)
8119 struct nodelist *start;
8120 struct nodelist **lpp;
8125 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8126 (*lpp)->n = copynode(lp->n);
8128 lpp = &(*lpp)->next;
8135 copynode(union node *n)
8142 funcblock = (char *) funcblock + nodesize[n->type];
8146 new->ncmd.redirect = copynode(n->ncmd.redirect);
8147 new->ncmd.args = copynode(n->ncmd.args);
8148 new->ncmd.assign = copynode(n->ncmd.assign);
8151 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8152 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8157 new->nredir.redirect = copynode(n->nredir.redirect);
8158 new->nredir.n = copynode(n->nredir.n);
8165 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8166 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8169 new->nif.elsepart = copynode(n->nif.elsepart);
8170 new->nif.ifpart = copynode(n->nif.ifpart);
8171 new->nif.test = copynode(n->nif.test);
8174 new->nfor.var = nodeckstrdup(n->nfor.var);
8175 new->nfor.body = copynode(n->nfor.body);
8176 new->nfor.args = copynode(n->nfor.args);
8179 new->ncase.cases = copynode(n->ncase.cases);
8180 new->ncase.expr = copynode(n->ncase.expr);
8183 new->nclist.body = copynode(n->nclist.body);
8184 new->nclist.pattern = copynode(n->nclist.pattern);
8185 new->nclist.next = copynode(n->nclist.next);
8189 new->narg.backquote = copynodelist(n->narg.backquote);
8190 new->narg.text = nodeckstrdup(n->narg.text);
8191 new->narg.next = copynode(n->narg.next);
8194 #if ENABLE_ASH_BASH_COMPAT
8201 new->nfile.fname = copynode(n->nfile.fname);
8202 new->nfile.fd = n->nfile.fd;
8203 new->nfile.next = copynode(n->nfile.next);
8207 new->ndup.vname = copynode(n->ndup.vname);
8208 new->ndup.dupfd = n->ndup.dupfd;
8209 new->ndup.fd = n->ndup.fd;
8210 new->ndup.next = copynode(n->ndup.next);
8214 new->nhere.doc = copynode(n->nhere.doc);
8215 new->nhere.fd = n->nhere.fd;
8216 new->nhere.next = copynode(n->nhere.next);
8219 new->nnot.com = copynode(n->nnot.com);
8222 new->type = n->type;
8227 * Make a copy of a parse tree.
8229 static struct funcnode *
8230 copyfunc(union node *n)
8235 funcblocksize = offsetof(struct funcnode, n);
8238 blocksize = funcblocksize;
8239 f = ckmalloc(blocksize + funcstringsize);
8240 funcblock = (char *) f + offsetof(struct funcnode, n);
8241 funcstring = (char *) f + blocksize;
8248 * Define a shell function.
8251 defun(char *name, union node *func)
8253 struct cmdentry entry;
8256 entry.cmdtype = CMDFUNCTION;
8257 entry.u.func = copyfunc(func);
8258 addcmdentry(name, &entry);
8262 /* Reasons for skipping commands (see comment on breakcmd routine) */
8263 #define SKIPBREAK (1 << 0)
8264 #define SKIPCONT (1 << 1)
8265 #define SKIPFUNC (1 << 2)
8266 #define SKIPFILE (1 << 3)
8267 #define SKIPEVAL (1 << 4)
8268 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8269 static int skipcount; /* number of levels to skip */
8270 static int funcnest; /* depth of function calls */
8271 static int loopnest; /* current loop nesting level */
8273 /* Forward decl way out to parsing code - dotrap needs it */
8274 static int evalstring(char *s, int mask);
8276 /* Called to execute a trap.
8277 * Single callsite - at the end of evaltree().
8278 * If we return non-zero, evaltree raises EXEXIT exception.
8280 * Perhaps we should avoid entering new trap handlers
8281 * while we are executing a trap handler. [is it a TODO?]
8290 savestatus = exitstatus;
8294 TRACE(("dotrap entered\n"));
8295 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8302 /* non-trapped SIGINT is handled separately by raise_interrupt,
8303 * don't upset it by resetting gotsig[SIGINT-1] */
8304 if (sig == SIGINT && !t)
8307 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8311 want_exexit = evalstring(t, SKIPEVAL);
8312 exitstatus = savestatus;
8314 TRACE(("dotrap returns %d\n", want_exexit));
8319 TRACE(("dotrap returns 0\n"));
8323 /* forward declarations - evaluation is fairly recursive business... */
8324 static void evalloop(union node *, int);
8325 static void evalfor(union node *, int);
8326 static void evalcase(union node *, int);
8327 static void evalsubshell(union node *, int);
8328 static void expredir(union node *);
8329 static void evalpipe(union node *, int);
8330 static void evalcommand(union node *, int);
8331 static int evalbltin(const struct builtincmd *, int, char **);
8332 static void prehash(union node *);
8335 * Evaluate a parse tree. The value is left in the global variable
8339 evaltree(union node *n, int flags)
8341 struct jmploc *volatile savehandler = exception_handler;
8342 struct jmploc jmploc;
8344 void (*evalfn)(union node *, int);
8348 SAVE_INT(int_level);
8351 TRACE(("evaltree(NULL) called\n"));
8354 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8356 exception_handler = &jmploc;
8358 int err = setjmp(jmploc.loc);
8360 /* if it was a signal, check for trap handlers */
8361 if (exception_type == EXSIG) {
8362 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8363 exception_type, err));
8366 /* continue on the way out */
8367 TRACE(("exception %d in evaltree, propagating err=%d\n",
8368 exception_type, err));
8369 exception_handler = savehandler;
8370 longjmp(exception_handler->loc, err);
8377 out1fmt("Node type = %d\n", n->type);
8382 evaltree(n->nnot.com, EV_TESTED);
8383 status = !exitstatus;
8386 expredir(n->nredir.redirect);
8387 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8389 evaltree(n->nredir.n, flags & EV_TESTED);
8390 status = exitstatus;
8392 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8395 evalfn = evalcommand;
8397 if (eflag && !(flags & EV_TESTED))
8409 evalfn = evalsubshell;
8422 #error NAND + 1 != NOR
8424 #if NOR + 1 != NSEMI
8425 #error NOR + 1 != NSEMI
8427 unsigned is_or = n->type - NAND;
8430 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8432 if ((!exitstatus) == is_or)
8445 evaltree(n->nif.test, EV_TESTED);
8448 if (exitstatus == 0) {
8452 if (n->nif.elsepart) {
8453 n = n->nif.elsepart;
8458 defun(n->narg.text, n->narg.next);
8462 exitstatus = status;
8467 exception_handler = savehandler;
8470 /* Order of checks below is important:
8471 * signal handlers trigger before exit caused by "set -e".
8473 if (pending_sig && dotrap())
8475 if (checkexit & exitstatus)
8476 evalskip |= SKIPEVAL;
8478 if (flags & EV_EXIT) {
8480 raise_exception(EXEXIT);
8483 RESTORE_INT(int_level);
8484 TRACE(("leaving evaltree (no interrupts)\n"));
8487 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8490 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8493 evalloop(union node *n, int flags)
8503 evaltree(n->nbinary.ch1, EV_TESTED);
8506 if (evalskip == SKIPCONT && --skipcount <= 0) {
8510 if (evalskip == SKIPBREAK && --skipcount <= 0)
8515 if (n->type != NWHILE)
8519 evaltree(n->nbinary.ch2, flags);
8520 status = exitstatus;
8525 exitstatus = status;
8529 evalfor(union node *n, int flags)
8531 struct arglist arglist;
8534 struct stackmark smark;
8536 setstackmark(&smark);
8537 arglist.list = NULL;
8538 arglist.lastp = &arglist.list;
8539 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8540 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8545 *arglist.lastp = NULL;
8550 for (sp = arglist.list; sp; sp = sp->next) {
8551 setvar0(n->nfor.var, sp->text);
8552 evaltree(n->nfor.body, flags);
8554 if (evalskip == SKIPCONT && --skipcount <= 0) {
8558 if (evalskip == SKIPBREAK && --skipcount <= 0)
8565 popstackmark(&smark);
8569 evalcase(union node *n, int flags)
8573 struct arglist arglist;
8574 struct stackmark smark;
8576 setstackmark(&smark);
8577 arglist.list = NULL;
8578 arglist.lastp = &arglist.list;
8579 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8581 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8582 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8583 if (casematch(patp, arglist.list->text)) {
8584 if (evalskip == 0) {
8585 evaltree(cp->nclist.body, flags);
8592 popstackmark(&smark);
8596 * Kick off a subshell to evaluate a tree.
8599 evalsubshell(union node *n, int flags)
8602 int backgnd = (n->type == NBACKGND);
8605 expredir(n->nredir.redirect);
8606 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8609 jp = makejob(/*n,*/ 1);
8610 if (forkshell(jp, n, backgnd) == 0) {
8615 flags &= ~EV_TESTED;
8617 redirect(n->nredir.redirect, 0);
8618 evaltreenr(n->nredir.n, flags);
8623 status = waitforjob(jp);
8624 exitstatus = status;
8629 * Compute the names of the files in a redirection list.
8631 static void fixredir(union node *, const char *, int);
8633 expredir(union node *n)
8637 for (redir = n; redir; redir = redir->nfile.next) {
8641 fn.lastp = &fn.list;
8642 switch (redir->type) {
8646 #if ENABLE_ASH_BASH_COMPAT
8651 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8652 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8653 #if ENABLE_ASH_BASH_COMPAT
8657 // By the design of stack allocator, the loop of this kind:
8658 // while true; do while true; do break; done </dev/null; done
8659 // will look like a memory leak: ash plans to free expfname's
8660 // of "/dev/null" as soon as it finishes running the loop
8661 // (in this case, never).
8662 // This "fix" is wrong:
8663 if (redir->nfile.expfname)
8664 stunalloc(redir->nfile.expfname);
8665 // It results in corrupted state of stacked allocations.
8667 redir->nfile.expfname = fn.list->text;
8670 case NTOFD: /* >& */
8671 if (redir->ndup.vname) {
8672 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8673 if (fn.list == NULL)
8674 ash_msg_and_raise_error("redir error");
8675 #if ENABLE_ASH_BASH_COMPAT
8676 //FIXME: we used expandarg with different args!
8677 if (!isdigit_str9(fn.list->text)) {
8678 /* >&file, not >&fd */
8679 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8680 ash_msg_and_raise_error("redir error");
8682 goto store_expfname;
8685 fixredir(redir, fn.list->text, 1);
8693 * Evaluate a pipeline. All the processes in the pipeline are children
8694 * of the process creating the pipeline. (This differs from some versions
8695 * of the shell, which make the last process in a pipeline the parent
8699 evalpipe(union node *n, int flags)
8702 struct nodelist *lp;
8707 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8709 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8713 jp = makejob(/*n,*/ pipelen);
8715 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8719 if (pipe(pip) < 0) {
8721 ash_msg_and_raise_error("pipe call failed");
8724 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8737 evaltreenr(lp->n, flags);
8743 /* Don't want to trigger debugging */
8747 if (n->npipe.pipe_backgnd == 0) {
8748 exitstatus = waitforjob(jp);
8749 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8755 * Controls whether the shell is interactive or not.
8758 setinteractive(int on)
8760 static smallint is_interactive;
8762 if (++on == is_interactive)
8764 is_interactive = on;
8768 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8769 if (is_interactive > 1) {
8770 /* Looks like they want an interactive shell */
8771 static smallint did_banner;
8774 /* note: ash and hush share this string */
8775 out1fmt("\n\n%s %s\n"
8776 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
8779 "built-in shell (ash)"
8793 setinteractive(iflag);
8795 #if ENABLE_FEATURE_EDITING_VI
8797 line_input_state->flags |= VI_MODE;
8799 line_input_state->flags &= ~VI_MODE;
8801 viflag = 0; /* forcibly keep the option off */
8805 static struct localvar *localvars;
8808 * Called after a function returns.
8809 * Interrupts must be off.
8814 struct localvar *lvp;
8817 while ((lvp = localvars) != NULL) {
8818 localvars = lvp->next;
8820 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
8821 if (vp == NULL) { /* $- saved */
8822 memcpy(optlist, lvp->text, sizeof(optlist));
8823 free((char*)lvp->text);
8825 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8826 unsetvar(vp->var_text);
8829 vp->var_func(var_end(lvp->text));
8830 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8831 free((char*)vp->var_text);
8832 vp->flags = lvp->flags;
8833 vp->var_text = lvp->text;
8840 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8842 volatile struct shparam saveparam;
8843 struct localvar *volatile savelocalvars;
8844 struct jmploc *volatile savehandler;
8845 struct jmploc jmploc;
8848 saveparam = shellparam;
8849 savelocalvars = localvars;
8850 e = setjmp(jmploc.loc);
8855 savehandler = exception_handler;
8856 exception_handler = &jmploc;
8858 shellparam.malloced = 0;
8862 shellparam.nparam = argc - 1;
8863 shellparam.p = argv + 1;
8864 #if ENABLE_ASH_GETOPTS
8865 shellparam.optind = 1;
8866 shellparam.optoff = -1;
8868 evaltree(&func->n, flags & EV_TESTED);
8874 localvars = savelocalvars;
8875 freeparam(&shellparam);
8876 shellparam = saveparam;
8877 exception_handler = savehandler;
8879 evalskip &= ~SKIPFUNC;
8883 #if ENABLE_ASH_CMDCMD
8885 parse_command_args(char **argv, const char **path)
8898 if (c == '-' && !*cp) {
8906 *path = bb_default_path;
8909 /* run 'typecmd' for other options */
8920 * Make a variable a local variable. When a variable is made local, it's
8921 * value and flags are saved in a localvar structure. The saved values
8922 * will be restored when the shell function returns. We handle the name
8923 * "-" as a special case: it makes changes to "set +-options" local
8924 * (options will be restored on return from the function).
8929 struct localvar *lvp;
8932 char *eq = strchr(name, '=');
8935 /* Cater for duplicate "local". Examples:
8936 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
8937 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
8941 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
8945 * it's a duplicate "local VAR" declaration, do nothing
8952 lvp = ckzalloc(sizeof(*lvp));
8953 if (LONE_DASH(name)) {
8955 p = ckmalloc(sizeof(optlist));
8956 lvp->text = memcpy(p, optlist, sizeof(optlist));
8959 vpp = hashvar(name);
8960 vp = *findvar(vpp, name);
8962 /* variable did not exist yet */
8964 setvareq(name, VSTRFIXED);
8966 setvar(name, NULL, VSTRFIXED);
8967 vp = *vpp; /* the new variable */
8968 lvp->flags = VUNSET;
8970 lvp->text = vp->var_text;
8971 lvp->flags = vp->flags;
8972 /* make sure neither "struct var" nor string gets freed
8973 * during (un)setting:
8975 vp->flags |= VSTRFIXED|VTEXTFIXED;
8979 /* "local VAR" unsets VAR: */
8980 setvar0(name, NULL);
8984 lvp->next = localvars;
8990 * The "local" command.
8992 static int FAST_FUNC
8993 localcmd(int argc UNUSED_PARAM, char **argv)
8998 ash_msg_and_raise_error("not in a function");
9001 while ((name = *argv++) != NULL) {
9007 static int FAST_FUNC
9008 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9013 static int FAST_FUNC
9014 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9019 static int FAST_FUNC
9020 execcmd(int argc UNUSED_PARAM, char **argv)
9023 iflag = 0; /* exit on error */
9026 shellexec(argv + 1, pathval(), 0);
9032 * The return command.
9034 static int FAST_FUNC
9035 returncmd(int argc UNUSED_PARAM, char **argv)
9038 * If called outside a function, do what ksh does;
9039 * skip the rest of the file.
9041 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
9042 return argv[1] ? number(argv[1]) : exitstatus;
9045 /* Forward declarations for builtintab[] */
9046 static int breakcmd(int, char **) FAST_FUNC;
9047 static int dotcmd(int, char **) FAST_FUNC;
9048 static int evalcmd(int, char **) FAST_FUNC;
9049 static int exitcmd(int, char **) FAST_FUNC;
9050 static int exportcmd(int, char **) FAST_FUNC;
9051 #if ENABLE_ASH_GETOPTS
9052 static int getoptscmd(int, char **) FAST_FUNC;
9055 static int helpcmd(int, char **) FAST_FUNC;
9058 static int historycmd(int, char **) FAST_FUNC;
9060 #if ENABLE_SH_MATH_SUPPORT
9061 static int letcmd(int, char **) FAST_FUNC;
9063 static int readcmd(int, char **) FAST_FUNC;
9064 static int setcmd(int, char **) FAST_FUNC;
9065 static int shiftcmd(int, char **) FAST_FUNC;
9066 static int timescmd(int, char **) FAST_FUNC;
9067 static int trapcmd(int, char **) FAST_FUNC;
9068 static int umaskcmd(int, char **) FAST_FUNC;
9069 static int unsetcmd(int, char **) FAST_FUNC;
9070 static int ulimitcmd(int, char **) FAST_FUNC;
9072 #define BUILTIN_NOSPEC "0"
9073 #define BUILTIN_SPECIAL "1"
9074 #define BUILTIN_REGULAR "2"
9075 #define BUILTIN_SPEC_REG "3"
9076 #define BUILTIN_ASSIGN "4"
9077 #define BUILTIN_SPEC_ASSG "5"
9078 #define BUILTIN_REG_ASSG "6"
9079 #define BUILTIN_SPEC_REG_ASSG "7"
9081 /* Stubs for calling non-FAST_FUNC's */
9082 #if ENABLE_ASH_BUILTIN_ECHO
9083 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9085 #if ENABLE_ASH_BUILTIN_PRINTF
9086 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9088 #if ENABLE_ASH_BUILTIN_TEST
9089 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9092 /* Keep these in proper order since it is searched via bsearch() */
9093 static const struct builtincmd builtintab[] = {
9094 { BUILTIN_SPEC_REG "." , dotcmd },
9095 { BUILTIN_SPEC_REG ":" , truecmd },
9096 #if ENABLE_ASH_BUILTIN_TEST
9097 { BUILTIN_REGULAR "[" , testcmd },
9098 #if ENABLE_ASH_BASH_COMPAT
9099 { BUILTIN_REGULAR "[[" , testcmd },
9102 #if ENABLE_ASH_ALIAS
9103 { BUILTIN_REG_ASSG "alias" , aliascmd },
9106 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9108 { BUILTIN_SPEC_REG "break" , breakcmd },
9109 { BUILTIN_REGULAR "cd" , cdcmd },
9110 { BUILTIN_NOSPEC "chdir" , cdcmd },
9111 #if ENABLE_ASH_CMDCMD
9112 { BUILTIN_REGULAR "command" , commandcmd },
9114 { BUILTIN_SPEC_REG "continue", breakcmd },
9115 #if ENABLE_ASH_BUILTIN_ECHO
9116 { BUILTIN_REGULAR "echo" , echocmd },
9118 { BUILTIN_SPEC_REG "eval" , evalcmd },
9119 { BUILTIN_SPEC_REG "exec" , execcmd },
9120 { BUILTIN_SPEC_REG "exit" , exitcmd },
9121 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9122 { BUILTIN_REGULAR "false" , falsecmd },
9124 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9126 #if ENABLE_ASH_GETOPTS
9127 { BUILTIN_REGULAR "getopts" , getoptscmd },
9129 { BUILTIN_NOSPEC "hash" , hashcmd },
9131 { BUILTIN_NOSPEC "help" , helpcmd },
9134 { BUILTIN_NOSPEC "history" , historycmd },
9137 { BUILTIN_REGULAR "jobs" , jobscmd },
9138 { BUILTIN_REGULAR "kill" , killcmd },
9140 #if ENABLE_SH_MATH_SUPPORT
9141 { BUILTIN_NOSPEC "let" , letcmd },
9143 { BUILTIN_ASSIGN "local" , localcmd },
9144 #if ENABLE_ASH_BUILTIN_PRINTF
9145 { BUILTIN_REGULAR "printf" , printfcmd },
9147 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9148 { BUILTIN_REGULAR "read" , readcmd },
9149 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9150 { BUILTIN_SPEC_REG "return" , returncmd },
9151 { BUILTIN_SPEC_REG "set" , setcmd },
9152 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9153 #if ENABLE_ASH_BASH_COMPAT
9154 { BUILTIN_SPEC_REG "source" , dotcmd },
9156 #if ENABLE_ASH_BUILTIN_TEST
9157 { BUILTIN_REGULAR "test" , testcmd },
9159 { BUILTIN_SPEC_REG "times" , timescmd },
9160 { BUILTIN_SPEC_REG "trap" , trapcmd },
9161 { BUILTIN_REGULAR "true" , truecmd },
9162 { BUILTIN_NOSPEC "type" , typecmd },
9163 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9164 { BUILTIN_REGULAR "umask" , umaskcmd },
9165 #if ENABLE_ASH_ALIAS
9166 { BUILTIN_REGULAR "unalias" , unaliascmd },
9168 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9169 { BUILTIN_REGULAR "wait" , waitcmd },
9172 /* Should match the above table! */
9173 #define COMMANDCMD (builtintab + \
9175 1 * ENABLE_ASH_BUILTIN_TEST + \
9176 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9177 1 * ENABLE_ASH_ALIAS + \
9178 1 * ENABLE_ASH_JOB_CONTROL + \
9180 #define EXECCMD (builtintab + \
9182 1 * ENABLE_ASH_BUILTIN_TEST + \
9183 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9184 1 * ENABLE_ASH_ALIAS + \
9185 1 * ENABLE_ASH_JOB_CONTROL + \
9187 1 * ENABLE_ASH_CMDCMD + \
9189 ENABLE_ASH_BUILTIN_ECHO + \
9193 * Search the table of builtin commands.
9195 static struct builtincmd *
9196 find_builtin(const char *name)
9198 struct builtincmd *bp;
9201 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9208 * Execute a simple command.
9211 isassignment(const char *p)
9213 const char *q = endofname(p);
9218 static int FAST_FUNC
9219 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9221 /* Preserve exitstatus of a previous possible redirection
9222 * as POSIX mandates */
9223 return back_exitstatus;
9226 evalcommand(union node *cmd, int flags)
9228 static const struct builtincmd null_bltin = {
9229 "\0\0", bltincmd /* why three NULs? */
9231 struct stackmark smark;
9233 struct arglist arglist;
9234 struct arglist varlist;
9237 const struct strlist *sp;
9238 struct cmdentry cmdentry;
9245 struct builtincmd *bcmd;
9246 smallint cmd_is_exec;
9247 smallint pseudovarflag = 0;
9249 /* First expand the arguments. */
9250 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9251 setstackmark(&smark);
9252 back_exitstatus = 0;
9254 cmdentry.cmdtype = CMDBUILTIN;
9255 cmdentry.u.cmd = &null_bltin;
9256 varlist.lastp = &varlist.list;
9257 *varlist.lastp = NULL;
9258 arglist.lastp = &arglist.list;
9259 *arglist.lastp = NULL;
9262 if (cmd->ncmd.args) {
9263 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9264 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9267 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9268 struct strlist **spp;
9270 spp = arglist.lastp;
9271 if (pseudovarflag && isassignment(argp->narg.text))
9272 expandarg(argp, &arglist, EXP_VARTILDE);
9274 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9276 for (sp = *spp; sp; sp = sp->next)
9280 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9281 for (sp = arglist.list; sp; sp = sp->next) {
9282 TRACE(("evalcommand arg: %s\n", sp->text));
9283 *nargv++ = sp->text;
9288 if (iflag && funcnest == 0 && argc > 0)
9289 lastarg = nargv[-1];
9292 expredir(cmd->ncmd.redirect);
9293 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9295 path = vpath.var_text;
9296 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9297 struct strlist **spp;
9300 spp = varlist.lastp;
9301 expandarg(argp, &varlist, EXP_VARTILDE);
9304 * Modify the command lookup path, if a PATH= assignment
9308 if (varcmp(p, path) == 0)
9312 /* Print the command if xflag is set. */
9315 const char *p = " %s" + 1;
9317 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9319 for (n = 0; n < 2; n++) {
9321 fdprintf(preverrout_fd, p, sp->text);
9327 safe_write(preverrout_fd, "\n", 1);
9333 /* Now locate the command. */
9335 int cmd_flag = DO_ERR;
9336 #if ENABLE_ASH_CMDCMD
9337 const char *oldpath = path + 5;
9341 find_command(argv[0], &cmdentry, cmd_flag, path);
9342 if (cmdentry.cmdtype == CMDUNKNOWN) {
9343 flush_stdout_stderr();
9348 /* implement bltin and command here */
9349 if (cmdentry.cmdtype != CMDBUILTIN)
9352 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9353 if (cmdentry.u.cmd == EXECCMD)
9355 #if ENABLE_ASH_CMDCMD
9356 if (cmdentry.u.cmd == COMMANDCMD) {
9358 nargv = parse_command_args(argv, &path);
9361 argc -= nargv - argv;
9363 cmd_flag |= DO_NOFUNC;
9371 /* We have a redirection error. */
9373 raise_exception(EXERROR);
9375 exitstatus = status;
9379 /* Execute the command. */
9380 switch (cmdentry.cmdtype) {
9383 #if ENABLE_FEATURE_SH_NOFORK
9384 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9385 * around run_nofork_applet() call.
9386 * (2) Should this check also be done in forkshell()?
9387 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9389 /* find_command() encodes applet_no as (-2 - applet_no) */
9390 int applet_no = (- cmdentry.u.index - 2);
9391 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9392 listsetvar(varlist.list, VEXPORT|VSTACK);
9393 /* run <applet>_main() */
9394 exitstatus = run_nofork_applet(applet_no, argv);
9398 /* Can we avoid forking off? For example, very last command
9399 * in a script or a subshell does not need forking,
9400 * we can just exec it.
9402 if (!(flags & EV_EXIT) || may_have_traps) {
9403 /* No, forking off a child is necessary */
9405 jp = makejob(/*cmd,*/ 1);
9406 if (forkshell(jp, cmd, FORK_FG) != 0) {
9408 exitstatus = waitforjob(jp);
9410 TRACE(("forked child exited with %d\n", exitstatus));
9415 /* fall through to exec'ing external program */
9417 listsetvar(varlist.list, VEXPORT|VSTACK);
9418 shellexec(argv, path, cmdentry.u.index);
9422 cmdenviron = varlist.list;
9424 struct strlist *list = cmdenviron;
9426 if (spclbltin > 0 || argc == 0) {
9428 if (cmd_is_exec && argc > 1)
9431 listsetvar(list, i);
9433 /* Tight loop with builtins only:
9434 * "while kill -0 $child; do true; done"
9435 * will never exit even if $child died, unless we do this
9436 * to reap the zombie and make kill detect that it's gone: */
9437 dowait(DOWAIT_NONBLOCK, NULL);
9439 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9441 int i = exception_type;
9442 if (i == EXEXIT || i == EXEXEC)
9446 exit_status = 128 + SIGINT;
9448 exit_status = 128 + pending_sig;
9449 exitstatus = exit_status;
9450 if (i == EXINT || spclbltin > 0) {
9452 longjmp(exception_handler->loc, 1);
9459 listsetvar(varlist.list, 0);
9460 /* See above for the rationale */
9461 dowait(DOWAIT_NONBLOCK, NULL);
9462 if (evalfun(cmdentry.u.func, argc, argv, flags))
9468 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9470 /* dsl: I think this is intended to be used to support
9471 * '_' in 'vi' command mode during line editing...
9472 * However I implemented that within libedit itself.
9474 setvar0("_", lastarg);
9476 popstackmark(&smark);
9480 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9482 char *volatile savecmdname;
9483 struct jmploc *volatile savehandler;
9484 struct jmploc jmploc;
9487 savecmdname = commandname;
9488 i = setjmp(jmploc.loc);
9491 savehandler = exception_handler;
9492 exception_handler = &jmploc;
9493 commandname = argv[0];
9495 optptr = NULL; /* initialize nextopt */
9496 exitstatus = (*cmd->builtin)(argc, argv);
9497 flush_stdout_stderr();
9499 exitstatus |= ferror(stdout);
9501 commandname = savecmdname;
9502 exception_handler = savehandler;
9508 goodname(const char *p)
9510 return endofname(p)[0] == '\0';
9515 * Search for a command. This is called before we fork so that the
9516 * location of the command will be available in the parent as well as
9517 * the child. The check for "goodname" is an overly conservative
9518 * check that the name will not be subject to expansion.
9521 prehash(union node *n)
9523 struct cmdentry entry;
9525 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9526 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9530 /* ============ Builtin commands
9532 * Builtin commands whose functions are closely tied to evaluation
9533 * are implemented here.
9537 * Handle break and continue commands. Break, continue, and return are
9538 * all handled by setting the evalskip flag. The evaluation routines
9539 * above all check this flag, and if it is set they start skipping
9540 * commands rather than executing them. The variable skipcount is
9541 * the number of loops to break/continue, or the number of function
9542 * levels to return. (The latter is always 1.) It should probably
9543 * be an error to break out of more loops than exist, but it isn't
9544 * in the standard shell so we don't make it one here.
9546 static int FAST_FUNC
9547 breakcmd(int argc UNUSED_PARAM, char **argv)
9549 int n = argv[1] ? number(argv[1]) : 1;
9552 ash_msg_and_raise_error(msg_illnum, argv[1]);
9556 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9563 /* ============ input.c
9565 * This implements the input routines used by the parser.
9569 INPUT_PUSH_FILE = 1,
9570 INPUT_NOFILE_OK = 2,
9573 static smallint checkkwd;
9574 /* values of checkkwd variable */
9575 #define CHKALIAS 0x1
9580 * Push a string back onto the input at this current parsefile level.
9581 * We handle aliases this way.
9583 #if !ENABLE_ASH_ALIAS
9584 #define pushstring(s, ap) pushstring(s)
9587 pushstring(char *s, struct alias *ap)
9594 if (g_parsefile->strpush) {
9595 sp = ckzalloc(sizeof(*sp));
9596 sp->prev = g_parsefile->strpush;
9598 sp = &(g_parsefile->basestrpush);
9600 g_parsefile->strpush = sp;
9601 sp->prev_string = g_parsefile->next_to_pgetc;
9602 sp->prev_left_in_line = g_parsefile->left_in_line;
9603 #if ENABLE_ASH_ALIAS
9606 ap->flag |= ALIASINUSE;
9610 g_parsefile->next_to_pgetc = s;
9611 g_parsefile->left_in_line = len;
9618 struct strpush *sp = g_parsefile->strpush;
9621 #if ENABLE_ASH_ALIAS
9623 if (g_parsefile->next_to_pgetc[-1] == ' '
9624 || g_parsefile->next_to_pgetc[-1] == '\t'
9626 checkkwd |= CHKALIAS;
9628 if (sp->string != sp->ap->val) {
9631 sp->ap->flag &= ~ALIASINUSE;
9632 if (sp->ap->flag & ALIASDEAD) {
9633 unalias(sp->ap->name);
9637 g_parsefile->next_to_pgetc = sp->prev_string;
9638 g_parsefile->left_in_line = sp->prev_left_in_line;
9639 g_parsefile->strpush = sp->prev;
9640 if (sp != &(g_parsefile->basestrpush))
9645 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9646 //it peeks whether it is &>, and then pushes back both chars.
9647 //This function needs to save last *next_to_pgetc to buf[0]
9648 //to make two pungetc() reliable. Currently,
9649 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9654 char *buf = g_parsefile->buf;
9656 g_parsefile->next_to_pgetc = buf;
9657 #if ENABLE_FEATURE_EDITING
9659 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9660 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9663 # if ENABLE_ASH_IDLE_TIMEOUT
9665 const char *tmout_var = lookupvar("TMOUT");
9667 timeout = atoi(tmout_var) * 1000;
9673 # if ENABLE_FEATURE_TAB_COMPLETION
9674 line_input_state->path_lookup = pathval();
9676 reinit_unicode_for_ash();
9677 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9679 /* Ctrl+C pressed */
9690 /* Ctrl+D pressed */
9693 # if ENABLE_ASH_IDLE_TIMEOUT
9694 else if (errno == EAGAIN && timeout > 0) {
9695 puts("\007timed out waiting for input: auto-logout");
9702 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9705 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9707 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9708 int flags = fcntl(0, F_GETFL);
9709 if (flags >= 0 && (flags & O_NONBLOCK)) {
9710 flags &= ~O_NONBLOCK;
9711 if (fcntl(0, F_SETFL, flags) >= 0) {
9712 out2str("sh: turning off NDELAY mode\n");
9723 * Refill the input buffer and return the next input character:
9725 * 1) If a string was pushed back on the input, pop it;
9726 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9727 * or we are reading from a string so we can't refill the buffer,
9729 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9730 * 4) Process input up to the next newline, deleting nul characters.
9732 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9733 #define pgetc_debug(...) ((void)0)
9740 while (g_parsefile->strpush) {
9741 #if ENABLE_ASH_ALIAS
9742 if (g_parsefile->left_in_line == -1
9743 && g_parsefile->strpush->ap
9744 && g_parsefile->next_to_pgetc[-1] != ' '
9745 && g_parsefile->next_to_pgetc[-1] != '\t'
9747 pgetc_debug("preadbuffer PEOA");
9752 /* try "pgetc" now: */
9753 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9754 g_parsefile->left_in_line,
9755 g_parsefile->next_to_pgetc,
9756 g_parsefile->next_to_pgetc);
9757 if (--g_parsefile->left_in_line >= 0)
9758 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9760 /* on both branches above g_parsefile->left_in_line < 0.
9761 * "pgetc" needs refilling.
9764 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9765 * pungetc() may increment it a few times.
9766 * Assuming it won't increment it to less than -90.
9768 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9769 pgetc_debug("preadbuffer PEOF1");
9770 /* even in failure keep left_in_line and next_to_pgetc
9771 * in lock step, for correct multi-layer pungetc.
9772 * left_in_line was decremented before preadbuffer(),
9773 * must inc next_to_pgetc: */
9774 g_parsefile->next_to_pgetc++;
9778 more = g_parsefile->left_in_buffer;
9780 flush_stdout_stderr();
9784 /* don't try reading again */
9785 g_parsefile->left_in_line = -99;
9786 pgetc_debug("preadbuffer PEOF2");
9787 g_parsefile->next_to_pgetc++;
9792 /* Find out where's the end of line.
9793 * Set g_parsefile->left_in_line
9794 * and g_parsefile->left_in_buffer acordingly.
9795 * NUL chars are deleted.
9797 q = g_parsefile->next_to_pgetc;
9805 memmove(q, q + 1, more);
9809 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9815 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9816 if (g_parsefile->left_in_line < 0)
9821 g_parsefile->left_in_buffer = more;
9826 out2str(g_parsefile->next_to_pgetc);
9830 pgetc_debug("preadbuffer at %d:%p'%s'",
9831 g_parsefile->left_in_line,
9832 g_parsefile->next_to_pgetc,
9833 g_parsefile->next_to_pgetc);
9834 return (unsigned char)*g_parsefile->next_to_pgetc++;
9837 #define pgetc_as_macro() \
9838 (--g_parsefile->left_in_line >= 0 \
9839 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9846 pgetc_debug("pgetc_fast at %d:%p'%s'",
9847 g_parsefile->left_in_line,
9848 g_parsefile->next_to_pgetc,
9849 g_parsefile->next_to_pgetc);
9850 return pgetc_as_macro();
9853 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9854 # define pgetc_fast() pgetc()
9856 # define pgetc_fast() pgetc_as_macro()
9859 #if ENABLE_ASH_ALIAS
9861 pgetc_without_PEOA(void)
9865 pgetc_debug("pgetc_fast at %d:%p'%s'",
9866 g_parsefile->left_in_line,
9867 g_parsefile->next_to_pgetc,
9868 g_parsefile->next_to_pgetc);
9870 } while (c == PEOA);
9874 # define pgetc_without_PEOA() pgetc()
9878 * Read a line from the script.
9881 pfgets(char *line, int len)
9887 while (--nleft > 0) {
9888 c = pgetc_without_PEOA();
9903 * Undo the last call to pgetc. Only one character may be pushed back.
9904 * PEOF may be pushed back.
9909 g_parsefile->left_in_line++;
9910 g_parsefile->next_to_pgetc--;
9911 pgetc_debug("pushed back to %d:%p'%s'",
9912 g_parsefile->left_in_line,
9913 g_parsefile->next_to_pgetc,
9914 g_parsefile->next_to_pgetc);
9918 * To handle the "." command, a stack of input files is used. Pushfile
9919 * adds a new entry to the stack and popfile restores the previous level.
9924 struct parsefile *pf;
9926 pf = ckzalloc(sizeof(*pf));
9927 pf->prev = g_parsefile;
9929 /*pf->strpush = NULL; - ckzalloc did it */
9930 /*pf->basestrpush.prev = NULL;*/
9937 struct parsefile *pf = g_parsefile;
9945 g_parsefile = pf->prev;
9951 * Return to top level.
9956 while (g_parsefile != &basepf)
9961 * Close the file(s) that the shell is reading commands from. Called
9962 * after a fork is done.
9968 if (g_parsefile->pf_fd > 0) {
9969 close(g_parsefile->pf_fd);
9970 g_parsefile->pf_fd = 0;
9975 * Like setinputfile, but takes an open file descriptor. Call this with
9979 setinputfd(int fd, int push)
9981 close_on_exec_on(fd);
9984 g_parsefile->buf = NULL;
9986 g_parsefile->pf_fd = fd;
9987 if (g_parsefile->buf == NULL)
9988 g_parsefile->buf = ckmalloc(IBUFSIZ);
9989 g_parsefile->left_in_buffer = 0;
9990 g_parsefile->left_in_line = 0;
9991 g_parsefile->linno = 1;
9995 * Set the input to take input from a file. If push is set, push the
9996 * old input onto the stack first.
9999 setinputfile(const char *fname, int flags)
10005 fd = open(fname, O_RDONLY);
10007 if (flags & INPUT_NOFILE_OK)
10009 ash_msg_and_raise_error("can't open '%s'", fname);
10012 fd2 = copyfd(fd, 10);
10015 ash_msg_and_raise_error("out of file descriptors");
10018 setinputfd(fd, flags & INPUT_PUSH_FILE);
10025 * Like setinputfile, but takes input from a string.
10028 setinputstring(char *string)
10032 g_parsefile->next_to_pgetc = string;
10033 g_parsefile->left_in_line = strlen(string);
10034 g_parsefile->buf = NULL;
10035 g_parsefile->linno = 1;
10040 /* ============ mail.c
10042 * Routines to check for mail.
10045 #if ENABLE_ASH_MAIL
10047 /* Hash of mtimes of mailboxes */
10048 static unsigned mailtime_hash;
10049 /* Set if MAIL or MAILPATH is changed. */
10050 static smallint mail_var_path_changed;
10053 * Print appropriate message(s) if mail has arrived.
10054 * If mail_var_path_changed is set,
10055 * then the value of MAIL has mail_var_path_changed,
10056 * so we just update the values.
10065 struct stackmark smark;
10068 setstackmark(&smark);
10069 mpath = mpathset() ? mpathval() : mailval();
10072 p = path_advance(&mpath, nullstr);
10077 for (q = p; *q; q++)
10083 q[-1] = '\0'; /* delete trailing '/' */
10084 if (stat(p, &statb) < 0) {
10087 /* Very simplistic "hash": just a sum of all mtimes */
10088 new_hash += (unsigned)statb.st_mtime;
10090 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10091 if (mailtime_hash != 0)
10092 out2str("you have mail\n");
10093 mailtime_hash = new_hash;
10095 mail_var_path_changed = 0;
10096 popstackmark(&smark);
10099 static void FAST_FUNC
10100 changemail(const char *val UNUSED_PARAM)
10102 mail_var_path_changed = 1;
10105 #endif /* ASH_MAIL */
10108 /* ============ ??? */
10111 * Set the shell parameters.
10114 setparam(char **argv)
10120 for (nparam = 0; argv[nparam]; nparam++)
10122 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10124 *ap++ = ckstrdup(*argv++);
10127 freeparam(&shellparam);
10128 shellparam.malloced = 1;
10129 shellparam.nparam = nparam;
10130 shellparam.p = newparam;
10131 #if ENABLE_ASH_GETOPTS
10132 shellparam.optind = 1;
10133 shellparam.optoff = -1;
10138 * Process shell options. The global variable argptr contains a pointer
10139 * to the argument list; we advance it past the options.
10141 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10142 * For a non-interactive shell, an error condition encountered
10143 * by a special built-in ... shall cause the shell to write a diagnostic message
10144 * to standard error and exit as shown in the following table:
10145 * Error Special Built-In
10147 * Utility syntax error (option or operand error) Shall exit
10149 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10150 * we see that bash does not do that (set "finishes" with error code 1 instead,
10151 * and shell continues), and people rely on this behavior!
10153 * set -o barfoo 2>/dev/null
10156 * Oh well. Let's mimic that.
10159 plus_minus_o(char *name, int val)
10164 for (i = 0; i < NOPTS; i++) {
10165 if (strcmp(name, optnames(i)) == 0) {
10170 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10173 for (i = 0; i < NOPTS; i++) {
10175 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10177 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10183 setoption(int flag, int val)
10187 for (i = 0; i < NOPTS; i++) {
10188 if (optletters(i) == flag) {
10193 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10197 options(int cmdline)
10205 while ((p = *argptr) != NULL) {
10207 if (c != '-' && c != '+')
10210 val = 0; /* val = 0 if c == '+' */
10213 if (p[0] == '\0' || LONE_DASH(p)) {
10215 /* "-" means turn off -x and -v */
10218 /* "--" means reset params */
10219 else if (*argptr == NULL)
10222 break; /* "-" or "--" terminates options */
10225 /* first char was + or - */
10226 while ((c = *p++) != '\0') {
10227 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10228 if (c == 'c' && cmdline) {
10229 minusc = p; /* command is after shell args */
10230 } else if (c == 'o') {
10231 if (plus_minus_o(*argptr, val)) {
10232 /* it already printed err message */
10233 return 1; /* error */
10237 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10239 /* bash does not accept +-login, we also won't */
10240 } else if (cmdline && val && (c == '-')) { /* long options */
10241 if (strcmp(p, "login") == 0)
10253 * The shift builtin command.
10255 static int FAST_FUNC
10256 shiftcmd(int argc UNUSED_PARAM, char **argv)
10263 n = number(argv[1]);
10264 if (n > shellparam.nparam)
10265 n = 0; /* bash compat, was = shellparam.nparam; */
10267 shellparam.nparam -= n;
10268 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10269 if (shellparam.malloced)
10272 ap2 = shellparam.p;
10273 while ((*ap2++ = *ap1++) != NULL)
10275 #if ENABLE_ASH_GETOPTS
10276 shellparam.optind = 1;
10277 shellparam.optoff = -1;
10284 * POSIX requires that 'set' (but not export or readonly) output the
10285 * variables in lexicographic order - by the locale's collating order (sigh).
10286 * Maybe we could keep them in an ordered balanced binary tree
10287 * instead of hashed lists.
10288 * For now just roll 'em through qsort for printing...
10291 showvars(const char *sep_prefix, int on, int off)
10294 char **ep, **epend;
10296 ep = listvars(on, off, &epend);
10297 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10299 sep = *sep_prefix ? " " : sep_prefix;
10301 for (; ep < epend; ep++) {
10305 p = strchrnul(*ep, '=');
10308 q = single_quote(++p);
10309 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10315 * The set command builtin.
10317 static int FAST_FUNC
10318 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10323 return showvars(nullstr, 0, VUNSET);
10326 retval = options(/*cmdline:*/ 0);
10327 if (retval == 0) { /* if no parse error... */
10329 if (*argptr != NULL) {
10337 #if ENABLE_ASH_RANDOM_SUPPORT
10338 static void FAST_FUNC
10339 change_random(const char *value)
10343 if (value == NULL) {
10344 /* "get", generate */
10345 t = next_random(&random_gen);
10346 /* set without recursion */
10347 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10348 vrandom.flags &= ~VNOFUNC;
10351 t = strtoul(value, NULL, 10);
10352 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10357 #if ENABLE_ASH_GETOPTS
10359 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10370 if (*param_optind < 1)
10372 optnext = optfirst + *param_optind - 1;
10374 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10377 p = optnext[-1] + *optoff;
10378 if (p == NULL || *p == '\0') {
10379 /* Current word is done, advance */
10381 if (p == NULL || *p != '-' || *++p == '\0') {
10388 if (LONE_DASH(p)) /* check for "--" */
10393 for (q = optstr; *q != c;) {
10395 if (optstr[0] == ':') {
10397 /*sbuf[1] = '\0'; - already is */
10398 err |= setvarsafe("OPTARG", sbuf, 0);
10400 fprintf(stderr, "Illegal option -%c\n", c);
10401 unsetvar("OPTARG");
10411 if (*p == '\0' && (p = *optnext) == NULL) {
10412 if (optstr[0] == ':') {
10414 /*sbuf[1] = '\0'; - already is */
10415 err |= setvarsafe("OPTARG", sbuf, 0);
10418 fprintf(stderr, "No arg for -%c option\n", c);
10419 unsetvar("OPTARG");
10427 err |= setvarsafe("OPTARG", p, 0);
10430 err |= setvarsafe("OPTARG", nullstr, 0);
10432 *optoff = p ? p - *(optnext - 1) : -1;
10433 *param_optind = optnext - optfirst + 1;
10434 err |= setvarsafe("OPTIND", itoa(*param_optind), VNOFUNC);
10436 /*sbuf[1] = '\0'; - already is */
10437 err |= setvarsafe(optvar, sbuf, 0);
10441 flush_stdout_stderr();
10442 raise_exception(EXERROR);
10448 * The getopts builtin. Shellparam.optnext points to the next argument
10449 * to be processed. Shellparam.optptr points to the next character to
10450 * be processed in the current argument. If shellparam.optnext is NULL,
10451 * then it's the first time getopts has been called.
10453 static int FAST_FUNC
10454 getoptscmd(int argc, char **argv)
10459 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10461 optbase = shellparam.p;
10462 if (shellparam.optind > shellparam.nparam + 1) {
10463 shellparam.optind = 1;
10464 shellparam.optoff = -1;
10467 optbase = &argv[3];
10468 if (shellparam.optind > argc - 2) {
10469 shellparam.optind = 1;
10470 shellparam.optoff = -1;
10474 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10475 &shellparam.optoff);
10477 #endif /* ASH_GETOPTS */
10480 /* ============ Shell parser */
10483 struct heredoc *next; /* next here document in list */
10484 union node *here; /* redirection node */
10485 char *eofmark; /* string indicating end of input */
10486 smallint striptabs; /* if set, strip leading tabs */
10489 static smallint tokpushback; /* last token pushed back */
10490 static smallint quoteflag; /* set if (part of) last token was quoted */
10491 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10492 static struct heredoc *heredoclist; /* list of here documents to read */
10493 static char *wordtext; /* text of last word returned by readtoken */
10494 static struct nodelist *backquotelist;
10495 static union node *redirnode;
10496 static struct heredoc *heredoc;
10498 static const char *
10499 tokname(char *buf, int tok)
10502 return tokname_array[tok] + 1;
10503 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10507 /* raise_error_unexpected_syntax:
10508 * Called when an unexpected token is read during the parse. The argument
10509 * is the token that is expected, or -1 if more than one type of token can
10510 * occur at this point.
10512 static void raise_error_unexpected_syntax(int) NORETURN;
10514 raise_error_unexpected_syntax(int token)
10520 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10522 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10523 raise_error_syntax(msg);
10527 #define EOFMARKLEN 79
10529 /* parsing is heavily cross-recursive, need these forward decls */
10530 static union node *andor(void);
10531 static union node *pipeline(void);
10532 static union node *parse_command(void);
10533 static void parseheredoc(void);
10534 static int peektoken(void);
10535 static int readtoken(void);
10537 static union node *
10540 union node *n1, *n2, *n3;
10545 switch (peektoken()) {
10553 if (!n1 && (nlflag & 1))
10559 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10560 if (nlflag == 2 && tokname_array[peektoken()][0])
10566 if (tok == TBACKGND) {
10567 if (n2->type == NPIPE) {
10568 n2->npipe.pipe_backgnd = 1;
10570 if (n2->type != NREDIR) {
10571 n3 = stzalloc(sizeof(struct nredir));
10573 /*n3->nredir.redirect = NULL; - stzalloc did it */
10576 n2->type = NBACKGND;
10582 n3 = stzalloc(sizeof(struct nbinary));
10584 n3->nbinary.ch1 = n1;
10585 n3->nbinary.ch2 = n2;
10598 raise_error_unexpected_syntax(-1);
10605 static union node *
10608 union node *n1, *n2, *n3;
10616 } else if (t == TOR) {
10622 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10624 n3 = stzalloc(sizeof(struct nbinary));
10626 n3->nbinary.ch1 = n1;
10627 n3->nbinary.ch2 = n2;
10632 static union node *
10635 union node *n1, *n2, *pipenode;
10636 struct nodelist *lp, *prev;
10640 TRACE(("pipeline: entered\n"));
10641 if (readtoken() == TNOT) {
10643 checkkwd = CHKKWD | CHKALIAS;
10646 n1 = parse_command();
10647 if (readtoken() == TPIPE) {
10648 pipenode = stzalloc(sizeof(struct npipe));
10649 pipenode->type = NPIPE;
10650 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10651 lp = stzalloc(sizeof(struct nodelist));
10652 pipenode->npipe.cmdlist = lp;
10656 lp = stzalloc(sizeof(struct nodelist));
10657 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10658 lp->n = parse_command();
10660 } while (readtoken() == TPIPE);
10666 n2 = stzalloc(sizeof(struct nnot));
10674 static union node *
10679 n = stzalloc(sizeof(struct narg));
10681 /*n->narg.next = NULL; - stzalloc did it */
10682 n->narg.text = wordtext;
10683 n->narg.backquote = backquotelist;
10688 fixredir(union node *n, const char *text, int err)
10692 TRACE(("Fix redir %s %d\n", text, err));
10694 n->ndup.vname = NULL;
10696 fd = bb_strtou(text, NULL, 10);
10697 if (!errno && fd >= 0)
10698 n->ndup.dupfd = fd;
10699 else if (LONE_DASH(text))
10700 n->ndup.dupfd = -1;
10703 raise_error_syntax("bad fd number");
10704 n->ndup.vname = makename();
10709 * Returns true if the text contains nothing to expand (no dollar signs
10713 noexpand(const char *text)
10717 while ((c = *text++) != '\0') {
10718 if (c == CTLQUOTEMARK)
10722 else if (SIT(c, BASESYNTAX) == CCTL)
10731 union node *n = redirnode;
10733 if (readtoken() != TWORD)
10734 raise_error_unexpected_syntax(-1);
10735 if (n->type == NHERE) {
10736 struct heredoc *here = heredoc;
10740 if (quoteflag == 0)
10742 TRACE(("Here document %d\n", n->type));
10743 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10744 raise_error_syntax("illegal eof marker for << redirection");
10745 rmescapes(wordtext, 0);
10746 here->eofmark = wordtext;
10748 if (heredoclist == NULL)
10749 heredoclist = here;
10751 for (p = heredoclist; p->next; p = p->next)
10755 } else if (n->type == NTOFD || n->type == NFROMFD) {
10756 fixredir(n, wordtext, 0);
10758 n->nfile.fname = makename();
10762 static union node *
10765 union node *args, **app;
10766 union node *n = NULL;
10767 union node *vars, **vpp;
10768 union node **rpp, *redir;
10770 #if ENABLE_ASH_BASH_COMPAT
10771 smallint double_brackets_flag = 0;
10772 smallint function_flag = 0;
10782 savecheckkwd = CHKALIAS;
10785 checkkwd = savecheckkwd;
10788 #if ENABLE_ASH_BASH_COMPAT
10790 if (peektoken() != TWORD)
10791 raise_error_unexpected_syntax(TWORD);
10794 case TAND: /* "&&" */
10795 case TOR: /* "||" */
10796 if (!double_brackets_flag) {
10800 wordtext = (char *) (t == TAND ? "-a" : "-o");
10803 n = stzalloc(sizeof(struct narg));
10805 /*n->narg.next = NULL; - stzalloc did it */
10806 n->narg.text = wordtext;
10807 #if ENABLE_ASH_BASH_COMPAT
10808 if (strcmp("[[", wordtext) == 0)
10809 double_brackets_flag = 1;
10810 else if (strcmp("]]", wordtext) == 0)
10811 double_brackets_flag = 0;
10813 n->narg.backquote = backquotelist;
10814 if (savecheckkwd && isassignment(wordtext)) {
10816 vpp = &n->narg.next;
10819 app = &n->narg.next;
10822 #if ENABLE_ASH_BASH_COMPAT
10823 if (function_flag) {
10824 checkkwd = CHKNL | CHKKWD;
10825 switch (peektoken()) {
10837 if (strcmp("[[", wordtext) == 0)
10841 raise_error_unexpected_syntax(-1);
10847 *rpp = n = redirnode;
10848 rpp = &n->nfile.next;
10849 parsefname(); /* read name of redirection file */
10852 IF_ASH_BASH_COMPAT(do_func:)
10853 if (args && app == &args->narg.next
10856 struct builtincmd *bcmd;
10859 /* We have a function */
10860 if (IF_ASH_BASH_COMPAT(!function_flag &&) readtoken() != TRP)
10861 raise_error_unexpected_syntax(TRP);
10862 name = n->narg.text;
10863 if (!goodname(name)
10864 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10866 raise_error_syntax("bad function name");
10869 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10870 n->narg.next = parse_command();
10873 IF_ASH_BASH_COMPAT(function_flag = 0;)
10884 n = stzalloc(sizeof(struct ncmd));
10886 n->ncmd.args = args;
10887 n->ncmd.assign = vars;
10888 n->ncmd.redirect = redir;
10892 static union node *
10893 parse_command(void)
10895 union node *n1, *n2;
10896 union node *ap, **app;
10897 union node *cp, **cpp;
10898 union node *redir, **rpp;
10905 switch (readtoken()) {
10907 raise_error_unexpected_syntax(-1);
10910 n1 = stzalloc(sizeof(struct nif));
10912 n1->nif.test = list(0);
10913 if (readtoken() != TTHEN)
10914 raise_error_unexpected_syntax(TTHEN);
10915 n1->nif.ifpart = list(0);
10917 while (readtoken() == TELIF) {
10918 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10919 n2 = n2->nif.elsepart;
10921 n2->nif.test = list(0);
10922 if (readtoken() != TTHEN)
10923 raise_error_unexpected_syntax(TTHEN);
10924 n2->nif.ifpart = list(0);
10926 if (lasttoken == TELSE)
10927 n2->nif.elsepart = list(0);
10929 n2->nif.elsepart = NULL;
10937 n1 = stzalloc(sizeof(struct nbinary));
10938 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10939 n1->nbinary.ch1 = list(0);
10942 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
10943 got == TWORD ? wordtext : ""));
10944 raise_error_unexpected_syntax(TDO);
10946 n1->nbinary.ch2 = list(0);
10951 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10952 raise_error_syntax("bad for loop variable");
10953 n1 = stzalloc(sizeof(struct nfor));
10955 n1->nfor.var = wordtext;
10956 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10957 if (readtoken() == TIN) {
10959 while (readtoken() == TWORD) {
10960 n2 = stzalloc(sizeof(struct narg));
10962 /*n2->narg.next = NULL; - stzalloc did it */
10963 n2->narg.text = wordtext;
10964 n2->narg.backquote = backquotelist;
10966 app = &n2->narg.next;
10969 n1->nfor.args = ap;
10970 if (lasttoken != TNL && lasttoken != TSEMI)
10971 raise_error_unexpected_syntax(-1);
10973 n2 = stzalloc(sizeof(struct narg));
10975 /*n2->narg.next = NULL; - stzalloc did it */
10976 n2->narg.text = (char *)dolatstr;
10977 /*n2->narg.backquote = NULL;*/
10978 n1->nfor.args = n2;
10980 * Newline or semicolon here is optional (but note
10981 * that the original Bourne shell only allowed NL).
10983 if (lasttoken != TSEMI)
10986 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10987 if (readtoken() != TDO)
10988 raise_error_unexpected_syntax(TDO);
10989 n1->nfor.body = list(0);
10993 n1 = stzalloc(sizeof(struct ncase));
10995 if (readtoken() != TWORD)
10996 raise_error_unexpected_syntax(TWORD);
10997 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10999 /*n2->narg.next = NULL; - stzalloc did it */
11000 n2->narg.text = wordtext;
11001 n2->narg.backquote = backquotelist;
11002 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11003 if (readtoken() != TIN)
11004 raise_error_unexpected_syntax(TIN);
11005 cpp = &n1->ncase.cases;
11007 checkkwd = CHKNL | CHKKWD;
11009 while (t != TESAC) {
11010 if (lasttoken == TLP)
11012 *cpp = cp = stzalloc(sizeof(struct nclist));
11014 app = &cp->nclist.pattern;
11016 *app = ap = stzalloc(sizeof(struct narg));
11018 /*ap->narg.next = NULL; - stzalloc did it */
11019 ap->narg.text = wordtext;
11020 ap->narg.backquote = backquotelist;
11021 if (readtoken() != TPIPE)
11023 app = &ap->narg.next;
11026 //ap->narg.next = NULL;
11027 if (lasttoken != TRP)
11028 raise_error_unexpected_syntax(TRP);
11029 cp->nclist.body = list(2);
11031 cpp = &cp->nclist.next;
11033 checkkwd = CHKNL | CHKKWD;
11037 raise_error_unexpected_syntax(TENDCASE);
11044 n1 = stzalloc(sizeof(struct nredir));
11045 n1->type = NSUBSHELL;
11046 n1->nredir.n = list(0);
11047 /*n1->nredir.redirect = NULL; - stzalloc did it */
11054 IF_ASH_BASH_COMPAT(case TFUNCTION:)
11058 return simplecmd();
11061 if (readtoken() != t)
11062 raise_error_unexpected_syntax(t);
11065 /* Now check for redirection which may follow command */
11066 checkkwd = CHKKWD | CHKALIAS;
11068 while (readtoken() == TREDIR) {
11069 *rpp = n2 = redirnode;
11070 rpp = &n2->nfile.next;
11076 if (n1->type != NSUBSHELL) {
11077 n2 = stzalloc(sizeof(struct nredir));
11082 n1->nredir.redirect = redir;
11087 #if ENABLE_ASH_BASH_COMPAT
11088 static int decode_dollar_squote(void)
11090 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11096 p = strchr(C_escapes, c);
11101 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11105 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11107 } else if (c == 'x') { /* \xHH */
11111 } while (isxdigit(c) && --cnt);
11113 if (cnt == 3) { /* \x but next char is "bad" */
11117 } else { /* simple seq like \\ or \t */
11122 c = bb_process_escape_sequence((void*)&p);
11123 } else { /* unrecognized "\z": print both chars unless ' or " */
11124 if (c != '\'' && c != '"') {
11126 c |= 0x100; /* "please encode \, then me" */
11134 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11135 * is not NULL, read a here document. In the latter case, eofmark is the
11136 * word which marks the end of the document and striptabs is true if
11137 * leading tabs should be stripped from the document. The argument c
11138 * is the first character of the input token or document.
11140 * Because C does not have internal subroutines, I have simulated them
11141 * using goto's to implement the subroutine linkage. The following macros
11142 * will run code that appears at the end of readtoken1.
11144 #define CHECKEND() {goto checkend; checkend_return:;}
11145 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11146 #define PARSESUB() {goto parsesub; parsesub_return:;}
11147 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11148 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11149 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11151 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11153 /* NB: syntax parameter fits into smallint */
11154 /* c parameter is an unsigned char or PEOF or PEOA */
11157 char line[EOFMARKLEN + 1];
11158 struct nodelist *bqlist;
11162 smallint prevsyntax; /* syntax before arithmetic */
11163 #if ENABLE_ASH_EXPAND_PRMT
11164 smallint pssyntax; /* we are expanding a prompt string */
11166 int varnest; /* levels of variables expansion */
11167 int arinest; /* levels of arithmetic expansion */
11168 int parenlevel; /* levels of parens in arithmetic */
11169 int dqvarnest; /* levels of variables expansion within double quotes */
11171 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11173 startlinno = g_parsefile->linno;
11177 #if ENABLE_ASH_EXPAND_PRMT
11178 pssyntax = (syntax == PSSYNTAX);
11182 dblquote = (syntax == DQSYNTAX);
11188 STARTSTACKSTR(out);
11190 /* For each line, until end of word */
11191 CHECKEND(); /* set c to PEOF if at end of here document */
11192 for (;;) { /* until end of line or end of word */
11193 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11194 switch (SIT(c, syntax)) {
11195 case CNL: /* '\n' */
11196 if (syntax == BASESYNTAX)
11197 goto endword; /* exit outer loop */
11199 g_parsefile->linno++;
11200 setprompt_if(doprompt, 2);
11202 goto loop; /* continue outer loop */
11207 if (eofmark == NULL || dblquote)
11208 USTPUTC(CTLESC, out);
11209 #if ENABLE_ASH_BASH_COMPAT
11210 if (c == '\\' && bash_dollar_squote) {
11211 c = decode_dollar_squote();
11213 USTPUTC('\\', out);
11214 c = (unsigned char)c;
11220 case CBACK: /* backslash */
11221 c = pgetc_without_PEOA();
11223 USTPUTC(CTLESC, out);
11224 USTPUTC('\\', out);
11226 } else if (c == '\n') {
11227 setprompt_if(doprompt, 2);
11229 #if ENABLE_ASH_EXPAND_PRMT
11230 if (c == '$' && pssyntax) {
11231 USTPUTC(CTLESC, out);
11232 USTPUTC('\\', out);
11235 /* Backslash is retained if we are in "str" and next char isn't special */
11240 && (c != '"' || eofmark != NULL)
11242 USTPUTC('\\', out);
11244 USTPUTC(CTLESC, out);
11252 if (eofmark == NULL) {
11253 USTPUTC(CTLQUOTEMARK, out);
11261 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11262 if (eofmark != NULL && varnest == 0) {
11265 if (dqvarnest == 0) {
11266 syntax = BASESYNTAX;
11273 case CVAR: /* '$' */
11274 PARSESUB(); /* parse substitution */
11276 case CENDVAR: /* '}' */
11279 if (dqvarnest > 0) {
11286 #if ENABLE_SH_MATH_SUPPORT
11287 case CLP: /* '(' in arithmetic */
11291 case CRP: /* ')' in arithmetic */
11292 if (parenlevel > 0) {
11295 if (pgetc() == ')') {
11297 if (--arinest == 0) {
11298 syntax = prevsyntax;
11302 * unbalanced parens
11303 * (don't 2nd guess - no error)
11311 case CBQUOTE: /* '`' */
11315 goto endword; /* exit outer loop */
11319 if (varnest == 0) {
11320 #if ENABLE_ASH_BASH_COMPAT
11322 if (pgetc() == '>')
11323 c = 0x100 + '>'; /* flag &> */
11327 goto endword; /* exit outer loop */
11329 IF_ASH_ALIAS(if (c != PEOA))
11336 #if ENABLE_SH_MATH_SUPPORT
11337 if (syntax == ARISYNTAX)
11338 raise_error_syntax("missing '))'");
11340 if (syntax != BASESYNTAX && eofmark == NULL)
11341 raise_error_syntax("unterminated quoted string");
11342 if (varnest != 0) {
11343 startlinno = g_parsefile->linno;
11345 raise_error_syntax("missing '}'");
11347 USTPUTC('\0', out);
11348 len = out - (char *)stackblock();
11349 out = stackblock();
11350 if (eofmark == NULL) {
11351 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11354 if (isdigit_str9(out)) {
11355 PARSEREDIR(); /* passed as params: out, c */
11356 lasttoken = TREDIR;
11359 /* else: non-number X seen, interpret it
11360 * as "NNNX>file" = "NNNX >file" */
11364 quoteflag = quotef;
11365 backquotelist = bqlist;
11366 grabstackblock(len);
11370 /* end of readtoken routine */
11373 * Check to see whether we are at the end of the here document. When this
11374 * is called, c is set to the first character of the next input line. If
11375 * we are at the end of the here document, this routine sets the c to PEOF.
11379 #if ENABLE_ASH_ALIAS
11381 c = pgetc_without_PEOA();
11384 while (c == '\t') {
11385 c = pgetc_without_PEOA();
11388 if (c == *eofmark) {
11389 if (pfgets(line, sizeof(line)) != NULL) {
11393 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11395 if (*p == '\n' && *q == '\0') {
11397 g_parsefile->linno++;
11398 needprompt = doprompt;
11400 pushstring(line, NULL);
11405 goto checkend_return;
11409 * Parse a redirection operator. The variable "out" points to a string
11410 * specifying the fd to be redirected. The variable "c" contains the
11411 * first character of the redirection operator.
11414 /* out is already checked to be a valid number or "" */
11415 int fd = (*out == '\0' ? -1 : atoi(out));
11418 np = stzalloc(sizeof(struct nfile));
11423 np->type = NAPPEND;
11425 np->type = NCLOBBER;
11428 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11434 #if ENABLE_ASH_BASH_COMPAT
11435 else if (c == 0x100 + '>') { /* this flags &> redirection */
11437 pgetc(); /* this is '>', no need to check */
11441 else { /* c == '<' */
11442 /*np->nfile.fd = 0; - stzalloc did it */
11446 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11447 np = stzalloc(sizeof(struct nhere));
11448 /*np->nfile.fd = 0; - stzalloc did it */
11451 heredoc = stzalloc(sizeof(struct heredoc));
11452 heredoc->here = np;
11455 heredoc->striptabs = 1;
11457 /*heredoc->striptabs = 0; - stzalloc did it */
11463 np->type = NFROMFD;
11467 np->type = NFROMTO;
11479 goto parseredir_return;
11483 * Parse a substitution. At this point, we have read the dollar sign
11484 * and nothing else.
11487 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11488 * (assuming ascii char codes, as the original implementation did) */
11489 #define is_special(c) \
11490 (((unsigned)(c) - 33 < 32) \
11491 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11493 unsigned char subtype;
11498 if (c > 255 /* PEOA or PEOF */
11499 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11501 #if ENABLE_ASH_BASH_COMPAT
11503 bash_dollar_squote = 1;
11508 } else if (c == '(') {
11509 /* $(command) or $((arith)) */
11510 if (pgetc() == '(') {
11511 #if ENABLE_SH_MATH_SUPPORT
11514 raise_error_syntax("you disabled math support for $((arith)) syntax");
11521 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11522 USTPUTC(CTLVAR, out);
11523 typeloc = out - (char *)stackblock();
11524 USTPUTC(VSNORMAL, out);
11525 subtype = VSNORMAL;
11531 c = '#'; /* ${#} - same as $# */
11533 subtype = VSLENGTH; /* ${#VAR} */
11538 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11539 /* $[{[#]]NAME[}] */
11543 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11544 } else if (isdigit(c)) {
11545 /* $[{[#]]NUM[}] */
11549 } while (isdigit(c));
11550 } else if (is_special(c)) {
11551 /* $[{[#]]<specialchar>[}] */
11556 raise_error_syntax("bad substitution");
11558 if (c != '}' && subtype == VSLENGTH) {
11559 /* ${#VAR didn't end with } */
11565 if (subtype == 0) {
11566 /* ${VAR...} but not $VAR or ${#VAR} */
11567 /* c == first char after VAR */
11571 #if ENABLE_ASH_BASH_COMPAT
11572 if (c == ':' || c == '$' || isdigit(c)) {
11573 //TODO: support more general format ${v:EXPR:EXPR},
11574 // where EXPR follows $(()) rules
11575 subtype = VSSUBSTR;
11577 break; /* "goto do_pungetc" is bigger (!) */
11583 static const char types[] ALIGN1 = "}-+?=";
11584 const char *p = strchr(types, c);
11587 subtype = p - types + VSNORMAL;
11593 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11600 #if ENABLE_ASH_BASH_COMPAT
11602 /* ${v/[/]pattern/repl} */
11603 //TODO: encode pattern and repl separately.
11604 // Currently ${v/$var_with_slash/repl} is horribly broken
11605 subtype = VSREPLACE;
11609 subtype++; /* VSREPLACEALL */
11617 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11618 if (subtype != VSNORMAL) {
11625 goto parsesub_return;
11629 * Called to parse command substitutions. Newstyle is set if the command
11630 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11631 * list of commands (passed by reference), and savelen is the number of
11632 * characters on the top of the stack which must be preserved.
11635 struct nodelist **nlpp;
11639 smallint saveprompt = 0;
11642 savelen = out - (char *)stackblock();
11644 str = alloca(savelen);
11645 memcpy(str, stackblock(), savelen);
11648 /* We must read until the closing backquote, giving special
11649 * treatment to some slashes, and then push the string and
11650 * reread it as input, interpreting it normally.
11656 STARTSTACKSTR(pout);
11660 setprompt_if(needprompt, 2);
11669 g_parsefile->linno++;
11670 setprompt_if(doprompt, 2);
11672 * If eating a newline, avoid putting
11673 * the newline into the new character
11674 * stream (via the STPUTC after the
11679 if (pc != '\\' && pc != '`' && pc != '$'
11680 && (!dblquote || pc != '"')
11682 STPUTC('\\', pout);
11684 if (pc <= 255 /* not PEOA or PEOF */) {
11690 IF_ASH_ALIAS(case PEOA:)
11691 startlinno = g_parsefile->linno;
11692 raise_error_syntax("EOF in backquote substitution");
11695 g_parsefile->linno++;
11696 needprompt = doprompt;
11705 STPUTC('\0', pout);
11706 psavelen = pout - (char *)stackblock();
11707 if (psavelen > 0) {
11708 pstr = grabstackstr(pout);
11709 setinputstring(pstr);
11714 nlpp = &(*nlpp)->next;
11715 *nlpp = stzalloc(sizeof(**nlpp));
11716 /* (*nlpp)->next = NULL; - stzalloc did it */
11719 saveprompt = doprompt;
11726 doprompt = saveprompt;
11727 else if (readtoken() != TRP)
11728 raise_error_unexpected_syntax(TRP);
11733 * Start reading from old file again, ignoring any pushed back
11734 * tokens left from the backquote parsing
11739 while (stackblocksize() <= savelen)
11741 STARTSTACKSTR(out);
11743 memcpy(out, str, savelen);
11744 STADJUST(savelen, out);
11746 USTPUTC(CTLBACKQ, out);
11748 goto parsebackq_oldreturn;
11749 goto parsebackq_newreturn;
11752 #if ENABLE_SH_MATH_SUPPORT
11754 * Parse an arithmetic expansion (indicate start of one and set state)
11757 if (++arinest == 1) {
11758 prevsyntax = syntax;
11759 syntax = ARISYNTAX;
11761 USTPUTC(CTLARI, out);
11762 goto parsearith_return;
11765 } /* end of readtoken */
11768 * Read the next input token.
11769 * If the token is a word, we set backquotelist to the list of cmds in
11770 * backquotes. We set quoteflag to true if any part of the word was
11772 * If the token is TREDIR, then we set redirnode to a structure containing
11774 * In all cases, the variable startlinno is set to the number of the line
11775 * on which the token starts.
11777 * [Change comment: here documents and internal procedures]
11778 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11779 * word parsing code into a separate routine. In this case, readtoken
11780 * doesn't need to have any internal procedures, but parseword does.
11781 * We could also make parseoperator in essence the main routine, and
11782 * have parseword (readtoken1?) handle both words and redirection.]
11784 #define NEW_xxreadtoken
11785 #ifdef NEW_xxreadtoken
11786 /* singles must be first! */
11787 static const char xxreadtoken_chars[7] ALIGN1 = {
11788 '\n', '(', ')', /* singles */
11789 '&', '|', ';', /* doubles */
11793 #define xxreadtoken_singles 3
11794 #define xxreadtoken_doubles 3
11796 static const char xxreadtoken_tokens[] ALIGN1 = {
11797 TNL, TLP, TRP, /* only single occurrence allowed */
11798 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11799 TEOF, /* corresponds to trailing nul */
11800 TAND, TOR, TENDCASE /* if double occurrence */
11812 setprompt_if(needprompt, 2);
11813 startlinno = g_parsefile->linno;
11814 for (;;) { /* until token or start of word found */
11816 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11820 while ((c = pgetc()) != '\n' && c != PEOF)
11823 } else if (c == '\\') {
11824 if (pgetc() != '\n') {
11826 break; /* return readtoken1(...) */
11828 startlinno = ++g_parsefile->linno;
11829 setprompt_if(doprompt, 2);
11833 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11836 g_parsefile->linno++;
11837 needprompt = doprompt;
11840 p = strchr(xxreadtoken_chars, c);
11842 break; /* return readtoken1(...) */
11844 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11846 if (cc == c) { /* double occurrence? */
11847 p += xxreadtoken_doubles + 1;
11850 #if ENABLE_ASH_BASH_COMPAT
11851 if (c == '&' && cc == '>') /* &> */
11852 break; /* return readtoken1(...) */
11857 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11862 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11864 #else /* old xxreadtoken */
11865 #define RETURN(token) return lasttoken = token
11875 setprompt_if(needprompt, 2);
11876 startlinno = g_parsefile->linno;
11877 for (;;) { /* until token or start of word found */
11880 case ' ': case '\t':
11881 IF_ASH_ALIAS(case PEOA:)
11884 while ((c = pgetc()) != '\n' && c != PEOF)
11889 if (pgetc() == '\n') {
11890 startlinno = ++g_parsefile->linno;
11891 setprompt_if(doprompt, 2);
11897 g_parsefile->linno++;
11898 needprompt = doprompt;
11903 if (pgetc() == '&')
11908 if (pgetc() == '|')
11913 if (pgetc() == ';')
11926 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11929 #endif /* old xxreadtoken */
11935 int kwd = checkkwd;
11937 smallint alreadyseen = tokpushback;
11940 #if ENABLE_ASH_ALIAS
11956 if (t != TWORD || quoteflag) {
11961 * check for keywords
11963 if (kwd & CHKKWD) {
11964 const char *const *pp;
11966 pp = findkwd(wordtext);
11968 lasttoken = t = pp - tokname_array;
11969 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
11974 if (checkkwd & CHKALIAS) {
11975 #if ENABLE_ASH_ALIAS
11977 ap = lookupalias(wordtext, 1);
11980 pushstring(ap->val, ap);
11990 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11992 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
12008 * Read and parse a command. Returns NODE_EOF on end of file.
12009 * (NULL is a valid parse tree indicating a blank line.)
12011 static union node *
12012 parsecmd(int interact)
12017 doprompt = interact;
12018 setprompt_if(doprompt, doprompt);
12024 * Input any here documents.
12029 struct heredoc *here;
12032 here = heredoclist;
12033 heredoclist = NULL;
12036 setprompt_if(needprompt, 2);
12037 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12038 here->eofmark, here->striptabs);
12039 n = stzalloc(sizeof(struct narg));
12040 n->narg.type = NARG;
12041 /*n->narg.next = NULL; - stzalloc did it */
12042 n->narg.text = wordtext;
12043 n->narg.backquote = backquotelist;
12044 here->here->nhere.doc = n;
12051 * called by editline -- any expansions to the prompt should be added here.
12053 #if ENABLE_ASH_EXPAND_PRMT
12054 static const char *
12055 expandstr(const char *ps)
12059 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12060 * and token processing _can_ alter it (delete NULs etc). */
12061 setinputstring((char *)ps);
12062 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12065 n.narg.type = NARG;
12066 n.narg.next = NULL;
12067 n.narg.text = wordtext;
12068 n.narg.backquote = backquotelist;
12070 expandarg(&n, NULL, EXP_QUOTED);
12071 return stackblock();
12076 * Execute a command or commands contained in a string.
12079 evalstring(char *s, int mask)
12082 struct stackmark smark;
12086 setstackmark(&smark);
12089 while ((n = parsecmd(0)) != NODE_EOF) {
12091 popstackmark(&smark);
12104 * The eval command.
12106 static int FAST_FUNC
12107 evalcmd(int argc UNUSED_PARAM, char **argv)
12116 STARTSTACKSTR(concat);
12118 concat = stack_putstr(p, concat);
12122 STPUTC(' ', concat);
12124 STPUTC('\0', concat);
12125 p = grabstackstr(concat);
12127 evalstring(p, ~SKIPEVAL);
12133 * Read and execute commands.
12134 * "Top" is nonzero for the top level command loop;
12135 * it turns on prompting if the shell is interactive.
12141 struct stackmark smark;
12145 TRACE(("cmdloop(%d) called\n", top));
12149 setstackmark(&smark);
12152 showjobs(SHOW_CHANGED|SHOW_STDERR);
12155 if (iflag && top) {
12159 n = parsecmd(inter);
12161 if (DEBUG > 2 && debug && (n != NODE_EOF))
12164 if (n == NODE_EOF) {
12165 if (!top || numeof >= 50)
12167 if (!stoppedjobs()) {
12170 out2str("\nUse \"exit\" to leave shell.\n");
12173 } else if (nflag == 0) {
12174 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12179 popstackmark(&smark);
12184 return skip & SKIPEVAL;
12191 * Take commands from a file. To be compatible we should do a path
12192 * search for the file, which is necessary to find sub-commands.
12195 find_dot_file(char *name)
12198 const char *path = pathval();
12201 /* don't try this for absolute or relative paths */
12202 if (strchr(name, '/'))
12205 /* IIRC standards do not say whether . is to be searched.
12206 * And it is even smaller this way, making it unconditional for now:
12208 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12213 while ((fullname = path_advance(&path, name)) != NULL) {
12215 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12217 * Don't bother freeing here, since it will
12218 * be freed by the caller.
12222 if (fullname != name)
12223 stunalloc(fullname);
12226 /* not found in the PATH */
12227 ash_msg_and_raise_error("%s: not found", name);
12231 static int FAST_FUNC
12232 dotcmd(int argc, char **argv)
12235 struct strlist *sp;
12236 volatile struct shparam saveparam;
12238 for (sp = cmdenviron; sp; sp = sp->next)
12239 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12242 /* bash says: "bash: .: filename argument required" */
12243 return 2; /* bash compat */
12246 /* "false; . empty_file; echo $?" should print 0, not 1: */
12249 /* This aborts if file isn't found, which is POSIXly correct.
12250 * bash returns exitcode 1 instead.
12252 fullname = find_dot_file(argv[1]);
12255 if (argc) { /* argc > 0, argv[0] != NULL */
12256 saveparam = shellparam;
12257 shellparam.malloced = 0;
12258 shellparam.nparam = argc;
12259 shellparam.p = argv;
12262 /* This aborts if file can't be opened, which is POSIXly correct.
12263 * bash returns exitcode 1 instead.
12265 setinputfile(fullname, INPUT_PUSH_FILE);
12266 commandname = fullname;
12271 freeparam(&shellparam);
12272 shellparam = saveparam;
12278 static int FAST_FUNC
12279 exitcmd(int argc UNUSED_PARAM, char **argv)
12284 exitstatus = number(argv[1]);
12285 raise_exception(EXEXIT);
12290 * Read a file containing shell functions.
12293 readcmdfile(char *name)
12295 setinputfile(name, INPUT_PUSH_FILE);
12301 /* ============ find_command inplementation */
12304 * Resolve a command name. If you change this routine, you may have to
12305 * change the shellexec routine as well.
12308 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12310 struct tblentry *cmdp;
12317 struct builtincmd *bcmd;
12319 /* If name contains a slash, don't use PATH or hash table */
12320 if (strchr(name, '/') != NULL) {
12321 entry->u.index = -1;
12322 if (act & DO_ABS) {
12323 while (stat(name, &statb) < 0) {
12325 if (errno == EINTR)
12328 entry->cmdtype = CMDUNKNOWN;
12332 entry->cmdtype = CMDNORMAL;
12336 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12338 updatetbl = (path == pathval());
12341 if (strstr(path, "%builtin") != NULL)
12342 act |= DO_ALTBLTIN;
12345 /* If name is in the table, check answer will be ok */
12346 cmdp = cmdlookup(name, 0);
12347 if (cmdp != NULL) {
12350 switch (cmdp->cmdtype) {
12368 } else if (cmdp->rehash == 0)
12369 /* if not invalidated by cd, we're done */
12373 /* If %builtin not in path, check for builtin next */
12374 bcmd = find_builtin(name);
12376 if (IS_BUILTIN_REGULAR(bcmd))
12377 goto builtin_success;
12378 if (act & DO_ALTPATH) {
12379 if (!(act & DO_ALTBLTIN))
12380 goto builtin_success;
12381 } else if (builtinloc <= 0) {
12382 goto builtin_success;
12386 #if ENABLE_FEATURE_SH_STANDALONE
12388 int applet_no = find_applet_by_name(name);
12389 if (applet_no >= 0) {
12390 entry->cmdtype = CMDNORMAL;
12391 entry->u.index = -2 - applet_no;
12397 /* We have to search path. */
12398 prev = -1; /* where to start */
12399 if (cmdp && cmdp->rehash) { /* doing a rehash */
12400 if (cmdp->cmdtype == CMDBUILTIN)
12403 prev = cmdp->param.index;
12409 while ((fullname = path_advance(&path, name)) != NULL) {
12410 stunalloc(fullname);
12411 /* NB: code below will still use fullname
12412 * despite it being "unallocated" */
12415 if (prefix(pathopt, "builtin")) {
12417 goto builtin_success;
12420 if ((act & DO_NOFUNC)
12421 || !prefix(pathopt, "func")
12422 ) { /* ignore unimplemented options */
12426 /* if rehash, don't redo absolute path names */
12427 if (fullname[0] == '/' && idx <= prev) {
12430 TRACE(("searchexec \"%s\": no change\n", name));
12433 while (stat(fullname, &statb) < 0) {
12435 if (errno == EINTR)
12438 if (errno != ENOENT && errno != ENOTDIR)
12442 e = EACCES; /* if we fail, this will be the error */
12443 if (!S_ISREG(statb.st_mode))
12445 if (pathopt) { /* this is a %func directory */
12446 stalloc(strlen(fullname) + 1);
12447 /* NB: stalloc will return space pointed by fullname
12448 * (because we don't have any intervening allocations
12449 * between stunalloc above and this stalloc) */
12450 readcmdfile(fullname);
12451 cmdp = cmdlookup(name, 0);
12452 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12453 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12454 stunalloc(fullname);
12457 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12459 entry->cmdtype = CMDNORMAL;
12460 entry->u.index = idx;
12464 cmdp = cmdlookup(name, 1);
12465 cmdp->cmdtype = CMDNORMAL;
12466 cmdp->param.index = idx;
12471 /* We failed. If there was an entry for this command, delete it */
12472 if (cmdp && updatetbl)
12473 delete_cmd_entry();
12475 ash_msg("%s: %s", name, errmsg(e, "not found"));
12476 entry->cmdtype = CMDUNKNOWN;
12481 entry->cmdtype = CMDBUILTIN;
12482 entry->u.cmd = bcmd;
12486 cmdp = cmdlookup(name, 1);
12487 cmdp->cmdtype = CMDBUILTIN;
12488 cmdp->param.cmd = bcmd;
12492 entry->cmdtype = cmdp->cmdtype;
12493 entry->u = cmdp->param;
12497 /* ============ trap.c */
12500 * The trap builtin.
12502 static int FAST_FUNC
12503 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12507 int signo, exitcode;
12512 for (signo = 0; signo < NSIG; signo++) {
12513 char *tr = trap_ptr[signo];
12515 /* note: bash adds "SIG", but only if invoked
12516 * as "bash". If called as "sh", or if set -o posix,
12517 * then it prints short signal names.
12518 * We are printing short names: */
12519 out1fmt("trap -- %s %s\n",
12521 get_signame(signo));
12522 /* trap_ptr != trap only if we are in special-cased `trap` code.
12523 * In this case, we will exit very soon, no need to free(). */
12524 /* if (trap_ptr != trap && tp[0]) */
12529 if (trap_ptr != trap) {
12542 signo = get_signum(*ap);
12544 /* Mimic bash message exactly */
12545 ash_msg("%s: invalid signal specification", *ap);
12551 if (LONE_DASH(action))
12554 action = ckstrdup(action);
12558 may_have_traps = 1;
12559 trap[signo] = action;
12570 /* ============ Builtins */
12572 #if ENABLE_ASH_HELP
12573 static int FAST_FUNC
12574 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12580 "Built-in commands:\n"
12581 "------------------\n");
12582 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12583 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12584 builtintab[i].name + 1);
12590 # if ENABLE_FEATURE_SH_STANDALONE
12592 const char *a = applet_names;
12594 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12599 a += strlen(a) + 1;
12604 return EXIT_SUCCESS;
12609 static int FAST_FUNC
12610 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12612 show_history(line_input_state);
12613 return EXIT_SUCCESS;
12618 * The export and readonly commands.
12620 static int FAST_FUNC
12621 exportcmd(int argc UNUSED_PARAM, char **argv)
12631 /* "readonly" in bash accepts, but ignores -n.
12632 * We do the same: it saves a conditional in nextopt's param.
12635 while ((opt = nextopt("np")) != '\0') {
12637 flag_off = VEXPORT;
12640 if (argv[0][0] == 'r') {
12642 flag_off = 0; /* readonly ignores -n */
12644 flag_off = ~flag_off;
12646 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12652 p = strchr(name, '=');
12656 vp = *findvar(hashvar(name), name);
12658 vp->flags = ((vp->flags | flag) & flag_off);
12662 setvar(name, p, (flag & flag_off));
12663 } while ((name = *++aptr) != NULL);
12668 /* No arguments. Show the list of exported or readonly vars.
12671 showvars(argv[0], flag, 0);
12676 * Delete a function if it exists.
12679 unsetfunc(const char *name)
12681 struct tblentry *cmdp;
12683 cmdp = cmdlookup(name, 0);
12684 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12685 delete_cmd_entry();
12689 * The unset builtin command. We unset the function before we unset the
12690 * variable to allow a function to be unset when there is a readonly variable
12691 * with the same name.
12693 static int FAST_FUNC
12694 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12701 while ((i = nextopt("vf")) != 0) {
12705 for (ap = argptr; *ap; ap++) {
12718 static const unsigned char timescmd_str[] ALIGN1 = {
12719 ' ', offsetof(struct tms, tms_utime),
12720 '\n', offsetof(struct tms, tms_stime),
12721 ' ', offsetof(struct tms, tms_cutime),
12722 '\n', offsetof(struct tms, tms_cstime),
12725 static int FAST_FUNC
12726 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12728 unsigned long clk_tck, s, t;
12729 const unsigned char *p;
12732 clk_tck = bb_clk_tck();
12737 t = *(clock_t *)(((char *) &buf) + p[1]);
12740 out1fmt("%lum%lu.%03lus%c",
12742 (t * 1000) / clk_tck,
12750 #if ENABLE_SH_MATH_SUPPORT
12752 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12753 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12755 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12757 static int FAST_FUNC
12758 letcmd(int argc UNUSED_PARAM, char **argv)
12764 ash_msg_and_raise_error("expression expected");
12766 i = ash_arith(*argv);
12774 * The read builtin. Options:
12775 * -r Do not interpret '\' specially
12776 * -s Turn off echo (tty only)
12777 * -n NCHARS Read NCHARS max
12778 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12779 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12780 * -u FD Read from given FD instead of fd 0
12781 * This uses unbuffered input, which may be avoidable in some cases.
12782 * TODO: bash also has:
12783 * -a ARRAY Read into array[0],[1],etc
12784 * -d DELIM End on DELIM char, not newline
12785 * -e Use line editing (tty only)
12787 static int FAST_FUNC
12788 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12790 char *opt_n = NULL;
12791 char *opt_p = NULL;
12792 char *opt_t = NULL;
12793 char *opt_u = NULL;
12794 int read_flags = 0;
12798 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12807 read_flags |= BUILTIN_READ_SILENT;
12813 read_flags |= BUILTIN_READ_RAW;
12823 /* "read -s" needs to save/restore termios, can't allow ^C
12824 * to jump out of it.
12827 r = shell_builtin_read(setvar0,
12829 bltinlookup("IFS"), /* can be NULL */
12838 if ((uintptr_t)r > 1)
12839 ash_msg_and_raise_error(r);
12841 return (uintptr_t)r;
12844 static int FAST_FUNC
12845 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12847 static const char permuser[3] ALIGN1 = "ogu";
12850 int symbolic_mode = 0;
12852 while (nextopt("S") != '\0') {
12861 if (*argptr == NULL) {
12862 if (symbolic_mode) {
12863 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
12870 *p++ = permuser[i];
12872 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
12873 if (!(mask & 0400)) *p++ = 'r';
12874 if (!(mask & 0200)) *p++ = 'w';
12875 if (!(mask & 0100)) *p++ = 'x';
12883 out1fmt("%04o\n", mask);
12886 char *modestr = *argptr;
12887 /* numeric umasks are taken as-is */
12888 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
12889 if (!isdigit(modestr[0]))
12891 mask = bb_parse_mode(modestr, mask);
12892 if ((unsigned)mask > 0777) {
12893 ash_msg_and_raise_error("illegal mode: %s", modestr);
12895 if (!isdigit(modestr[0]))
12902 static int FAST_FUNC
12903 ulimitcmd(int argc UNUSED_PARAM, char **argv)
12905 return shell_builtin_ulimit(argv);
12908 /* ============ main() and helpers */
12911 * Called to exit the shell.
12920 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
12921 save_history(line_input_state);
12924 status = exitstatus;
12925 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12926 if (setjmp(loc.loc)) {
12927 if (exception_type == EXEXIT)
12928 /* dash bug: it just does _exit(exitstatus) here
12929 * but we have to do setjobctl(0) first!
12930 * (bug is still not fixed in dash-0.5.3 - if you run dash
12931 * under Midnight Commander, on exit from dash MC is backgrounded) */
12932 status = exitstatus;
12935 exception_handler = &loc;
12942 flush_stdout_stderr();
12952 /* from input.c: */
12953 /* we will never free this */
12954 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
12957 signal(SIGCHLD, SIG_DFL);
12958 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12959 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12961 signal(SIGHUP, SIG_DFL);
12967 struct stat st1, st2;
12970 for (envp = environ; envp && *envp; envp++) {
12971 if (strchr(*envp, '=')) {
12972 setvareq(*envp, VEXPORT|VTEXTFIXED);
12976 setvar0("PPID", utoa(getppid()));
12977 #if ENABLE_ASH_BASH_COMPAT
12978 p = lookupvar("SHLVL");
12979 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
12980 if (!lookupvar("HOSTNAME")) {
12981 struct utsname uts;
12983 setvar0("HOSTNAME", uts.nodename);
12986 p = lookupvar("PWD");
12988 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12989 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
12999 //usage:#define ash_trivial_usage
13000 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13001 //usage:#define ash_full_usage "\n\n"
13002 //usage: "Unix shell interpreter"
13004 //usage:#if ENABLE_FEATURE_SH_IS_ASH
13005 //usage:# define sh_trivial_usage ash_trivial_usage
13006 //usage:# define sh_full_usage ash_full_usage
13008 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
13009 //usage:# define bash_trivial_usage ash_trivial_usage
13010 //usage:# define bash_full_usage ash_full_usage
13014 * Process the shell command line arguments.
13017 procargs(char **argv)
13020 const char *xminusc;
13025 /* if (xargv[0]) - mmm, this is always true! */
13027 for (i = 0; i < NOPTS; i++)
13030 if (options(/*cmdline:*/ 1)) {
13031 /* it already printed err message */
13032 raise_exception(EXERROR);
13036 if (*xargv == NULL) {
13038 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13041 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13045 for (i = 0; i < NOPTS; i++)
13046 if (optlist[i] == 2)
13051 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13056 } else if (!sflag) {
13057 setinputfile(*xargv, 0);
13060 commandname = arg0;
13063 shellparam.p = xargv;
13064 #if ENABLE_ASH_GETOPTS
13065 shellparam.optind = 1;
13066 shellparam.optoff = -1;
13068 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13070 shellparam.nparam++;
13077 * Read /etc/profile or .profile.
13080 read_profile(const char *name)
13084 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13093 * This routine is called when an error or an interrupt occurs in an
13094 * interactive shell and control is returned to the main command loop.
13102 /* from input.c: */
13103 g_parsefile->left_in_buffer = 0;
13104 g_parsefile->left_in_line = 0; /* clear input buffer */
13106 /* from parser.c: */
13109 /* from redir.c: */
13110 clearredir(/*drop:*/ 0);
13114 static short profile_buf[16384];
13115 extern int etext();
13119 * Main routine. We initialize things, parse the arguments, execute
13120 * profiles if we're a login shell, and then call cmdloop to execute
13121 * commands. The setjmp call sets up the location to jump to when an
13122 * exception occurs. When an exception occurs the variable "state"
13123 * is used to figure out how far we had gotten.
13125 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13126 int ash_main(int argc UNUSED_PARAM, char **argv)
13128 const char *shinit;
13129 volatile smallint state;
13130 struct jmploc jmploc;
13131 struct stackmark smark;
13133 /* Initialize global data */
13137 #if ENABLE_ASH_ALIAS
13143 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13146 #if ENABLE_FEATURE_EDITING
13147 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13150 if (setjmp(jmploc.loc)) {
13156 e = exception_type;
13160 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13164 newline_and_flush(stderr);
13167 popstackmark(&smark);
13168 FORCE_INT_ON; /* enable interrupts */
13177 exception_handler = &jmploc;
13180 TRACE(("Shell args: "));
13181 trace_puts_args(argv);
13183 rootpid = getpid();
13186 setstackmark(&smark);
13189 if (argv[0] && argv[0][0] == '-')
13195 read_profile("/etc/profile");
13198 hp = lookupvar("HOME");
13200 hp = concat_path_file(hp, ".profile");
13209 getuid() == geteuid() && getgid() == getegid() &&
13213 shinit = lookupvar("ENV");
13214 if (shinit != NULL && *shinit != '\0') {
13215 read_profile(shinit);
13221 /* evalstring pushes parsefile stack.
13222 * Ensure we don't falsely claim that 0 (stdin)
13223 * is one of stacked source fds.
13224 * Testcase: ash -c 'exec 1>&0' must not complain. */
13225 // if (!sflag) g_parsefile->pf_fd = -1;
13226 // ^^ not necessary since now we special-case fd 0
13227 // in is_hidden_fd() to not be considered "hidden fd"
13228 evalstring(minusc, 0);
13231 if (sflag || minusc == NULL) {
13232 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13234 const char *hp = lookupvar("HISTFILE");
13236 hp = lookupvar("HOME");
13238 hp = concat_path_file(hp, ".ash_history");
13239 setvar0("HISTFILE", hp);
13241 hp = lookupvar("HISTFILE");
13245 line_input_state->hist_file = hp;
13246 # if ENABLE_FEATURE_SH_HISTFILESIZE
13247 hp = lookupvar("HISTFILESIZE");
13248 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13252 state4: /* XXX ??? - why isn't this before the "if" statement */
13260 extern void _mcleanup(void);
13264 TRACE(("End of main reached\n"));
13271 * Copyright (c) 1989, 1991, 1993, 1994
13272 * The Regents of the University of California. All rights reserved.
13274 * This code is derived from software contributed to Berkeley by
13275 * Kenneth Almquist.
13277 * Redistribution and use in source and binary forms, with or without
13278 * modification, are permitted provided that the following conditions
13280 * 1. Redistributions of source code must retain the above copyright
13281 * notice, this list of conditions and the following disclaimer.
13282 * 2. Redistributions in binary form must reproduce the above copyright
13283 * notice, this list of conditions and the following disclaimer in the
13284 * documentation and/or other materials provided with the distribution.
13285 * 3. Neither the name of the University nor the names of its contributors
13286 * may be used to endorse or promote products derived from this software
13287 * without specific prior written permission.
13289 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13290 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13291 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13292 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13293 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13294 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13295 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13296 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13297 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13298 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF