1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
20 * The following should be set to reflect the type of system you have:
21 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22 * define SYSV if you are running under System V.
23 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24 * define DEBUG=2 to compile in and turn on debugging.
26 * When debugging is on (DEBUG is 1 and "set -o debug" was executed),
27 * debugging info will be written to ./trace and a quit signal
28 * will generate a core dump.
31 /* Tweak debug output verbosity here */
38 #define JOBS ENABLE_ASH_JOB_CONTROL
42 #include <sys/times.h>
43 #include <sys/utsname.h> /* for setting $HOSTNAME */
45 #include "busybox.h" /* for applet_names */
48 #include "shell_common.h"
49 #if ENABLE_SH_MATH_SUPPORT
52 #if ENABLE_ASH_RANDOM_SUPPORT
55 # define CLEAR_RANDOM_T(rnd) ((void)0)
58 #include "NUM_APPLETS.h"
60 /* STANDALONE does not make sense, and won't compile */
61 # undef CONFIG_FEATURE_SH_STANDALONE
62 # undef ENABLE_FEATURE_SH_STANDALONE
63 # undef IF_FEATURE_SH_STANDALONE
64 # undef IF_NOT_FEATURE_SH_STANDALONE
65 # define ENABLE_FEATURE_SH_STANDALONE 0
66 # define IF_FEATURE_SH_STANDALONE(...)
67 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
71 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
75 # error "Do not even bother, ash will not run on NOMMU machine"
81 //config: depends on !NOMMU
83 //config: Tha 'ash' shell adds about 60k in the default configuration and is
84 //config: the most complete and most pedantically correct shell included with
85 //config: busybox. This shell is actually a derivative of the Debian 'dash'
86 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
87 //config: (written by Kenneth Almquist) from NetBSD.
89 //config:config ASH_BASH_COMPAT
90 //config: bool "bash-compatible extensions"
92 //config: depends on ASH
94 //config: Enable bash-compatible extensions.
96 //config:config ASH_IDLE_TIMEOUT
97 //config: bool "Idle timeout variable"
99 //config: depends on ASH
101 //config: Enables bash-like auto-logout after $TMOUT seconds of idle time.
103 //config:config ASH_JOB_CONTROL
104 //config: bool "Job control"
106 //config: depends on ASH
108 //config: Enable job control in the ash shell.
110 //config:config ASH_ALIAS
111 //config: bool "Alias support"
113 //config: depends on ASH
115 //config: Enable alias support in the ash shell.
117 //config:config ASH_GETOPTS
118 //config: bool "Builtin getopt to parse positional parameters"
120 //config: depends on ASH
122 //config: Enable support for getopts builtin in ash.
124 //config:config ASH_BUILTIN_ECHO
125 //config: bool "Builtin version of 'echo'"
127 //config: depends on ASH
129 //config: Enable support for echo builtin in ash.
131 //config:config ASH_BUILTIN_PRINTF
132 //config: bool "Builtin version of 'printf'"
134 //config: depends on ASH
136 //config: Enable support for printf builtin in ash.
138 //config:config ASH_BUILTIN_TEST
139 //config: bool "Builtin version of 'test'"
141 //config: depends on ASH
143 //config: Enable support for test builtin in ash.
145 //config:config ASH_HELP
146 //config: bool "help builtin"
148 //config: depends on ASH
150 //config: Enable help builtin in ash.
152 //config:config ASH_CMDCMD
153 //config: bool "'command' command to override shell builtins"
155 //config: depends on ASH
157 //config: Enable support for the ash 'command' builtin, which allows
158 //config: you to run the specified command with the specified arguments,
159 //config: even when there is an ash builtin command with the same name.
161 //config:config ASH_MAIL
162 //config: bool "Check for new mail on interactive shells"
164 //config: depends on ASH
166 //config: Enable "check for new mail" function in the ash shell.
168 //config:config ASH_OPTIMIZE_FOR_SIZE
169 //config: bool "Optimize for size instead of speed"
171 //config: depends on ASH
173 //config: Compile ash for reduced size at the price of speed.
175 //config:config ASH_RANDOM_SUPPORT
176 //config: bool "Pseudorandom generator and $RANDOM variable"
178 //config: depends on ASH
180 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
181 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
182 //config: You can reset the generator by using a specified start value.
183 //config: After "unset RANDOM" the generator will switch off and this
184 //config: variable will no longer have special treatment.
186 //config:config ASH_EXPAND_PRMT
187 //config: bool "Expand prompt string"
189 //config: depends on ASH
191 //config: "PS#" may contain volatile content, such as backquote commands.
192 //config: This option recreates the prompt string from the environment
193 //config: variable each time it is displayed.
196 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
197 //applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, sh))
198 //applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, bash))
200 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
201 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
204 /* ============ Hash table sizes. Configurable. */
208 #define CMDTABLESIZE 31 /* should be prime */
211 /* ============ Shell options */
213 static const char *const optletters_optnames[] = {
228 #if ENABLE_ASH_BASH_COMPAT
237 #define optletters(n) optletters_optnames[n][0]
238 #define optnames(n) (optletters_optnames[n] + 1)
240 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
243 /* ============ Misc data */
245 #define msg_illnum "Illegal number: %s"
248 * We enclose jmp_buf in a structure so that we can declare pointers to
249 * jump locations. The global variable handler contains the location to
250 * jump to when an exception occurs, and the global variable exception_type
251 * contains a code identifying the exception. To implement nested
252 * exception handlers, the user should save the value of handler on entry
253 * to an inner scope, set handler to point to a jmploc structure for the
254 * inner scope, and restore handler on exit from the scope.
260 struct globals_misc {
261 /* pid of main shell */
263 /* shell level: 0 for the main shell, 1 for its children, and so on */
265 #define rootshell (!shlvl)
266 char *minusc; /* argument to -c option */
268 char *curdir; // = nullstr; /* current working directory */
269 char *physdir; // = nullstr; /* physical working directory */
271 char *arg0; /* value of $0 */
273 struct jmploc *exception_handler;
275 volatile int suppress_int; /* counter */
276 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
277 /* last pending signal */
278 volatile /*sig_atomic_t*/ smallint pending_sig;
279 smallint exception_type; /* kind of exception (0..5) */
281 #define EXINT 0 /* SIGINT received */
282 #define EXERROR 1 /* a generic error */
283 #define EXSHELLPROC 2 /* execute a shell procedure */
284 #define EXEXEC 3 /* command execution failed */
285 #define EXEXIT 4 /* exit the shell */
286 #define EXSIG 5 /* trapped signal in wait(1) */
289 char nullstr[1]; /* zero length string */
292 #define eflag optlist[0]
293 #define fflag optlist[1]
294 #define Iflag optlist[2]
295 #define iflag optlist[3]
296 #define mflag optlist[4]
297 #define nflag optlist[5]
298 #define sflag optlist[6]
299 #define xflag optlist[7]
300 #define vflag optlist[8]
301 #define Cflag optlist[9]
302 #define aflag optlist[10]
303 #define bflag optlist[11]
304 #define uflag optlist[12]
305 #define viflag optlist[13]
306 #if ENABLE_ASH_BASH_COMPAT
307 # define pipefail optlist[14]
312 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
313 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
316 /* trap handler commands */
318 * Sigmode records the current value of the signal handlers for the various
319 * modes. A value of zero means that the current handler is not known.
320 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
322 char sigmode[NSIG - 1];
323 #define S_DFL 1 /* default signal handling (SIG_DFL) */
324 #define S_CATCH 2 /* signal is caught */
325 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
326 #define S_HARD_IGN 4 /* signal is ignored permenantly */
328 /* indicates specified signal received */
329 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
330 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
332 char **trap_ptr; /* used only by "trap hack" */
334 /* Rarely referenced stuff */
335 #if ENABLE_ASH_RANDOM_SUPPORT
338 pid_t backgndpid; /* pid of last background process */
339 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
341 extern struct globals_misc *const ash_ptr_to_globals_misc;
342 #define G_misc (*ash_ptr_to_globals_misc)
343 #define rootpid (G_misc.rootpid )
344 #define shlvl (G_misc.shlvl )
345 #define minusc (G_misc.minusc )
346 #define curdir (G_misc.curdir )
347 #define physdir (G_misc.physdir )
348 #define arg0 (G_misc.arg0 )
349 #define exception_handler (G_misc.exception_handler)
350 #define exception_type (G_misc.exception_type )
351 #define suppress_int (G_misc.suppress_int )
352 #define pending_int (G_misc.pending_int )
353 #define pending_sig (G_misc.pending_sig )
354 #define isloginsh (G_misc.isloginsh )
355 #define nullstr (G_misc.nullstr )
356 #define optlist (G_misc.optlist )
357 #define sigmode (G_misc.sigmode )
358 #define gotsig (G_misc.gotsig )
359 #define may_have_traps (G_misc.may_have_traps )
360 #define trap (G_misc.trap )
361 #define trap_ptr (G_misc.trap_ptr )
362 #define random_gen (G_misc.random_gen )
363 #define backgndpid (G_misc.backgndpid )
364 #define job_warning (G_misc.job_warning)
365 #define INIT_G_misc() do { \
366 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
374 /* ============ DEBUG */
376 static void trace_printf(const char *fmt, ...);
377 static void trace_vprintf(const char *fmt, va_list va);
378 # define TRACE(param) trace_printf param
379 # define TRACEV(param) trace_vprintf param
380 # define close(fd) do { \
382 if (close(dfd) < 0) \
383 bb_error_msg("bug on %d: closing %d(0x%x)", \
384 __LINE__, dfd, dfd); \
387 # define TRACE(param)
388 # define TRACEV(param)
392 /* ============ Utility functions */
393 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
395 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
396 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
398 static int isdigit_str9(const char *str)
400 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
401 while (--maxlen && isdigit(*str))
403 return (*str == '\0');
406 static const char *var_end(const char *var)
415 /* ============ Interrupts / exceptions */
417 static void exitshell(void) NORETURN;
420 * These macros allow the user to suspend the handling of interrupt signals
421 * over a period of time. This is similar to SIGHOLD or to sigblock, but
422 * much more efficient and portable. (But hacking the kernel is so much
423 * more fun than worrying about efficiency and portability. :-))
425 #define INT_OFF do { \
431 * Called to raise an exception. Since C doesn't include exceptions, we
432 * just do a longjmp to the exception handler. The type of exception is
433 * stored in the global variable "exception_type".
435 static void raise_exception(int) NORETURN;
437 raise_exception(int e)
440 if (exception_handler == NULL)
445 longjmp(exception_handler->loc, 1);
448 #define raise_exception(e) do { \
449 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
450 raise_exception(e); \
455 * Called from trap.c when a SIGINT is received. (If the user specifies
456 * that SIGINT is to be trapped or ignored using the trap builtin, then
457 * this routine is not called.) Suppressint is nonzero when interrupts
458 * are held using the INT_OFF macro. (The test for iflag is just
459 * defensive programming.)
461 static void raise_interrupt(void) NORETURN;
463 raise_interrupt(void)
468 /* Signal is not automatically unmasked after it is raised,
469 * do it ourself - unmask all signals */
470 sigprocmask_allsigs(SIG_UNBLOCK);
471 /* pending_sig = 0; - now done in signal_handler() */
474 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
475 if (!(rootshell && iflag)) {
476 /* Kill ourself with SIGINT */
477 signal(SIGINT, SIG_DFL);
482 raise_exception(ex_type);
486 #define raise_interrupt() do { \
487 TRACE(("raising interrupt on line %d\n", __LINE__)); \
492 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
496 if (--suppress_int == 0 && pending_int) {
500 #define INT_ON int_on()
501 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
509 #define FORCE_INT_ON force_int_on()
511 #define SAVE_INT(v) ((v) = suppress_int)
513 #define RESTORE_INT(v) do { \
515 suppress_int = (v); \
516 if (suppress_int == 0 && pending_int) \
521 /* ============ Stdout/stderr output */
524 outstr(const char *p, FILE *file)
532 flush_stdout_stderr(void)
539 /* Was called outcslow(c,FILE*), but c was always '\n' */
541 newline_and_flush(FILE *dest)
549 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
551 out1fmt(const char *fmt, ...)
558 r = vprintf(fmt, ap);
564 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
566 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
573 ret = vsnprintf(outbuf, length, fmt, ap);
580 out1str(const char *p)
586 out2str(const char *p)
589 flush_stdout_stderr();
593 /* ============ Parser structures */
595 /* control characters in argument strings */
596 #define CTL_FIRST CTLESC
597 #define CTLESC ((unsigned char)'\201') /* escape next character */
598 #define CTLVAR ((unsigned char)'\202') /* variable defn */
599 #define CTLENDVAR ((unsigned char)'\203')
600 #define CTLBACKQ ((unsigned char)'\204')
601 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
602 #define CTLENDARI ((unsigned char)'\207')
603 #define CTLQUOTEMARK ((unsigned char)'\210')
604 #define CTL_LAST CTLQUOTEMARK
606 /* variable substitution byte (follows CTLVAR) */
607 #define VSTYPE 0x0f /* type of variable substitution */
608 #define VSNUL 0x10 /* colon--treat the empty string as unset */
610 /* values of VSTYPE field */
611 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
612 #define VSMINUS 0x2 /* ${var-text} */
613 #define VSPLUS 0x3 /* ${var+text} */
614 #define VSQUESTION 0x4 /* ${var?message} */
615 #define VSASSIGN 0x5 /* ${var=text} */
616 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
617 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
618 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
619 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
620 #define VSLENGTH 0xa /* ${#var} */
621 #if ENABLE_ASH_BASH_COMPAT
622 #define VSSUBSTR 0xc /* ${var:position:length} */
623 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
624 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
627 static const char dolatstr[] ALIGN1 = {
628 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
630 #define DOLATSTRLEN 6
649 #if ENABLE_ASH_BASH_COMPAT
666 smallint type; /* Nxxxx */
669 union node *redirect;
674 smallint pipe_backgnd;
675 struct nodelist *cmdlist;
681 union node *redirect;
694 union node *elsepart;
721 struct nodelist *backquote;
724 /* nfile and ndup layout must match!
725 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
726 * that it is actually NTO2 (>&file), and change its type.
743 char *_unused_expfname;
762 struct nredir nredir;
763 struct nbinary nbinary;
767 struct nclist nclist;
776 * NODE_EOF is returned by parsecmd when it encounters an end of file.
777 * It must be distinct from NULL.
779 #define NODE_EOF ((union node *) -1L)
782 struct nodelist *next;
795 freefunc(struct funcnode *f)
797 if (f && --f->count < 0)
802 /* ============ Debugging output */
806 static FILE *tracefile;
809 trace_printf(const char *fmt, ...)
816 fprintf(tracefile, "%u ", (int) time(NULL));
818 fprintf(tracefile, "[%u] ", (int) getpid());
820 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
822 vfprintf(tracefile, fmt, va);
827 trace_vprintf(const char *fmt, va_list va)
832 fprintf(tracefile, "%u ", (int) time(NULL));
834 fprintf(tracefile, "[%u] ", (int) getpid());
836 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
837 vfprintf(tracefile, fmt, va);
841 trace_puts(const char *s)
849 trace_puts_quoted(char *s)
856 putc('"', tracefile);
857 for (p = s; *p; p++) {
858 switch ((unsigned char)*p) {
859 case '\n': c = 'n'; goto backslash;
860 case '\t': c = 't'; goto backslash;
861 case '\r': c = 'r'; goto backslash;
862 case '\"': c = '\"'; goto backslash;
863 case '\\': c = '\\'; goto backslash;
864 case CTLESC: c = 'e'; goto backslash;
865 case CTLVAR: c = 'v'; goto backslash;
866 case CTLBACKQ: c = 'q'; goto backslash;
868 putc('\\', tracefile);
872 if (*p >= ' ' && *p <= '~')
875 putc('\\', tracefile);
876 putc((*p >> 6) & 03, tracefile);
877 putc((*p >> 3) & 07, tracefile);
878 putc(*p & 07, tracefile);
883 putc('"', tracefile);
887 trace_puts_args(char **ap)
894 trace_puts_quoted(*ap);
896 putc('\n', tracefile);
899 putc(' ', tracefile);
914 /* leave open because libedit might be using it */
917 strcpy(s, "./trace");
919 if (!freopen(s, "a", tracefile)) {
920 fprintf(stderr, "Can't re-open %s\n", s);
925 tracefile = fopen(s, "a");
926 if (tracefile == NULL) {
927 fprintf(stderr, "Can't open %s\n", s);
933 flags = fcntl(fileno(tracefile), F_GETFL);
935 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
937 setlinebuf(tracefile);
938 fputs("\nTracing started.\n", tracefile);
942 indent(int amount, char *pfx, FILE *fp)
946 for (i = 0; i < amount; i++) {
947 if (pfx && i == amount - 1)
953 /* little circular references here... */
954 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
957 sharg(union node *arg, FILE *fp)
960 struct nodelist *bqlist;
961 unsigned char subtype;
963 if (arg->type != NARG) {
964 out1fmt("<node type %d>\n", arg->type);
967 bqlist = arg->narg.backquote;
968 for (p = arg->narg.text; *p; p++) {
969 switch ((unsigned char)*p) {
978 if (subtype == VSLENGTH)
989 switch (subtype & VSTYPE) {
1015 case VSTRIMRIGHTMAX:
1022 out1fmt("<subtype %d>", subtype);
1031 shtree(bqlist->n, -1, NULL, fp);
1042 shcmd(union node *cmd, FILE *fp)
1050 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1056 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1060 switch (np->nfile.type) {
1061 case NTO: s = ">>"+1; dftfd = 1; break;
1062 case NCLOBBER: s = ">|"; dftfd = 1; break;
1063 case NAPPEND: s = ">>"; dftfd = 1; break;
1064 #if ENABLE_ASH_BASH_COMPAT
1067 case NTOFD: s = ">&"; dftfd = 1; break;
1068 case NFROM: s = "<"; break;
1069 case NFROMFD: s = "<&"; break;
1070 case NFROMTO: s = "<>"; break;
1071 default: s = "*error*"; break;
1073 if (np->nfile.fd != dftfd)
1074 fprintf(fp, "%d", np->nfile.fd);
1076 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1077 fprintf(fp, "%d", np->ndup.dupfd);
1079 sharg(np->nfile.fname, fp);
1086 shtree(union node *n, int ind, char *pfx, FILE *fp)
1088 struct nodelist *lp;
1094 indent(ind, pfx, fp);
1096 if (n == NODE_EOF) {
1111 shtree(n->nbinary.ch1, ind, NULL, fp);
1114 shtree(n->nbinary.ch2, ind, NULL, fp);
1122 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1123 shtree(lp->n, 0, NULL, fp);
1127 if (n->npipe.pipe_backgnd)
1133 fprintf(fp, "<node type %d>", n->type);
1141 showtree(union node *n)
1143 trace_puts("showtree called\n");
1144 shtree(n, 1, NULL, stderr);
1150 /* ============ Parser data */
1153 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1156 struct strlist *next;
1163 struct strpush *prev; /* preceding string on stack */
1165 int prev_left_in_line;
1166 #if ENABLE_ASH_ALIAS
1167 struct alias *ap; /* if push was associated with an alias */
1169 char *string; /* remember the string since it may change */
1173 struct parsefile *prev; /* preceding file on stack */
1174 int linno; /* current line */
1175 int pf_fd; /* file descriptor (or -1 if string) */
1176 int left_in_line; /* number of chars left in this line */
1177 int left_in_buffer; /* number of chars left in this buffer past the line */
1178 char *next_to_pgetc; /* next char in buffer */
1179 char *buf; /* input buffer */
1180 struct strpush *strpush; /* for pushing strings at this level */
1181 struct strpush basestrpush; /* so pushing one is fast */
1184 static struct parsefile basepf; /* top level input file */
1185 static struct parsefile *g_parsefile = &basepf; /* current input file */
1186 static int startlinno; /* line # where last token started */
1187 static char *commandname; /* currently executing command */
1188 static struct strlist *cmdenviron; /* environment for builtin command */
1189 static uint8_t exitstatus; /* exit status of last command */
1192 /* ============ Message printing */
1195 ash_vmsg(const char *msg, va_list ap)
1197 fprintf(stderr, "%s: ", arg0);
1199 if (strcmp(arg0, commandname))
1200 fprintf(stderr, "%s: ", commandname);
1201 if (!iflag || g_parsefile->pf_fd > 0)
1202 fprintf(stderr, "line %d: ", startlinno);
1204 vfprintf(stderr, msg, ap);
1205 newline_and_flush(stderr);
1209 * Exverror is called to raise the error exception. If the second argument
1210 * is not NULL then error prints an error message using printf style
1211 * formatting. It then raises the error exception.
1213 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1215 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1219 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1221 TRACE(("\") pid=%d\n", getpid()));
1223 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1228 flush_stdout_stderr();
1229 raise_exception(cond);
1233 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1235 ash_msg_and_raise_error(const char *msg, ...)
1240 ash_vmsg_and_raise(EXERROR, msg, ap);
1245 static void raise_error_syntax(const char *) NORETURN;
1247 raise_error_syntax(const char *msg)
1249 ash_msg_and_raise_error("syntax error: %s", msg);
1253 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1255 ash_msg_and_raise(int cond, const char *msg, ...)
1260 ash_vmsg_and_raise(cond, msg, ap);
1266 * error/warning routines for external builtins
1269 ash_msg(const char *fmt, ...)
1279 * Return a string describing an error. The returned string may be a
1280 * pointer to a static buffer that will be overwritten on the next call.
1281 * Action describes the operation that got the error.
1284 errmsg(int e, const char *em)
1286 if (e == ENOENT || e == ENOTDIR) {
1293 /* ============ Memory allocation */
1296 /* I consider these wrappers nearly useless:
1297 * ok, they return you to nearest exception handler, but
1298 * how much memory do you leak in the process, making
1299 * memory starvation worse?
1302 ckrealloc(void * p, size_t nbytes)
1304 p = realloc(p, nbytes);
1306 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1311 ckmalloc(size_t nbytes)
1313 return ckrealloc(NULL, nbytes);
1317 ckzalloc(size_t nbytes)
1319 return memset(ckmalloc(nbytes), 0, nbytes);
1323 ckstrdup(const char *s)
1325 char *p = strdup(s);
1327 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1331 /* Using bbox equivalents. They exit if out of memory */
1332 # define ckrealloc xrealloc
1333 # define ckmalloc xmalloc
1334 # define ckzalloc xzalloc
1335 # define ckstrdup xstrdup
1339 * It appears that grabstackstr() will barf with such alignments
1340 * because stalloc() will return a string allocated in a new stackblock.
1342 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1344 /* Most machines require the value returned from malloc to be aligned
1345 * in some way. The following macro will get this right
1346 * on many machines. */
1347 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1348 /* Minimum size of a block */
1349 MINSIZE = SHELL_ALIGN(504),
1352 struct stack_block {
1353 struct stack_block *prev;
1354 char space[MINSIZE];
1358 struct stack_block *stackp;
1361 struct stackmark *marknext;
1365 struct globals_memstack {
1366 struct stack_block *g_stackp; // = &stackbase;
1367 struct stackmark *markp;
1368 char *g_stacknxt; // = stackbase.space;
1369 char *sstrend; // = stackbase.space + MINSIZE;
1370 size_t g_stacknleft; // = MINSIZE;
1371 int herefd; // = -1;
1372 struct stack_block stackbase;
1374 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1375 #define G_memstack (*ash_ptr_to_globals_memstack)
1376 #define g_stackp (G_memstack.g_stackp )
1377 #define markp (G_memstack.markp )
1378 #define g_stacknxt (G_memstack.g_stacknxt )
1379 #define sstrend (G_memstack.sstrend )
1380 #define g_stacknleft (G_memstack.g_stacknleft)
1381 #define herefd (G_memstack.herefd )
1382 #define stackbase (G_memstack.stackbase )
1383 #define INIT_G_memstack() do { \
1384 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1386 g_stackp = &stackbase; \
1387 g_stacknxt = stackbase.space; \
1388 g_stacknleft = MINSIZE; \
1389 sstrend = stackbase.space + MINSIZE; \
1394 #define stackblock() ((void *)g_stacknxt)
1395 #define stackblocksize() g_stacknleft
1398 * Parse trees for commands are allocated in lifo order, so we use a stack
1399 * to make this more efficient, and also to avoid all sorts of exception
1400 * handling code to handle interrupts in the middle of a parse.
1402 * The size 504 was chosen because the Ultrix malloc handles that size
1406 stalloc(size_t nbytes)
1411 aligned = SHELL_ALIGN(nbytes);
1412 if (aligned > g_stacknleft) {
1415 struct stack_block *sp;
1417 blocksize = aligned;
1418 if (blocksize < MINSIZE)
1419 blocksize = MINSIZE;
1420 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1421 if (len < blocksize)
1422 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1425 sp->prev = g_stackp;
1426 g_stacknxt = sp->space;
1427 g_stacknleft = blocksize;
1428 sstrend = g_stacknxt + blocksize;
1433 g_stacknxt += aligned;
1434 g_stacknleft -= aligned;
1439 stzalloc(size_t nbytes)
1441 return memset(stalloc(nbytes), 0, nbytes);
1448 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1449 write(STDERR_FILENO, "stunalloc\n", 10);
1453 g_stacknleft += g_stacknxt - (char *)p;
1458 * Like strdup but works with the ash stack.
1461 ststrdup(const char *p)
1463 size_t len = strlen(p) + 1;
1464 return memcpy(stalloc(len), p, len);
1468 setstackmark(struct stackmark *mark)
1470 mark->stackp = g_stackp;
1471 mark->stacknxt = g_stacknxt;
1472 mark->stacknleft = g_stacknleft;
1473 mark->marknext = markp;
1478 popstackmark(struct stackmark *mark)
1480 struct stack_block *sp;
1486 markp = mark->marknext;
1487 while (g_stackp != mark->stackp) {
1489 g_stackp = sp->prev;
1492 g_stacknxt = mark->stacknxt;
1493 g_stacknleft = mark->stacknleft;
1494 sstrend = mark->stacknxt + mark->stacknleft;
1499 * When the parser reads in a string, it wants to stick the string on the
1500 * stack and only adjust the stack pointer when it knows how big the
1501 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1502 * of space on top of the stack and stackblocklen returns the length of
1503 * this block. Growstackblock will grow this space by at least one byte,
1504 * possibly moving it (like realloc). Grabstackblock actually allocates the
1505 * part of the block that has been used.
1508 growstackblock(void)
1512 newlen = g_stacknleft * 2;
1513 if (newlen < g_stacknleft)
1514 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1518 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1519 struct stack_block *oldstackp;
1520 struct stackmark *xmark;
1521 struct stack_block *sp;
1522 struct stack_block *prevstackp;
1526 oldstackp = g_stackp;
1528 prevstackp = sp->prev;
1529 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1530 sp = ckrealloc(sp, grosslen);
1531 sp->prev = prevstackp;
1533 g_stacknxt = sp->space;
1534 g_stacknleft = newlen;
1535 sstrend = sp->space + newlen;
1538 * Stack marks pointing to the start of the old block
1539 * must be relocated to point to the new block
1542 while (xmark != NULL && xmark->stackp == oldstackp) {
1543 xmark->stackp = g_stackp;
1544 xmark->stacknxt = g_stacknxt;
1545 xmark->stacknleft = g_stacknleft;
1546 xmark = xmark->marknext;
1550 char *oldspace = g_stacknxt;
1551 size_t oldlen = g_stacknleft;
1552 char *p = stalloc(newlen);
1554 /* free the space we just allocated */
1555 g_stacknxt = memcpy(p, oldspace, oldlen);
1556 g_stacknleft += newlen;
1561 grabstackblock(size_t len)
1563 len = SHELL_ALIGN(len);
1565 g_stacknleft -= len;
1569 * The following routines are somewhat easier to use than the above.
1570 * The user declares a variable of type STACKSTR, which may be declared
1571 * to be a register. The macro STARTSTACKSTR initializes things. Then
1572 * the user uses the macro STPUTC to add characters to the string. In
1573 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1574 * grown as necessary. When the user is done, she can just leave the
1575 * string there and refer to it using stackblock(). Or she can allocate
1576 * the space for it using grabstackstr(). If it is necessary to allow
1577 * someone else to use the stack temporarily and then continue to grow
1578 * the string, the user should use grabstack to allocate the space, and
1579 * then call ungrabstr(p) to return to the previous mode of operation.
1581 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1582 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1583 * is space for at least one character.
1588 size_t len = stackblocksize();
1589 if (herefd >= 0 && len >= 1024) {
1590 full_write(herefd, stackblock(), len);
1591 return stackblock();
1594 return (char *)stackblock() + len;
1598 * Called from CHECKSTRSPACE.
1601 makestrspace(size_t newlen, char *p)
1603 size_t len = p - g_stacknxt;
1604 size_t size = stackblocksize();
1609 size = stackblocksize();
1611 if (nleft >= newlen)
1615 return (char *)stackblock() + len;
1619 stack_nputstr(const char *s, size_t n, char *p)
1621 p = makestrspace(n, p);
1622 p = (char *)memcpy(p, s, n) + n;
1627 stack_putstr(const char *s, char *p)
1629 return stack_nputstr(s, strlen(s), p);
1633 _STPUTC(int c, char *p)
1641 #define STARTSTACKSTR(p) ((p) = stackblock())
1642 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1643 #define CHECKSTRSPACE(n, p) do { \
1646 size_t m = sstrend - q; \
1648 (p) = makestrspace(l, q); \
1650 #define USTPUTC(c, p) (*(p)++ = (c))
1651 #define STACKSTRNUL(p) do { \
1652 if ((p) == sstrend) \
1653 (p) = growstackstr(); \
1656 #define STUNPUTC(p) (--(p))
1657 #define STTOPC(p) ((p)[-1])
1658 #define STADJUST(amount, p) ((p) += (amount))
1660 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1661 #define ungrabstackstr(s, p) stunalloc(s)
1662 #define stackstrend() ((void *)sstrend)
1665 /* ============ String helpers */
1668 * prefix -- see if pfx is a prefix of string.
1671 prefix(const char *string, const char *pfx)
1674 if (*pfx++ != *string++)
1677 return (char *) string;
1681 * Check for a valid number. This should be elsewhere.
1684 is_number(const char *p)
1689 } while (*++p != '\0');
1694 * Convert a string of digits to an integer, printing an error message on
1698 number(const char *s)
1701 ash_msg_and_raise_error(msg_illnum, s);
1706 * Produce a possibly single quoted string suitable as input to the shell.
1707 * The return string is allocated on the stack.
1710 single_quote(const char *s)
1720 len = strchrnul(s, '\'') - s;
1722 q = p = makestrspace(len + 3, p);
1725 q = (char *)memcpy(q, s, len) + len;
1734 do len++; while (*++s == '\'');
1736 q = p = makestrspace(len + 3, p);
1739 q = (char *)memcpy(q, s - len, len) + len;
1747 return stackblock();
1751 /* ============ nextopt */
1753 static char **argptr; /* argument list for builtin commands */
1754 static char *optionarg; /* set by nextopt (like getopt) */
1755 static char *optptr; /* used by nextopt */
1758 * XXX - should get rid of. Have all builtins use getopt(3).
1759 * The library getopt must have the BSD extension static variable
1760 * "optreset", otherwise it can't be used within the shell safely.
1762 * Standard option processing (a la getopt) for builtin routines.
1763 * The only argument that is passed to nextopt is the option string;
1764 * the other arguments are unnecessary. It returns the character,
1765 * or '\0' on end of input.
1768 nextopt(const char *optstring)
1775 if (p == NULL || *p == '\0') {
1776 /* We ate entire "-param", take next one */
1782 if (*++p == '\0') /* just "-" ? */
1785 if (LONE_DASH(p)) /* "--" ? */
1787 /* p => next "-param" */
1789 /* p => some option char in the middle of a "-param" */
1791 for (q = optstring; *q != c;) {
1793 ash_msg_and_raise_error("illegal option -%c", c);
1801 ash_msg_and_raise_error("no arg for -%c option", c);
1811 /* ============ Shell variables */
1814 * The parsefile structure pointed to by the global variable parsefile
1815 * contains information about the current file being read.
1818 int nparam; /* # of positional parameters (without $0) */
1819 #if ENABLE_ASH_GETOPTS
1820 int optind; /* next parameter to be processed by getopts */
1821 int optoff; /* used by getopts */
1823 unsigned char malloced; /* if parameter list dynamically allocated */
1824 char **p; /* parameter list */
1828 * Free the list of positional parameters.
1831 freeparam(volatile struct shparam *param)
1833 if (param->malloced) {
1835 ap = ap1 = param->p;
1842 #if ENABLE_ASH_GETOPTS
1843 static void FAST_FUNC getoptsreset(const char *value);
1847 struct var *next; /* next entry in hash list */
1848 int flags; /* flags are defined above */
1849 const char *var_text; /* name=value */
1850 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1851 /* the variable gets set/unset */
1855 struct localvar *next; /* next local variable in list */
1856 struct var *vp; /* the variable that was made local */
1857 int flags; /* saved flags */
1858 const char *text; /* saved text */
1862 #define VEXPORT 0x01 /* variable is exported */
1863 #define VREADONLY 0x02 /* variable cannot be modified */
1864 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1865 #define VTEXTFIXED 0x08 /* text is statically allocated */
1866 #define VSTACK 0x10 /* text is allocated on the stack */
1867 #define VUNSET 0x20 /* the variable is not set */
1868 #define VNOFUNC 0x40 /* don't call the callback function */
1869 #define VNOSET 0x80 /* do not set variable - just readonly test */
1870 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1871 #if ENABLE_ASH_RANDOM_SUPPORT
1872 # define VDYNAMIC 0x200 /* dynamic variable */
1878 /* Need to be before varinit_data[] */
1879 #if ENABLE_LOCALE_SUPPORT
1880 static void FAST_FUNC
1881 change_lc_all(const char *value)
1883 if (value && *value != '\0')
1884 setlocale(LC_ALL, value);
1886 static void FAST_FUNC
1887 change_lc_ctype(const char *value)
1889 if (value && *value != '\0')
1890 setlocale(LC_CTYPE, value);
1894 static void chkmail(void);
1895 static void changemail(const char *var_value) FAST_FUNC;
1897 # define chkmail() ((void)0)
1899 static void changepath(const char *) FAST_FUNC;
1900 #if ENABLE_ASH_RANDOM_SUPPORT
1901 static void change_random(const char *) FAST_FUNC;
1904 static const struct {
1906 const char *var_text;
1907 void (*var_func)(const char *) FAST_FUNC;
1908 } varinit_data[] = {
1910 * Note: VEXPORT would not work correctly here for NOFORK applets:
1911 * some environment strings may be constant.
1913 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1915 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1916 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1918 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1919 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1920 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1921 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1922 #if ENABLE_ASH_GETOPTS
1923 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1925 #if ENABLE_ASH_RANDOM_SUPPORT
1926 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1928 #if ENABLE_LOCALE_SUPPORT
1929 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1930 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1932 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1933 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1939 struct globals_var {
1940 struct shparam shellparam; /* $@ current positional parameters */
1941 struct redirtab *redirlist;
1943 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1944 struct var *vartab[VTABSIZE];
1945 struct var varinit[ARRAY_SIZE(varinit_data)];
1947 extern struct globals_var *const ash_ptr_to_globals_var;
1948 #define G_var (*ash_ptr_to_globals_var)
1949 #define shellparam (G_var.shellparam )
1950 //#define redirlist (G_var.redirlist )
1951 #define g_nullredirs (G_var.g_nullredirs )
1952 #define preverrout_fd (G_var.preverrout_fd)
1953 #define vartab (G_var.vartab )
1954 #define varinit (G_var.varinit )
1955 #define INIT_G_var() do { \
1957 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1959 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1960 varinit[i].flags = varinit_data[i].flags; \
1961 varinit[i].var_text = varinit_data[i].var_text; \
1962 varinit[i].var_func = varinit_data[i].var_func; \
1966 #define vifs varinit[0]
1968 # define vmail (&vifs)[1]
1969 # define vmpath (&vmail)[1]
1970 # define vpath (&vmpath)[1]
1972 # define vpath (&vifs)[1]
1974 #define vps1 (&vpath)[1]
1975 #define vps2 (&vps1)[1]
1976 #define vps4 (&vps2)[1]
1977 #if ENABLE_ASH_GETOPTS
1978 # define voptind (&vps4)[1]
1979 # if ENABLE_ASH_RANDOM_SUPPORT
1980 # define vrandom (&voptind)[1]
1983 # if ENABLE_ASH_RANDOM_SUPPORT
1984 # define vrandom (&vps4)[1]
1989 * The following macros access the values of the above variables.
1990 * They have to skip over the name. They return the null string
1991 * for unset variables.
1993 #define ifsval() (vifs.var_text + 4)
1994 #define ifsset() ((vifs.flags & VUNSET) == 0)
1996 # define mailval() (vmail.var_text + 5)
1997 # define mpathval() (vmpath.var_text + 9)
1998 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2000 #define pathval() (vpath.var_text + 5)
2001 #define ps1val() (vps1.var_text + 4)
2002 #define ps2val() (vps2.var_text + 4)
2003 #define ps4val() (vps4.var_text + 4)
2004 #if ENABLE_ASH_GETOPTS
2005 # define optindval() (voptind.var_text + 7)
2008 #if ENABLE_ASH_GETOPTS
2009 static void FAST_FUNC
2010 getoptsreset(const char *value)
2012 shellparam.optind = number(value);
2013 shellparam.optoff = -1;
2018 * Compares two strings up to the first = or '\0'. The first
2019 * string must be terminated by '='; the second may be terminated by
2020 * either '=' or '\0'.
2023 varcmp(const char *p, const char *q)
2027 while ((c = *p) == (d = *q)) {
2028 if (c == '\0' || c == '=')
2042 * Find the appropriate entry in the hash table from the name.
2044 static struct var **
2045 hashvar(const char *p)
2049 hashval = ((unsigned char) *p) << 4;
2050 while (*p && *p != '=')
2051 hashval += (unsigned char) *p++;
2052 return &vartab[hashval % VTABSIZE];
2056 vpcmp(const void *a, const void *b)
2058 return varcmp(*(const char **)a, *(const char **)b);
2062 * This routine initializes the builtin variables.
2072 * PS1 depends on uid
2074 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2075 vps1.var_text = "PS1=\\w \\$ ";
2078 vps1.var_text = "PS1=# ";
2081 end = vp + ARRAY_SIZE(varinit);
2083 vpp = hashvar(vp->var_text);
2086 } while (++vp < end);
2089 static struct var **
2090 findvar(struct var **vpp, const char *name)
2092 for (; *vpp; vpp = &(*vpp)->next) {
2093 if (varcmp((*vpp)->var_text, name) == 0) {
2101 * Find the value of a variable. Returns NULL if not set.
2103 static const char* FAST_FUNC
2104 lookupvar(const char *name)
2108 v = *findvar(hashvar(name), name);
2110 #if ENABLE_ASH_RANDOM_SUPPORT
2112 * Dynamic variables are implemented roughly the same way they are
2113 * in bash. Namely, they're "special" so long as they aren't unset.
2114 * As soon as they're unset, they're no longer dynamic, and dynamic
2115 * lookup will no longer happen at that point. -- PFM.
2117 if (v->flags & VDYNAMIC)
2120 if (!(v->flags & VUNSET))
2121 return var_end(v->var_text);
2126 static void reinit_unicode_for_ash(void)
2128 /* Unicode support should be activated even if LANG is set
2129 * _during_ shell execution, not only if it was set when
2130 * shell was started. Therefore, re-check LANG every time:
2132 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2133 || ENABLE_UNICODE_USING_LOCALE
2135 const char *s = lookupvar("LC_ALL");
2136 if (!s) s = lookupvar("LC_CTYPE");
2137 if (!s) s = lookupvar("LANG");
2143 * Search the environment of a builtin command.
2146 bltinlookup(const char *name)
2150 for (sp = cmdenviron; sp; sp = sp->next) {
2151 if (varcmp(sp->text, name) == 0)
2152 return var_end(sp->text);
2154 return lookupvar(name);
2158 * Same as setvar except that the variable and value are passed in
2159 * the first argument as name=value. Since the first argument will
2160 * be actually stored in the table, it should not be a string that
2162 * Called with interrupts off.
2165 setvareq(char *s, int flags)
2167 struct var *vp, **vpp;
2170 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2171 vp = *findvar(vpp, s);
2173 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2176 if (flags & VNOSAVE)
2179 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2185 if (vp->var_func && !(flags & VNOFUNC))
2186 vp->var_func(var_end(s));
2188 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2189 free((char*)vp->var_text);
2191 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2193 /* variable s is not found */
2196 vp = ckzalloc(sizeof(*vp));
2198 /*vp->func = NULL; - ckzalloc did it */
2201 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2208 * Set the value of a variable. The flags argument is ored with the
2209 * flags of the variable. If val is NULL, the variable is unset.
2212 setvar(const char *name, const char *val, int flags)
2220 q = endofname(name);
2221 p = strchrnul(q, '=');
2223 if (!namelen || p != q)
2224 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2229 vallen = strlen(val);
2233 nameeq = ckmalloc(namelen + vallen + 2);
2234 p = memcpy(nameeq, name, namelen) + namelen;
2237 p = memcpy(p, val, vallen) + vallen;
2240 setvareq(nameeq, flags | VNOSAVE);
2244 static void FAST_FUNC
2245 setvar0(const char *name, const char *val)
2247 setvar(name, val, 0);
2250 #if ENABLE_ASH_GETOPTS
2252 * Safe version of setvar, returns 1 on success 0 on failure.
2255 setvarsafe(const char *name, const char *val, int flags)
2258 volatile int saveint;
2259 struct jmploc *volatile savehandler = exception_handler;
2260 struct jmploc jmploc;
2263 if (setjmp(jmploc.loc))
2266 exception_handler = &jmploc;
2267 setvar(name, val, flags);
2270 exception_handler = savehandler;
2271 RESTORE_INT(saveint);
2277 * Unset the specified variable.
2280 unsetvar(const char *s)
2286 vpp = findvar(hashvar(s), s);
2290 int flags = vp->flags;
2293 if (flags & VREADONLY)
2295 #if ENABLE_ASH_RANDOM_SUPPORT
2296 vp->flags &= ~VDYNAMIC;
2300 if ((flags & VSTRFIXED) == 0) {
2302 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2303 free((char*)vp->var_text);
2309 vp->flags &= ~VEXPORT;
2319 * Process a linked list of variable assignments.
2322 listsetvar(struct strlist *list_set_var, int flags)
2324 struct strlist *lp = list_set_var;
2330 setvareq(lp->text, flags);
2337 * Generate a list of variables satisfying the given conditions.
2340 listvars(int on, int off, char ***end)
2351 for (vp = *vpp; vp; vp = vp->next) {
2352 if ((vp->flags & mask) == on) {
2353 if (ep == stackstrend())
2354 ep = growstackstr();
2355 *ep++ = (char*)vp->var_text;
2358 } while (++vpp < vartab + VTABSIZE);
2359 if (ep == stackstrend())
2360 ep = growstackstr();
2364 return grabstackstr(ep);
2368 /* ============ Path search helper
2370 * The variable path (passed by reference) should be set to the start
2371 * of the path before the first call; path_advance will update
2372 * this value as it proceeds. Successive calls to path_advance will return
2373 * the possible path expansions in sequence. If an option (indicated by
2374 * a percent sign) appears in the path entry then the global variable
2375 * pathopt will be set to point to it; otherwise pathopt will be set to
2378 static const char *pathopt; /* set by path_advance */
2381 path_advance(const char **path, const char *name)
2391 for (p = start; *p && *p != ':' && *p != '%'; p++)
2393 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2394 while (stackblocksize() < len)
2398 memcpy(q, start, p - start);
2406 while (*p && *p != ':')
2413 return stalloc(len);
2417 /* ============ Prompt */
2419 static smallint doprompt; /* if set, prompt the user */
2420 static smallint needprompt; /* true if interactive and at start of line */
2422 #if ENABLE_FEATURE_EDITING
2423 static line_input_t *line_input_state;
2424 static const char *cmdedit_prompt;
2426 putprompt(const char *s)
2428 if (ENABLE_ASH_EXPAND_PRMT) {
2429 free((char*)cmdedit_prompt);
2430 cmdedit_prompt = ckstrdup(s);
2437 putprompt(const char *s)
2443 #if ENABLE_ASH_EXPAND_PRMT
2444 /* expandstr() needs parsing machinery, so it is far away ahead... */
2445 static const char *expandstr(const char *ps);
2447 #define expandstr(s) s
2451 setprompt_if(smallint do_set, int whichprompt)
2454 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2461 switch (whichprompt) {
2471 #if ENABLE_ASH_EXPAND_PRMT
2472 setstackmark(&smark);
2473 stalloc(stackblocksize());
2475 putprompt(expandstr(prompt));
2476 #if ENABLE_ASH_EXPAND_PRMT
2477 popstackmark(&smark);
2482 /* ============ The cd and pwd commands */
2484 #define CD_PHYSICAL 1
2494 while ((i = nextopt("LP")) != '\0') {
2496 flags ^= CD_PHYSICAL;
2505 * Update curdir (the name of the current directory) in response to a
2509 updatepwd(const char *dir)
2516 cdcomppath = ststrdup(dir);
2519 if (curdir == nullstr)
2521 new = stack_putstr(curdir, new);
2523 new = makestrspace(strlen(dir) + 2, new);
2524 lim = (char *)stackblock() + 1;
2528 if (new > lim && *lim == '/')
2533 if (dir[1] == '/' && dir[2] != '/') {
2539 p = strtok(cdcomppath, "/");
2543 if (p[1] == '.' && p[2] == '\0') {
2555 new = stack_putstr(p, new);
2558 p = strtok(NULL, "/");
2563 return stackblock();
2567 * Find out what the current directory is. If we already know the current
2568 * directory, this routine returns immediately.
2573 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2574 return dir ? dir : nullstr;
2578 setpwd(const char *val, int setold)
2582 oldcur = dir = curdir;
2585 setvar("OLDPWD", oldcur, VEXPORT);
2588 if (physdir != nullstr) {
2589 if (physdir != oldcur)
2593 if (oldcur == val || !val) {
2599 dir = ckstrdup(val);
2600 if (oldcur != dir && oldcur != nullstr) {
2605 setvar("PWD", dir, VEXPORT);
2608 static void hashcd(void);
2611 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2612 * know that the current directory has changed.
2615 docd(const char *dest, int flags)
2617 const char *dir = NULL;
2620 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2623 if (!(flags & CD_PHYSICAL)) {
2624 dir = updatepwd(dest);
2638 static int FAST_FUNC
2639 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2651 dest = bltinlookup("HOME");
2652 else if (LONE_DASH(dest)) {
2653 dest = bltinlookup("OLDPWD");
2675 path = bltinlookup("CDPATH");
2684 p = path_advance(&path, dest);
2685 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2689 if (!docd(p, flags))
2694 ash_msg_and_raise_error("can't cd to %s", dest);
2697 if (flags & CD_PRINT)
2698 out1fmt("%s\n", curdir);
2702 static int FAST_FUNC
2703 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2706 const char *dir = curdir;
2710 if (physdir == nullstr)
2714 out1fmt("%s\n", dir);
2719 /* ============ ... */
2722 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2724 /* Syntax classes */
2725 #define CWORD 0 /* character is nothing special */
2726 #define CNL 1 /* newline character */
2727 #define CBACK 2 /* a backslash character */
2728 #define CSQUOTE 3 /* single quote */
2729 #define CDQUOTE 4 /* double quote */
2730 #define CENDQUOTE 5 /* a terminating quote */
2731 #define CBQUOTE 6 /* backwards single quote */
2732 #define CVAR 7 /* a dollar sign */
2733 #define CENDVAR 8 /* a '}' character */
2734 #define CLP 9 /* a left paren in arithmetic */
2735 #define CRP 10 /* a right paren in arithmetic */
2736 #define CENDFILE 11 /* end of file */
2737 #define CCTL 12 /* like CWORD, except it must be escaped */
2738 #define CSPCL 13 /* these terminate a word */
2739 #define CIGN 14 /* character should be ignored */
2742 #if ENABLE_ASH_ALIAS
2746 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2748 #if ENABLE_SH_MATH_SUPPORT
2749 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2751 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2753 static const uint16_t S_I_T[] ALIGN2 = {
2754 #if ENABLE_ASH_ALIAS
2755 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2757 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2758 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2759 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2760 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2761 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2762 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2763 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2764 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2765 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2766 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2767 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2768 #if !USE_SIT_FUNCTION
2769 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2770 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2771 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2775 /* Constants below must match table above */
2777 #if ENABLE_ASH_ALIAS
2778 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2780 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2781 CNL_CNL_CNL_CNL , /* 2 */
2782 CWORD_CCTL_CCTL_CWORD , /* 3 */
2783 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2784 CVAR_CVAR_CWORD_CVAR , /* 5 */
2785 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2786 CSPCL_CWORD_CWORD_CLP , /* 7 */
2787 CSPCL_CWORD_CWORD_CRP , /* 8 */
2788 CBACK_CBACK_CCTL_CBACK , /* 9 */
2789 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2790 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2791 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2792 CWORD_CWORD_CWORD_CWORD , /* 13 */
2793 CCTL_CCTL_CCTL_CCTL , /* 14 */
2796 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2797 * caller must ensure proper cast on it if c is *char_ptr!
2799 /* Values for syntax param */
2800 #define BASESYNTAX 0 /* not in quotes */
2801 #define DQSYNTAX 1 /* in double quotes */
2802 #define SQSYNTAX 2 /* in single quotes */
2803 #define ARISYNTAX 3 /* in arithmetic */
2804 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2806 #if USE_SIT_FUNCTION
2809 SIT(int c, int syntax)
2811 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2812 # if ENABLE_ASH_ALIAS
2813 static const uint8_t syntax_index_table[] ALIGN1 = {
2814 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2815 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2816 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2820 static const uint8_t syntax_index_table[] ALIGN1 = {
2821 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2822 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2823 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2832 # if ENABLE_ASH_ALIAS
2838 /* Cast is purely for paranoia here,
2839 * just in case someone passed signed char to us */
2840 if ((unsigned char)c >= CTL_FIRST
2841 && (unsigned char)c <= CTL_LAST
2845 s = strchrnul(spec_symbls, c);
2848 indx = syntax_index_table[s - spec_symbls];
2850 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2853 #else /* !USE_SIT_FUNCTION */
2855 static const uint8_t syntax_index_table[] ALIGN1 = {
2856 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2857 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2867 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2868 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2890 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2891 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2892 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2893 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2894 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2895 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2896 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2897 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2898 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2899 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2900 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2901 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2902 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2903 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2904 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2905 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2906 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2907 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2908 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2909 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2910 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2911 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2912 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2913 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2916 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2917 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2918 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2919 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2920 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2921 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2949 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2950 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2951 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2954 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2982 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2983 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2984 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2985 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2986 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2987 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2988 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2989 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2990 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2991 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2992 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2993 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2994 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2995 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2996 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2997 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2998 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2999 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3000 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3001 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3002 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3113 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3114 # if ENABLE_ASH_ALIAS
3115 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3119 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3121 #endif /* !USE_SIT_FUNCTION */
3124 /* ============ Alias handling */
3126 #if ENABLE_ASH_ALIAS
3128 #define ALIASINUSE 1
3139 static struct alias **atab; // [ATABSIZE];
3140 #define INIT_G_alias() do { \
3141 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3145 static struct alias **
3146 __lookupalias(const char *name) {
3147 unsigned int hashval;
3154 ch = (unsigned char)*p;
3158 ch = (unsigned char)*++p;
3160 app = &atab[hashval % ATABSIZE];
3162 for (; *app; app = &(*app)->next) {
3163 if (strcmp(name, (*app)->name) == 0) {
3171 static struct alias *
3172 lookupalias(const char *name, int check)
3174 struct alias *ap = *__lookupalias(name);
3176 if (check && ap && (ap->flag & ALIASINUSE))
3181 static struct alias *
3182 freealias(struct alias *ap)
3186 if (ap->flag & ALIASINUSE) {
3187 ap->flag |= ALIASDEAD;
3199 setalias(const char *name, const char *val)
3201 struct alias *ap, **app;
3203 app = __lookupalias(name);
3207 if (!(ap->flag & ALIASINUSE)) {
3210 ap->val = ckstrdup(val);
3211 ap->flag &= ~ALIASDEAD;
3214 ap = ckzalloc(sizeof(struct alias));
3215 ap->name = ckstrdup(name);
3216 ap->val = ckstrdup(val);
3217 /*ap->flag = 0; - ckzalloc did it */
3218 /*ap->next = NULL;*/
3225 unalias(const char *name)
3229 app = __lookupalias(name);
3233 *app = freealias(*app);
3244 struct alias *ap, **app;
3248 for (i = 0; i < ATABSIZE; i++) {
3250 for (ap = *app; ap; ap = *app) {
3251 *app = freealias(*app);
3261 printalias(const struct alias *ap)
3263 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3267 * TODO - sort output
3269 static int FAST_FUNC
3270 aliascmd(int argc UNUSED_PARAM, char **argv)
3279 for (i = 0; i < ATABSIZE; i++) {
3280 for (ap = atab[i]; ap; ap = ap->next) {
3286 while ((n = *++argv) != NULL) {
3287 v = strchr(n+1, '=');
3288 if (v == NULL) { /* n+1: funny ksh stuff */
3289 ap = *__lookupalias(n);
3291 fprintf(stderr, "%s: %s not found\n", "alias", n);
3304 static int FAST_FUNC
3305 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3309 while ((i = nextopt("a")) != '\0') {
3315 for (i = 0; *argptr; argptr++) {
3316 if (unalias(*argptr)) {
3317 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3325 #endif /* ASH_ALIAS */
3328 /* ============ jobs.c */
3330 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3333 #define FORK_NOJOB 2
3335 /* mode flags for showjob(s) */
3336 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3337 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3338 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3339 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3342 * A job structure contains information about a job. A job is either a
3343 * single process or a set of processes contained in a pipeline. In the
3344 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3348 pid_t ps_pid; /* process id */
3349 int ps_status; /* last process status from wait() */
3350 char *ps_cmd; /* text of command being run */
3354 struct procstat ps0; /* status of process */
3355 struct procstat *ps; /* status or processes when more than one */
3357 int stopstatus; /* status of a stopped job */
3360 nprocs: 16, /* number of processes */
3362 #define JOBRUNNING 0 /* at least one proc running */
3363 #define JOBSTOPPED 1 /* all procs are stopped */
3364 #define JOBDONE 2 /* all procs are completed */
3366 sigint: 1, /* job was killed by SIGINT */
3367 jobctl: 1, /* job running under job control */
3369 waited: 1, /* true if this entry has been waited for */
3370 used: 1, /* true if this entry is in used */
3371 changed: 1; /* true if status has changed */
3372 struct job *prev_job; /* previous job */
3375 static struct job *makejob(/*union node *,*/ int);
3376 static int forkshell(struct job *, union node *, int);
3377 static int waitforjob(struct job *);
3380 enum { doing_jobctl = 0 };
3381 #define setjobctl(on) do {} while (0)
3383 static smallint doing_jobctl; //references:8
3384 static void setjobctl(int);
3391 ignoresig(int signo)
3393 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3394 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3395 /* No, need to do it */
3396 signal(signo, SIG_IGN);
3398 sigmode[signo - 1] = S_HARD_IGN;
3402 * Only one usage site - in setsignal()
3405 signal_handler(int signo)
3407 gotsig[signo - 1] = 1;
3409 if (signo == SIGINT && !trap[SIGINT]) {
3410 if (!suppress_int) {
3412 raise_interrupt(); /* does not return */
3416 pending_sig = signo;
3421 * Set the signal handler for the specified signal. The routine figures
3422 * out what it should be set to.
3425 setsignal(int signo)
3428 char cur_act, new_act;
3429 struct sigaction act;
3433 if (t != NULL) { /* trap for this sig is set */
3435 if (t[0] == '\0') /* trap is "": ignore this sig */
3439 if (rootshell && new_act == S_DFL) {
3442 if (iflag || minusc || sflag == 0)
3451 * "In all cases, bash ignores SIGQUIT. Non-builtin
3452 * commands run by bash have signal handlers
3453 * set to the values inherited by the shell
3454 * from its parent". */
3470 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3471 //whereas we have to restore it to what shell got on entry
3472 //from the parent. See comment above
3474 t = &sigmode[signo - 1];
3477 /* current setting is not yet known */
3478 if (sigaction(signo, NULL, &act)) {
3479 /* pretend it worked; maybe we should give a warning,
3480 * but other shells don't. We don't alter sigmode,
3481 * so we retry every time.
3482 * btw, in Linux it never fails. --vda */
3485 if (act.sa_handler == SIG_IGN) {
3486 cur_act = S_HARD_IGN;
3488 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3490 cur_act = S_IGN; /* don't hard ignore these */
3494 if (cur_act == S_HARD_IGN || cur_act == new_act)
3497 act.sa_handler = SIG_DFL;
3500 act.sa_handler = signal_handler;
3503 act.sa_handler = SIG_IGN;
3507 /* flags and mask matter only if !DFL and !IGN, but we do it
3508 * for all cases for more deterministic behavior:
3511 sigfillset(&act.sa_mask);
3513 sigaction_set(signo, &act);
3518 /* mode flags for set_curjob */
3519 #define CUR_DELETE 2
3520 #define CUR_RUNNING 1
3521 #define CUR_STOPPED 0
3523 /* mode flags for dowait */
3524 #define DOWAIT_NONBLOCK WNOHANG
3525 #define DOWAIT_BLOCK 0
3528 /* pgrp of shell on invocation */
3529 static int initialpgrp; //references:2
3530 static int ttyfd = -1; //5
3533 static struct job *jobtab; //5
3535 static unsigned njobs; //4
3537 static struct job *curjob; //lots
3538 /* number of presumed living untracked jobs */
3539 static int jobless; //4
3542 set_curjob(struct job *jp, unsigned mode)
3545 struct job **jpp, **curp;
3547 /* first remove from list */
3548 jpp = curp = &curjob;
3553 jpp = &jp1->prev_job;
3555 *jpp = jp1->prev_job;
3557 /* Then re-insert in correct position */
3565 /* job being deleted */
3568 /* newly created job or backgrounded job,
3569 * put after all stopped jobs.
3574 if (!jp1 || jp1->state != JOBSTOPPED)
3577 jpp = &jp1->prev_job;
3583 /* newly stopped job - becomes curjob */
3584 jp->prev_job = *jpp;
3592 jobno(const struct job *jp)
3594 return jp - jobtab + 1;
3599 * Convert a job name to a job structure.
3602 #define getjob(name, getctl) getjob(name)
3605 getjob(const char *name, int getctl)
3609 const char *err_msg = "%s: no such job";
3613 char *(*match)(const char *, const char *);
3628 if (c == '+' || c == '%') {
3630 err_msg = "No current job";
3636 err_msg = "No previous job";
3647 jp = jobtab + num - 1;
3662 if (match(jp->ps[0].ps_cmd, p)) {
3666 err_msg = "%s: ambiguous";
3676 err_msg = "job %s not created under job control";
3677 if (getctl && jp->jobctl == 0)
3682 ash_msg_and_raise_error(err_msg, name);
3686 * Mark a job structure as unused.
3689 freejob(struct job *jp)
3691 struct procstat *ps;
3695 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3696 if (ps->ps_cmd != nullstr)
3699 if (jp->ps != &jp->ps0)
3702 set_curjob(jp, CUR_DELETE);
3708 xtcsetpgrp(int fd, pid_t pgrp)
3710 if (tcsetpgrp(fd, pgrp))
3711 ash_msg_and_raise_error("can't set tty process group (%m)");
3715 * Turn job control on and off.
3717 * Note: This code assumes that the third arg to ioctl is a character
3718 * pointer, which is true on Berkeley systems but not System V. Since
3719 * System V doesn't have job control yet, this isn't a problem now.
3721 * Called with interrupts off.
3729 if (on == doing_jobctl || rootshell == 0)
3733 ofd = fd = open(_PATH_TTY, O_RDWR);
3735 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3736 * That sometimes helps to acquire controlling tty.
3737 * Obviously, a workaround for bugs when someone
3738 * failed to provide a controlling tty to bash! :) */
3744 fd = fcntl(fd, F_DUPFD, 10);
3749 /* fd is a tty at this point */
3750 close_on_exec_on(fd);
3751 while (1) { /* while we are in the background */
3752 pgrp = tcgetpgrp(fd);
3755 ash_msg("can't access tty; job control turned off");
3759 if (pgrp == getpgrp())
3770 xtcsetpgrp(fd, pgrp);
3772 /* turning job control off */
3775 /* was xtcsetpgrp, but this can make exiting ash
3776 * loop forever if pty is already deleted */
3777 tcsetpgrp(fd, pgrp);
3791 static int FAST_FUNC
3792 killcmd(int argc, char **argv)
3794 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3797 if (argv[i][0] == '%') {
3799 * "kill %N" - job kill
3800 * Converting to pgrp / pid kill
3806 jp = getjob(argv[i], 0);
3808 * In jobs started under job control, we signal
3809 * entire process group by kill -PGRP_ID.
3810 * This happens, f.e., in interactive shell.
3812 * Otherwise, we signal each child via
3813 * kill PID1 PID2 PID3.
3815 * sh -c 'sleep 1|sleep 1 & kill %1'
3816 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3817 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3819 n = jp->nprocs; /* can't be 0 (I hope) */
3822 dst = alloca(n * sizeof(int)*4);
3824 for (j = 0; j < n; j++) {
3825 struct procstat *ps = &jp->ps[j];
3826 /* Skip non-running and not-stopped members
3827 * (i.e. dead members) of the job
3829 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3832 * kill_main has matching code to expect
3833 * leading space. Needed to not confuse
3834 * negative pids with "kill -SIGNAL_NO" syntax
3836 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3840 } while (argv[++i]);
3842 return kill_main(argc, argv);
3846 showpipe(struct job *jp /*, FILE *out*/)
3848 struct procstat *ps;
3849 struct procstat *psend;
3851 psend = jp->ps + jp->nprocs;
3852 for (ps = jp->ps + 1; ps < psend; ps++)
3853 printf(" | %s", ps->ps_cmd);
3854 newline_and_flush(stdout);
3855 flush_stdout_stderr();
3860 restartjob(struct job *jp, int mode)
3862 struct procstat *ps;
3868 if (jp->state == JOBDONE)
3870 jp->state = JOBRUNNING;
3871 pgid = jp->ps[0].ps_pid;
3872 if (mode == FORK_FG)
3873 xtcsetpgrp(ttyfd, pgid);
3874 killpg(pgid, SIGCONT);
3878 if (WIFSTOPPED(ps->ps_status)) {
3884 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3889 static int FAST_FUNC
3890 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3896 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3900 jp = getjob(*argv, 1);
3901 if (mode == FORK_BG) {
3902 set_curjob(jp, CUR_RUNNING);
3903 printf("[%d] ", jobno(jp));
3905 out1str(jp->ps[0].ps_cmd);
3906 showpipe(jp /*, stdout*/);
3907 retval = restartjob(jp, mode);
3908 } while (*argv && *++argv);
3914 sprint_status48(char *s, int status, int sigonly)
3920 if (!WIFEXITED(status)) {
3921 if (JOBS && WIFSTOPPED(status))
3922 st = WSTOPSIG(status);
3924 st = WTERMSIG(status);
3926 if (st == SIGINT || st == SIGPIPE)
3928 if (JOBS && WIFSTOPPED(status))
3932 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3933 col = fmtstr(s, 32, strsignal(st));
3934 if (WCOREDUMP(status)) {
3935 strcpy(s + col, " (core dumped)");
3936 col += sizeof(" (core dumped)")-1;
3938 } else if (!sigonly) {
3939 st = WEXITSTATUS(status);
3940 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
3947 dowait(int wait_flags, struct job *job)
3952 struct job *thisjob;
3954 TRACE(("dowait(0x%x) called\n", wait_flags));
3956 /* Do a wait system call. If job control is compiled in, we accept
3957 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3958 * NB: _not_ safe_waitpid, we need to detect EINTR */
3960 wait_flags |= WUNTRACED;
3961 pid = waitpid(-1, &status, wait_flags);
3962 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3963 pid, status, errno, strerror(errno)));
3969 for (jp = curjob; jp; jp = jp->prev_job) {
3971 struct procstat *ps;
3972 struct procstat *psend;
3973 if (jp->state == JOBDONE)
3977 psend = ps + jp->nprocs;
3979 if (ps->ps_pid == pid) {
3980 TRACE(("Job %d: changing status of proc %d "
3981 "from 0x%x to 0x%x\n",
3982 jobno(jp), pid, ps->ps_status, status));
3983 ps->ps_status = status;
3986 if (ps->ps_status == -1)
3987 jobstate = JOBRUNNING;
3989 if (jobstate == JOBRUNNING)
3991 if (WIFSTOPPED(ps->ps_status)) {
3992 jp->stopstatus = ps->ps_status;
3993 jobstate = JOBSTOPPED;
3996 } while (++ps < psend);
4000 /* Found the job where one of its processes changed its state.
4001 * Is there at least one live and running process in this job? */
4002 if (jobstate != JOBRUNNING) {
4003 /* No. All live processes in the job are stopped
4004 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4006 thisjob->changed = 1;
4007 if (thisjob->state != jobstate) {
4008 TRACE(("Job %d: changing state from %d to %d\n",
4009 jobno(thisjob), thisjob->state, jobstate));
4010 thisjob->state = jobstate;
4012 if (jobstate == JOBSTOPPED)
4013 set_curjob(thisjob, CUR_STOPPED);
4019 /* The process wasn't found in job list */
4020 if (JOBS && !WIFSTOPPED(status))
4025 if (thisjob && thisjob == job) {
4029 len = sprint_status48(s, status, 1);
4040 blocking_wait_with_raise_on_sig(void)
4042 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
4043 if (pid <= 0 && pending_sig)
4044 raise_exception(EXSIG);
4050 showjob(struct job *jp, int mode)
4052 struct procstat *ps;
4053 struct procstat *psend;
4056 char s[16 + 16 + 48];
4057 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4061 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4062 /* just output process (group) id of pipeline */
4063 fprintf(out, "%d\n", ps->ps_pid);
4067 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4072 else if (curjob && jp == curjob->prev_job)
4075 if (mode & SHOW_PIDS)
4076 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4078 psend = ps + jp->nprocs;
4080 if (jp->state == JOBRUNNING) {
4081 strcpy(s + col, "Running");
4082 col += sizeof("Running") - 1;
4084 int status = psend[-1].ps_status;
4085 if (jp->state == JOBSTOPPED)
4086 status = jp->stopstatus;
4087 col += sprint_status48(s + col, status, 0);
4089 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4091 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4092 * or prints several "PID | <cmdN>" lines,
4093 * depending on SHOW_PIDS bit.
4094 * We do not print status of individual processes
4095 * between PID and <cmdN>. bash does it, but not very well:
4096 * first line shows overall job status, not process status,
4097 * making it impossible to know 1st process status.
4101 /* for each process */
4104 if (mode & SHOW_PIDS)
4105 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4107 fprintf(out, "%s%*c%s%s",
4109 33 - col >= 0 ? 33 - col : 0, ' ',
4110 ps == jp->ps ? "" : "| ",
4113 } while (++ps != psend);
4114 newline_and_flush(out);
4118 if (jp->state == JOBDONE) {
4119 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4125 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4126 * statuses have changed since the last call to showjobs.
4133 TRACE(("showjobs(0x%x) called\n", mode));
4135 /* Handle all finished jobs */
4136 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4139 for (jp = curjob; jp; jp = jp->prev_job) {
4140 if (!(mode & SHOW_CHANGED) || jp->changed) {
4146 static int FAST_FUNC
4147 jobscmd(int argc UNUSED_PARAM, char **argv)
4152 while ((m = nextopt("lp")) != '\0') {
4156 mode |= SHOW_ONLY_PGID;
4162 showjob(getjob(*argv, 0), mode);
4172 /* Called only on finished or stopped jobs (no members are running) */
4174 getstatus(struct job *job)
4178 struct procstat *ps;
4180 /* Fetch last member's status */
4181 ps = job->ps + job->nprocs - 1;
4182 status = ps->ps_status;
4184 /* "set -o pipefail" mode: use last _nonzero_ status */
4185 while (status == 0 && --ps >= job->ps)
4186 status = ps->ps_status;
4189 retval = WEXITSTATUS(status);
4190 if (!WIFEXITED(status)) {
4192 retval = WSTOPSIG(status);
4193 if (!WIFSTOPPED(status))
4196 /* XXX: limits number of signals */
4197 retval = WTERMSIG(status);
4199 if (retval == SIGINT)
4205 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4206 jobno(job), job->nprocs, status, retval));
4210 static int FAST_FUNC
4211 waitcmd(int argc UNUSED_PARAM, char **argv)
4218 raise_exception(EXSIG);
4225 /* wait for all jobs */
4229 if (!jp) /* no running procs */
4231 if (jp->state == JOBRUNNING)
4236 blocking_wait_with_raise_on_sig();
4238 * "When bash is waiting for an asynchronous command via
4239 * the wait builtin, the reception of a signal for which a trap
4240 * has been set will cause the wait builtin to return immediately
4241 * with an exit status greater than 128, immediately after which
4242 * the trap is executed."
4244 * blocking_wait_with_raise_on_sig raises signal handlers
4245 * if it gets no pid (pid < 0). However,
4246 * if child sends us a signal *and immediately exits*,
4247 * blocking_wait_with_raise_on_sig gets pid > 0
4248 * and does not handle pending_sig. Check this case: */
4250 raise_exception(EXSIG);
4256 if (**argv != '%') {
4257 pid_t pid = number(*argv);
4262 if (job->ps[job->nprocs - 1].ps_pid == pid)
4264 job = job->prev_job;
4267 job = getjob(*argv, 0);
4269 /* loop until process terminated or stopped */
4270 while (job->state == JOBRUNNING)
4271 blocking_wait_with_raise_on_sig();
4273 retval = getstatus(job);
4286 struct job *jp, *jq;
4288 len = njobs * sizeof(*jp);
4290 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4292 offset = (char *)jp - (char *)jq;
4294 /* Relocate pointers */
4297 jq = (struct job *)((char *)jq + l);
4301 #define joff(p) ((struct job *)((char *)(p) + l))
4302 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4303 if (joff(jp)->ps == &jq->ps0)
4304 jmove(joff(jp)->ps);
4305 if (joff(jp)->prev_job)
4306 jmove(joff(jp)->prev_job);
4316 jp = (struct job *)((char *)jp + len);
4320 } while (--jq >= jp);
4325 * Return a new job structure.
4326 * Called with interrupts off.
4329 makejob(/*union node *node,*/ int nprocs)
4334 for (i = njobs, jp = jobtab; ; jp++) {
4341 if (jp->state != JOBDONE || !jp->waited)
4350 memset(jp, 0, sizeof(*jp));
4352 /* jp->jobctl is a bitfield.
4353 * "jp->jobctl |= jobctl" likely to give awful code */
4357 jp->prev_job = curjob;
4362 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4364 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4371 * Return a string identifying a command (to be printed by the
4374 static char *cmdnextc;
4377 cmdputs(const char *s)
4379 static const char vstype[VSTYPE + 1][3] = {
4380 "", "}", "-", "+", "?", "=",
4381 "%", "%%", "#", "##"
4382 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4385 const char *p, *str;
4389 unsigned char subtype = 0;
4393 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4395 while ((c = *p++) != '\0') {
4403 if ((subtype & VSTYPE) == VSLENGTH)
4409 str = "\"}" + !(quoted & 1);
4416 #if ENABLE_SH_MATH_SUPPORT
4431 if ((subtype & VSTYPE) != VSNORMAL)
4433 str = vstype[subtype & VSTYPE];
4434 if (subtype & VSNUL)
4443 /* These can only happen inside quotes */
4456 while ((c = *str++) != '\0') {
4459 } /* while *p++ not NUL */
4462 USTPUTC('"', nextc);
4468 /* cmdtxt() and cmdlist() call each other */
4469 static void cmdtxt(union node *n);
4472 cmdlist(union node *np, int sep)
4474 for (; np; np = np->narg.next) {
4478 if (sep && np->narg.next)
4484 cmdtxt(union node *n)
4487 struct nodelist *lp;
4498 lp = n->npipe.cmdlist;
4516 cmdtxt(n->nbinary.ch1);
4532 cmdtxt(n->nif.test);
4534 if (n->nif.elsepart) {
4535 cmdtxt(n->nif.ifpart);
4537 n = n->nif.elsepart;
4555 cmdtxt(n->nbinary.ch1);
4565 cmdputs(n->nfor.var);
4567 cmdlist(n->nfor.args, 1);
4572 cmdputs(n->narg.text);
4576 cmdlist(n->ncmd.args, 1);
4577 cmdlist(n->ncmd.redirect, 0);
4590 cmdputs(n->ncase.expr->narg.text);
4592 for (np = n->ncase.cases; np; np = np->nclist.next) {
4593 cmdtxt(np->nclist.pattern);
4595 cmdtxt(np->nclist.body);
4609 #if ENABLE_ASH_BASH_COMPAT
4624 cmdputs(utoa(n->nfile.fd));
4626 if (n->type == NTOFD || n->type == NFROMFD) {
4627 cmdputs(utoa(n->ndup.dupfd));
4636 commandtext(union node *n)
4640 STARTSTACKSTR(cmdnextc);
4642 name = stackblock();
4643 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4644 name, cmdnextc, cmdnextc));
4645 return ckstrdup(name);
4650 * Fork off a subshell. If we are doing job control, give the subshell its
4651 * own process group. Jp is a job structure that the job is to be added to.
4652 * N is the command that will be evaluated by the child. Both jp and n may
4653 * be NULL. The mode parameter can be one of the following:
4654 * FORK_FG - Fork off a foreground process.
4655 * FORK_BG - Fork off a background process.
4656 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4657 * process group even if job control is on.
4659 * When job control is turned off, background processes have their standard
4660 * input redirected to /dev/null (except for the second and later processes
4663 * Called with interrupts off.
4666 * Clear traps on a fork.
4673 for (tp = trap; tp < &trap[NSIG]; tp++) {
4674 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4676 if (trap_ptr == trap)
4678 /* else: it "belongs" to trap_ptr vector, don't free */
4680 if ((tp - trap) != 0)
4681 setsignal(tp - trap);
4688 /* Lives far away from here, needed for forkchild */
4689 static void closescript(void);
4691 /* Called after fork(), in child */
4692 static NOINLINE void
4693 forkchild(struct job *jp, union node *n, int mode)
4697 TRACE(("Child shell %d\n", getpid()));
4701 /* man bash: "Non-builtin commands run by bash have signal handlers
4702 * set to the values inherited by the shell from its parent".
4703 * Do we do it correctly? */
4707 if (mode == FORK_NOJOB /* is it `xxx` ? */
4708 && n && n->type == NCMD /* is it single cmd? */
4709 /* && n->ncmd.args->type == NARG - always true? */
4710 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4711 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4712 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4714 TRACE(("Trap hack\n"));
4715 /* Awful hack for `trap` or $(trap).
4717 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4718 * contains an example where "trap" is executed in a subshell:
4720 * save_traps=$(trap)
4722 * eval "$save_traps"
4724 * Standard does not say that "trap" in subshell shall print
4725 * parent shell's traps. It only says that its output
4726 * must have suitable form, but then, in the above example
4727 * (which is not supposed to be normative), it implies that.
4729 * bash (and probably other shell) does implement it
4730 * (traps are reset to defaults, but "trap" still shows them),
4731 * but as a result, "trap" logic is hopelessly messed up:
4734 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4735 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4736 * # true | trap <--- trap is in subshell - no output (ditto)
4737 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4738 * trap -- 'echo Ho' SIGWINCH
4739 * # echo `(trap)` <--- in subshell in subshell - output
4740 * trap -- 'echo Ho' SIGWINCH
4741 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4742 * trap -- 'echo Ho' SIGWINCH
4744 * The rules when to forget and when to not forget traps
4745 * get really complex and nonsensical.
4747 * Our solution: ONLY bare $(trap) or `trap` is special.
4749 /* Save trap handler strings for trap builtin to print */
4750 trap_ptr = xmemdup(trap, sizeof(trap));
4751 /* Fall through into clearing traps */
4755 /* do job control only in root shell */
4757 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4760 if (jp->nprocs == 0)
4763 pgrp = jp->ps[0].ps_pid;
4764 /* this can fail because we are doing it in the parent also */
4766 if (mode == FORK_FG)
4767 xtcsetpgrp(ttyfd, pgrp);
4772 if (mode == FORK_BG) {
4773 /* man bash: "When job control is not in effect,
4774 * asynchronous commands ignore SIGINT and SIGQUIT" */
4777 if (jp->nprocs == 0) {
4779 if (open(bb_dev_null, O_RDONLY) != 0)
4780 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4784 if (iflag) { /* why if iflag only? */
4789 * "In all cases, bash ignores SIGQUIT. Non-builtin
4790 * commands run by bash have signal handlers
4791 * set to the values inherited by the shell
4793 * Take care of the second rule: */
4797 if (n && n->type == NCMD
4798 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4800 TRACE(("Job hack\n"));
4801 /* "jobs": we do not want to clear job list for it,
4802 * instead we remove only _its_ own_ job from job list.
4803 * This makes "jobs .... | cat" more useful.
4809 for (jp = curjob; jp; jp = jp->prev_job)
4814 /* Called after fork(), in parent */
4816 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4819 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4821 TRACE(("In parent shell: child = %d\n", pid));
4823 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4829 if (mode != FORK_NOJOB && jp->jobctl) {
4832 if (jp->nprocs == 0)
4835 pgrp = jp->ps[0].ps_pid;
4836 /* This can fail because we are doing it in the child also */
4840 if (mode == FORK_BG) {
4841 backgndpid = pid; /* set $! */
4842 set_curjob(jp, CUR_RUNNING);
4845 struct procstat *ps = &jp->ps[jp->nprocs++];
4848 ps->ps_cmd = nullstr;
4850 if (doing_jobctl && n)
4851 ps->ps_cmd = commandtext(n);
4857 forkshell(struct job *jp, union node *n, int mode)
4861 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4864 TRACE(("Fork failed, errno=%d", errno));
4867 ash_msg_and_raise_error("can't fork");
4870 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4871 forkchild(jp, n, mode);
4873 forkparent(jp, n, mode, pid);
4879 * Wait for job to finish.
4881 * Under job control we have the problem that while a child process
4882 * is running interrupts generated by the user are sent to the child
4883 * but not to the shell. This means that an infinite loop started by
4884 * an interactive user may be hard to kill. With job control turned off,
4885 * an interactive user may place an interactive program inside a loop.
4886 * If the interactive program catches interrupts, the user doesn't want
4887 * these interrupts to also abort the loop. The approach we take here
4888 * is to have the shell ignore interrupt signals while waiting for a
4889 * foreground process to terminate, and then send itself an interrupt
4890 * signal if the child process was terminated by an interrupt signal.
4891 * Unfortunately, some programs want to do a bit of cleanup and then
4892 * exit on interrupt; unless these processes terminate themselves by
4893 * sending a signal to themselves (instead of calling exit) they will
4894 * confuse this approach.
4896 * Called with interrupts off.
4899 waitforjob(struct job *jp)
4903 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4906 while (jp->state == JOBRUNNING) {
4907 /* In non-interactive shells, we _can_ get
4908 * a keyboard signal here and be EINTRed,
4909 * but we just loop back, waiting for command to complete.
4912 * "If bash is waiting for a command to complete and receives
4913 * a signal for which a trap has been set, the trap
4914 * will not be executed until the command completes."
4916 * Reality is that even if trap is not set, bash
4917 * will not act on the signal until command completes.
4918 * Try this. sleep5intoff.c:
4919 * #include <signal.h>
4920 * #include <unistd.h>
4923 * sigemptyset(&set);
4924 * sigaddset(&set, SIGINT);
4925 * sigaddset(&set, SIGQUIT);
4926 * sigprocmask(SIG_BLOCK, &set, NULL);
4930 * $ bash -c './sleep5intoff; echo hi'
4931 * ^C^C^C^C <--- pressing ^C once a second
4933 * $ bash -c './sleep5intoff; echo hi'
4934 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4937 dowait(DOWAIT_BLOCK, jp);
4944 xtcsetpgrp(ttyfd, rootpid);
4946 * This is truly gross.
4947 * If we're doing job control, then we did a TIOCSPGRP which
4948 * caused us (the shell) to no longer be in the controlling
4949 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4950 * intuit from the subprocess exit status whether a SIGINT
4951 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4953 if (jp->sigint) /* TODO: do the same with all signals */
4954 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4956 if (jp->state == JOBDONE)
4963 * return 1 if there are stopped jobs, otherwise 0
4975 if (jp && jp->state == JOBSTOPPED) {
4976 out2str("You have stopped jobs.\n");
4985 /* ============ redir.c
4987 * Code for dealing with input/output redirection.
4992 #define EMPTY -2 /* marks an unused slot in redirtab */
4993 #define CLOSED -3 /* marks a slot of previously-closed fd */
4996 * Open a file in noclobber mode.
4997 * The code was copied from bash.
5000 noclobberopen(const char *fname)
5003 struct stat finfo, finfo2;
5006 * If the file exists and is a regular file, return an error
5009 r = stat(fname, &finfo);
5010 if (r == 0 && S_ISREG(finfo.st_mode)) {
5016 * If the file was not present (r != 0), make sure we open it
5017 * exclusively so that if it is created before we open it, our open
5018 * will fail. Make sure that we do not truncate an existing file.
5019 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5020 * file was not a regular file, we leave O_EXCL off.
5023 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5024 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5026 /* If the open failed, return the file descriptor right away. */
5031 * OK, the open succeeded, but the file may have been changed from a
5032 * non-regular file to a regular file between the stat and the open.
5033 * We are assuming that the O_EXCL open handles the case where FILENAME
5034 * did not exist and is symlinked to an existing file between the stat
5039 * If we can open it and fstat the file descriptor, and neither check
5040 * revealed that it was a regular file, and the file has not been
5041 * replaced, return the file descriptor.
5043 if (fstat(fd, &finfo2) == 0
5044 && !S_ISREG(finfo2.st_mode)
5045 && finfo.st_dev == finfo2.st_dev
5046 && finfo.st_ino == finfo2.st_ino
5051 /* The file has been replaced. badness. */
5058 * Handle here documents. Normally we fork off a process to write the
5059 * data to a pipe. If the document is short, we can stuff the data in
5060 * the pipe without forking.
5062 /* openhere needs this forward reference */
5063 static void expandhere(union node *arg, int fd);
5065 openhere(union node *redir)
5071 ash_msg_and_raise_error("pipe call failed");
5072 if (redir->type == NHERE) {
5073 len = strlen(redir->nhere.doc->narg.text);
5074 if (len <= PIPE_BUF) {
5075 full_write(pip[1], redir->nhere.doc->narg.text, len);
5079 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5082 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5083 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5084 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5085 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5086 signal(SIGPIPE, SIG_DFL);
5087 if (redir->type == NHERE)
5088 full_write(pip[1], redir->nhere.doc->narg.text, len);
5090 expandhere(redir->nhere.doc, pip[1]);
5091 _exit(EXIT_SUCCESS);
5099 openredirect(union node *redir)
5104 fname = redir->nfile.expfname;
5105 switch (redir->nfile.type) {
5107 f = open(fname, O_RDONLY);
5112 f = open(fname, O_RDWR|O_CREAT, 0666);
5117 #if ENABLE_ASH_BASH_COMPAT
5120 /* Take care of noclobber mode. */
5122 f = noclobberopen(fname);
5129 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5134 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5142 /* Fall through to eliminate warning. */
5143 /* Our single caller does this itself */
5150 f = openhere(redir);
5156 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5158 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5162 * Copy a file descriptor to be >= to. Returns -1
5163 * if the source file descriptor is closed, EMPTY if there are no unused
5164 * file descriptors left.
5166 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5167 * old code was doing close(to) prior to copyfd() to achieve the same */
5169 COPYFD_EXACT = (int)~(INT_MAX),
5170 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5173 copyfd(int from, int to)
5177 if (to & COPYFD_EXACT) {
5178 to &= ~COPYFD_EXACT;
5180 newfd = dup2(from, to);
5182 newfd = fcntl(from, F_DUPFD, to);
5185 if (errno == EMFILE)
5187 /* Happens when source fd is not open: try "echo >&99" */
5188 ash_msg_and_raise_error("%d: %m", from);
5193 /* Struct def and variable are moved down to the first usage site */
5198 struct redirtab *next;
5201 struct two_fd_t two_fd[];
5203 #define redirlist (G_var.redirlist)
5205 static int need_to_remember(struct redirtab *rp, int fd)
5209 if (!rp) /* remembering was not requested */
5212 for (i = 0; i < rp->pair_count; i++) {
5213 if (rp->two_fd[i].orig == fd) {
5214 /* already remembered */
5221 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5222 static int is_hidden_fd(struct redirtab *rp, int fd)
5225 struct parsefile *pf;
5229 /* Check open scripts' fds */
5232 /* We skip pf_fd == 0 case because of the following case:
5233 * $ ash # running ash interactively
5235 * and in script.sh: "exec 9>&0".
5236 * Even though top-level pf_fd _is_ 0,
5237 * it's still ok to use it: "read" builtin uses it,
5238 * why should we cripple "exec" builtin?
5240 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5248 /* Check saved fds of redirects */
5249 fd |= COPYFD_RESTORE;
5250 for (i = 0; i < rp->pair_count; i++) {
5251 if (rp->two_fd[i].copy == fd) {
5259 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5260 * old file descriptors are stashed away so that the redirection can be
5261 * undone by calling popredir.
5263 /* flags passed to redirect */
5264 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5265 #define REDIR_SAVEFD2 03 /* set preverrout */
5267 redirect(union node *redir, int flags)
5269 struct redirtab *sv;
5274 int copied_fd2 = -1;
5284 if (flags & REDIR_PUSH) {
5285 union node *tmp = redir;
5288 #if ENABLE_ASH_BASH_COMPAT
5289 if (tmp->nfile.type == NTO2)
5292 tmp = tmp->nfile.next;
5294 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5295 sv->next = redirlist;
5296 sv->pair_count = sv_pos;
5298 sv->nullredirs = g_nullredirs - 1;
5300 while (sv_pos > 0) {
5302 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5308 fd = redir->nfile.fd;
5309 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5310 right_fd = redir->ndup.dupfd;
5311 //bb_error_msg("doing %d > %d", fd, right_fd);
5312 /* redirect from/to same file descriptor? */
5315 /* "echo >&10" and 10 is a fd opened to a sh script? */
5316 if (is_hidden_fd(sv, right_fd)) {
5317 errno = EBADF; /* as if it is closed */
5318 ash_msg_and_raise_error("%d: %m", right_fd);
5322 newfd = openredirect(redir); /* always >= 0 */
5324 /* Descriptor wasn't open before redirect.
5325 * Mark it for close in the future */
5326 if (need_to_remember(sv, fd)) {
5327 goto remember_to_close;
5332 #if ENABLE_ASH_BASH_COMPAT
5335 if (need_to_remember(sv, fd)) {
5336 /* Copy old descriptor */
5337 /* Careful to not accidentally "save"
5338 * to the same fd as right side fd in N>&M */
5339 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5340 i = fcntl(fd, F_DUPFD, minfd);
5341 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5342 * are closed in popredir() in the child, preventing them from leaking
5343 * into child. (popredir() also cleans up the mess in case of failures)
5348 /* Strange error (e.g. "too many files" EMFILE?) */
5352 ash_msg_and_raise_error("%d: %m", fd);
5355 /* EBADF: it is not open - good, remember to close it */
5358 } else { /* fd is open, save its copy */
5359 /* "exec fd>&-" should not close fds
5360 * which point to script file(s).
5361 * Force them to be restored afterwards */
5362 if (is_hidden_fd(sv, fd))
5363 i |= COPYFD_RESTORE;
5367 sv->two_fd[sv_pos].orig = fd;
5368 sv->two_fd[sv_pos].copy = i;
5372 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5373 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5374 /* Don't want to trigger debugging */
5378 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5380 } else if (fd != newfd) { /* move newfd to fd */
5381 copyfd(newfd, fd | COPYFD_EXACT);
5382 #if ENABLE_ASH_BASH_COMPAT
5383 if (!(redir->nfile.type == NTO2 && fd == 2))
5387 #if ENABLE_ASH_BASH_COMPAT
5388 if (redir->nfile.type == NTO2 && fd == 1) {
5389 /* We already redirected it to fd 1, now copy it to 2 */
5395 } while ((redir = redir->nfile.next) != NULL);
5398 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5399 preverrout_fd = copied_fd2;
5403 * Undo the effects of the last redirection.
5406 popredir(int drop, int restore)
5408 struct redirtab *rp;
5411 if (--g_nullredirs >= 0 || redirlist == NULL)
5415 for (i = 0; i < rp->pair_count; i++) {
5416 int fd = rp->two_fd[i].orig;
5417 int copy = rp->two_fd[i].copy;
5418 if (copy == CLOSED) {
5423 if (copy != EMPTY) {
5424 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5425 copy &= ~COPYFD_RESTORE;
5427 copyfd(copy, fd | COPYFD_EXACT);
5429 close(copy & ~COPYFD_RESTORE);
5432 redirlist = rp->next;
5433 g_nullredirs = rp->nullredirs;
5439 * Undo all redirections. Called on error or interrupt.
5443 * Discard all saved file descriptors.
5446 clearredir(int drop)
5452 popredir(drop, /*restore:*/ 0);
5457 redirectsafe(union node *redir, int flags)
5460 volatile int saveint;
5461 struct jmploc *volatile savehandler = exception_handler;
5462 struct jmploc jmploc;
5465 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5466 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5468 exception_handler = &jmploc;
5469 redirect(redir, flags);
5471 exception_handler = savehandler;
5472 if (err && exception_type != EXERROR)
5473 longjmp(exception_handler->loc, 1);
5474 RESTORE_INT(saveint);
5479 /* ============ Routines to expand arguments to commands
5481 * We have to deal with backquotes, shell variables, and file metacharacters.
5484 #if ENABLE_SH_MATH_SUPPORT
5486 ash_arith(const char *s)
5488 arith_state_t math_state;
5491 math_state.lookupvar = lookupvar;
5492 math_state.setvar = setvar0;
5493 //math_state.endofname = endofname;
5496 result = arith(&math_state, s);
5497 if (math_state.errmsg)
5498 ash_msg_and_raise_error(math_state.errmsg);
5508 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5509 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5510 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5511 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5512 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5513 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5514 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5515 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5516 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5520 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5521 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5522 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5523 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5524 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5526 /* Add CTLESC when necessary. */
5527 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5528 /* Do not skip NUL characters. */
5529 #define QUOTES_KEEPNUL EXP_TILDE
5532 * Structure specifying which parts of the string should be searched
5533 * for IFS characters.
5536 struct ifsregion *next; /* next region in list */
5537 int begoff; /* offset of start of region */
5538 int endoff; /* offset of end of region */
5539 int nulonly; /* search for nul bytes only */
5543 struct strlist *list;
5544 struct strlist **lastp;
5547 /* output of current string */
5548 static char *expdest;
5549 /* list of back quote expressions */
5550 static struct nodelist *argbackq;
5551 /* first struct in list of ifs regions */
5552 static struct ifsregion ifsfirst;
5553 /* last struct in list */
5554 static struct ifsregion *ifslastp;
5555 /* holds expanded arg list */
5556 static struct arglist exparg;
5561 #if !ENABLE_SH_MATH_SUPPORT
5562 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5563 typedef long arith_t;
5564 # define ARITH_FMT "%ld"
5571 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5572 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5573 STADJUST(len, expdest);
5578 esclen(const char *start, const char *p)
5582 while (p > start && (unsigned char)*--p == CTLESC) {
5589 * Remove any CTLESC characters from a string.
5592 rmescapes(char *str, int flag)
5594 static const char qchars[] ALIGN1 = {
5595 IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
5599 unsigned protect_against_glob;
5601 IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
5603 p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
5609 if (flag & RMESCAPE_ALLOC) {
5610 size_t len = p - str;
5611 size_t fulllen = len + strlen(p) + 1;
5613 if (flag & RMESCAPE_GROW) {
5614 int strloc = str - (char *)stackblock();
5615 r = makestrspace(fulllen, expdest);
5616 /* p and str may be invalidated by makestrspace */
5617 str = (char *)stackblock() + strloc;
5619 } else if (flag & RMESCAPE_HEAP) {
5620 r = ckmalloc(fulllen);
5622 r = stalloc(fulllen);
5626 q = (char *)memcpy(q, str, len) + len;
5631 globbing = flag & RMESCAPE_GLOB;
5632 protect_against_glob = globbing;
5634 if ((unsigned char)*p == CTLQUOTEMARK) {
5635 // Note: both inquotes and protect_against_glob only affect whether
5636 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5637 inquotes = ~inquotes;
5639 protect_against_glob = globbing;
5642 if ((unsigned char)*p == CTLESC) {
5644 if (protect_against_glob) {
5647 } else if (*p == '\\' && !inquotes) {
5648 /* naked back slash */
5649 protect_against_glob = 0;
5652 #if ENABLE_ASH_BASH_COMPAT
5653 else if (*p == '/' && slash) {
5654 /* stop handling globbing and mark location of slash */
5655 globbing = slash = 0;
5659 protect_against_glob = globbing;
5664 if (flag & RMESCAPE_GROW) {
5666 STADJUST(q - r + 1, expdest);
5670 #define pmatch(a, b) !fnmatch((a), (b), 0)
5673 * Prepare a pattern for a expmeta (internal glob(3)) call.
5675 * Returns an stalloced string.
5678 preglob(const char *pattern, int flag)
5680 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5684 * Put a string on the stack.
5687 memtodest(const char *p, size_t len, int syntax, int quotes)
5694 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5697 unsigned char c = *p++;
5699 int n = SIT(c, syntax);
5700 if ((quotes & QUOTES_ESC) &&
5702 (((quotes & EXP_FULL) || syntax != BASESYNTAX) &&
5705 } else if (!(quotes & QUOTES_KEEPNUL))
5714 strtodest(const char *p, int syntax, int quotes)
5716 size_t len = strlen(p);
5717 memtodest(p, len, syntax, quotes);
5722 * Record the fact that we have to scan this region of the
5723 * string for IFS characters.
5726 recordregion(int start, int end, int nulonly)
5728 struct ifsregion *ifsp;
5730 if (ifslastp == NULL) {
5734 ifsp = ckzalloc(sizeof(*ifsp));
5735 /*ifsp->next = NULL; - ckzalloc did it */
5736 ifslastp->next = ifsp;
5740 ifslastp->begoff = start;
5741 ifslastp->endoff = end;
5742 ifslastp->nulonly = nulonly;
5746 removerecordregions(int endoff)
5748 if (ifslastp == NULL)
5751 if (ifsfirst.endoff > endoff) {
5752 while (ifsfirst.next) {
5753 struct ifsregion *ifsp;
5755 ifsp = ifsfirst.next->next;
5756 free(ifsfirst.next);
5757 ifsfirst.next = ifsp;
5760 if (ifsfirst.begoff > endoff) {
5763 ifslastp = &ifsfirst;
5764 ifsfirst.endoff = endoff;
5769 ifslastp = &ifsfirst;
5770 while (ifslastp->next && ifslastp->next->begoff < endoff)
5771 ifslastp = ifslastp->next;
5772 while (ifslastp->next) {
5773 struct ifsregion *ifsp;
5775 ifsp = ifslastp->next->next;
5776 free(ifslastp->next);
5777 ifslastp->next = ifsp;
5780 if (ifslastp->endoff > endoff)
5781 ifslastp->endoff = endoff;
5785 exptilde(char *startp, char *p, int flags)
5791 int quotes = flags & QUOTES_ESC;
5795 while ((c = *++p) != '\0') {
5802 if (flags & EXP_VARTILDE)
5812 if (*name == '\0') {
5813 home = lookupvar("HOME");
5815 pw = getpwnam(name);
5820 if (!home || !*home)
5823 strtodest(home, SQSYNTAX, quotes);
5831 * Execute a command inside back quotes. If it's a builtin command, we
5832 * want to save its output in a block obtained from malloc. Otherwise
5833 * we fork off a subprocess and get the output of the command via a pipe.
5834 * Should be called with interrupts off.
5836 struct backcmd { /* result of evalbackcmd */
5837 int fd; /* file descriptor to read from */
5838 int nleft; /* number of chars in buffer */
5839 char *buf; /* buffer */
5840 struct job *jp; /* job structure for command */
5843 /* These forward decls are needed to use "eval" code for backticks handling: */
5844 static uint8_t back_exitstatus; /* exit status of backquoted command */
5845 #define EV_EXIT 01 /* exit after evaluating tree */
5846 static void evaltree(union node *, int);
5848 static void FAST_FUNC
5849 evalbackcmd(union node *n, struct backcmd *result)
5860 saveherefd = herefd;
5868 ash_msg_and_raise_error("pipe call failed");
5869 jp = makejob(/*n,*/ 1);
5870 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5875 copyfd(pip[1], 1 | COPYFD_EXACT);
5879 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5883 result->fd = pip[0];
5886 herefd = saveherefd;
5888 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5889 result->fd, result->buf, result->nleft, result->jp));
5893 * Expand stuff in backwards quotes.
5896 expbackq(union node *cmd, int flag)
5904 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
5905 struct stackmark smark;
5908 setstackmark(&smark);
5910 startloc = dest - (char *)stackblock();
5912 evalbackcmd(cmd, &in);
5913 popstackmark(&smark);
5920 memtodest(p, i, syntax, flag & QUOTES_ESC);
5924 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
5925 TRACE(("expbackq: read returns %d\n", i));
5934 back_exitstatus = waitforjob(in.jp);
5938 /* Eat all trailing newlines */
5940 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5944 if (!(flag & EXP_QUOTED))
5945 recordregion(startloc, dest - (char *)stackblock(), 0);
5946 TRACE(("evalbackq: size:%d:'%.*s'\n",
5947 (int)((dest - (char *)stackblock()) - startloc),
5948 (int)((dest - (char *)stackblock()) - startloc),
5949 stackblock() + startloc));
5952 #if ENABLE_SH_MATH_SUPPORT
5954 * Expand arithmetic expression. Backup to start of expression,
5955 * evaluate, place result in (backed up) result, adjust string position.
5967 * This routine is slightly over-complicated for
5968 * efficiency. Next we scan backwards looking for the
5969 * start of arithmetic.
5971 start = stackblock();
5978 while ((unsigned char)*p != CTLARI) {
5982 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5987 esc = esclen(start, p);
5997 removerecordregions(begoff);
6001 if (flag & QUOTES_ESC)
6002 rmescapes(p + 1, 0);
6004 len = cvtnum(ash_arith(p + 1));
6006 if (!(flag & EXP_QUOTED))
6007 recordregion(begoff, begoff + len, 0);
6011 /* argstr needs it */
6012 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6015 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6016 * characters to allow for further processing. Otherwise treat
6017 * $@ like $* since no splitting will be performed.
6019 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6020 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6021 * for correct expansion of "B=$A" word.
6024 argstr(char *p, int flags, struct strlist *var_str_list)
6026 static const char spclchars[] ALIGN1 = {
6034 #if ENABLE_SH_MATH_SUPPORT
6039 const char *reject = spclchars;
6040 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6045 if (!(flags & EXP_VARTILDE)) {
6047 } else if (flags & EXP_VARTILDE2) {
6052 if (flags & EXP_TILDE) {
6055 flags &= ~EXP_TILDE;
6059 p = exptilde(p, q, flags);
6062 startloc = expdest - (char *)stackblock();
6066 length += strcspn(p + length, reject);
6070 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6072 /* c == '=' || c == ':' || c == CTLENDARI */
6078 expdest = stack_nputstr(p, length, expdest);
6079 newloc = expdest - (char *)stackblock();
6080 if (breakall && !inquotes && newloc > startloc) {
6081 recordregion(startloc, newloc, 0);
6092 if (flags & EXP_VARTILDE2) {
6096 flags |= EXP_VARTILDE2;
6101 * sort of a hack - expand tildes in variable
6102 * assignments (after the first '=' and after ':'s).
6111 case CTLENDVAR: /* ??? */
6114 inquotes ^= EXP_QUOTED;
6115 /* "$@" syntax adherence hack */
6116 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6117 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6121 if (flags & QUOTES_ESC) {
6132 * Quoted parameter expansion pattern: remove quote
6133 * unless inside inner quotes or we have a literal
6136 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6137 EXP_QPAT && *p != '\\')
6142 TRACE(("argstr: evalvar('%s')\n", p));
6143 p = evalvar(p, flags | inquotes, var_str_list);
6144 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6147 expbackq(argbackq->n, flags | inquotes);
6148 argbackq = argbackq->next;
6150 #if ENABLE_SH_MATH_SUPPORT
6153 expari(flags | inquotes);
6162 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6163 char *pattern, int quotes, int zero)
6172 const char *s = loc2;
6179 match = pmatch(pattern, s);
6184 if (quotes && (unsigned char)*loc == CTLESC)
6193 scanright(char *startp, char *rmesc, char *rmescend,
6194 char *pattern, int quotes, int match_at_start)
6196 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6197 int try2optimize = match_at_start;
6203 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6204 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6205 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6207 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6208 * and on each iteration they go back two/one char until they reach the beginning.
6209 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6211 /* TODO: document in what other circumstances we are called. */
6213 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6216 const char *s = loc2;
6217 if (match_at_start) {
6221 match = pmatch(pattern, s);
6222 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6226 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6228 /* Maybe we can optimize this:
6229 * if pattern ends with unescaped *, we can avoid checking
6230 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6231 * it wont match truncated "raw_value_of_" strings too.
6233 unsigned plen = strlen(pattern);
6234 /* Does it end with "*"? */
6235 if (plen != 0 && pattern[--plen] == '*') {
6236 /* "xxxx*" is not escaped */
6237 /* "xxx\*" is escaped */
6238 /* "xx\\*" is not escaped */
6239 /* "x\\\*" is escaped */
6241 while (plen != 0 && pattern[--plen] == '\\')
6244 break; /* ends with unescaped "*" */
6252 esc = esclen(startp, loc);
6263 static void varunset(const char *, const char *, const char *, int) NORETURN;
6265 varunset(const char *end, const char *var, const char *umsg, int varflags)
6271 msg = "parameter not set";
6273 if ((unsigned char)*end == CTLENDVAR) {
6274 if (varflags & VSNUL)
6280 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6284 subevalvar(char *p, char *varname, int strloc, int subtype,
6285 int startloc, int varflags, int flag, struct strlist *var_str_list)
6287 struct nodelist *saveargbackq = argbackq;
6288 int quotes = flag & QUOTES_ESC;
6291 char *rmesc, *rmescend;
6293 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6294 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6295 int saveherefd = herefd;
6296 int amount, resetloc;
6297 IF_ASH_BASH_COMPAT(int workloc;)
6299 char *(*scan)(char*, char*, char*, char*, int, int);
6301 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6302 // p, varname, strloc, subtype, startloc, varflags, quotes);
6305 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6306 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6308 STPUTC('\0', expdest);
6309 herefd = saveherefd;
6310 argbackq = saveargbackq;
6311 startp = (char *)stackblock() + startloc;
6315 setvar0(varname, startp);
6316 amount = startp - expdest;
6317 STADJUST(amount, expdest);
6321 varunset(p, varname, startp, varflags);
6324 #if ENABLE_ASH_BASH_COMPAT
6326 loc = str = stackblock() + strloc;
6327 /* Read POS in ${var:POS:LEN} */
6328 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6329 len = str - startp - 1;
6331 /* *loc != '\0', guaranteed by parser */
6335 /* Adjust the length by the number of escapes */
6336 for (ptr = startp; ptr < (str - 1); ptr++) {
6337 if ((unsigned char)*ptr == CTLESC) {
6345 if (*loc++ == ':') {
6349 /* Skip POS in ${var:POS:LEN} */
6351 while (*loc && *loc != ':') {
6353 * bash complains on: var=qwe; echo ${var:1a:123}
6355 ash_msg_and_raise_error(msg_illnum, str);
6359 if (*loc++ == ':') {
6364 /* ${VAR:$((-n)):l} starts n chars from the end */
6365 pos = orig_len + pos;
6367 if ((unsigned)pos >= orig_len) {
6368 /* apart from obvious ${VAR:999999:l},
6369 * covers ${VAR:$((-9999999)):l} - result is ""
6375 if (len > (orig_len - pos))
6376 len = orig_len - pos;
6378 for (str = startp; pos; str++, pos--) {
6379 if (quotes && (unsigned char)*str == CTLESC)
6382 for (loc = startp; len; len--) {
6383 if (quotes && (unsigned char)*str == CTLESC)
6388 amount = loc - expdest;
6389 STADJUST(amount, expdest);
6394 resetloc = expdest - (char *)stackblock();
6396 /* We'll comeback here if we grow the stack while handling
6397 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6398 * stack will need rebasing, and we'll need to remove our work
6401 IF_ASH_BASH_COMPAT(restart:)
6403 amount = expdest - ((char *)stackblock() + resetloc);
6404 STADJUST(-amount, expdest);
6405 startp = (char *)stackblock() + startloc;
6408 rmescend = (char *)stackblock() + strloc;
6410 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6411 if (rmesc != startp) {
6413 startp = (char *)stackblock() + startloc;
6417 str = (char *)stackblock() + strloc;
6419 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6420 * The result is a_\_z_c (not a\_\_z_c)!
6422 * The search pattern and replace string treat backslashes differently!
6423 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6424 * and string. It's only used on the first call.
6426 preglob(str, IF_ASH_BASH_COMPAT(
6427 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6428 RMESCAPE_SLASH :) 0);
6430 #if ENABLE_ASH_BASH_COMPAT
6431 workloc = expdest - (char *)stackblock();
6432 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6436 if ((repl=strchr(str, CTLESC)))
6441 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6443 /* If there's no pattern to match, return the expansion unmolested */
6452 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6453 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6455 /* No match, advance */
6456 char *restart_detect = stackblock();
6458 STPUTC(*idx, expdest);
6459 if (quotes && (unsigned char)*idx == CTLESC) {
6462 STPUTC(*idx, expdest);
6464 if (stackblock() != restart_detect)
6469 /* continue; - prone to quadratic behavior, smarter code: */
6472 if (str[0] == '*') {
6473 /* Pattern is "*foo". If "*foo" does not match "long_string",
6474 * it would never match "ong_string" etc, no point in trying.
6481 if (subtype == VSREPLACEALL) {
6483 if (quotes && (unsigned char)*idx == CTLESC)
6492 //bb_error_msg("repl:'%s'", repl);
6493 for (loc = (char*)repl; *loc; loc++) {
6494 char *restart_detect = stackblock();
6495 if (quotes && *loc == '\\') {
6496 STPUTC(CTLESC, expdest);
6499 STPUTC(*loc, expdest);
6500 if (stackblock() != restart_detect)
6505 if (subtype == VSREPLACE) {
6506 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6508 char *restart_detect = stackblock();
6509 STPUTC(*idx, expdest);
6510 if (stackblock() != restart_detect)
6519 /* We've put the replaced text into a buffer at workloc, now
6520 * move it to the right place and adjust the stack.
6522 STPUTC('\0', expdest);
6523 startp = (char *)stackblock() + startloc;
6524 memmove(startp, (char *)stackblock() + workloc, len + 1);
6525 //bb_error_msg("startp:'%s'", startp);
6526 amount = expdest - (startp + len);
6527 STADJUST(-amount, expdest);
6530 #endif /* ENABLE_ASH_BASH_COMPAT */
6532 subtype -= VSTRIMRIGHT;
6534 if (subtype < 0 || subtype > 7)
6537 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6538 zero = subtype >> 1;
6539 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6540 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6542 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6545 memmove(startp, loc, str - loc);
6546 loc = startp + (str - loc) - 1;
6549 amount = loc - expdest;
6550 STADJUST(amount, expdest);
6556 * Add the value of a specialized variable to the stack string.
6557 * name parameter (examples):
6558 * ash -c 'echo $1' name:'1='
6559 * ash -c 'echo $qwe' name:'qwe='
6560 * ash -c 'echo $$' name:'$='
6561 * ash -c 'echo ${$}' name:'$='
6562 * ash -c 'echo ${$##q}' name:'$=q'
6563 * ash -c 'echo ${#$}' name:'$='
6564 * note: examples with bad shell syntax:
6565 * ash -c 'echo ${#$1}' name:'$=1'
6566 * ash -c 'echo ${#1#}' name:'1=#'
6568 static NOINLINE ssize_t
6569 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6576 int quoted = flags & EXP_QUOTED;
6577 int subtype = varflags & VSTYPE;
6578 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6579 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6580 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6582 sep = quoted ? ((flags & EXP_FULL) << CHAR_BIT) : 0;
6592 num = shellparam.nparam;
6600 goto check_1char_name;
6602 expdest = makestrspace(NOPTS, expdest);
6603 for (i = NOPTS - 1; i >= 0; i--) {
6605 USTPUTC(optletters(i), expdest);
6611 /* handles cases similar to ${#$1} */
6612 if (name[2] != '\0')
6613 raise_error_syntax("bad substitution");
6620 if (quoted && (flags & EXP_FULL)) {
6621 /* note: this is not meant as PEOF value */
6622 sep = 1 << CHAR_BIT;
6627 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6633 while ((p = *ap++) != NULL) {
6634 len += strtodest(p, syntax, quotes);
6638 memtodest(&sepc, 1, syntax, quotes);
6642 } /* case '@' and '*' */
6653 num = atoi(name); /* number(name) fails on ${N#str} etc */
6654 if (num < 0 || num > shellparam.nparam)
6656 p = num ? shellparam.p[num - 1] : arg0;
6659 /* NB: name has form "VAR=..." */
6661 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6662 * which should be considered before we check variables. */
6664 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6668 str = var_str_list->text;
6669 eq = strchr(str, '=');
6670 if (!eq) /* stop at first non-assignment */
6673 if (name_len == (unsigned)(eq - str)
6674 && strncmp(str, name, name_len) == 0
6677 /* goto value; - WRONG! */
6678 /* think "A=1 A=2 B=$A" */
6680 var_str_list = var_str_list->next;
6681 } while (var_str_list);
6685 p = lookupvar(name);
6690 len = strtodest(p, syntax, quotes);
6691 #if ENABLE_UNICODE_SUPPORT
6692 if (subtype == VSLENGTH && len > 0) {
6693 reinit_unicode_for_ash();
6694 if (unicode_status == UNICODE_ON) {
6695 STADJUST(-len, expdest);
6697 len = unicode_strlen(p);
6705 STADJUST(-len, expdest);
6710 * Expand a variable, and return a pointer to the next character in the
6714 evalvar(char *p, int flags, struct strlist *var_str_list)
6725 varflags = (unsigned char) *p++;
6726 subtype = varflags & VSTYPE;
6727 quoted = flags & EXP_QUOTED;
6729 easy = (!quoted || (*var == '@' && shellparam.nparam));
6730 startloc = expdest - (char *)stackblock();
6731 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6734 varlen = varvalue(var, varflags, flags, var_str_list);
6735 if (varflags & VSNUL)
6738 if (subtype == VSPLUS) {
6739 varlen = -1 - varlen;
6743 if (subtype == VSMINUS) {
6748 flags | EXP_TILDE | EXP_WORD,
6758 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6760 if (subevalvar(p, var, /* strloc: */ 0,
6761 subtype, startloc, varflags,
6762 /* quotes: */ flags & ~QUOTES_ESC,
6767 * Remove any recorded regions beyond
6770 removerecordregions(startloc);
6780 if (varlen < 0 && uflag)
6781 varunset(p, var, 0, 0);
6783 if (subtype == VSLENGTH) {
6784 cvtnum(varlen > 0 ? varlen : 0);
6788 if (subtype == VSNORMAL) {
6799 case VSTRIMRIGHTMAX:
6800 #if ENABLE_ASH_BASH_COMPAT
6813 * Terminate the string and start recording the pattern
6816 STPUTC('\0', expdest);
6817 patloc = expdest - (char *)stackblock();
6818 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6819 startloc, varflags, flags, var_str_list)) {
6820 int amount = expdest - (
6821 (char *)stackblock() + patloc - 1
6823 STADJUST(-amount, expdest);
6825 /* Remove any recorded regions beyond start of variable */
6826 removerecordregions(startloc);
6828 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6832 if (subtype != VSNORMAL) { /* skip to end of alternative */
6835 unsigned char c = *p++;
6838 else if (c == CTLBACKQ) {
6840 argbackq = argbackq->next;
6841 } else if (c == CTLVAR) {
6842 if ((*p++ & VSTYPE) != VSNORMAL)
6844 } else if (c == CTLENDVAR) {
6854 * Break the argument string into pieces based upon IFS and add the
6855 * strings to the argument list. The regions of the string to be
6856 * searched for IFS characters have been stored by recordregion.
6859 ifsbreakup(char *string, struct arglist *arglist)
6861 struct ifsregion *ifsp;
6866 const char *ifs, *realifs;
6871 if (ifslastp != NULL) {
6874 realifs = ifsset() ? ifsval() : defifs;
6877 p = string + ifsp->begoff;
6878 nulonly = ifsp->nulonly;
6879 ifs = nulonly ? nullstr : realifs;
6881 while (p < string + ifsp->endoff) {
6883 if ((unsigned char)*p == CTLESC)
6885 if (!strchr(ifs, *p)) {
6890 ifsspc = (strchr(defifs, *p) != NULL);
6891 /* Ignore IFS whitespace at start */
6892 if (q == start && ifsspc) {
6898 sp = stzalloc(sizeof(*sp));
6900 *arglist->lastp = sp;
6901 arglist->lastp = &sp->next;
6905 if (p >= string + ifsp->endoff) {
6909 if ((unsigned char)*p == CTLESC)
6911 if (strchr(ifs, *p) == NULL) {
6915 if (strchr(defifs, *p) == NULL) {
6930 } while (ifsp != NULL);
6939 sp = stzalloc(sizeof(*sp));
6941 *arglist->lastp = sp;
6942 arglist->lastp = &sp->next;
6948 struct ifsregion *p;
6953 struct ifsregion *ifsp;
6959 ifsfirst.next = NULL;
6964 * Add a file name to the list.
6967 addfname(const char *name)
6971 sp = stzalloc(sizeof(*sp));
6972 sp->text = ststrdup(name);
6974 exparg.lastp = &sp->next;
6978 * Do metacharacter (i.e. *, ?, [...]) expansion.
6981 expmeta(char *expdir, char *enddir, char *name)
6997 for (p = name; esc = 0, *p; p += esc + 1) {
6998 if (*p == '*' || *p == '?')
7000 else if (*p == '[') {
7007 if (*q == '/' || *q == '\0')
7017 if (p[esc] == '/') {
7020 start = p + esc + 1;
7024 if (metaflag == 0) { /* we've reached the end of the file name */
7025 if (enddir != expdir)
7033 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7044 } while (p < start);
7046 if (enddir == expdir) {
7048 } else if (enddir == expdir + 1 && *expdir == '/') {
7057 if (enddir != expdir)
7059 if (*endname == 0) {
7072 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7073 if (dp->d_name[0] == '.' && !matchdot)
7075 if (pmatch(start, dp->d_name)) {
7077 strcpy(enddir, dp->d_name);
7080 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7083 expmeta(expdir, p, endname);
7089 endname[-esc - 1] = esc ? '\\' : '/';
7092 static struct strlist *
7093 msort(struct strlist *list, int len)
7095 struct strlist *p, *q = NULL;
7096 struct strlist **lpp;
7104 for (n = half; --n >= 0;) {
7108 q->next = NULL; /* terminate first half of list */
7109 q = msort(list, half); /* sort first half of list */
7110 p = msort(p, len - half); /* sort second half */
7113 #if ENABLE_LOCALE_SUPPORT
7114 if (strcoll(p->text, q->text) < 0)
7116 if (strcmp(p->text, q->text) < 0)
7140 * Sort the results of file name expansion. It calculates the number of
7141 * strings to sort and then calls msort (short for merge sort) to do the
7144 static struct strlist *
7145 expsort(struct strlist *str)
7151 for (sp = str; sp; sp = sp->next)
7153 return msort(str, len);
7157 expandmeta(struct strlist *str /*, int flag*/)
7159 static const char metachars[] ALIGN1 = {
7162 /* TODO - EXP_REDIR */
7166 struct strlist **savelastp;
7172 if (!strpbrk(str->text, metachars))
7174 savelastp = exparg.lastp;
7177 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7179 int i = strlen(str->text);
7180 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7182 expmeta(expdir, expdir, p);
7187 if (exparg.lastp == savelastp) {
7192 *exparg.lastp = str;
7193 rmescapes(str->text, 0);
7194 exparg.lastp = &str->next;
7196 *exparg.lastp = NULL;
7197 *savelastp = sp = expsort(*savelastp);
7198 while (sp->next != NULL)
7200 exparg.lastp = &sp->next;
7207 * Perform variable substitution and command substitution on an argument,
7208 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7209 * perform splitting and file name expansion. When arglist is NULL, perform
7210 * here document expansion.
7213 expandarg(union node *arg, struct arglist *arglist, int flag)
7218 argbackq = arg->narg.backquote;
7219 STARTSTACKSTR(expdest);
7220 ifsfirst.next = NULL;
7222 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7223 argstr(arg->narg.text, flag,
7224 /* var_str_list: */ arglist ? arglist->list : NULL);
7225 p = _STPUTC('\0', expdest);
7227 if (arglist == NULL) {
7228 return; /* here document expanded */
7230 p = grabstackstr(p);
7231 TRACE(("expandarg: p:'%s'\n", p));
7232 exparg.lastp = &exparg.list;
7236 if (flag & EXP_FULL) {
7237 ifsbreakup(p, &exparg);
7238 *exparg.lastp = NULL;
7239 exparg.lastp = &exparg.list;
7240 expandmeta(exparg.list /*, flag*/);
7242 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7244 TRACE(("expandarg: rmescapes:'%s'\n", p));
7246 sp = stzalloc(sizeof(*sp));
7249 exparg.lastp = &sp->next;
7253 *exparg.lastp = NULL;
7255 *arglist->lastp = exparg.list;
7256 arglist->lastp = exparg.lastp;
7261 * Expand shell variables and backquotes inside a here document.
7264 expandhere(union node *arg, int fd)
7267 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7268 full_write(fd, stackblock(), expdest - (char *)stackblock());
7272 * Returns true if the pattern matches the string.
7275 patmatch(char *pattern, const char *string)
7277 return pmatch(preglob(pattern, 0), string);
7281 * See if a pattern matches in a case statement.
7284 casematch(union node *pattern, char *val)
7286 struct stackmark smark;
7289 setstackmark(&smark);
7290 argbackq = pattern->narg.backquote;
7291 STARTSTACKSTR(expdest);
7293 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7294 /* var_str_list: */ NULL);
7295 STACKSTRNUL(expdest);
7296 result = patmatch(stackblock(), val);
7297 popstackmark(&smark);
7302 /* ============ find_command */
7306 int (*builtin)(int, char **) FAST_FUNC;
7307 /* unsigned flags; */
7309 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7310 /* "regular" builtins always take precedence over commands,
7311 * regardless of PATH=....%builtin... position */
7312 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7313 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7316 smallint cmdtype; /* CMDxxx */
7319 /* index >= 0 for commands without path (slashes) */
7320 /* (TODO: what exactly does the value mean? PATH position?) */
7321 /* index == -1 for commands with slashes */
7322 /* index == (-2 - applet_no) for NOFORK applets */
7323 const struct builtincmd *cmd;
7324 struct funcnode *func;
7327 /* values of cmdtype */
7328 #define CMDUNKNOWN -1 /* no entry in table for command */
7329 #define CMDNORMAL 0 /* command is an executable program */
7330 #define CMDFUNCTION 1 /* command is a shell function */
7331 #define CMDBUILTIN 2 /* command is a shell builtin */
7333 /* action to find_command() */
7334 #define DO_ERR 0x01 /* prints errors */
7335 #define DO_ABS 0x02 /* checks absolute paths */
7336 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7337 #define DO_ALTPATH 0x08 /* using alternate path */
7338 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7340 static void find_command(char *, struct cmdentry *, int, const char *);
7343 /* ============ Hashing commands */
7346 * When commands are first encountered, they are entered in a hash table.
7347 * This ensures that a full path search will not have to be done for them
7348 * on each invocation.
7350 * We should investigate converting to a linear search, even though that
7351 * would make the command name "hash" a misnomer.
7355 struct tblentry *next; /* next entry in hash chain */
7356 union param param; /* definition of builtin function */
7357 smallint cmdtype; /* CMDxxx */
7358 char rehash; /* if set, cd done since entry created */
7359 char cmdname[1]; /* name of command */
7362 static struct tblentry **cmdtable;
7363 #define INIT_G_cmdtable() do { \
7364 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7367 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7371 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7373 #if ENABLE_FEATURE_SH_STANDALONE
7374 if (applet_no >= 0) {
7375 if (APPLET_IS_NOEXEC(applet_no)) {
7379 run_applet_no_and_exit(applet_no, argv);
7381 /* re-exec ourselves with the new arguments */
7382 execve(bb_busybox_exec_path, argv, envp);
7383 /* If they called chroot or otherwise made the binary no longer
7384 * executable, fall through */
7391 execve(cmd, argv, envp);
7392 } while (errno == EINTR);
7394 execve(cmd, argv, envp);
7396 if (cmd == (char*) bb_busybox_exec_path) {
7397 /* We already visited ENOEXEC branch below, don't do it again */
7398 //TODO: try execve(initial_argv0_of_shell, argv, envp) before giving up?
7402 if (errno == ENOEXEC) {
7403 /* Run "cmd" as a shell script:
7404 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7405 * "If the execve() function fails with ENOEXEC, the shell
7406 * shall execute a command equivalent to having a shell invoked
7407 * with the command name as its first operand,
7408 * with any remaining arguments passed to the new shell"
7410 * That is, do not use $SHELL, user's shell, or /bin/sh;
7411 * just call ourselves.
7413 * Note that bash reads ~80 chars of the file, and if it sees
7414 * a zero byte before it sees newline, it doesn't try to
7415 * interpret it, but fails with "cannot execute binary file"
7416 * message and exit code 126. For one, this prevents attempts
7417 * to interpret foreign ELF binaries as shell scripts.
7422 for (ap = argv; *ap; ap++)
7424 new = ckmalloc((ap - argv + 2) * sizeof(new[0]));
7425 new[0] = (char*) "ash";
7428 while ((*ap++ = *++argv) != NULL)
7430 cmd = (char*) bb_busybox_exec_path;
7437 * Exec a program. Never returns. If you change this routine, you may
7438 * have to change the find_command routine as well.
7440 static void shellexec(char **, const char *, int) NORETURN;
7442 shellexec(char **argv, const char *path, int idx)
7448 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7450 clearredir(/*drop:*/ 1);
7451 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7452 if (strchr(argv[0], '/') != NULL
7453 #if ENABLE_FEATURE_SH_STANDALONE
7454 || (applet_no = find_applet_by_name(argv[0])) >= 0
7457 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7458 if (applet_no >= 0) {
7459 /* We tried execing ourself, but it didn't work.
7460 * Maybe /proc/self/exe doesn't exist?
7469 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7470 if (--idx < 0 && pathopt == NULL) {
7471 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7472 if (errno != ENOENT && errno != ENOTDIR)
7479 /* Map to POSIX errors */
7491 exitstatus = exerrno;
7492 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7493 argv[0], e, suppress_int));
7494 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7499 printentry(struct tblentry *cmdp)
7505 idx = cmdp->param.index;
7508 name = path_advance(&path, cmdp->cmdname);
7510 } while (--idx >= 0);
7511 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7515 * Clear out command entries. The argument specifies the first entry in
7516 * PATH which has changed.
7519 clearcmdentry(int firstchange)
7521 struct tblentry **tblp;
7522 struct tblentry **pp;
7523 struct tblentry *cmdp;
7526 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7528 while ((cmdp = *pp) != NULL) {
7529 if ((cmdp->cmdtype == CMDNORMAL &&
7530 cmdp->param.index >= firstchange)
7531 || (cmdp->cmdtype == CMDBUILTIN &&
7532 builtinloc >= firstchange)
7545 * Locate a command in the command hash table. If "add" is nonzero,
7546 * add the command to the table if it is not already present. The
7547 * variable "lastcmdentry" is set to point to the address of the link
7548 * pointing to the entry, so that delete_cmd_entry can delete the
7551 * Interrupts must be off if called with add != 0.
7553 static struct tblentry **lastcmdentry;
7555 static struct tblentry *
7556 cmdlookup(const char *name, int add)
7558 unsigned int hashval;
7560 struct tblentry *cmdp;
7561 struct tblentry **pp;
7564 hashval = (unsigned char)*p << 4;
7566 hashval += (unsigned char)*p++;
7568 pp = &cmdtable[hashval % CMDTABLESIZE];
7569 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7570 if (strcmp(cmdp->cmdname, name) == 0)
7574 if (add && cmdp == NULL) {
7575 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7577 /* + 1 - already done because
7578 * tblentry::cmdname is char[1] */);
7579 /*cmdp->next = NULL; - ckzalloc did it */
7580 cmdp->cmdtype = CMDUNKNOWN;
7581 strcpy(cmdp->cmdname, name);
7588 * Delete the command entry returned on the last lookup.
7591 delete_cmd_entry(void)
7593 struct tblentry *cmdp;
7596 cmdp = *lastcmdentry;
7597 *lastcmdentry = cmdp->next;
7598 if (cmdp->cmdtype == CMDFUNCTION)
7599 freefunc(cmdp->param.func);
7605 * Add a new command entry, replacing any existing command entry for
7606 * the same name - except special builtins.
7609 addcmdentry(char *name, struct cmdentry *entry)
7611 struct tblentry *cmdp;
7613 cmdp = cmdlookup(name, 1);
7614 if (cmdp->cmdtype == CMDFUNCTION) {
7615 freefunc(cmdp->param.func);
7617 cmdp->cmdtype = entry->cmdtype;
7618 cmdp->param = entry->u;
7622 static int FAST_FUNC
7623 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7625 struct tblentry **pp;
7626 struct tblentry *cmdp;
7628 struct cmdentry entry;
7631 if (nextopt("r") != '\0') {
7636 if (*argptr == NULL) {
7637 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7638 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7639 if (cmdp->cmdtype == CMDNORMAL)
7647 while ((name = *argptr) != NULL) {
7648 cmdp = cmdlookup(name, 0);
7650 && (cmdp->cmdtype == CMDNORMAL
7651 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7655 find_command(name, &entry, DO_ERR, pathval());
7656 if (entry.cmdtype == CMDUNKNOWN)
7664 * Called when a cd is done. Marks all commands so the next time they
7665 * are executed they will be rehashed.
7670 struct tblentry **pp;
7671 struct tblentry *cmdp;
7673 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7674 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7675 if (cmdp->cmdtype == CMDNORMAL
7676 || (cmdp->cmdtype == CMDBUILTIN
7677 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7687 * Fix command hash table when PATH changed.
7688 * Called before PATH is changed. The argument is the new value of PATH;
7689 * pathval() still returns the old value at this point.
7690 * Called with interrupts off.
7692 static void FAST_FUNC
7693 changepath(const char *new)
7701 firstchange = 9999; /* assume no change */
7707 if ((*old == '\0' && *new == ':')
7708 || (*old == ':' && *new == '\0')
7712 old = new; /* ignore subsequent differences */
7716 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7723 if (builtinloc < 0 && idx_bltin >= 0)
7724 builtinloc = idx_bltin; /* zap builtins */
7725 if (builtinloc >= 0 && idx_bltin < 0)
7727 clearcmdentry(firstchange);
7728 builtinloc = idx_bltin;
7753 #if ENABLE_ASH_BASH_COMPAT
7764 typedef smallint token_id_t;
7766 /* first char is indicating which tokens mark the end of a list */
7767 static const char *const tokname_array[] = {
7781 #define KWDOFFSET 13
7782 /* the following are keywords */
7792 #if ENABLE_ASH_BASH_COMPAT
7804 /* Wrapper around strcmp for qsort/bsearch/... */
7806 pstrcmp(const void *a, const void *b)
7808 return strcmp((char*) a, (*(char**) b) + 1);
7811 static const char *const *
7812 findkwd(const char *s)
7814 return bsearch(s, tokname_array + KWDOFFSET,
7815 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7816 sizeof(tokname_array[0]), pstrcmp);
7820 * Locate and print what a word is...
7823 describe_command(char *command, const char *path, int describe_command_verbose)
7825 struct cmdentry entry;
7826 struct tblentry *cmdp;
7827 #if ENABLE_ASH_ALIAS
7828 const struct alias *ap;
7831 path = path ? path : pathval();
7833 if (describe_command_verbose) {
7837 /* First look at the keywords */
7838 if (findkwd(command)) {
7839 out1str(describe_command_verbose ? " is a shell keyword" : command);
7843 #if ENABLE_ASH_ALIAS
7844 /* Then look at the aliases */
7845 ap = lookupalias(command, 0);
7847 if (!describe_command_verbose) {
7852 out1fmt(" is an alias for %s", ap->val);
7856 /* Then check if it is a tracked alias */
7857 cmdp = cmdlookup(command, 0);
7859 entry.cmdtype = cmdp->cmdtype;
7860 entry.u = cmdp->param;
7862 /* Finally use brute force */
7863 find_command(command, &entry, DO_ABS, path);
7866 switch (entry.cmdtype) {
7868 int j = entry.u.index;
7874 p = path_advance(&path, command);
7878 if (describe_command_verbose) {
7880 (cmdp ? " a tracked alias for" : nullstr), p
7889 if (describe_command_verbose) {
7890 out1str(" is a shell function");
7897 if (describe_command_verbose) {
7898 out1fmt(" is a %sshell builtin",
7899 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7900 "special " : nullstr
7908 if (describe_command_verbose) {
7909 out1str(": not found\n");
7918 static int FAST_FUNC
7919 typecmd(int argc UNUSED_PARAM, char **argv)
7925 /* type -p ... ? (we don't bother checking for 'p') */
7926 if (argv[1] && argv[1][0] == '-') {
7931 err |= describe_command(argv[i++], NULL, verbose);
7936 #if ENABLE_ASH_CMDCMD
7937 static int FAST_FUNC
7938 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7945 const char *path = NULL;
7947 while ((c = nextopt("pvV")) != '\0')
7949 verify |= VERIFY_VERBOSE;
7951 verify |= VERIFY_BRIEF;
7957 path = bb_default_path;
7958 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7959 if (verify && (*argptr != NULL)) {
7960 return describe_command(*argptr, path, verify - VERIFY_BRIEF);
7968 /* ============ eval.c */
7970 static int funcblocksize; /* size of structures in function */
7971 static int funcstringsize; /* size of strings in node */
7972 static void *funcblock; /* block to allocate function from */
7973 static char *funcstring; /* block to allocate strings from */
7975 /* flags in argument to evaltree */
7976 #define EV_EXIT 01 /* exit after evaluating tree */
7977 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7978 #define EV_BACKCMD 04 /* command executing within back quotes */
7980 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
7981 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7982 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7983 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7984 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7985 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7986 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7987 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7988 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7989 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7990 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7991 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7992 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7993 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7994 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7995 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7996 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7997 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7998 #if ENABLE_ASH_BASH_COMPAT
7999 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8001 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8002 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8003 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8004 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8005 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8006 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8007 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8008 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8009 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8012 static void calcsize(union node *n);
8015 sizenodelist(struct nodelist *lp)
8018 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8025 calcsize(union node *n)
8029 funcblocksize += nodesize[n->type];
8032 calcsize(n->ncmd.redirect);
8033 calcsize(n->ncmd.args);
8034 calcsize(n->ncmd.assign);
8037 sizenodelist(n->npipe.cmdlist);
8042 calcsize(n->nredir.redirect);
8043 calcsize(n->nredir.n);
8050 calcsize(n->nbinary.ch2);
8051 calcsize(n->nbinary.ch1);
8054 calcsize(n->nif.elsepart);
8055 calcsize(n->nif.ifpart);
8056 calcsize(n->nif.test);
8059 funcstringsize += strlen(n->nfor.var) + 1;
8060 calcsize(n->nfor.body);
8061 calcsize(n->nfor.args);
8064 calcsize(n->ncase.cases);
8065 calcsize(n->ncase.expr);
8068 calcsize(n->nclist.body);
8069 calcsize(n->nclist.pattern);
8070 calcsize(n->nclist.next);
8074 sizenodelist(n->narg.backquote);
8075 funcstringsize += strlen(n->narg.text) + 1;
8076 calcsize(n->narg.next);
8079 #if ENABLE_ASH_BASH_COMPAT
8086 calcsize(n->nfile.fname);
8087 calcsize(n->nfile.next);
8091 calcsize(n->ndup.vname);
8092 calcsize(n->ndup.next);
8096 calcsize(n->nhere.doc);
8097 calcsize(n->nhere.next);
8100 calcsize(n->nnot.com);
8106 nodeckstrdup(char *s)
8108 char *rtn = funcstring;
8110 strcpy(funcstring, s);
8111 funcstring += strlen(s) + 1;
8115 static union node *copynode(union node *);
8117 static struct nodelist *
8118 copynodelist(struct nodelist *lp)
8120 struct nodelist *start;
8121 struct nodelist **lpp;
8126 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8127 (*lpp)->n = copynode(lp->n);
8129 lpp = &(*lpp)->next;
8136 copynode(union node *n)
8143 funcblock = (char *) funcblock + nodesize[n->type];
8147 new->ncmd.redirect = copynode(n->ncmd.redirect);
8148 new->ncmd.args = copynode(n->ncmd.args);
8149 new->ncmd.assign = copynode(n->ncmd.assign);
8152 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8153 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8158 new->nredir.redirect = copynode(n->nredir.redirect);
8159 new->nredir.n = copynode(n->nredir.n);
8166 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8167 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8170 new->nif.elsepart = copynode(n->nif.elsepart);
8171 new->nif.ifpart = copynode(n->nif.ifpart);
8172 new->nif.test = copynode(n->nif.test);
8175 new->nfor.var = nodeckstrdup(n->nfor.var);
8176 new->nfor.body = copynode(n->nfor.body);
8177 new->nfor.args = copynode(n->nfor.args);
8180 new->ncase.cases = copynode(n->ncase.cases);
8181 new->ncase.expr = copynode(n->ncase.expr);
8184 new->nclist.body = copynode(n->nclist.body);
8185 new->nclist.pattern = copynode(n->nclist.pattern);
8186 new->nclist.next = copynode(n->nclist.next);
8190 new->narg.backquote = copynodelist(n->narg.backquote);
8191 new->narg.text = nodeckstrdup(n->narg.text);
8192 new->narg.next = copynode(n->narg.next);
8195 #if ENABLE_ASH_BASH_COMPAT
8202 new->nfile.fname = copynode(n->nfile.fname);
8203 new->nfile.fd = n->nfile.fd;
8204 new->nfile.next = copynode(n->nfile.next);
8208 new->ndup.vname = copynode(n->ndup.vname);
8209 new->ndup.dupfd = n->ndup.dupfd;
8210 new->ndup.fd = n->ndup.fd;
8211 new->ndup.next = copynode(n->ndup.next);
8215 new->nhere.doc = copynode(n->nhere.doc);
8216 new->nhere.fd = n->nhere.fd;
8217 new->nhere.next = copynode(n->nhere.next);
8220 new->nnot.com = copynode(n->nnot.com);
8223 new->type = n->type;
8228 * Make a copy of a parse tree.
8230 static struct funcnode *
8231 copyfunc(union node *n)
8236 funcblocksize = offsetof(struct funcnode, n);
8239 blocksize = funcblocksize;
8240 f = ckmalloc(blocksize + funcstringsize);
8241 funcblock = (char *) f + offsetof(struct funcnode, n);
8242 funcstring = (char *) f + blocksize;
8249 * Define a shell function.
8252 defun(char *name, union node *func)
8254 struct cmdentry entry;
8257 entry.cmdtype = CMDFUNCTION;
8258 entry.u.func = copyfunc(func);
8259 addcmdentry(name, &entry);
8263 /* Reasons for skipping commands (see comment on breakcmd routine) */
8264 #define SKIPBREAK (1 << 0)
8265 #define SKIPCONT (1 << 1)
8266 #define SKIPFUNC (1 << 2)
8267 #define SKIPFILE (1 << 3)
8268 #define SKIPEVAL (1 << 4)
8269 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8270 static int skipcount; /* number of levels to skip */
8271 static int funcnest; /* depth of function calls */
8272 static int loopnest; /* current loop nesting level */
8274 /* Forward decl way out to parsing code - dotrap needs it */
8275 static int evalstring(char *s, int mask);
8277 /* Called to execute a trap.
8278 * Single callsite - at the end of evaltree().
8279 * If we return non-zero, evaltree raises EXEXIT exception.
8281 * Perhaps we should avoid entering new trap handlers
8282 * while we are executing a trap handler. [is it a TODO?]
8291 savestatus = exitstatus;
8295 TRACE(("dotrap entered\n"));
8296 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8303 /* non-trapped SIGINT is handled separately by raise_interrupt,
8304 * don't upset it by resetting gotsig[SIGINT-1] */
8305 if (sig == SIGINT && !t)
8308 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8312 want_exexit = evalstring(t, SKIPEVAL);
8313 exitstatus = savestatus;
8315 TRACE(("dotrap returns %d\n", want_exexit));
8320 TRACE(("dotrap returns 0\n"));
8324 /* forward declarations - evaluation is fairly recursive business... */
8325 static void evalloop(union node *, int);
8326 static void evalfor(union node *, int);
8327 static void evalcase(union node *, int);
8328 static void evalsubshell(union node *, int);
8329 static void expredir(union node *);
8330 static void evalpipe(union node *, int);
8331 static void evalcommand(union node *, int);
8332 static int evalbltin(const struct builtincmd *, int, char **);
8333 static void prehash(union node *);
8336 * Evaluate a parse tree. The value is left in the global variable
8340 evaltree(union node *n, int flags)
8342 struct jmploc *volatile savehandler = exception_handler;
8343 struct jmploc jmploc;
8345 void (*evalfn)(union node *, int);
8349 SAVE_INT(int_level);
8352 TRACE(("evaltree(NULL) called\n"));
8355 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8357 exception_handler = &jmploc;
8359 int err = setjmp(jmploc.loc);
8361 /* if it was a signal, check for trap handlers */
8362 if (exception_type == EXSIG) {
8363 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8364 exception_type, err));
8367 /* continue on the way out */
8368 TRACE(("exception %d in evaltree, propagating err=%d\n",
8369 exception_type, err));
8370 exception_handler = savehandler;
8371 longjmp(exception_handler->loc, err);
8378 out1fmt("Node type = %d\n", n->type);
8383 evaltree(n->nnot.com, EV_TESTED);
8384 status = !exitstatus;
8387 expredir(n->nredir.redirect);
8388 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8390 evaltree(n->nredir.n, flags & EV_TESTED);
8391 status = exitstatus;
8393 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8396 evalfn = evalcommand;
8398 if (eflag && !(flags & EV_TESTED))
8410 evalfn = evalsubshell;
8423 #error NAND + 1 != NOR
8425 #if NOR + 1 != NSEMI
8426 #error NOR + 1 != NSEMI
8428 unsigned is_or = n->type - NAND;
8431 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8433 if ((!exitstatus) == is_or)
8446 evaltree(n->nif.test, EV_TESTED);
8449 if (exitstatus == 0) {
8453 if (n->nif.elsepart) {
8454 n = n->nif.elsepart;
8459 defun(n->narg.text, n->narg.next);
8463 exitstatus = status;
8468 exception_handler = savehandler;
8471 /* Order of checks below is important:
8472 * signal handlers trigger before exit caused by "set -e".
8474 if (pending_sig && dotrap())
8476 if (checkexit & exitstatus)
8477 evalskip |= SKIPEVAL;
8479 if (flags & EV_EXIT) {
8481 raise_exception(EXEXIT);
8484 RESTORE_INT(int_level);
8485 TRACE(("leaving evaltree (no interrupts)\n"));
8488 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8491 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8494 evalloop(union node *n, int flags)
8504 evaltree(n->nbinary.ch1, EV_TESTED);
8507 if (evalskip == SKIPCONT && --skipcount <= 0) {
8511 if (evalskip == SKIPBREAK && --skipcount <= 0)
8516 if (n->type != NWHILE)
8520 evaltree(n->nbinary.ch2, flags);
8521 status = exitstatus;
8526 exitstatus = status;
8530 evalfor(union node *n, int flags)
8532 struct arglist arglist;
8535 struct stackmark smark;
8537 setstackmark(&smark);
8538 arglist.list = NULL;
8539 arglist.lastp = &arglist.list;
8540 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8541 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8546 *arglist.lastp = NULL;
8551 for (sp = arglist.list; sp; sp = sp->next) {
8552 setvar0(n->nfor.var, sp->text);
8553 evaltree(n->nfor.body, flags);
8555 if (evalskip == SKIPCONT && --skipcount <= 0) {
8559 if (evalskip == SKIPBREAK && --skipcount <= 0)
8566 popstackmark(&smark);
8570 evalcase(union node *n, int flags)
8574 struct arglist arglist;
8575 struct stackmark smark;
8577 setstackmark(&smark);
8578 arglist.list = NULL;
8579 arglist.lastp = &arglist.list;
8580 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8582 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8583 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8584 if (casematch(patp, arglist.list->text)) {
8585 if (evalskip == 0) {
8586 evaltree(cp->nclist.body, flags);
8593 popstackmark(&smark);
8597 * Kick off a subshell to evaluate a tree.
8600 evalsubshell(union node *n, int flags)
8603 int backgnd = (n->type == NBACKGND);
8606 expredir(n->nredir.redirect);
8607 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8610 jp = makejob(/*n,*/ 1);
8611 if (forkshell(jp, n, backgnd) == 0) {
8616 flags &= ~EV_TESTED;
8618 redirect(n->nredir.redirect, 0);
8619 evaltreenr(n->nredir.n, flags);
8624 status = waitforjob(jp);
8625 exitstatus = status;
8630 * Compute the names of the files in a redirection list.
8632 static void fixredir(union node *, const char *, int);
8634 expredir(union node *n)
8638 for (redir = n; redir; redir = redir->nfile.next) {
8642 fn.lastp = &fn.list;
8643 switch (redir->type) {
8647 #if ENABLE_ASH_BASH_COMPAT
8652 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8653 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8654 #if ENABLE_ASH_BASH_COMPAT
8658 // By the design of stack allocator, the loop of this kind:
8659 // while true; do while true; do break; done </dev/null; done
8660 // will look like a memory leak: ash plans to free expfname's
8661 // of "/dev/null" as soon as it finishes running the loop
8662 // (in this case, never).
8663 // This "fix" is wrong:
8664 if (redir->nfile.expfname)
8665 stunalloc(redir->nfile.expfname);
8666 // It results in corrupted state of stacked allocations.
8668 redir->nfile.expfname = fn.list->text;
8671 case NTOFD: /* >& */
8672 if (redir->ndup.vname) {
8673 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8674 if (fn.list == NULL)
8675 ash_msg_and_raise_error("redir error");
8676 #if ENABLE_ASH_BASH_COMPAT
8677 //FIXME: we used expandarg with different args!
8678 if (!isdigit_str9(fn.list->text)) {
8679 /* >&file, not >&fd */
8680 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8681 ash_msg_and_raise_error("redir error");
8683 goto store_expfname;
8686 fixredir(redir, fn.list->text, 1);
8694 * Evaluate a pipeline. All the processes in the pipeline are children
8695 * of the process creating the pipeline. (This differs from some versions
8696 * of the shell, which make the last process in a pipeline the parent
8700 evalpipe(union node *n, int flags)
8703 struct nodelist *lp;
8708 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8710 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8714 jp = makejob(/*n,*/ pipelen);
8716 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8720 if (pipe(pip) < 0) {
8722 ash_msg_and_raise_error("pipe call failed");
8725 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8738 evaltreenr(lp->n, flags);
8744 /* Don't want to trigger debugging */
8748 if (n->npipe.pipe_backgnd == 0) {
8749 exitstatus = waitforjob(jp);
8750 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8756 * Controls whether the shell is interactive or not.
8759 setinteractive(int on)
8761 static smallint is_interactive;
8763 if (++on == is_interactive)
8765 is_interactive = on;
8769 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8770 if (is_interactive > 1) {
8771 /* Looks like they want an interactive shell */
8772 static smallint did_banner;
8775 /* note: ash and hush share this string */
8776 out1fmt("\n\n%s %s\n"
8777 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
8780 "built-in shell (ash)"
8794 setinteractive(iflag);
8796 #if ENABLE_FEATURE_EDITING_VI
8798 line_input_state->flags |= VI_MODE;
8800 line_input_state->flags &= ~VI_MODE;
8802 viflag = 0; /* forcibly keep the option off */
8806 static struct localvar *localvars;
8809 * Called after a function returns.
8810 * Interrupts must be off.
8815 struct localvar *lvp;
8818 while ((lvp = localvars) != NULL) {
8819 localvars = lvp->next;
8821 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
8822 if (vp == NULL) { /* $- saved */
8823 memcpy(optlist, lvp->text, sizeof(optlist));
8824 free((char*)lvp->text);
8826 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8827 unsetvar(vp->var_text);
8830 vp->var_func(var_end(lvp->text));
8831 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8832 free((char*)vp->var_text);
8833 vp->flags = lvp->flags;
8834 vp->var_text = lvp->text;
8841 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8843 volatile struct shparam saveparam;
8844 struct localvar *volatile savelocalvars;
8845 struct jmploc *volatile savehandler;
8846 struct jmploc jmploc;
8849 saveparam = shellparam;
8850 savelocalvars = localvars;
8851 e = setjmp(jmploc.loc);
8856 savehandler = exception_handler;
8857 exception_handler = &jmploc;
8859 shellparam.malloced = 0;
8863 shellparam.nparam = argc - 1;
8864 shellparam.p = argv + 1;
8865 #if ENABLE_ASH_GETOPTS
8866 shellparam.optind = 1;
8867 shellparam.optoff = -1;
8869 evaltree(&func->n, flags & EV_TESTED);
8875 localvars = savelocalvars;
8876 freeparam(&shellparam);
8877 shellparam = saveparam;
8878 exception_handler = savehandler;
8880 evalskip &= ~SKIPFUNC;
8884 #if ENABLE_ASH_CMDCMD
8886 parse_command_args(char **argv, const char **path)
8899 if (c == '-' && !*cp) {
8907 *path = bb_default_path;
8910 /* run 'typecmd' for other options */
8921 * Make a variable a local variable. When a variable is made local, it's
8922 * value and flags are saved in a localvar structure. The saved values
8923 * will be restored when the shell function returns. We handle the name
8924 * "-" as a special case: it makes changes to "set +-options" local
8925 * (options will be restored on return from the function).
8930 struct localvar *lvp;
8933 char *eq = strchr(name, '=');
8936 /* Cater for duplicate "local". Examples:
8937 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
8938 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
8942 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
8946 * it's a duplicate "local VAR" declaration, do nothing
8953 lvp = ckzalloc(sizeof(*lvp));
8954 if (LONE_DASH(name)) {
8956 p = ckmalloc(sizeof(optlist));
8957 lvp->text = memcpy(p, optlist, sizeof(optlist));
8960 vpp = hashvar(name);
8961 vp = *findvar(vpp, name);
8963 /* variable did not exist yet */
8965 setvareq(name, VSTRFIXED);
8967 setvar(name, NULL, VSTRFIXED);
8968 vp = *vpp; /* the new variable */
8969 lvp->flags = VUNSET;
8971 lvp->text = vp->var_text;
8972 lvp->flags = vp->flags;
8973 /* make sure neither "struct var" nor string gets freed
8974 * during (un)setting:
8976 vp->flags |= VSTRFIXED|VTEXTFIXED;
8980 /* "local VAR" unsets VAR: */
8981 setvar0(name, NULL);
8985 lvp->next = localvars;
8991 * The "local" command.
8993 static int FAST_FUNC
8994 localcmd(int argc UNUSED_PARAM, char **argv)
8999 ash_msg_and_raise_error("not in a function");
9002 while ((name = *argv++) != NULL) {
9008 static int FAST_FUNC
9009 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9014 static int FAST_FUNC
9015 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9020 static int FAST_FUNC
9021 execcmd(int argc UNUSED_PARAM, char **argv)
9024 iflag = 0; /* exit on error */
9027 shellexec(argv + 1, pathval(), 0);
9033 * The return command.
9035 static int FAST_FUNC
9036 returncmd(int argc UNUSED_PARAM, char **argv)
9039 * If called outside a function, do what ksh does;
9040 * skip the rest of the file.
9042 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
9043 return argv[1] ? number(argv[1]) : exitstatus;
9046 /* Forward declarations for builtintab[] */
9047 static int breakcmd(int, char **) FAST_FUNC;
9048 static int dotcmd(int, char **) FAST_FUNC;
9049 static int evalcmd(int, char **) FAST_FUNC;
9050 static int exitcmd(int, char **) FAST_FUNC;
9051 static int exportcmd(int, char **) FAST_FUNC;
9052 #if ENABLE_ASH_GETOPTS
9053 static int getoptscmd(int, char **) FAST_FUNC;
9056 static int helpcmd(int, char **) FAST_FUNC;
9059 static int historycmd(int, char **) FAST_FUNC;
9061 #if ENABLE_SH_MATH_SUPPORT
9062 static int letcmd(int, char **) FAST_FUNC;
9064 static int readcmd(int, char **) FAST_FUNC;
9065 static int setcmd(int, char **) FAST_FUNC;
9066 static int shiftcmd(int, char **) FAST_FUNC;
9067 static int timescmd(int, char **) FAST_FUNC;
9068 static int trapcmd(int, char **) FAST_FUNC;
9069 static int umaskcmd(int, char **) FAST_FUNC;
9070 static int unsetcmd(int, char **) FAST_FUNC;
9071 static int ulimitcmd(int, char **) FAST_FUNC;
9073 #define BUILTIN_NOSPEC "0"
9074 #define BUILTIN_SPECIAL "1"
9075 #define BUILTIN_REGULAR "2"
9076 #define BUILTIN_SPEC_REG "3"
9077 #define BUILTIN_ASSIGN "4"
9078 #define BUILTIN_SPEC_ASSG "5"
9079 #define BUILTIN_REG_ASSG "6"
9080 #define BUILTIN_SPEC_REG_ASSG "7"
9082 /* Stubs for calling non-FAST_FUNC's */
9083 #if ENABLE_ASH_BUILTIN_ECHO
9084 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9086 #if ENABLE_ASH_BUILTIN_PRINTF
9087 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9089 #if ENABLE_ASH_BUILTIN_TEST
9090 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9093 /* Keep these in proper order since it is searched via bsearch() */
9094 static const struct builtincmd builtintab[] = {
9095 { BUILTIN_SPEC_REG "." , dotcmd },
9096 { BUILTIN_SPEC_REG ":" , truecmd },
9097 #if ENABLE_ASH_BUILTIN_TEST
9098 { BUILTIN_REGULAR "[" , testcmd },
9099 #if ENABLE_ASH_BASH_COMPAT
9100 { BUILTIN_REGULAR "[[" , testcmd },
9103 #if ENABLE_ASH_ALIAS
9104 { BUILTIN_REG_ASSG "alias" , aliascmd },
9107 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9109 { BUILTIN_SPEC_REG "break" , breakcmd },
9110 { BUILTIN_REGULAR "cd" , cdcmd },
9111 { BUILTIN_NOSPEC "chdir" , cdcmd },
9112 #if ENABLE_ASH_CMDCMD
9113 { BUILTIN_REGULAR "command" , commandcmd },
9115 { BUILTIN_SPEC_REG "continue", breakcmd },
9116 #if ENABLE_ASH_BUILTIN_ECHO
9117 { BUILTIN_REGULAR "echo" , echocmd },
9119 { BUILTIN_SPEC_REG "eval" , evalcmd },
9120 { BUILTIN_SPEC_REG "exec" , execcmd },
9121 { BUILTIN_SPEC_REG "exit" , exitcmd },
9122 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9123 { BUILTIN_REGULAR "false" , falsecmd },
9125 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9127 #if ENABLE_ASH_GETOPTS
9128 { BUILTIN_REGULAR "getopts" , getoptscmd },
9130 { BUILTIN_NOSPEC "hash" , hashcmd },
9132 { BUILTIN_NOSPEC "help" , helpcmd },
9135 { BUILTIN_NOSPEC "history" , historycmd },
9138 { BUILTIN_REGULAR "jobs" , jobscmd },
9139 { BUILTIN_REGULAR "kill" , killcmd },
9141 #if ENABLE_SH_MATH_SUPPORT
9142 { BUILTIN_NOSPEC "let" , letcmd },
9144 { BUILTIN_ASSIGN "local" , localcmd },
9145 #if ENABLE_ASH_BUILTIN_PRINTF
9146 { BUILTIN_REGULAR "printf" , printfcmd },
9148 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9149 { BUILTIN_REGULAR "read" , readcmd },
9150 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9151 { BUILTIN_SPEC_REG "return" , returncmd },
9152 { BUILTIN_SPEC_REG "set" , setcmd },
9153 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9154 #if ENABLE_ASH_BASH_COMPAT
9155 { BUILTIN_SPEC_REG "source" , dotcmd },
9157 #if ENABLE_ASH_BUILTIN_TEST
9158 { BUILTIN_REGULAR "test" , testcmd },
9160 { BUILTIN_SPEC_REG "times" , timescmd },
9161 { BUILTIN_SPEC_REG "trap" , trapcmd },
9162 { BUILTIN_REGULAR "true" , truecmd },
9163 { BUILTIN_NOSPEC "type" , typecmd },
9164 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9165 { BUILTIN_REGULAR "umask" , umaskcmd },
9166 #if ENABLE_ASH_ALIAS
9167 { BUILTIN_REGULAR "unalias" , unaliascmd },
9169 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9170 { BUILTIN_REGULAR "wait" , waitcmd },
9173 /* Should match the above table! */
9174 #define COMMANDCMD (builtintab + \
9176 1 * ENABLE_ASH_BUILTIN_TEST + \
9177 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9178 1 * ENABLE_ASH_ALIAS + \
9179 1 * ENABLE_ASH_JOB_CONTROL + \
9181 #define EXECCMD (builtintab + \
9183 1 * ENABLE_ASH_BUILTIN_TEST + \
9184 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9185 1 * ENABLE_ASH_ALIAS + \
9186 1 * ENABLE_ASH_JOB_CONTROL + \
9188 1 * ENABLE_ASH_CMDCMD + \
9190 ENABLE_ASH_BUILTIN_ECHO + \
9194 * Search the table of builtin commands.
9196 static struct builtincmd *
9197 find_builtin(const char *name)
9199 struct builtincmd *bp;
9202 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9209 * Execute a simple command.
9212 isassignment(const char *p)
9214 const char *q = endofname(p);
9219 static int FAST_FUNC
9220 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9222 /* Preserve exitstatus of a previous possible redirection
9223 * as POSIX mandates */
9224 return back_exitstatus;
9227 evalcommand(union node *cmd, int flags)
9229 static const struct builtincmd null_bltin = {
9230 "\0\0", bltincmd /* why three NULs? */
9232 struct stackmark smark;
9234 struct arglist arglist;
9235 struct arglist varlist;
9238 const struct strlist *sp;
9239 struct cmdentry cmdentry;
9246 struct builtincmd *bcmd;
9247 smallint cmd_is_exec;
9248 smallint pseudovarflag = 0;
9250 /* First expand the arguments. */
9251 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9252 setstackmark(&smark);
9253 back_exitstatus = 0;
9255 cmdentry.cmdtype = CMDBUILTIN;
9256 cmdentry.u.cmd = &null_bltin;
9257 varlist.lastp = &varlist.list;
9258 *varlist.lastp = NULL;
9259 arglist.lastp = &arglist.list;
9260 *arglist.lastp = NULL;
9263 if (cmd->ncmd.args) {
9264 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9265 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9268 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9269 struct strlist **spp;
9271 spp = arglist.lastp;
9272 if (pseudovarflag && isassignment(argp->narg.text))
9273 expandarg(argp, &arglist, EXP_VARTILDE);
9275 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9277 for (sp = *spp; sp; sp = sp->next)
9281 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9282 for (sp = arglist.list; sp; sp = sp->next) {
9283 TRACE(("evalcommand arg: %s\n", sp->text));
9284 *nargv++ = sp->text;
9289 if (iflag && funcnest == 0 && argc > 0)
9290 lastarg = nargv[-1];
9293 expredir(cmd->ncmd.redirect);
9294 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9296 path = vpath.var_text;
9297 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9298 struct strlist **spp;
9301 spp = varlist.lastp;
9302 expandarg(argp, &varlist, EXP_VARTILDE);
9305 * Modify the command lookup path, if a PATH= assignment
9309 if (varcmp(p, path) == 0)
9313 /* Print the command if xflag is set. */
9316 const char *p = " %s" + 1;
9318 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9320 for (n = 0; n < 2; n++) {
9322 fdprintf(preverrout_fd, p, sp->text);
9328 safe_write(preverrout_fd, "\n", 1);
9334 /* Now locate the command. */
9336 int cmd_flag = DO_ERR;
9337 #if ENABLE_ASH_CMDCMD
9338 const char *oldpath = path + 5;
9342 find_command(argv[0], &cmdentry, cmd_flag, path);
9343 if (cmdentry.cmdtype == CMDUNKNOWN) {
9344 flush_stdout_stderr();
9349 /* implement bltin and command here */
9350 if (cmdentry.cmdtype != CMDBUILTIN)
9353 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9354 if (cmdentry.u.cmd == EXECCMD)
9356 #if ENABLE_ASH_CMDCMD
9357 if (cmdentry.u.cmd == COMMANDCMD) {
9359 nargv = parse_command_args(argv, &path);
9362 argc -= nargv - argv;
9364 cmd_flag |= DO_NOFUNC;
9372 /* We have a redirection error. */
9374 raise_exception(EXERROR);
9376 exitstatus = status;
9380 /* Execute the command. */
9381 switch (cmdentry.cmdtype) {
9384 #if ENABLE_FEATURE_SH_NOFORK
9385 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9386 * around run_nofork_applet() call.
9387 * (2) Should this check also be done in forkshell()?
9388 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9390 /* find_command() encodes applet_no as (-2 - applet_no) */
9391 int applet_no = (- cmdentry.u.index - 2);
9392 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9393 listsetvar(varlist.list, VEXPORT|VSTACK);
9394 /* run <applet>_main() */
9395 exitstatus = run_nofork_applet(applet_no, argv);
9399 /* Can we avoid forking off? For example, very last command
9400 * in a script or a subshell does not need forking,
9401 * we can just exec it.
9403 if (!(flags & EV_EXIT) || may_have_traps) {
9404 /* No, forking off a child is necessary */
9406 jp = makejob(/*cmd,*/ 1);
9407 if (forkshell(jp, cmd, FORK_FG) != 0) {
9409 exitstatus = waitforjob(jp);
9411 TRACE(("forked child exited with %d\n", exitstatus));
9416 /* fall through to exec'ing external program */
9418 listsetvar(varlist.list, VEXPORT|VSTACK);
9419 shellexec(argv, path, cmdentry.u.index);
9423 cmdenviron = varlist.list;
9425 struct strlist *list = cmdenviron;
9427 if (spclbltin > 0 || argc == 0) {
9429 if (cmd_is_exec && argc > 1)
9432 listsetvar(list, i);
9434 /* Tight loop with builtins only:
9435 * "while kill -0 $child; do true; done"
9436 * will never exit even if $child died, unless we do this
9437 * to reap the zombie and make kill detect that it's gone: */
9438 dowait(DOWAIT_NONBLOCK, NULL);
9440 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9442 int i = exception_type;
9443 if (i == EXEXIT || i == EXEXEC)
9447 exit_status = 128 + SIGINT;
9449 exit_status = 128 + pending_sig;
9450 exitstatus = exit_status;
9451 if (i == EXINT || spclbltin > 0) {
9453 longjmp(exception_handler->loc, 1);
9460 listsetvar(varlist.list, 0);
9461 /* See above for the rationale */
9462 dowait(DOWAIT_NONBLOCK, NULL);
9463 if (evalfun(cmdentry.u.func, argc, argv, flags))
9469 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9471 /* dsl: I think this is intended to be used to support
9472 * '_' in 'vi' command mode during line editing...
9473 * However I implemented that within libedit itself.
9475 setvar0("_", lastarg);
9477 popstackmark(&smark);
9481 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9483 char *volatile savecmdname;
9484 struct jmploc *volatile savehandler;
9485 struct jmploc jmploc;
9488 savecmdname = commandname;
9489 i = setjmp(jmploc.loc);
9492 savehandler = exception_handler;
9493 exception_handler = &jmploc;
9494 commandname = argv[0];
9496 optptr = NULL; /* initialize nextopt */
9497 exitstatus = (*cmd->builtin)(argc, argv);
9498 flush_stdout_stderr();
9500 exitstatus |= ferror(stdout);
9502 commandname = savecmdname;
9503 exception_handler = savehandler;
9509 goodname(const char *p)
9511 return endofname(p)[0] == '\0';
9516 * Search for a command. This is called before we fork so that the
9517 * location of the command will be available in the parent as well as
9518 * the child. The check for "goodname" is an overly conservative
9519 * check that the name will not be subject to expansion.
9522 prehash(union node *n)
9524 struct cmdentry entry;
9526 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9527 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9531 /* ============ Builtin commands
9533 * Builtin commands whose functions are closely tied to evaluation
9534 * are implemented here.
9538 * Handle break and continue commands. Break, continue, and return are
9539 * all handled by setting the evalskip flag. The evaluation routines
9540 * above all check this flag, and if it is set they start skipping
9541 * commands rather than executing them. The variable skipcount is
9542 * the number of loops to break/continue, or the number of function
9543 * levels to return. (The latter is always 1.) It should probably
9544 * be an error to break out of more loops than exist, but it isn't
9545 * in the standard shell so we don't make it one here.
9547 static int FAST_FUNC
9548 breakcmd(int argc UNUSED_PARAM, char **argv)
9550 int n = argv[1] ? number(argv[1]) : 1;
9553 ash_msg_and_raise_error(msg_illnum, argv[1]);
9557 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9564 /* ============ input.c
9566 * This implements the input routines used by the parser.
9570 INPUT_PUSH_FILE = 1,
9571 INPUT_NOFILE_OK = 2,
9574 static smallint checkkwd;
9575 /* values of checkkwd variable */
9576 #define CHKALIAS 0x1
9581 * Push a string back onto the input at this current parsefile level.
9582 * We handle aliases this way.
9584 #if !ENABLE_ASH_ALIAS
9585 #define pushstring(s, ap) pushstring(s)
9588 pushstring(char *s, struct alias *ap)
9595 if (g_parsefile->strpush) {
9596 sp = ckzalloc(sizeof(*sp));
9597 sp->prev = g_parsefile->strpush;
9599 sp = &(g_parsefile->basestrpush);
9601 g_parsefile->strpush = sp;
9602 sp->prev_string = g_parsefile->next_to_pgetc;
9603 sp->prev_left_in_line = g_parsefile->left_in_line;
9604 #if ENABLE_ASH_ALIAS
9607 ap->flag |= ALIASINUSE;
9611 g_parsefile->next_to_pgetc = s;
9612 g_parsefile->left_in_line = len;
9619 struct strpush *sp = g_parsefile->strpush;
9622 #if ENABLE_ASH_ALIAS
9624 if (g_parsefile->next_to_pgetc[-1] == ' '
9625 || g_parsefile->next_to_pgetc[-1] == '\t'
9627 checkkwd |= CHKALIAS;
9629 if (sp->string != sp->ap->val) {
9632 sp->ap->flag &= ~ALIASINUSE;
9633 if (sp->ap->flag & ALIASDEAD) {
9634 unalias(sp->ap->name);
9638 g_parsefile->next_to_pgetc = sp->prev_string;
9639 g_parsefile->left_in_line = sp->prev_left_in_line;
9640 g_parsefile->strpush = sp->prev;
9641 if (sp != &(g_parsefile->basestrpush))
9646 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9647 //it peeks whether it is &>, and then pushes back both chars.
9648 //This function needs to save last *next_to_pgetc to buf[0]
9649 //to make two pungetc() reliable. Currently,
9650 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9655 char *buf = g_parsefile->buf;
9657 g_parsefile->next_to_pgetc = buf;
9658 #if ENABLE_FEATURE_EDITING
9660 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9661 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9664 # if ENABLE_ASH_IDLE_TIMEOUT
9666 const char *tmout_var = lookupvar("TMOUT");
9668 timeout = atoi(tmout_var) * 1000;
9674 # if ENABLE_FEATURE_TAB_COMPLETION
9675 line_input_state->path_lookup = pathval();
9677 reinit_unicode_for_ash();
9678 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9680 /* Ctrl+C pressed */
9691 /* Ctrl+D pressed */
9694 # if ENABLE_ASH_IDLE_TIMEOUT
9695 else if (errno == EAGAIN && timeout > 0) {
9696 puts("\007timed out waiting for input: auto-logout");
9703 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9706 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9708 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9709 int flags = fcntl(0, F_GETFL);
9710 if (flags >= 0 && (flags & O_NONBLOCK)) {
9711 flags &= ~O_NONBLOCK;
9712 if (fcntl(0, F_SETFL, flags) >= 0) {
9713 out2str("sh: turning off NDELAY mode\n");
9724 * Refill the input buffer and return the next input character:
9726 * 1) If a string was pushed back on the input, pop it;
9727 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9728 * or we are reading from a string so we can't refill the buffer,
9730 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9731 * 4) Process input up to the next newline, deleting nul characters.
9733 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9734 #define pgetc_debug(...) ((void)0)
9741 while (g_parsefile->strpush) {
9742 #if ENABLE_ASH_ALIAS
9743 if (g_parsefile->left_in_line == -1
9744 && g_parsefile->strpush->ap
9745 && g_parsefile->next_to_pgetc[-1] != ' '
9746 && g_parsefile->next_to_pgetc[-1] != '\t'
9748 pgetc_debug("preadbuffer PEOA");
9753 /* try "pgetc" now: */
9754 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9755 g_parsefile->left_in_line,
9756 g_parsefile->next_to_pgetc,
9757 g_parsefile->next_to_pgetc);
9758 if (--g_parsefile->left_in_line >= 0)
9759 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9761 /* on both branches above g_parsefile->left_in_line < 0.
9762 * "pgetc" needs refilling.
9765 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9766 * pungetc() may increment it a few times.
9767 * Assuming it won't increment it to less than -90.
9769 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9770 pgetc_debug("preadbuffer PEOF1");
9771 /* even in failure keep left_in_line and next_to_pgetc
9772 * in lock step, for correct multi-layer pungetc.
9773 * left_in_line was decremented before preadbuffer(),
9774 * must inc next_to_pgetc: */
9775 g_parsefile->next_to_pgetc++;
9779 more = g_parsefile->left_in_buffer;
9781 flush_stdout_stderr();
9785 /* don't try reading again */
9786 g_parsefile->left_in_line = -99;
9787 pgetc_debug("preadbuffer PEOF2");
9788 g_parsefile->next_to_pgetc++;
9793 /* Find out where's the end of line.
9794 * Set g_parsefile->left_in_line
9795 * and g_parsefile->left_in_buffer acordingly.
9796 * NUL chars are deleted.
9798 q = g_parsefile->next_to_pgetc;
9806 memmove(q, q + 1, more);
9810 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9816 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9817 if (g_parsefile->left_in_line < 0)
9822 g_parsefile->left_in_buffer = more;
9827 out2str(g_parsefile->next_to_pgetc);
9831 pgetc_debug("preadbuffer at %d:%p'%s'",
9832 g_parsefile->left_in_line,
9833 g_parsefile->next_to_pgetc,
9834 g_parsefile->next_to_pgetc);
9835 return (unsigned char)*g_parsefile->next_to_pgetc++;
9838 #define pgetc_as_macro() \
9839 (--g_parsefile->left_in_line >= 0 \
9840 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9847 pgetc_debug("pgetc_fast at %d:%p'%s'",
9848 g_parsefile->left_in_line,
9849 g_parsefile->next_to_pgetc,
9850 g_parsefile->next_to_pgetc);
9851 return pgetc_as_macro();
9854 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9855 # define pgetc_fast() pgetc()
9857 # define pgetc_fast() pgetc_as_macro()
9860 #if ENABLE_ASH_ALIAS
9862 pgetc_without_PEOA(void)
9866 pgetc_debug("pgetc_fast at %d:%p'%s'",
9867 g_parsefile->left_in_line,
9868 g_parsefile->next_to_pgetc,
9869 g_parsefile->next_to_pgetc);
9871 } while (c == PEOA);
9875 # define pgetc_without_PEOA() pgetc()
9879 * Read a line from the script.
9882 pfgets(char *line, int len)
9888 while (--nleft > 0) {
9889 c = pgetc_without_PEOA();
9904 * Undo the last call to pgetc. Only one character may be pushed back.
9905 * PEOF may be pushed back.
9910 g_parsefile->left_in_line++;
9911 g_parsefile->next_to_pgetc--;
9912 pgetc_debug("pushed back to %d:%p'%s'",
9913 g_parsefile->left_in_line,
9914 g_parsefile->next_to_pgetc,
9915 g_parsefile->next_to_pgetc);
9919 * To handle the "." command, a stack of input files is used. Pushfile
9920 * adds a new entry to the stack and popfile restores the previous level.
9925 struct parsefile *pf;
9927 pf = ckzalloc(sizeof(*pf));
9928 pf->prev = g_parsefile;
9930 /*pf->strpush = NULL; - ckzalloc did it */
9931 /*pf->basestrpush.prev = NULL;*/
9938 struct parsefile *pf = g_parsefile;
9946 g_parsefile = pf->prev;
9952 * Return to top level.
9957 while (g_parsefile != &basepf)
9962 * Close the file(s) that the shell is reading commands from. Called
9963 * after a fork is done.
9969 if (g_parsefile->pf_fd > 0) {
9970 close(g_parsefile->pf_fd);
9971 g_parsefile->pf_fd = 0;
9976 * Like setinputfile, but takes an open file descriptor. Call this with
9980 setinputfd(int fd, int push)
9982 close_on_exec_on(fd);
9985 g_parsefile->buf = NULL;
9987 g_parsefile->pf_fd = fd;
9988 if (g_parsefile->buf == NULL)
9989 g_parsefile->buf = ckmalloc(IBUFSIZ);
9990 g_parsefile->left_in_buffer = 0;
9991 g_parsefile->left_in_line = 0;
9992 g_parsefile->linno = 1;
9996 * Set the input to take input from a file. If push is set, push the
9997 * old input onto the stack first.
10000 setinputfile(const char *fname, int flags)
10006 fd = open(fname, O_RDONLY);
10008 if (flags & INPUT_NOFILE_OK)
10010 ash_msg_and_raise_error("can't open '%s'", fname);
10013 fd2 = copyfd(fd, 10);
10016 ash_msg_and_raise_error("out of file descriptors");
10019 setinputfd(fd, flags & INPUT_PUSH_FILE);
10026 * Like setinputfile, but takes input from a string.
10029 setinputstring(char *string)
10033 g_parsefile->next_to_pgetc = string;
10034 g_parsefile->left_in_line = strlen(string);
10035 g_parsefile->buf = NULL;
10036 g_parsefile->linno = 1;
10041 /* ============ mail.c
10043 * Routines to check for mail.
10046 #if ENABLE_ASH_MAIL
10048 /* Hash of mtimes of mailboxes */
10049 static unsigned mailtime_hash;
10050 /* Set if MAIL or MAILPATH is changed. */
10051 static smallint mail_var_path_changed;
10054 * Print appropriate message(s) if mail has arrived.
10055 * If mail_var_path_changed is set,
10056 * then the value of MAIL has mail_var_path_changed,
10057 * so we just update the values.
10066 struct stackmark smark;
10069 setstackmark(&smark);
10070 mpath = mpathset() ? mpathval() : mailval();
10073 p = path_advance(&mpath, nullstr);
10078 for (q = p; *q; q++)
10084 q[-1] = '\0'; /* delete trailing '/' */
10085 if (stat(p, &statb) < 0) {
10088 /* Very simplistic "hash": just a sum of all mtimes */
10089 new_hash += (unsigned)statb.st_mtime;
10091 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10092 if (mailtime_hash != 0)
10093 out2str("you have mail\n");
10094 mailtime_hash = new_hash;
10096 mail_var_path_changed = 0;
10097 popstackmark(&smark);
10100 static void FAST_FUNC
10101 changemail(const char *val UNUSED_PARAM)
10103 mail_var_path_changed = 1;
10106 #endif /* ASH_MAIL */
10109 /* ============ ??? */
10112 * Set the shell parameters.
10115 setparam(char **argv)
10121 for (nparam = 0; argv[nparam]; nparam++)
10123 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10125 *ap++ = ckstrdup(*argv++);
10128 freeparam(&shellparam);
10129 shellparam.malloced = 1;
10130 shellparam.nparam = nparam;
10131 shellparam.p = newparam;
10132 #if ENABLE_ASH_GETOPTS
10133 shellparam.optind = 1;
10134 shellparam.optoff = -1;
10139 * Process shell options. The global variable argptr contains a pointer
10140 * to the argument list; we advance it past the options.
10142 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10143 * For a non-interactive shell, an error condition encountered
10144 * by a special built-in ... shall cause the shell to write a diagnostic message
10145 * to standard error and exit as shown in the following table:
10146 * Error Special Built-In
10148 * Utility syntax error (option or operand error) Shall exit
10150 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10151 * we see that bash does not do that (set "finishes" with error code 1 instead,
10152 * and shell continues), and people rely on this behavior!
10154 * set -o barfoo 2>/dev/null
10157 * Oh well. Let's mimic that.
10160 plus_minus_o(char *name, int val)
10165 for (i = 0; i < NOPTS; i++) {
10166 if (strcmp(name, optnames(i)) == 0) {
10171 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10174 for (i = 0; i < NOPTS; i++) {
10176 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10178 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10184 setoption(int flag, int val)
10188 for (i = 0; i < NOPTS; i++) {
10189 if (optletters(i) == flag) {
10194 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10198 options(int cmdline)
10206 while ((p = *argptr) != NULL) {
10208 if (c != '-' && c != '+')
10211 val = 0; /* val = 0 if c == '+' */
10214 if (p[0] == '\0' || LONE_DASH(p)) {
10216 /* "-" means turn off -x and -v */
10219 /* "--" means reset params */
10220 else if (*argptr == NULL)
10223 break; /* "-" or "--" terminates options */
10226 /* first char was + or - */
10227 while ((c = *p++) != '\0') {
10228 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10229 if (c == 'c' && cmdline) {
10230 minusc = p; /* command is after shell args */
10231 } else if (c == 'o') {
10232 if (plus_minus_o(*argptr, val)) {
10233 /* it already printed err message */
10234 return 1; /* error */
10238 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10240 /* bash does not accept +-login, we also won't */
10241 } else if (cmdline && val && (c == '-')) { /* long options */
10242 if (strcmp(p, "login") == 0)
10254 * The shift builtin command.
10256 static int FAST_FUNC
10257 shiftcmd(int argc UNUSED_PARAM, char **argv)
10264 n = number(argv[1]);
10265 if (n > shellparam.nparam)
10266 n = 0; /* bash compat, was = shellparam.nparam; */
10268 shellparam.nparam -= n;
10269 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10270 if (shellparam.malloced)
10273 ap2 = shellparam.p;
10274 while ((*ap2++ = *ap1++) != NULL)
10276 #if ENABLE_ASH_GETOPTS
10277 shellparam.optind = 1;
10278 shellparam.optoff = -1;
10285 * POSIX requires that 'set' (but not export or readonly) output the
10286 * variables in lexicographic order - by the locale's collating order (sigh).
10287 * Maybe we could keep them in an ordered balanced binary tree
10288 * instead of hashed lists.
10289 * For now just roll 'em through qsort for printing...
10292 showvars(const char *sep_prefix, int on, int off)
10295 char **ep, **epend;
10297 ep = listvars(on, off, &epend);
10298 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10300 sep = *sep_prefix ? " " : sep_prefix;
10302 for (; ep < epend; ep++) {
10306 p = strchrnul(*ep, '=');
10309 q = single_quote(++p);
10310 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10316 * The set command builtin.
10318 static int FAST_FUNC
10319 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10324 return showvars(nullstr, 0, VUNSET);
10327 retval = options(/*cmdline:*/ 0);
10328 if (retval == 0) { /* if no parse error... */
10330 if (*argptr != NULL) {
10338 #if ENABLE_ASH_RANDOM_SUPPORT
10339 static void FAST_FUNC
10340 change_random(const char *value)
10344 if (value == NULL) {
10345 /* "get", generate */
10346 t = next_random(&random_gen);
10347 /* set without recursion */
10348 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10349 vrandom.flags &= ~VNOFUNC;
10352 t = strtoul(value, NULL, 10);
10353 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10358 #if ENABLE_ASH_GETOPTS
10360 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10371 if (*param_optind < 1)
10373 optnext = optfirst + *param_optind - 1;
10375 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10378 p = optnext[-1] + *optoff;
10379 if (p == NULL || *p == '\0') {
10380 /* Current word is done, advance */
10382 if (p == NULL || *p != '-' || *++p == '\0') {
10389 if (LONE_DASH(p)) /* check for "--" */
10394 for (q = optstr; *q != c;) {
10396 if (optstr[0] == ':') {
10398 /*sbuf[1] = '\0'; - already is */
10399 err |= setvarsafe("OPTARG", sbuf, 0);
10401 fprintf(stderr, "Illegal option -%c\n", c);
10402 unsetvar("OPTARG");
10412 if (*p == '\0' && (p = *optnext) == NULL) {
10413 if (optstr[0] == ':') {
10415 /*sbuf[1] = '\0'; - already is */
10416 err |= setvarsafe("OPTARG", sbuf, 0);
10419 fprintf(stderr, "No arg for -%c option\n", c);
10420 unsetvar("OPTARG");
10428 err |= setvarsafe("OPTARG", p, 0);
10431 err |= setvarsafe("OPTARG", nullstr, 0);
10433 *optoff = p ? p - *(optnext - 1) : -1;
10434 *param_optind = optnext - optfirst + 1;
10435 err |= setvarsafe("OPTIND", itoa(*param_optind), VNOFUNC);
10437 /*sbuf[1] = '\0'; - already is */
10438 err |= setvarsafe(optvar, sbuf, 0);
10442 flush_stdout_stderr();
10443 raise_exception(EXERROR);
10449 * The getopts builtin. Shellparam.optnext points to the next argument
10450 * to be processed. Shellparam.optptr points to the next character to
10451 * be processed in the current argument. If shellparam.optnext is NULL,
10452 * then it's the first time getopts has been called.
10454 static int FAST_FUNC
10455 getoptscmd(int argc, char **argv)
10460 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10462 optbase = shellparam.p;
10463 if (shellparam.optind > shellparam.nparam + 1) {
10464 shellparam.optind = 1;
10465 shellparam.optoff = -1;
10468 optbase = &argv[3];
10469 if (shellparam.optind > argc - 2) {
10470 shellparam.optind = 1;
10471 shellparam.optoff = -1;
10475 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10476 &shellparam.optoff);
10478 #endif /* ASH_GETOPTS */
10481 /* ============ Shell parser */
10484 struct heredoc *next; /* next here document in list */
10485 union node *here; /* redirection node */
10486 char *eofmark; /* string indicating end of input */
10487 smallint striptabs; /* if set, strip leading tabs */
10490 static smallint tokpushback; /* last token pushed back */
10491 static smallint quoteflag; /* set if (part of) last token was quoted */
10492 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10493 static struct heredoc *heredoclist; /* list of here documents to read */
10494 static char *wordtext; /* text of last word returned by readtoken */
10495 static struct nodelist *backquotelist;
10496 static union node *redirnode;
10497 static struct heredoc *heredoc;
10499 static const char *
10500 tokname(char *buf, int tok)
10503 return tokname_array[tok] + 1;
10504 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10508 /* raise_error_unexpected_syntax:
10509 * Called when an unexpected token is read during the parse. The argument
10510 * is the token that is expected, or -1 if more than one type of token can
10511 * occur at this point.
10513 static void raise_error_unexpected_syntax(int) NORETURN;
10515 raise_error_unexpected_syntax(int token)
10521 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10523 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10524 raise_error_syntax(msg);
10528 #define EOFMARKLEN 79
10530 /* parsing is heavily cross-recursive, need these forward decls */
10531 static union node *andor(void);
10532 static union node *pipeline(void);
10533 static union node *parse_command(void);
10534 static void parseheredoc(void);
10535 static int peektoken(void);
10536 static int readtoken(void);
10538 static union node *
10541 union node *n1, *n2, *n3;
10546 switch (peektoken()) {
10554 if (!n1 && (nlflag & 1))
10560 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10561 if (nlflag == 2 && tokname_array[peektoken()][0])
10567 if (tok == TBACKGND) {
10568 if (n2->type == NPIPE) {
10569 n2->npipe.pipe_backgnd = 1;
10571 if (n2->type != NREDIR) {
10572 n3 = stzalloc(sizeof(struct nredir));
10574 /*n3->nredir.redirect = NULL; - stzalloc did it */
10577 n2->type = NBACKGND;
10583 n3 = stzalloc(sizeof(struct nbinary));
10585 n3->nbinary.ch1 = n1;
10586 n3->nbinary.ch2 = n2;
10599 raise_error_unexpected_syntax(-1);
10606 static union node *
10609 union node *n1, *n2, *n3;
10617 } else if (t == TOR) {
10623 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10625 n3 = stzalloc(sizeof(struct nbinary));
10627 n3->nbinary.ch1 = n1;
10628 n3->nbinary.ch2 = n2;
10633 static union node *
10636 union node *n1, *n2, *pipenode;
10637 struct nodelist *lp, *prev;
10641 TRACE(("pipeline: entered\n"));
10642 if (readtoken() == TNOT) {
10644 checkkwd = CHKKWD | CHKALIAS;
10647 n1 = parse_command();
10648 if (readtoken() == TPIPE) {
10649 pipenode = stzalloc(sizeof(struct npipe));
10650 pipenode->type = NPIPE;
10651 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10652 lp = stzalloc(sizeof(struct nodelist));
10653 pipenode->npipe.cmdlist = lp;
10657 lp = stzalloc(sizeof(struct nodelist));
10658 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10659 lp->n = parse_command();
10661 } while (readtoken() == TPIPE);
10667 n2 = stzalloc(sizeof(struct nnot));
10675 static union node *
10680 n = stzalloc(sizeof(struct narg));
10682 /*n->narg.next = NULL; - stzalloc did it */
10683 n->narg.text = wordtext;
10684 n->narg.backquote = backquotelist;
10689 fixredir(union node *n, const char *text, int err)
10693 TRACE(("Fix redir %s %d\n", text, err));
10695 n->ndup.vname = NULL;
10697 fd = bb_strtou(text, NULL, 10);
10698 if (!errno && fd >= 0)
10699 n->ndup.dupfd = fd;
10700 else if (LONE_DASH(text))
10701 n->ndup.dupfd = -1;
10704 raise_error_syntax("bad fd number");
10705 n->ndup.vname = makename();
10710 * Returns true if the text contains nothing to expand (no dollar signs
10714 noexpand(const char *text)
10718 while ((c = *text++) != '\0') {
10719 if (c == CTLQUOTEMARK)
10723 else if (SIT(c, BASESYNTAX) == CCTL)
10732 union node *n = redirnode;
10734 if (readtoken() != TWORD)
10735 raise_error_unexpected_syntax(-1);
10736 if (n->type == NHERE) {
10737 struct heredoc *here = heredoc;
10741 if (quoteflag == 0)
10743 TRACE(("Here document %d\n", n->type));
10744 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10745 raise_error_syntax("illegal eof marker for << redirection");
10746 rmescapes(wordtext, 0);
10747 here->eofmark = wordtext;
10749 if (heredoclist == NULL)
10750 heredoclist = here;
10752 for (p = heredoclist; p->next; p = p->next)
10756 } else if (n->type == NTOFD || n->type == NFROMFD) {
10757 fixredir(n, wordtext, 0);
10759 n->nfile.fname = makename();
10763 static union node *
10766 union node *args, **app;
10767 union node *n = NULL;
10768 union node *vars, **vpp;
10769 union node **rpp, *redir;
10771 #if ENABLE_ASH_BASH_COMPAT
10772 smallint double_brackets_flag = 0;
10773 smallint function_flag = 0;
10783 savecheckkwd = CHKALIAS;
10786 checkkwd = savecheckkwd;
10789 #if ENABLE_ASH_BASH_COMPAT
10791 if (peektoken() != TWORD)
10792 raise_error_unexpected_syntax(TWORD);
10795 case TAND: /* "&&" */
10796 case TOR: /* "||" */
10797 if (!double_brackets_flag) {
10801 wordtext = (char *) (t == TAND ? "-a" : "-o");
10804 n = stzalloc(sizeof(struct narg));
10806 /*n->narg.next = NULL; - stzalloc did it */
10807 n->narg.text = wordtext;
10808 #if ENABLE_ASH_BASH_COMPAT
10809 if (strcmp("[[", wordtext) == 0)
10810 double_brackets_flag = 1;
10811 else if (strcmp("]]", wordtext) == 0)
10812 double_brackets_flag = 0;
10814 n->narg.backquote = backquotelist;
10815 if (savecheckkwd && isassignment(wordtext)) {
10817 vpp = &n->narg.next;
10820 app = &n->narg.next;
10823 #if ENABLE_ASH_BASH_COMPAT
10824 if (function_flag) {
10825 checkkwd = CHKNL | CHKKWD;
10826 switch (peektoken()) {
10838 if (strcmp("[[", wordtext) == 0)
10842 raise_error_unexpected_syntax(-1);
10848 *rpp = n = redirnode;
10849 rpp = &n->nfile.next;
10850 parsefname(); /* read name of redirection file */
10853 IF_ASH_BASH_COMPAT(do_func:)
10854 if (args && app == &args->narg.next
10857 struct builtincmd *bcmd;
10860 /* We have a function */
10861 if (IF_ASH_BASH_COMPAT(!function_flag &&) readtoken() != TRP)
10862 raise_error_unexpected_syntax(TRP);
10863 name = n->narg.text;
10864 if (!goodname(name)
10865 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10867 raise_error_syntax("bad function name");
10870 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10871 n->narg.next = parse_command();
10874 IF_ASH_BASH_COMPAT(function_flag = 0;)
10885 n = stzalloc(sizeof(struct ncmd));
10887 n->ncmd.args = args;
10888 n->ncmd.assign = vars;
10889 n->ncmd.redirect = redir;
10893 static union node *
10894 parse_command(void)
10896 union node *n1, *n2;
10897 union node *ap, **app;
10898 union node *cp, **cpp;
10899 union node *redir, **rpp;
10906 switch (readtoken()) {
10908 raise_error_unexpected_syntax(-1);
10911 n1 = stzalloc(sizeof(struct nif));
10913 n1->nif.test = list(0);
10914 if (readtoken() != TTHEN)
10915 raise_error_unexpected_syntax(TTHEN);
10916 n1->nif.ifpart = list(0);
10918 while (readtoken() == TELIF) {
10919 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10920 n2 = n2->nif.elsepart;
10922 n2->nif.test = list(0);
10923 if (readtoken() != TTHEN)
10924 raise_error_unexpected_syntax(TTHEN);
10925 n2->nif.ifpart = list(0);
10927 if (lasttoken == TELSE)
10928 n2->nif.elsepart = list(0);
10930 n2->nif.elsepart = NULL;
10938 n1 = stzalloc(sizeof(struct nbinary));
10939 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10940 n1->nbinary.ch1 = list(0);
10943 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
10944 got == TWORD ? wordtext : ""));
10945 raise_error_unexpected_syntax(TDO);
10947 n1->nbinary.ch2 = list(0);
10952 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10953 raise_error_syntax("bad for loop variable");
10954 n1 = stzalloc(sizeof(struct nfor));
10956 n1->nfor.var = wordtext;
10957 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10958 if (readtoken() == TIN) {
10960 while (readtoken() == TWORD) {
10961 n2 = stzalloc(sizeof(struct narg));
10963 /*n2->narg.next = NULL; - stzalloc did it */
10964 n2->narg.text = wordtext;
10965 n2->narg.backquote = backquotelist;
10967 app = &n2->narg.next;
10970 n1->nfor.args = ap;
10971 if (lasttoken != TNL && lasttoken != TSEMI)
10972 raise_error_unexpected_syntax(-1);
10974 n2 = stzalloc(sizeof(struct narg));
10976 /*n2->narg.next = NULL; - stzalloc did it */
10977 n2->narg.text = (char *)dolatstr;
10978 /*n2->narg.backquote = NULL;*/
10979 n1->nfor.args = n2;
10981 * Newline or semicolon here is optional (but note
10982 * that the original Bourne shell only allowed NL).
10984 if (lasttoken != TSEMI)
10987 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10988 if (readtoken() != TDO)
10989 raise_error_unexpected_syntax(TDO);
10990 n1->nfor.body = list(0);
10994 n1 = stzalloc(sizeof(struct ncase));
10996 if (readtoken() != TWORD)
10997 raise_error_unexpected_syntax(TWORD);
10998 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11000 /*n2->narg.next = NULL; - stzalloc did it */
11001 n2->narg.text = wordtext;
11002 n2->narg.backquote = backquotelist;
11003 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11004 if (readtoken() != TIN)
11005 raise_error_unexpected_syntax(TIN);
11006 cpp = &n1->ncase.cases;
11008 checkkwd = CHKNL | CHKKWD;
11010 while (t != TESAC) {
11011 if (lasttoken == TLP)
11013 *cpp = cp = stzalloc(sizeof(struct nclist));
11015 app = &cp->nclist.pattern;
11017 *app = ap = stzalloc(sizeof(struct narg));
11019 /*ap->narg.next = NULL; - stzalloc did it */
11020 ap->narg.text = wordtext;
11021 ap->narg.backquote = backquotelist;
11022 if (readtoken() != TPIPE)
11024 app = &ap->narg.next;
11027 //ap->narg.next = NULL;
11028 if (lasttoken != TRP)
11029 raise_error_unexpected_syntax(TRP);
11030 cp->nclist.body = list(2);
11032 cpp = &cp->nclist.next;
11034 checkkwd = CHKNL | CHKKWD;
11038 raise_error_unexpected_syntax(TENDCASE);
11045 n1 = stzalloc(sizeof(struct nredir));
11046 n1->type = NSUBSHELL;
11047 n1->nredir.n = list(0);
11048 /*n1->nredir.redirect = NULL; - stzalloc did it */
11055 IF_ASH_BASH_COMPAT(case TFUNCTION:)
11059 return simplecmd();
11062 if (readtoken() != t)
11063 raise_error_unexpected_syntax(t);
11066 /* Now check for redirection which may follow command */
11067 checkkwd = CHKKWD | CHKALIAS;
11069 while (readtoken() == TREDIR) {
11070 *rpp = n2 = redirnode;
11071 rpp = &n2->nfile.next;
11077 if (n1->type != NSUBSHELL) {
11078 n2 = stzalloc(sizeof(struct nredir));
11083 n1->nredir.redirect = redir;
11088 #if ENABLE_ASH_BASH_COMPAT
11089 static int decode_dollar_squote(void)
11091 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11097 p = strchr(C_escapes, c);
11102 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11106 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11108 } else if (c == 'x') { /* \xHH */
11112 } while (isxdigit(c) && --cnt);
11114 if (cnt == 3) { /* \x but next char is "bad" */
11118 } else { /* simple seq like \\ or \t */
11123 c = bb_process_escape_sequence((void*)&p);
11124 } else { /* unrecognized "\z": print both chars unless ' or " */
11125 if (c != '\'' && c != '"') {
11127 c |= 0x100; /* "please encode \, then me" */
11135 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11136 * is not NULL, read a here document. In the latter case, eofmark is the
11137 * word which marks the end of the document and striptabs is true if
11138 * leading tabs should be stripped from the document. The argument c
11139 * is the first character of the input token or document.
11141 * Because C does not have internal subroutines, I have simulated them
11142 * using goto's to implement the subroutine linkage. The following macros
11143 * will run code that appears at the end of readtoken1.
11145 #define CHECKEND() {goto checkend; checkend_return:;}
11146 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11147 #define PARSESUB() {goto parsesub; parsesub_return:;}
11148 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11149 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11150 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11152 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11154 /* NB: syntax parameter fits into smallint */
11155 /* c parameter is an unsigned char or PEOF or PEOA */
11158 char line[EOFMARKLEN + 1];
11159 struct nodelist *bqlist;
11163 smallint prevsyntax; /* syntax before arithmetic */
11164 #if ENABLE_ASH_EXPAND_PRMT
11165 smallint pssyntax; /* we are expanding a prompt string */
11167 int varnest; /* levels of variables expansion */
11168 int arinest; /* levels of arithmetic expansion */
11169 int parenlevel; /* levels of parens in arithmetic */
11170 int dqvarnest; /* levels of variables expansion within double quotes */
11172 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11174 startlinno = g_parsefile->linno;
11178 #if ENABLE_ASH_EXPAND_PRMT
11179 pssyntax = (syntax == PSSYNTAX);
11183 dblquote = (syntax == DQSYNTAX);
11189 STARTSTACKSTR(out);
11191 /* For each line, until end of word */
11192 CHECKEND(); /* set c to PEOF if at end of here document */
11193 for (;;) { /* until end of line or end of word */
11194 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11195 switch (SIT(c, syntax)) {
11196 case CNL: /* '\n' */
11197 if (syntax == BASESYNTAX)
11198 goto endword; /* exit outer loop */
11200 g_parsefile->linno++;
11201 setprompt_if(doprompt, 2);
11203 goto loop; /* continue outer loop */
11208 if (eofmark == NULL || dblquote)
11209 USTPUTC(CTLESC, out);
11210 #if ENABLE_ASH_BASH_COMPAT
11211 if (c == '\\' && bash_dollar_squote) {
11212 c = decode_dollar_squote();
11214 USTPUTC('\\', out);
11215 c = (unsigned char)c;
11221 case CBACK: /* backslash */
11222 c = pgetc_without_PEOA();
11224 USTPUTC(CTLESC, out);
11225 USTPUTC('\\', out);
11227 } else if (c == '\n') {
11228 setprompt_if(doprompt, 2);
11230 #if ENABLE_ASH_EXPAND_PRMT
11231 if (c == '$' && pssyntax) {
11232 USTPUTC(CTLESC, out);
11233 USTPUTC('\\', out);
11236 /* Backslash is retained if we are in "str" and next char isn't special */
11241 && (c != '"' || eofmark != NULL)
11243 USTPUTC('\\', out);
11245 USTPUTC(CTLESC, out);
11253 if (eofmark == NULL) {
11254 USTPUTC(CTLQUOTEMARK, out);
11262 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11263 if (eofmark != NULL && varnest == 0) {
11266 if (dqvarnest == 0) {
11267 syntax = BASESYNTAX;
11274 case CVAR: /* '$' */
11275 PARSESUB(); /* parse substitution */
11277 case CENDVAR: /* '}' */
11280 if (dqvarnest > 0) {
11287 #if ENABLE_SH_MATH_SUPPORT
11288 case CLP: /* '(' in arithmetic */
11292 case CRP: /* ')' in arithmetic */
11293 if (parenlevel > 0) {
11296 if (pgetc() == ')') {
11298 if (--arinest == 0) {
11299 syntax = prevsyntax;
11303 * unbalanced parens
11304 * (don't 2nd guess - no error)
11312 case CBQUOTE: /* '`' */
11316 goto endword; /* exit outer loop */
11320 if (varnest == 0) {
11321 #if ENABLE_ASH_BASH_COMPAT
11323 if (pgetc() == '>')
11324 c = 0x100 + '>'; /* flag &> */
11328 goto endword; /* exit outer loop */
11330 IF_ASH_ALIAS(if (c != PEOA))
11337 #if ENABLE_SH_MATH_SUPPORT
11338 if (syntax == ARISYNTAX)
11339 raise_error_syntax("missing '))'");
11341 if (syntax != BASESYNTAX && eofmark == NULL)
11342 raise_error_syntax("unterminated quoted string");
11343 if (varnest != 0) {
11344 startlinno = g_parsefile->linno;
11346 raise_error_syntax("missing '}'");
11348 USTPUTC('\0', out);
11349 len = out - (char *)stackblock();
11350 out = stackblock();
11351 if (eofmark == NULL) {
11352 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11355 if (isdigit_str9(out)) {
11356 PARSEREDIR(); /* passed as params: out, c */
11357 lasttoken = TREDIR;
11360 /* else: non-number X seen, interpret it
11361 * as "NNNX>file" = "NNNX >file" */
11365 quoteflag = quotef;
11366 backquotelist = bqlist;
11367 grabstackblock(len);
11371 /* end of readtoken routine */
11374 * Check to see whether we are at the end of the here document. When this
11375 * is called, c is set to the first character of the next input line. If
11376 * we are at the end of the here document, this routine sets the c to PEOF.
11380 #if ENABLE_ASH_ALIAS
11382 c = pgetc_without_PEOA();
11385 while (c == '\t') {
11386 c = pgetc_without_PEOA();
11389 if (c == *eofmark) {
11390 if (pfgets(line, sizeof(line)) != NULL) {
11394 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11396 if (*p == '\n' && *q == '\0') {
11398 g_parsefile->linno++;
11399 needprompt = doprompt;
11401 pushstring(line, NULL);
11406 goto checkend_return;
11410 * Parse a redirection operator. The variable "out" points to a string
11411 * specifying the fd to be redirected. The variable "c" contains the
11412 * first character of the redirection operator.
11415 /* out is already checked to be a valid number or "" */
11416 int fd = (*out == '\0' ? -1 : atoi(out));
11419 np = stzalloc(sizeof(struct nfile));
11424 np->type = NAPPEND;
11426 np->type = NCLOBBER;
11429 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11435 #if ENABLE_ASH_BASH_COMPAT
11436 else if (c == 0x100 + '>') { /* this flags &> redirection */
11438 pgetc(); /* this is '>', no need to check */
11442 else { /* c == '<' */
11443 /*np->nfile.fd = 0; - stzalloc did it */
11447 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11448 np = stzalloc(sizeof(struct nhere));
11449 /*np->nfile.fd = 0; - stzalloc did it */
11452 heredoc = stzalloc(sizeof(struct heredoc));
11453 heredoc->here = np;
11456 heredoc->striptabs = 1;
11458 /*heredoc->striptabs = 0; - stzalloc did it */
11464 np->type = NFROMFD;
11468 np->type = NFROMTO;
11480 goto parseredir_return;
11484 * Parse a substitution. At this point, we have read the dollar sign
11485 * and nothing else.
11488 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11489 * (assuming ascii char codes, as the original implementation did) */
11490 #define is_special(c) \
11491 (((unsigned)(c) - 33 < 32) \
11492 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11494 unsigned char subtype;
11499 if (c > 255 /* PEOA or PEOF */
11500 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11502 #if ENABLE_ASH_BASH_COMPAT
11503 if (syntax != DQSYNTAX && c == '\'')
11504 bash_dollar_squote = 1;
11509 } else if (c == '(') {
11510 /* $(command) or $((arith)) */
11511 if (pgetc() == '(') {
11512 #if ENABLE_SH_MATH_SUPPORT
11515 raise_error_syntax("you disabled math support for $((arith)) syntax");
11522 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11523 USTPUTC(CTLVAR, out);
11524 typeloc = out - (char *)stackblock();
11525 USTPUTC(VSNORMAL, out);
11526 subtype = VSNORMAL;
11532 c = '#'; /* ${#} - same as $# */
11534 subtype = VSLENGTH; /* ${#VAR} */
11539 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11540 /* $[{[#]]NAME[}] */
11544 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11545 } else if (isdigit(c)) {
11546 /* $[{[#]]NUM[}] */
11550 } while (isdigit(c));
11551 } else if (is_special(c)) {
11552 /* $[{[#]]<specialchar>[}] */
11557 raise_error_syntax("bad substitution");
11559 if (c != '}' && subtype == VSLENGTH) {
11560 /* ${#VAR didn't end with } */
11566 if (subtype == 0) {
11567 /* ${VAR...} but not $VAR or ${#VAR} */
11568 /* c == first char after VAR */
11572 #if ENABLE_ASH_BASH_COMPAT
11573 if (c == ':' || c == '$' || isdigit(c)) {
11574 //TODO: support more general format ${v:EXPR:EXPR},
11575 // where EXPR follows $(()) rules
11576 subtype = VSSUBSTR;
11578 break; /* "goto do_pungetc" is bigger (!) */
11584 static const char types[] ALIGN1 = "}-+?=";
11585 const char *p = strchr(types, c);
11588 subtype = p - types + VSNORMAL;
11594 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11601 #if ENABLE_ASH_BASH_COMPAT
11603 /* ${v/[/]pattern/repl} */
11604 //TODO: encode pattern and repl separately.
11605 // Currently ${v/$var_with_slash/repl} is horribly broken
11606 subtype = VSREPLACE;
11610 subtype++; /* VSREPLACEALL */
11618 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11619 if (subtype != VSNORMAL) {
11626 goto parsesub_return;
11630 * Called to parse command substitutions. Newstyle is set if the command
11631 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11632 * list of commands (passed by reference), and savelen is the number of
11633 * characters on the top of the stack which must be preserved.
11636 struct nodelist **nlpp;
11640 smallint saveprompt = 0;
11643 savelen = out - (char *)stackblock();
11645 str = alloca(savelen);
11646 memcpy(str, stackblock(), savelen);
11649 /* We must read until the closing backquote, giving special
11650 * treatment to some slashes, and then push the string and
11651 * reread it as input, interpreting it normally.
11657 STARTSTACKSTR(pout);
11661 setprompt_if(needprompt, 2);
11670 g_parsefile->linno++;
11671 setprompt_if(doprompt, 2);
11673 * If eating a newline, avoid putting
11674 * the newline into the new character
11675 * stream (via the STPUTC after the
11680 if (pc != '\\' && pc != '`' && pc != '$'
11681 && (!dblquote || pc != '"')
11683 STPUTC('\\', pout);
11685 if (pc <= 255 /* not PEOA or PEOF */) {
11691 IF_ASH_ALIAS(case PEOA:)
11692 startlinno = g_parsefile->linno;
11693 raise_error_syntax("EOF in backquote substitution");
11696 g_parsefile->linno++;
11697 needprompt = doprompt;
11706 STPUTC('\0', pout);
11707 psavelen = pout - (char *)stackblock();
11708 if (psavelen > 0) {
11709 pstr = grabstackstr(pout);
11710 setinputstring(pstr);
11715 nlpp = &(*nlpp)->next;
11716 *nlpp = stzalloc(sizeof(**nlpp));
11717 /* (*nlpp)->next = NULL; - stzalloc did it */
11720 saveprompt = doprompt;
11727 doprompt = saveprompt;
11728 else if (readtoken() != TRP)
11729 raise_error_unexpected_syntax(TRP);
11734 * Start reading from old file again, ignoring any pushed back
11735 * tokens left from the backquote parsing
11740 while (stackblocksize() <= savelen)
11742 STARTSTACKSTR(out);
11744 memcpy(out, str, savelen);
11745 STADJUST(savelen, out);
11747 USTPUTC(CTLBACKQ, out);
11749 goto parsebackq_oldreturn;
11750 goto parsebackq_newreturn;
11753 #if ENABLE_SH_MATH_SUPPORT
11755 * Parse an arithmetic expansion (indicate start of one and set state)
11758 if (++arinest == 1) {
11759 prevsyntax = syntax;
11760 syntax = ARISYNTAX;
11762 USTPUTC(CTLARI, out);
11763 goto parsearith_return;
11766 } /* end of readtoken */
11769 * Read the next input token.
11770 * If the token is a word, we set backquotelist to the list of cmds in
11771 * backquotes. We set quoteflag to true if any part of the word was
11773 * If the token is TREDIR, then we set redirnode to a structure containing
11775 * In all cases, the variable startlinno is set to the number of the line
11776 * on which the token starts.
11778 * [Change comment: here documents and internal procedures]
11779 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11780 * word parsing code into a separate routine. In this case, readtoken
11781 * doesn't need to have any internal procedures, but parseword does.
11782 * We could also make parseoperator in essence the main routine, and
11783 * have parseword (readtoken1?) handle both words and redirection.]
11785 #define NEW_xxreadtoken
11786 #ifdef NEW_xxreadtoken
11787 /* singles must be first! */
11788 static const char xxreadtoken_chars[7] ALIGN1 = {
11789 '\n', '(', ')', /* singles */
11790 '&', '|', ';', /* doubles */
11794 #define xxreadtoken_singles 3
11795 #define xxreadtoken_doubles 3
11797 static const char xxreadtoken_tokens[] ALIGN1 = {
11798 TNL, TLP, TRP, /* only single occurrence allowed */
11799 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11800 TEOF, /* corresponds to trailing nul */
11801 TAND, TOR, TENDCASE /* if double occurrence */
11813 setprompt_if(needprompt, 2);
11814 startlinno = g_parsefile->linno;
11815 for (;;) { /* until token or start of word found */
11817 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11821 while ((c = pgetc()) != '\n' && c != PEOF)
11824 } else if (c == '\\') {
11825 if (pgetc() != '\n') {
11827 break; /* return readtoken1(...) */
11829 startlinno = ++g_parsefile->linno;
11830 setprompt_if(doprompt, 2);
11834 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11837 g_parsefile->linno++;
11838 needprompt = doprompt;
11841 p = strchr(xxreadtoken_chars, c);
11843 break; /* return readtoken1(...) */
11845 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11847 if (cc == c) { /* double occurrence? */
11848 p += xxreadtoken_doubles + 1;
11851 #if ENABLE_ASH_BASH_COMPAT
11852 if (c == '&' && cc == '>') /* &> */
11853 break; /* return readtoken1(...) */
11858 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11863 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11865 #else /* old xxreadtoken */
11866 #define RETURN(token) return lasttoken = token
11876 setprompt_if(needprompt, 2);
11877 startlinno = g_parsefile->linno;
11878 for (;;) { /* until token or start of word found */
11881 case ' ': case '\t':
11882 IF_ASH_ALIAS(case PEOA:)
11885 while ((c = pgetc()) != '\n' && c != PEOF)
11890 if (pgetc() == '\n') {
11891 startlinno = ++g_parsefile->linno;
11892 setprompt_if(doprompt, 2);
11898 g_parsefile->linno++;
11899 needprompt = doprompt;
11904 if (pgetc() == '&')
11909 if (pgetc() == '|')
11914 if (pgetc() == ';')
11927 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11930 #endif /* old xxreadtoken */
11936 int kwd = checkkwd;
11938 smallint alreadyseen = tokpushback;
11941 #if ENABLE_ASH_ALIAS
11957 if (t != TWORD || quoteflag) {
11962 * check for keywords
11964 if (kwd & CHKKWD) {
11965 const char *const *pp;
11967 pp = findkwd(wordtext);
11969 lasttoken = t = pp - tokname_array;
11970 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
11975 if (checkkwd & CHKALIAS) {
11976 #if ENABLE_ASH_ALIAS
11978 ap = lookupalias(wordtext, 1);
11981 pushstring(ap->val, ap);
11991 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11993 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
12009 * Read and parse a command. Returns NODE_EOF on end of file.
12010 * (NULL is a valid parse tree indicating a blank line.)
12012 static union node *
12013 parsecmd(int interact)
12018 doprompt = interact;
12019 setprompt_if(doprompt, doprompt);
12025 * Input any here documents.
12030 struct heredoc *here;
12033 here = heredoclist;
12034 heredoclist = NULL;
12037 setprompt_if(needprompt, 2);
12038 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12039 here->eofmark, here->striptabs);
12040 n = stzalloc(sizeof(struct narg));
12041 n->narg.type = NARG;
12042 /*n->narg.next = NULL; - stzalloc did it */
12043 n->narg.text = wordtext;
12044 n->narg.backquote = backquotelist;
12045 here->here->nhere.doc = n;
12052 * called by editline -- any expansions to the prompt should be added here.
12054 #if ENABLE_ASH_EXPAND_PRMT
12055 static const char *
12056 expandstr(const char *ps)
12060 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12061 * and token processing _can_ alter it (delete NULs etc). */
12062 setinputstring((char *)ps);
12063 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12066 n.narg.type = NARG;
12067 n.narg.next = NULL;
12068 n.narg.text = wordtext;
12069 n.narg.backquote = backquotelist;
12071 expandarg(&n, NULL, EXP_QUOTED);
12072 return stackblock();
12077 * Execute a command or commands contained in a string.
12080 evalstring(char *s, int mask)
12083 struct stackmark smark;
12087 setstackmark(&smark);
12090 while ((n = parsecmd(0)) != NODE_EOF) {
12092 popstackmark(&smark);
12105 * The eval command.
12107 static int FAST_FUNC
12108 evalcmd(int argc UNUSED_PARAM, char **argv)
12117 STARTSTACKSTR(concat);
12119 concat = stack_putstr(p, concat);
12123 STPUTC(' ', concat);
12125 STPUTC('\0', concat);
12126 p = grabstackstr(concat);
12128 evalstring(p, ~SKIPEVAL);
12134 * Read and execute commands.
12135 * "Top" is nonzero for the top level command loop;
12136 * it turns on prompting if the shell is interactive.
12142 struct stackmark smark;
12146 TRACE(("cmdloop(%d) called\n", top));
12150 setstackmark(&smark);
12153 showjobs(SHOW_CHANGED|SHOW_STDERR);
12156 if (iflag && top) {
12160 n = parsecmd(inter);
12162 if (DEBUG > 2 && debug && (n != NODE_EOF))
12165 if (n == NODE_EOF) {
12166 if (!top || numeof >= 50)
12168 if (!stoppedjobs()) {
12171 out2str("\nUse \"exit\" to leave shell.\n");
12174 } else if (nflag == 0) {
12175 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12180 popstackmark(&smark);
12185 return skip & SKIPEVAL;
12192 * Take commands from a file. To be compatible we should do a path
12193 * search for the file, which is necessary to find sub-commands.
12196 find_dot_file(char *name)
12199 const char *path = pathval();
12202 /* don't try this for absolute or relative paths */
12203 if (strchr(name, '/'))
12206 /* IIRC standards do not say whether . is to be searched.
12207 * And it is even smaller this way, making it unconditional for now:
12209 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12214 while ((fullname = path_advance(&path, name)) != NULL) {
12216 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12218 * Don't bother freeing here, since it will
12219 * be freed by the caller.
12223 if (fullname != name)
12224 stunalloc(fullname);
12227 /* not found in the PATH */
12228 ash_msg_and_raise_error("%s: not found", name);
12232 static int FAST_FUNC
12233 dotcmd(int argc, char **argv)
12236 struct strlist *sp;
12237 volatile struct shparam saveparam;
12239 for (sp = cmdenviron; sp; sp = sp->next)
12240 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12243 /* bash says: "bash: .: filename argument required" */
12244 return 2; /* bash compat */
12247 /* "false; . empty_file; echo $?" should print 0, not 1: */
12250 /* This aborts if file isn't found, which is POSIXly correct.
12251 * bash returns exitcode 1 instead.
12253 fullname = find_dot_file(argv[1]);
12256 if (argc) { /* argc > 0, argv[0] != NULL */
12257 saveparam = shellparam;
12258 shellparam.malloced = 0;
12259 shellparam.nparam = argc;
12260 shellparam.p = argv;
12263 /* This aborts if file can't be opened, which is POSIXly correct.
12264 * bash returns exitcode 1 instead.
12266 setinputfile(fullname, INPUT_PUSH_FILE);
12267 commandname = fullname;
12272 freeparam(&shellparam);
12273 shellparam = saveparam;
12279 static int FAST_FUNC
12280 exitcmd(int argc UNUSED_PARAM, char **argv)
12285 exitstatus = number(argv[1]);
12286 raise_exception(EXEXIT);
12291 * Read a file containing shell functions.
12294 readcmdfile(char *name)
12296 setinputfile(name, INPUT_PUSH_FILE);
12302 /* ============ find_command inplementation */
12305 * Resolve a command name. If you change this routine, you may have to
12306 * change the shellexec routine as well.
12309 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12311 struct tblentry *cmdp;
12318 struct builtincmd *bcmd;
12320 /* If name contains a slash, don't use PATH or hash table */
12321 if (strchr(name, '/') != NULL) {
12322 entry->u.index = -1;
12323 if (act & DO_ABS) {
12324 while (stat(name, &statb) < 0) {
12326 if (errno == EINTR)
12329 entry->cmdtype = CMDUNKNOWN;
12333 entry->cmdtype = CMDNORMAL;
12337 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12339 updatetbl = (path == pathval());
12342 if (strstr(path, "%builtin") != NULL)
12343 act |= DO_ALTBLTIN;
12346 /* If name is in the table, check answer will be ok */
12347 cmdp = cmdlookup(name, 0);
12348 if (cmdp != NULL) {
12351 switch (cmdp->cmdtype) {
12369 } else if (cmdp->rehash == 0)
12370 /* if not invalidated by cd, we're done */
12374 /* If %builtin not in path, check for builtin next */
12375 bcmd = find_builtin(name);
12377 if (IS_BUILTIN_REGULAR(bcmd))
12378 goto builtin_success;
12379 if (act & DO_ALTPATH) {
12380 if (!(act & DO_ALTBLTIN))
12381 goto builtin_success;
12382 } else if (builtinloc <= 0) {
12383 goto builtin_success;
12387 #if ENABLE_FEATURE_SH_STANDALONE
12389 int applet_no = find_applet_by_name(name);
12390 if (applet_no >= 0) {
12391 entry->cmdtype = CMDNORMAL;
12392 entry->u.index = -2 - applet_no;
12398 /* We have to search path. */
12399 prev = -1; /* where to start */
12400 if (cmdp && cmdp->rehash) { /* doing a rehash */
12401 if (cmdp->cmdtype == CMDBUILTIN)
12404 prev = cmdp->param.index;
12410 while ((fullname = path_advance(&path, name)) != NULL) {
12411 stunalloc(fullname);
12412 /* NB: code below will still use fullname
12413 * despite it being "unallocated" */
12416 if (prefix(pathopt, "builtin")) {
12418 goto builtin_success;
12421 if ((act & DO_NOFUNC)
12422 || !prefix(pathopt, "func")
12423 ) { /* ignore unimplemented options */
12427 /* if rehash, don't redo absolute path names */
12428 if (fullname[0] == '/' && idx <= prev) {
12431 TRACE(("searchexec \"%s\": no change\n", name));
12434 while (stat(fullname, &statb) < 0) {
12436 if (errno == EINTR)
12439 if (errno != ENOENT && errno != ENOTDIR)
12443 e = EACCES; /* if we fail, this will be the error */
12444 if (!S_ISREG(statb.st_mode))
12446 if (pathopt) { /* this is a %func directory */
12447 stalloc(strlen(fullname) + 1);
12448 /* NB: stalloc will return space pointed by fullname
12449 * (because we don't have any intervening allocations
12450 * between stunalloc above and this stalloc) */
12451 readcmdfile(fullname);
12452 cmdp = cmdlookup(name, 0);
12453 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12454 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12455 stunalloc(fullname);
12458 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12460 entry->cmdtype = CMDNORMAL;
12461 entry->u.index = idx;
12465 cmdp = cmdlookup(name, 1);
12466 cmdp->cmdtype = CMDNORMAL;
12467 cmdp->param.index = idx;
12472 /* We failed. If there was an entry for this command, delete it */
12473 if (cmdp && updatetbl)
12474 delete_cmd_entry();
12476 ash_msg("%s: %s", name, errmsg(e, "not found"));
12477 entry->cmdtype = CMDUNKNOWN;
12482 entry->cmdtype = CMDBUILTIN;
12483 entry->u.cmd = bcmd;
12487 cmdp = cmdlookup(name, 1);
12488 cmdp->cmdtype = CMDBUILTIN;
12489 cmdp->param.cmd = bcmd;
12493 entry->cmdtype = cmdp->cmdtype;
12494 entry->u = cmdp->param;
12498 /* ============ trap.c */
12501 * The trap builtin.
12503 static int FAST_FUNC
12504 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12508 int signo, exitcode;
12513 for (signo = 0; signo < NSIG; signo++) {
12514 char *tr = trap_ptr[signo];
12516 /* note: bash adds "SIG", but only if invoked
12517 * as "bash". If called as "sh", or if set -o posix,
12518 * then it prints short signal names.
12519 * We are printing short names: */
12520 out1fmt("trap -- %s %s\n",
12522 get_signame(signo));
12523 /* trap_ptr != trap only if we are in special-cased `trap` code.
12524 * In this case, we will exit very soon, no need to free(). */
12525 /* if (trap_ptr != trap && tp[0]) */
12530 if (trap_ptr != trap) {
12543 signo = get_signum(*ap);
12545 /* Mimic bash message exactly */
12546 ash_msg("%s: invalid signal specification", *ap);
12552 if (LONE_DASH(action))
12555 action = ckstrdup(action);
12559 may_have_traps = 1;
12560 trap[signo] = action;
12571 /* ============ Builtins */
12573 #if ENABLE_ASH_HELP
12574 static int FAST_FUNC
12575 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12581 "Built-in commands:\n"
12582 "------------------\n");
12583 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12584 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12585 builtintab[i].name + 1);
12591 # if ENABLE_FEATURE_SH_STANDALONE
12593 const char *a = applet_names;
12595 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12600 while (*a++ != '\0')
12606 return EXIT_SUCCESS;
12611 static int FAST_FUNC
12612 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12614 show_history(line_input_state);
12615 return EXIT_SUCCESS;
12620 * The export and readonly commands.
12622 static int FAST_FUNC
12623 exportcmd(int argc UNUSED_PARAM, char **argv)
12633 /* "readonly" in bash accepts, but ignores -n.
12634 * We do the same: it saves a conditional in nextopt's param.
12637 while ((opt = nextopt("np")) != '\0') {
12639 flag_off = VEXPORT;
12642 if (argv[0][0] == 'r') {
12644 flag_off = 0; /* readonly ignores -n */
12646 flag_off = ~flag_off;
12648 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12654 p = strchr(name, '=');
12658 vp = *findvar(hashvar(name), name);
12660 vp->flags = ((vp->flags | flag) & flag_off);
12664 setvar(name, p, (flag & flag_off));
12665 } while ((name = *++aptr) != NULL);
12670 /* No arguments. Show the list of exported or readonly vars.
12673 showvars(argv[0], flag, 0);
12678 * Delete a function if it exists.
12681 unsetfunc(const char *name)
12683 struct tblentry *cmdp;
12685 cmdp = cmdlookup(name, 0);
12686 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12687 delete_cmd_entry();
12691 * The unset builtin command. We unset the function before we unset the
12692 * variable to allow a function to be unset when there is a readonly variable
12693 * with the same name.
12695 static int FAST_FUNC
12696 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12703 while ((i = nextopt("vf")) != 0) {
12707 for (ap = argptr; *ap; ap++) {
12720 static const unsigned char timescmd_str[] ALIGN1 = {
12721 ' ', offsetof(struct tms, tms_utime),
12722 '\n', offsetof(struct tms, tms_stime),
12723 ' ', offsetof(struct tms, tms_cutime),
12724 '\n', offsetof(struct tms, tms_cstime),
12727 static int FAST_FUNC
12728 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12730 unsigned long clk_tck, s, t;
12731 const unsigned char *p;
12734 clk_tck = bb_clk_tck();
12739 t = *(clock_t *)(((char *) &buf) + p[1]);
12742 out1fmt("%lum%lu.%03lus%c",
12744 (t * 1000) / clk_tck,
12752 #if ENABLE_SH_MATH_SUPPORT
12754 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12755 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12757 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12759 static int FAST_FUNC
12760 letcmd(int argc UNUSED_PARAM, char **argv)
12766 ash_msg_and_raise_error("expression expected");
12768 i = ash_arith(*argv);
12776 * The read builtin. Options:
12777 * -r Do not interpret '\' specially
12778 * -s Turn off echo (tty only)
12779 * -n NCHARS Read NCHARS max
12780 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12781 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12782 * -u FD Read from given FD instead of fd 0
12783 * This uses unbuffered input, which may be avoidable in some cases.
12784 * TODO: bash also has:
12785 * -a ARRAY Read into array[0],[1],etc
12786 * -d DELIM End on DELIM char, not newline
12787 * -e Use line editing (tty only)
12789 static int FAST_FUNC
12790 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12792 char *opt_n = NULL;
12793 char *opt_p = NULL;
12794 char *opt_t = NULL;
12795 char *opt_u = NULL;
12796 int read_flags = 0;
12800 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12809 read_flags |= BUILTIN_READ_SILENT;
12815 read_flags |= BUILTIN_READ_RAW;
12825 /* "read -s" needs to save/restore termios, can't allow ^C
12826 * to jump out of it.
12829 r = shell_builtin_read(setvar0,
12831 bltinlookup("IFS"), /* can be NULL */
12840 if ((uintptr_t)r > 1)
12841 ash_msg_and_raise_error(r);
12843 return (uintptr_t)r;
12846 static int FAST_FUNC
12847 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12849 static const char permuser[3] ALIGN1 = "ogu";
12852 int symbolic_mode = 0;
12854 while (nextopt("S") != '\0') {
12863 if (*argptr == NULL) {
12864 if (symbolic_mode) {
12865 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
12872 *p++ = permuser[i];
12874 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
12875 if (!(mask & 0400)) *p++ = 'r';
12876 if (!(mask & 0200)) *p++ = 'w';
12877 if (!(mask & 0100)) *p++ = 'x';
12885 out1fmt("%04o\n", mask);
12888 char *modestr = *argptr;
12889 /* numeric umasks are taken as-is */
12890 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
12891 if (!isdigit(modestr[0]))
12893 mask = bb_parse_mode(modestr, mask);
12894 if ((unsigned)mask > 0777) {
12895 ash_msg_and_raise_error("illegal mode: %s", modestr);
12897 if (!isdigit(modestr[0]))
12904 static int FAST_FUNC
12905 ulimitcmd(int argc UNUSED_PARAM, char **argv)
12907 return shell_builtin_ulimit(argv);
12910 /* ============ main() and helpers */
12913 * Called to exit the shell.
12922 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
12923 save_history(line_input_state);
12926 status = exitstatus;
12927 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12928 if (setjmp(loc.loc)) {
12929 if (exception_type == EXEXIT)
12930 /* dash bug: it just does _exit(exitstatus) here
12931 * but we have to do setjobctl(0) first!
12932 * (bug is still not fixed in dash-0.5.3 - if you run dash
12933 * under Midnight Commander, on exit from dash MC is backgrounded) */
12934 status = exitstatus;
12937 exception_handler = &loc;
12944 flush_stdout_stderr();
12954 /* from input.c: */
12955 /* we will never free this */
12956 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
12959 signal(SIGCHLD, SIG_DFL);
12960 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12961 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12963 signal(SIGHUP, SIG_DFL);
12969 struct stat st1, st2;
12972 for (envp = environ; envp && *envp; envp++) {
12973 if (strchr(*envp, '=')) {
12974 setvareq(*envp, VEXPORT|VTEXTFIXED);
12978 setvar0("PPID", utoa(getppid()));
12979 #if ENABLE_ASH_BASH_COMPAT
12980 p = lookupvar("SHLVL");
12981 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
12982 if (!lookupvar("HOSTNAME")) {
12983 struct utsname uts;
12985 setvar0("HOSTNAME", uts.nodename);
12988 p = lookupvar("PWD");
12990 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12991 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13001 //usage:#define ash_trivial_usage
13002 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13003 //usage:#define ash_full_usage "\n\n"
13004 //usage: "Unix shell interpreter"
13006 //usage:#if ENABLE_FEATURE_SH_IS_ASH
13007 //usage:# define sh_trivial_usage ash_trivial_usage
13008 //usage:# define sh_full_usage ash_full_usage
13010 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
13011 //usage:# define bash_trivial_usage ash_trivial_usage
13012 //usage:# define bash_full_usage ash_full_usage
13016 * Process the shell command line arguments.
13019 procargs(char **argv)
13022 const char *xminusc;
13027 /* if (xargv[0]) - mmm, this is always true! */
13029 for (i = 0; i < NOPTS; i++)
13032 if (options(/*cmdline:*/ 1)) {
13033 /* it already printed err message */
13034 raise_exception(EXERROR);
13038 if (*xargv == NULL) {
13040 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13043 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13047 for (i = 0; i < NOPTS; i++)
13048 if (optlist[i] == 2)
13053 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13058 } else if (!sflag) {
13059 setinputfile(*xargv, 0);
13062 commandname = arg0;
13065 shellparam.p = xargv;
13066 #if ENABLE_ASH_GETOPTS
13067 shellparam.optind = 1;
13068 shellparam.optoff = -1;
13070 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13072 shellparam.nparam++;
13079 * Read /etc/profile or .profile.
13082 read_profile(const char *name)
13086 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13095 * This routine is called when an error or an interrupt occurs in an
13096 * interactive shell and control is returned to the main command loop.
13104 /* from input.c: */
13105 g_parsefile->left_in_buffer = 0;
13106 g_parsefile->left_in_line = 0; /* clear input buffer */
13108 /* from parser.c: */
13111 /* from redir.c: */
13112 clearredir(/*drop:*/ 0);
13116 static short profile_buf[16384];
13117 extern int etext();
13121 * Main routine. We initialize things, parse the arguments, execute
13122 * profiles if we're a login shell, and then call cmdloop to execute
13123 * commands. The setjmp call sets up the location to jump to when an
13124 * exception occurs. When an exception occurs the variable "state"
13125 * is used to figure out how far we had gotten.
13127 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13128 int ash_main(int argc UNUSED_PARAM, char **argv)
13130 const char *shinit;
13131 volatile smallint state;
13132 struct jmploc jmploc;
13133 struct stackmark smark;
13135 /* Initialize global data */
13139 #if ENABLE_ASH_ALIAS
13145 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13148 #if ENABLE_FEATURE_EDITING
13149 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13152 if (setjmp(jmploc.loc)) {
13158 e = exception_type;
13162 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13166 newline_and_flush(stderr);
13169 popstackmark(&smark);
13170 FORCE_INT_ON; /* enable interrupts */
13179 exception_handler = &jmploc;
13182 TRACE(("Shell args: "));
13183 trace_puts_args(argv);
13185 rootpid = getpid();
13188 setstackmark(&smark);
13191 if (argv[0] && argv[0][0] == '-')
13197 read_profile("/etc/profile");
13200 hp = lookupvar("HOME");
13202 hp = concat_path_file(hp, ".profile");
13211 getuid() == geteuid() && getgid() == getegid() &&
13215 shinit = lookupvar("ENV");
13216 if (shinit != NULL && *shinit != '\0') {
13217 read_profile(shinit);
13223 /* evalstring pushes parsefile stack.
13224 * Ensure we don't falsely claim that 0 (stdin)
13225 * is one of stacked source fds.
13226 * Testcase: ash -c 'exec 1>&0' must not complain. */
13227 // if (!sflag) g_parsefile->pf_fd = -1;
13228 // ^^ not necessary since now we special-case fd 0
13229 // in is_hidden_fd() to not be considered "hidden fd"
13230 evalstring(minusc, 0);
13233 if (sflag || minusc == NULL) {
13234 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13236 const char *hp = lookupvar("HISTFILE");
13238 hp = lookupvar("HOME");
13240 hp = concat_path_file(hp, ".ash_history");
13241 setvar0("HISTFILE", hp);
13243 hp = lookupvar("HISTFILE");
13247 line_input_state->hist_file = hp;
13248 # if ENABLE_FEATURE_SH_HISTFILESIZE
13249 hp = lookupvar("HISTFILESIZE");
13250 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13254 state4: /* XXX ??? - why isn't this before the "if" statement */
13262 extern void _mcleanup(void);
13266 TRACE(("End of main reached\n"));
13273 * Copyright (c) 1989, 1991, 1993, 1994
13274 * The Regents of the University of California. All rights reserved.
13276 * This code is derived from software contributed to Berkeley by
13277 * Kenneth Almquist.
13279 * Redistribution and use in source and binary forms, with or without
13280 * modification, are permitted provided that the following conditions
13282 * 1. Redistributions of source code must retain the above copyright
13283 * notice, this list of conditions and the following disclaimer.
13284 * 2. Redistributions in binary form must reproduce the above copyright
13285 * notice, this list of conditions and the following disclaimer in the
13286 * documentation and/or other materials provided with the distribution.
13287 * 3. Neither the name of the University nor the names of its contributors
13288 * may be used to endorse or promote products derived from this software
13289 * without specific prior written permission.
13291 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13292 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13293 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13294 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13295 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13296 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13297 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13298 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13299 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13300 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF