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 the GPL v2 or later, see the file LICENSE in this tarball.
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, debugging info will be written to ./trace and
27 * a quit signal will generate a core dump.
30 /* Tweak debug output verbosity here */
37 #define JOBS ENABLE_ASH_JOB_CONTROL
39 #include "busybox.h" /* for applet_names */
43 #include <sys/times.h>
45 #include "shell_common.h"
47 #if ENABLE_ASH_RANDOM_SUPPORT
50 # define CLEAR_RANDOM_T(rnd) ((void)0)
53 #define SKIP_definitions 1
54 #include "applet_tables.h"
55 #undef SKIP_definitions
57 /* STANDALONE does not make sense, and won't compile */
58 # undef CONFIG_FEATURE_SH_STANDALONE
59 # undef ENABLE_FEATURE_SH_STANDALONE
60 # undef IF_FEATURE_SH_STANDALONE
61 # undef IF_NOT_FEATURE_SH_STANDALONE
62 # define ENABLE_FEATURE_SH_STANDALONE 0
63 # define IF_FEATURE_SH_STANDALONE(...)
64 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
68 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
72 # error "Do not even bother, ash will not run on NOMMU machine"
76 /* ============ Hash table sizes. Configurable. */
80 #define CMDTABLESIZE 31 /* should be prime */
83 /* ============ Shell options */
85 static const char *const optletters_optnames[] = {
100 #if ENABLE_ASH_BASH_COMPAT
109 #define optletters(n) optletters_optnames[n][0]
110 #define optnames(n) (optletters_optnames[n] + 1)
112 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
115 /* ============ Misc data */
117 #define msg_illnum "Illegal number: %s"
120 * We enclose jmp_buf in a structure so that we can declare pointers to
121 * jump locations. The global variable handler contains the location to
122 * jump to when an exception occurs, and the global variable exception_type
123 * contains a code identifying the exception. To implement nested
124 * exception handlers, the user should save the value of handler on entry
125 * to an inner scope, set handler to point to a jmploc structure for the
126 * inner scope, and restore handler on exit from the scope.
132 struct globals_misc {
133 /* pid of main shell */
135 /* shell level: 0 for the main shell, 1 for its children, and so on */
137 #define rootshell (!shlvl)
138 char *minusc; /* argument to -c option */
140 char *curdir; // = nullstr; /* current working directory */
141 char *physdir; // = nullstr; /* physical working directory */
143 char *arg0; /* value of $0 */
145 struct jmploc *exception_handler;
147 volatile int suppress_int; /* counter */
148 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
149 /* last pending signal */
150 volatile /*sig_atomic_t*/ smallint pending_sig;
151 smallint exception_type; /* kind of exception (0..5) */
153 #define EXINT 0 /* SIGINT received */
154 #define EXERROR 1 /* a generic error */
155 #define EXSHELLPROC 2 /* execute a shell procedure */
156 #define EXEXEC 3 /* command execution failed */
157 #define EXEXIT 4 /* exit the shell */
158 #define EXSIG 5 /* trapped signal in wait(1) */
161 char nullstr[1]; /* zero length string */
164 #define eflag optlist[0]
165 #define fflag optlist[1]
166 #define Iflag optlist[2]
167 #define iflag optlist[3]
168 #define mflag optlist[4]
169 #define nflag optlist[5]
170 #define sflag optlist[6]
171 #define xflag optlist[7]
172 #define vflag optlist[8]
173 #define Cflag optlist[9]
174 #define aflag optlist[10]
175 #define bflag optlist[11]
176 #define uflag optlist[12]
177 #define viflag optlist[13]
178 #if ENABLE_ASH_BASH_COMPAT
179 # define pipefail optlist[14]
184 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
185 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
188 /* trap handler commands */
190 * Sigmode records the current value of the signal handlers for the various
191 * modes. A value of zero means that the current handler is not known.
192 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
194 char sigmode[NSIG - 1];
195 #define S_DFL 1 /* default signal handling (SIG_DFL) */
196 #define S_CATCH 2 /* signal is caught */
197 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
198 #define S_HARD_IGN 4 /* signal is ignored permenantly */
200 /* indicates specified signal received */
201 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
202 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
204 char **trap_ptr; /* used only by "trap hack" */
206 /* Rarely referenced stuff */
207 #if ENABLE_ASH_RANDOM_SUPPORT
210 pid_t backgndpid; /* pid of last background process */
211 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
213 extern struct globals_misc *const ash_ptr_to_globals_misc;
214 #define G_misc (*ash_ptr_to_globals_misc)
215 #define rootpid (G_misc.rootpid )
216 #define shlvl (G_misc.shlvl )
217 #define minusc (G_misc.minusc )
218 #define curdir (G_misc.curdir )
219 #define physdir (G_misc.physdir )
220 #define arg0 (G_misc.arg0 )
221 #define exception_handler (G_misc.exception_handler)
222 #define exception_type (G_misc.exception_type )
223 #define suppress_int (G_misc.suppress_int )
224 #define pending_int (G_misc.pending_int )
225 #define pending_sig (G_misc.pending_sig )
226 #define isloginsh (G_misc.isloginsh )
227 #define nullstr (G_misc.nullstr )
228 #define optlist (G_misc.optlist )
229 #define sigmode (G_misc.sigmode )
230 #define gotsig (G_misc.gotsig )
231 #define may_have_traps (G_misc.may_have_traps )
232 #define trap (G_misc.trap )
233 #define trap_ptr (G_misc.trap_ptr )
234 #define random_gen (G_misc.random_gen )
235 #define backgndpid (G_misc.backgndpid )
236 #define job_warning (G_misc.job_warning)
237 #define INIT_G_misc() do { \
238 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
246 /* ============ DEBUG */
248 static void trace_printf(const char *fmt, ...);
249 static void trace_vprintf(const char *fmt, va_list va);
250 # define TRACE(param) trace_printf param
251 # define TRACEV(param) trace_vprintf param
252 # define close(fd) do { \
254 if (close(dfd) < 0) \
255 bb_error_msg("bug on %d: closing %d(0x%x)", \
256 __LINE__, dfd, dfd); \
259 # define TRACE(param)
260 # define TRACEV(param)
264 /* ============ Utility functions */
265 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
267 static int isdigit_str9(const char *str)
269 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
270 while (--maxlen && isdigit(*str))
272 return (*str == '\0');
275 static const char *var_end(const char *var)
284 /* ============ Interrupts / exceptions */
286 * These macros allow the user to suspend the handling of interrupt signals
287 * over a period of time. This is similar to SIGHOLD or to sigblock, but
288 * much more efficient and portable. (But hacking the kernel is so much
289 * more fun than worrying about efficiency and portability. :-))
291 #define INT_OFF do { \
297 * Called to raise an exception. Since C doesn't include exceptions, we
298 * just do a longjmp to the exception handler. The type of exception is
299 * stored in the global variable "exception_type".
301 static void raise_exception(int) NORETURN;
303 raise_exception(int e)
306 if (exception_handler == NULL)
311 longjmp(exception_handler->loc, 1);
314 #define raise_exception(e) do { \
315 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
316 raise_exception(e); \
321 * Called from trap.c when a SIGINT is received. (If the user specifies
322 * that SIGINT is to be trapped or ignored using the trap builtin, then
323 * this routine is not called.) Suppressint is nonzero when interrupts
324 * are held using the INT_OFF macro. (The test for iflag is just
325 * defensive programming.)
327 static void raise_interrupt(void) NORETURN;
329 raise_interrupt(void)
334 /* Signal is not automatically unmasked after it is raised,
335 * do it ourself - unmask all signals */
336 sigprocmask_allsigs(SIG_UNBLOCK);
337 /* pending_sig = 0; - now done in signal_handler() */
340 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
341 if (!(rootshell && iflag)) {
342 /* Kill ourself with SIGINT */
343 signal(SIGINT, SIG_DFL);
348 raise_exception(ex_type);
352 #define raise_interrupt() do { \
353 TRACE(("raising interrupt on line %d\n", __LINE__)); \
358 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
362 if (--suppress_int == 0 && pending_int) {
366 #define INT_ON int_on()
367 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
375 #define FORCE_INT_ON force_int_on()
377 #define SAVE_INT(v) ((v) = suppress_int)
379 #define RESTORE_INT(v) do { \
381 suppress_int = (v); \
382 if (suppress_int == 0 && pending_int) \
387 /* ============ Stdout/stderr output */
390 outstr(const char *p, FILE *file)
398 flush_stdout_stderr(void)
406 outcslow(int c, FILE *dest)
414 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
416 out1fmt(const char *fmt, ...)
423 r = vprintf(fmt, ap);
429 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
431 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
438 ret = vsnprintf(outbuf, length, fmt, ap);
445 out1str(const char *p)
451 out2str(const char *p)
454 flush_stdout_stderr();
458 /* ============ Parser structures */
460 /* control characters in argument strings */
461 #define CTL_FIRST CTLESC
462 #define CTLESC ((unsigned char)'\201') /* escape next character */
463 #define CTLVAR ((unsigned char)'\202') /* variable defn */
464 #define CTLENDVAR ((unsigned char)'\203')
465 #define CTLBACKQ ((unsigned char)'\204')
466 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
467 /* CTLBACKQ | CTLQUOTE == '\205' */
468 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
469 #define CTLENDARI ((unsigned char)'\207')
470 #define CTLQUOTEMARK ((unsigned char)'\210')
471 #define CTL_LAST CTLQUOTEMARK
473 /* variable substitution byte (follows CTLVAR) */
474 #define VSTYPE 0x0f /* type of variable substitution */
475 #define VSNUL 0x10 /* colon--treat the empty string as unset */
476 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
478 /* values of VSTYPE field */
479 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
480 #define VSMINUS 0x2 /* ${var-text} */
481 #define VSPLUS 0x3 /* ${var+text} */
482 #define VSQUESTION 0x4 /* ${var?message} */
483 #define VSASSIGN 0x5 /* ${var=text} */
484 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
485 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
486 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
487 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
488 #define VSLENGTH 0xa /* ${#var} */
489 #if ENABLE_ASH_BASH_COMPAT
490 #define VSSUBSTR 0xc /* ${var:position:length} */
491 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
492 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
495 static const char dolatstr[] ALIGN1 = {
496 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
516 #if ENABLE_ASH_BASH_COMPAT
533 smallint type; /* Nxxxx */
536 union node *redirect;
541 smallint pipe_backgnd;
542 struct nodelist *cmdlist;
548 union node *redirect;
561 union node *elsepart;
588 struct nodelist *backquote;
591 /* nfile and ndup layout must match!
592 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
593 * that it is actually NTO2 (>&file), and change its type.
610 char *_unused_expfname;
629 struct nredir nredir;
630 struct nbinary nbinary;
634 struct nclist nclist;
643 * NODE_EOF is returned by parsecmd when it encounters an end of file.
644 * It must be distinct from NULL.
646 #define NODE_EOF ((union node *) -1L)
649 struct nodelist *next;
662 freefunc(struct funcnode *f)
664 if (f && --f->count < 0)
669 /* ============ Debugging output */
673 static FILE *tracefile;
676 trace_printf(const char *fmt, ...)
683 fprintf(tracefile, "%u ", (int) time(NULL));
685 fprintf(tracefile, "[%u] ", (int) getpid());
687 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
689 vfprintf(tracefile, fmt, va);
694 trace_vprintf(const char *fmt, va_list va)
699 fprintf(tracefile, "%u ", (int) time(NULL));
701 fprintf(tracefile, "[%u] ", (int) getpid());
703 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
704 vfprintf(tracefile, fmt, va);
708 trace_puts(const char *s)
716 trace_puts_quoted(char *s)
723 putc('"', tracefile);
724 for (p = s; *p; p++) {
725 switch ((unsigned char)*p) {
726 case '\n': c = 'n'; goto backslash;
727 case '\t': c = 't'; goto backslash;
728 case '\r': c = 'r'; goto backslash;
729 case '\"': c = '\"'; goto backslash;
730 case '\\': c = '\\'; goto backslash;
731 case CTLESC: c = 'e'; goto backslash;
732 case CTLVAR: c = 'v'; goto backslash;
733 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
734 case CTLBACKQ: c = 'q'; goto backslash;
735 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
737 putc('\\', tracefile);
741 if (*p >= ' ' && *p <= '~')
744 putc('\\', tracefile);
745 putc((*p >> 6) & 03, tracefile);
746 putc((*p >> 3) & 07, tracefile);
747 putc(*p & 07, tracefile);
752 putc('"', tracefile);
756 trace_puts_args(char **ap)
763 trace_puts_quoted(*ap);
765 putc('\n', tracefile);
768 putc(' ', tracefile);
783 /* leave open because libedit might be using it */
786 strcpy(s, "./trace");
788 if (!freopen(s, "a", tracefile)) {
789 fprintf(stderr, "Can't re-open %s\n", s);
794 tracefile = fopen(s, "a");
795 if (tracefile == NULL) {
796 fprintf(stderr, "Can't open %s\n", s);
802 flags = fcntl(fileno(tracefile), F_GETFL);
804 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
806 setlinebuf(tracefile);
807 fputs("\nTracing started.\n", tracefile);
811 indent(int amount, char *pfx, FILE *fp)
815 for (i = 0; i < amount; i++) {
816 if (pfx && i == amount - 1)
822 /* little circular references here... */
823 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
826 sharg(union node *arg, FILE *fp)
829 struct nodelist *bqlist;
830 unsigned char subtype;
832 if (arg->type != NARG) {
833 out1fmt("<node type %d>\n", arg->type);
836 bqlist = arg->narg.backquote;
837 for (p = arg->narg.text; *p; p++) {
838 switch ((unsigned char)*p) {
846 if (subtype == VSLENGTH)
855 switch (subtype & VSTYPE) {
888 out1fmt("<subtype %d>", subtype);
895 case CTLBACKQ|CTLQUOTE:
898 shtree(bqlist->n, -1, NULL, fp);
909 shcmd(union node *cmd, FILE *fp)
917 for (np = cmd->ncmd.args; np; np = np->narg.next) {
923 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
927 switch (np->nfile.type) {
928 case NTO: s = ">>"+1; dftfd = 1; break;
929 case NCLOBBER: s = ">|"; dftfd = 1; break;
930 case NAPPEND: s = ">>"; dftfd = 1; break;
931 #if ENABLE_ASH_BASH_COMPAT
934 case NTOFD: s = ">&"; dftfd = 1; break;
935 case NFROM: s = "<"; break;
936 case NFROMFD: s = "<&"; break;
937 case NFROMTO: s = "<>"; break;
938 default: s = "*error*"; break;
940 if (np->nfile.fd != dftfd)
941 fprintf(fp, "%d", np->nfile.fd);
943 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
944 fprintf(fp, "%d", np->ndup.dupfd);
946 sharg(np->nfile.fname, fp);
953 shtree(union node *n, int ind, char *pfx, FILE *fp)
961 indent(ind, pfx, fp);
978 shtree(n->nbinary.ch1, ind, NULL, fp);
981 shtree(n->nbinary.ch2, ind, NULL, fp);
989 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
990 shtree(lp->n, 0, NULL, fp);
994 if (n->npipe.pipe_backgnd)
1000 fprintf(fp, "<node type %d>", n->type);
1008 showtree(union node *n)
1010 trace_puts("showtree called\n");
1011 shtree(n, 1, NULL, stderr);
1017 /* ============ Parser data */
1020 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1023 struct strlist *next;
1030 struct strpush *prev; /* preceding string on stack */
1032 int prev_left_in_line;
1033 #if ENABLE_ASH_ALIAS
1034 struct alias *ap; /* if push was associated with an alias */
1036 char *string; /* remember the string since it may change */
1040 struct parsefile *prev; /* preceding file on stack */
1041 int linno; /* current line */
1042 int pf_fd; /* file descriptor (or -1 if string) */
1043 int left_in_line; /* number of chars left in this line */
1044 int left_in_buffer; /* number of chars left in this buffer past the line */
1045 char *next_to_pgetc; /* next char in buffer */
1046 char *buf; /* input buffer */
1047 struct strpush *strpush; /* for pushing strings at this level */
1048 struct strpush basestrpush; /* so pushing one is fast */
1051 static struct parsefile basepf; /* top level input file */
1052 static struct parsefile *g_parsefile = &basepf; /* current input file */
1053 static int startlinno; /* line # where last token started */
1054 static char *commandname; /* currently executing command */
1055 static struct strlist *cmdenviron; /* environment for builtin command */
1056 static uint8_t exitstatus; /* exit status of last command */
1059 /* ============ Message printing */
1062 ash_vmsg(const char *msg, va_list ap)
1064 fprintf(stderr, "%s: ", arg0);
1066 if (strcmp(arg0, commandname))
1067 fprintf(stderr, "%s: ", commandname);
1068 if (!iflag || g_parsefile->pf_fd > 0)
1069 fprintf(stderr, "line %d: ", startlinno);
1071 vfprintf(stderr, msg, ap);
1072 outcslow('\n', stderr);
1076 * Exverror is called to raise the error exception. If the second argument
1077 * is not NULL then error prints an error message using printf style
1078 * formatting. It then raises the error exception.
1080 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1082 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1086 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1088 TRACE(("\") pid=%d\n", getpid()));
1090 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1095 flush_stdout_stderr();
1096 raise_exception(cond);
1100 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1102 ash_msg_and_raise_error(const char *msg, ...)
1107 ash_vmsg_and_raise(EXERROR, msg, ap);
1112 static void raise_error_syntax(const char *) NORETURN;
1114 raise_error_syntax(const char *msg)
1116 ash_msg_and_raise_error("syntax error: %s", msg);
1120 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1122 ash_msg_and_raise(int cond, const char *msg, ...)
1127 ash_vmsg_and_raise(cond, msg, ap);
1133 * error/warning routines for external builtins
1136 ash_msg(const char *fmt, ...)
1146 * Return a string describing an error. The returned string may be a
1147 * pointer to a static buffer that will be overwritten on the next call.
1148 * Action describes the operation that got the error.
1151 errmsg(int e, const char *em)
1153 if (e == ENOENT || e == ENOTDIR) {
1160 /* ============ Memory allocation */
1163 /* I consider these wrappers nearly useless:
1164 * ok, they return you to nearest exception handler, but
1165 * how much memory do you leak in the process, making
1166 * memory starvation worse?
1169 ckrealloc(void * p, size_t nbytes)
1171 p = realloc(p, nbytes);
1173 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1178 ckmalloc(size_t nbytes)
1180 return ckrealloc(NULL, nbytes);
1184 ckzalloc(size_t nbytes)
1186 return memset(ckmalloc(nbytes), 0, nbytes);
1190 ckstrdup(const char *s)
1192 char *p = strdup(s);
1194 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1198 /* Using bbox equivalents. They exit if out of memory */
1199 # define ckrealloc xrealloc
1200 # define ckmalloc xmalloc
1201 # define ckzalloc xzalloc
1202 # define ckstrdup xstrdup
1206 * It appears that grabstackstr() will barf with such alignments
1207 * because stalloc() will return a string allocated in a new stackblock.
1209 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1211 /* Most machines require the value returned from malloc to be aligned
1212 * in some way. The following macro will get this right
1213 * on many machines. */
1214 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1215 /* Minimum size of a block */
1216 MINSIZE = SHELL_ALIGN(504),
1219 struct stack_block {
1220 struct stack_block *prev;
1221 char space[MINSIZE];
1225 struct stack_block *stackp;
1228 struct stackmark *marknext;
1232 struct globals_memstack {
1233 struct stack_block *g_stackp; // = &stackbase;
1234 struct stackmark *markp;
1235 char *g_stacknxt; // = stackbase.space;
1236 char *sstrend; // = stackbase.space + MINSIZE;
1237 size_t g_stacknleft; // = MINSIZE;
1238 int herefd; // = -1;
1239 struct stack_block stackbase;
1241 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1242 #define G_memstack (*ash_ptr_to_globals_memstack)
1243 #define g_stackp (G_memstack.g_stackp )
1244 #define markp (G_memstack.markp )
1245 #define g_stacknxt (G_memstack.g_stacknxt )
1246 #define sstrend (G_memstack.sstrend )
1247 #define g_stacknleft (G_memstack.g_stacknleft)
1248 #define herefd (G_memstack.herefd )
1249 #define stackbase (G_memstack.stackbase )
1250 #define INIT_G_memstack() do { \
1251 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1253 g_stackp = &stackbase; \
1254 g_stacknxt = stackbase.space; \
1255 g_stacknleft = MINSIZE; \
1256 sstrend = stackbase.space + MINSIZE; \
1261 #define stackblock() ((void *)g_stacknxt)
1262 #define stackblocksize() g_stacknleft
1265 * Parse trees for commands are allocated in lifo order, so we use a stack
1266 * to make this more efficient, and also to avoid all sorts of exception
1267 * handling code to handle interrupts in the middle of a parse.
1269 * The size 504 was chosen because the Ultrix malloc handles that size
1273 stalloc(size_t nbytes)
1278 aligned = SHELL_ALIGN(nbytes);
1279 if (aligned > g_stacknleft) {
1282 struct stack_block *sp;
1284 blocksize = aligned;
1285 if (blocksize < MINSIZE)
1286 blocksize = MINSIZE;
1287 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1288 if (len < blocksize)
1289 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1292 sp->prev = g_stackp;
1293 g_stacknxt = sp->space;
1294 g_stacknleft = blocksize;
1295 sstrend = g_stacknxt + blocksize;
1300 g_stacknxt += aligned;
1301 g_stacknleft -= aligned;
1306 stzalloc(size_t nbytes)
1308 return memset(stalloc(nbytes), 0, nbytes);
1315 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1316 write(STDERR_FILENO, "stunalloc\n", 10);
1320 g_stacknleft += g_stacknxt - (char *)p;
1325 * Like strdup but works with the ash stack.
1328 ststrdup(const char *p)
1330 size_t len = strlen(p) + 1;
1331 return memcpy(stalloc(len), p, len);
1335 setstackmark(struct stackmark *mark)
1337 mark->stackp = g_stackp;
1338 mark->stacknxt = g_stacknxt;
1339 mark->stacknleft = g_stacknleft;
1340 mark->marknext = markp;
1345 popstackmark(struct stackmark *mark)
1347 struct stack_block *sp;
1353 markp = mark->marknext;
1354 while (g_stackp != mark->stackp) {
1356 g_stackp = sp->prev;
1359 g_stacknxt = mark->stacknxt;
1360 g_stacknleft = mark->stacknleft;
1361 sstrend = mark->stacknxt + mark->stacknleft;
1366 * When the parser reads in a string, it wants to stick the string on the
1367 * stack and only adjust the stack pointer when it knows how big the
1368 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1369 * of space on top of the stack and stackblocklen returns the length of
1370 * this block. Growstackblock will grow this space by at least one byte,
1371 * possibly moving it (like realloc). Grabstackblock actually allocates the
1372 * part of the block that has been used.
1375 growstackblock(void)
1379 newlen = g_stacknleft * 2;
1380 if (newlen < g_stacknleft)
1381 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1385 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1386 struct stack_block *oldstackp;
1387 struct stackmark *xmark;
1388 struct stack_block *sp;
1389 struct stack_block *prevstackp;
1393 oldstackp = g_stackp;
1395 prevstackp = sp->prev;
1396 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1397 sp = ckrealloc(sp, grosslen);
1398 sp->prev = prevstackp;
1400 g_stacknxt = sp->space;
1401 g_stacknleft = newlen;
1402 sstrend = sp->space + newlen;
1405 * Stack marks pointing to the start of the old block
1406 * must be relocated to point to the new block
1409 while (xmark != NULL && xmark->stackp == oldstackp) {
1410 xmark->stackp = g_stackp;
1411 xmark->stacknxt = g_stacknxt;
1412 xmark->stacknleft = g_stacknleft;
1413 xmark = xmark->marknext;
1417 char *oldspace = g_stacknxt;
1418 size_t oldlen = g_stacknleft;
1419 char *p = stalloc(newlen);
1421 /* free the space we just allocated */
1422 g_stacknxt = memcpy(p, oldspace, oldlen);
1423 g_stacknleft += newlen;
1428 grabstackblock(size_t len)
1430 len = SHELL_ALIGN(len);
1432 g_stacknleft -= len;
1436 * The following routines are somewhat easier to use than the above.
1437 * The user declares a variable of type STACKSTR, which may be declared
1438 * to be a register. The macro STARTSTACKSTR initializes things. Then
1439 * the user uses the macro STPUTC to add characters to the string. In
1440 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1441 * grown as necessary. When the user is done, she can just leave the
1442 * string there and refer to it using stackblock(). Or she can allocate
1443 * the space for it using grabstackstr(). If it is necessary to allow
1444 * someone else to use the stack temporarily and then continue to grow
1445 * the string, the user should use grabstack to allocate the space, and
1446 * then call ungrabstr(p) to return to the previous mode of operation.
1448 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1449 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1450 * is space for at least one character.
1455 size_t len = stackblocksize();
1456 if (herefd >= 0 && len >= 1024) {
1457 full_write(herefd, stackblock(), len);
1458 return stackblock();
1461 return (char *)stackblock() + len;
1465 * Called from CHECKSTRSPACE.
1468 makestrspace(size_t newlen, char *p)
1470 size_t len = p - g_stacknxt;
1471 size_t size = stackblocksize();
1476 size = stackblocksize();
1478 if (nleft >= newlen)
1482 return (char *)stackblock() + len;
1486 stack_nputstr(const char *s, size_t n, char *p)
1488 p = makestrspace(n, p);
1489 p = (char *)memcpy(p, s, n) + n;
1494 stack_putstr(const char *s, char *p)
1496 return stack_nputstr(s, strlen(s), p);
1500 _STPUTC(int c, char *p)
1508 #define STARTSTACKSTR(p) ((p) = stackblock())
1509 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1510 #define CHECKSTRSPACE(n, p) do { \
1513 size_t m = sstrend - q; \
1515 (p) = makestrspace(l, q); \
1517 #define USTPUTC(c, p) (*(p)++ = (c))
1518 #define STACKSTRNUL(p) do { \
1519 if ((p) == sstrend) \
1520 (p) = growstackstr(); \
1523 #define STUNPUTC(p) (--(p))
1524 #define STTOPC(p) ((p)[-1])
1525 #define STADJUST(amount, p) ((p) += (amount))
1527 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1528 #define ungrabstackstr(s, p) stunalloc(s)
1529 #define stackstrend() ((void *)sstrend)
1532 /* ============ String helpers */
1535 * prefix -- see if pfx is a prefix of string.
1538 prefix(const char *string, const char *pfx)
1541 if (*pfx++ != *string++)
1544 return (char *) string;
1548 * Check for a valid number. This should be elsewhere.
1551 is_number(const char *p)
1556 } while (*++p != '\0');
1561 * Convert a string of digits to an integer, printing an error message on
1565 number(const char *s)
1568 ash_msg_and_raise_error(msg_illnum, s);
1573 * Produce a possibly single quoted string suitable as input to the shell.
1574 * The return string is allocated on the stack.
1577 single_quote(const char *s)
1587 len = strchrnul(s, '\'') - s;
1589 q = p = makestrspace(len + 3, p);
1592 q = (char *)memcpy(q, s, len) + len;
1601 do len++; while (*++s == '\'');
1603 q = p = makestrspace(len + 3, p);
1606 q = (char *)memcpy(q, s - len, len) + len;
1614 return stackblock();
1618 /* ============ nextopt */
1620 static char **argptr; /* argument list for builtin commands */
1621 static char *optionarg; /* set by nextopt (like getopt) */
1622 static char *optptr; /* used by nextopt */
1625 * XXX - should get rid of. Have all builtins use getopt(3).
1626 * The library getopt must have the BSD extension static variable
1627 * "optreset", otherwise it can't be used within the shell safely.
1629 * Standard option processing (a la getopt) for builtin routines.
1630 * The only argument that is passed to nextopt is the option string;
1631 * the other arguments are unnecessary. It returns the character,
1632 * or '\0' on end of input.
1635 nextopt(const char *optstring)
1642 if (p == NULL || *p == '\0') {
1643 /* We ate entire "-param", take next one */
1649 if (*++p == '\0') /* just "-" ? */
1652 if (LONE_DASH(p)) /* "--" ? */
1654 /* p => next "-param" */
1656 /* p => some option char in the middle of a "-param" */
1658 for (q = optstring; *q != c;) {
1660 ash_msg_and_raise_error("illegal option -%c", c);
1668 ash_msg_and_raise_error("no arg for -%c option", c);
1678 /* ============ Shell variables */
1681 * The parsefile structure pointed to by the global variable parsefile
1682 * contains information about the current file being read.
1685 int nparam; /* # of positional parameters (without $0) */
1686 #if ENABLE_ASH_GETOPTS
1687 int optind; /* next parameter to be processed by getopts */
1688 int optoff; /* used by getopts */
1690 unsigned char malloced; /* if parameter list dynamically allocated */
1691 char **p; /* parameter list */
1695 * Free the list of positional parameters.
1698 freeparam(volatile struct shparam *param)
1700 if (param->malloced) {
1702 ap = ap1 = param->p;
1709 #if ENABLE_ASH_GETOPTS
1710 static void FAST_FUNC getoptsreset(const char *value);
1714 struct var *next; /* next entry in hash list */
1715 int flags; /* flags are defined above */
1716 const char *var_text; /* name=value */
1717 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1718 /* the variable gets set/unset */
1722 struct localvar *next; /* next local variable in list */
1723 struct var *vp; /* the variable that was made local */
1724 int flags; /* saved flags */
1725 const char *text; /* saved text */
1729 #define VEXPORT 0x01 /* variable is exported */
1730 #define VREADONLY 0x02 /* variable cannot be modified */
1731 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1732 #define VTEXTFIXED 0x08 /* text is statically allocated */
1733 #define VSTACK 0x10 /* text is allocated on the stack */
1734 #define VUNSET 0x20 /* the variable is not set */
1735 #define VNOFUNC 0x40 /* don't call the callback function */
1736 #define VNOSET 0x80 /* do not set variable - just readonly test */
1737 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1738 #if ENABLE_ASH_RANDOM_SUPPORT
1739 # define VDYNAMIC 0x200 /* dynamic variable */
1745 /* Need to be before varinit_data[] */
1746 #if ENABLE_LOCALE_SUPPORT
1747 static void FAST_FUNC
1748 change_lc_all(const char *value)
1750 if (value && *value != '\0')
1751 setlocale(LC_ALL, value);
1753 static void FAST_FUNC
1754 change_lc_ctype(const char *value)
1756 if (value && *value != '\0')
1757 setlocale(LC_CTYPE, value);
1761 static void chkmail(void);
1762 static void changemail(const char *) FAST_FUNC;
1764 static void changepath(const char *) FAST_FUNC;
1765 #if ENABLE_ASH_RANDOM_SUPPORT
1766 static void change_random(const char *) FAST_FUNC;
1769 static const struct {
1771 const char *var_text;
1772 void (*var_func)(const char *) FAST_FUNC;
1773 } varinit_data[] = {
1774 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1776 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1777 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1779 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1780 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1781 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1782 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1783 #if ENABLE_ASH_GETOPTS
1784 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1786 #if ENABLE_ASH_RANDOM_SUPPORT
1787 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1789 #if ENABLE_LOCALE_SUPPORT
1790 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1791 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1793 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1794 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1800 struct globals_var {
1801 struct shparam shellparam; /* $@ current positional parameters */
1802 struct redirtab *redirlist;
1804 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1805 struct var *vartab[VTABSIZE];
1806 struct var varinit[ARRAY_SIZE(varinit_data)];
1808 extern struct globals_var *const ash_ptr_to_globals_var;
1809 #define G_var (*ash_ptr_to_globals_var)
1810 #define shellparam (G_var.shellparam )
1811 //#define redirlist (G_var.redirlist )
1812 #define g_nullredirs (G_var.g_nullredirs )
1813 #define preverrout_fd (G_var.preverrout_fd)
1814 #define vartab (G_var.vartab )
1815 #define varinit (G_var.varinit )
1816 #define INIT_G_var() do { \
1818 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1820 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1821 varinit[i].flags = varinit_data[i].flags; \
1822 varinit[i].var_text = varinit_data[i].var_text; \
1823 varinit[i].var_func = varinit_data[i].var_func; \
1827 #define vifs varinit[0]
1829 # define vmail (&vifs)[1]
1830 # define vmpath (&vmail)[1]
1831 # define vpath (&vmpath)[1]
1833 # define vpath (&vifs)[1]
1835 #define vps1 (&vpath)[1]
1836 #define vps2 (&vps1)[1]
1837 #define vps4 (&vps2)[1]
1838 #if ENABLE_ASH_GETOPTS
1839 # define voptind (&vps4)[1]
1840 # if ENABLE_ASH_RANDOM_SUPPORT
1841 # define vrandom (&voptind)[1]
1844 # if ENABLE_ASH_RANDOM_SUPPORT
1845 # define vrandom (&vps4)[1]
1850 * The following macros access the values of the above variables.
1851 * They have to skip over the name. They return the null string
1852 * for unset variables.
1854 #define ifsval() (vifs.var_text + 4)
1855 #define ifsset() ((vifs.flags & VUNSET) == 0)
1857 # define mailval() (vmail.var_text + 5)
1858 # define mpathval() (vmpath.var_text + 9)
1859 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1861 #define pathval() (vpath.var_text + 5)
1862 #define ps1val() (vps1.var_text + 4)
1863 #define ps2val() (vps2.var_text + 4)
1864 #define ps4val() (vps4.var_text + 4)
1865 #if ENABLE_ASH_GETOPTS
1866 # define optindval() (voptind.var_text + 7)
1870 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1871 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1873 #if ENABLE_ASH_GETOPTS
1874 static void FAST_FUNC
1875 getoptsreset(const char *value)
1877 shellparam.optind = number(value);
1878 shellparam.optoff = -1;
1883 * Return of a legal variable name (a letter or underscore followed by zero or
1884 * more letters, underscores, and digits).
1886 static char* FAST_FUNC
1887 endofname(const char *name)
1895 if (!is_in_name(*p))
1902 * Compares two strings up to the first = or '\0'. The first
1903 * string must be terminated by '='; the second may be terminated by
1904 * either '=' or '\0'.
1907 varcmp(const char *p, const char *q)
1911 while ((c = *p) == (d = *q)) {
1926 * Find the appropriate entry in the hash table from the name.
1928 static struct var **
1929 hashvar(const char *p)
1933 hashval = ((unsigned char) *p) << 4;
1934 while (*p && *p != '=')
1935 hashval += (unsigned char) *p++;
1936 return &vartab[hashval % VTABSIZE];
1940 vpcmp(const void *a, const void *b)
1942 return varcmp(*(const char **)a, *(const char **)b);
1946 * This routine initializes the builtin variables.
1956 * PS1 depends on uid
1958 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1959 vps1.var_text = "PS1=\\w \\$ ";
1962 vps1.var_text = "PS1=# ";
1965 end = vp + ARRAY_SIZE(varinit);
1967 vpp = hashvar(vp->var_text);
1970 } while (++vp < end);
1973 static struct var **
1974 findvar(struct var **vpp, const char *name)
1976 for (; *vpp; vpp = &(*vpp)->next) {
1977 if (varcmp((*vpp)->var_text, name) == 0) {
1985 * Find the value of a variable. Returns NULL if not set.
1987 static const char* FAST_FUNC
1988 lookupvar(const char *name)
1992 v = *findvar(hashvar(name), name);
1994 #if ENABLE_ASH_RANDOM_SUPPORT
1996 * Dynamic variables are implemented roughly the same way they are
1997 * in bash. Namely, they're "special" so long as they aren't unset.
1998 * As soon as they're unset, they're no longer dynamic, and dynamic
1999 * lookup will no longer happen at that point. -- PFM.
2001 if (v->flags & VDYNAMIC)
2004 if (!(v->flags & VUNSET))
2005 return var_end(v->var_text);
2011 * Search the environment of a builtin command.
2014 bltinlookup(const char *name)
2018 for (sp = cmdenviron; sp; sp = sp->next) {
2019 if (varcmp(sp->text, name) == 0)
2020 return var_end(sp->text);
2022 return lookupvar(name);
2026 * Same as setvar except that the variable and value are passed in
2027 * the first argument as name=value. Since the first argument will
2028 * be actually stored in the table, it should not be a string that
2030 * Called with interrupts off.
2033 setvareq(char *s, int flags)
2035 struct var *vp, **vpp;
2038 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2039 vp = *findvar(vpp, s);
2041 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2044 if (flags & VNOSAVE)
2047 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2053 if (vp->var_func && !(flags & VNOFUNC))
2054 vp->var_func(var_end(s));
2056 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2057 free((char*)vp->var_text);
2059 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2061 /* variable s is not found */
2064 vp = ckzalloc(sizeof(*vp));
2066 /*vp->func = NULL; - ckzalloc did it */
2069 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2076 * Set the value of a variable. The flags argument is ored with the
2077 * flags of the variable. If val is NULL, the variable is unset.
2080 setvar(const char *name, const char *val, int flags)
2087 q = endofname(name);
2088 p = strchrnul(q, '=');
2090 if (!namelen || p != q)
2091 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2096 vallen = strlen(val);
2099 nameeq = ckmalloc(namelen + vallen + 2);
2100 p = (char *)memcpy(nameeq, name, namelen) + namelen;
2103 p = (char *)memcpy(p, val, vallen) + vallen;
2106 setvareq(nameeq, flags | VNOSAVE);
2110 static void FAST_FUNC
2111 setvar2(const char *name, const char *val)
2113 setvar(name, val, 0);
2116 #if ENABLE_ASH_GETOPTS
2118 * Safe version of setvar, returns 1 on success 0 on failure.
2121 setvarsafe(const char *name, const char *val, int flags)
2124 volatile int saveint;
2125 struct jmploc *volatile savehandler = exception_handler;
2126 struct jmploc jmploc;
2129 if (setjmp(jmploc.loc))
2132 exception_handler = &jmploc;
2133 setvar(name, val, flags);
2136 exception_handler = savehandler;
2137 RESTORE_INT(saveint);
2143 * Unset the specified variable.
2146 unsetvar(const char *s)
2152 vpp = findvar(hashvar(s), s);
2156 int flags = vp->flags;
2159 if (flags & VREADONLY)
2161 #if ENABLE_ASH_RANDOM_SUPPORT
2162 vp->flags &= ~VDYNAMIC;
2166 if ((flags & VSTRFIXED) == 0) {
2168 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2169 free((char*)vp->var_text);
2175 vp->flags &= ~VEXPORT;
2185 * Process a linked list of variable assignments.
2188 listsetvar(struct strlist *list_set_var, int flags)
2190 struct strlist *lp = list_set_var;
2196 setvareq(lp->text, flags);
2203 * Generate a list of variables satisfying the given conditions.
2206 listvars(int on, int off, char ***end)
2217 for (vp = *vpp; vp; vp = vp->next) {
2218 if ((vp->flags & mask) == on) {
2219 if (ep == stackstrend())
2220 ep = growstackstr();
2221 *ep++ = (char*)vp->var_text;
2224 } while (++vpp < vartab + VTABSIZE);
2225 if (ep == stackstrend())
2226 ep = growstackstr();
2230 return grabstackstr(ep);
2234 /* ============ Path search helper
2236 * The variable path (passed by reference) should be set to the start
2237 * of the path before the first call; path_advance will update
2238 * this value as it proceeds. Successive calls to path_advance will return
2239 * the possible path expansions in sequence. If an option (indicated by
2240 * a percent sign) appears in the path entry then the global variable
2241 * pathopt will be set to point to it; otherwise pathopt will be set to
2244 static const char *pathopt; /* set by path_advance */
2247 path_advance(const char **path, const char *name)
2257 for (p = start; *p && *p != ':' && *p != '%'; p++)
2259 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2260 while (stackblocksize() < len)
2264 memcpy(q, start, p - start);
2272 while (*p && *p != ':')
2279 return stalloc(len);
2283 /* ============ Prompt */
2285 static smallint doprompt; /* if set, prompt the user */
2286 static smallint needprompt; /* true if interactive and at start of line */
2288 #if ENABLE_FEATURE_EDITING
2289 static line_input_t *line_input_state;
2290 static const char *cmdedit_prompt;
2292 putprompt(const char *s)
2294 if (ENABLE_ASH_EXPAND_PRMT) {
2295 free((char*)cmdedit_prompt);
2296 cmdedit_prompt = ckstrdup(s);
2303 putprompt(const char *s)
2309 #if ENABLE_ASH_EXPAND_PRMT
2310 /* expandstr() needs parsing machinery, so it is far away ahead... */
2311 static const char *expandstr(const char *ps);
2313 #define expandstr(s) s
2317 setprompt(int whichprompt)
2320 #if ENABLE_ASH_EXPAND_PRMT
2321 struct stackmark smark;
2326 switch (whichprompt) {
2336 #if ENABLE_ASH_EXPAND_PRMT
2337 setstackmark(&smark);
2338 stalloc(stackblocksize());
2340 putprompt(expandstr(prompt));
2341 #if ENABLE_ASH_EXPAND_PRMT
2342 popstackmark(&smark);
2347 /* ============ The cd and pwd commands */
2349 #define CD_PHYSICAL 1
2359 while ((i = nextopt("LP")) != '\0') {
2361 flags ^= CD_PHYSICAL;
2370 * Update curdir (the name of the current directory) in response to a
2374 updatepwd(const char *dir)
2381 cdcomppath = ststrdup(dir);
2384 if (curdir == nullstr)
2386 new = stack_putstr(curdir, new);
2388 new = makestrspace(strlen(dir) + 2, new);
2389 lim = (char *)stackblock() + 1;
2393 if (new > lim && *lim == '/')
2398 if (dir[1] == '/' && dir[2] != '/') {
2404 p = strtok(cdcomppath, "/");
2408 if (p[1] == '.' && p[2] == '\0') {
2420 new = stack_putstr(p, new);
2428 return stackblock();
2432 * Find out what the current directory is. If we already know the current
2433 * directory, this routine returns immediately.
2438 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2439 return dir ? dir : nullstr;
2443 setpwd(const char *val, int setold)
2447 oldcur = dir = curdir;
2450 setvar("OLDPWD", oldcur, VEXPORT);
2453 if (physdir != nullstr) {
2454 if (physdir != oldcur)
2458 if (oldcur == val || !val) {
2464 dir = ckstrdup(val);
2465 if (oldcur != dir && oldcur != nullstr) {
2470 setvar("PWD", dir, VEXPORT);
2473 static void hashcd(void);
2476 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2477 * know that the current directory has changed.
2480 docd(const char *dest, int flags)
2482 const char *dir = NULL;
2485 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2488 if (!(flags & CD_PHYSICAL)) {
2489 dir = updatepwd(dest);
2503 static int FAST_FUNC
2504 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2516 dest = bltinlookup("HOME");
2517 else if (LONE_DASH(dest)) {
2518 dest = bltinlookup("OLDPWD");
2540 path = bltinlookup("CDPATH");
2549 p = path_advance(&path, dest);
2550 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2554 if (!docd(p, flags))
2559 ash_msg_and_raise_error("can't cd to %s", dest);
2562 if (flags & CD_PRINT)
2563 out1fmt("%s\n", curdir);
2567 static int FAST_FUNC
2568 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2571 const char *dir = curdir;
2575 if (physdir == nullstr)
2579 out1fmt("%s\n", dir);
2584 /* ============ ... */
2587 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2589 /* Syntax classes */
2590 #define CWORD 0 /* character is nothing special */
2591 #define CNL 1 /* newline character */
2592 #define CBACK 2 /* a backslash character */
2593 #define CSQUOTE 3 /* single quote */
2594 #define CDQUOTE 4 /* double quote */
2595 #define CENDQUOTE 5 /* a terminating quote */
2596 #define CBQUOTE 6 /* backwards single quote */
2597 #define CVAR 7 /* a dollar sign */
2598 #define CENDVAR 8 /* a '}' character */
2599 #define CLP 9 /* a left paren in arithmetic */
2600 #define CRP 10 /* a right paren in arithmetic */
2601 #define CENDFILE 11 /* end of file */
2602 #define CCTL 12 /* like CWORD, except it must be escaped */
2603 #define CSPCL 13 /* these terminate a word */
2604 #define CIGN 14 /* character should be ignored */
2607 #if ENABLE_ASH_ALIAS
2611 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2613 #if ENABLE_SH_MATH_SUPPORT
2614 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2616 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2618 static const uint16_t S_I_T[] = {
2619 #if ENABLE_ASH_ALIAS
2620 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2622 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2623 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2624 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2625 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2626 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2627 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2628 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2629 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2630 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2631 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2632 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2633 #if !USE_SIT_FUNCTION
2634 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2635 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2636 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2640 /* Constants below must match table above */
2642 #if ENABLE_ASH_ALIAS
2643 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2645 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2646 CNL_CNL_CNL_CNL , /* 2 */
2647 CWORD_CCTL_CCTL_CWORD , /* 3 */
2648 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2649 CVAR_CVAR_CWORD_CVAR , /* 5 */
2650 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2651 CSPCL_CWORD_CWORD_CLP , /* 7 */
2652 CSPCL_CWORD_CWORD_CRP , /* 8 */
2653 CBACK_CBACK_CCTL_CBACK , /* 9 */
2654 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2655 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2656 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2657 CWORD_CWORD_CWORD_CWORD , /* 13 */
2658 CCTL_CCTL_CCTL_CCTL , /* 14 */
2661 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2662 * caller must ensure proper cast on it if c is *char_ptr!
2664 /* Values for syntax param */
2665 #define BASESYNTAX 0 /* not in quotes */
2666 #define DQSYNTAX 1 /* in double quotes */
2667 #define SQSYNTAX 2 /* in single quotes */
2668 #define ARISYNTAX 3 /* in arithmetic */
2669 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2671 #if USE_SIT_FUNCTION
2674 SIT(int c, int syntax)
2676 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2677 # if ENABLE_ASH_ALIAS
2678 static const uint8_t syntax_index_table[] ALIGN1 = {
2679 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2680 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2681 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2685 static const uint8_t syntax_index_table[] ALIGN1 = {
2686 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2687 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2688 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2697 # if ENABLE_ASH_ALIAS
2703 /* Cast is purely for paranoia here,
2704 * just in case someone passed signed char to us */
2705 if ((unsigned char)c >= CTL_FIRST
2706 && (unsigned char)c <= CTL_LAST
2710 s = strchrnul(spec_symbls, c);
2713 indx = syntax_index_table[s - spec_symbls];
2715 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2718 #else /* !USE_SIT_FUNCTION */
2720 static const uint8_t syntax_index_table[] = {
2721 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2722 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2723 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2724 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2725 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2726 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2727 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2728 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2732 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2733 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2738 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2739 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2755 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2756 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2757 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2758 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2759 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2760 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2761 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2762 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2763 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2764 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2765 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2766 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2767 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2768 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2769 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2770 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2771 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2772 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2773 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2774 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2775 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2776 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2777 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2778 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2779 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2780 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2781 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2782 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2783 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2784 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2785 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2786 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2787 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2788 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2789 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2790 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2791 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2792 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2793 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2794 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2795 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2796 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2797 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2800 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2802 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2803 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2814 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2815 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2816 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2817 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2819 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2820 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2821 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2822 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2823 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2824 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2825 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2847 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2848 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2849 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2850 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2852 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2853 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2854 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2855 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2856 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2857 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2858 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2859 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 162 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 163 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 164 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 165 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 166 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 167 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 168 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 169 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 170 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 171 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 172 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 173 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 174 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 175 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 176 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 177 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 178 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 179 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 180 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 181 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 182 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 183 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 184 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 185 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 186 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 187 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 188 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 189 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 190 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 191 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 192 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 193 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 194 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 195 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 196 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 197 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 198 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 199 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 200 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 201 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 202 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 203 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 204 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 205 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 206 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 207 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 208 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 209 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 210 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 211 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 212 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 213 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 214 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 215 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 216 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 217 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 218 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 219 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 220 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 221 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 222 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 223 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 224 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 225 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 226 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 227 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 228 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 229 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 231 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 232 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 233 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 234 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 235 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 236 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 237 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 238 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 239 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 241 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 242 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 243 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 244 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 245 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 246 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 247 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 248 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 249 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 250 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 251 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 252 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 253 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 254 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 255 */ CWORD_CWORD_CWORD_CWORD,
2978 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2979 # if ENABLE_ASH_ALIAS
2980 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
2984 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
2986 #endif /* !USE_SIT_FUNCTION */
2989 /* ============ Alias handling */
2991 #if ENABLE_ASH_ALIAS
2993 #define ALIASINUSE 1
3004 static struct alias **atab; // [ATABSIZE];
3005 #define INIT_G_alias() do { \
3006 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3010 static struct alias **
3011 __lookupalias(const char *name) {
3012 unsigned int hashval;
3019 ch = (unsigned char)*p;
3023 ch = (unsigned char)*++p;
3025 app = &atab[hashval % ATABSIZE];
3027 for (; *app; app = &(*app)->next) {
3028 if (strcmp(name, (*app)->name) == 0) {
3036 static struct alias *
3037 lookupalias(const char *name, int check)
3039 struct alias *ap = *__lookupalias(name);
3041 if (check && ap && (ap->flag & ALIASINUSE))
3046 static struct alias *
3047 freealias(struct alias *ap)
3051 if (ap->flag & ALIASINUSE) {
3052 ap->flag |= ALIASDEAD;
3064 setalias(const char *name, const char *val)
3066 struct alias *ap, **app;
3068 app = __lookupalias(name);
3072 if (!(ap->flag & ALIASINUSE)) {
3075 ap->val = ckstrdup(val);
3076 ap->flag &= ~ALIASDEAD;
3079 ap = ckzalloc(sizeof(struct alias));
3080 ap->name = ckstrdup(name);
3081 ap->val = ckstrdup(val);
3082 /*ap->flag = 0; - ckzalloc did it */
3083 /*ap->next = NULL;*/
3090 unalias(const char *name)
3094 app = __lookupalias(name);
3098 *app = freealias(*app);
3109 struct alias *ap, **app;
3113 for (i = 0; i < ATABSIZE; i++) {
3115 for (ap = *app; ap; ap = *app) {
3116 *app = freealias(*app);
3126 printalias(const struct alias *ap)
3128 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3132 * TODO - sort output
3134 static int FAST_FUNC
3135 aliascmd(int argc UNUSED_PARAM, char **argv)
3144 for (i = 0; i < ATABSIZE; i++) {
3145 for (ap = atab[i]; ap; ap = ap->next) {
3151 while ((n = *++argv) != NULL) {
3152 v = strchr(n+1, '=');
3153 if (v == NULL) { /* n+1: funny ksh stuff */
3154 ap = *__lookupalias(n);
3156 fprintf(stderr, "%s: %s not found\n", "alias", n);
3169 static int FAST_FUNC
3170 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3174 while ((i = nextopt("a")) != '\0') {
3180 for (i = 0; *argptr; argptr++) {
3181 if (unalias(*argptr)) {
3182 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3190 #endif /* ASH_ALIAS */
3193 /* ============ jobs.c */
3195 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3198 #define FORK_NOJOB 2
3200 /* mode flags for showjob(s) */
3201 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3202 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3203 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3206 * A job structure contains information about a job. A job is either a
3207 * single process or a set of processes contained in a pipeline. In the
3208 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3212 pid_t ps_pid; /* process id */
3213 int ps_status; /* last process status from wait() */
3214 char *ps_cmd; /* text of command being run */
3218 struct procstat ps0; /* status of process */
3219 struct procstat *ps; /* status or processes when more than one */
3221 int stopstatus; /* status of a stopped job */
3224 nprocs: 16, /* number of processes */
3226 #define JOBRUNNING 0 /* at least one proc running */
3227 #define JOBSTOPPED 1 /* all procs are stopped */
3228 #define JOBDONE 2 /* all procs are completed */
3230 sigint: 1, /* job was killed by SIGINT */
3231 jobctl: 1, /* job running under job control */
3233 waited: 1, /* true if this entry has been waited for */
3234 used: 1, /* true if this entry is in used */
3235 changed: 1; /* true if status has changed */
3236 struct job *prev_job; /* previous job */
3239 static struct job *makejob(/*union node *,*/ int);
3240 static int forkshell(struct job *, union node *, int);
3241 static int waitforjob(struct job *);
3244 enum { doing_jobctl = 0 };
3245 #define setjobctl(on) do {} while (0)
3247 static smallint doing_jobctl; //references:8
3248 static void setjobctl(int);
3255 ignoresig(int signo)
3257 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3258 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3259 /* No, need to do it */
3260 signal(signo, SIG_IGN);
3262 sigmode[signo - 1] = S_HARD_IGN;
3266 * Only one usage site - in setsignal()
3269 signal_handler(int signo)
3271 gotsig[signo - 1] = 1;
3273 if (signo == SIGINT && !trap[SIGINT]) {
3274 if (!suppress_int) {
3276 raise_interrupt(); /* does not return */
3280 pending_sig = signo;
3285 * Set the signal handler for the specified signal. The routine figures
3286 * out what it should be set to.
3289 setsignal(int signo)
3292 char cur_act, new_act;
3293 struct sigaction act;
3297 if (t != NULL) { /* trap for this sig is set */
3299 if (t[0] == '\0') /* trap is "": ignore this sig */
3303 if (rootshell && new_act == S_DFL) {
3306 if (iflag || minusc || sflag == 0)
3315 * "In all cases, bash ignores SIGQUIT. Non-builtin
3316 * commands run by bash have signal handlers
3317 * set to the values inherited by the shell
3318 * from its parent". */
3334 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3335 //whereas we have to restore it to what shell got on entry
3336 //from the parent. See comment above
3338 t = &sigmode[signo - 1];
3341 /* current setting is not yet known */
3342 if (sigaction(signo, NULL, &act)) {
3343 /* pretend it worked; maybe we should give a warning,
3344 * but other shells don't. We don't alter sigmode,
3345 * so we retry every time.
3346 * btw, in Linux it never fails. --vda */
3349 if (act.sa_handler == SIG_IGN) {
3350 cur_act = S_HARD_IGN;
3352 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3354 cur_act = S_IGN; /* don't hard ignore these */
3358 if (cur_act == S_HARD_IGN || cur_act == new_act)
3361 act.sa_handler = SIG_DFL;
3364 act.sa_handler = signal_handler;
3365 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3366 sigfillset(&act.sa_mask); /* ditto */
3369 act.sa_handler = SIG_IGN;
3372 sigaction_set(signo, &act);
3377 /* mode flags for set_curjob */
3378 #define CUR_DELETE 2
3379 #define CUR_RUNNING 1
3380 #define CUR_STOPPED 0
3382 /* mode flags for dowait */
3383 #define DOWAIT_NONBLOCK WNOHANG
3384 #define DOWAIT_BLOCK 0
3387 /* pgrp of shell on invocation */
3388 static int initialpgrp; //references:2
3389 static int ttyfd = -1; //5
3392 static struct job *jobtab; //5
3394 static unsigned njobs; //4
3396 static struct job *curjob; //lots
3397 /* number of presumed living untracked jobs */
3398 static int jobless; //4
3401 set_curjob(struct job *jp, unsigned mode)
3404 struct job **jpp, **curp;
3406 /* first remove from list */
3407 jpp = curp = &curjob;
3412 jpp = &jp1->prev_job;
3414 *jpp = jp1->prev_job;
3416 /* Then re-insert in correct position */
3424 /* job being deleted */
3427 /* newly created job or backgrounded job,
3428 put after all stopped jobs. */
3432 if (!jp1 || jp1->state != JOBSTOPPED)
3435 jpp = &jp1->prev_job;
3441 /* newly stopped job - becomes curjob */
3442 jp->prev_job = *jpp;
3450 jobno(const struct job *jp)
3452 return jp - jobtab + 1;
3457 * Convert a job name to a job structure.
3460 #define getjob(name, getctl) getjob(name)
3463 getjob(const char *name, int getctl)
3467 const char *err_msg = "%s: no such job";
3471 char *(*match)(const char *, const char *);
3486 if (c == '+' || c == '%') {
3488 err_msg = "No current job";
3494 err_msg = "No previous job";
3505 jp = jobtab + num - 1;
3520 if (match(jp->ps[0].ps_cmd, p)) {
3524 err_msg = "%s: ambiguous";
3534 err_msg = "job %s not created under job control";
3535 if (getctl && jp->jobctl == 0)
3540 ash_msg_and_raise_error(err_msg, name);
3544 * Mark a job structure as unused.
3547 freejob(struct job *jp)
3549 struct procstat *ps;
3553 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3554 if (ps->ps_cmd != nullstr)
3557 if (jp->ps != &jp->ps0)
3560 set_curjob(jp, CUR_DELETE);
3566 xtcsetpgrp(int fd, pid_t pgrp)
3568 if (tcsetpgrp(fd, pgrp))
3569 ash_msg_and_raise_error("can't set tty process group (%m)");
3573 * Turn job control on and off.
3575 * Note: This code assumes that the third arg to ioctl is a character
3576 * pointer, which is true on Berkeley systems but not System V. Since
3577 * System V doesn't have job control yet, this isn't a problem now.
3579 * Called with interrupts off.
3587 if (on == doing_jobctl || rootshell == 0)
3591 ofd = fd = open(_PATH_TTY, O_RDWR);
3593 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3594 * That sometimes helps to acquire controlling tty.
3595 * Obviously, a workaround for bugs when someone
3596 * failed to provide a controlling tty to bash! :) */
3602 fd = fcntl(fd, F_DUPFD, 10);
3607 /* fd is a tty at this point */
3608 close_on_exec_on(fd);
3609 do { /* while we are in the background */
3610 pgrp = tcgetpgrp(fd);
3613 ash_msg("can't access tty; job control turned off");
3617 if (pgrp == getpgrp())
3628 xtcsetpgrp(fd, pgrp);
3630 /* turning job control off */
3633 /* was xtcsetpgrp, but this can make exiting ash
3634 * loop forever if pty is already deleted */
3635 tcsetpgrp(fd, pgrp);
3649 static int FAST_FUNC
3650 killcmd(int argc, char **argv)
3653 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3655 if (argv[i][0] == '%') {
3656 struct job *jp = getjob(argv[i], 0);
3657 unsigned pid = jp->ps[0].ps_pid;
3658 /* Enough space for ' -NNN<nul>' */
3659 argv[i] = alloca(sizeof(int)*3 + 3);
3660 /* kill_main has matching code to expect
3661 * leading space. Needed to not confuse
3662 * negative pids with "kill -SIGNAL_NO" syntax */
3663 sprintf(argv[i], " -%u", pid);
3665 } while (argv[++i]);
3667 return kill_main(argc, argv);
3671 showpipe(struct job *jp /*, FILE *out*/)
3673 struct procstat *ps;
3674 struct procstat *psend;
3676 psend = jp->ps + jp->nprocs;
3677 for (ps = jp->ps + 1; ps < psend; ps++)
3678 printf(" | %s", ps->ps_cmd);
3679 outcslow('\n', stdout);
3680 flush_stdout_stderr();
3685 restartjob(struct job *jp, int mode)
3687 struct procstat *ps;
3693 if (jp->state == JOBDONE)
3695 jp->state = JOBRUNNING;
3696 pgid = jp->ps[0].ps_pid;
3697 if (mode == FORK_FG)
3698 xtcsetpgrp(ttyfd, pgid);
3699 killpg(pgid, SIGCONT);
3703 if (WIFSTOPPED(ps->ps_status)) {
3709 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3714 static int FAST_FUNC
3715 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3721 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3725 jp = getjob(*argv, 1);
3726 if (mode == FORK_BG) {
3727 set_curjob(jp, CUR_RUNNING);
3728 printf("[%d] ", jobno(jp));
3730 out1str(jp->ps[0].ps_cmd);
3731 showpipe(jp /*, stdout*/);
3732 retval = restartjob(jp, mode);
3733 } while (*argv && *++argv);
3739 sprint_status(char *s, int status, int sigonly)
3745 if (!WIFEXITED(status)) {
3747 if (WIFSTOPPED(status))
3748 st = WSTOPSIG(status);
3751 st = WTERMSIG(status);
3753 if (st == SIGINT || st == SIGPIPE)
3756 if (WIFSTOPPED(status))
3761 col = fmtstr(s, 32, strsignal(st));
3762 if (WCOREDUMP(status)) {
3763 col += fmtstr(s + col, 16, " (core dumped)");
3765 } else if (!sigonly) {
3766 st = WEXITSTATUS(status);
3768 col = fmtstr(s, 16, "Done(%d)", st);
3770 col = fmtstr(s, 16, "Done");
3777 dowait(int wait_flags, struct job *job)
3782 struct job *thisjob;
3785 TRACE(("dowait(0x%x) called\n", wait_flags));
3787 /* Do a wait system call. If job control is compiled in, we accept
3788 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3789 * NB: _not_ safe_waitpid, we need to detect EINTR */
3791 wait_flags |= WUNTRACED;
3792 pid = waitpid(-1, &status, wait_flags);
3793 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3794 pid, status, errno, strerror(errno)));
3800 for (jp = curjob; jp; jp = jp->prev_job) {
3801 struct procstat *ps;
3802 struct procstat *psend;
3803 if (jp->state == JOBDONE)
3807 psend = ps + jp->nprocs;
3809 if (ps->ps_pid == pid) {
3810 TRACE(("Job %d: changing status of proc %d "
3811 "from 0x%x to 0x%x\n",
3812 jobno(jp), pid, ps->ps_status, status));
3813 ps->ps_status = status;
3816 if (ps->ps_status == -1)
3819 if (state == JOBRUNNING)
3821 if (WIFSTOPPED(ps->ps_status)) {
3822 jp->stopstatus = ps->ps_status;
3826 } while (++ps < psend);
3831 if (!WIFSTOPPED(status))
3837 if (state != JOBRUNNING) {
3838 thisjob->changed = 1;
3840 if (thisjob->state != state) {
3841 TRACE(("Job %d: changing state from %d to %d\n",
3842 jobno(thisjob), thisjob->state, state));
3843 thisjob->state = state;
3845 if (state == JOBSTOPPED) {
3846 set_curjob(thisjob, CUR_STOPPED);
3855 if (thisjob && thisjob == job) {
3859 len = sprint_status(s, status, 1);
3870 blocking_wait_with_raise_on_sig(void)
3872 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
3873 if (pid <= 0 && pending_sig)
3874 raise_exception(EXSIG);
3880 showjob(FILE *out, struct job *jp, int mode)
3882 struct procstat *ps;
3883 struct procstat *psend;
3890 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
3891 /* just output process (group) id of pipeline */
3892 fprintf(out, "%d\n", ps->ps_pid);
3896 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3901 else if (curjob && jp == curjob->prev_job)
3904 if (mode & SHOW_PIDS)
3905 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
3907 psend = ps + jp->nprocs;
3909 if (jp->state == JOBRUNNING) {
3910 strcpy(s + col, "Running");
3911 col += sizeof("Running") - 1;
3913 int status = psend[-1].ps_status;
3914 if (jp->state == JOBSTOPPED)
3915 status = jp->stopstatus;
3916 col += sprint_status(s + col, status, 0);
3918 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
3920 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3921 * or prints several "PID | <cmdN>" lines,
3922 * depending on SHOW_PIDS bit.
3923 * We do not print status of individual processes
3924 * between PID and <cmdN>. bash does it, but not very well:
3925 * first line shows overall job status, not process status,
3926 * making it impossible to know 1st process status.
3930 /* for each process */
3933 if (mode & SHOW_PIDS)
3934 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
3936 fprintf(out, "%s%*c%s%s",
3938 33 - col >= 0 ? 33 - col : 0, ' ',
3939 ps == jp->ps ? "" : "| ",
3942 } while (++ps != psend);
3943 outcslow('\n', out);
3947 if (jp->state == JOBDONE) {
3948 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3954 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3955 * statuses have changed since the last call to showjobs.
3958 showjobs(FILE *out, int mode)
3962 TRACE(("showjobs(0x%x) called\n", mode));
3964 /* Handle all finished jobs */
3965 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
3968 for (jp = curjob; jp; jp = jp->prev_job) {
3969 if (!(mode & SHOW_CHANGED) || jp->changed) {
3970 showjob(out, jp, mode);
3975 static int FAST_FUNC
3976 jobscmd(int argc UNUSED_PARAM, char **argv)
3981 while ((m = nextopt("lp")) != '\0') {
3985 mode |= SHOW_ONLY_PGID;
3991 showjob(stdout, getjob(*argv, 0), mode);
3994 showjobs(stdout, mode);
4001 /* Called only on finished or stopped jobs (no members are running) */
4003 getstatus(struct job *job)
4007 struct procstat *ps;
4009 /* Fetch last member's status */
4010 ps = job->ps + job->nprocs - 1;
4011 status = ps->ps_status;
4013 /* "set -o pipefail" mode: use last _nonzero_ status */
4014 while (status == 0 && --ps >= job->ps)
4015 status = ps->ps_status;
4018 retval = WEXITSTATUS(status);
4019 if (!WIFEXITED(status)) {
4021 retval = WSTOPSIG(status);
4022 if (!WIFSTOPPED(status))
4025 /* XXX: limits number of signals */
4026 retval = WTERMSIG(status);
4028 if (retval == SIGINT)
4034 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4035 jobno(job), job->nprocs, status, retval));
4039 static int FAST_FUNC
4040 waitcmd(int argc UNUSED_PARAM, char **argv)
4047 raise_exception(EXSIG);
4054 /* wait for all jobs */
4058 if (!jp) /* no running procs */
4060 if (jp->state == JOBRUNNING)
4065 blocking_wait_with_raise_on_sig();
4067 * "When bash is waiting for an asynchronous command via
4068 * the wait builtin, the reception of a signal for which a trap
4069 * has been set will cause the wait builtin to return immediately
4070 * with an exit status greater than 128, immediately after which
4071 * the trap is executed."
4073 * blocking_wait_with_raise_on_sig raises signal handlers
4074 * if it gets no pid (pid < 0). However,
4075 * if child sends us a signal *and immediately exits*,
4076 * blocking_wait_with_raise_on_sig gets pid > 0
4077 * and does not handle pending_sig. Check this case: */
4079 raise_exception(EXSIG);
4085 if (**argv != '%') {
4086 pid_t pid = number(*argv);
4091 if (job->ps[job->nprocs - 1].ps_pid == pid)
4093 job = job->prev_job;
4096 job = getjob(*argv, 0);
4097 /* loop until process terminated or stopped */
4098 while (job->state == JOBRUNNING)
4099 blocking_wait_with_raise_on_sig();
4101 retval = getstatus(job);
4114 struct job *jp, *jq;
4116 len = njobs * sizeof(*jp);
4118 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4120 offset = (char *)jp - (char *)jq;
4122 /* Relocate pointers */
4125 jq = (struct job *)((char *)jq + l);
4129 #define joff(p) ((struct job *)((char *)(p) + l))
4130 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4131 if (joff(jp)->ps == &jq->ps0)
4132 jmove(joff(jp)->ps);
4133 if (joff(jp)->prev_job)
4134 jmove(joff(jp)->prev_job);
4144 jp = (struct job *)((char *)jp + len);
4148 } while (--jq >= jp);
4153 * Return a new job structure.
4154 * Called with interrupts off.
4157 makejob(/*union node *node,*/ int nprocs)
4162 for (i = njobs, jp = jobtab; ; jp++) {
4169 if (jp->state != JOBDONE || !jp->waited)
4178 memset(jp, 0, sizeof(*jp));
4180 /* jp->jobctl is a bitfield.
4181 * "jp->jobctl |= jobctl" likely to give awful code */
4185 jp->prev_job = curjob;
4190 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4192 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4199 * Return a string identifying a command (to be printed by the
4202 static char *cmdnextc;
4205 cmdputs(const char *s)
4207 static const char vstype[VSTYPE + 1][3] = {
4208 "", "}", "-", "+", "?", "=",
4209 "%", "%%", "#", "##"
4210 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4213 const char *p, *str;
4217 unsigned char subtype = 0;
4221 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4223 while ((c = *p++) != '\0') {
4231 if ((subtype & VSTYPE) == VSLENGTH)
4235 if (!(subtype & VSQUOTE) == !(quoted & 1))
4241 str = "\"}" + !(quoted & 1);
4248 case CTLBACKQ+CTLQUOTE:
4251 #if ENABLE_SH_MATH_SUPPORT
4266 if ((subtype & VSTYPE) != VSNORMAL)
4268 str = vstype[subtype & VSTYPE];
4269 if (subtype & VSNUL)
4278 /* These can only happen inside quotes */
4291 while ((c = *str++) != '\0') {
4294 } /* while *p++ not NUL */
4297 USTPUTC('"', nextc);
4303 /* cmdtxt() and cmdlist() call each other */
4304 static void cmdtxt(union node *n);
4307 cmdlist(union node *np, int sep)
4309 for (; np; np = np->narg.next) {
4313 if (sep && np->narg.next)
4319 cmdtxt(union node *n)
4322 struct nodelist *lp;
4333 lp = n->npipe.cmdlist;
4351 cmdtxt(n->nbinary.ch1);
4367 cmdtxt(n->nif.test);
4369 if (n->nif.elsepart) {
4370 cmdtxt(n->nif.ifpart);
4372 n = n->nif.elsepart;
4390 cmdtxt(n->nbinary.ch1);
4400 cmdputs(n->nfor.var);
4402 cmdlist(n->nfor.args, 1);
4407 cmdputs(n->narg.text);
4411 cmdlist(n->ncmd.args, 1);
4412 cmdlist(n->ncmd.redirect, 0);
4425 cmdputs(n->ncase.expr->narg.text);
4427 for (np = n->ncase.cases; np; np = np->nclist.next) {
4428 cmdtxt(np->nclist.pattern);
4430 cmdtxt(np->nclist.body);
4444 #if ENABLE_ASH_BASH_COMPAT
4459 cmdputs(utoa(n->nfile.fd));
4461 if (n->type == NTOFD || n->type == NFROMFD) {
4462 cmdputs(utoa(n->ndup.dupfd));
4471 commandtext(union node *n)
4475 STARTSTACKSTR(cmdnextc);
4477 name = stackblock();
4478 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4479 name, cmdnextc, cmdnextc));
4480 return ckstrdup(name);
4485 * Fork off a subshell. If we are doing job control, give the subshell its
4486 * own process group. Jp is a job structure that the job is to be added to.
4487 * N is the command that will be evaluated by the child. Both jp and n may
4488 * be NULL. The mode parameter can be one of the following:
4489 * FORK_FG - Fork off a foreground process.
4490 * FORK_BG - Fork off a background process.
4491 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4492 * process group even if job control is on.
4494 * When job control is turned off, background processes have their standard
4495 * input redirected to /dev/null (except for the second and later processes
4498 * Called with interrupts off.
4501 * Clear traps on a fork.
4508 for (tp = trap; tp < &trap[NSIG]; tp++) {
4509 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4511 if (trap_ptr == trap)
4513 /* else: it "belongs" to trap_ptr vector, don't free */
4515 if ((tp - trap) != 0)
4516 setsignal(tp - trap);
4522 /* Lives far away from here, needed for forkchild */
4523 static void closescript(void);
4525 /* Called after fork(), in child */
4526 static NOINLINE void
4527 forkchild(struct job *jp, union node *n, int mode)
4531 TRACE(("Child shell %d\n", getpid()));
4535 /* man bash: "Non-builtin commands run by bash have signal handlers
4536 * set to the values inherited by the shell from its parent".
4537 * Do we do it correctly? */
4541 if (mode == FORK_NOJOB /* is it `xxx` ? */
4542 && n && n->type == NCMD /* is it single cmd? */
4543 /* && n->ncmd.args->type == NARG - always true? */
4544 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4545 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4546 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4548 TRACE(("Trap hack\n"));
4549 /* Awful hack for `trap` or $(trap).
4551 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4552 * contains an example where "trap" is executed in a subshell:
4554 * save_traps=$(trap)
4556 * eval "$save_traps"
4558 * Standard does not say that "trap" in subshell shall print
4559 * parent shell's traps. It only says that its output
4560 * must have suitable form, but then, in the above example
4561 * (which is not supposed to be normative), it implies that.
4563 * bash (and probably other shell) does implement it
4564 * (traps are reset to defaults, but "trap" still shows them),
4565 * but as a result, "trap" logic is hopelessly messed up:
4568 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4569 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4570 * # true | trap <--- trap is in subshell - no output (ditto)
4571 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4572 * trap -- 'echo Ho' SIGWINCH
4573 * # echo `(trap)` <--- in subshell in subshell - output
4574 * trap -- 'echo Ho' SIGWINCH
4575 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4576 * trap -- 'echo Ho' SIGWINCH
4578 * The rules when to forget and when to not forget traps
4579 * get really complex and nonsensical.
4581 * Our solution: ONLY bare $(trap) or `trap` is special.
4583 /* Save trap handler strings for trap builtin to print */
4584 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4585 /* Fall through into clearing traps */
4589 /* do job control only in root shell */
4591 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4594 if (jp->nprocs == 0)
4597 pgrp = jp->ps[0].ps_pid;
4598 /* this can fail because we are doing it in the parent also */
4600 if (mode == FORK_FG)
4601 xtcsetpgrp(ttyfd, pgrp);
4606 if (mode == FORK_BG) {
4607 /* man bash: "When job control is not in effect,
4608 * asynchronous commands ignore SIGINT and SIGQUIT" */
4611 if (jp->nprocs == 0) {
4613 if (open(bb_dev_null, O_RDONLY) != 0)
4614 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4618 if (iflag) { /* why if iflag only? */
4623 * "In all cases, bash ignores SIGQUIT. Non-builtin
4624 * commands run by bash have signal handlers
4625 * set to the values inherited by the shell
4627 * Take care of the second rule: */
4631 if (n && n->type == NCMD
4632 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4634 TRACE(("Job hack\n"));
4635 /* "jobs": we do not want to clear job list for it,
4636 * instead we remove only _its_ own_ job from job list.
4637 * This makes "jobs .... | cat" more useful.
4643 for (jp = curjob; jp; jp = jp->prev_job)
4648 /* Called after fork(), in parent */
4650 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4653 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4655 TRACE(("In parent shell: child = %d\n", pid));
4657 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4663 if (mode != FORK_NOJOB && jp->jobctl) {
4666 if (jp->nprocs == 0)
4669 pgrp = jp->ps[0].ps_pid;
4670 /* This can fail because we are doing it in the child also */
4674 if (mode == FORK_BG) {
4675 backgndpid = pid; /* set $! */
4676 set_curjob(jp, CUR_RUNNING);
4679 struct procstat *ps = &jp->ps[jp->nprocs++];
4682 ps->ps_cmd = nullstr;
4684 if (doing_jobctl && n)
4685 ps->ps_cmd = commandtext(n);
4691 forkshell(struct job *jp, union node *n, int mode)
4695 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4698 TRACE(("Fork failed, errno=%d", errno));
4701 ash_msg_and_raise_error("can't fork");
4704 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4705 forkchild(jp, n, mode);
4707 forkparent(jp, n, mode, pid);
4713 * Wait for job to finish.
4715 * Under job control we have the problem that while a child process
4716 * is running interrupts generated by the user are sent to the child
4717 * but not to the shell. This means that an infinite loop started by
4718 * an interactive user may be hard to kill. With job control turned off,
4719 * an interactive user may place an interactive program inside a loop.
4720 * If the interactive program catches interrupts, the user doesn't want
4721 * these interrupts to also abort the loop. The approach we take here
4722 * is to have the shell ignore interrupt signals while waiting for a
4723 * foreground process to terminate, and then send itself an interrupt
4724 * signal if the child process was terminated by an interrupt signal.
4725 * Unfortunately, some programs want to do a bit of cleanup and then
4726 * exit on interrupt; unless these processes terminate themselves by
4727 * sending a signal to themselves (instead of calling exit) they will
4728 * confuse this approach.
4730 * Called with interrupts off.
4733 waitforjob(struct job *jp)
4737 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4740 while (jp->state == JOBRUNNING) {
4741 /* In non-interactive shells, we _can_ get
4742 * a keyboard signal here and be EINTRed,
4743 * but we just loop back, waiting for command to complete.
4746 * "If bash is waiting for a command to complete and receives
4747 * a signal for which a trap has been set, the trap
4748 * will not be executed until the command completes."
4750 * Reality is that even if trap is not set, bash
4751 * will not act on the signal until command completes.
4752 * Try this. sleep5intoff.c:
4753 * #include <signal.h>
4754 * #include <unistd.h>
4757 * sigemptyset(&set);
4758 * sigaddset(&set, SIGINT);
4759 * sigaddset(&set, SIGQUIT);
4760 * sigprocmask(SIG_BLOCK, &set, NULL);
4764 * $ bash -c './sleep5intoff; echo hi'
4765 * ^C^C^C^C <--- pressing ^C once a second
4767 * $ bash -c './sleep5intoff; echo hi'
4768 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4771 dowait(DOWAIT_BLOCK, jp);
4778 xtcsetpgrp(ttyfd, rootpid);
4780 * This is truly gross.
4781 * If we're doing job control, then we did a TIOCSPGRP which
4782 * caused us (the shell) to no longer be in the controlling
4783 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4784 * intuit from the subprocess exit status whether a SIGINT
4785 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4787 if (jp->sigint) /* TODO: do the same with all signals */
4788 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4790 if (jp->state == JOBDONE)
4797 * return 1 if there are stopped jobs, otherwise 0
4809 if (jp && jp->state == JOBSTOPPED) {
4810 out2str("You have stopped jobs.\n");
4819 /* ============ redir.c
4821 * Code for dealing with input/output redirection.
4824 #define EMPTY -2 /* marks an unused slot in redirtab */
4825 #define CLOSED -3 /* marks a slot of previously-closed fd */
4828 * Open a file in noclobber mode.
4829 * The code was copied from bash.
4832 noclobberopen(const char *fname)
4835 struct stat finfo, finfo2;
4838 * If the file exists and is a regular file, return an error
4841 r = stat(fname, &finfo);
4842 if (r == 0 && S_ISREG(finfo.st_mode)) {
4848 * If the file was not present (r != 0), make sure we open it
4849 * exclusively so that if it is created before we open it, our open
4850 * will fail. Make sure that we do not truncate an existing file.
4851 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4852 * file was not a regular file, we leave O_EXCL off.
4855 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4856 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4858 /* If the open failed, return the file descriptor right away. */
4863 * OK, the open succeeded, but the file may have been changed from a
4864 * non-regular file to a regular file between the stat and the open.
4865 * We are assuming that the O_EXCL open handles the case where FILENAME
4866 * did not exist and is symlinked to an existing file between the stat
4871 * If we can open it and fstat the file descriptor, and neither check
4872 * revealed that it was a regular file, and the file has not been
4873 * replaced, return the file descriptor.
4875 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4876 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4879 /* The file has been replaced. badness. */
4886 * Handle here documents. Normally we fork off a process to write the
4887 * data to a pipe. If the document is short, we can stuff the data in
4888 * the pipe without forking.
4890 /* openhere needs this forward reference */
4891 static void expandhere(union node *arg, int fd);
4893 openhere(union node *redir)
4899 ash_msg_and_raise_error("pipe call failed");
4900 if (redir->type == NHERE) {
4901 len = strlen(redir->nhere.doc->narg.text);
4902 if (len <= PIPE_BUF) {
4903 full_write(pip[1], redir->nhere.doc->narg.text, len);
4907 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4910 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4911 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4912 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4913 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4914 signal(SIGPIPE, SIG_DFL);
4915 if (redir->type == NHERE)
4916 full_write(pip[1], redir->nhere.doc->narg.text, len);
4918 expandhere(redir->nhere.doc, pip[1]);
4919 _exit(EXIT_SUCCESS);
4927 openredirect(union node *redir)
4932 switch (redir->nfile.type) {
4934 fname = redir->nfile.expfname;
4935 f = open(fname, O_RDONLY);
4940 fname = redir->nfile.expfname;
4941 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4946 #if ENABLE_ASH_BASH_COMPAT
4949 /* Take care of noclobber mode. */
4951 fname = redir->nfile.expfname;
4952 f = noclobberopen(fname);
4959 fname = redir->nfile.expfname;
4960 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4965 fname = redir->nfile.expfname;
4966 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4974 /* Fall through to eliminate warning. */
4975 /* Our single caller does this itself */
4982 f = openhere(redir);
4988 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4990 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
4994 * Copy a file descriptor to be >= to. Returns -1
4995 * if the source file descriptor is closed, EMPTY if there are no unused
4996 * file descriptors left.
4998 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
4999 * old code was doing close(to) prior to copyfd() to achieve the same */
5001 COPYFD_EXACT = (int)~(INT_MAX),
5002 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5005 copyfd(int from, int to)
5009 if (to & COPYFD_EXACT) {
5010 to &= ~COPYFD_EXACT;
5012 newfd = dup2(from, to);
5014 newfd = fcntl(from, F_DUPFD, to);
5017 if (errno == EMFILE)
5019 /* Happens when source fd is not open: try "echo >&99" */
5020 ash_msg_and_raise_error("%d: %m", from);
5025 /* Struct def and variable are moved down to the first usage site */
5030 struct redirtab *next;
5033 struct two_fd_t two_fd[];
5035 #define redirlist (G_var.redirlist)
5037 static int need_to_remember(struct redirtab *rp, int fd)
5041 if (!rp) /* remembering was not requested */
5044 for (i = 0; i < rp->pair_count; i++) {
5045 if (rp->two_fd[i].orig == fd) {
5046 /* already remembered */
5053 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5054 static int is_hidden_fd(struct redirtab *rp, int fd)
5057 struct parsefile *pf;
5061 /* Check open scripts' fds */
5064 /* We skip pf_fd == 0 case because of the following case:
5065 * $ ash # running ash interactively
5067 * and in script.sh: "exec 9>&0".
5068 * Even though top-level pf_fd _is_ 0,
5069 * it's still ok to use it: "read" builtin uses it,
5070 * why should we cripple "exec" builtin?
5072 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5080 /* Check saved fds of redirects */
5081 fd |= COPYFD_RESTORE;
5082 for (i = 0; i < rp->pair_count; i++) {
5083 if (rp->two_fd[i].copy == fd) {
5091 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5092 * old file descriptors are stashed away so that the redirection can be
5093 * undone by calling popredir.
5095 /* flags passed to redirect */
5096 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5097 #define REDIR_SAVEFD2 03 /* set preverrout */
5099 redirect(union node *redir, int flags)
5101 struct redirtab *sv;
5106 int copied_fd2 = -1;
5116 if (flags & REDIR_PUSH) {
5117 union node *tmp = redir;
5120 #if ENABLE_ASH_BASH_COMPAT
5121 if (tmp->nfile.type == NTO2)
5124 tmp = tmp->nfile.next;
5126 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5127 sv->next = redirlist;
5128 sv->pair_count = sv_pos;
5130 sv->nullredirs = g_nullredirs - 1;
5132 while (sv_pos > 0) {
5134 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5140 fd = redir->nfile.fd;
5141 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5142 right_fd = redir->ndup.dupfd;
5143 //bb_error_msg("doing %d > %d", fd, right_fd);
5144 /* redirect from/to same file descriptor? */
5147 /* "echo >&10" and 10 is a fd opened to a sh script? */
5148 if (is_hidden_fd(sv, right_fd)) {
5149 errno = EBADF; /* as if it is closed */
5150 ash_msg_and_raise_error("%d: %m", right_fd);
5154 newfd = openredirect(redir); /* always >= 0 */
5156 /* Descriptor wasn't open before redirect.
5157 * Mark it for close in the future */
5158 if (need_to_remember(sv, fd)) {
5159 goto remember_to_close;
5164 #if ENABLE_ASH_BASH_COMPAT
5167 if (need_to_remember(sv, fd)) {
5168 /* Copy old descriptor */
5169 /* Careful to not accidentally "save"
5170 * to the same fd as right side fd in N>&M */
5171 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5172 i = fcntl(fd, F_DUPFD, minfd);
5173 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5174 * are closed in popredir() in the child, preventing them from leaking
5175 * into child. (popredir() also cleans up the mess in case of failures)
5180 /* Strange error (e.g. "too many files" EMFILE?) */
5184 ash_msg_and_raise_error("%d: %m", fd);
5187 /* EBADF: it is not open - good, remember to close it */
5190 } else { /* fd is open, save its copy */
5191 /* "exec fd>&-" should not close fds
5192 * which point to script file(s).
5193 * Force them to be restored afterwards */
5194 if (is_hidden_fd(sv, fd))
5195 i |= COPYFD_RESTORE;
5199 sv->two_fd[sv_pos].orig = fd;
5200 sv->two_fd[sv_pos].copy = i;
5204 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5205 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5206 /* Don't want to trigger debugging */
5210 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5212 } else if (fd != newfd) { /* move newfd to fd */
5213 copyfd(newfd, fd | COPYFD_EXACT);
5214 #if ENABLE_ASH_BASH_COMPAT
5215 if (!(redir->nfile.type == NTO2 && fd == 2))
5219 #if ENABLE_ASH_BASH_COMPAT
5220 if (redir->nfile.type == NTO2 && fd == 1) {
5221 /* We already redirected it to fd 1, now copy it to 2 */
5227 } while ((redir = redir->nfile.next) != NULL);
5230 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5231 preverrout_fd = copied_fd2;
5235 * Undo the effects of the last redirection.
5238 popredir(int drop, int restore)
5240 struct redirtab *rp;
5243 if (--g_nullredirs >= 0)
5247 for (i = 0; i < rp->pair_count; i++) {
5248 int fd = rp->two_fd[i].orig;
5249 int copy = rp->two_fd[i].copy;
5250 if (copy == CLOSED) {
5255 if (copy != EMPTY) {
5256 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5257 copy &= ~COPYFD_RESTORE;
5259 copyfd(copy, fd | COPYFD_EXACT);
5261 close(copy & ~COPYFD_RESTORE);
5264 redirlist = rp->next;
5265 g_nullredirs = rp->nullredirs;
5271 * Undo all redirections. Called on error or interrupt.
5275 * Discard all saved file descriptors.
5278 clearredir(int drop)
5284 popredir(drop, /*restore:*/ 0);
5289 redirectsafe(union node *redir, int flags)
5292 volatile int saveint;
5293 struct jmploc *volatile savehandler = exception_handler;
5294 struct jmploc jmploc;
5297 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5298 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5300 exception_handler = &jmploc;
5301 redirect(redir, flags);
5303 exception_handler = savehandler;
5304 if (err && exception_type != EXERROR)
5305 longjmp(exception_handler->loc, 1);
5306 RESTORE_INT(saveint);
5311 /* ============ Routines to expand arguments to commands
5313 * We have to deal with backquotes, shell variables, and file metacharacters.
5316 #if ENABLE_SH_MATH_SUPPORT
5318 ash_arith(const char *s)
5320 arith_eval_hooks_t math_hooks;
5324 math_hooks.lookupvar = lookupvar;
5325 math_hooks.setvar = setvar2;
5326 math_hooks.endofname = endofname;
5329 result = arith(s, &errcode, &math_hooks);
5332 ash_msg_and_raise_error("exponent less than 0");
5334 ash_msg_and_raise_error("divide by zero");
5336 ash_msg_and_raise_error("expression recursion loop detected");
5337 raise_error_syntax(s);
5348 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5349 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5350 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5351 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5352 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5353 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5354 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5355 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5356 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5360 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5361 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5362 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5363 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5364 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5367 * Structure specifying which parts of the string should be searched
5368 * for IFS characters.
5371 struct ifsregion *next; /* next region in list */
5372 int begoff; /* offset of start of region */
5373 int endoff; /* offset of end of region */
5374 int nulonly; /* search for nul bytes only */
5378 struct strlist *list;
5379 struct strlist **lastp;
5382 /* output of current string */
5383 static char *expdest;
5384 /* list of back quote expressions */
5385 static struct nodelist *argbackq;
5386 /* first struct in list of ifs regions */
5387 static struct ifsregion ifsfirst;
5388 /* last struct in list */
5389 static struct ifsregion *ifslastp;
5390 /* holds expanded arg list */
5391 static struct arglist exparg;
5401 expdest = makestrspace(32, expdest);
5402 len = fmtstr(expdest, 32, arith_t_fmt, num);
5403 STADJUST(len, expdest);
5408 esclen(const char *start, const char *p)
5412 while (p > start && (unsigned char)*--p == CTLESC) {
5419 * Remove any CTLESC characters from a string.
5422 rmescapes(char *str, int flag)
5424 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5428 unsigned protect_against_glob;
5431 p = strpbrk(str, qchars);
5437 if (flag & RMESCAPE_ALLOC) {
5438 size_t len = p - str;
5439 size_t fulllen = len + strlen(p) + 1;
5441 if (flag & RMESCAPE_GROW) {
5442 int strloc = str - (char *)stackblock();
5443 r = makestrspace(fulllen, expdest);
5444 /* p and str may be invalidated by makestrspace */
5445 str = (char *)stackblock() + strloc;
5447 } else if (flag & RMESCAPE_HEAP) {
5448 r = ckmalloc(fulllen);
5450 r = stalloc(fulllen);
5454 q = (char *)memcpy(q, str, len) + len;
5458 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5459 globbing = flag & RMESCAPE_GLOB;
5460 protect_against_glob = globbing;
5462 if ((unsigned char)*p == CTLQUOTEMARK) {
5463 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5464 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5465 // Note: both inquotes and protect_against_glob only affect whether
5466 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5467 inquotes = ~inquotes;
5469 protect_against_glob = globbing;
5473 /* naked back slash */
5474 protect_against_glob = 0;
5477 if ((unsigned char)*p == CTLESC) {
5479 if (protect_against_glob && inquotes && *p != '/') {
5483 protect_against_glob = globbing;
5488 if (flag & RMESCAPE_GROW) {
5490 STADJUST(q - r + 1, expdest);
5494 #define pmatch(a, b) !fnmatch((a), (b), 0)
5497 * Prepare a pattern for a expmeta (internal glob(3)) call.
5499 * Returns an stalloced string.
5502 preglob(const char *pattern, int quoted, int flag)
5504 flag |= RMESCAPE_GLOB;
5506 flag |= RMESCAPE_QUOTED;
5508 return rmescapes((char *)pattern, flag);
5512 * Put a string on the stack.
5515 memtodest(const char *p, size_t len, int syntax, int quotes)
5519 q = makestrspace(quotes ? len * 2 : len, q);
5522 unsigned char c = *p++;
5526 int n = SIT(c, syntax);
5527 if (n == CCTL || n == CBACK)
5537 strtodest(const char *p, int syntax, int quotes)
5539 memtodest(p, strlen(p), syntax, quotes);
5543 * Record the fact that we have to scan this region of the
5544 * string for IFS characters.
5547 recordregion(int start, int end, int nulonly)
5549 struct ifsregion *ifsp;
5551 if (ifslastp == NULL) {
5555 ifsp = ckzalloc(sizeof(*ifsp));
5556 /*ifsp->next = NULL; - ckzalloc did it */
5557 ifslastp->next = ifsp;
5561 ifslastp->begoff = start;
5562 ifslastp->endoff = end;
5563 ifslastp->nulonly = nulonly;
5567 removerecordregions(int endoff)
5569 if (ifslastp == NULL)
5572 if (ifsfirst.endoff > endoff) {
5573 while (ifsfirst.next != NULL) {
5574 struct ifsregion *ifsp;
5576 ifsp = ifsfirst.next->next;
5577 free(ifsfirst.next);
5578 ifsfirst.next = ifsp;
5581 if (ifsfirst.begoff > endoff)
5584 ifslastp = &ifsfirst;
5585 ifsfirst.endoff = endoff;
5590 ifslastp = &ifsfirst;
5591 while (ifslastp->next && ifslastp->next->begoff < endoff)
5592 ifslastp=ifslastp->next;
5593 while (ifslastp->next != NULL) {
5594 struct ifsregion *ifsp;
5596 ifsp = ifslastp->next->next;
5597 free(ifslastp->next);
5598 ifslastp->next = ifsp;
5601 if (ifslastp->endoff > endoff)
5602 ifslastp->endoff = endoff;
5606 exptilde(char *startp, char *p, int flags)
5612 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5617 while ((c = *++p) != '\0') {
5624 if (flags & EXP_VARTILDE)
5634 if (*name == '\0') {
5635 home = lookupvar("HOME");
5637 pw = getpwnam(name);
5642 if (!home || !*home)
5645 startloc = expdest - (char *)stackblock();
5646 strtodest(home, SQSYNTAX, quotes);
5647 recordregion(startloc, expdest - (char *)stackblock(), 0);
5655 * Execute a command inside back quotes. If it's a builtin command, we
5656 * want to save its output in a block obtained from malloc. Otherwise
5657 * we fork off a subprocess and get the output of the command via a pipe.
5658 * Should be called with interrupts off.
5660 struct backcmd { /* result of evalbackcmd */
5661 int fd; /* file descriptor to read from */
5662 int nleft; /* number of chars in buffer */
5663 char *buf; /* buffer */
5664 struct job *jp; /* job structure for command */
5667 /* These forward decls are needed to use "eval" code for backticks handling: */
5668 static uint8_t back_exitstatus; /* exit status of backquoted command */
5669 #define EV_EXIT 01 /* exit after evaluating tree */
5670 static void evaltree(union node *, int);
5672 static void FAST_FUNC
5673 evalbackcmd(union node *n, struct backcmd *result)
5684 saveherefd = herefd;
5692 ash_msg_and_raise_error("pipe call failed");
5693 jp = makejob(/*n,*/ 1);
5694 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5699 copyfd(pip[1], 1 | COPYFD_EXACT);
5703 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5707 result->fd = pip[0];
5710 herefd = saveherefd;
5712 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5713 result->fd, result->buf, result->nleft, result->jp));
5717 * Expand stuff in backwards quotes.
5720 expbackq(union node *cmd, int quoted, int quotes)
5728 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5729 struct stackmark smark;
5732 setstackmark(&smark);
5734 startloc = dest - (char *)stackblock();
5736 evalbackcmd(cmd, &in);
5737 popstackmark(&smark);
5744 memtodest(p, i, syntax, quotes);
5748 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5749 TRACE(("expbackq: read returns %d\n", i));
5758 back_exitstatus = waitforjob(in.jp);
5762 /* Eat all trailing newlines */
5764 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5769 recordregion(startloc, dest - (char *)stackblock(), 0);
5770 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5771 (dest - (char *)stackblock()) - startloc,
5772 (dest - (char *)stackblock()) - startloc,
5773 stackblock() + startloc));
5776 #if ENABLE_SH_MATH_SUPPORT
5778 * Expand arithmetic expression. Backup to start of expression,
5779 * evaluate, place result in (backed up) result, adjust string position.
5792 * This routine is slightly over-complicated for
5793 * efficiency. Next we scan backwards looking for the
5794 * start of arithmetic.
5796 start = stackblock();
5803 while ((unsigned char)*p != CTLARI) {
5807 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5812 esc = esclen(start, p);
5822 removerecordregions(begoff);
5829 rmescapes(p + 2, 0);
5831 len = cvtnum(ash_arith(p + 2));
5834 recordregion(begoff, begoff + len, 0);
5838 /* argstr needs it */
5839 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5842 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5843 * characters to allow for further processing. Otherwise treat
5844 * $@ like $* since no splitting will be performed.
5846 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5847 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5848 * for correct expansion of "B=$A" word.
5851 argstr(char *p, int flags, struct strlist *var_str_list)
5853 static const char spclchars[] ALIGN1 = {
5861 CTLBACKQ | CTLQUOTE,
5862 #if ENABLE_SH_MATH_SUPPORT
5867 const char *reject = spclchars;
5868 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5869 int breakall = flags & EXP_WORD;
5874 if (!(flags & EXP_VARTILDE)) {
5876 } else if (flags & EXP_VARTILDE2) {
5881 if (flags & EXP_TILDE) {
5884 flags &= ~EXP_TILDE;
5887 if (*q == CTLESC && (flags & EXP_QWORD))
5890 p = exptilde(p, q, flags);
5893 startloc = expdest - (char *)stackblock();
5897 length += strcspn(p + length, reject);
5901 #if ENABLE_SH_MATH_SUPPORT
5905 /* c == '=' || c == ':' || c == CTLENDARI */
5911 expdest = stack_nputstr(p, length, expdest);
5912 newloc = expdest - (char *)stackblock();
5913 if (breakall && !inquotes && newloc > startloc) {
5914 recordregion(startloc, newloc, 0);
5925 if (flags & EXP_VARTILDE2) {
5929 flags |= EXP_VARTILDE2;
5934 * sort of a hack - expand tildes in variable
5935 * assignments (after the first '=' and after ':'s).
5944 case CTLENDVAR: /* ??? */
5947 /* "$@" syntax adherence hack */
5949 && memcmp(p, dolatstr, 4) == 0
5950 && ( p[4] == CTLQUOTEMARK
5951 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5954 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
5957 inquotes = !inquotes;
5970 p = evalvar(p, flags, var_str_list);
5974 case CTLBACKQ|CTLQUOTE:
5975 expbackq(argbackq->n, c, quotes);
5976 argbackq = argbackq->next;
5978 #if ENABLE_SH_MATH_SUPPORT
5991 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
5994 // This commented out code was added by James Simmons <jsimmons@infradead.org>
5995 // as part of a larger change when he added support for ${var/a/b}.
5996 // However, it broke # and % operators:
6000 //echo ${var#ab} abcdcd abcdcd
6001 //echo ${var##ab} abcdcd abcdcd
6002 //echo ${var#a*b} abcdcd ababcdcd (!)
6003 //echo ${var##a*b} cdcd cdcd
6004 //echo ${var#?} babcdcd ababcdcd (!)
6005 //echo ${var##?} babcdcd babcdcd
6006 //echo ${var#*} ababcdcd babcdcd (!)
6008 //echo ${var%cd} ababcd ababcd
6009 //echo ${var%%cd} ababcd abab (!)
6010 //echo ${var%c*d} ababcd ababcd
6011 //echo ${var%%c*d} abab ababcdcd (!)
6012 //echo ${var%?} ababcdc ababcdc
6013 //echo ${var%%?} ababcdc ababcdcd (!)
6014 //echo ${var%*} ababcdcd ababcdcd
6017 // Commenting it back out helped. Remove it completely if it really
6020 char *loc, *loc2; //, *full;
6026 int match; // = strlen(str);
6027 const char *s = loc2;
6034 match = pmatch(str, s); // this line was deleted
6036 // // chop off end if its '*'
6037 // full = strrchr(str, '*');
6038 // if (full && full != str)
6041 // // If str starts with '*' replace with s.
6042 // if ((*str == '*') && strlen(s) >= match) {
6043 // full = xstrdup(s);
6044 // strncpy(full+strlen(s)-match+1, str+1, match-1);
6046 // full = xstrndup(str, match);
6047 // match = strncmp(s, full, strlen(full));
6051 if (match) // if (!match)
6053 if (quotes && (unsigned char)*loc == CTLESC)
6062 scanright(char *startp, char *rmesc, char *rmescend, char *pattern, int quotes, int match_at_start)
6064 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6065 int try2optimize = match_at_start;
6071 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6072 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6073 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6075 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6076 * and on each iteration they go back two/one char until they reach the beginning.
6077 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6079 /* TODO: document in what other circumstances we are called. */
6081 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6084 const char *s = loc2;
6085 if (match_at_start) {
6089 match = pmatch(pattern, s);
6090 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6094 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6096 /* Maybe we can optimize this:
6097 * if pattern ends with unescaped *, we can avoid checking
6098 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6099 * it wont match truncated "raw_value_of_" strings too.
6101 unsigned plen = strlen(pattern);
6102 /* Does it end with "*"? */
6103 if (plen != 0 && pattern[--plen] == '*') {
6104 /* "xxxx*" is not escaped */
6105 /* "xxx\*" is escaped */
6106 /* "xx\\*" is not escaped */
6107 /* "x\\\*" is escaped */
6109 while (plen != 0 && pattern[--plen] == '\\')
6112 break; /* ends with unescaped "*" */
6120 esc = esclen(startp, loc);
6131 static void varunset(const char *, const char *, const char *, int) NORETURN;
6133 varunset(const char *end, const char *var, const char *umsg, int varflags)
6139 msg = "parameter not set";
6141 if ((unsigned char)*end == CTLENDVAR) {
6142 if (varflags & VSNUL)
6148 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6151 #if ENABLE_ASH_BASH_COMPAT
6153 parse_sub_pattern(char *arg, int inquotes)
6155 char *idx, *repl = NULL;
6164 /* Only the first '/' seen is our separator */
6171 if (!inquotes && c == '\\' && arg[1] == '\\')
6172 arg++; /* skip both \\, not just first one */
6179 #endif /* ENABLE_ASH_BASH_COMPAT */
6182 subevalvar(char *p, char *str, int strloc, int subtype,
6183 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6185 struct nodelist *saveargbackq = argbackq;
6188 char *rmesc, *rmescend;
6189 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6190 IF_ASH_BASH_COMPAT(char null = '\0';)
6191 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6192 int saveherefd = herefd;
6193 int amount, workloc, resetloc;
6195 char *(*scan)(char*, char*, char*, char*, int, int);
6198 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6200 STPUTC('\0', expdest);
6201 herefd = saveherefd;
6202 argbackq = saveargbackq;
6203 startp = (char *)stackblock() + startloc;
6207 setvar(str, startp, 0);
6208 amount = startp - expdest;
6209 STADJUST(amount, expdest);
6212 #if ENABLE_ASH_BASH_COMPAT
6214 loc = str = stackblock() + strloc;
6215 /* Read POS in ${var:POS:LEN} */
6216 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6217 len = str - startp - 1;
6219 /* *loc != '\0', guaranteed by parser */
6223 /* Adjust the length by the number of escapes */
6224 for (ptr = startp; ptr < (str - 1); ptr++) {
6225 if ((unsigned char)*ptr == CTLESC) {
6233 if (*loc++ == ':') {
6237 /* Skip POS in ${var:POS:LEN} */
6239 while (*loc && *loc != ':') {
6241 * bash complains on: var=qwe; echo ${var:1a:123}
6243 ash_msg_and_raise_error(msg_illnum, str);
6247 if (*loc++ == ':') {
6251 if (pos >= orig_len) {
6255 if (len > (orig_len - pos))
6256 len = orig_len - pos;
6258 for (str = startp; pos; str++, pos--) {
6259 if (quotes && (unsigned char)*str == CTLESC)
6262 for (loc = startp; len; len--) {
6263 if (quotes && (unsigned char)*str == CTLESC)
6268 amount = loc - expdest;
6269 STADJUST(amount, expdest);
6274 varunset(p, str, startp, varflags);
6277 resetloc = expdest - (char *)stackblock();
6279 /* We'll comeback here if we grow the stack while handling
6280 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6281 * stack will need rebasing, and we'll need to remove our work
6284 IF_ASH_BASH_COMPAT(restart:)
6286 amount = expdest - ((char *)stackblock() + resetloc);
6287 STADJUST(-amount, expdest);
6288 startp = (char *)stackblock() + startloc;
6291 rmescend = (char *)stackblock() + strloc;
6293 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6294 if (rmesc != startp) {
6296 startp = (char *)stackblock() + startloc;
6300 str = (char *)stackblock() + strloc;
6301 preglob(str, varflags & VSQUOTE, 0);
6302 workloc = expdest - (char *)stackblock();
6304 #if ENABLE_ASH_BASH_COMPAT
6305 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6309 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6314 /* If there's no pattern to match, return the expansion unmolested */
6323 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6325 /* No match, advance */
6326 char *restart_detect = stackblock();
6328 STPUTC(*idx, expdest);
6329 if (quotes && (unsigned char)*idx == CTLESC) {
6332 STPUTC(*idx, expdest);
6334 if (stackblock() != restart_detect)
6339 /* continue; - prone to quadratic behavior, smarter code: */
6342 if (str[0] == '*') {
6343 /* Pattern is "*foo". If "*foo" does not match "long_string",
6344 * it would never match "ong_string" etc, no point in trying.
6351 if (subtype == VSREPLACEALL) {
6353 if (quotes && (unsigned char)*idx == CTLESC)
6362 for (loc = repl; *loc; loc++) {
6363 char *restart_detect = stackblock();
6364 STPUTC(*loc, expdest);
6365 if (stackblock() != restart_detect)
6370 if (subtype == VSREPLACE) {
6372 char *restart_detect = stackblock();
6373 STPUTC(*idx, expdest);
6374 if (stackblock() != restart_detect)
6383 /* We've put the replaced text into a buffer at workloc, now
6384 * move it to the right place and adjust the stack.
6386 startp = stackblock() + startloc;
6387 STPUTC('\0', expdest);
6388 memmove(startp, stackblock() + workloc, len);
6389 startp[len++] = '\0';
6390 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6391 STADJUST(-amount, expdest);
6394 #endif /* ENABLE_ASH_BASH_COMPAT */
6396 subtype -= VSTRIMRIGHT;
6398 if (subtype < 0 || subtype > 7)
6401 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6402 zero = subtype >> 1;
6403 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6404 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6406 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6409 memmove(startp, loc, str - loc);
6410 loc = startp + (str - loc) - 1;
6413 amount = loc - expdest;
6414 STADJUST(amount, expdest);
6420 * Add the value of a specialized variable to the stack string.
6421 * name parameter (examples):
6422 * ash -c 'echo $1' name:'1='
6423 * ash -c 'echo $qwe' name:'qwe='
6424 * ash -c 'echo $$' name:'$='
6425 * ash -c 'echo ${$}' name:'$='
6426 * ash -c 'echo ${$##q}' name:'$=q'
6427 * ash -c 'echo ${#$}' name:'$='
6428 * note: examples with bad shell syntax:
6429 * ash -c 'echo ${#$1}' name:'$=1'
6430 * ash -c 'echo ${#1#}' name:'1=#'
6432 static NOINLINE ssize_t
6433 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6440 int subtype = varflags & VSTYPE;
6441 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6442 int quoted = varflags & VSQUOTE;
6443 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6453 num = shellparam.nparam;
6461 goto check_1char_name;
6463 expdest = makestrspace(NOPTS, expdest);
6464 for (i = NOPTS - 1; i >= 0; i--) {
6466 USTPUTC(optletters(i), expdest);
6472 /* handles cases similar to ${#$1} */
6473 if (name[2] != '\0')
6474 raise_error_syntax("bad substitution");
6481 if (quoted && (flags & EXP_FULL)) {
6482 /* note: this is not meant as PEOF value */
6483 sep = 1 << CHAR_BIT;
6488 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6489 i = SIT(sep, syntax);
6490 if (quotes && (i == CCTL || i == CBACK))
6496 while ((p = *ap++) != NULL) {
6499 partlen = strlen(p);
6502 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6503 memtodest(p, partlen, syntax, quotes);
6509 if (subtype == VSPLUS || subtype == VSLENGTH) {
6515 /* note: may put NUL despite sep != 0
6516 * (see sep = 1 << CHAR_BIT above) */
6522 } /* case '@' and '*' */
6533 num = atoi(name); /* number(name) fails on ${N#str} etc */
6534 if (num < 0 || num > shellparam.nparam)
6536 p = num ? shellparam.p[num - 1] : arg0;
6539 /* NB: name has form "VAR=..." */
6541 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6542 * which should be considered before we check variables. */
6544 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6548 str = var_str_list->text;
6549 eq = strchr(str, '=');
6550 if (!eq) /* stop at first non-assignment */
6553 if (name_len == (unsigned)(eq - str)
6554 && strncmp(str, name, name_len) == 0
6557 /* goto value; - WRONG! */
6558 /* think "A=1 A=2 B=$A" */
6560 var_str_list = var_str_list->next;
6561 } while (var_str_list);
6565 p = lookupvar(name);
6571 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6572 memtodest(p, len, syntax, quotes);
6576 if (subtype == VSPLUS || subtype == VSLENGTH)
6577 STADJUST(-len, expdest);
6582 * Expand a variable, and return a pointer to the next character in the
6586 evalvar(char *p, int flags, struct strlist *var_str_list)
6597 varflags = (unsigned char) *p++;
6598 subtype = varflags & VSTYPE;
6599 quoted = varflags & VSQUOTE;
6601 easy = (!quoted || (*var == '@' && shellparam.nparam));
6602 startloc = expdest - (char *)stackblock();
6603 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6606 varlen = varvalue(var, varflags, flags, var_str_list);
6607 if (varflags & VSNUL)
6610 if (subtype == VSPLUS) {
6611 varlen = -1 - varlen;
6615 if (subtype == VSMINUS) {
6619 p, flags | EXP_TILDE |
6620 (quoted ? EXP_QWORD : EXP_WORD),
6630 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6632 if (subevalvar(p, var, /* strloc: */ 0,
6633 subtype, startloc, varflags,
6639 * Remove any recorded regions beyond
6642 removerecordregions(startloc);
6652 if (varlen < 0 && uflag)
6653 varunset(p, var, 0, 0);
6655 if (subtype == VSLENGTH) {
6656 cvtnum(varlen > 0 ? varlen : 0);
6660 if (subtype == VSNORMAL) {
6671 case VSTRIMRIGHTMAX:
6672 #if ENABLE_ASH_BASH_COMPAT
6685 * Terminate the string and start recording the pattern
6688 STPUTC('\0', expdest);
6689 patloc = expdest - (char *)stackblock();
6690 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6692 //TODO: | EXP_REDIR too? All other such places do it too
6693 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6696 int amount = expdest - (
6697 (char *)stackblock() + patloc - 1
6699 STADJUST(-amount, expdest);
6701 /* Remove any recorded regions beyond start of variable */
6702 removerecordregions(startloc);
6704 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6708 if (subtype != VSNORMAL) { /* skip to end of alternative */
6711 unsigned char c = *p++;
6714 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6716 argbackq = argbackq->next;
6717 } else if (c == CTLVAR) {
6718 if ((*p++ & VSTYPE) != VSNORMAL)
6720 } else if (c == CTLENDVAR) {
6730 * Break the argument string into pieces based upon IFS and add the
6731 * strings to the argument list. The regions of the string to be
6732 * searched for IFS characters have been stored by recordregion.
6735 ifsbreakup(char *string, struct arglist *arglist)
6737 struct ifsregion *ifsp;
6742 const char *ifs, *realifs;
6747 if (ifslastp != NULL) {
6750 realifs = ifsset() ? ifsval() : defifs;
6753 p = string + ifsp->begoff;
6754 nulonly = ifsp->nulonly;
6755 ifs = nulonly ? nullstr : realifs;
6757 while (p < string + ifsp->endoff) {
6759 if ((unsigned char)*p == CTLESC)
6761 if (!strchr(ifs, *p)) {
6766 ifsspc = (strchr(defifs, *p) != NULL);
6767 /* Ignore IFS whitespace at start */
6768 if (q == start && ifsspc) {
6774 sp = stzalloc(sizeof(*sp));
6776 *arglist->lastp = sp;
6777 arglist->lastp = &sp->next;
6781 if (p >= string + ifsp->endoff) {
6785 if ((unsigned char)*p == CTLESC)
6787 if (strchr(ifs, *p) == NULL) {
6791 if (strchr(defifs, *p) == NULL) {
6806 } while (ifsp != NULL);
6815 sp = stzalloc(sizeof(*sp));
6817 *arglist->lastp = sp;
6818 arglist->lastp = &sp->next;
6824 struct ifsregion *p;
6829 struct ifsregion *ifsp;
6835 ifsfirst.next = NULL;
6840 * Add a file name to the list.
6843 addfname(const char *name)
6847 sp = stzalloc(sizeof(*sp));
6848 sp->text = ststrdup(name);
6850 exparg.lastp = &sp->next;
6853 static char *expdir;
6856 * Do metacharacter (i.e. *, ?, [...]) expansion.
6859 expmeta(char *enddir, char *name)
6874 for (p = name; *p; p++) {
6875 if (*p == '*' || *p == '?')
6877 else if (*p == '[') {
6884 if (*q == '/' || *q == '\0')
6891 } else if (*p == '\\')
6893 else if (*p == '/') {
6900 if (metaflag == 0) { /* we've reached the end of the file name */
6901 if (enddir != expdir)
6909 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6920 } while (p < start);
6922 if (enddir == expdir) {
6924 } else if (enddir == expdir + 1 && *expdir == '/') {
6933 if (enddir != expdir)
6935 if (*endname == 0) {
6947 while (!pending_int && (dp = readdir(dirp)) != NULL) {
6948 if (dp->d_name[0] == '.' && !matchdot)
6950 if (pmatch(start, dp->d_name)) {
6952 strcpy(enddir, dp->d_name);
6955 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6958 expmeta(p, endname);
6967 static struct strlist *
6968 msort(struct strlist *list, int len)
6970 struct strlist *p, *q = NULL;
6971 struct strlist **lpp;
6979 for (n = half; --n >= 0;) {
6983 q->next = NULL; /* terminate first half of list */
6984 q = msort(list, half); /* sort first half of list */
6985 p = msort(p, len - half); /* sort second half */
6988 #if ENABLE_LOCALE_SUPPORT
6989 if (strcoll(p->text, q->text) < 0)
6991 if (strcmp(p->text, q->text) < 0)
7015 * Sort the results of file name expansion. It calculates the number of
7016 * strings to sort and then calls msort (short for merge sort) to do the
7019 static struct strlist *
7020 expsort(struct strlist *str)
7026 for (sp = str; sp; sp = sp->next)
7028 return msort(str, len);
7032 expandmeta(struct strlist *str /*, int flag*/)
7034 static const char metachars[] ALIGN1 = {
7037 /* TODO - EXP_REDIR */
7040 struct strlist **savelastp;
7046 if (!strpbrk(str->text, metachars))
7048 savelastp = exparg.lastp;
7051 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7053 int i = strlen(str->text);
7054 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7062 if (exparg.lastp == savelastp) {
7067 *exparg.lastp = str;
7068 rmescapes(str->text, 0);
7069 exparg.lastp = &str->next;
7071 *exparg.lastp = NULL;
7072 *savelastp = sp = expsort(*savelastp);
7073 while (sp->next != NULL)
7075 exparg.lastp = &sp->next;
7082 * Perform variable substitution and command substitution on an argument,
7083 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7084 * perform splitting and file name expansion. When arglist is NULL, perform
7085 * here document expansion.
7088 expandarg(union node *arg, struct arglist *arglist, int flag)
7093 argbackq = arg->narg.backquote;
7094 STARTSTACKSTR(expdest);
7095 ifsfirst.next = NULL;
7097 argstr(arg->narg.text, flag,
7098 /* var_str_list: */ arglist ? arglist->list : NULL);
7099 p = _STPUTC('\0', expdest);
7101 if (arglist == NULL) {
7102 return; /* here document expanded */
7104 p = grabstackstr(p);
7105 exparg.lastp = &exparg.list;
7109 if (flag & EXP_FULL) {
7110 ifsbreakup(p, &exparg);
7111 *exparg.lastp = NULL;
7112 exparg.lastp = &exparg.list;
7113 expandmeta(exparg.list /*, flag*/);
7115 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7117 sp = stzalloc(sizeof(*sp));
7120 exparg.lastp = &sp->next;
7124 *exparg.lastp = NULL;
7126 *arglist->lastp = exparg.list;
7127 arglist->lastp = exparg.lastp;
7132 * Expand shell variables and backquotes inside a here document.
7135 expandhere(union node *arg, int fd)
7138 expandarg(arg, (struct arglist *)NULL, 0);
7139 full_write(fd, stackblock(), expdest - (char *)stackblock());
7143 * Returns true if the pattern matches the string.
7146 patmatch(char *pattern, const char *string)
7148 return pmatch(preglob(pattern, 0, 0), string);
7152 * See if a pattern matches in a case statement.
7155 casematch(union node *pattern, char *val)
7157 struct stackmark smark;
7160 setstackmark(&smark);
7161 argbackq = pattern->narg.backquote;
7162 STARTSTACKSTR(expdest);
7164 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7165 /* var_str_list: */ NULL);
7166 STACKSTRNUL(expdest);
7167 result = patmatch(stackblock(), val);
7168 popstackmark(&smark);
7173 /* ============ find_command */
7177 int (*builtin)(int, char **) FAST_FUNC;
7178 /* unsigned flags; */
7180 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7181 /* "regular" builtins always take precedence over commands,
7182 * regardless of PATH=....%builtin... position */
7183 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7184 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7187 smallint cmdtype; /* CMDxxx */
7190 /* index >= 0 for commands without path (slashes) */
7191 /* (TODO: what exactly does the value mean? PATH position?) */
7192 /* index == -1 for commands with slashes */
7193 /* index == (-2 - applet_no) for NOFORK applets */
7194 const struct builtincmd *cmd;
7195 struct funcnode *func;
7198 /* values of cmdtype */
7199 #define CMDUNKNOWN -1 /* no entry in table for command */
7200 #define CMDNORMAL 0 /* command is an executable program */
7201 #define CMDFUNCTION 1 /* command is a shell function */
7202 #define CMDBUILTIN 2 /* command is a shell builtin */
7204 /* action to find_command() */
7205 #define DO_ERR 0x01 /* prints errors */
7206 #define DO_ABS 0x02 /* checks absolute paths */
7207 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7208 #define DO_ALTPATH 0x08 /* using alternate path */
7209 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7211 static void find_command(char *, struct cmdentry *, int, const char *);
7214 /* ============ Hashing commands */
7217 * When commands are first encountered, they are entered in a hash table.
7218 * This ensures that a full path search will not have to be done for them
7219 * on each invocation.
7221 * We should investigate converting to a linear search, even though that
7222 * would make the command name "hash" a misnomer.
7226 struct tblentry *next; /* next entry in hash chain */
7227 union param param; /* definition of builtin function */
7228 smallint cmdtype; /* CMDxxx */
7229 char rehash; /* if set, cd done since entry created */
7230 char cmdname[1]; /* name of command */
7233 static struct tblentry **cmdtable;
7234 #define INIT_G_cmdtable() do { \
7235 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7238 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7242 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7246 #if ENABLE_FEATURE_SH_STANDALONE
7247 if (applet_no >= 0) {
7248 if (APPLET_IS_NOEXEC(applet_no)) {
7252 run_applet_no_and_exit(applet_no, argv);
7254 /* re-exec ourselves with the new arguments */
7255 execve(bb_busybox_exec_path, argv, envp);
7256 /* If they called chroot or otherwise made the binary no longer
7257 * executable, fall through */
7264 execve(cmd, argv, envp);
7265 } while (errno == EINTR);
7267 execve(cmd, argv, envp);
7273 if (errno == ENOEXEC) {
7277 for (ap = argv; *ap; ap++)
7279 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7281 ap[0] = cmd = (char *)DEFAULT_SHELL;
7284 while ((*ap++ = *argv++) != NULL)
7293 * Exec a program. Never returns. If you change this routine, you may
7294 * have to change the find_command routine as well.
7296 static void shellexec(char **, const char *, int) NORETURN;
7298 shellexec(char **argv, const char *path, int idx)
7304 #if ENABLE_FEATURE_SH_STANDALONE
7308 clearredir(/*drop:*/ 1);
7309 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7310 if (strchr(argv[0], '/') != NULL
7311 #if ENABLE_FEATURE_SH_STANDALONE
7312 || (applet_no = find_applet_by_name(argv[0])) >= 0
7315 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7319 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7320 if (--idx < 0 && pathopt == NULL) {
7321 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7322 if (errno != ENOENT && errno != ENOTDIR)
7329 /* Map to POSIX errors */
7341 exitstatus = exerrno;
7342 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7343 argv[0], e, suppress_int));
7344 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7349 printentry(struct tblentry *cmdp)
7355 idx = cmdp->param.index;
7358 name = path_advance(&path, cmdp->cmdname);
7360 } while (--idx >= 0);
7361 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7365 * Clear out command entries. The argument specifies the first entry in
7366 * PATH which has changed.
7369 clearcmdentry(int firstchange)
7371 struct tblentry **tblp;
7372 struct tblentry **pp;
7373 struct tblentry *cmdp;
7376 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7378 while ((cmdp = *pp) != NULL) {
7379 if ((cmdp->cmdtype == CMDNORMAL &&
7380 cmdp->param.index >= firstchange)
7381 || (cmdp->cmdtype == CMDBUILTIN &&
7382 builtinloc >= firstchange)
7395 * Locate a command in the command hash table. If "add" is nonzero,
7396 * add the command to the table if it is not already present. The
7397 * variable "lastcmdentry" is set to point to the address of the link
7398 * pointing to the entry, so that delete_cmd_entry can delete the
7401 * Interrupts must be off if called with add != 0.
7403 static struct tblentry **lastcmdentry;
7405 static struct tblentry *
7406 cmdlookup(const char *name, int add)
7408 unsigned int hashval;
7410 struct tblentry *cmdp;
7411 struct tblentry **pp;
7414 hashval = (unsigned char)*p << 4;
7416 hashval += (unsigned char)*p++;
7418 pp = &cmdtable[hashval % CMDTABLESIZE];
7419 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7420 if (strcmp(cmdp->cmdname, name) == 0)
7424 if (add && cmdp == NULL) {
7425 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7427 /* + 1 - already done because
7428 * tblentry::cmdname is char[1] */);
7429 /*cmdp->next = NULL; - ckzalloc did it */
7430 cmdp->cmdtype = CMDUNKNOWN;
7431 strcpy(cmdp->cmdname, name);
7438 * Delete the command entry returned on the last lookup.
7441 delete_cmd_entry(void)
7443 struct tblentry *cmdp;
7446 cmdp = *lastcmdentry;
7447 *lastcmdentry = cmdp->next;
7448 if (cmdp->cmdtype == CMDFUNCTION)
7449 freefunc(cmdp->param.func);
7455 * Add a new command entry, replacing any existing command entry for
7456 * the same name - except special builtins.
7459 addcmdentry(char *name, struct cmdentry *entry)
7461 struct tblentry *cmdp;
7463 cmdp = cmdlookup(name, 1);
7464 if (cmdp->cmdtype == CMDFUNCTION) {
7465 freefunc(cmdp->param.func);
7467 cmdp->cmdtype = entry->cmdtype;
7468 cmdp->param = entry->u;
7472 static int FAST_FUNC
7473 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7475 struct tblentry **pp;
7476 struct tblentry *cmdp;
7478 struct cmdentry entry;
7481 if (nextopt("r") != '\0') {
7486 if (*argptr == NULL) {
7487 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7488 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7489 if (cmdp->cmdtype == CMDNORMAL)
7497 while ((name = *argptr) != NULL) {
7498 cmdp = cmdlookup(name, 0);
7500 && (cmdp->cmdtype == CMDNORMAL
7501 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7505 find_command(name, &entry, DO_ERR, pathval());
7506 if (entry.cmdtype == CMDUNKNOWN)
7514 * Called when a cd is done. Marks all commands so the next time they
7515 * are executed they will be rehashed.
7520 struct tblentry **pp;
7521 struct tblentry *cmdp;
7523 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7524 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7525 if (cmdp->cmdtype == CMDNORMAL
7526 || (cmdp->cmdtype == CMDBUILTIN
7527 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7537 * Fix command hash table when PATH changed.
7538 * Called before PATH is changed. The argument is the new value of PATH;
7539 * pathval() still returns the old value at this point.
7540 * Called with interrupts off.
7542 static void FAST_FUNC
7543 changepath(const char *new)
7551 firstchange = 9999; /* assume no change */
7557 if ((*old == '\0' && *new == ':')
7558 || (*old == ':' && *new == '\0')
7562 old = new; /* ignore subsequent differences */
7566 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7573 if (builtinloc < 0 && idx_bltin >= 0)
7574 builtinloc = idx_bltin; /* zap builtins */
7575 if (builtinloc >= 0 && idx_bltin < 0)
7577 clearcmdentry(firstchange);
7578 builtinloc = idx_bltin;
7593 #define TENDBQUOTE 12
7610 typedef smallint token_id_t;
7612 /* first char is indicating which tokens mark the end of a list */
7613 static const char *const tokname_array[] = {
7627 #define KWDOFFSET 13
7628 /* the following are keywords */
7647 /* Wrapper around strcmp for qsort/bsearch/... */
7649 pstrcmp(const void *a, const void *b)
7651 return strcmp((char*) a, (*(char**) b) + 1);
7654 static const char *const *
7655 findkwd(const char *s)
7657 return bsearch(s, tokname_array + KWDOFFSET,
7658 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7659 sizeof(tokname_array[0]), pstrcmp);
7663 * Locate and print what a word is...
7666 describe_command(char *command, int describe_command_verbose)
7668 struct cmdentry entry;
7669 struct tblentry *cmdp;
7670 #if ENABLE_ASH_ALIAS
7671 const struct alias *ap;
7673 const char *path = pathval();
7675 if (describe_command_verbose) {
7679 /* First look at the keywords */
7680 if (findkwd(command)) {
7681 out1str(describe_command_verbose ? " is a shell keyword" : command);
7685 #if ENABLE_ASH_ALIAS
7686 /* Then look at the aliases */
7687 ap = lookupalias(command, 0);
7689 if (!describe_command_verbose) {
7694 out1fmt(" is an alias for %s", ap->val);
7698 /* Then check if it is a tracked alias */
7699 cmdp = cmdlookup(command, 0);
7701 entry.cmdtype = cmdp->cmdtype;
7702 entry.u = cmdp->param;
7704 /* Finally use brute force */
7705 find_command(command, &entry, DO_ABS, path);
7708 switch (entry.cmdtype) {
7710 int j = entry.u.index;
7716 p = path_advance(&path, command);
7720 if (describe_command_verbose) {
7722 (cmdp ? " a tracked alias for" : nullstr), p
7731 if (describe_command_verbose) {
7732 out1str(" is a shell function");
7739 if (describe_command_verbose) {
7740 out1fmt(" is a %sshell builtin",
7741 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7742 "special " : nullstr
7750 if (describe_command_verbose) {
7751 out1str(": not found\n");
7760 static int FAST_FUNC
7761 typecmd(int argc UNUSED_PARAM, char **argv)
7767 /* type -p ... ? (we don't bother checking for 'p') */
7768 if (argv[1] && argv[1][0] == '-') {
7773 err |= describe_command(argv[i++], verbose);
7778 #if ENABLE_ASH_CMDCMD
7779 static int FAST_FUNC
7780 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7788 while ((c = nextopt("pvV")) != '\0')
7790 verify |= VERIFY_VERBOSE;
7792 verify |= VERIFY_BRIEF;
7797 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7798 if (verify && (*argptr != NULL)) {
7799 return describe_command(*argptr, verify - VERIFY_BRIEF);
7807 /* ============ eval.c */
7809 static int funcblocksize; /* size of structures in function */
7810 static int funcstringsize; /* size of strings in node */
7811 static void *funcblock; /* block to allocate function from */
7812 static char *funcstring; /* block to allocate strings from */
7814 /* flags in argument to evaltree */
7815 #define EV_EXIT 01 /* exit after evaluating tree */
7816 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7817 #define EV_BACKCMD 04 /* command executing within back quotes */
7819 static const uint8_t nodesize[N_NUMBER] = {
7820 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7821 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7822 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7823 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7824 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7825 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7826 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7827 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7828 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7829 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7830 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7831 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7832 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7833 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7834 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7835 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7836 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7837 #if ENABLE_ASH_BASH_COMPAT
7838 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7840 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7841 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7842 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7843 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7844 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7845 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7846 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7847 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7848 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7851 static void calcsize(union node *n);
7854 sizenodelist(struct nodelist *lp)
7857 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7864 calcsize(union node *n)
7868 funcblocksize += nodesize[n->type];
7871 calcsize(n->ncmd.redirect);
7872 calcsize(n->ncmd.args);
7873 calcsize(n->ncmd.assign);
7876 sizenodelist(n->npipe.cmdlist);
7881 calcsize(n->nredir.redirect);
7882 calcsize(n->nredir.n);
7889 calcsize(n->nbinary.ch2);
7890 calcsize(n->nbinary.ch1);
7893 calcsize(n->nif.elsepart);
7894 calcsize(n->nif.ifpart);
7895 calcsize(n->nif.test);
7898 funcstringsize += strlen(n->nfor.var) + 1;
7899 calcsize(n->nfor.body);
7900 calcsize(n->nfor.args);
7903 calcsize(n->ncase.cases);
7904 calcsize(n->ncase.expr);
7907 calcsize(n->nclist.body);
7908 calcsize(n->nclist.pattern);
7909 calcsize(n->nclist.next);
7913 sizenodelist(n->narg.backquote);
7914 funcstringsize += strlen(n->narg.text) + 1;
7915 calcsize(n->narg.next);
7918 #if ENABLE_ASH_BASH_COMPAT
7925 calcsize(n->nfile.fname);
7926 calcsize(n->nfile.next);
7930 calcsize(n->ndup.vname);
7931 calcsize(n->ndup.next);
7935 calcsize(n->nhere.doc);
7936 calcsize(n->nhere.next);
7939 calcsize(n->nnot.com);
7945 nodeckstrdup(char *s)
7947 char *rtn = funcstring;
7949 strcpy(funcstring, s);
7950 funcstring += strlen(s) + 1;
7954 static union node *copynode(union node *);
7956 static struct nodelist *
7957 copynodelist(struct nodelist *lp)
7959 struct nodelist *start;
7960 struct nodelist **lpp;
7965 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7966 (*lpp)->n = copynode(lp->n);
7968 lpp = &(*lpp)->next;
7975 copynode(union node *n)
7982 funcblock = (char *) funcblock + nodesize[n->type];
7986 new->ncmd.redirect = copynode(n->ncmd.redirect);
7987 new->ncmd.args = copynode(n->ncmd.args);
7988 new->ncmd.assign = copynode(n->ncmd.assign);
7991 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7992 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
7997 new->nredir.redirect = copynode(n->nredir.redirect);
7998 new->nredir.n = copynode(n->nredir.n);
8005 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8006 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8009 new->nif.elsepart = copynode(n->nif.elsepart);
8010 new->nif.ifpart = copynode(n->nif.ifpart);
8011 new->nif.test = copynode(n->nif.test);
8014 new->nfor.var = nodeckstrdup(n->nfor.var);
8015 new->nfor.body = copynode(n->nfor.body);
8016 new->nfor.args = copynode(n->nfor.args);
8019 new->ncase.cases = copynode(n->ncase.cases);
8020 new->ncase.expr = copynode(n->ncase.expr);
8023 new->nclist.body = copynode(n->nclist.body);
8024 new->nclist.pattern = copynode(n->nclist.pattern);
8025 new->nclist.next = copynode(n->nclist.next);
8029 new->narg.backquote = copynodelist(n->narg.backquote);
8030 new->narg.text = nodeckstrdup(n->narg.text);
8031 new->narg.next = copynode(n->narg.next);
8034 #if ENABLE_ASH_BASH_COMPAT
8041 new->nfile.fname = copynode(n->nfile.fname);
8042 new->nfile.fd = n->nfile.fd;
8043 new->nfile.next = copynode(n->nfile.next);
8047 new->ndup.vname = copynode(n->ndup.vname);
8048 new->ndup.dupfd = n->ndup.dupfd;
8049 new->ndup.fd = n->ndup.fd;
8050 new->ndup.next = copynode(n->ndup.next);
8054 new->nhere.doc = copynode(n->nhere.doc);
8055 new->nhere.fd = n->nhere.fd;
8056 new->nhere.next = copynode(n->nhere.next);
8059 new->nnot.com = copynode(n->nnot.com);
8062 new->type = n->type;
8067 * Make a copy of a parse tree.
8069 static struct funcnode *
8070 copyfunc(union node *n)
8075 funcblocksize = offsetof(struct funcnode, n);
8078 blocksize = funcblocksize;
8079 f = ckmalloc(blocksize + funcstringsize);
8080 funcblock = (char *) f + offsetof(struct funcnode, n);
8081 funcstring = (char *) f + blocksize;
8088 * Define a shell function.
8091 defun(char *name, union node *func)
8093 struct cmdentry entry;
8096 entry.cmdtype = CMDFUNCTION;
8097 entry.u.func = copyfunc(func);
8098 addcmdentry(name, &entry);
8102 /* Reasons for skipping commands (see comment on breakcmd routine) */
8103 #define SKIPBREAK (1 << 0)
8104 #define SKIPCONT (1 << 1)
8105 #define SKIPFUNC (1 << 2)
8106 #define SKIPFILE (1 << 3)
8107 #define SKIPEVAL (1 << 4)
8108 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8109 static int skipcount; /* number of levels to skip */
8110 static int funcnest; /* depth of function calls */
8111 static int loopnest; /* current loop nesting level */
8113 /* Forward decl way out to parsing code - dotrap needs it */
8114 static int evalstring(char *s, int mask);
8116 /* Called to execute a trap.
8117 * Single callsite - at the end of evaltree().
8118 * If we return non-zero, exaltree raises EXEXIT exception.
8120 * Perhaps we should avoid entering new trap handlers
8121 * while we are executing a trap handler. [is it a TODO?]
8130 savestatus = exitstatus;
8134 TRACE(("dotrap entered\n"));
8135 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8142 /* non-trapped SIGINT is handled separately by raise_interrupt,
8143 * don't upset it by resetting gotsig[SIGINT-1] */
8144 if (sig == SIGINT && !t)
8147 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8151 want_exexit = evalstring(t, SKIPEVAL);
8152 exitstatus = savestatus;
8154 TRACE(("dotrap returns %d\n", want_exexit));
8159 TRACE(("dotrap returns 0\n"));
8163 /* forward declarations - evaluation is fairly recursive business... */
8164 static void evalloop(union node *, int);
8165 static void evalfor(union node *, int);
8166 static void evalcase(union node *, int);
8167 static void evalsubshell(union node *, int);
8168 static void expredir(union node *);
8169 static void evalpipe(union node *, int);
8170 static void evalcommand(union node *, int);
8171 static int evalbltin(const struct builtincmd *, int, char **);
8172 static void prehash(union node *);
8175 * Evaluate a parse tree. The value is left in the global variable
8179 evaltree(union node *n, int flags)
8181 struct jmploc *volatile savehandler = exception_handler;
8182 struct jmploc jmploc;
8184 void (*evalfn)(union node *, int);
8188 SAVE_INT(int_level);
8191 TRACE(("evaltree(NULL) called\n"));
8194 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8196 exception_handler = &jmploc;
8198 int err = setjmp(jmploc.loc);
8200 /* if it was a signal, check for trap handlers */
8201 if (exception_type == EXSIG) {
8202 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8203 exception_type, err));
8206 /* continue on the way out */
8207 TRACE(("exception %d in evaltree, propagating err=%d\n",
8208 exception_type, err));
8209 exception_handler = savehandler;
8210 longjmp(exception_handler->loc, err);
8217 out1fmt("Node type = %d\n", n->type);
8222 evaltree(n->nnot.com, EV_TESTED);
8223 status = !exitstatus;
8226 expredir(n->nredir.redirect);
8227 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8229 evaltree(n->nredir.n, flags & EV_TESTED);
8230 status = exitstatus;
8232 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8235 evalfn = evalcommand;
8237 if (eflag && !(flags & EV_TESTED))
8249 evalfn = evalsubshell;
8262 #error NAND + 1 != NOR
8264 #if NOR + 1 != NSEMI
8265 #error NOR + 1 != NSEMI
8267 unsigned is_or = n->type - NAND;
8270 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8272 if (!exitstatus == is_or)
8285 evaltree(n->nif.test, EV_TESTED);
8288 if (exitstatus == 0) {
8292 if (n->nif.elsepart) {
8293 n = n->nif.elsepart;
8298 defun(n->narg.text, n->narg.next);
8302 exitstatus = status;
8307 exception_handler = savehandler;
8309 if (checkexit & exitstatus)
8310 evalskip |= SKIPEVAL;
8311 else if (pending_sig && dotrap())
8314 if (flags & EV_EXIT) {
8316 raise_exception(EXEXIT);
8319 RESTORE_INT(int_level);
8320 TRACE(("leaving evaltree (no interrupts)\n"));
8323 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8326 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8329 evalloop(union node *n, int flags)
8339 evaltree(n->nbinary.ch1, EV_TESTED);
8342 if (evalskip == SKIPCONT && --skipcount <= 0) {
8346 if (evalskip == SKIPBREAK && --skipcount <= 0)
8351 if (n->type != NWHILE)
8355 evaltree(n->nbinary.ch2, flags);
8356 status = exitstatus;
8361 exitstatus = status;
8365 evalfor(union node *n, int flags)
8367 struct arglist arglist;
8370 struct stackmark smark;
8372 setstackmark(&smark);
8373 arglist.list = NULL;
8374 arglist.lastp = &arglist.list;
8375 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8376 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8381 *arglist.lastp = NULL;
8386 for (sp = arglist.list; sp; sp = sp->next) {
8387 setvar(n->nfor.var, sp->text, 0);
8388 evaltree(n->nfor.body, flags);
8390 if (evalskip == SKIPCONT && --skipcount <= 0) {
8394 if (evalskip == SKIPBREAK && --skipcount <= 0)
8401 popstackmark(&smark);
8405 evalcase(union node *n, int flags)
8409 struct arglist arglist;
8410 struct stackmark smark;
8412 setstackmark(&smark);
8413 arglist.list = NULL;
8414 arglist.lastp = &arglist.list;
8415 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8417 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8418 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8419 if (casematch(patp, arglist.list->text)) {
8420 if (evalskip == 0) {
8421 evaltree(cp->nclist.body, flags);
8428 popstackmark(&smark);
8432 * Kick off a subshell to evaluate a tree.
8435 evalsubshell(union node *n, int flags)
8438 int backgnd = (n->type == NBACKGND);
8441 expredir(n->nredir.redirect);
8442 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8445 jp = makejob(/*n,*/ 1);
8446 if (forkshell(jp, n, backgnd) == 0) {
8451 flags &= ~EV_TESTED;
8453 redirect(n->nredir.redirect, 0);
8454 evaltreenr(n->nredir.n, flags);
8459 status = waitforjob(jp);
8460 exitstatus = status;
8465 * Compute the names of the files in a redirection list.
8467 static void fixredir(union node *, const char *, int);
8469 expredir(union node *n)
8473 for (redir = n; redir; redir = redir->nfile.next) {
8477 fn.lastp = &fn.list;
8478 switch (redir->type) {
8482 #if ENABLE_ASH_BASH_COMPAT
8487 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8488 #if ENABLE_ASH_BASH_COMPAT
8491 redir->nfile.expfname = fn.list->text;
8494 case NTOFD: /* >& */
8495 if (redir->ndup.vname) {
8496 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8497 if (fn.list == NULL)
8498 ash_msg_and_raise_error("redir error");
8499 #if ENABLE_ASH_BASH_COMPAT
8500 //FIXME: we used expandarg with different args!
8501 if (!isdigit_str9(fn.list->text)) {
8502 /* >&file, not >&fd */
8503 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8504 ash_msg_and_raise_error("redir error");
8506 goto store_expfname;
8509 fixredir(redir, fn.list->text, 1);
8517 * Evaluate a pipeline. All the processes in the pipeline are children
8518 * of the process creating the pipeline. (This differs from some versions
8519 * of the shell, which make the last process in a pipeline the parent
8523 evalpipe(union node *n, int flags)
8526 struct nodelist *lp;
8531 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8533 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8537 jp = makejob(/*n,*/ pipelen);
8539 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8543 if (pipe(pip) < 0) {
8545 ash_msg_and_raise_error("pipe call failed");
8548 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8561 evaltreenr(lp->n, flags);
8567 /* Don't want to trigger debugging */
8571 if (n->npipe.pipe_backgnd == 0) {
8572 exitstatus = waitforjob(jp);
8573 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8579 * Controls whether the shell is interactive or not.
8582 setinteractive(int on)
8584 static smallint is_interactive;
8586 if (++on == is_interactive)
8588 is_interactive = on;
8592 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8593 if (is_interactive > 1) {
8594 /* Looks like they want an interactive shell */
8595 static smallint did_banner;
8598 /* note: ash and hush share this string */
8599 out1fmt("\n\n%s %s\n"
8600 "Enter 'help' for a list of built-in commands."
8603 "built-in shell (ash)"
8617 setinteractive(iflag);
8619 #if ENABLE_FEATURE_EDITING_VI
8621 line_input_state->flags |= VI_MODE;
8623 line_input_state->flags &= ~VI_MODE;
8625 viflag = 0; /* forcibly keep the option off */
8629 static struct localvar *localvars;
8632 * Called after a function returns.
8633 * Interrupts must be off.
8638 struct localvar *lvp;
8641 while ((lvp = localvars) != NULL) {
8642 localvars = lvp->next;
8644 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8645 if (vp == NULL) { /* $- saved */
8646 memcpy(optlist, lvp->text, sizeof(optlist));
8647 free((char*)lvp->text);
8649 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8650 unsetvar(vp->var_text);
8653 vp->var_func(var_end(lvp->text));
8654 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8655 free((char*)vp->var_text);
8656 vp->flags = lvp->flags;
8657 vp->var_text = lvp->text;
8664 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8666 volatile struct shparam saveparam;
8667 struct localvar *volatile savelocalvars;
8668 struct jmploc *volatile savehandler;
8669 struct jmploc jmploc;
8672 saveparam = shellparam;
8673 savelocalvars = localvars;
8674 e = setjmp(jmploc.loc);
8679 savehandler = exception_handler;
8680 exception_handler = &jmploc;
8682 shellparam.malloced = 0;
8686 shellparam.nparam = argc - 1;
8687 shellparam.p = argv + 1;
8688 #if ENABLE_ASH_GETOPTS
8689 shellparam.optind = 1;
8690 shellparam.optoff = -1;
8692 evaltree(&func->n, flags & EV_TESTED);
8698 localvars = savelocalvars;
8699 freeparam(&shellparam);
8700 shellparam = saveparam;
8701 exception_handler = savehandler;
8703 evalskip &= ~SKIPFUNC;
8707 #if ENABLE_ASH_CMDCMD
8709 parse_command_args(char **argv, const char **path)
8722 if (c == '-' && !*cp) {
8729 *path = bb_default_path;
8732 /* run 'typecmd' for other options */
8743 * Make a variable a local variable. When a variable is made local, it's
8744 * value and flags are saved in a localvar structure. The saved values
8745 * will be restored when the shell function returns. We handle the name
8746 * "-" as a special case.
8751 struct localvar *lvp;
8756 lvp = ckzalloc(sizeof(struct localvar));
8757 if (LONE_DASH(name)) {
8759 p = ckmalloc(sizeof(optlist));
8760 lvp->text = memcpy(p, optlist, sizeof(optlist));
8765 vpp = hashvar(name);
8766 vp = *findvar(vpp, name);
8767 eq = strchr(name, '=');
8770 setvareq(name, VSTRFIXED);
8772 setvar(name, NULL, VSTRFIXED);
8773 vp = *vpp; /* the new variable */
8774 lvp->flags = VUNSET;
8776 lvp->text = vp->var_text;
8777 lvp->flags = vp->flags;
8778 vp->flags |= VSTRFIXED|VTEXTFIXED;
8784 lvp->next = localvars;
8790 * The "local" command.
8792 static int FAST_FUNC
8793 localcmd(int argc UNUSED_PARAM, char **argv)
8798 while ((name = *argv++) != NULL) {
8804 static int FAST_FUNC
8805 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8810 static int FAST_FUNC
8811 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8816 static int FAST_FUNC
8817 execcmd(int argc UNUSED_PARAM, char **argv)
8820 iflag = 0; /* exit on error */
8823 shellexec(argv + 1, pathval(), 0);
8829 * The return command.
8831 static int FAST_FUNC
8832 returncmd(int argc UNUSED_PARAM, char **argv)
8835 * If called outside a function, do what ksh does;
8836 * skip the rest of the file.
8838 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8839 return argv[1] ? number(argv[1]) : exitstatus;
8842 /* Forward declarations for builtintab[] */
8843 static int breakcmd(int, char **) FAST_FUNC;
8844 static int dotcmd(int, char **) FAST_FUNC;
8845 static int evalcmd(int, char **) FAST_FUNC;
8846 static int exitcmd(int, char **) FAST_FUNC;
8847 static int exportcmd(int, char **) FAST_FUNC;
8848 #if ENABLE_ASH_GETOPTS
8849 static int getoptscmd(int, char **) FAST_FUNC;
8851 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8852 static int helpcmd(int, char **) FAST_FUNC;
8854 #if ENABLE_SH_MATH_SUPPORT
8855 static int letcmd(int, char **) FAST_FUNC;
8857 static int readcmd(int, char **) FAST_FUNC;
8858 static int setcmd(int, char **) FAST_FUNC;
8859 static int shiftcmd(int, char **) FAST_FUNC;
8860 static int timescmd(int, char **) FAST_FUNC;
8861 static int trapcmd(int, char **) FAST_FUNC;
8862 static int umaskcmd(int, char **) FAST_FUNC;
8863 static int unsetcmd(int, char **) FAST_FUNC;
8864 static int ulimitcmd(int, char **) FAST_FUNC;
8866 #define BUILTIN_NOSPEC "0"
8867 #define BUILTIN_SPECIAL "1"
8868 #define BUILTIN_REGULAR "2"
8869 #define BUILTIN_SPEC_REG "3"
8870 #define BUILTIN_ASSIGN "4"
8871 #define BUILTIN_SPEC_ASSG "5"
8872 #define BUILTIN_REG_ASSG "6"
8873 #define BUILTIN_SPEC_REG_ASSG "7"
8875 /* Stubs for calling non-FAST_FUNC's */
8876 #if ENABLE_ASH_BUILTIN_ECHO
8877 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8879 #if ENABLE_ASH_BUILTIN_PRINTF
8880 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8882 #if ENABLE_ASH_BUILTIN_TEST
8883 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8886 /* Keep these in proper order since it is searched via bsearch() */
8887 static const struct builtincmd builtintab[] = {
8888 { BUILTIN_SPEC_REG "." , dotcmd },
8889 { BUILTIN_SPEC_REG ":" , truecmd },
8890 #if ENABLE_ASH_BUILTIN_TEST
8891 { BUILTIN_REGULAR "[" , testcmd },
8892 #if ENABLE_ASH_BASH_COMPAT
8893 { BUILTIN_REGULAR "[[" , testcmd },
8896 #if ENABLE_ASH_ALIAS
8897 { BUILTIN_REG_ASSG "alias" , aliascmd },
8900 { BUILTIN_REGULAR "bg" , fg_bgcmd },
8902 { BUILTIN_SPEC_REG "break" , breakcmd },
8903 { BUILTIN_REGULAR "cd" , cdcmd },
8904 { BUILTIN_NOSPEC "chdir" , cdcmd },
8905 #if ENABLE_ASH_CMDCMD
8906 { BUILTIN_REGULAR "command" , commandcmd },
8908 { BUILTIN_SPEC_REG "continue", breakcmd },
8909 #if ENABLE_ASH_BUILTIN_ECHO
8910 { BUILTIN_REGULAR "echo" , echocmd },
8912 { BUILTIN_SPEC_REG "eval" , evalcmd },
8913 { BUILTIN_SPEC_REG "exec" , execcmd },
8914 { BUILTIN_SPEC_REG "exit" , exitcmd },
8915 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
8916 { BUILTIN_REGULAR "false" , falsecmd },
8918 { BUILTIN_REGULAR "fg" , fg_bgcmd },
8920 #if ENABLE_ASH_GETOPTS
8921 { BUILTIN_REGULAR "getopts" , getoptscmd },
8923 { BUILTIN_NOSPEC "hash" , hashcmd },
8924 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8925 { BUILTIN_NOSPEC "help" , helpcmd },
8928 { BUILTIN_REGULAR "jobs" , jobscmd },
8929 { BUILTIN_REGULAR "kill" , killcmd },
8931 #if ENABLE_SH_MATH_SUPPORT
8932 { BUILTIN_NOSPEC "let" , letcmd },
8934 { BUILTIN_ASSIGN "local" , localcmd },
8935 #if ENABLE_ASH_BUILTIN_PRINTF
8936 { BUILTIN_REGULAR "printf" , printfcmd },
8938 { BUILTIN_NOSPEC "pwd" , pwdcmd },
8939 { BUILTIN_REGULAR "read" , readcmd },
8940 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8941 { BUILTIN_SPEC_REG "return" , returncmd },
8942 { BUILTIN_SPEC_REG "set" , setcmd },
8943 { BUILTIN_SPEC_REG "shift" , shiftcmd },
8944 #if ENABLE_ASH_BASH_COMPAT
8945 { BUILTIN_SPEC_REG "source" , dotcmd },
8947 #if ENABLE_ASH_BUILTIN_TEST
8948 { BUILTIN_REGULAR "test" , testcmd },
8950 { BUILTIN_SPEC_REG "times" , timescmd },
8951 { BUILTIN_SPEC_REG "trap" , trapcmd },
8952 { BUILTIN_REGULAR "true" , truecmd },
8953 { BUILTIN_NOSPEC "type" , typecmd },
8954 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
8955 { BUILTIN_REGULAR "umask" , umaskcmd },
8956 #if ENABLE_ASH_ALIAS
8957 { BUILTIN_REGULAR "unalias" , unaliascmd },
8959 { BUILTIN_SPEC_REG "unset" , unsetcmd },
8960 { BUILTIN_REGULAR "wait" , waitcmd },
8963 /* Should match the above table! */
8964 #define COMMANDCMD (builtintab + \
8966 1 * ENABLE_ASH_BUILTIN_TEST + \
8967 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8968 1 * ENABLE_ASH_ALIAS + \
8969 1 * ENABLE_ASH_JOB_CONTROL + \
8971 #define EXECCMD (builtintab + \
8973 1 * ENABLE_ASH_BUILTIN_TEST + \
8974 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8975 1 * ENABLE_ASH_ALIAS + \
8976 1 * ENABLE_ASH_JOB_CONTROL + \
8978 1 * ENABLE_ASH_CMDCMD + \
8980 ENABLE_ASH_BUILTIN_ECHO + \
8984 * Search the table of builtin commands.
8986 static struct builtincmd *
8987 find_builtin(const char *name)
8989 struct builtincmd *bp;
8992 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8999 * Execute a simple command.
9002 isassignment(const char *p)
9004 const char *q = endofname(p);
9009 static int FAST_FUNC
9010 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9012 /* Preserve exitstatus of a previous possible redirection
9013 * as POSIX mandates */
9014 return back_exitstatus;
9017 evalcommand(union node *cmd, int flags)
9019 static const struct builtincmd null_bltin = {
9020 "\0\0", bltincmd /* why three NULs? */
9022 struct stackmark smark;
9024 struct arglist arglist;
9025 struct arglist varlist;
9028 const struct strlist *sp;
9029 struct cmdentry cmdentry;
9036 struct builtincmd *bcmd;
9037 smallint cmd_is_exec;
9038 smallint pseudovarflag = 0;
9040 /* First expand the arguments. */
9041 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9042 setstackmark(&smark);
9043 back_exitstatus = 0;
9045 cmdentry.cmdtype = CMDBUILTIN;
9046 cmdentry.u.cmd = &null_bltin;
9047 varlist.lastp = &varlist.list;
9048 *varlist.lastp = NULL;
9049 arglist.lastp = &arglist.list;
9050 *arglist.lastp = NULL;
9053 if (cmd->ncmd.args) {
9054 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9055 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9058 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9059 struct strlist **spp;
9061 spp = arglist.lastp;
9062 if (pseudovarflag && isassignment(argp->narg.text))
9063 expandarg(argp, &arglist, EXP_VARTILDE);
9065 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9067 for (sp = *spp; sp; sp = sp->next)
9071 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9072 for (sp = arglist.list; sp; sp = sp->next) {
9073 TRACE(("evalcommand arg: %s\n", sp->text));
9074 *nargv++ = sp->text;
9079 if (iflag && funcnest == 0 && argc > 0)
9080 lastarg = nargv[-1];
9083 expredir(cmd->ncmd.redirect);
9084 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9086 path = vpath.var_text;
9087 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9088 struct strlist **spp;
9091 spp = varlist.lastp;
9092 expandarg(argp, &varlist, EXP_VARTILDE);
9095 * Modify the command lookup path, if a PATH= assignment
9099 if (varcmp(p, path) == 0)
9103 /* Print the command if xflag is set. */
9106 const char *p = " %s";
9109 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9112 for (n = 0; n < 2; n++) {
9114 fdprintf(preverrout_fd, p, sp->text);
9122 safe_write(preverrout_fd, "\n", 1);
9128 /* Now locate the command. */
9130 const char *oldpath;
9131 int cmd_flag = DO_ERR;
9136 find_command(argv[0], &cmdentry, cmd_flag, path);
9137 if (cmdentry.cmdtype == CMDUNKNOWN) {
9138 flush_stdout_stderr();
9143 /* implement bltin and command here */
9144 if (cmdentry.cmdtype != CMDBUILTIN)
9147 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9148 if (cmdentry.u.cmd == EXECCMD)
9150 #if ENABLE_ASH_CMDCMD
9151 if (cmdentry.u.cmd == COMMANDCMD) {
9153 nargv = parse_command_args(argv, &path);
9156 argc -= nargv - argv;
9158 cmd_flag |= DO_NOFUNC;
9166 /* We have a redirection error. */
9168 raise_exception(EXERROR);
9170 exitstatus = status;
9174 /* Execute the command. */
9175 switch (cmdentry.cmdtype) {
9178 #if ENABLE_FEATURE_SH_NOFORK
9179 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9180 * around run_nofork_applet() call.
9181 * (2) Should this check also be done in forkshell()?
9182 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9184 /* find_command() encodes applet_no as (-2 - applet_no) */
9185 int applet_no = (- cmdentry.u.index - 2);
9186 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9187 listsetvar(varlist.list, VEXPORT|VSTACK);
9188 /* run <applet>_main() */
9189 exitstatus = run_nofork_applet(applet_no, argv);
9193 /* Can we avoid forking off? For example, very last command
9194 * in a script or a subshell does not need forking,
9195 * we can just exec it.
9197 if (!(flags & EV_EXIT) || may_have_traps) {
9198 /* No, forking off a child is necessary */
9200 jp = makejob(/*cmd,*/ 1);
9201 if (forkshell(jp, cmd, FORK_FG) != 0) {
9203 exitstatus = waitforjob(jp);
9205 TRACE(("forked child exited with %d\n", exitstatus));
9210 /* fall through to exec'ing external program */
9212 listsetvar(varlist.list, VEXPORT|VSTACK);
9213 shellexec(argv, path, cmdentry.u.index);
9217 cmdenviron = varlist.list;
9219 struct strlist *list = cmdenviron;
9221 if (spclbltin > 0 || argc == 0) {
9223 if (cmd_is_exec && argc > 1)
9226 listsetvar(list, i);
9228 /* Tight loop with builtins only:
9229 * "while kill -0 $child; do true; done"
9230 * will never exit even if $child died, unless we do this
9231 * to reap the zombie and make kill detect that it's gone: */
9232 dowait(DOWAIT_NONBLOCK, NULL);
9234 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9236 int i = exception_type;
9241 exit_status = 128 + SIGINT;
9243 exit_status = 128 + pending_sig;
9244 exitstatus = exit_status;
9245 if (i == EXINT || spclbltin > 0) {
9247 longjmp(exception_handler->loc, 1);
9254 listsetvar(varlist.list, 0);
9255 /* See above for the rationale */
9256 dowait(DOWAIT_NONBLOCK, NULL);
9257 if (evalfun(cmdentry.u.func, argc, argv, flags))
9264 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9266 /* dsl: I think this is intended to be used to support
9267 * '_' in 'vi' command mode during line editing...
9268 * However I implemented that within libedit itself.
9270 setvar("_", lastarg, 0);
9272 popstackmark(&smark);
9276 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9278 char *volatile savecmdname;
9279 struct jmploc *volatile savehandler;
9280 struct jmploc jmploc;
9283 savecmdname = commandname;
9284 i = setjmp(jmploc.loc);
9287 savehandler = exception_handler;
9288 exception_handler = &jmploc;
9289 commandname = argv[0];
9291 optptr = NULL; /* initialize nextopt */
9292 exitstatus = (*cmd->builtin)(argc, argv);
9293 flush_stdout_stderr();
9295 exitstatus |= ferror(stdout);
9297 commandname = savecmdname;
9298 exception_handler = savehandler;
9304 goodname(const char *p)
9306 return !*endofname(p);
9311 * Search for a command. This is called before we fork so that the
9312 * location of the command will be available in the parent as well as
9313 * the child. The check for "goodname" is an overly conservative
9314 * check that the name will not be subject to expansion.
9317 prehash(union node *n)
9319 struct cmdentry entry;
9321 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9322 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9326 /* ============ Builtin commands
9328 * Builtin commands whose functions are closely tied to evaluation
9329 * are implemented here.
9333 * Handle break and continue commands. Break, continue, and return are
9334 * all handled by setting the evalskip flag. The evaluation routines
9335 * above all check this flag, and if it is set they start skipping
9336 * commands rather than executing them. The variable skipcount is
9337 * the number of loops to break/continue, or the number of function
9338 * levels to return. (The latter is always 1.) It should probably
9339 * be an error to break out of more loops than exist, but it isn't
9340 * in the standard shell so we don't make it one here.
9342 static int FAST_FUNC
9343 breakcmd(int argc UNUSED_PARAM, char **argv)
9345 int n = argv[1] ? number(argv[1]) : 1;
9348 ash_msg_and_raise_error(msg_illnum, argv[1]);
9352 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9359 /* ============ input.c
9361 * This implements the input routines used by the parser.
9365 INPUT_PUSH_FILE = 1,
9366 INPUT_NOFILE_OK = 2,
9369 static smallint checkkwd;
9370 /* values of checkkwd variable */
9371 #define CHKALIAS 0x1
9376 * Push a string back onto the input at this current parsefile level.
9377 * We handle aliases this way.
9379 #if !ENABLE_ASH_ALIAS
9380 #define pushstring(s, ap) pushstring(s)
9383 pushstring(char *s, struct alias *ap)
9390 if (g_parsefile->strpush) {
9391 sp = ckzalloc(sizeof(*sp));
9392 sp->prev = g_parsefile->strpush;
9394 sp = &(g_parsefile->basestrpush);
9396 g_parsefile->strpush = sp;
9397 sp->prev_string = g_parsefile->next_to_pgetc;
9398 sp->prev_left_in_line = g_parsefile->left_in_line;
9399 #if ENABLE_ASH_ALIAS
9402 ap->flag |= ALIASINUSE;
9406 g_parsefile->next_to_pgetc = s;
9407 g_parsefile->left_in_line = len;
9414 struct strpush *sp = g_parsefile->strpush;
9417 #if ENABLE_ASH_ALIAS
9419 if (g_parsefile->next_to_pgetc[-1] == ' '
9420 || g_parsefile->next_to_pgetc[-1] == '\t'
9422 checkkwd |= CHKALIAS;
9424 if (sp->string != sp->ap->val) {
9427 sp->ap->flag &= ~ALIASINUSE;
9428 if (sp->ap->flag & ALIASDEAD) {
9429 unalias(sp->ap->name);
9433 g_parsefile->next_to_pgetc = sp->prev_string;
9434 g_parsefile->left_in_line = sp->prev_left_in_line;
9435 g_parsefile->strpush = sp->prev;
9436 if (sp != &(g_parsefile->basestrpush))
9441 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9442 //it peeks whether it is &>, and then pushes back both chars.
9443 //This function needs to save last *next_to_pgetc to buf[0]
9444 //to make two pungetc() reliable. Currently,
9445 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9450 char *buf = g_parsefile->buf;
9452 g_parsefile->next_to_pgetc = buf;
9453 #if ENABLE_FEATURE_EDITING
9455 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9456 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9458 #if ENABLE_FEATURE_TAB_COMPLETION
9459 line_input_state->path_lookup = pathval();
9461 nr = read_line_input(cmdedit_prompt, buf, IBUFSIZ, line_input_state);
9463 /* Ctrl+C pressed */
9472 if (nr < 0 && errno == 0) {
9473 /* Ctrl+D pressed */
9478 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9482 /* nonblock_safe_read() handles this problem */
9484 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9485 int flags = fcntl(0, F_GETFL);
9486 if (flags >= 0 && (flags & O_NONBLOCK)) {
9487 flags &= ~O_NONBLOCK;
9488 if (fcntl(0, F_SETFL, flags) >= 0) {
9489 out2str("sh: turning off NDELAY mode\n");
9500 * Refill the input buffer and return the next input character:
9502 * 1) If a string was pushed back on the input, pop it;
9503 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9504 * or we are reading from a string so we can't refill the buffer,
9506 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9507 * 4) Process input up to the next newline, deleting nul characters.
9509 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9510 #define pgetc_debug(...) ((void)0)
9517 while (g_parsefile->strpush) {
9518 #if ENABLE_ASH_ALIAS
9519 if (g_parsefile->left_in_line == -1
9520 && g_parsefile->strpush->ap
9521 && g_parsefile->next_to_pgetc[-1] != ' '
9522 && g_parsefile->next_to_pgetc[-1] != '\t'
9524 pgetc_debug("preadbuffer PEOA");
9529 /* try "pgetc" now: */
9530 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9531 g_parsefile->left_in_line,
9532 g_parsefile->next_to_pgetc,
9533 g_parsefile->next_to_pgetc);
9534 if (--g_parsefile->left_in_line >= 0)
9535 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9537 /* on both branches above g_parsefile->left_in_line < 0.
9538 * "pgetc" needs refilling.
9541 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9542 * pungetc() may increment it a few times.
9543 * Assuming it won't increment it to less than -90.
9545 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9546 pgetc_debug("preadbuffer PEOF1");
9547 /* even in failure keep left_in_line and next_to_pgetc
9548 * in lock step, for correct multi-layer pungetc.
9549 * left_in_line was decremented before preadbuffer(),
9550 * must inc next_to_pgetc: */
9551 g_parsefile->next_to_pgetc++;
9555 more = g_parsefile->left_in_buffer;
9557 flush_stdout_stderr();
9561 /* don't try reading again */
9562 g_parsefile->left_in_line = -99;
9563 pgetc_debug("preadbuffer PEOF2");
9564 g_parsefile->next_to_pgetc++;
9569 /* Find out where's the end of line.
9570 * Set g_parsefile->left_in_line
9571 * and g_parsefile->left_in_buffer acordingly.
9572 * NUL chars are deleted.
9574 q = g_parsefile->next_to_pgetc;
9582 memmove(q, q + 1, more);
9586 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9592 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9593 if (g_parsefile->left_in_line < 0)
9598 g_parsefile->left_in_buffer = more;
9603 out2str(g_parsefile->next_to_pgetc);
9607 pgetc_debug("preadbuffer at %d:%p'%s'",
9608 g_parsefile->left_in_line,
9609 g_parsefile->next_to_pgetc,
9610 g_parsefile->next_to_pgetc);
9611 return (unsigned char)*g_parsefile->next_to_pgetc++;
9614 #define pgetc_as_macro() \
9615 (--g_parsefile->left_in_line >= 0 \
9616 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9623 pgetc_debug("pgetc_fast at %d:%p'%s'",
9624 g_parsefile->left_in_line,
9625 g_parsefile->next_to_pgetc,
9626 g_parsefile->next_to_pgetc);
9627 return pgetc_as_macro();
9630 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9631 # define pgetc_fast() pgetc()
9633 # define pgetc_fast() pgetc_as_macro()
9636 #if ENABLE_ASH_ALIAS
9638 pgetc_without_PEOA(void)
9642 pgetc_debug("pgetc_fast at %d:%p'%s'",
9643 g_parsefile->left_in_line,
9644 g_parsefile->next_to_pgetc,
9645 g_parsefile->next_to_pgetc);
9647 } while (c == PEOA);
9651 # define pgetc_without_PEOA() pgetc()
9655 * Read a line from the script.
9658 pfgets(char *line, int len)
9664 while (--nleft > 0) {
9665 c = pgetc_without_PEOA();
9680 * Undo the last call to pgetc. Only one character may be pushed back.
9681 * PEOF may be pushed back.
9686 g_parsefile->left_in_line++;
9687 g_parsefile->next_to_pgetc--;
9688 pgetc_debug("pushed back to %d:%p'%s'",
9689 g_parsefile->left_in_line,
9690 g_parsefile->next_to_pgetc,
9691 g_parsefile->next_to_pgetc);
9695 * To handle the "." command, a stack of input files is used. Pushfile
9696 * adds a new entry to the stack and popfile restores the previous level.
9701 struct parsefile *pf;
9703 pf = ckzalloc(sizeof(*pf));
9704 pf->prev = g_parsefile;
9706 /*pf->strpush = NULL; - ckzalloc did it */
9707 /*pf->basestrpush.prev = NULL;*/
9714 struct parsefile *pf = g_parsefile;
9722 g_parsefile = pf->prev;
9728 * Return to top level.
9733 while (g_parsefile != &basepf)
9738 * Close the file(s) that the shell is reading commands from. Called
9739 * after a fork is done.
9745 if (g_parsefile->pf_fd > 0) {
9746 close(g_parsefile->pf_fd);
9747 g_parsefile->pf_fd = 0;
9752 * Like setinputfile, but takes an open file descriptor. Call this with
9756 setinputfd(int fd, int push)
9758 close_on_exec_on(fd);
9761 g_parsefile->buf = NULL;
9763 g_parsefile->pf_fd = fd;
9764 if (g_parsefile->buf == NULL)
9765 g_parsefile->buf = ckmalloc(IBUFSIZ);
9766 g_parsefile->left_in_buffer = 0;
9767 g_parsefile->left_in_line = 0;
9768 g_parsefile->linno = 1;
9772 * Set the input to take input from a file. If push is set, push the
9773 * old input onto the stack first.
9776 setinputfile(const char *fname, int flags)
9782 fd = open(fname, O_RDONLY);
9784 if (flags & INPUT_NOFILE_OK)
9786 ash_msg_and_raise_error("can't open '%s'", fname);
9789 fd2 = copyfd(fd, 10);
9792 ash_msg_and_raise_error("out of file descriptors");
9795 setinputfd(fd, flags & INPUT_PUSH_FILE);
9802 * Like setinputfile, but takes input from a string.
9805 setinputstring(char *string)
9809 g_parsefile->next_to_pgetc = string;
9810 g_parsefile->left_in_line = strlen(string);
9811 g_parsefile->buf = NULL;
9812 g_parsefile->linno = 1;
9817 /* ============ mail.c
9819 * Routines to check for mail.
9824 #define MAXMBOXES 10
9826 /* times of mailboxes */
9827 static time_t mailtime[MAXMBOXES];
9828 /* Set if MAIL or MAILPATH is changed. */
9829 static smallint mail_var_path_changed;
9832 * Print appropriate message(s) if mail has arrived.
9833 * If mail_var_path_changed is set,
9834 * then the value of MAIL has mail_var_path_changed,
9835 * so we just update the values.
9844 struct stackmark smark;
9847 setstackmark(&smark);
9848 mpath = mpathset() ? mpathval() : mailval();
9849 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9850 p = path_advance(&mpath, nullstr);
9855 for (q = p; *q; q++)
9861 q[-1] = '\0'; /* delete trailing '/' */
9862 if (stat(p, &statb) < 0) {
9866 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9869 pathopt ? pathopt : "you have mail"
9872 *mtp = statb.st_mtime;
9874 mail_var_path_changed = 0;
9875 popstackmark(&smark);
9878 static void FAST_FUNC
9879 changemail(const char *val UNUSED_PARAM)
9881 mail_var_path_changed = 1;
9884 #endif /* ASH_MAIL */
9887 /* ============ ??? */
9890 * Set the shell parameters.
9893 setparam(char **argv)
9899 for (nparam = 0; argv[nparam]; nparam++)
9901 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9903 *ap++ = ckstrdup(*argv++);
9906 freeparam(&shellparam);
9907 shellparam.malloced = 1;
9908 shellparam.nparam = nparam;
9909 shellparam.p = newparam;
9910 #if ENABLE_ASH_GETOPTS
9911 shellparam.optind = 1;
9912 shellparam.optoff = -1;
9917 * Process shell options. The global variable argptr contains a pointer
9918 * to the argument list; we advance it past the options.
9920 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9921 * For a non-interactive shell, an error condition encountered
9922 * by a special built-in ... shall cause the shell to write a diagnostic message
9923 * to standard error and exit as shown in the following table:
9924 * Error Special Built-In
9926 * Utility syntax error (option or operand error) Shall exit
9928 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9929 * we see that bash does not do that (set "finishes" with error code 1 instead,
9930 * and shell continues), and people rely on this behavior!
9932 * set -o barfoo 2>/dev/null
9935 * Oh well. Let's mimic that.
9938 plus_minus_o(char *name, int val)
9943 for (i = 0; i < NOPTS; i++) {
9944 if (strcmp(name, optnames(i)) == 0) {
9949 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9952 for (i = 0; i < NOPTS; i++) {
9954 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9956 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9962 setoption(int flag, int val)
9966 for (i = 0; i < NOPTS; i++) {
9967 if (optletters(i) == flag) {
9972 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9976 options(int cmdline)
9984 while ((p = *argptr) != NULL) {
9986 if (c != '-' && c != '+')
9989 val = 0; /* val = 0 if c == '+' */
9992 if (p[0] == '\0' || LONE_DASH(p)) {
9994 /* "-" means turn off -x and -v */
9997 /* "--" means reset params */
9998 else if (*argptr == NULL)
10001 break; /* "-" or "--" terminates options */
10004 /* first char was + or - */
10005 while ((c = *p++) != '\0') {
10006 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10007 if (c == 'c' && cmdline) {
10008 minusc = p; /* command is after shell args */
10009 } else if (c == 'o') {
10010 if (plus_minus_o(*argptr, val)) {
10011 /* it already printed err message */
10012 return 1; /* error */
10016 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10018 /* bash does not accept +-login, we also won't */
10019 } else if (cmdline && val && (c == '-')) { /* long options */
10020 if (strcmp(p, "login") == 0)
10032 * The shift builtin command.
10034 static int FAST_FUNC
10035 shiftcmd(int argc UNUSED_PARAM, char **argv)
10042 n = number(argv[1]);
10043 if (n > shellparam.nparam)
10044 n = 0; /* bash compat, was = shellparam.nparam; */
10046 shellparam.nparam -= n;
10047 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10048 if (shellparam.malloced)
10051 ap2 = shellparam.p;
10052 while ((*ap2++ = *ap1++) != NULL)
10054 #if ENABLE_ASH_GETOPTS
10055 shellparam.optind = 1;
10056 shellparam.optoff = -1;
10063 * POSIX requires that 'set' (but not export or readonly) output the
10064 * variables in lexicographic order - by the locale's collating order (sigh).
10065 * Maybe we could keep them in an ordered balanced binary tree
10066 * instead of hashed lists.
10067 * For now just roll 'em through qsort for printing...
10070 showvars(const char *sep_prefix, int on, int off)
10073 char **ep, **epend;
10075 ep = listvars(on, off, &epend);
10076 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10078 sep = *sep_prefix ? " " : sep_prefix;
10080 for (; ep < epend; ep++) {
10084 p = strchrnul(*ep, '=');
10087 q = single_quote(++p);
10088 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10094 * The set command builtin.
10096 static int FAST_FUNC
10097 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10102 return showvars(nullstr, 0, VUNSET);
10105 if (!options(0)) { /* if no parse error... */
10108 if (*argptr != NULL) {
10116 #if ENABLE_ASH_RANDOM_SUPPORT
10117 static void FAST_FUNC
10118 change_random(const char *value)
10122 if (value == NULL) {
10123 /* "get", generate */
10124 t = next_random(&random_gen);
10125 /* set without recursion */
10126 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10127 vrandom.flags &= ~VNOFUNC;
10130 t = strtoul(value, NULL, 10);
10131 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10136 #if ENABLE_ASH_GETOPTS
10138 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10147 if (*param_optind < 1)
10149 optnext = optfirst + *param_optind - 1;
10151 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10154 p = optnext[-1] + *optoff;
10155 if (p == NULL || *p == '\0') {
10156 /* Current word is done, advance */
10158 if (p == NULL || *p != '-' || *++p == '\0') {
10165 if (LONE_DASH(p)) /* check for "--" */
10170 for (q = optstr; *q != c;) {
10172 if (optstr[0] == ':') {
10175 err |= setvarsafe("OPTARG", s, 0);
10177 fprintf(stderr, "Illegal option -%c\n", c);
10178 unsetvar("OPTARG");
10188 if (*p == '\0' && (p = *optnext) == NULL) {
10189 if (optstr[0] == ':') {
10192 err |= setvarsafe("OPTARG", s, 0);
10195 fprintf(stderr, "No arg for -%c option\n", c);
10196 unsetvar("OPTARG");
10204 err |= setvarsafe("OPTARG", p, 0);
10207 err |= setvarsafe("OPTARG", nullstr, 0);
10209 *optoff = p ? p - *(optnext - 1) : -1;
10210 *param_optind = optnext - optfirst + 1;
10211 fmtstr(s, sizeof(s), "%d", *param_optind);
10212 err |= setvarsafe("OPTIND", s, VNOFUNC);
10215 err |= setvarsafe(optvar, s, 0);
10219 flush_stdout_stderr();
10220 raise_exception(EXERROR);
10226 * The getopts builtin. Shellparam.optnext points to the next argument
10227 * to be processed. Shellparam.optptr points to the next character to
10228 * be processed in the current argument. If shellparam.optnext is NULL,
10229 * then it's the first time getopts has been called.
10231 static int FAST_FUNC
10232 getoptscmd(int argc, char **argv)
10237 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10239 optbase = shellparam.p;
10240 if (shellparam.optind > shellparam.nparam + 1) {
10241 shellparam.optind = 1;
10242 shellparam.optoff = -1;
10245 optbase = &argv[3];
10246 if (shellparam.optind > argc - 2) {
10247 shellparam.optind = 1;
10248 shellparam.optoff = -1;
10252 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10253 &shellparam.optoff);
10255 #endif /* ASH_GETOPTS */
10258 /* ============ Shell parser */
10261 struct heredoc *next; /* next here document in list */
10262 union node *here; /* redirection node */
10263 char *eofmark; /* string indicating end of input */
10264 smallint striptabs; /* if set, strip leading tabs */
10267 static smallint tokpushback; /* last token pushed back */
10268 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10269 static smallint quoteflag; /* set if (part of) last token was quoted */
10270 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10271 static struct heredoc *heredoclist; /* list of here documents to read */
10272 static char *wordtext; /* text of last word returned by readtoken */
10273 static struct nodelist *backquotelist;
10274 static union node *redirnode;
10275 static struct heredoc *heredoc;
10277 static const char *
10278 tokname(char *buf, int tok)
10281 return tokname_array[tok] + 1;
10282 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10286 /* raise_error_unexpected_syntax:
10287 * Called when an unexpected token is read during the parse. The argument
10288 * is the token that is expected, or -1 if more than one type of token can
10289 * occur at this point.
10291 static void raise_error_unexpected_syntax(int) NORETURN;
10293 raise_error_unexpected_syntax(int token)
10299 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10301 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10302 raise_error_syntax(msg);
10306 #define EOFMARKLEN 79
10308 /* parsing is heavily cross-recursive, need these forward decls */
10309 static union node *andor(void);
10310 static union node *pipeline(void);
10311 static union node *parse_command(void);
10312 static void parseheredoc(void);
10313 static char peektoken(void);
10314 static int readtoken(void);
10316 static union node *
10319 union node *n1, *n2, *n3;
10322 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10323 if (nlflag == 2 && peektoken())
10329 if (tok == TBACKGND) {
10330 if (n2->type == NPIPE) {
10331 n2->npipe.pipe_backgnd = 1;
10333 if (n2->type != NREDIR) {
10334 n3 = stzalloc(sizeof(struct nredir));
10336 /*n3->nredir.redirect = NULL; - stzalloc did it */
10339 n2->type = NBACKGND;
10345 n3 = stzalloc(sizeof(struct nbinary));
10347 n3->nbinary.ch1 = n1;
10348 n3->nbinary.ch2 = n2;
10364 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10372 pungetc(); /* push back EOF on input */
10376 raise_error_unexpected_syntax(-1);
10383 static union node *
10386 union node *n1, *n2, *n3;
10394 } else if (t == TOR) {
10400 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10402 n3 = stzalloc(sizeof(struct nbinary));
10404 n3->nbinary.ch1 = n1;
10405 n3->nbinary.ch2 = n2;
10410 static union node *
10413 union node *n1, *n2, *pipenode;
10414 struct nodelist *lp, *prev;
10418 TRACE(("pipeline: entered\n"));
10419 if (readtoken() == TNOT) {
10421 checkkwd = CHKKWD | CHKALIAS;
10424 n1 = parse_command();
10425 if (readtoken() == TPIPE) {
10426 pipenode = stzalloc(sizeof(struct npipe));
10427 pipenode->type = NPIPE;
10428 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10429 lp = stzalloc(sizeof(struct nodelist));
10430 pipenode->npipe.cmdlist = lp;
10434 lp = stzalloc(sizeof(struct nodelist));
10435 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10436 lp->n = parse_command();
10438 } while (readtoken() == TPIPE);
10444 n2 = stzalloc(sizeof(struct nnot));
10452 static union node *
10457 n = stzalloc(sizeof(struct narg));
10459 /*n->narg.next = NULL; - stzalloc did it */
10460 n->narg.text = wordtext;
10461 n->narg.backquote = backquotelist;
10466 fixredir(union node *n, const char *text, int err)
10470 TRACE(("Fix redir %s %d\n", text, err));
10472 n->ndup.vname = NULL;
10474 fd = bb_strtou(text, NULL, 10);
10475 if (!errno && fd >= 0)
10476 n->ndup.dupfd = fd;
10477 else if (LONE_DASH(text))
10478 n->ndup.dupfd = -1;
10481 raise_error_syntax("bad fd number");
10482 n->ndup.vname = makename();
10487 * Returns true if the text contains nothing to expand (no dollar signs
10491 noexpand(const char *text)
10495 while ((c = *text++) != '\0') {
10496 if (c == CTLQUOTEMARK)
10500 else if (SIT(c, BASESYNTAX) == CCTL)
10509 union node *n = redirnode;
10511 if (readtoken() != TWORD)
10512 raise_error_unexpected_syntax(-1);
10513 if (n->type == NHERE) {
10514 struct heredoc *here = heredoc;
10518 if (quoteflag == 0)
10520 TRACE(("Here document %d\n", n->type));
10521 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10522 raise_error_syntax("illegal eof marker for << redirection");
10523 rmescapes(wordtext, 0);
10524 here->eofmark = wordtext;
10526 if (heredoclist == NULL)
10527 heredoclist = here;
10529 for (p = heredoclist; p->next; p = p->next)
10533 } else if (n->type == NTOFD || n->type == NFROMFD) {
10534 fixredir(n, wordtext, 0);
10536 n->nfile.fname = makename();
10540 static union node *
10543 union node *args, **app;
10544 union node *n = NULL;
10545 union node *vars, **vpp;
10546 union node **rpp, *redir;
10548 #if ENABLE_ASH_BASH_COMPAT
10549 smallint double_brackets_flag = 0;
10559 savecheckkwd = CHKALIAS;
10562 checkkwd = savecheckkwd;
10565 #if ENABLE_ASH_BASH_COMPAT
10566 case TAND: /* "&&" */
10567 case TOR: /* "||" */
10568 if (!double_brackets_flag) {
10572 wordtext = (char *) (t == TAND ? "-a" : "-o");
10575 n = stzalloc(sizeof(struct narg));
10577 /*n->narg.next = NULL; - stzalloc did it */
10578 n->narg.text = wordtext;
10579 #if ENABLE_ASH_BASH_COMPAT
10580 if (strcmp("[[", wordtext) == 0)
10581 double_brackets_flag = 1;
10582 else if (strcmp("]]", wordtext) == 0)
10583 double_brackets_flag = 0;
10585 n->narg.backquote = backquotelist;
10586 if (savecheckkwd && isassignment(wordtext)) {
10588 vpp = &n->narg.next;
10591 app = &n->narg.next;
10596 *rpp = n = redirnode;
10597 rpp = &n->nfile.next;
10598 parsefname(); /* read name of redirection file */
10601 if (args && app == &args->narg.next
10604 struct builtincmd *bcmd;
10607 /* We have a function */
10608 if (readtoken() != TRP)
10609 raise_error_unexpected_syntax(TRP);
10610 name = n->narg.text;
10611 if (!goodname(name)
10612 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10614 raise_error_syntax("bad function name");
10617 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10618 n->narg.next = parse_command();
10631 n = stzalloc(sizeof(struct ncmd));
10633 n->ncmd.args = args;
10634 n->ncmd.assign = vars;
10635 n->ncmd.redirect = redir;
10639 static union node *
10640 parse_command(void)
10642 union node *n1, *n2;
10643 union node *ap, **app;
10644 union node *cp, **cpp;
10645 union node *redir, **rpp;
10652 switch (readtoken()) {
10654 raise_error_unexpected_syntax(-1);
10657 n1 = stzalloc(sizeof(struct nif));
10659 n1->nif.test = list(0);
10660 if (readtoken() != TTHEN)
10661 raise_error_unexpected_syntax(TTHEN);
10662 n1->nif.ifpart = list(0);
10664 while (readtoken() == TELIF) {
10665 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10666 n2 = n2->nif.elsepart;
10668 n2->nif.test = list(0);
10669 if (readtoken() != TTHEN)
10670 raise_error_unexpected_syntax(TTHEN);
10671 n2->nif.ifpart = list(0);
10673 if (lasttoken == TELSE)
10674 n2->nif.elsepart = list(0);
10676 n2->nif.elsepart = NULL;
10684 n1 = stzalloc(sizeof(struct nbinary));
10685 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10686 n1->nbinary.ch1 = list(0);
10689 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
10690 got == TWORD ? wordtext : ""));
10691 raise_error_unexpected_syntax(TDO);
10693 n1->nbinary.ch2 = list(0);
10698 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10699 raise_error_syntax("bad for loop variable");
10700 n1 = stzalloc(sizeof(struct nfor));
10702 n1->nfor.var = wordtext;
10703 checkkwd = CHKKWD | CHKALIAS;
10704 if (readtoken() == TIN) {
10706 while (readtoken() == TWORD) {
10707 n2 = stzalloc(sizeof(struct narg));
10709 /*n2->narg.next = NULL; - stzalloc did it */
10710 n2->narg.text = wordtext;
10711 n2->narg.backquote = backquotelist;
10713 app = &n2->narg.next;
10716 n1->nfor.args = ap;
10717 if (lasttoken != TNL && lasttoken != TSEMI)
10718 raise_error_unexpected_syntax(-1);
10720 n2 = stzalloc(sizeof(struct narg));
10722 /*n2->narg.next = NULL; - stzalloc did it */
10723 n2->narg.text = (char *)dolatstr;
10724 /*n2->narg.backquote = NULL;*/
10725 n1->nfor.args = n2;
10727 * Newline or semicolon here is optional (but note
10728 * that the original Bourne shell only allowed NL).
10730 if (lasttoken != TNL && lasttoken != TSEMI)
10733 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10734 if (readtoken() != TDO)
10735 raise_error_unexpected_syntax(TDO);
10736 n1->nfor.body = list(0);
10740 n1 = stzalloc(sizeof(struct ncase));
10742 if (readtoken() != TWORD)
10743 raise_error_unexpected_syntax(TWORD);
10744 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10746 /*n2->narg.next = NULL; - stzalloc did it */
10747 n2->narg.text = wordtext;
10748 n2->narg.backquote = backquotelist;
10750 checkkwd = CHKKWD | CHKALIAS;
10751 } while (readtoken() == TNL);
10752 if (lasttoken != TIN)
10753 raise_error_unexpected_syntax(TIN);
10754 cpp = &n1->ncase.cases;
10756 checkkwd = CHKNL | CHKKWD;
10758 while (t != TESAC) {
10759 if (lasttoken == TLP)
10761 *cpp = cp = stzalloc(sizeof(struct nclist));
10763 app = &cp->nclist.pattern;
10765 *app = ap = stzalloc(sizeof(struct narg));
10767 /*ap->narg.next = NULL; - stzalloc did it */
10768 ap->narg.text = wordtext;
10769 ap->narg.backquote = backquotelist;
10770 if (readtoken() != TPIPE)
10772 app = &ap->narg.next;
10775 //ap->narg.next = NULL;
10776 if (lasttoken != TRP)
10777 raise_error_unexpected_syntax(TRP);
10778 cp->nclist.body = list(2);
10780 cpp = &cp->nclist.next;
10782 checkkwd = CHKNL | CHKKWD;
10786 raise_error_unexpected_syntax(TENDCASE);
10793 n1 = stzalloc(sizeof(struct nredir));
10794 n1->type = NSUBSHELL;
10795 n1->nredir.n = list(0);
10796 /*n1->nredir.redirect = NULL; - stzalloc did it */
10806 return simplecmd();
10809 if (readtoken() != t)
10810 raise_error_unexpected_syntax(t);
10813 /* Now check for redirection which may follow command */
10814 checkkwd = CHKKWD | CHKALIAS;
10816 while (readtoken() == TREDIR) {
10817 *rpp = n2 = redirnode;
10818 rpp = &n2->nfile.next;
10824 if (n1->type != NSUBSHELL) {
10825 n2 = stzalloc(sizeof(struct nredir));
10830 n1->nredir.redirect = redir;
10835 #if ENABLE_ASH_BASH_COMPAT
10836 static int decode_dollar_squote(void)
10838 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10844 p = strchr(C_escapes, c);
10849 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10853 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10855 } else if (c == 'x') { /* \xHH */
10859 } while (isxdigit(c) && --cnt);
10861 if (cnt == 3) { /* \x but next char is "bad" */
10865 } else { /* simple seq like \\ or \t */
10870 c = bb_process_escape_sequence((void*)&p);
10871 } else { /* unrecognized "\z": print both chars unless ' or " */
10872 if (c != '\'' && c != '"') {
10874 c |= 0x100; /* "please encode \, then me" */
10882 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10883 * is not NULL, read a here document. In the latter case, eofmark is the
10884 * word which marks the end of the document and striptabs is true if
10885 * leading tabs should be stripped from the document. The argument c
10886 * is the first character of the input token or document.
10888 * Because C does not have internal subroutines, I have simulated them
10889 * using goto's to implement the subroutine linkage. The following macros
10890 * will run code that appears at the end of readtoken1.
10892 #define CHECKEND() {goto checkend; checkend_return:;}
10893 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10894 #define PARSESUB() {goto parsesub; parsesub_return:;}
10895 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10896 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10897 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10899 readtoken1(int c, int syntax, char *eofmark, int striptabs)
10901 /* NB: syntax parameter fits into smallint */
10902 /* c parameter is an unsigned char or PEOF or PEOA */
10905 char line[EOFMARKLEN + 1];
10906 struct nodelist *bqlist;
10910 smallint prevsyntax; /* syntax before arithmetic */
10911 #if ENABLE_ASH_EXPAND_PRMT
10912 smallint pssyntax; /* we are expanding a prompt string */
10914 int varnest; /* levels of variables expansion */
10915 int arinest; /* levels of arithmetic expansion */
10916 int parenlevel; /* levels of parens in arithmetic */
10917 int dqvarnest; /* levels of variables expansion within double quotes */
10919 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10922 /* Avoid longjmp clobbering */
10928 (void) &parenlevel;
10931 (void) &prevsyntax;
10934 startlinno = g_parsefile->linno;
10939 #if ENABLE_ASH_EXPAND_PRMT
10940 pssyntax = (syntax == PSSYNTAX);
10944 dblquote = (syntax == DQSYNTAX);
10950 STARTSTACKSTR(out);
10952 /* For each line, until end of word */
10954 CHECKEND(); /* set c to PEOF if at end of here document */
10955 for (;;) { /* until end of line or end of word */
10956 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10957 switch (SIT(c, syntax)) {
10958 case CNL: /* '\n' */
10959 if (syntax == BASESYNTAX)
10960 goto endword; /* exit outer loop */
10962 g_parsefile->linno++;
10966 goto loop; /* continue outer loop */
10971 if (eofmark == NULL || dblquote)
10972 USTPUTC(CTLESC, out);
10973 #if ENABLE_ASH_BASH_COMPAT
10974 if (c == '\\' && bash_dollar_squote) {
10975 c = decode_dollar_squote();
10977 USTPUTC('\\', out);
10978 c = (unsigned char)c;
10984 case CBACK: /* backslash */
10985 c = pgetc_without_PEOA();
10987 USTPUTC(CTLESC, out);
10988 USTPUTC('\\', out);
10990 } else if (c == '\n') {
10994 #if ENABLE_ASH_EXPAND_PRMT
10995 if (c == '$' && pssyntax) {
10996 USTPUTC(CTLESC, out);
10997 USTPUTC('\\', out);
11000 if (dblquote && c != '\\'
11001 && c != '`' && c != '$'
11002 && (c != '"' || eofmark != NULL)
11004 USTPUTC(CTLESC, out);
11005 USTPUTC('\\', out);
11007 if (SIT(c, SQSYNTAX) == CCTL)
11008 USTPUTC(CTLESC, out);
11016 if (eofmark == NULL) {
11017 USTPUTC(CTLQUOTEMARK, out);
11025 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11026 if (eofmark != NULL && arinest == 0
11031 if (dqvarnest == 0) {
11032 syntax = BASESYNTAX;
11039 case CVAR: /* '$' */
11040 PARSESUB(); /* parse substitution */
11042 case CENDVAR: /* '}' */
11045 if (dqvarnest > 0) {
11048 USTPUTC(CTLENDVAR, out);
11053 #if ENABLE_SH_MATH_SUPPORT
11054 case CLP: /* '(' in arithmetic */
11058 case CRP: /* ')' in arithmetic */
11059 if (parenlevel > 0) {
11063 if (pgetc() == ')') {
11064 if (--arinest == 0) {
11065 USTPUTC(CTLENDARI, out);
11066 syntax = prevsyntax;
11067 dblquote = (syntax == DQSYNTAX);
11072 * unbalanced parens
11073 * (don't 2nd guess - no error)
11081 case CBQUOTE: /* '`' */
11085 goto endword; /* exit outer loop */
11089 if (varnest == 0) {
11090 #if ENABLE_ASH_BASH_COMPAT
11092 if (pgetc() == '>')
11093 c = 0x100 + '>'; /* flag &> */
11097 goto endword; /* exit outer loop */
11099 IF_ASH_ALIAS(if (c != PEOA))
11107 #if ENABLE_SH_MATH_SUPPORT
11108 if (syntax == ARISYNTAX)
11109 raise_error_syntax("missing '))'");
11111 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11112 raise_error_syntax("unterminated quoted string");
11113 if (varnest != 0) {
11114 startlinno = g_parsefile->linno;
11116 raise_error_syntax("missing '}'");
11118 USTPUTC('\0', out);
11119 len = out - (char *)stackblock();
11120 out = stackblock();
11121 if (eofmark == NULL) {
11122 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11125 if (isdigit_str9(out)) {
11126 PARSEREDIR(); /* passed as params: out, c */
11127 lasttoken = TREDIR;
11130 /* else: non-number X seen, interpret it
11131 * as "NNNX>file" = "NNNX >file" */
11135 quoteflag = quotef;
11136 backquotelist = bqlist;
11137 grabstackblock(len);
11141 /* end of readtoken routine */
11144 * Check to see whether we are at the end of the here document. When this
11145 * is called, c is set to the first character of the next input line. If
11146 * we are at the end of the here document, this routine sets the c to PEOF.
11150 #if ENABLE_ASH_ALIAS
11152 c = pgetc_without_PEOA();
11155 while (c == '\t') {
11156 c = pgetc_without_PEOA();
11159 if (c == *eofmark) {
11160 if (pfgets(line, sizeof(line)) != NULL) {
11164 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11166 if (*p == '\n' && *q == '\0') {
11168 g_parsefile->linno++;
11169 needprompt = doprompt;
11171 pushstring(line, NULL);
11176 goto checkend_return;
11180 * Parse a redirection operator. The variable "out" points to a string
11181 * specifying the fd to be redirected. The variable "c" contains the
11182 * first character of the redirection operator.
11185 /* out is already checked to be a valid number or "" */
11186 int fd = (*out == '\0' ? -1 : atoi(out));
11189 np = stzalloc(sizeof(struct nfile));
11194 np->type = NAPPEND;
11196 np->type = NCLOBBER;
11199 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11205 #if ENABLE_ASH_BASH_COMPAT
11206 else if (c == 0x100 + '>') { /* this flags &> redirection */
11208 pgetc(); /* this is '>', no need to check */
11212 else { /* c == '<' */
11213 /*np->nfile.fd = 0; - stzalloc did it */
11217 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11218 np = stzalloc(sizeof(struct nhere));
11219 /*np->nfile.fd = 0; - stzalloc did it */
11222 heredoc = stzalloc(sizeof(struct heredoc));
11223 heredoc->here = np;
11226 heredoc->striptabs = 1;
11228 /*heredoc->striptabs = 0; - stzalloc did it */
11234 np->type = NFROMFD;
11238 np->type = NFROMTO;
11250 goto parseredir_return;
11254 * Parse a substitution. At this point, we have read the dollar sign
11255 * and nothing else.
11258 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11259 * (assuming ascii char codes, as the original implementation did) */
11260 #define is_special(c) \
11261 (((unsigned)(c) - 33 < 32) \
11262 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11264 unsigned char subtype;
11268 static const char types[] ALIGN1 = "}-+?=";
11271 if (c > 255 /* PEOA or PEOF */
11272 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11274 #if ENABLE_ASH_BASH_COMPAT
11276 bash_dollar_squote = 1;
11281 } else if (c == '(') { /* $(command) or $((arith)) */
11282 if (pgetc() == '(') {
11283 #if ENABLE_SH_MATH_SUPPORT
11286 raise_error_syntax("you disabled math support for $((arith)) syntax");
11293 USTPUTC(CTLVAR, out);
11294 typeloc = out - (char *)stackblock();
11295 USTPUTC(VSNORMAL, out);
11296 subtype = VSNORMAL;
11304 subtype = VSLENGTH;
11308 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11312 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11313 } else if (isdigit(c)) {
11317 } while (isdigit(c));
11318 } else if (is_special(c)) {
11323 raise_error_syntax("bad substitution");
11325 if (c != '}' && subtype == VSLENGTH)
11330 if (subtype == 0) {
11334 #if ENABLE_ASH_BASH_COMPAT
11335 if (c == ':' || c == '$' || isdigit(c)) {
11337 subtype = VSSUBSTR;
11344 p = strchr(types, c);
11347 subtype = p - types + VSNORMAL;
11352 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11360 #if ENABLE_ASH_BASH_COMPAT
11362 subtype = VSREPLACE;
11365 subtype++; /* VSREPLACEALL */
11374 if (dblquote || arinest)
11376 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11377 if (subtype != VSNORMAL) {
11379 if (dblquote || arinest) {
11384 goto parsesub_return;
11388 * Called to parse command substitutions. Newstyle is set if the command
11389 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11390 * list of commands (passed by reference), and savelen is the number of
11391 * characters on the top of the stack which must be preserved.
11394 struct nodelist **nlpp;
11397 char *volatile str;
11398 struct jmploc jmploc;
11399 struct jmploc *volatile savehandler;
11401 smallint saveprompt = 0;
11404 (void) &saveprompt;
11406 savepbq = parsebackquote;
11407 if (setjmp(jmploc.loc)) {
11409 parsebackquote = 0;
11410 exception_handler = savehandler;
11411 longjmp(exception_handler->loc, 1);
11415 savelen = out - (char *)stackblock();
11417 str = ckmalloc(savelen);
11418 memcpy(str, stackblock(), savelen);
11420 savehandler = exception_handler;
11421 exception_handler = &jmploc;
11424 /* We must read until the closing backquote, giving special
11425 treatment to some slashes, and then push the string and
11426 reread it as input, interpreting it normally. */
11433 STARTSTACKSTR(pout);
11446 g_parsefile->linno++;
11450 * If eating a newline, avoid putting
11451 * the newline into the new character
11452 * stream (via the STPUTC after the
11457 if (pc != '\\' && pc != '`' && pc != '$'
11458 && (!dblquote || pc != '"')
11460 STPUTC('\\', pout);
11462 if (pc <= 255 /* not PEOA or PEOF */) {
11468 IF_ASH_ALIAS(case PEOA:)
11469 startlinno = g_parsefile->linno;
11470 raise_error_syntax("EOF in backquote substitution");
11473 g_parsefile->linno++;
11474 needprompt = doprompt;
11483 STPUTC('\0', pout);
11484 psavelen = pout - (char *)stackblock();
11485 if (psavelen > 0) {
11486 pstr = grabstackstr(pout);
11487 setinputstring(pstr);
11492 nlpp = &(*nlpp)->next;
11493 *nlpp = stzalloc(sizeof(**nlpp));
11494 /* (*nlpp)->next = NULL; - stzalloc did it */
11495 parsebackquote = oldstyle;
11498 saveprompt = doprompt;
11505 doprompt = saveprompt;
11506 else if (readtoken() != TRP)
11507 raise_error_unexpected_syntax(TRP);
11512 * Start reading from old file again, ignoring any pushed back
11513 * tokens left from the backquote parsing
11518 while (stackblocksize() <= savelen)
11520 STARTSTACKSTR(out);
11522 memcpy(out, str, savelen);
11523 STADJUST(savelen, out);
11529 parsebackquote = savepbq;
11530 exception_handler = savehandler;
11531 if (arinest || dblquote)
11532 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11534 USTPUTC(CTLBACKQ, out);
11536 goto parsebackq_oldreturn;
11537 goto parsebackq_newreturn;
11540 #if ENABLE_SH_MATH_SUPPORT
11542 * Parse an arithmetic expansion (indicate start of one and set state)
11545 if (++arinest == 1) {
11546 prevsyntax = syntax;
11547 syntax = ARISYNTAX;
11548 USTPUTC(CTLARI, out);
11555 * we collapse embedded arithmetic expansion to
11556 * parenthesis, which should be equivalent
11560 goto parsearith_return;
11564 } /* end of readtoken */
11567 * Read the next input token.
11568 * If the token is a word, we set backquotelist to the list of cmds in
11569 * backquotes. We set quoteflag to true if any part of the word was
11571 * If the token is TREDIR, then we set redirnode to a structure containing
11573 * In all cases, the variable startlinno is set to the number of the line
11574 * on which the token starts.
11576 * [Change comment: here documents and internal procedures]
11577 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11578 * word parsing code into a separate routine. In this case, readtoken
11579 * doesn't need to have any internal procedures, but parseword does.
11580 * We could also make parseoperator in essence the main routine, and
11581 * have parseword (readtoken1?) handle both words and redirection.]
11583 #define NEW_xxreadtoken
11584 #ifdef NEW_xxreadtoken
11585 /* singles must be first! */
11586 static const char xxreadtoken_chars[7] ALIGN1 = {
11587 '\n', '(', ')', /* singles */
11588 '&', '|', ';', /* doubles */
11592 #define xxreadtoken_singles 3
11593 #define xxreadtoken_doubles 3
11595 static const char xxreadtoken_tokens[] ALIGN1 = {
11596 TNL, TLP, TRP, /* only single occurrence allowed */
11597 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11598 TEOF, /* corresponds to trailing nul */
11599 TAND, TOR, TENDCASE /* if double occurrence */
11614 startlinno = g_parsefile->linno;
11615 for (;;) { /* until token or start of word found */
11617 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11621 while ((c = pgetc()) != '\n' && c != PEOF)
11624 } else if (c == '\\') {
11625 if (pgetc() != '\n') {
11627 break; /* return readtoken1(...) */
11629 startlinno = ++g_parsefile->linno;
11635 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11638 g_parsefile->linno++;
11639 needprompt = doprompt;
11642 p = strchr(xxreadtoken_chars, c);
11644 break; /* return readtoken1(...) */
11646 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11648 if (cc == c) { /* double occurrence? */
11649 p += xxreadtoken_doubles + 1;
11652 #if ENABLE_ASH_BASH_COMPAT
11653 if (c == '&' && cc == '>') /* &> */
11654 break; /* return readtoken1(...) */
11659 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11664 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11666 #else /* old xxreadtoken */
11667 #define RETURN(token) return lasttoken = token
11680 startlinno = g_parsefile->linno;
11681 for (;;) { /* until token or start of word found */
11684 case ' ': case '\t':
11685 IF_ASH_ALIAS(case PEOA:)
11688 while ((c = pgetc()) != '\n' && c != PEOF)
11693 if (pgetc() == '\n') {
11694 startlinno = ++g_parsefile->linno;
11702 g_parsefile->linno++;
11703 needprompt = doprompt;
11708 if (pgetc() == '&')
11713 if (pgetc() == '|')
11718 if (pgetc() == ';')
11731 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11734 #endif /* old xxreadtoken */
11741 smallint alreadyseen = tokpushback;
11744 #if ENABLE_ASH_ALIAS
11753 if (checkkwd & CHKNL) {
11760 if (t != TWORD || quoteflag) {
11765 * check for keywords
11767 if (checkkwd & CHKKWD) {
11768 const char *const *pp;
11770 pp = findkwd(wordtext);
11772 lasttoken = t = pp - tokname_array;
11773 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
11778 if (checkkwd & CHKALIAS) {
11779 #if ENABLE_ASH_ALIAS
11781 ap = lookupalias(wordtext, 1);
11784 pushstring(ap->val, ap);
11794 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11796 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11808 return tokname_array[t][0];
11812 * Read and parse a command. Returns NODE_EOF on end of file.
11813 * (NULL is a valid parse tree indicating a blank line.)
11815 static union node *
11816 parsecmd(int interact)
11821 doprompt = interact;
11823 setprompt(doprompt);
11835 * Input any here documents.
11840 struct heredoc *here;
11843 here = heredoclist;
11844 heredoclist = NULL;
11850 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11851 here->eofmark, here->striptabs);
11852 n = stzalloc(sizeof(struct narg));
11853 n->narg.type = NARG;
11854 /*n->narg.next = NULL; - stzalloc did it */
11855 n->narg.text = wordtext;
11856 n->narg.backquote = backquotelist;
11857 here->here->nhere.doc = n;
11864 * called by editline -- any expansions to the prompt should be added here.
11866 #if ENABLE_ASH_EXPAND_PRMT
11867 static const char *
11868 expandstr(const char *ps)
11872 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11873 * and token processing _can_ alter it (delete NULs etc). */
11874 setinputstring((char *)ps);
11875 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11878 n.narg.type = NARG;
11879 n.narg.next = NULL;
11880 n.narg.text = wordtext;
11881 n.narg.backquote = backquotelist;
11883 expandarg(&n, NULL, 0);
11884 return stackblock();
11889 * Execute a command or commands contained in a string.
11892 evalstring(char *s, int mask)
11895 struct stackmark smark;
11899 setstackmark(&smark);
11902 while ((n = parsecmd(0)) != NODE_EOF) {
11904 popstackmark(&smark);
11917 * The eval command.
11919 static int FAST_FUNC
11920 evalcmd(int argc UNUSED_PARAM, char **argv)
11929 STARTSTACKSTR(concat);
11931 concat = stack_putstr(p, concat);
11935 STPUTC(' ', concat);
11937 STPUTC('\0', concat);
11938 p = grabstackstr(concat);
11940 evalstring(p, ~SKIPEVAL);
11947 * Read and execute commands.
11948 * "Top" is nonzero for the top level command loop;
11949 * it turns on prompting if the shell is interactive.
11955 struct stackmark smark;
11959 TRACE(("cmdloop(%d) called\n", top));
11963 setstackmark(&smark);
11966 showjobs(stderr, SHOW_CHANGED);
11969 if (iflag && top) {
11971 #if ENABLE_ASH_MAIL
11975 n = parsecmd(inter);
11977 if (DEBUG > 2 && debug && (n != NODE_EOF))
11980 if (n == NODE_EOF) {
11981 if (!top || numeof >= 50)
11983 if (!stoppedjobs()) {
11986 out2str("\nUse \"exit\" to leave shell.\n");
11989 } else if (nflag == 0) {
11990 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11995 popstackmark(&smark);
12000 return skip & SKIPEVAL;
12007 * Take commands from a file. To be compatible we should do a path
12008 * search for the file, which is necessary to find sub-commands.
12011 find_dot_file(char *name)
12014 const char *path = pathval();
12017 /* don't try this for absolute or relative paths */
12018 if (strchr(name, '/'))
12021 /* IIRC standards do not say whether . is to be searched.
12022 * And it is even smaller this way, making it unconditional for now:
12024 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12029 while ((fullname = path_advance(&path, name)) != NULL) {
12031 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12033 * Don't bother freeing here, since it will
12034 * be freed by the caller.
12038 if (fullname != name)
12039 stunalloc(fullname);
12042 /* not found in the PATH */
12043 ash_msg_and_raise_error("%s: not found", name);
12047 static int FAST_FUNC
12048 dotcmd(int argc, char **argv)
12051 struct strlist *sp;
12052 volatile struct shparam saveparam;
12054 for (sp = cmdenviron; sp; sp = sp->next)
12055 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12058 /* bash says: "bash: .: filename argument required" */
12059 return 2; /* bash compat */
12062 /* "false; . empty_file; echo $?" should print 0, not 1: */
12065 fullname = find_dot_file(argv[1]);
12069 if (argc) { /* argc > 0, argv[0] != NULL */
12070 saveparam = shellparam;
12071 shellparam.malloced = 0;
12072 shellparam.nparam = argc;
12073 shellparam.p = argv;
12076 setinputfile(fullname, INPUT_PUSH_FILE);
12077 commandname = fullname;
12082 freeparam(&shellparam);
12083 shellparam = saveparam;
12089 static int FAST_FUNC
12090 exitcmd(int argc UNUSED_PARAM, char **argv)
12095 exitstatus = number(argv[1]);
12096 raise_exception(EXEXIT);
12101 * Read a file containing shell functions.
12104 readcmdfile(char *name)
12106 setinputfile(name, INPUT_PUSH_FILE);
12112 /* ============ find_command inplementation */
12115 * Resolve a command name. If you change this routine, you may have to
12116 * change the shellexec routine as well.
12119 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12121 struct tblentry *cmdp;
12128 struct builtincmd *bcmd;
12130 /* If name contains a slash, don't use PATH or hash table */
12131 if (strchr(name, '/') != NULL) {
12132 entry->u.index = -1;
12133 if (act & DO_ABS) {
12134 while (stat(name, &statb) < 0) {
12136 if (errno == EINTR)
12139 entry->cmdtype = CMDUNKNOWN;
12143 entry->cmdtype = CMDNORMAL;
12147 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12149 updatetbl = (path == pathval());
12152 if (strstr(path, "%builtin") != NULL)
12153 act |= DO_ALTBLTIN;
12156 /* If name is in the table, check answer will be ok */
12157 cmdp = cmdlookup(name, 0);
12158 if (cmdp != NULL) {
12161 switch (cmdp->cmdtype) {
12179 } else if (cmdp->rehash == 0)
12180 /* if not invalidated by cd, we're done */
12184 /* If %builtin not in path, check for builtin next */
12185 bcmd = find_builtin(name);
12187 if (IS_BUILTIN_REGULAR(bcmd))
12188 goto builtin_success;
12189 if (act & DO_ALTPATH) {
12190 if (!(act & DO_ALTBLTIN))
12191 goto builtin_success;
12192 } else if (builtinloc <= 0) {
12193 goto builtin_success;
12197 #if ENABLE_FEATURE_SH_STANDALONE
12199 int applet_no = find_applet_by_name(name);
12200 if (applet_no >= 0) {
12201 entry->cmdtype = CMDNORMAL;
12202 entry->u.index = -2 - applet_no;
12208 /* We have to search path. */
12209 prev = -1; /* where to start */
12210 if (cmdp && cmdp->rehash) { /* doing a rehash */
12211 if (cmdp->cmdtype == CMDBUILTIN)
12214 prev = cmdp->param.index;
12220 while ((fullname = path_advance(&path, name)) != NULL) {
12221 stunalloc(fullname);
12222 /* NB: code below will still use fullname
12223 * despite it being "unallocated" */
12226 if (prefix(pathopt, "builtin")) {
12228 goto builtin_success;
12231 if ((act & DO_NOFUNC)
12232 || !prefix(pathopt, "func")
12233 ) { /* ignore unimplemented options */
12237 /* if rehash, don't redo absolute path names */
12238 if (fullname[0] == '/' && idx <= prev) {
12241 TRACE(("searchexec \"%s\": no change\n", name));
12244 while (stat(fullname, &statb) < 0) {
12246 if (errno == EINTR)
12249 if (errno != ENOENT && errno != ENOTDIR)
12253 e = EACCES; /* if we fail, this will be the error */
12254 if (!S_ISREG(statb.st_mode))
12256 if (pathopt) { /* this is a %func directory */
12257 stalloc(strlen(fullname) + 1);
12258 /* NB: stalloc will return space pointed by fullname
12259 * (because we don't have any intervening allocations
12260 * between stunalloc above and this stalloc) */
12261 readcmdfile(fullname);
12262 cmdp = cmdlookup(name, 0);
12263 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12264 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12265 stunalloc(fullname);
12268 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12270 entry->cmdtype = CMDNORMAL;
12271 entry->u.index = idx;
12275 cmdp = cmdlookup(name, 1);
12276 cmdp->cmdtype = CMDNORMAL;
12277 cmdp->param.index = idx;
12282 /* We failed. If there was an entry for this command, delete it */
12283 if (cmdp && updatetbl)
12284 delete_cmd_entry();
12286 ash_msg("%s: %s", name, errmsg(e, "not found"));
12287 entry->cmdtype = CMDUNKNOWN;
12292 entry->cmdtype = CMDBUILTIN;
12293 entry->u.cmd = bcmd;
12297 cmdp = cmdlookup(name, 1);
12298 cmdp->cmdtype = CMDBUILTIN;
12299 cmdp->param.cmd = bcmd;
12303 entry->cmdtype = cmdp->cmdtype;
12304 entry->u = cmdp->param;
12308 /* ============ trap.c */
12311 * The trap builtin.
12313 static int FAST_FUNC
12314 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12318 int signo, exitcode;
12323 for (signo = 0; signo < NSIG; signo++) {
12324 char *tr = trap_ptr[signo];
12326 /* note: bash adds "SIG", but only if invoked
12327 * as "bash". If called as "sh", or if set -o posix,
12328 * then it prints short signal names.
12329 * We are printing short names: */
12330 out1fmt("trap -- %s %s\n",
12332 get_signame(signo));
12333 /* trap_ptr != trap only if we are in special-cased `trap` code.
12334 * In this case, we will exit very soon, no need to free(). */
12335 /* if (trap_ptr != trap && tp[0]) */
12340 if (trap_ptr != trap) {
12353 signo = get_signum(*ap);
12355 /* Mimic bash message exactly */
12356 ash_msg("%s: invalid signal specification", *ap);
12362 if (LONE_DASH(action))
12365 action = ckstrdup(action);
12369 may_have_traps = 1;
12370 trap[signo] = action;
12381 /* ============ Builtins */
12383 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12385 * Lists available builtins
12387 static int FAST_FUNC
12388 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12394 "Built-in commands:\n"
12395 "------------------\n");
12396 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12397 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12398 builtintab[i].name + 1);
12404 #if ENABLE_FEATURE_SH_STANDALONE
12406 const char *a = applet_names;
12408 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12413 a += strlen(a) + 1;
12418 return EXIT_SUCCESS;
12420 #endif /* FEATURE_SH_EXTRA_QUIET */
12423 * The export and readonly commands.
12425 static int FAST_FUNC
12426 exportcmd(int argc UNUSED_PARAM, char **argv)
12432 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12434 if (nextopt("p") != 'p') {
12439 p = strchr(name, '=');
12443 vp = *findvar(hashvar(name), name);
12449 setvar(name, p, flag);
12450 } while ((name = *++aptr) != NULL);
12454 showvars(argv[0], flag, 0);
12459 * Delete a function if it exists.
12462 unsetfunc(const char *name)
12464 struct tblentry *cmdp;
12466 cmdp = cmdlookup(name, 0);
12467 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12468 delete_cmd_entry();
12472 * The unset builtin command. We unset the function before we unset the
12473 * variable to allow a function to be unset when there is a readonly variable
12474 * with the same name.
12476 static int FAST_FUNC
12477 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12484 while ((i = nextopt("vf")) != 0) {
12488 for (ap = argptr; *ap; ap++) {
12501 static const unsigned char timescmd_str[] ALIGN1 = {
12502 ' ', offsetof(struct tms, tms_utime),
12503 '\n', offsetof(struct tms, tms_stime),
12504 ' ', offsetof(struct tms, tms_cutime),
12505 '\n', offsetof(struct tms, tms_cstime),
12508 static int FAST_FUNC
12509 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12511 unsigned long clk_tck, s, t;
12512 const unsigned char *p;
12515 clk_tck = sysconf(_SC_CLK_TCK);
12520 t = *(clock_t *)(((char *) &buf) + p[1]);
12523 out1fmt("%lum%lu.%03lus%c",
12525 (t * 1000) / clk_tck,
12533 #if ENABLE_SH_MATH_SUPPORT
12535 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12536 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12538 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12540 static int FAST_FUNC
12541 letcmd(int argc UNUSED_PARAM, char **argv)
12547 ash_msg_and_raise_error("expression expected");
12549 i = ash_arith(*argv);
12557 * The read builtin. Options:
12558 * -r Do not interpret '\' specially
12559 * -s Turn off echo (tty only)
12560 * -n NCHARS Read NCHARS max
12561 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12562 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12563 * -u FD Read from given FD instead of fd 0
12564 * This uses unbuffered input, which may be avoidable in some cases.
12565 * TODO: bash also has:
12566 * -a ARRAY Read into array[0],[1],etc
12567 * -d DELIM End on DELIM char, not newline
12568 * -e Use line editing (tty only)
12570 static int FAST_FUNC
12571 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12573 char *opt_n = NULL;
12574 char *opt_p = NULL;
12575 char *opt_t = NULL;
12576 char *opt_u = NULL;
12577 int read_flags = 0;
12581 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12590 read_flags |= BUILTIN_READ_SILENT;
12596 read_flags |= BUILTIN_READ_RAW;
12606 r = shell_builtin_read(setvar2,
12608 bltinlookup("IFS"), /* can be NULL */
12616 if ((uintptr_t)r > 1)
12617 ash_msg_and_raise_error(r);
12619 return (uintptr_t)r;
12622 static int FAST_FUNC
12623 umaskcmd(int argc UNUSED_PARAM, char **argv)
12625 static const char permuser[3] ALIGN1 = "ugo";
12626 static const char permmode[3] ALIGN1 = "rwx";
12627 static const short permmask[] ALIGN2 = {
12628 S_IRUSR, S_IWUSR, S_IXUSR,
12629 S_IRGRP, S_IWGRP, S_IXGRP,
12630 S_IROTH, S_IWOTH, S_IXOTH
12633 /* TODO: use bb_parse_mode() instead */
12638 int symbolic_mode = 0;
12640 while (nextopt("S") != '\0') {
12651 if (symbolic_mode) {
12655 for (i = 0; i < 3; i++) {
12658 *p++ = permuser[i];
12660 for (j = 0; j < 3; j++) {
12661 if ((mask & permmask[3 * i + j]) == 0) {
12662 *p++ = permmode[j];
12670 out1fmt("%.4o\n", mask);
12673 if (isdigit((unsigned char) *ap)) {
12676 if (*ap >= '8' || *ap < '0')
12677 ash_msg_and_raise_error(msg_illnum, argv[1]);
12678 mask = (mask << 3) + (*ap - '0');
12679 } while (*++ap != '\0');
12682 mask = ~mask & 0777;
12683 if (!bb_parse_mode(ap, &mask)) {
12684 ash_msg_and_raise_error("illegal mode: %s", ap);
12686 umask(~mask & 0777);
12692 static int FAST_FUNC
12693 ulimitcmd(int argc UNUSED_PARAM, char **argv)
12695 return shell_builtin_ulimit(argv);
12698 /* ============ main() and helpers */
12701 * Called to exit the shell.
12703 static void exitshell(void) NORETURN;
12711 status = exitstatus;
12712 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12713 if (setjmp(loc.loc)) {
12714 if (exception_type == EXEXIT)
12715 /* dash bug: it just does _exit(exitstatus) here
12716 * but we have to do setjobctl(0) first!
12717 * (bug is still not fixed in dash-0.5.3 - if you run dash
12718 * under Midnight Commander, on exit from dash MC is backgrounded) */
12719 status = exitstatus;
12722 exception_handler = &loc;
12729 flush_stdout_stderr();
12739 /* from input.c: */
12740 /* we will never free this */
12741 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
12744 signal(SIGCHLD, SIG_DFL);
12745 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12746 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12748 signal(SIGHUP, SIG_DFL);
12754 struct stat st1, st2;
12757 for (envp = environ; envp && *envp; envp++) {
12758 if (strchr(*envp, '=')) {
12759 setvareq(*envp, VEXPORT|VTEXTFIXED);
12763 setvar("PPID", utoa(getppid()), 0);
12765 p = lookupvar("PWD");
12767 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12768 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12775 * Process the shell command line arguments.
12778 procargs(char **argv)
12781 const char *xminusc;
12786 /* if (xargv[0]) - mmm, this is always true! */
12788 for (i = 0; i < NOPTS; i++)
12792 /* it already printed err message */
12793 raise_exception(EXERROR);
12797 if (*xargv == NULL) {
12799 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12802 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12806 for (i = 0; i < NOPTS; i++)
12807 if (optlist[i] == 2)
12812 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12817 } else if (!sflag) {
12818 setinputfile(*xargv, 0);
12821 commandname = arg0;
12824 shellparam.p = xargv;
12825 #if ENABLE_ASH_GETOPTS
12826 shellparam.optind = 1;
12827 shellparam.optoff = -1;
12829 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
12831 shellparam.nparam++;
12838 * Read /etc/profile or .profile.
12841 read_profile(const char *name)
12845 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12854 * This routine is called when an error or an interrupt occurs in an
12855 * interactive shell and control is returned to the main command loop.
12863 /* from input.c: */
12864 g_parsefile->left_in_buffer = 0;
12865 g_parsefile->left_in_line = 0; /* clear input buffer */
12867 /* from parser.c: */
12870 /* from redir.c: */
12871 clearredir(/*drop:*/ 0);
12875 static short profile_buf[16384];
12876 extern int etext();
12880 * Main routine. We initialize things, parse the arguments, execute
12881 * profiles if we're a login shell, and then call cmdloop to execute
12882 * commands. The setjmp call sets up the location to jump to when an
12883 * exception occurs. When an exception occurs the variable "state"
12884 * is used to figure out how far we had gotten.
12886 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
12887 int ash_main(int argc UNUSED_PARAM, char **argv)
12889 const char *shinit;
12890 volatile smallint state;
12891 struct jmploc jmploc;
12892 struct stackmark smark;
12894 /* Initialize global data */
12898 #if ENABLE_ASH_ALIAS
12904 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12907 #if ENABLE_FEATURE_EDITING
12908 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12911 if (setjmp(jmploc.loc)) {
12917 e = exception_type;
12921 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12924 outcslow('\n', stderr);
12926 popstackmark(&smark);
12927 FORCE_INT_ON; /* enable interrupts */
12936 exception_handler = &jmploc;
12939 TRACE(("Shell args: "));
12940 trace_puts_args(argv);
12942 rootpid = getpid();
12945 setstackmark(&smark);
12948 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
12950 const char *hp = lookupvar("HISTFILE");
12953 hp = lookupvar("HOME");
12955 char *defhp = concat_path_file(hp, ".ash_history");
12956 setvar("HISTFILE", defhp, 0);
12962 if (/* argv[0] && */ argv[0][0] == '-')
12966 read_profile("/etc/profile");
12969 read_profile(".profile");
12975 getuid() == geteuid() && getgid() == getegid() &&
12979 shinit = lookupvar("ENV");
12980 if (shinit != NULL && *shinit != '\0') {
12981 read_profile(shinit);
12987 /* evalstring pushes parsefile stack.
12988 * Ensure we don't falsely claim that 0 (stdin)
12989 * is one of stacked source fds.
12990 * Testcase: ash -c 'exec 1>&0' must not complain. */
12991 // if (!sflag) g_parsefile->pf_fd = -1;
12992 // ^^ not necessary since now we special-case fd 0
12993 // in is_hidden_fd() to not be considered "hidden fd"
12994 evalstring(minusc, 0);
12997 if (sflag || minusc == NULL) {
12998 #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13000 const char *hp = lookupvar("HISTFILE");
13002 line_input_state->hist_file = hp;
13005 state4: /* XXX ??? - why isn't this before the "if" statement */
13013 extern void _mcleanup(void);
13023 * Copyright (c) 1989, 1991, 1993, 1994
13024 * The Regents of the University of California. All rights reserved.
13026 * This code is derived from software contributed to Berkeley by
13027 * Kenneth Almquist.
13029 * Redistribution and use in source and binary forms, with or without
13030 * modification, are permitted provided that the following conditions
13032 * 1. Redistributions of source code must retain the above copyright
13033 * notice, this list of conditions and the following disclaimer.
13034 * 2. Redistributions in binary form must reproduce the above copyright
13035 * notice, this list of conditions and the following disclaimer in the
13036 * documentation and/or other materials provided with the distribution.
13037 * 3. Neither the name of the University nor the names of its contributors
13038 * may be used to endorse or promote products derived from this software
13039 * without specific prior written permission.
13041 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13042 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13043 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13044 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13045 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13046 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13047 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13048 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13049 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13050 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF