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
45 #include "busybox.h" /* for applet_names */
50 #include "shell_common.h"
51 #include "builtin_read.h"
52 #include "builtin_ulimit.h"
54 #if ENABLE_ASH_RANDOM_SUPPORT
57 # define CLEAR_RANDOM_T(rnd) ((void)0)
60 #define SKIP_definitions 1
61 #include "applet_tables.h"
62 #undef SKIP_definitions
64 /* STANDALONE does not make sense, and won't compile */
65 # undef CONFIG_FEATURE_SH_STANDALONE
66 # undef ENABLE_FEATURE_SH_STANDALONE
67 # undef IF_FEATURE_SH_STANDALONE
68 # undef IF_NOT_FEATURE_SH_STANDALONE
69 # define ENABLE_FEATURE_SH_STANDALONE 0
70 # define IF_FEATURE_SH_STANDALONE(...)
71 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
75 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
79 # error "Do not even bother, ash will not run on NOMMU machine"
83 /* ============ Hash table sizes. Configurable. */
87 #define CMDTABLESIZE 31 /* should be prime */
90 /* ============ Shell options */
92 static const char *const optletters_optnames[] = {
107 #if ENABLE_ASH_BASH_COMPAT
116 #define optletters(n) optletters_optnames[n][0]
117 #define optnames(n) (optletters_optnames[n] + 1)
119 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
122 /* ============ Misc data */
124 static const char homestr[] ALIGN1 = "HOME";
125 static const char snlfmt[] ALIGN1 = "%s\n";
126 static const char msg_illnum[] ALIGN1 = "Illegal number: %s";
129 * We enclose jmp_buf in a structure so that we can declare pointers to
130 * jump locations. The global variable handler contains the location to
131 * jump to when an exception occurs, and the global variable exception_type
132 * contains a code identifying the exception. To implement nested
133 * exception handlers, the user should save the value of handler on entry
134 * to an inner scope, set handler to point to a jmploc structure for the
135 * inner scope, and restore handler on exit from the scope.
141 struct globals_misc {
142 /* pid of main shell */
144 /* shell level: 0 for the main shell, 1 for its children, and so on */
146 #define rootshell (!shlvl)
147 char *minusc; /* argument to -c option */
149 char *curdir; // = nullstr; /* current working directory */
150 char *physdir; // = nullstr; /* physical working directory */
152 char *arg0; /* value of $0 */
154 struct jmploc *exception_handler;
156 volatile int suppress_int; /* counter */
157 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
158 /* last pending signal */
159 volatile /*sig_atomic_t*/ smallint pending_sig;
160 smallint exception_type; /* kind of exception (0..5) */
162 #define EXINT 0 /* SIGINT received */
163 #define EXERROR 1 /* a generic error */
164 #define EXSHELLPROC 2 /* execute a shell procedure */
165 #define EXEXEC 3 /* command execution failed */
166 #define EXEXIT 4 /* exit the shell */
167 #define EXSIG 5 /* trapped signal in wait(1) */
170 char nullstr[1]; /* zero length string */
173 #define eflag optlist[0]
174 #define fflag optlist[1]
175 #define Iflag optlist[2]
176 #define iflag optlist[3]
177 #define mflag optlist[4]
178 #define nflag optlist[5]
179 #define sflag optlist[6]
180 #define xflag optlist[7]
181 #define vflag optlist[8]
182 #define Cflag optlist[9]
183 #define aflag optlist[10]
184 #define bflag optlist[11]
185 #define uflag optlist[12]
186 #define viflag optlist[13]
187 #if ENABLE_ASH_BASH_COMPAT
188 # define pipefail optlist[14]
193 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
194 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
197 /* trap handler commands */
199 * Sigmode records the current value of the signal handlers for the various
200 * modes. A value of zero means that the current handler is not known.
201 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
203 char sigmode[NSIG - 1];
204 #define S_DFL 1 /* default signal handling (SIG_DFL) */
205 #define S_CATCH 2 /* signal is caught */
206 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
207 #define S_HARD_IGN 4 /* signal is ignored permenantly */
209 /* indicates specified signal received */
210 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
211 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
213 char **trap_ptr; /* used only by "trap hack" */
215 /* Rarely referenced stuff */
216 #if ENABLE_ASH_RANDOM_SUPPORT
219 pid_t backgndpid; /* pid of last background process */
220 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
222 extern struct globals_misc *const ash_ptr_to_globals_misc;
223 #define G_misc (*ash_ptr_to_globals_misc)
224 #define rootpid (G_misc.rootpid )
225 #define shlvl (G_misc.shlvl )
226 #define minusc (G_misc.minusc )
227 #define curdir (G_misc.curdir )
228 #define physdir (G_misc.physdir )
229 #define arg0 (G_misc.arg0 )
230 #define exception_handler (G_misc.exception_handler)
231 #define exception_type (G_misc.exception_type )
232 #define suppress_int (G_misc.suppress_int )
233 #define pending_int (G_misc.pending_int )
234 #define pending_sig (G_misc.pending_sig )
235 #define isloginsh (G_misc.isloginsh )
236 #define nullstr (G_misc.nullstr )
237 #define optlist (G_misc.optlist )
238 #define sigmode (G_misc.sigmode )
239 #define gotsig (G_misc.gotsig )
240 #define may_have_traps (G_misc.may_have_traps )
241 #define trap (G_misc.trap )
242 #define trap_ptr (G_misc.trap_ptr )
243 #define random_gen (G_misc.random_gen )
244 #define backgndpid (G_misc.backgndpid )
245 #define job_warning (G_misc.job_warning)
246 #define INIT_G_misc() do { \
247 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
255 /* ============ DEBUG */
257 static void trace_printf(const char *fmt, ...);
258 static void trace_vprintf(const char *fmt, va_list va);
259 # define TRACE(param) trace_printf param
260 # define TRACEV(param) trace_vprintf param
261 # define close(fd) do { \
263 if (close(dfd) < 0) \
264 bb_error_msg("bug on %d: closing %d(0x%x)", \
265 __LINE__, dfd, dfd); \
268 # define TRACE(param)
269 # define TRACEV(param)
273 /* ============ Utility functions */
274 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
276 static int isdigit_str9(const char *str)
278 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
279 while (--maxlen && isdigit(*str))
281 return (*str == '\0');
285 /* ============ Interrupts / exceptions */
287 * These macros allow the user to suspend the handling of interrupt signals
288 * over a period of time. This is similar to SIGHOLD or to sigblock, but
289 * much more efficient and portable. (But hacking the kernel is so much
290 * more fun than worrying about efficiency and portability. :-))
292 #define INT_OFF do { \
298 * Called to raise an exception. Since C doesn't include exceptions, we
299 * just do a longjmp to the exception handler. The type of exception is
300 * stored in the global variable "exception_type".
302 static void raise_exception(int) NORETURN;
304 raise_exception(int e)
307 if (exception_handler == NULL)
312 longjmp(exception_handler->loc, 1);
315 #define raise_exception(e) do { \
316 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
317 raise_exception(e); \
322 * Called from trap.c when a SIGINT is received. (If the user specifies
323 * that SIGINT is to be trapped or ignored using the trap builtin, then
324 * this routine is not called.) Suppressint is nonzero when interrupts
325 * are held using the INT_OFF macro. (The test for iflag is just
326 * defensive programming.)
328 static void raise_interrupt(void) NORETURN;
330 raise_interrupt(void)
335 /* Signal is not automatically unmasked after it is raised,
336 * do it ourself - unmask all signals */
337 sigprocmask_allsigs(SIG_UNBLOCK);
338 /* pending_sig = 0; - now done in signal_handler() */
341 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
342 if (!(rootshell && iflag)) {
343 /* Kill ourself with SIGINT */
344 signal(SIGINT, SIG_DFL);
349 raise_exception(ex_type);
353 #define raise_interrupt() do { \
354 TRACE(("raising interrupt on line %d\n", __LINE__)); \
359 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
363 if (--suppress_int == 0 && pending_int) {
367 #define INT_ON int_on()
368 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
376 #define FORCE_INT_ON force_int_on()
378 #define SAVE_INT(v) ((v) = suppress_int)
380 #define RESTORE_INT(v) do { \
382 suppress_int = (v); \
383 if (suppress_int == 0 && pending_int) \
388 /* ============ Stdout/stderr output */
391 outstr(const char *p, FILE *file)
399 flush_stdout_stderr(void)
407 outcslow(int c, FILE *dest)
415 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
417 out1fmt(const char *fmt, ...)
424 r = vprintf(fmt, ap);
430 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
432 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
439 ret = vsnprintf(outbuf, length, fmt, ap);
446 out1str(const char *p)
452 out2str(const char *p)
455 flush_stdout_stderr();
459 /* ============ Parser structures */
461 /* control characters in argument strings */
462 #define CTL_FIRST CTLESC
463 #define CTLESC ((unsigned char)'\201') /* escape next character */
464 #define CTLVAR ((unsigned char)'\202') /* variable defn */
465 #define CTLENDVAR ((unsigned char)'\203')
466 #define CTLBACKQ ((unsigned char)'\204')
467 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
468 /* CTLBACKQ | CTLQUOTE == '\205' */
469 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
470 #define CTLENDARI ((unsigned char)'\207')
471 #define CTLQUOTEMARK ((unsigned char)'\210')
472 #define CTL_LAST CTLQUOTEMARK
474 /* variable substitution byte (follows CTLVAR) */
475 #define VSTYPE 0x0f /* type of variable substitution */
476 #define VSNUL 0x10 /* colon--treat the empty string as unset */
477 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
479 /* values of VSTYPE field */
480 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
481 #define VSMINUS 0x2 /* ${var-text} */
482 #define VSPLUS 0x3 /* ${var+text} */
483 #define VSQUESTION 0x4 /* ${var?message} */
484 #define VSASSIGN 0x5 /* ${var=text} */
485 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
486 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
487 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
488 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
489 #define VSLENGTH 0xa /* ${#var} */
490 #if ENABLE_ASH_BASH_COMPAT
491 #define VSSUBSTR 0xc /* ${var:position:length} */
492 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
493 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
496 static const char dolatstr[] ALIGN1 = {
497 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
517 #if ENABLE_ASH_BASH_COMPAT
534 smallint type; /* Nxxxx */
537 union node *redirect;
542 smallint pipe_backgnd;
543 struct nodelist *cmdlist;
549 union node *redirect;
562 union node *elsepart;
589 struct nodelist *backquote;
592 /* nfile and ndup layout must match!
593 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
594 * that it is actually NTO2 (>&file), and change its type.
611 char *_unused_expfname;
630 struct nredir nredir;
631 struct nbinary nbinary;
635 struct nclist nclist;
644 * NODE_EOF is returned by parsecmd when it encounters an end of file.
645 * It must be distinct from NULL.
647 #define NODE_EOF ((union node *) -1L)
650 struct nodelist *next;
663 freefunc(struct funcnode *f)
665 if (f && --f->count < 0)
670 /* ============ Debugging output */
674 static FILE *tracefile;
677 trace_printf(const char *fmt, ...)
684 fprintf(tracefile, "%u ", (int) time(NULL));
686 fprintf(tracefile, "[%u] ", (int) getpid());
688 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
690 vfprintf(tracefile, fmt, va);
695 trace_vprintf(const char *fmt, va_list va)
700 fprintf(tracefile, "%u ", (int) time(NULL));
702 fprintf(tracefile, "[%u] ", (int) getpid());
704 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
705 vfprintf(tracefile, fmt, va);
709 trace_puts(const char *s)
717 trace_puts_quoted(char *s)
724 putc('"', tracefile);
725 for (p = s; *p; p++) {
726 switch ((unsigned char)*p) {
727 case '\n': c = 'n'; goto backslash;
728 case '\t': c = 't'; goto backslash;
729 case '\r': c = 'r'; goto backslash;
730 case '\"': c = '\"'; goto backslash;
731 case '\\': c = '\\'; goto backslash;
732 case CTLESC: c = 'e'; goto backslash;
733 case CTLVAR: c = 'v'; goto backslash;
734 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
735 case CTLBACKQ: c = 'q'; goto backslash;
736 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
738 putc('\\', tracefile);
742 if (*p >= ' ' && *p <= '~')
745 putc('\\', tracefile);
746 putc((*p >> 6) & 03, tracefile);
747 putc((*p >> 3) & 07, tracefile);
748 putc(*p & 07, tracefile);
753 putc('"', tracefile);
757 trace_puts_args(char **ap)
764 trace_puts_quoted(*ap);
766 putc('\n', tracefile);
769 putc(' ', tracefile);
784 /* leave open because libedit might be using it */
787 strcpy(s, "./trace");
789 if (!freopen(s, "a", tracefile)) {
790 fprintf(stderr, "Can't re-open %s\n", s);
795 tracefile = fopen(s, "a");
796 if (tracefile == NULL) {
797 fprintf(stderr, "Can't open %s\n", s);
803 flags = fcntl(fileno(tracefile), F_GETFL);
805 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
807 setlinebuf(tracefile);
808 fputs("\nTracing started.\n", tracefile);
812 indent(int amount, char *pfx, FILE *fp)
816 for (i = 0; i < amount; i++) {
817 if (pfx && i == amount - 1)
823 /* little circular references here... */
824 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
827 sharg(union node *arg, FILE *fp)
830 struct nodelist *bqlist;
831 unsigned char subtype;
833 if (arg->type != NARG) {
834 out1fmt("<node type %d>\n", arg->type);
837 bqlist = arg->narg.backquote;
838 for (p = arg->narg.text; *p; p++) {
839 switch ((unsigned char)*p) {
847 if (subtype == VSLENGTH)
856 switch (subtype & VSTYPE) {
889 out1fmt("<subtype %d>", subtype);
896 case CTLBACKQ|CTLQUOTE:
899 shtree(bqlist->n, -1, NULL, fp);
910 shcmd(union node *cmd, FILE *fp)
918 for (np = cmd->ncmd.args; np; np = np->narg.next) {
924 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
928 switch (np->nfile.type) {
929 case NTO: s = ">>"+1; dftfd = 1; break;
930 case NCLOBBER: s = ">|"; dftfd = 1; break;
931 case NAPPEND: s = ">>"; dftfd = 1; break;
932 #if ENABLE_ASH_BASH_COMPAT
935 case NTOFD: s = ">&"; dftfd = 1; break;
936 case NFROM: s = "<"; break;
937 case NFROMFD: s = "<&"; break;
938 case NFROMTO: s = "<>"; break;
939 default: s = "*error*"; break;
941 if (np->nfile.fd != dftfd)
942 fprintf(fp, "%d", np->nfile.fd);
944 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
945 fprintf(fp, "%d", np->ndup.dupfd);
947 sharg(np->nfile.fname, fp);
954 shtree(union node *n, int ind, char *pfx, FILE *fp)
962 indent(ind, pfx, fp);
979 shtree(n->nbinary.ch1, ind, NULL, fp);
982 shtree(n->nbinary.ch2, ind, NULL, fp);
990 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
991 shtree(lp->n, 0, NULL, fp);
995 if (n->npipe.pipe_backgnd)
1001 fprintf(fp, "<node type %d>", n->type);
1009 showtree(union node *n)
1011 trace_puts("showtree called\n");
1012 shtree(n, 1, NULL, stderr);
1018 /* ============ Parser data */
1021 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1024 struct strlist *next;
1031 struct strpush *prev; /* preceding string on stack */
1033 int prev_left_in_line;
1034 #if ENABLE_ASH_ALIAS
1035 struct alias *ap; /* if push was associated with an alias */
1037 char *string; /* remember the string since it may change */
1041 struct parsefile *prev; /* preceding file on stack */
1042 int linno; /* current line */
1043 int fd; /* file descriptor (or -1 if string) */
1044 int left_in_line; /* number of chars left in this line */
1045 int left_in_buffer; /* number of chars left in this buffer past the line */
1046 char *next_to_pgetc; /* next char in buffer */
1047 char *buf; /* input buffer */
1048 struct strpush *strpush; /* for pushing strings at this level */
1049 struct strpush basestrpush; /* so pushing one is fast */
1052 static struct parsefile basepf; /* top level input file */
1053 static struct parsefile *g_parsefile = &basepf; /* current input file */
1054 static int startlinno; /* line # where last token started */
1055 static char *commandname; /* currently executing command */
1056 static struct strlist *cmdenviron; /* environment for builtin command */
1057 static uint8_t exitstatus; /* exit status of last command */
1060 /* ============ Message printing */
1063 ash_vmsg(const char *msg, va_list ap)
1065 fprintf(stderr, "%s: ", arg0);
1067 if (strcmp(arg0, commandname))
1068 fprintf(stderr, "%s: ", commandname);
1069 if (!iflag || g_parsefile->fd)
1070 fprintf(stderr, "line %d: ", startlinno);
1072 vfprintf(stderr, msg, ap);
1073 outcslow('\n', stderr);
1077 * Exverror is called to raise the error exception. If the second argument
1078 * is not NULL then error prints an error message using printf style
1079 * formatting. It then raises the error exception.
1081 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1083 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1087 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1089 TRACE(("\") pid=%d\n", getpid()));
1091 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1096 flush_stdout_stderr();
1097 raise_exception(cond);
1101 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1103 ash_msg_and_raise_error(const char *msg, ...)
1108 ash_vmsg_and_raise(EXERROR, msg, ap);
1113 static void raise_error_syntax(const char *) NORETURN;
1115 raise_error_syntax(const char *msg)
1117 ash_msg_and_raise_error("syntax error: %s", msg);
1121 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1123 ash_msg_and_raise(int cond, const char *msg, ...)
1128 ash_vmsg_and_raise(cond, msg, ap);
1134 * error/warning routines for external builtins
1137 ash_msg(const char *fmt, ...)
1147 * Return a string describing an error. The returned string may be a
1148 * pointer to a static buffer that will be overwritten on the next call.
1149 * Action describes the operation that got the error.
1152 errmsg(int e, const char *em)
1154 if (e == ENOENT || e == ENOTDIR) {
1161 /* ============ Memory allocation */
1164 /* I consider these wrappers nearly useless:
1165 * ok, they return you to nearest exception handler, but
1166 * how much memory do you leak in the process, making
1167 * memory starvation worse?
1170 ckrealloc(void * p, size_t nbytes)
1172 p = realloc(p, nbytes);
1174 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1179 ckmalloc(size_t nbytes)
1181 return ckrealloc(NULL, nbytes);
1185 ckzalloc(size_t nbytes)
1187 return memset(ckmalloc(nbytes), 0, nbytes);
1191 ckstrdup(const char *s)
1193 char *p = strdup(s);
1195 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1199 /* Using bbox equivalents. They exit if out of memory */
1200 # define ckrealloc xrealloc
1201 # define ckmalloc xmalloc
1202 # define ckzalloc xzalloc
1203 # define ckstrdup xstrdup
1207 * It appears that grabstackstr() will barf with such alignments
1208 * because stalloc() will return a string allocated in a new stackblock.
1210 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1212 /* Most machines require the value returned from malloc to be aligned
1213 * in some way. The following macro will get this right
1214 * on many machines. */
1215 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1216 /* Minimum size of a block */
1217 MINSIZE = SHELL_ALIGN(504),
1220 struct stack_block {
1221 struct stack_block *prev;
1222 char space[MINSIZE];
1226 struct stack_block *stackp;
1229 struct stackmark *marknext;
1233 struct globals_memstack {
1234 struct stack_block *g_stackp; // = &stackbase;
1235 struct stackmark *markp;
1236 char *g_stacknxt; // = stackbase.space;
1237 char *sstrend; // = stackbase.space + MINSIZE;
1238 size_t g_stacknleft; // = MINSIZE;
1239 int herefd; // = -1;
1240 struct stack_block stackbase;
1242 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1243 #define G_memstack (*ash_ptr_to_globals_memstack)
1244 #define g_stackp (G_memstack.g_stackp )
1245 #define markp (G_memstack.markp )
1246 #define g_stacknxt (G_memstack.g_stacknxt )
1247 #define sstrend (G_memstack.sstrend )
1248 #define g_stacknleft (G_memstack.g_stacknleft)
1249 #define herefd (G_memstack.herefd )
1250 #define stackbase (G_memstack.stackbase )
1251 #define INIT_G_memstack() do { \
1252 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1254 g_stackp = &stackbase; \
1255 g_stacknxt = stackbase.space; \
1256 g_stacknleft = MINSIZE; \
1257 sstrend = stackbase.space + MINSIZE; \
1262 #define stackblock() ((void *)g_stacknxt)
1263 #define stackblocksize() g_stacknleft
1266 * Parse trees for commands are allocated in lifo order, so we use a stack
1267 * to make this more efficient, and also to avoid all sorts of exception
1268 * handling code to handle interrupts in the middle of a parse.
1270 * The size 504 was chosen because the Ultrix malloc handles that size
1274 stalloc(size_t nbytes)
1279 aligned = SHELL_ALIGN(nbytes);
1280 if (aligned > g_stacknleft) {
1283 struct stack_block *sp;
1285 blocksize = aligned;
1286 if (blocksize < MINSIZE)
1287 blocksize = MINSIZE;
1288 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1289 if (len < blocksize)
1290 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1293 sp->prev = g_stackp;
1294 g_stacknxt = sp->space;
1295 g_stacknleft = blocksize;
1296 sstrend = g_stacknxt + blocksize;
1301 g_stacknxt += aligned;
1302 g_stacknleft -= aligned;
1307 stzalloc(size_t nbytes)
1309 return memset(stalloc(nbytes), 0, nbytes);
1316 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1317 write(STDERR_FILENO, "stunalloc\n", 10);
1321 g_stacknleft += g_stacknxt - (char *)p;
1326 * Like strdup but works with the ash stack.
1329 ststrdup(const char *p)
1331 size_t len = strlen(p) + 1;
1332 return memcpy(stalloc(len), p, len);
1336 setstackmark(struct stackmark *mark)
1338 mark->stackp = g_stackp;
1339 mark->stacknxt = g_stacknxt;
1340 mark->stacknleft = g_stacknleft;
1341 mark->marknext = markp;
1346 popstackmark(struct stackmark *mark)
1348 struct stack_block *sp;
1354 markp = mark->marknext;
1355 while (g_stackp != mark->stackp) {
1357 g_stackp = sp->prev;
1360 g_stacknxt = mark->stacknxt;
1361 g_stacknleft = mark->stacknleft;
1362 sstrend = mark->stacknxt + mark->stacknleft;
1367 * When the parser reads in a string, it wants to stick the string on the
1368 * stack and only adjust the stack pointer when it knows how big the
1369 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1370 * of space on top of the stack and stackblocklen returns the length of
1371 * this block. Growstackblock will grow this space by at least one byte,
1372 * possibly moving it (like realloc). Grabstackblock actually allocates the
1373 * part of the block that has been used.
1376 growstackblock(void)
1380 newlen = g_stacknleft * 2;
1381 if (newlen < g_stacknleft)
1382 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1386 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1387 struct stack_block *oldstackp;
1388 struct stackmark *xmark;
1389 struct stack_block *sp;
1390 struct stack_block *prevstackp;
1394 oldstackp = g_stackp;
1396 prevstackp = sp->prev;
1397 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1398 sp = ckrealloc(sp, grosslen);
1399 sp->prev = prevstackp;
1401 g_stacknxt = sp->space;
1402 g_stacknleft = newlen;
1403 sstrend = sp->space + newlen;
1406 * Stack marks pointing to the start of the old block
1407 * must be relocated to point to the new block
1410 while (xmark != NULL && xmark->stackp == oldstackp) {
1411 xmark->stackp = g_stackp;
1412 xmark->stacknxt = g_stacknxt;
1413 xmark->stacknleft = g_stacknleft;
1414 xmark = xmark->marknext;
1418 char *oldspace = g_stacknxt;
1419 size_t oldlen = g_stacknleft;
1420 char *p = stalloc(newlen);
1422 /* free the space we just allocated */
1423 g_stacknxt = memcpy(p, oldspace, oldlen);
1424 g_stacknleft += newlen;
1429 grabstackblock(size_t len)
1431 len = SHELL_ALIGN(len);
1433 g_stacknleft -= len;
1437 * The following routines are somewhat easier to use than the above.
1438 * The user declares a variable of type STACKSTR, which may be declared
1439 * to be a register. The macro STARTSTACKSTR initializes things. Then
1440 * the user uses the macro STPUTC to add characters to the string. In
1441 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1442 * grown as necessary. When the user is done, she can just leave the
1443 * string there and refer to it using stackblock(). Or she can allocate
1444 * the space for it using grabstackstr(). If it is necessary to allow
1445 * someone else to use the stack temporarily and then continue to grow
1446 * the string, the user should use grabstack to allocate the space, and
1447 * then call ungrabstr(p) to return to the previous mode of operation.
1449 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1450 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1451 * is space for at least one character.
1456 size_t len = stackblocksize();
1457 if (herefd >= 0 && len >= 1024) {
1458 full_write(herefd, stackblock(), len);
1459 return stackblock();
1462 return (char *)stackblock() + len;
1466 * Called from CHECKSTRSPACE.
1469 makestrspace(size_t newlen, char *p)
1471 size_t len = p - g_stacknxt;
1472 size_t size = stackblocksize();
1477 size = stackblocksize();
1479 if (nleft >= newlen)
1483 return (char *)stackblock() + len;
1487 stack_nputstr(const char *s, size_t n, char *p)
1489 p = makestrspace(n, p);
1490 p = (char *)memcpy(p, s, n) + n;
1495 stack_putstr(const char *s, char *p)
1497 return stack_nputstr(s, strlen(s), p);
1501 _STPUTC(int c, char *p)
1509 #define STARTSTACKSTR(p) ((p) = stackblock())
1510 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1511 #define CHECKSTRSPACE(n, p) do { \
1514 size_t m = sstrend - q; \
1516 (p) = makestrspace(l, q); \
1518 #define USTPUTC(c, p) (*(p)++ = (c))
1519 #define STACKSTRNUL(p) do { \
1520 if ((p) == sstrend) \
1521 (p) = growstackstr(); \
1524 #define STUNPUTC(p) (--(p))
1525 #define STTOPC(p) ((p)[-1])
1526 #define STADJUST(amount, p) ((p) += (amount))
1528 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1529 #define ungrabstackstr(s, p) stunalloc(s)
1530 #define stackstrend() ((void *)sstrend)
1533 /* ============ String helpers */
1536 * prefix -- see if pfx is a prefix of string.
1539 prefix(const char *string, const char *pfx)
1542 if (*pfx++ != *string++)
1545 return (char *) string;
1549 * Check for a valid number. This should be elsewhere.
1552 is_number(const char *p)
1557 } while (*++p != '\0');
1562 * Convert a string of digits to an integer, printing an error message on
1566 number(const char *s)
1569 ash_msg_and_raise_error(msg_illnum, s);
1574 * Produce a possibly single quoted string suitable as input to the shell.
1575 * The return string is allocated on the stack.
1578 single_quote(const char *s)
1588 len = strchrnul(s, '\'') - s;
1590 q = p = makestrspace(len + 3, p);
1593 q = (char *)memcpy(q, s, len) + len;
1602 do len++; while (*++s == '\'');
1604 q = p = makestrspace(len + 3, p);
1607 q = (char *)memcpy(q, s - len, len) + len;
1615 return stackblock();
1619 /* ============ nextopt */
1621 static char **argptr; /* argument list for builtin commands */
1622 static char *optionarg; /* set by nextopt (like getopt) */
1623 static char *optptr; /* used by nextopt */
1626 * XXX - should get rid of. Have all builtins use getopt(3).
1627 * The library getopt must have the BSD extension static variable
1628 * "optreset", otherwise it can't be used within the shell safely.
1630 * Standard option processing (a la getopt) for builtin routines.
1631 * The only argument that is passed to nextopt is the option string;
1632 * the other arguments are unnecessary. It returns the character,
1633 * or '\0' on end of input.
1636 nextopt(const char *optstring)
1643 if (p == NULL || *p == '\0') {
1644 /* We ate entire "-param", take next one */
1650 if (*++p == '\0') /* just "-" ? */
1653 if (LONE_DASH(p)) /* "--" ? */
1655 /* p => next "-param" */
1657 /* p => some option char in the middle of a "-param" */
1659 for (q = optstring; *q != c;) {
1661 ash_msg_and_raise_error("illegal option -%c", c);
1669 ash_msg_and_raise_error("no arg for -%c option", c);
1679 /* ============ Shell variables */
1682 * The parsefile structure pointed to by the global variable parsefile
1683 * contains information about the current file being read.
1686 int nparam; /* # of positional parameters (without $0) */
1687 #if ENABLE_ASH_GETOPTS
1688 int optind; /* next parameter to be processed by getopts */
1689 int optoff; /* used by getopts */
1691 unsigned char malloced; /* if parameter list dynamically allocated */
1692 char **p; /* parameter list */
1696 * Free the list of positional parameters.
1699 freeparam(volatile struct shparam *param)
1701 if (param->malloced) {
1703 ap = ap1 = param->p;
1710 #if ENABLE_ASH_GETOPTS
1711 static void FAST_FUNC getoptsreset(const char *value);
1715 struct var *next; /* next entry in hash list */
1716 int flags; /* flags are defined above */
1717 const char *text; /* name=value */
1718 void (*func)(const char *) FAST_FUNC; /* function to be called when */
1719 /* the variable gets set/unset */
1723 struct localvar *next; /* next local variable in list */
1724 struct var *vp; /* the variable that was made local */
1725 int flags; /* saved flags */
1726 const char *text; /* saved text */
1730 #define VEXPORT 0x01 /* variable is exported */
1731 #define VREADONLY 0x02 /* variable cannot be modified */
1732 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1733 #define VTEXTFIXED 0x08 /* text is statically allocated */
1734 #define VSTACK 0x10 /* text is allocated on the stack */
1735 #define VUNSET 0x20 /* the variable is not set */
1736 #define VNOFUNC 0x40 /* don't call the callback function */
1737 #define VNOSET 0x80 /* do not set variable - just readonly test */
1738 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1739 #if ENABLE_ASH_RANDOM_SUPPORT
1740 # define VDYNAMIC 0x200 /* dynamic variable */
1746 /* Need to be before varinit_data[] */
1747 #if ENABLE_LOCALE_SUPPORT
1748 static void FAST_FUNC
1749 change_lc_all(const char *value)
1751 if (value && *value != '\0')
1752 setlocale(LC_ALL, value);
1754 static void FAST_FUNC
1755 change_lc_ctype(const char *value)
1757 if (value && *value != '\0')
1758 setlocale(LC_CTYPE, value);
1762 static void chkmail(void);
1763 static void changemail(const char *) FAST_FUNC;
1765 static void changepath(const char *) FAST_FUNC;
1766 #if ENABLE_ASH_RANDOM_SUPPORT
1767 static void change_random(const char *) FAST_FUNC;
1770 static const struct {
1773 void (*func)(const char *) FAST_FUNC;
1774 } varinit_data[] = {
1775 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1777 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1778 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1780 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1781 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1782 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1783 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1784 #if ENABLE_ASH_GETOPTS
1785 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1787 #if ENABLE_ASH_RANDOM_SUPPORT
1788 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
1790 #if ENABLE_LOCALE_SUPPORT
1791 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1792 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
1794 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1795 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
1801 struct globals_var {
1802 struct shparam shellparam; /* $@ current positional parameters */
1803 struct redirtab *redirlist;
1805 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1806 struct var *vartab[VTABSIZE];
1807 struct var varinit[ARRAY_SIZE(varinit_data)];
1809 extern struct globals_var *const ash_ptr_to_globals_var;
1810 #define G_var (*ash_ptr_to_globals_var)
1811 #define shellparam (G_var.shellparam )
1812 //#define redirlist (G_var.redirlist )
1813 #define g_nullredirs (G_var.g_nullredirs )
1814 #define preverrout_fd (G_var.preverrout_fd)
1815 #define vartab (G_var.vartab )
1816 #define varinit (G_var.varinit )
1817 #define INIT_G_var() do { \
1819 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1821 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1822 varinit[i].flags = varinit_data[i].flags; \
1823 varinit[i].text = varinit_data[i].text; \
1824 varinit[i].func = varinit_data[i].func; \
1828 #define vifs varinit[0]
1830 # define vmail (&vifs)[1]
1831 # define vmpath (&vmail)[1]
1832 # define vpath (&vmpath)[1]
1834 # define vpath (&vifs)[1]
1836 #define vps1 (&vpath)[1]
1837 #define vps2 (&vps1)[1]
1838 #define vps4 (&vps2)[1]
1839 #if ENABLE_ASH_GETOPTS
1840 # define voptind (&vps4)[1]
1841 # if ENABLE_ASH_RANDOM_SUPPORT
1842 # define vrandom (&voptind)[1]
1845 # if ENABLE_ASH_RANDOM_SUPPORT
1846 # define vrandom (&vps4)[1]
1851 * The following macros access the values of the above variables.
1852 * They have to skip over the name. They return the null string
1853 * for unset variables.
1855 #define ifsval() (vifs.text + 4)
1856 #define ifsset() ((vifs.flags & VUNSET) == 0)
1858 # define mailval() (vmail.text + 5)
1859 # define mpathval() (vmpath.text + 9)
1860 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1862 #define pathval() (vpath.text + 5)
1863 #define ps1val() (vps1.text + 4)
1864 #define ps2val() (vps2.text + 4)
1865 #define ps4val() (vps4.text + 4)
1866 #if ENABLE_ASH_GETOPTS
1867 # define optindval() (voptind.text + 7)
1871 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1872 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1874 #if ENABLE_ASH_GETOPTS
1875 static void FAST_FUNC
1876 getoptsreset(const char *value)
1878 shellparam.optind = number(value);
1879 shellparam.optoff = -1;
1884 * Return of a legal variable name (a letter or underscore followed by zero or
1885 * more letters, underscores, and digits).
1887 static char* FAST_FUNC
1888 endofname(const char *name)
1896 if (!is_in_name(*p))
1903 * Compares two strings up to the first = or '\0'. The first
1904 * string must be terminated by '='; the second may be terminated by
1905 * either '=' or '\0'.
1908 varcmp(const char *p, const char *q)
1912 while ((c = *p) == (d = *q)) {
1927 varequal(const char *a, const char *b)
1929 return !varcmp(a, b);
1933 * Find the appropriate entry in the hash table from the name.
1935 static struct var **
1936 hashvar(const char *p)
1940 hashval = ((unsigned char) *p) << 4;
1941 while (*p && *p != '=')
1942 hashval += (unsigned char) *p++;
1943 return &vartab[hashval % VTABSIZE];
1947 vpcmp(const void *a, const void *b)
1949 return varcmp(*(const char **)a, *(const char **)b);
1953 * This routine initializes the builtin variables.
1963 * PS1 depends on uid
1965 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1966 vps1.text = "PS1=\\w \\$ ";
1969 vps1.text = "PS1=# ";
1972 end = vp + ARRAY_SIZE(varinit);
1974 vpp = hashvar(vp->text);
1977 } while (++vp < end);
1980 static struct var **
1981 findvar(struct var **vpp, const char *name)
1983 for (; *vpp; vpp = &(*vpp)->next) {
1984 if (varequal((*vpp)->text, name)) {
1992 * Find the value of a variable. Returns NULL if not set.
1994 static const char* FAST_FUNC
1995 lookupvar(const char *name)
1999 v = *findvar(hashvar(name), name);
2001 #if ENABLE_ASH_RANDOM_SUPPORT
2003 * Dynamic variables are implemented roughly the same way they are
2004 * in bash. Namely, they're "special" so long as they aren't unset.
2005 * As soon as they're unset, they're no longer dynamic, and dynamic
2006 * lookup will no longer happen at that point. -- PFM.
2008 if ((v->flags & VDYNAMIC))
2011 if (!(v->flags & VUNSET))
2012 return strchrnul(v->text, '=') + 1;
2018 * Search the environment of a builtin command.
2021 bltinlookup(const char *name)
2025 for (sp = cmdenviron; sp; sp = sp->next) {
2026 if (varequal(sp->text, name))
2027 return strchrnul(sp->text, '=') + 1;
2029 return lookupvar(name);
2033 * Same as setvar except that the variable and value are passed in
2034 * the first argument as name=value. Since the first argument will
2035 * be actually stored in the table, it should not be a string that
2037 * Called with interrupts off.
2040 setvareq(char *s, int flags)
2042 struct var *vp, **vpp;
2045 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2046 vp = *findvar(vpp, s);
2048 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2051 if (flags & VNOSAVE)
2054 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2060 if (vp->func && (flags & VNOFUNC) == 0)
2061 (*vp->func)(strchrnul(s, '=') + 1);
2063 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2064 free((char*)vp->text);
2066 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2071 vp = ckzalloc(sizeof(*vp));
2073 /*vp->func = NULL; - ckzalloc did it */
2076 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2083 * Set the value of a variable. The flags argument is ored with the
2084 * flags of the variable. If val is NULL, the variable is unset.
2087 setvar(const char *name, const char *val, int flags)
2094 q = endofname(name);
2095 p = strchrnul(q, '=');
2097 if (!namelen || p != q)
2098 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2103 vallen = strlen(val);
2106 nameeq = ckmalloc(namelen + vallen + 2);
2107 p = (char *)memcpy(nameeq, name, namelen) + namelen;
2110 p = (char *)memcpy(p, val, vallen) + vallen;
2113 setvareq(nameeq, flags | VNOSAVE);
2117 static void FAST_FUNC
2118 setvar2(const char *name, const char *val)
2120 setvar(name, val, 0);
2123 #if ENABLE_ASH_GETOPTS
2125 * Safe version of setvar, returns 1 on success 0 on failure.
2128 setvarsafe(const char *name, const char *val, int flags)
2131 volatile int saveint;
2132 struct jmploc *volatile savehandler = exception_handler;
2133 struct jmploc jmploc;
2136 if (setjmp(jmploc.loc))
2139 exception_handler = &jmploc;
2140 setvar(name, val, flags);
2143 exception_handler = savehandler;
2144 RESTORE_INT(saveint);
2150 * Unset the specified variable.
2153 unsetvar(const char *s)
2159 vpp = findvar(hashvar(s), s);
2163 int flags = vp->flags;
2166 if (flags & VREADONLY)
2168 #if ENABLE_ASH_RANDOM_SUPPORT
2169 vp->flags &= ~VDYNAMIC;
2173 if ((flags & VSTRFIXED) == 0) {
2175 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2176 free((char*)vp->text);
2182 vp->flags &= ~VEXPORT;
2192 * Process a linked list of variable assignments.
2195 listsetvar(struct strlist *list_set_var, int flags)
2197 struct strlist *lp = list_set_var;
2203 setvareq(lp->text, flags);
2210 * Generate a list of variables satisfying the given conditions.
2213 listvars(int on, int off, char ***end)
2224 for (vp = *vpp; vp; vp = vp->next) {
2225 if ((vp->flags & mask) == on) {
2226 if (ep == stackstrend())
2227 ep = growstackstr();
2228 *ep++ = (char *) vp->text;
2231 } while (++vpp < vartab + VTABSIZE);
2232 if (ep == stackstrend())
2233 ep = growstackstr();
2237 return grabstackstr(ep);
2241 /* ============ Path search helper
2243 * The variable path (passed by reference) should be set to the start
2244 * of the path before the first call; path_advance will update
2245 * this value as it proceeds. Successive calls to path_advance will return
2246 * the possible path expansions in sequence. If an option (indicated by
2247 * a percent sign) appears in the path entry then the global variable
2248 * pathopt will be set to point to it; otherwise pathopt will be set to
2251 static const char *pathopt; /* set by path_advance */
2254 path_advance(const char **path, const char *name)
2264 for (p = start; *p && *p != ':' && *p != '%'; p++)
2266 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2267 while (stackblocksize() < len)
2271 memcpy(q, start, p - start);
2279 while (*p && *p != ':')
2286 return stalloc(len);
2290 /* ============ Prompt */
2292 static smallint doprompt; /* if set, prompt the user */
2293 static smallint needprompt; /* true if interactive and at start of line */
2295 #if ENABLE_FEATURE_EDITING
2296 static line_input_t *line_input_state;
2297 static const char *cmdedit_prompt;
2299 putprompt(const char *s)
2301 if (ENABLE_ASH_EXPAND_PRMT) {
2302 free((char*)cmdedit_prompt);
2303 cmdedit_prompt = ckstrdup(s);
2310 putprompt(const char *s)
2316 #if ENABLE_ASH_EXPAND_PRMT
2317 /* expandstr() needs parsing machinery, so it is far away ahead... */
2318 static const char *expandstr(const char *ps);
2320 #define expandstr(s) s
2324 setprompt(int whichprompt)
2327 #if ENABLE_ASH_EXPAND_PRMT
2328 struct stackmark smark;
2333 switch (whichprompt) {
2343 #if ENABLE_ASH_EXPAND_PRMT
2344 setstackmark(&smark);
2345 stalloc(stackblocksize());
2347 putprompt(expandstr(prompt));
2348 #if ENABLE_ASH_EXPAND_PRMT
2349 popstackmark(&smark);
2354 /* ============ The cd and pwd commands */
2356 #define CD_PHYSICAL 1
2366 while ((i = nextopt("LP")) != '\0') {
2368 flags ^= CD_PHYSICAL;
2377 * Update curdir (the name of the current directory) in response to a
2381 updatepwd(const char *dir)
2388 cdcomppath = ststrdup(dir);
2391 if (curdir == nullstr)
2393 new = stack_putstr(curdir, new);
2395 new = makestrspace(strlen(dir) + 2, new);
2396 lim = (char *)stackblock() + 1;
2400 if (new > lim && *lim == '/')
2405 if (dir[1] == '/' && dir[2] != '/') {
2411 p = strtok(cdcomppath, "/");
2415 if (p[1] == '.' && p[2] == '\0') {
2427 new = stack_putstr(p, new);
2435 return stackblock();
2439 * Find out what the current directory is. If we already know the current
2440 * directory, this routine returns immediately.
2445 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2446 return dir ? dir : nullstr;
2450 setpwd(const char *val, int setold)
2454 oldcur = dir = curdir;
2457 setvar("OLDPWD", oldcur, VEXPORT);
2460 if (physdir != nullstr) {
2461 if (physdir != oldcur)
2465 if (oldcur == val || !val) {
2471 dir = ckstrdup(val);
2472 if (oldcur != dir && oldcur != nullstr) {
2477 setvar("PWD", dir, VEXPORT);
2480 static void hashcd(void);
2483 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2484 * know that the current directory has changed.
2487 docd(const char *dest, int flags)
2489 const char *dir = NULL;
2492 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2495 if (!(flags & CD_PHYSICAL)) {
2496 dir = updatepwd(dest);
2510 static int FAST_FUNC
2511 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2523 dest = bltinlookup(homestr);
2524 else if (LONE_DASH(dest)) {
2525 dest = bltinlookup("OLDPWD");
2547 path = bltinlookup("CDPATH");
2556 p = path_advance(&path, dest);
2557 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2561 if (!docd(p, flags))
2566 ash_msg_and_raise_error("can't cd to %s", dest);
2569 if (flags & CD_PRINT)
2570 out1fmt(snlfmt, curdir);
2574 static int FAST_FUNC
2575 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2578 const char *dir = curdir;
2582 if (physdir == nullstr)
2586 out1fmt(snlfmt, dir);
2591 /* ============ ... */
2594 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2596 /* Syntax classes */
2597 #define CWORD 0 /* character is nothing special */
2598 #define CNL 1 /* newline character */
2599 #define CBACK 2 /* a backslash character */
2600 #define CSQUOTE 3 /* single quote */
2601 #define CDQUOTE 4 /* double quote */
2602 #define CENDQUOTE 5 /* a terminating quote */
2603 #define CBQUOTE 6 /* backwards single quote */
2604 #define CVAR 7 /* a dollar sign */
2605 #define CENDVAR 8 /* a '}' character */
2606 #define CLP 9 /* a left paren in arithmetic */
2607 #define CRP 10 /* a right paren in arithmetic */
2608 #define CENDFILE 11 /* end of file */
2609 #define CCTL 12 /* like CWORD, except it must be escaped */
2610 #define CSPCL 13 /* these terminate a word */
2611 #define CIGN 14 /* character should be ignored */
2614 #if ENABLE_ASH_ALIAS
2618 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2620 #if ENABLE_SH_MATH_SUPPORT
2621 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2623 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2625 static const uint16_t S_I_T[] = {
2626 #if ENABLE_ASH_ALIAS
2627 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2629 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2630 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2631 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2632 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2633 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2634 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2635 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2636 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2637 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2638 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2639 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2640 #if !USE_SIT_FUNCTION
2641 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2642 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2643 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2647 /* Constants below must match table above */
2649 #if ENABLE_ASH_ALIAS
2650 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2652 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2653 CNL_CNL_CNL_CNL , /* 2 */
2654 CWORD_CCTL_CCTL_CWORD , /* 3 */
2655 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2656 CVAR_CVAR_CWORD_CVAR , /* 5 */
2657 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2658 CSPCL_CWORD_CWORD_CLP , /* 7 */
2659 CSPCL_CWORD_CWORD_CRP , /* 8 */
2660 CBACK_CBACK_CCTL_CBACK , /* 9 */
2661 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2662 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2663 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2664 CWORD_CWORD_CWORD_CWORD , /* 13 */
2665 CCTL_CCTL_CCTL_CCTL , /* 14 */
2668 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2669 * caller must ensure proper cast on it if c is *char_ptr!
2671 /* Values for syntax param */
2672 #define BASESYNTAX 0 /* not in quotes */
2673 #define DQSYNTAX 1 /* in double quotes */
2674 #define SQSYNTAX 2 /* in single quotes */
2675 #define ARISYNTAX 3 /* in arithmetic */
2676 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2678 #if USE_SIT_FUNCTION
2681 SIT(int c, int syntax)
2683 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2684 # if ENABLE_ASH_ALIAS
2685 static const uint8_t syntax_index_table[] ALIGN1 = {
2686 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2687 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2688 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2692 static const uint8_t syntax_index_table[] ALIGN1 = {
2693 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2694 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2695 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2704 # if ENABLE_ASH_ALIAS
2710 /* Cast is purely for paranoia here,
2711 * just in case someone passed signed char to us */
2712 if ((unsigned char)c >= CTL_FIRST
2713 && (unsigned char)c <= CTL_LAST
2717 s = strchrnul(spec_symbls, c);
2720 indx = syntax_index_table[s - spec_symbls];
2722 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2725 #else /* !USE_SIT_FUNCTION */
2727 static const uint8_t syntax_index_table[] = {
2728 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2729 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2738 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2739 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2740 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2760 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2761 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2762 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2763 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2764 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2765 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2766 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2767 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2768 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2769 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2770 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2771 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2772 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2773 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2774 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2775 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2776 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2777 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2778 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2779 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2780 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2781 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2782 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2783 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2784 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2785 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2786 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2787 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2788 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2789 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2790 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2791 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2792 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2793 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2794 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2795 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2796 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2797 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2800 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2802 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2803 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2814 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2815 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2816 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2817 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2819 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2820 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2821 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2822 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2823 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2824 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2825 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2826 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2848 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2849 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2850 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2851 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2852 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2853 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2854 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2855 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2856 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2857 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2859 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2860 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2861 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2862 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2863 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2864 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2865 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2866 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 162 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 163 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 164 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 165 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 166 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 167 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 168 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 169 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 170 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 171 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 172 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 173 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 174 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 175 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 176 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 177 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 178 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 179 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 180 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 181 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 182 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 183 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 184 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 185 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 186 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 187 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 188 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 189 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 190 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 191 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 192 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 193 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 194 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 195 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 196 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 197 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 198 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 199 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 200 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 201 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 202 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 203 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 204 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 205 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 206 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 207 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 208 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 209 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 210 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 211 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 212 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 213 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 214 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 215 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 216 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 217 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 218 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 219 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 220 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 221 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 222 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 223 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 224 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 225 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 226 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 227 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 228 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 229 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 231 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 232 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 233 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 234 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 235 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 236 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 237 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 238 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 239 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 241 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 242 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 243 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 244 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 245 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 246 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 247 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 248 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 249 */ CWORD_CWORD_CWORD_CWORD,
2979 /* 250 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 251 */ CWORD_CWORD_CWORD_CWORD,
2981 /* 252 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 253 */ CWORD_CWORD_CWORD_CWORD,
2983 /* 254 */ CWORD_CWORD_CWORD_CWORD,
2984 /* 255 */ CWORD_CWORD_CWORD_CWORD,
2985 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2986 # if ENABLE_ASH_ALIAS
2987 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
2991 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
2993 #endif /* !USE_SIT_FUNCTION */
2996 /* ============ Alias handling */
2998 #if ENABLE_ASH_ALIAS
3000 #define ALIASINUSE 1
3011 static struct alias **atab; // [ATABSIZE];
3012 #define INIT_G_alias() do { \
3013 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3017 static struct alias **
3018 __lookupalias(const char *name) {
3019 unsigned int hashval;
3026 ch = (unsigned char)*p;
3030 ch = (unsigned char)*++p;
3032 app = &atab[hashval % ATABSIZE];
3034 for (; *app; app = &(*app)->next) {
3035 if (strcmp(name, (*app)->name) == 0) {
3043 static struct alias *
3044 lookupalias(const char *name, int check)
3046 struct alias *ap = *__lookupalias(name);
3048 if (check && ap && (ap->flag & ALIASINUSE))
3053 static struct alias *
3054 freealias(struct alias *ap)
3058 if (ap->flag & ALIASINUSE) {
3059 ap->flag |= ALIASDEAD;
3071 setalias(const char *name, const char *val)
3073 struct alias *ap, **app;
3075 app = __lookupalias(name);
3079 if (!(ap->flag & ALIASINUSE)) {
3082 ap->val = ckstrdup(val);
3083 ap->flag &= ~ALIASDEAD;
3086 ap = ckzalloc(sizeof(struct alias));
3087 ap->name = ckstrdup(name);
3088 ap->val = ckstrdup(val);
3089 /*ap->flag = 0; - ckzalloc did it */
3090 /*ap->next = NULL;*/
3097 unalias(const char *name)
3101 app = __lookupalias(name);
3105 *app = freealias(*app);
3116 struct alias *ap, **app;
3120 for (i = 0; i < ATABSIZE; i++) {
3122 for (ap = *app; ap; ap = *app) {
3123 *app = freealias(*app);
3133 printalias(const struct alias *ap)
3135 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3139 * TODO - sort output
3141 static int FAST_FUNC
3142 aliascmd(int argc UNUSED_PARAM, char **argv)
3151 for (i = 0; i < ATABSIZE; i++) {
3152 for (ap = atab[i]; ap; ap = ap->next) {
3158 while ((n = *++argv) != NULL) {
3159 v = strchr(n+1, '=');
3160 if (v == NULL) { /* n+1: funny ksh stuff */
3161 ap = *__lookupalias(n);
3163 fprintf(stderr, "%s: %s not found\n", "alias", n);
3176 static int FAST_FUNC
3177 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3181 while ((i = nextopt("a")) != '\0') {
3187 for (i = 0; *argptr; argptr++) {
3188 if (unalias(*argptr)) {
3189 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3197 #endif /* ASH_ALIAS */
3200 /* ============ jobs.c */
3202 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3205 #define FORK_NOJOB 2
3207 /* mode flags for showjob(s) */
3208 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3209 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3210 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3213 * A job structure contains information about a job. A job is either a
3214 * single process or a set of processes contained in a pipeline. In the
3215 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3219 pid_t ps_pid; /* process id */
3220 int ps_status; /* last process status from wait() */
3221 char *ps_cmd; /* text of command being run */
3225 struct procstat ps0; /* status of process */
3226 struct procstat *ps; /* status or processes when more than one */
3228 int stopstatus; /* status of a stopped job */
3231 nprocs: 16, /* number of processes */
3233 #define JOBRUNNING 0 /* at least one proc running */
3234 #define JOBSTOPPED 1 /* all procs are stopped */
3235 #define JOBDONE 2 /* all procs are completed */
3237 sigint: 1, /* job was killed by SIGINT */
3238 jobctl: 1, /* job running under job control */
3240 waited: 1, /* true if this entry has been waited for */
3241 used: 1, /* true if this entry is in used */
3242 changed: 1; /* true if status has changed */
3243 struct job *prev_job; /* previous job */
3246 static struct job *makejob(/*union node *,*/ int);
3247 static int forkshell(struct job *, union node *, int);
3248 static int waitforjob(struct job *);
3251 enum { doing_jobctl = 0 };
3252 #define setjobctl(on) do {} while (0)
3254 static smallint doing_jobctl; //references:8
3255 static void setjobctl(int);
3262 ignoresig(int signo)
3264 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3265 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3266 /* No, need to do it */
3267 signal(signo, SIG_IGN);
3269 sigmode[signo - 1] = S_HARD_IGN;
3273 * Only one usage site - in setsignal()
3276 signal_handler(int signo)
3278 gotsig[signo - 1] = 1;
3280 if (signo == SIGINT && !trap[SIGINT]) {
3281 if (!suppress_int) {
3283 raise_interrupt(); /* does not return */
3287 pending_sig = signo;
3292 * Set the signal handler for the specified signal. The routine figures
3293 * out what it should be set to.
3296 setsignal(int signo)
3299 char cur_act, new_act;
3300 struct sigaction act;
3304 if (t != NULL) { /* trap for this sig is set */
3306 if (t[0] == '\0') /* trap is "": ignore this sig */
3310 if (rootshell && new_act == S_DFL) {
3313 if (iflag || minusc || sflag == 0)
3322 * "In all cases, bash ignores SIGQUIT. Non-builtin
3323 * commands run by bash have signal handlers
3324 * set to the values inherited by the shell
3325 * from its parent". */
3341 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3342 //whereas we have to restore it to what shell got on entry
3343 //from the parent. See comment above
3345 t = &sigmode[signo - 1];
3348 /* current setting is not yet known */
3349 if (sigaction(signo, NULL, &act)) {
3350 /* pretend it worked; maybe we should give a warning,
3351 * but other shells don't. We don't alter sigmode,
3352 * so we retry every time.
3353 * btw, in Linux it never fails. --vda */
3356 if (act.sa_handler == SIG_IGN) {
3357 cur_act = S_HARD_IGN;
3359 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3361 cur_act = S_IGN; /* don't hard ignore these */
3365 if (cur_act == S_HARD_IGN || cur_act == new_act)
3368 act.sa_handler = SIG_DFL;
3371 act.sa_handler = signal_handler;
3372 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3373 sigfillset(&act.sa_mask); /* ditto */
3376 act.sa_handler = SIG_IGN;
3379 sigaction_set(signo, &act);
3384 /* mode flags for set_curjob */
3385 #define CUR_DELETE 2
3386 #define CUR_RUNNING 1
3387 #define CUR_STOPPED 0
3389 /* mode flags for dowait */
3390 #define DOWAIT_NONBLOCK WNOHANG
3391 #define DOWAIT_BLOCK 0
3394 /* pgrp of shell on invocation */
3395 static int initialpgrp; //references:2
3396 static int ttyfd = -1; //5
3399 static struct job *jobtab; //5
3401 static unsigned njobs; //4
3403 static struct job *curjob; //lots
3404 /* number of presumed living untracked jobs */
3405 static int jobless; //4
3408 set_curjob(struct job *jp, unsigned mode)
3411 struct job **jpp, **curp;
3413 /* first remove from list */
3414 jpp = curp = &curjob;
3419 jpp = &jp1->prev_job;
3421 *jpp = jp1->prev_job;
3423 /* Then re-insert in correct position */
3431 /* job being deleted */
3434 /* newly created job or backgrounded job,
3435 put after all stopped jobs. */
3439 if (!jp1 || jp1->state != JOBSTOPPED)
3442 jpp = &jp1->prev_job;
3448 /* newly stopped job - becomes curjob */
3449 jp->prev_job = *jpp;
3457 jobno(const struct job *jp)
3459 return jp - jobtab + 1;
3464 * Convert a job name to a job structure.
3467 #define getjob(name, getctl) getjob(name)
3470 getjob(const char *name, int getctl)
3474 const char *err_msg = "%s: no such job";
3478 char *(*match)(const char *, const char *);
3493 if (c == '+' || c == '%') {
3495 err_msg = "No current job";
3501 err_msg = "No previous job";
3512 jp = jobtab + num - 1;
3527 if (match(jp->ps[0].ps_cmd, p)) {
3531 err_msg = "%s: ambiguous";
3541 err_msg = "job %s not created under job control";
3542 if (getctl && jp->jobctl == 0)
3547 ash_msg_and_raise_error(err_msg, name);
3551 * Mark a job structure as unused.
3554 freejob(struct job *jp)
3556 struct procstat *ps;
3560 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3561 if (ps->ps_cmd != nullstr)
3564 if (jp->ps != &jp->ps0)
3567 set_curjob(jp, CUR_DELETE);
3573 xtcsetpgrp(int fd, pid_t pgrp)
3575 if (tcsetpgrp(fd, pgrp))
3576 ash_msg_and_raise_error("can't set tty process group (%m)");
3580 * Turn job control on and off.
3582 * Note: This code assumes that the third arg to ioctl is a character
3583 * pointer, which is true on Berkeley systems but not System V. Since
3584 * System V doesn't have job control yet, this isn't a problem now.
3586 * Called with interrupts off.
3594 if (on == doing_jobctl || rootshell == 0)
3598 ofd = fd = open(_PATH_TTY, O_RDWR);
3600 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3601 * That sometimes helps to acquire controlling tty.
3602 * Obviously, a workaround for bugs when someone
3603 * failed to provide a controlling tty to bash! :) */
3609 fd = fcntl(fd, F_DUPFD, 10);
3614 /* fd is a tty at this point */
3615 close_on_exec_on(fd);
3616 do { /* while we are in the background */
3617 pgrp = tcgetpgrp(fd);
3620 ash_msg("can't access tty; job control turned off");
3624 if (pgrp == getpgrp())
3635 xtcsetpgrp(fd, pgrp);
3637 /* turning job control off */
3640 /* was xtcsetpgrp, but this can make exiting ash
3641 * loop forever if pty is already deleted */
3642 tcsetpgrp(fd, pgrp);
3656 static int FAST_FUNC
3657 killcmd(int argc, char **argv)
3660 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3662 if (argv[i][0] == '%') {
3663 struct job *jp = getjob(argv[i], 0);
3664 unsigned pid = jp->ps[0].ps_pid;
3665 /* Enough space for ' -NNN<nul>' */
3666 argv[i] = alloca(sizeof(int)*3 + 3);
3667 /* kill_main has matching code to expect
3668 * leading space. Needed to not confuse
3669 * negative pids with "kill -SIGNAL_NO" syntax */
3670 sprintf(argv[i], " -%u", pid);
3672 } while (argv[++i]);
3674 return kill_main(argc, argv);
3678 showpipe(struct job *jp /*, FILE *out*/)
3680 struct procstat *ps;
3681 struct procstat *psend;
3683 psend = jp->ps + jp->nprocs;
3684 for (ps = jp->ps + 1; ps < psend; ps++)
3685 printf(" | %s", ps->ps_cmd);
3686 outcslow('\n', stdout);
3687 flush_stdout_stderr();
3692 restartjob(struct job *jp, int mode)
3694 struct procstat *ps;
3700 if (jp->state == JOBDONE)
3702 jp->state = JOBRUNNING;
3703 pgid = jp->ps[0].ps_pid;
3704 if (mode == FORK_FG)
3705 xtcsetpgrp(ttyfd, pgid);
3706 killpg(pgid, SIGCONT);
3710 if (WIFSTOPPED(ps->ps_status)) {
3716 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3721 static int FAST_FUNC
3722 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3728 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3732 jp = getjob(*argv, 1);
3733 if (mode == FORK_BG) {
3734 set_curjob(jp, CUR_RUNNING);
3735 printf("[%d] ", jobno(jp));
3737 out1str(jp->ps[0].ps_cmd);
3738 showpipe(jp /*, stdout*/);
3739 retval = restartjob(jp, mode);
3740 } while (*argv && *++argv);
3746 sprint_status(char *s, int status, int sigonly)
3752 if (!WIFEXITED(status)) {
3754 if (WIFSTOPPED(status))
3755 st = WSTOPSIG(status);
3758 st = WTERMSIG(status);
3760 if (st == SIGINT || st == SIGPIPE)
3763 if (WIFSTOPPED(status))
3768 col = fmtstr(s, 32, strsignal(st));
3769 if (WCOREDUMP(status)) {
3770 col += fmtstr(s + col, 16, " (core dumped)");
3772 } else if (!sigonly) {
3773 st = WEXITSTATUS(status);
3775 col = fmtstr(s, 16, "Done(%d)", st);
3777 col = fmtstr(s, 16, "Done");
3784 dowait(int wait_flags, struct job *job)
3789 struct job *thisjob;
3792 TRACE(("dowait(0x%x) called\n", wait_flags));
3794 /* Do a wait system call. If job control is compiled in, we accept
3795 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3796 * NB: _not_ safe_waitpid, we need to detect EINTR */
3798 wait_flags |= WUNTRACED;
3799 pid = waitpid(-1, &status, wait_flags);
3800 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3801 pid, status, errno, strerror(errno)));
3807 for (jp = curjob; jp; jp = jp->prev_job) {
3808 struct procstat *ps;
3809 struct procstat *psend;
3810 if (jp->state == JOBDONE)
3814 psend = ps + jp->nprocs;
3816 if (ps->ps_pid == pid) {
3817 TRACE(("Job %d: changing status of proc %d "
3818 "from 0x%x to 0x%x\n",
3819 jobno(jp), pid, ps->ps_status, status));
3820 ps->ps_status = status;
3823 if (ps->ps_status == -1)
3826 if (state == JOBRUNNING)
3828 if (WIFSTOPPED(ps->ps_status)) {
3829 jp->stopstatus = ps->ps_status;
3833 } while (++ps < psend);
3838 if (!WIFSTOPPED(status))
3844 if (state != JOBRUNNING) {
3845 thisjob->changed = 1;
3847 if (thisjob->state != state) {
3848 TRACE(("Job %d: changing state from %d to %d\n",
3849 jobno(thisjob), thisjob->state, state));
3850 thisjob->state = state;
3852 if (state == JOBSTOPPED) {
3853 set_curjob(thisjob, CUR_STOPPED);
3862 if (thisjob && thisjob == job) {
3866 len = sprint_status(s, status, 1);
3877 blocking_wait_with_raise_on_sig(void)
3879 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
3880 if (pid <= 0 && pending_sig)
3881 raise_exception(EXSIG);
3887 showjob(FILE *out, struct job *jp, int mode)
3889 struct procstat *ps;
3890 struct procstat *psend;
3897 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
3898 /* just output process (group) id of pipeline */
3899 fprintf(out, "%d\n", ps->ps_pid);
3903 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3908 else if (curjob && jp == curjob->prev_job)
3911 if (mode & SHOW_PIDS)
3912 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
3914 psend = ps + jp->nprocs;
3916 if (jp->state == JOBRUNNING) {
3917 strcpy(s + col, "Running");
3918 col += sizeof("Running") - 1;
3920 int status = psend[-1].ps_status;
3921 if (jp->state == JOBSTOPPED)
3922 status = jp->stopstatus;
3923 col += sprint_status(s + col, status, 0);
3925 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
3927 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3928 * or prints several "PID | <cmdN>" lines,
3929 * depending on SHOW_PIDS bit.
3930 * We do not print status of individual processes
3931 * between PID and <cmdN>. bash does it, but not very well:
3932 * first line shows overall job status, not process status,
3933 * making it impossible to know 1st process status.
3937 /* for each process */
3940 if (mode & SHOW_PIDS)
3941 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
3943 fprintf(out, "%s%*c%s%s",
3945 33 - col >= 0 ? 33 - col : 0, ' ',
3946 ps == jp->ps ? "" : "| ",
3949 } while (++ps != psend);
3950 outcslow('\n', out);
3954 if (jp->state == JOBDONE) {
3955 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3961 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3962 * statuses have changed since the last call to showjobs.
3965 showjobs(FILE *out, int mode)
3969 TRACE(("showjobs(0x%x) called\n", mode));
3971 /* Handle all finished jobs */
3972 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
3975 for (jp = curjob; jp; jp = jp->prev_job) {
3976 if (!(mode & SHOW_CHANGED) || jp->changed) {
3977 showjob(out, jp, mode);
3982 static int FAST_FUNC
3983 jobscmd(int argc UNUSED_PARAM, char **argv)
3988 while ((m = nextopt("lp")) != '\0') {
3992 mode |= SHOW_ONLY_PGID;
3998 showjob(stdout, getjob(*argv, 0), mode);
4001 showjobs(stdout, mode);
4008 /* Called only on finished or stopped jobs (no members are running) */
4010 getstatus(struct job *job)
4014 struct procstat *ps;
4016 /* Fetch last member's status */
4017 ps = job->ps + job->nprocs - 1;
4018 status = ps->ps_status;
4020 /* "set -o pipefail" mode: use last _nonzero_ status */
4021 while (status == 0 && --ps >= job->ps)
4022 status = ps->ps_status;
4025 retval = WEXITSTATUS(status);
4026 if (!WIFEXITED(status)) {
4028 retval = WSTOPSIG(status);
4029 if (!WIFSTOPPED(status))
4032 /* XXX: limits number of signals */
4033 retval = WTERMSIG(status);
4035 if (retval == SIGINT)
4041 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4042 jobno(job), job->nprocs, status, retval));
4046 static int FAST_FUNC
4047 waitcmd(int argc UNUSED_PARAM, char **argv)
4054 raise_exception(EXSIG);
4061 /* wait for all jobs */
4065 if (!jp) /* no running procs */
4067 if (jp->state == JOBRUNNING)
4072 blocking_wait_with_raise_on_sig();
4074 * "When bash is waiting for an asynchronous command via
4075 * the wait builtin, the reception of a signal for which a trap
4076 * has been set will cause the wait builtin to return immediately
4077 * with an exit status greater than 128, immediately after which
4078 * the trap is executed."
4080 * blocking_wait_with_raise_on_sig raises signal handlers
4081 * if it gets no pid (pid < 0). However,
4082 * if child sends us a signal *and immediately exits*,
4083 * blocking_wait_with_raise_on_sig gets pid > 0
4084 * and does not handle pending_sig. Check this case: */
4086 raise_exception(EXSIG);
4092 if (**argv != '%') {
4093 pid_t pid = number(*argv);
4098 if (job->ps[job->nprocs - 1].ps_pid == pid)
4100 job = job->prev_job;
4103 job = getjob(*argv, 0);
4104 /* loop until process terminated or stopped */
4105 while (job->state == JOBRUNNING)
4106 blocking_wait_with_raise_on_sig();
4108 retval = getstatus(job);
4121 struct job *jp, *jq;
4123 len = njobs * sizeof(*jp);
4125 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4127 offset = (char *)jp - (char *)jq;
4129 /* Relocate pointers */
4132 jq = (struct job *)((char *)jq + l);
4136 #define joff(p) ((struct job *)((char *)(p) + l))
4137 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4138 if (joff(jp)->ps == &jq->ps0)
4139 jmove(joff(jp)->ps);
4140 if (joff(jp)->prev_job)
4141 jmove(joff(jp)->prev_job);
4151 jp = (struct job *)((char *)jp + len);
4155 } while (--jq >= jp);
4160 * Return a new job structure.
4161 * Called with interrupts off.
4164 makejob(/*union node *node,*/ int nprocs)
4169 for (i = njobs, jp = jobtab; ; jp++) {
4176 if (jp->state != JOBDONE || !jp->waited)
4185 memset(jp, 0, sizeof(*jp));
4187 /* jp->jobctl is a bitfield.
4188 * "jp->jobctl |= jobctl" likely to give awful code */
4192 jp->prev_job = curjob;
4197 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4199 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4206 * Return a string identifying a command (to be printed by the
4209 static char *cmdnextc;
4212 cmdputs(const char *s)
4214 static const char vstype[VSTYPE + 1][3] = {
4215 "", "}", "-", "+", "?", "=",
4216 "%", "%%", "#", "##"
4217 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4220 const char *p, *str;
4224 unsigned char subtype = 0;
4228 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4230 while ((c = *p++) != '\0') {
4238 if ((subtype & VSTYPE) == VSLENGTH)
4242 if (!(subtype & VSQUOTE) == !(quoted & 1))
4248 str = "\"}" + !(quoted & 1);
4255 case CTLBACKQ+CTLQUOTE:
4258 #if ENABLE_SH_MATH_SUPPORT
4273 if ((subtype & VSTYPE) != VSNORMAL)
4275 str = vstype[subtype & VSTYPE];
4276 if (subtype & VSNUL)
4285 /* These can only happen inside quotes */
4298 while ((c = *str++) != '\0') {
4301 } /* while *p++ not NUL */
4304 USTPUTC('"', nextc);
4310 /* cmdtxt() and cmdlist() call each other */
4311 static void cmdtxt(union node *n);
4314 cmdlist(union node *np, int sep)
4316 for (; np; np = np->narg.next) {
4320 if (sep && np->narg.next)
4326 cmdtxt(union node *n)
4329 struct nodelist *lp;
4340 lp = n->npipe.cmdlist;
4358 cmdtxt(n->nbinary.ch1);
4374 cmdtxt(n->nif.test);
4376 if (n->nif.elsepart) {
4377 cmdtxt(n->nif.ifpart);
4379 n = n->nif.elsepart;
4397 cmdtxt(n->nbinary.ch1);
4407 cmdputs(n->nfor.var);
4409 cmdlist(n->nfor.args, 1);
4414 cmdputs(n->narg.text);
4418 cmdlist(n->ncmd.args, 1);
4419 cmdlist(n->ncmd.redirect, 0);
4432 cmdputs(n->ncase.expr->narg.text);
4434 for (np = n->ncase.cases; np; np = np->nclist.next) {
4435 cmdtxt(np->nclist.pattern);
4437 cmdtxt(np->nclist.body);
4451 #if ENABLE_ASH_BASH_COMPAT
4466 cmdputs(utoa(n->nfile.fd));
4468 if (n->type == NTOFD || n->type == NFROMFD) {
4469 cmdputs(utoa(n->ndup.dupfd));
4478 commandtext(union node *n)
4482 STARTSTACKSTR(cmdnextc);
4484 name = stackblock();
4485 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4486 name, cmdnextc, cmdnextc));
4487 return ckstrdup(name);
4492 * Fork off a subshell. If we are doing job control, give the subshell its
4493 * own process group. Jp is a job structure that the job is to be added to.
4494 * N is the command that will be evaluated by the child. Both jp and n may
4495 * be NULL. The mode parameter can be one of the following:
4496 * FORK_FG - Fork off a foreground process.
4497 * FORK_BG - Fork off a background process.
4498 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4499 * process group even if job control is on.
4501 * When job control is turned off, background processes have their standard
4502 * input redirected to /dev/null (except for the second and later processes
4505 * Called with interrupts off.
4508 * Clear traps on a fork.
4515 for (tp = trap; tp < &trap[NSIG]; tp++) {
4516 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4518 if (trap_ptr == trap)
4520 /* else: it "belongs" to trap_ptr vector, don't free */
4522 if ((tp - trap) != 0)
4523 setsignal(tp - trap);
4529 /* Lives far away from here, needed for forkchild */
4530 static void closescript(void);
4532 /* Called after fork(), in child */
4533 static NOINLINE void
4534 forkchild(struct job *jp, union node *n, int mode)
4538 TRACE(("Child shell %d\n", getpid()));
4542 /* man bash: "Non-builtin commands run by bash have signal handlers
4543 * set to the values inherited by the shell from its parent".
4544 * Do we do it correctly? */
4548 if (mode == FORK_NOJOB /* is it `xxx` ? */
4549 && n && n->type == NCMD /* is it single cmd? */
4550 /* && n->ncmd.args->type == NARG - always true? */
4551 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4552 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4553 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4555 TRACE(("Trap hack\n"));
4556 /* Awful hack for `trap` or $(trap).
4558 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4559 * contains an example where "trap" is executed in a subshell:
4561 * save_traps=$(trap)
4563 * eval "$save_traps"
4565 * Standard does not say that "trap" in subshell shall print
4566 * parent shell's traps. It only says that its output
4567 * must have suitable form, but then, in the above example
4568 * (which is not supposed to be normative), it implies that.
4570 * bash (and probably other shell) does implement it
4571 * (traps are reset to defaults, but "trap" still shows them),
4572 * but as a result, "trap" logic is hopelessly messed up:
4575 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4576 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4577 * # true | trap <--- trap is in subshell - no output (ditto)
4578 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4579 * trap -- 'echo Ho' SIGWINCH
4580 * # echo `(trap)` <--- in subshell in subshell - output
4581 * trap -- 'echo Ho' SIGWINCH
4582 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4583 * trap -- 'echo Ho' SIGWINCH
4585 * The rules when to forget and when to not forget traps
4586 * get really complex and nonsensical.
4588 * Our solution: ONLY bare $(trap) or `trap` is special.
4590 /* Save trap handler strings for trap builtin to print */
4591 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4592 /* Fall through into clearing traps */
4596 /* do job control only in root shell */
4598 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4601 if (jp->nprocs == 0)
4604 pgrp = jp->ps[0].ps_pid;
4605 /* this can fail because we are doing it in the parent also */
4607 if (mode == FORK_FG)
4608 xtcsetpgrp(ttyfd, pgrp);
4613 if (mode == FORK_BG) {
4614 /* man bash: "When job control is not in effect,
4615 * asynchronous commands ignore SIGINT and SIGQUIT" */
4618 if (jp->nprocs == 0) {
4620 if (open(bb_dev_null, O_RDONLY) != 0)
4621 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4625 if (iflag) { /* why if iflag only? */
4630 * "In all cases, bash ignores SIGQUIT. Non-builtin
4631 * commands run by bash have signal handlers
4632 * set to the values inherited by the shell
4634 * Take care of the second rule: */
4638 if (n && n->type == NCMD
4639 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4641 TRACE(("Job hack\n"));
4642 /* "jobs": we do not want to clear job list for it,
4643 * instead we remove only _its_ own_ job from job list.
4644 * This makes "jobs .... | cat" more useful.
4650 for (jp = curjob; jp; jp = jp->prev_job)
4655 /* Called after fork(), in parent */
4657 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4660 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4662 TRACE(("In parent shell: child = %d\n", pid));
4664 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4670 if (mode != FORK_NOJOB && jp->jobctl) {
4673 if (jp->nprocs == 0)
4676 pgrp = jp->ps[0].ps_pid;
4677 /* This can fail because we are doing it in the child also */
4681 if (mode == FORK_BG) {
4682 backgndpid = pid; /* set $! */
4683 set_curjob(jp, CUR_RUNNING);
4686 struct procstat *ps = &jp->ps[jp->nprocs++];
4689 ps->ps_cmd = nullstr;
4691 if (doing_jobctl && n)
4692 ps->ps_cmd = commandtext(n);
4698 forkshell(struct job *jp, union node *n, int mode)
4702 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4705 TRACE(("Fork failed, errno=%d", errno));
4708 ash_msg_and_raise_error("can't fork");
4711 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4712 forkchild(jp, n, mode);
4714 forkparent(jp, n, mode, pid);
4720 * Wait for job to finish.
4722 * Under job control we have the problem that while a child process
4723 * is running interrupts generated by the user are sent to the child
4724 * but not to the shell. This means that an infinite loop started by
4725 * an interactive user may be hard to kill. With job control turned off,
4726 * an interactive user may place an interactive program inside a loop.
4727 * If the interactive program catches interrupts, the user doesn't want
4728 * these interrupts to also abort the loop. The approach we take here
4729 * is to have the shell ignore interrupt signals while waiting for a
4730 * foreground process to terminate, and then send itself an interrupt
4731 * signal if the child process was terminated by an interrupt signal.
4732 * Unfortunately, some programs want to do a bit of cleanup and then
4733 * exit on interrupt; unless these processes terminate themselves by
4734 * sending a signal to themselves (instead of calling exit) they will
4735 * confuse this approach.
4737 * Called with interrupts off.
4740 waitforjob(struct job *jp)
4744 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4747 while (jp->state == JOBRUNNING) {
4748 /* In non-interactive shells, we _can_ get
4749 * a keyboard signal here and be EINTRed,
4750 * but we just loop back, waiting for command to complete.
4753 * "If bash is waiting for a command to complete and receives
4754 * a signal for which a trap has been set, the trap
4755 * will not be executed until the command completes."
4757 * Reality is that even if trap is not set, bash
4758 * will not act on the signal until command completes.
4759 * Try this. sleep5intoff.c:
4760 * #include <signal.h>
4761 * #include <unistd.h>
4764 * sigemptyset(&set);
4765 * sigaddset(&set, SIGINT);
4766 * sigaddset(&set, SIGQUIT);
4767 * sigprocmask(SIG_BLOCK, &set, NULL);
4771 * $ bash -c './sleep5intoff; echo hi'
4772 * ^C^C^C^C <--- pressing ^C once a second
4774 * $ bash -c './sleep5intoff; echo hi'
4775 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4778 dowait(DOWAIT_BLOCK, jp);
4785 xtcsetpgrp(ttyfd, rootpid);
4787 * This is truly gross.
4788 * If we're doing job control, then we did a TIOCSPGRP which
4789 * caused us (the shell) to no longer be in the controlling
4790 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4791 * intuit from the subprocess exit status whether a SIGINT
4792 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4794 if (jp->sigint) /* TODO: do the same with all signals */
4795 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4797 if (jp->state == JOBDONE)
4804 * return 1 if there are stopped jobs, otherwise 0
4816 if (jp && jp->state == JOBSTOPPED) {
4817 out2str("You have stopped jobs.\n");
4826 /* ============ redir.c
4828 * Code for dealing with input/output redirection.
4831 #define EMPTY -2 /* marks an unused slot in redirtab */
4832 #define CLOSED -3 /* marks a slot of previously-closed fd */
4835 * Open a file in noclobber mode.
4836 * The code was copied from bash.
4839 noclobberopen(const char *fname)
4842 struct stat finfo, finfo2;
4845 * If the file exists and is a regular file, return an error
4848 r = stat(fname, &finfo);
4849 if (r == 0 && S_ISREG(finfo.st_mode)) {
4855 * If the file was not present (r != 0), make sure we open it
4856 * exclusively so that if it is created before we open it, our open
4857 * will fail. Make sure that we do not truncate an existing file.
4858 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4859 * file was not a regular file, we leave O_EXCL off.
4862 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4863 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4865 /* If the open failed, return the file descriptor right away. */
4870 * OK, the open succeeded, but the file may have been changed from a
4871 * non-regular file to a regular file between the stat and the open.
4872 * We are assuming that the O_EXCL open handles the case where FILENAME
4873 * did not exist and is symlinked to an existing file between the stat
4878 * If we can open it and fstat the file descriptor, and neither check
4879 * revealed that it was a regular file, and the file has not been
4880 * replaced, return the file descriptor.
4882 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4883 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4886 /* The file has been replaced. badness. */
4893 * Handle here documents. Normally we fork off a process to write the
4894 * data to a pipe. If the document is short, we can stuff the data in
4895 * the pipe without forking.
4897 /* openhere needs this forward reference */
4898 static void expandhere(union node *arg, int fd);
4900 openhere(union node *redir)
4906 ash_msg_and_raise_error("pipe call failed");
4907 if (redir->type == NHERE) {
4908 len = strlen(redir->nhere.doc->narg.text);
4909 if (len <= PIPE_BUF) {
4910 full_write(pip[1], redir->nhere.doc->narg.text, len);
4914 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4917 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4918 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4919 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4920 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4921 signal(SIGPIPE, SIG_DFL);
4922 if (redir->type == NHERE)
4923 full_write(pip[1], redir->nhere.doc->narg.text, len);
4925 expandhere(redir->nhere.doc, pip[1]);
4926 _exit(EXIT_SUCCESS);
4934 openredirect(union node *redir)
4939 switch (redir->nfile.type) {
4941 fname = redir->nfile.expfname;
4942 f = open(fname, O_RDONLY);
4947 fname = redir->nfile.expfname;
4948 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4953 #if ENABLE_ASH_BASH_COMPAT
4956 /* Take care of noclobber mode. */
4958 fname = redir->nfile.expfname;
4959 f = noclobberopen(fname);
4966 fname = redir->nfile.expfname;
4967 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4972 fname = redir->nfile.expfname;
4973 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4981 /* Fall through to eliminate warning. */
4982 /* Our single caller does this itself */
4989 f = openhere(redir);
4995 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4997 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5001 * Copy a file descriptor to be >= to. Returns -1
5002 * if the source file descriptor is closed, EMPTY if there are no unused
5003 * file descriptors left.
5005 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5006 * old code was doing close(to) prior to copyfd() to achieve the same */
5008 COPYFD_EXACT = (int)~(INT_MAX),
5009 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5012 copyfd(int from, int to)
5016 if (to & COPYFD_EXACT) {
5017 to &= ~COPYFD_EXACT;
5019 newfd = dup2(from, to);
5021 newfd = fcntl(from, F_DUPFD, to);
5024 if (errno == EMFILE)
5026 /* Happens when source fd is not open: try "echo >&99" */
5027 ash_msg_and_raise_error("%d: %m", from);
5032 /* Struct def and variable are moved down to the first usage site */
5037 struct redirtab *next;
5040 struct two_fd_t two_fd[];
5042 #define redirlist (G_var.redirlist)
5044 static int need_to_remember(struct redirtab *rp, int fd)
5048 if (!rp) /* remembering was not requested */
5051 for (i = 0; i < rp->pair_count; i++) {
5052 if (rp->two_fd[i].orig == fd) {
5053 /* already remembered */
5060 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5061 static int is_hidden_fd(struct redirtab *rp, int fd)
5064 struct parsefile *pf;
5077 fd |= COPYFD_RESTORE;
5078 for (i = 0; i < rp->pair_count; i++) {
5079 if (rp->two_fd[i].copy == fd) {
5087 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5088 * old file descriptors are stashed away so that the redirection can be
5089 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5090 * standard output, and the standard error if it becomes a duplicate of
5091 * stdout, is saved in memory.
5093 /* flags passed to redirect */
5094 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5095 #define REDIR_SAVEFD2 03 /* set preverrout */
5097 redirect(union node *redir, int flags)
5099 struct redirtab *sv;
5104 int copied_fd2 = -1;
5114 if (flags & REDIR_PUSH) {
5115 union node *tmp = redir;
5118 #if ENABLE_ASH_BASH_COMPAT
5119 if (tmp->nfile.type == NTO2)
5122 tmp = tmp->nfile.next;
5124 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5125 sv->next = redirlist;
5126 sv->pair_count = sv_pos;
5128 sv->nullredirs = g_nullredirs - 1;
5130 while (sv_pos > 0) {
5132 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5137 fd = redir->nfile.fd;
5138 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5139 int right_fd = redir->ndup.dupfd;
5140 /* redirect from/to same file descriptor? */
5143 /* echo >&10 and 10 is a fd opened to the sh script? */
5144 if (is_hidden_fd(sv, right_fd)) {
5145 errno = EBADF; /* as if it is closed */
5146 ash_msg_and_raise_error("%d: %m", right_fd);
5150 newfd = openredirect(redir); /* always >= 0 */
5152 /* Descriptor wasn't open before redirect.
5153 * Mark it for close in the future */
5154 if (need_to_remember(sv, fd)) {
5155 goto remember_to_close;
5160 #if ENABLE_ASH_BASH_COMPAT
5163 if (need_to_remember(sv, fd)) {
5164 /* Copy old descriptor */
5165 i = fcntl(fd, F_DUPFD, 10);
5166 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5167 * are closed in popredir() in the child, preventing them from leaking
5168 * into child. (popredir() also cleans up the mess in case of failures)
5173 /* Strange error (e.g. "too many files" EMFILE?) */
5177 ash_msg_and_raise_error("%d: %m", fd);
5180 /* EBADF: it is not open - good, remember to close it */
5183 } else { /* fd is open, save its copy */
5184 /* "exec fd>&-" should not close fds
5185 * which point to script file(s).
5186 * Force them to be restored afterwards */
5187 if (is_hidden_fd(sv, fd))
5188 i |= COPYFD_RESTORE;
5192 sv->two_fd[sv_pos].orig = fd;
5193 sv->two_fd[sv_pos].copy = i;
5197 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5198 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5199 /* Don't want to trigger debugging */
5203 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5205 } else if (fd != newfd) { /* move newfd to fd */
5206 copyfd(newfd, fd | COPYFD_EXACT);
5207 #if ENABLE_ASH_BASH_COMPAT
5208 if (!(redir->nfile.type == NTO2 && fd == 2))
5212 #if ENABLE_ASH_BASH_COMPAT
5213 if (redir->nfile.type == NTO2 && fd == 1) {
5214 /* We already redirected it to fd 1, now copy it to 2 */
5220 } while ((redir = redir->nfile.next) != NULL);
5223 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5224 preverrout_fd = copied_fd2;
5228 * Undo the effects of the last redirection.
5231 popredir(int drop, int restore)
5233 struct redirtab *rp;
5236 if (--g_nullredirs >= 0)
5240 for (i = 0; i < rp->pair_count; i++) {
5241 int fd = rp->two_fd[i].orig;
5242 int copy = rp->two_fd[i].copy;
5243 if (copy == CLOSED) {
5248 if (copy != EMPTY) {
5249 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5250 copy &= ~COPYFD_RESTORE;
5252 copyfd(copy, fd | COPYFD_EXACT);
5254 close(copy & ~COPYFD_RESTORE);
5257 redirlist = rp->next;
5258 g_nullredirs = rp->nullredirs;
5264 * Undo all redirections. Called on error or interrupt.
5268 * Discard all saved file descriptors.
5271 clearredir(int drop)
5277 popredir(drop, /*restore:*/ 0);
5282 redirectsafe(union node *redir, int flags)
5285 volatile int saveint;
5286 struct jmploc *volatile savehandler = exception_handler;
5287 struct jmploc jmploc;
5290 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5291 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5293 exception_handler = &jmploc;
5294 redirect(redir, flags);
5296 exception_handler = savehandler;
5297 if (err && exception_type != EXERROR)
5298 longjmp(exception_handler->loc, 1);
5299 RESTORE_INT(saveint);
5304 /* ============ Routines to expand arguments to commands
5306 * We have to deal with backquotes, shell variables, and file metacharacters.
5309 #if ENABLE_SH_MATH_SUPPORT
5311 ash_arith(const char *s)
5313 arith_eval_hooks_t math_hooks;
5317 math_hooks.lookupvar = lookupvar;
5318 math_hooks.setvar = setvar2;
5319 math_hooks.endofname = endofname;
5322 result = arith(s, &errcode, &math_hooks);
5325 ash_msg_and_raise_error("exponent less than 0");
5327 ash_msg_and_raise_error("divide by zero");
5329 ash_msg_and_raise_error("expression recursion loop detected");
5330 raise_error_syntax(s);
5341 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5342 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5343 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5344 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5345 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5346 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5347 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5348 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5349 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5353 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5354 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5355 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5356 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5357 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5360 * Structure specifying which parts of the string should be searched
5361 * for IFS characters.
5364 struct ifsregion *next; /* next region in list */
5365 int begoff; /* offset of start of region */
5366 int endoff; /* offset of end of region */
5367 int nulonly; /* search for nul bytes only */
5371 struct strlist *list;
5372 struct strlist **lastp;
5375 /* output of current string */
5376 static char *expdest;
5377 /* list of back quote expressions */
5378 static struct nodelist *argbackq;
5379 /* first struct in list of ifs regions */
5380 static struct ifsregion ifsfirst;
5381 /* last struct in list */
5382 static struct ifsregion *ifslastp;
5383 /* holds expanded arg list */
5384 static struct arglist exparg;
5394 expdest = makestrspace(32, expdest);
5395 len = fmtstr(expdest, 32, arith_t_fmt, num);
5396 STADJUST(len, expdest);
5401 esclen(const char *start, const char *p)
5405 while (p > start && (unsigned char)*--p == CTLESC) {
5412 * Remove any CTLESC characters from a string.
5415 rmescapes(char *str, int flag)
5417 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5421 unsigned protect_against_glob;
5424 p = strpbrk(str, qchars);
5430 if (flag & RMESCAPE_ALLOC) {
5431 size_t len = p - str;
5432 size_t fulllen = len + strlen(p) + 1;
5434 if (flag & RMESCAPE_GROW) {
5435 int strloc = str - (char *)stackblock();
5436 r = makestrspace(fulllen, expdest);
5437 /* p and str may be invalidated by makestrspace */
5438 str = (char *)stackblock() + strloc;
5440 } else if (flag & RMESCAPE_HEAP) {
5441 r = ckmalloc(fulllen);
5443 r = stalloc(fulllen);
5447 q = (char *)memcpy(q, str, len) + len;
5451 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5452 globbing = flag & RMESCAPE_GLOB;
5453 protect_against_glob = globbing;
5455 if ((unsigned char)*p == CTLQUOTEMARK) {
5456 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5457 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5458 // Note: both inquotes and protect_against_glob only affect whether
5459 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5460 inquotes = ~inquotes;
5462 protect_against_glob = globbing;
5466 /* naked back slash */
5467 protect_against_glob = 0;
5470 if ((unsigned char)*p == CTLESC) {
5472 if (protect_against_glob && inquotes && *p != '/') {
5476 protect_against_glob = globbing;
5481 if (flag & RMESCAPE_GROW) {
5483 STADJUST(q - r + 1, expdest);
5487 #define pmatch(a, b) !fnmatch((a), (b), 0)
5490 * Prepare a pattern for a expmeta (internal glob(3)) call.
5492 * Returns an stalloced string.
5495 preglob(const char *pattern, int quoted, int flag)
5497 flag |= RMESCAPE_GLOB;
5499 flag |= RMESCAPE_QUOTED;
5501 return rmescapes((char *)pattern, flag);
5505 * Put a string on the stack.
5508 memtodest(const char *p, size_t len, int syntax, int quotes)
5512 q = makestrspace(quotes ? len * 2 : len, q);
5515 unsigned char c = *p++;
5519 int n = SIT(c, syntax);
5520 if (n == CCTL || n == CBACK)
5530 strtodest(const char *p, int syntax, int quotes)
5532 memtodest(p, strlen(p), syntax, quotes);
5536 * Record the fact that we have to scan this region of the
5537 * string for IFS characters.
5540 recordregion(int start, int end, int nulonly)
5542 struct ifsregion *ifsp;
5544 if (ifslastp == NULL) {
5548 ifsp = ckzalloc(sizeof(*ifsp));
5549 /*ifsp->next = NULL; - ckzalloc did it */
5550 ifslastp->next = ifsp;
5554 ifslastp->begoff = start;
5555 ifslastp->endoff = end;
5556 ifslastp->nulonly = nulonly;
5560 removerecordregions(int endoff)
5562 if (ifslastp == NULL)
5565 if (ifsfirst.endoff > endoff) {
5566 while (ifsfirst.next != NULL) {
5567 struct ifsregion *ifsp;
5569 ifsp = ifsfirst.next->next;
5570 free(ifsfirst.next);
5571 ifsfirst.next = ifsp;
5574 if (ifsfirst.begoff > endoff)
5577 ifslastp = &ifsfirst;
5578 ifsfirst.endoff = endoff;
5583 ifslastp = &ifsfirst;
5584 while (ifslastp->next && ifslastp->next->begoff < endoff)
5585 ifslastp=ifslastp->next;
5586 while (ifslastp->next != NULL) {
5587 struct ifsregion *ifsp;
5589 ifsp = ifslastp->next->next;
5590 free(ifslastp->next);
5591 ifslastp->next = ifsp;
5594 if (ifslastp->endoff > endoff)
5595 ifslastp->endoff = endoff;
5599 exptilde(char *startp, char *p, int flags)
5605 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5610 while ((c = *++p) != '\0') {
5617 if (flags & EXP_VARTILDE)
5627 if (*name == '\0') {
5628 home = lookupvar(homestr);
5630 pw = getpwnam(name);
5635 if (!home || !*home)
5638 startloc = expdest - (char *)stackblock();
5639 strtodest(home, SQSYNTAX, quotes);
5640 recordregion(startloc, expdest - (char *)stackblock(), 0);
5648 * Execute a command inside back quotes. If it's a builtin command, we
5649 * want to save its output in a block obtained from malloc. Otherwise
5650 * we fork off a subprocess and get the output of the command via a pipe.
5651 * Should be called with interrupts off.
5653 struct backcmd { /* result of evalbackcmd */
5654 int fd; /* file descriptor to read from */
5655 int nleft; /* number of chars in buffer */
5656 char *buf; /* buffer */
5657 struct job *jp; /* job structure for command */
5660 /* These forward decls are needed to use "eval" code for backticks handling: */
5661 static uint8_t back_exitstatus; /* exit status of backquoted command */
5662 #define EV_EXIT 01 /* exit after evaluating tree */
5663 static void evaltree(union node *, int);
5665 static void FAST_FUNC
5666 evalbackcmd(union node *n, struct backcmd *result)
5677 saveherefd = herefd;
5685 ash_msg_and_raise_error("pipe call failed");
5686 jp = makejob(/*n,*/ 1);
5687 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5692 copyfd(pip[1], 1 | COPYFD_EXACT);
5696 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5700 result->fd = pip[0];
5703 herefd = saveherefd;
5705 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5706 result->fd, result->buf, result->nleft, result->jp));
5710 * Expand stuff in backwards quotes.
5713 expbackq(union node *cmd, int quoted, int quotes)
5721 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5722 struct stackmark smark;
5725 setstackmark(&smark);
5727 startloc = dest - (char *)stackblock();
5729 evalbackcmd(cmd, &in);
5730 popstackmark(&smark);
5737 memtodest(p, i, syntax, quotes);
5741 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5742 TRACE(("expbackq: read returns %d\n", i));
5751 back_exitstatus = waitforjob(in.jp);
5755 /* Eat all trailing newlines */
5757 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5762 recordregion(startloc, dest - (char *)stackblock(), 0);
5763 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5764 (dest - (char *)stackblock()) - startloc,
5765 (dest - (char *)stackblock()) - startloc,
5766 stackblock() + startloc));
5769 #if ENABLE_SH_MATH_SUPPORT
5771 * Expand arithmetic expression. Backup to start of expression,
5772 * evaluate, place result in (backed up) result, adjust string position.
5785 * This routine is slightly over-complicated for
5786 * efficiency. Next we scan backwards looking for the
5787 * start of arithmetic.
5789 start = stackblock();
5796 while ((unsigned char)*p != CTLARI) {
5800 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5805 esc = esclen(start, p);
5815 removerecordregions(begoff);
5822 rmescapes(p + 2, 0);
5824 len = cvtnum(ash_arith(p + 2));
5827 recordregion(begoff, begoff + len, 0);
5831 /* argstr needs it */
5832 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5835 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5836 * characters to allow for further processing. Otherwise treat
5837 * $@ like $* since no splitting will be performed.
5839 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5840 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5841 * for correct expansion of "B=$A" word.
5844 argstr(char *p, int flags, struct strlist *var_str_list)
5846 static const char spclchars[] ALIGN1 = {
5854 CTLBACKQ | CTLQUOTE,
5855 #if ENABLE_SH_MATH_SUPPORT
5860 const char *reject = spclchars;
5861 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5862 int breakall = flags & EXP_WORD;
5867 if (!(flags & EXP_VARTILDE)) {
5869 } else if (flags & EXP_VARTILDE2) {
5874 if (flags & EXP_TILDE) {
5877 flags &= ~EXP_TILDE;
5880 if (*q == CTLESC && (flags & EXP_QWORD))
5883 p = exptilde(p, q, flags);
5886 startloc = expdest - (char *)stackblock();
5890 length += strcspn(p + length, reject);
5894 #if ENABLE_SH_MATH_SUPPORT
5898 /* c == '=' || c == ':' || c == CTLENDARI */
5904 expdest = stack_nputstr(p, length, expdest);
5905 newloc = expdest - (char *)stackblock();
5906 if (breakall && !inquotes && newloc > startloc) {
5907 recordregion(startloc, newloc, 0);
5918 if (flags & EXP_VARTILDE2) {
5922 flags |= EXP_VARTILDE2;
5927 * sort of a hack - expand tildes in variable
5928 * assignments (after the first '=' and after ':'s).
5937 case CTLENDVAR: /* ??? */
5940 /* "$@" syntax adherence hack */
5942 && memcmp(p, dolatstr, 4) == 0
5943 && ( p[4] == CTLQUOTEMARK
5944 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5947 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
5950 inquotes = !inquotes;
5963 p = evalvar(p, flags, var_str_list);
5967 case CTLBACKQ|CTLQUOTE:
5968 expbackq(argbackq->n, c, quotes);
5969 argbackq = argbackq->next;
5971 #if ENABLE_SH_MATH_SUPPORT
5984 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
5987 // This commented out code was added by James Simmons <jsimmons@infradead.org>
5988 // as part of a larger change when he added support for ${var/a/b}.
5989 // However, it broke # and % operators:
5993 //echo ${var#ab} abcdcd abcdcd
5994 //echo ${var##ab} abcdcd abcdcd
5995 //echo ${var#a*b} abcdcd ababcdcd (!)
5996 //echo ${var##a*b} cdcd cdcd
5997 //echo ${var#?} babcdcd ababcdcd (!)
5998 //echo ${var##?} babcdcd babcdcd
5999 //echo ${var#*} ababcdcd babcdcd (!)
6001 //echo ${var%cd} ababcd ababcd
6002 //echo ${var%%cd} ababcd abab (!)
6003 //echo ${var%c*d} ababcd ababcd
6004 //echo ${var%%c*d} abab ababcdcd (!)
6005 //echo ${var%?} ababcdc ababcdc
6006 //echo ${var%%?} ababcdc ababcdcd (!)
6007 //echo ${var%*} ababcdcd ababcdcd
6010 // Commenting it back out helped. Remove it completely if it really
6013 char *loc, *loc2; //, *full;
6019 int match; // = strlen(str);
6020 const char *s = loc2;
6027 match = pmatch(str, s); // this line was deleted
6029 // // chop off end if its '*'
6030 // full = strrchr(str, '*');
6031 // if (full && full != str)
6034 // // If str starts with '*' replace with s.
6035 // if ((*str == '*') && strlen(s) >= match) {
6036 // full = xstrdup(s);
6037 // strncpy(full+strlen(s)-match+1, str+1, match-1);
6039 // full = xstrndup(str, match);
6040 // match = strncmp(s, full, strlen(full));
6044 if (match) // if (!match)
6046 if (quotes && (unsigned char)*loc == CTLESC)
6055 scanright(char *startp, char *rmesc, char *rmescend, char *pattern, int quotes, int match_at_start)
6057 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6058 int try2optimize = match_at_start;
6064 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6065 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6066 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6068 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6069 * and on each iteration they go back two/one char until they reach the beginning.
6070 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6072 /* TODO: document in what other circumstances we are called. */
6074 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6077 const char *s = loc2;
6078 if (match_at_start) {
6082 match = pmatch(pattern, s);
6083 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6087 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6089 /* Maybe we can optimize this:
6090 * if pattern ends with unescaped *, we can avoid checking
6091 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6092 * it wont match truncated "raw_value_of_" strings too.
6094 unsigned plen = strlen(pattern);
6095 /* Does it end with "*"? */
6096 if (plen != 0 && pattern[--plen] == '*') {
6097 /* "xxxx*" is not escaped */
6098 /* "xxx\*" is escaped */
6099 /* "xx\\*" is not escaped */
6100 /* "x\\\*" is escaped */
6102 while (plen != 0 && pattern[--plen] == '\\')
6105 break; /* ends with unescaped "*" */
6113 esc = esclen(startp, loc);
6124 static void varunset(const char *, const char *, const char *, int) NORETURN;
6126 varunset(const char *end, const char *var, const char *umsg, int varflags)
6132 msg = "parameter not set";
6134 if ((unsigned char)*end == CTLENDVAR) {
6135 if (varflags & VSNUL)
6141 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6144 #if ENABLE_ASH_BASH_COMPAT
6146 parse_sub_pattern(char *arg, int inquotes)
6148 char *idx, *repl = NULL;
6157 /* Only the first '/' seen is our separator */
6164 if (!inquotes && c == '\\' && arg[1] == '\\')
6165 arg++; /* skip both \\, not just first one */
6172 #endif /* ENABLE_ASH_BASH_COMPAT */
6175 subevalvar(char *p, char *str, int strloc, int subtype,
6176 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6178 struct nodelist *saveargbackq = argbackq;
6181 char *rmesc, *rmescend;
6182 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6183 IF_ASH_BASH_COMPAT(char null = '\0';)
6184 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6185 int saveherefd = herefd;
6186 int amount, workloc, resetloc;
6188 char *(*scan)(char*, char*, char*, char*, int, int);
6191 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6193 STPUTC('\0', expdest);
6194 herefd = saveherefd;
6195 argbackq = saveargbackq;
6196 startp = (char *)stackblock() + startloc;
6200 setvar(str, startp, 0);
6201 amount = startp - expdest;
6202 STADJUST(amount, expdest);
6205 #if ENABLE_ASH_BASH_COMPAT
6207 loc = str = stackblock() + strloc;
6208 /* Read POS in ${var:POS:LEN} */
6209 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6210 len = str - startp - 1;
6212 /* *loc != '\0', guaranteed by parser */
6216 /* Adjust the length by the number of escapes */
6217 for (ptr = startp; ptr < (str - 1); ptr++) {
6218 if ((unsigned char)*ptr == CTLESC) {
6226 if (*loc++ == ':') {
6230 /* Skip POS in ${var:POS:LEN} */
6232 while (*loc && *loc != ':') {
6234 * bash complains on: var=qwe; echo ${var:1a:123}
6236 ash_msg_and_raise_error(msg_illnum, str);
6240 if (*loc++ == ':') {
6244 if (pos >= orig_len) {
6248 if (len > (orig_len - pos))
6249 len = orig_len - pos;
6251 for (str = startp; pos; str++, pos--) {
6252 if (quotes && (unsigned char)*str == CTLESC)
6255 for (loc = startp; len; len--) {
6256 if (quotes && (unsigned char)*str == CTLESC)
6261 amount = loc - expdest;
6262 STADJUST(amount, expdest);
6267 varunset(p, str, startp, varflags);
6270 resetloc = expdest - (char *)stackblock();
6272 /* We'll comeback here if we grow the stack while handling
6273 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6274 * stack will need rebasing, and we'll need to remove our work
6277 IF_ASH_BASH_COMPAT(restart:)
6279 amount = expdest - ((char *)stackblock() + resetloc);
6280 STADJUST(-amount, expdest);
6281 startp = (char *)stackblock() + startloc;
6284 rmescend = (char *)stackblock() + strloc;
6286 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6287 if (rmesc != startp) {
6289 startp = (char *)stackblock() + startloc;
6293 str = (char *)stackblock() + strloc;
6294 preglob(str, varflags & VSQUOTE, 0);
6295 workloc = expdest - (char *)stackblock();
6297 #if ENABLE_ASH_BASH_COMPAT
6298 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6302 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6307 /* If there's no pattern to match, return the expansion unmolested */
6316 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6318 /* No match, advance */
6319 char *restart_detect = stackblock();
6321 STPUTC(*idx, expdest);
6322 if (quotes && (unsigned char)*idx == CTLESC) {
6325 STPUTC(*idx, expdest);
6327 if (stackblock() != restart_detect)
6332 /* continue; - prone to quadratic behavior, smarter code: */
6335 if (str[0] == '*') {
6336 /* Pattern is "*foo". If "*foo" does not match "long_string",
6337 * it would never match "ong_string" etc, no point in trying.
6344 if (subtype == VSREPLACEALL) {
6346 if (quotes && (unsigned char)*idx == CTLESC)
6355 for (loc = repl; *loc; loc++) {
6356 char *restart_detect = stackblock();
6357 STPUTC(*loc, expdest);
6358 if (stackblock() != restart_detect)
6363 if (subtype == VSREPLACE) {
6365 char *restart_detect = stackblock();
6366 STPUTC(*idx, expdest);
6367 if (stackblock() != restart_detect)
6376 /* We've put the replaced text into a buffer at workloc, now
6377 * move it to the right place and adjust the stack.
6379 startp = stackblock() + startloc;
6380 STPUTC('\0', expdest);
6381 memmove(startp, stackblock() + workloc, len);
6382 startp[len++] = '\0';
6383 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6384 STADJUST(-amount, expdest);
6387 #endif /* ENABLE_ASH_BASH_COMPAT */
6389 subtype -= VSTRIMRIGHT;
6391 if (subtype < 0 || subtype > 7)
6394 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6395 zero = subtype >> 1;
6396 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6397 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6399 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6402 memmove(startp, loc, str - loc);
6403 loc = startp + (str - loc) - 1;
6406 amount = loc - expdest;
6407 STADJUST(amount, expdest);
6413 * Add the value of a specialized variable to the stack string.
6414 * name parameter (examples):
6415 * ash -c 'echo $1' name:'1='
6416 * ash -c 'echo $qwe' name:'qwe='
6417 * ash -c 'echo $$' name:'$='
6418 * ash -c 'echo ${$}' name:'$='
6419 * ash -c 'echo ${$##q}' name:'$=q'
6420 * ash -c 'echo ${#$}' name:'$='
6421 * note: examples with bad shell syntax:
6422 * ash -c 'echo ${#$1}' name:'$=1'
6423 * ash -c 'echo ${#1#}' name:'1=#'
6425 static NOINLINE ssize_t
6426 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6433 int subtype = varflags & VSTYPE;
6434 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6435 int quoted = varflags & VSQUOTE;
6436 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6446 num = shellparam.nparam;
6454 goto check_1char_name;
6456 expdest = makestrspace(NOPTS, expdest);
6457 for (i = NOPTS - 1; i >= 0; i--) {
6459 USTPUTC(optletters(i), expdest);
6465 /* handles cases similar to ${#$1} */
6466 if (name[2] != '\0')
6467 raise_error_syntax("bad substitution");
6474 if (quoted && (flags & EXP_FULL)) {
6475 /* note: this is not meant as PEOF value */
6476 sep = 1 << CHAR_BIT;
6481 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6482 i = SIT(sep, syntax);
6483 if (quotes && (i == CCTL || i == CBACK))
6489 while ((p = *ap++) != NULL) {
6492 partlen = strlen(p);
6495 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6496 memtodest(p, partlen, syntax, quotes);
6502 if (subtype == VSPLUS || subtype == VSLENGTH) {
6508 /* note: may put NUL despite sep != 0
6509 * (see sep = 1 << CHAR_BIT above) */
6515 } /* case '@' and '*' */
6526 num = atoi(name); /* number(name) fails on ${N#str} etc */
6527 if (num < 0 || num > shellparam.nparam)
6529 p = num ? shellparam.p[num - 1] : arg0;
6532 /* NB: name has form "VAR=..." */
6534 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6535 * which should be considered before we check variables. */
6537 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6541 str = var_str_list->text;
6542 eq = strchr(str, '=');
6543 if (!eq) /* stop at first non-assignment */
6546 if (name_len == (unsigned)(eq - str)
6547 && strncmp(str, name, name_len) == 0
6550 /* goto value; - WRONG! */
6551 /* think "A=1 A=2 B=$A" */
6553 var_str_list = var_str_list->next;
6554 } while (var_str_list);
6558 p = lookupvar(name);
6564 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6565 memtodest(p, len, syntax, quotes);
6569 if (subtype == VSPLUS || subtype == VSLENGTH)
6570 STADJUST(-len, expdest);
6575 * Expand a variable, and return a pointer to the next character in the
6579 evalvar(char *p, int flags, struct strlist *var_str_list)
6590 varflags = (unsigned char) *p++;
6591 subtype = varflags & VSTYPE;
6592 quoted = varflags & VSQUOTE;
6594 easy = (!quoted || (*var == '@' && shellparam.nparam));
6595 startloc = expdest - (char *)stackblock();
6596 p = strchr(p, '=') + 1;
6599 varlen = varvalue(var, varflags, flags, var_str_list);
6600 if (varflags & VSNUL)
6603 if (subtype == VSPLUS) {
6604 varlen = -1 - varlen;
6608 if (subtype == VSMINUS) {
6612 p, flags | EXP_TILDE |
6613 (quoted ? EXP_QWORD : EXP_WORD),
6623 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6625 if (subevalvar(p, var, /* strloc: */ 0,
6626 subtype, startloc, varflags,
6632 * Remove any recorded regions beyond
6635 removerecordregions(startloc);
6645 if (varlen < 0 && uflag)
6646 varunset(p, var, 0, 0);
6648 if (subtype == VSLENGTH) {
6649 cvtnum(varlen > 0 ? varlen : 0);
6653 if (subtype == VSNORMAL) {
6664 case VSTRIMRIGHTMAX:
6665 #if ENABLE_ASH_BASH_COMPAT
6678 * Terminate the string and start recording the pattern
6681 STPUTC('\0', expdest);
6682 patloc = expdest - (char *)stackblock();
6683 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6685 //TODO: | EXP_REDIR too? All other such places do it too
6686 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6689 int amount = expdest - (
6690 (char *)stackblock() + patloc - 1
6692 STADJUST(-amount, expdest);
6694 /* Remove any recorded regions beyond start of variable */
6695 removerecordregions(startloc);
6697 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6701 if (subtype != VSNORMAL) { /* skip to end of alternative */
6704 unsigned char c = *p++;
6707 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6709 argbackq = argbackq->next;
6710 } else if (c == CTLVAR) {
6711 if ((*p++ & VSTYPE) != VSNORMAL)
6713 } else if (c == CTLENDVAR) {
6723 * Break the argument string into pieces based upon IFS and add the
6724 * strings to the argument list. The regions of the string to be
6725 * searched for IFS characters have been stored by recordregion.
6728 ifsbreakup(char *string, struct arglist *arglist)
6730 struct ifsregion *ifsp;
6735 const char *ifs, *realifs;
6740 if (ifslastp != NULL) {
6743 realifs = ifsset() ? ifsval() : defifs;
6746 p = string + ifsp->begoff;
6747 nulonly = ifsp->nulonly;
6748 ifs = nulonly ? nullstr : realifs;
6750 while (p < string + ifsp->endoff) {
6752 if ((unsigned char)*p == CTLESC)
6754 if (!strchr(ifs, *p)) {
6759 ifsspc = (strchr(defifs, *p) != NULL);
6760 /* Ignore IFS whitespace at start */
6761 if (q == start && ifsspc) {
6767 sp = stzalloc(sizeof(*sp));
6769 *arglist->lastp = sp;
6770 arglist->lastp = &sp->next;
6774 if (p >= string + ifsp->endoff) {
6778 if ((unsigned char)*p == CTLESC)
6780 if (strchr(ifs, *p) == NULL) {
6784 if (strchr(defifs, *p) == NULL) {
6799 } while (ifsp != NULL);
6808 sp = stzalloc(sizeof(*sp));
6810 *arglist->lastp = sp;
6811 arglist->lastp = &sp->next;
6817 struct ifsregion *p;
6822 struct ifsregion *ifsp;
6828 ifsfirst.next = NULL;
6833 * Add a file name to the list.
6836 addfname(const char *name)
6840 sp = stzalloc(sizeof(*sp));
6841 sp->text = ststrdup(name);
6843 exparg.lastp = &sp->next;
6846 static char *expdir;
6849 * Do metacharacter (i.e. *, ?, [...]) expansion.
6852 expmeta(char *enddir, char *name)
6867 for (p = name; *p; p++) {
6868 if (*p == '*' || *p == '?')
6870 else if (*p == '[') {
6877 if (*q == '/' || *q == '\0')
6884 } else if (*p == '\\')
6886 else if (*p == '/') {
6893 if (metaflag == 0) { /* we've reached the end of the file name */
6894 if (enddir != expdir)
6902 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6913 } while (p < start);
6915 if (enddir == expdir) {
6917 } else if (enddir == expdir + 1 && *expdir == '/') {
6926 if (enddir != expdir)
6928 if (*endname == 0) {
6940 while (!pending_int && (dp = readdir(dirp)) != NULL) {
6941 if (dp->d_name[0] == '.' && !matchdot)
6943 if (pmatch(start, dp->d_name)) {
6945 strcpy(enddir, dp->d_name);
6948 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6951 expmeta(p, endname);
6960 static struct strlist *
6961 msort(struct strlist *list, int len)
6963 struct strlist *p, *q = NULL;
6964 struct strlist **lpp;
6972 for (n = half; --n >= 0;) {
6976 q->next = NULL; /* terminate first half of list */
6977 q = msort(list, half); /* sort first half of list */
6978 p = msort(p, len - half); /* sort second half */
6981 #if ENABLE_LOCALE_SUPPORT
6982 if (strcoll(p->text, q->text) < 0)
6984 if (strcmp(p->text, q->text) < 0)
7008 * Sort the results of file name expansion. It calculates the number of
7009 * strings to sort and then calls msort (short for merge sort) to do the
7012 static struct strlist *
7013 expsort(struct strlist *str)
7019 for (sp = str; sp; sp = sp->next)
7021 return msort(str, len);
7025 expandmeta(struct strlist *str /*, int flag*/)
7027 static const char metachars[] ALIGN1 = {
7030 /* TODO - EXP_REDIR */
7033 struct strlist **savelastp;
7039 if (!strpbrk(str->text, metachars))
7041 savelastp = exparg.lastp;
7044 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7046 int i = strlen(str->text);
7047 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7055 if (exparg.lastp == savelastp) {
7060 *exparg.lastp = str;
7061 rmescapes(str->text, 0);
7062 exparg.lastp = &str->next;
7064 *exparg.lastp = NULL;
7065 *savelastp = sp = expsort(*savelastp);
7066 while (sp->next != NULL)
7068 exparg.lastp = &sp->next;
7075 * Perform variable substitution and command substitution on an argument,
7076 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7077 * perform splitting and file name expansion. When arglist is NULL, perform
7078 * here document expansion.
7081 expandarg(union node *arg, struct arglist *arglist, int flag)
7086 argbackq = arg->narg.backquote;
7087 STARTSTACKSTR(expdest);
7088 ifsfirst.next = NULL;
7090 argstr(arg->narg.text, flag,
7091 /* var_str_list: */ arglist ? arglist->list : NULL);
7092 p = _STPUTC('\0', expdest);
7094 if (arglist == NULL) {
7095 return; /* here document expanded */
7097 p = grabstackstr(p);
7098 exparg.lastp = &exparg.list;
7102 if (flag & EXP_FULL) {
7103 ifsbreakup(p, &exparg);
7104 *exparg.lastp = NULL;
7105 exparg.lastp = &exparg.list;
7106 expandmeta(exparg.list /*, flag*/);
7108 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7110 sp = stzalloc(sizeof(*sp));
7113 exparg.lastp = &sp->next;
7117 *exparg.lastp = NULL;
7119 *arglist->lastp = exparg.list;
7120 arglist->lastp = exparg.lastp;
7125 * Expand shell variables and backquotes inside a here document.
7128 expandhere(union node *arg, int fd)
7131 expandarg(arg, (struct arglist *)NULL, 0);
7132 full_write(fd, stackblock(), expdest - (char *)stackblock());
7136 * Returns true if the pattern matches the string.
7139 patmatch(char *pattern, const char *string)
7141 return pmatch(preglob(pattern, 0, 0), string);
7145 * See if a pattern matches in a case statement.
7148 casematch(union node *pattern, char *val)
7150 struct stackmark smark;
7153 setstackmark(&smark);
7154 argbackq = pattern->narg.backquote;
7155 STARTSTACKSTR(expdest);
7157 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7158 /* var_str_list: */ NULL);
7159 STACKSTRNUL(expdest);
7160 result = patmatch(stackblock(), val);
7161 popstackmark(&smark);
7166 /* ============ find_command */
7170 int (*builtin)(int, char **) FAST_FUNC;
7171 /* unsigned flags; */
7173 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7174 /* "regular" builtins always take precedence over commands,
7175 * regardless of PATH=....%builtin... position */
7176 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7177 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7180 smallint cmdtype; /* CMDxxx */
7183 /* index >= 0 for commands without path (slashes) */
7184 /* (TODO: what exactly does the value mean? PATH position?) */
7185 /* index == -1 for commands with slashes */
7186 /* index == (-2 - applet_no) for NOFORK applets */
7187 const struct builtincmd *cmd;
7188 struct funcnode *func;
7191 /* values of cmdtype */
7192 #define CMDUNKNOWN -1 /* no entry in table for command */
7193 #define CMDNORMAL 0 /* command is an executable program */
7194 #define CMDFUNCTION 1 /* command is a shell function */
7195 #define CMDBUILTIN 2 /* command is a shell builtin */
7197 /* action to find_command() */
7198 #define DO_ERR 0x01 /* prints errors */
7199 #define DO_ABS 0x02 /* checks absolute paths */
7200 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7201 #define DO_ALTPATH 0x08 /* using alternate path */
7202 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7204 static void find_command(char *, struct cmdentry *, int, const char *);
7207 /* ============ Hashing commands */
7210 * When commands are first encountered, they are entered in a hash table.
7211 * This ensures that a full path search will not have to be done for them
7212 * on each invocation.
7214 * We should investigate converting to a linear search, even though that
7215 * would make the command name "hash" a misnomer.
7219 struct tblentry *next; /* next entry in hash chain */
7220 union param param; /* definition of builtin function */
7221 smallint cmdtype; /* CMDxxx */
7222 char rehash; /* if set, cd done since entry created */
7223 char cmdname[1]; /* name of command */
7226 static struct tblentry **cmdtable;
7227 #define INIT_G_cmdtable() do { \
7228 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7231 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7235 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7239 #if ENABLE_FEATURE_SH_STANDALONE
7240 if (applet_no >= 0) {
7241 if (APPLET_IS_NOEXEC(applet_no)) {
7244 run_applet_no_and_exit(applet_no, argv);
7246 /* re-exec ourselves with the new arguments */
7247 execve(bb_busybox_exec_path, argv, envp);
7248 /* If they called chroot or otherwise made the binary no longer
7249 * executable, fall through */
7256 execve(cmd, argv, envp);
7257 } while (errno == EINTR);
7259 execve(cmd, argv, envp);
7265 if (errno == ENOEXEC) {
7269 for (ap = argv; *ap; ap++)
7271 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7273 ap[0] = cmd = (char *)DEFAULT_SHELL;
7276 while ((*ap++ = *argv++) != NULL)
7285 * Exec a program. Never returns. If you change this routine, you may
7286 * have to change the find_command routine as well.
7288 static void shellexec(char **, const char *, int) NORETURN;
7290 shellexec(char **argv, const char *path, int idx)
7296 #if ENABLE_FEATURE_SH_STANDALONE
7300 clearredir(/*drop:*/ 1);
7301 envp = listvars(VEXPORT, VUNSET, 0);
7302 if (strchr(argv[0], '/') != NULL
7303 #if ENABLE_FEATURE_SH_STANDALONE
7304 || (applet_no = find_applet_by_name(argv[0])) >= 0
7307 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7311 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7312 if (--idx < 0 && pathopt == NULL) {
7313 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7314 if (errno != ENOENT && errno != ENOTDIR)
7321 /* Map to POSIX errors */
7333 exitstatus = exerrno;
7334 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7335 argv[0], e, suppress_int));
7336 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7341 printentry(struct tblentry *cmdp)
7347 idx = cmdp->param.index;
7350 name = path_advance(&path, cmdp->cmdname);
7352 } while (--idx >= 0);
7353 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7357 * Clear out command entries. The argument specifies the first entry in
7358 * PATH which has changed.
7361 clearcmdentry(int firstchange)
7363 struct tblentry **tblp;
7364 struct tblentry **pp;
7365 struct tblentry *cmdp;
7368 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7370 while ((cmdp = *pp) != NULL) {
7371 if ((cmdp->cmdtype == CMDNORMAL &&
7372 cmdp->param.index >= firstchange)
7373 || (cmdp->cmdtype == CMDBUILTIN &&
7374 builtinloc >= firstchange)
7387 * Locate a command in the command hash table. If "add" is nonzero,
7388 * add the command to the table if it is not already present. The
7389 * variable "lastcmdentry" is set to point to the address of the link
7390 * pointing to the entry, so that delete_cmd_entry can delete the
7393 * Interrupts must be off if called with add != 0.
7395 static struct tblentry **lastcmdentry;
7397 static struct tblentry *
7398 cmdlookup(const char *name, int add)
7400 unsigned int hashval;
7402 struct tblentry *cmdp;
7403 struct tblentry **pp;
7406 hashval = (unsigned char)*p << 4;
7408 hashval += (unsigned char)*p++;
7410 pp = &cmdtable[hashval % CMDTABLESIZE];
7411 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7412 if (strcmp(cmdp->cmdname, name) == 0)
7416 if (add && cmdp == NULL) {
7417 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7419 /* + 1 - already done because
7420 * tblentry::cmdname is char[1] */);
7421 /*cmdp->next = NULL; - ckzalloc did it */
7422 cmdp->cmdtype = CMDUNKNOWN;
7423 strcpy(cmdp->cmdname, name);
7430 * Delete the command entry returned on the last lookup.
7433 delete_cmd_entry(void)
7435 struct tblentry *cmdp;
7438 cmdp = *lastcmdentry;
7439 *lastcmdentry = cmdp->next;
7440 if (cmdp->cmdtype == CMDFUNCTION)
7441 freefunc(cmdp->param.func);
7447 * Add a new command entry, replacing any existing command entry for
7448 * the same name - except special builtins.
7451 addcmdentry(char *name, struct cmdentry *entry)
7453 struct tblentry *cmdp;
7455 cmdp = cmdlookup(name, 1);
7456 if (cmdp->cmdtype == CMDFUNCTION) {
7457 freefunc(cmdp->param.func);
7459 cmdp->cmdtype = entry->cmdtype;
7460 cmdp->param = entry->u;
7464 static int FAST_FUNC
7465 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7467 struct tblentry **pp;
7468 struct tblentry *cmdp;
7470 struct cmdentry entry;
7473 if (nextopt("r") != '\0') {
7478 if (*argptr == NULL) {
7479 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7480 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7481 if (cmdp->cmdtype == CMDNORMAL)
7489 while ((name = *argptr) != NULL) {
7490 cmdp = cmdlookup(name, 0);
7492 && (cmdp->cmdtype == CMDNORMAL
7493 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7497 find_command(name, &entry, DO_ERR, pathval());
7498 if (entry.cmdtype == CMDUNKNOWN)
7506 * Called when a cd is done. Marks all commands so the next time they
7507 * are executed they will be rehashed.
7512 struct tblentry **pp;
7513 struct tblentry *cmdp;
7515 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7516 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7517 if (cmdp->cmdtype == CMDNORMAL
7518 || (cmdp->cmdtype == CMDBUILTIN
7519 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7529 * Fix command hash table when PATH changed.
7530 * Called before PATH is changed. The argument is the new value of PATH;
7531 * pathval() still returns the old value at this point.
7532 * Called with interrupts off.
7534 static void FAST_FUNC
7535 changepath(const char *new)
7543 firstchange = 9999; /* assume no change */
7549 if ((*old == '\0' && *new == ':')
7550 || (*old == ':' && *new == '\0')
7554 old = new; /* ignore subsequent differences */
7558 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7565 if (builtinloc < 0 && idx_bltin >= 0)
7566 builtinloc = idx_bltin; /* zap builtins */
7567 if (builtinloc >= 0 && idx_bltin < 0)
7569 clearcmdentry(firstchange);
7570 builtinloc = idx_bltin;
7585 #define TENDBQUOTE 12
7602 typedef smallint token_id_t;
7604 /* first char is indicating which tokens mark the end of a list */
7605 static const char *const tokname_array[] = {
7619 #define KWDOFFSET 13
7620 /* the following are keywords */
7639 /* Wrapper around strcmp for qsort/bsearch/... */
7641 pstrcmp(const void *a, const void *b)
7643 return strcmp((char*) a, (*(char**) b) + 1);
7646 static const char *const *
7647 findkwd(const char *s)
7649 return bsearch(s, tokname_array + KWDOFFSET,
7650 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7651 sizeof(tokname_array[0]), pstrcmp);
7655 * Locate and print what a word is...
7658 describe_command(char *command, int describe_command_verbose)
7660 struct cmdentry entry;
7661 struct tblentry *cmdp;
7662 #if ENABLE_ASH_ALIAS
7663 const struct alias *ap;
7665 const char *path = pathval();
7667 if (describe_command_verbose) {
7671 /* First look at the keywords */
7672 if (findkwd(command)) {
7673 out1str(describe_command_verbose ? " is a shell keyword" : command);
7677 #if ENABLE_ASH_ALIAS
7678 /* Then look at the aliases */
7679 ap = lookupalias(command, 0);
7681 if (!describe_command_verbose) {
7686 out1fmt(" is an alias for %s", ap->val);
7690 /* Then check if it is a tracked alias */
7691 cmdp = cmdlookup(command, 0);
7693 entry.cmdtype = cmdp->cmdtype;
7694 entry.u = cmdp->param;
7696 /* Finally use brute force */
7697 find_command(command, &entry, DO_ABS, path);
7700 switch (entry.cmdtype) {
7702 int j = entry.u.index;
7708 p = path_advance(&path, command);
7712 if (describe_command_verbose) {
7714 (cmdp ? " a tracked alias for" : nullstr), p
7723 if (describe_command_verbose) {
7724 out1str(" is a shell function");
7731 if (describe_command_verbose) {
7732 out1fmt(" is a %sshell builtin",
7733 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7734 "special " : nullstr
7742 if (describe_command_verbose) {
7743 out1str(": not found\n");
7752 static int FAST_FUNC
7753 typecmd(int argc UNUSED_PARAM, char **argv)
7759 /* type -p ... ? (we don't bother checking for 'p') */
7760 if (argv[1] && argv[1][0] == '-') {
7765 err |= describe_command(argv[i++], verbose);
7770 #if ENABLE_ASH_CMDCMD
7771 static int FAST_FUNC
7772 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7780 while ((c = nextopt("pvV")) != '\0')
7782 verify |= VERIFY_VERBOSE;
7784 verify |= VERIFY_BRIEF;
7789 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7790 if (verify && (*argptr != NULL)) {
7791 return describe_command(*argptr, verify - VERIFY_BRIEF);
7799 /* ============ eval.c */
7801 static int funcblocksize; /* size of structures in function */
7802 static int funcstringsize; /* size of strings in node */
7803 static void *funcblock; /* block to allocate function from */
7804 static char *funcstring; /* block to allocate strings from */
7806 /* flags in argument to evaltree */
7807 #define EV_EXIT 01 /* exit after evaluating tree */
7808 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7809 #define EV_BACKCMD 04 /* command executing within back quotes */
7811 static const uint8_t nodesize[N_NUMBER] = {
7812 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7813 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7814 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7815 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7816 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7817 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7818 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7819 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7820 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7821 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7822 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7823 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7824 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7825 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7826 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7827 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7828 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7829 #if ENABLE_ASH_BASH_COMPAT
7830 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7832 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7833 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7834 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7835 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7836 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7837 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7838 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7839 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7840 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7843 static void calcsize(union node *n);
7846 sizenodelist(struct nodelist *lp)
7849 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7856 calcsize(union node *n)
7860 funcblocksize += nodesize[n->type];
7863 calcsize(n->ncmd.redirect);
7864 calcsize(n->ncmd.args);
7865 calcsize(n->ncmd.assign);
7868 sizenodelist(n->npipe.cmdlist);
7873 calcsize(n->nredir.redirect);
7874 calcsize(n->nredir.n);
7881 calcsize(n->nbinary.ch2);
7882 calcsize(n->nbinary.ch1);
7885 calcsize(n->nif.elsepart);
7886 calcsize(n->nif.ifpart);
7887 calcsize(n->nif.test);
7890 funcstringsize += strlen(n->nfor.var) + 1;
7891 calcsize(n->nfor.body);
7892 calcsize(n->nfor.args);
7895 calcsize(n->ncase.cases);
7896 calcsize(n->ncase.expr);
7899 calcsize(n->nclist.body);
7900 calcsize(n->nclist.pattern);
7901 calcsize(n->nclist.next);
7905 sizenodelist(n->narg.backquote);
7906 funcstringsize += strlen(n->narg.text) + 1;
7907 calcsize(n->narg.next);
7910 #if ENABLE_ASH_BASH_COMPAT
7917 calcsize(n->nfile.fname);
7918 calcsize(n->nfile.next);
7922 calcsize(n->ndup.vname);
7923 calcsize(n->ndup.next);
7927 calcsize(n->nhere.doc);
7928 calcsize(n->nhere.next);
7931 calcsize(n->nnot.com);
7937 nodeckstrdup(char *s)
7939 char *rtn = funcstring;
7941 strcpy(funcstring, s);
7942 funcstring += strlen(s) + 1;
7946 static union node *copynode(union node *);
7948 static struct nodelist *
7949 copynodelist(struct nodelist *lp)
7951 struct nodelist *start;
7952 struct nodelist **lpp;
7957 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7958 (*lpp)->n = copynode(lp->n);
7960 lpp = &(*lpp)->next;
7967 copynode(union node *n)
7974 funcblock = (char *) funcblock + nodesize[n->type];
7978 new->ncmd.redirect = copynode(n->ncmd.redirect);
7979 new->ncmd.args = copynode(n->ncmd.args);
7980 new->ncmd.assign = copynode(n->ncmd.assign);
7983 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7984 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
7989 new->nredir.redirect = copynode(n->nredir.redirect);
7990 new->nredir.n = copynode(n->nredir.n);
7997 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7998 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8001 new->nif.elsepart = copynode(n->nif.elsepart);
8002 new->nif.ifpart = copynode(n->nif.ifpart);
8003 new->nif.test = copynode(n->nif.test);
8006 new->nfor.var = nodeckstrdup(n->nfor.var);
8007 new->nfor.body = copynode(n->nfor.body);
8008 new->nfor.args = copynode(n->nfor.args);
8011 new->ncase.cases = copynode(n->ncase.cases);
8012 new->ncase.expr = copynode(n->ncase.expr);
8015 new->nclist.body = copynode(n->nclist.body);
8016 new->nclist.pattern = copynode(n->nclist.pattern);
8017 new->nclist.next = copynode(n->nclist.next);
8021 new->narg.backquote = copynodelist(n->narg.backquote);
8022 new->narg.text = nodeckstrdup(n->narg.text);
8023 new->narg.next = copynode(n->narg.next);
8026 #if ENABLE_ASH_BASH_COMPAT
8033 new->nfile.fname = copynode(n->nfile.fname);
8034 new->nfile.fd = n->nfile.fd;
8035 new->nfile.next = copynode(n->nfile.next);
8039 new->ndup.vname = copynode(n->ndup.vname);
8040 new->ndup.dupfd = n->ndup.dupfd;
8041 new->ndup.fd = n->ndup.fd;
8042 new->ndup.next = copynode(n->ndup.next);
8046 new->nhere.doc = copynode(n->nhere.doc);
8047 new->nhere.fd = n->nhere.fd;
8048 new->nhere.next = copynode(n->nhere.next);
8051 new->nnot.com = copynode(n->nnot.com);
8054 new->type = n->type;
8059 * Make a copy of a parse tree.
8061 static struct funcnode *
8062 copyfunc(union node *n)
8067 funcblocksize = offsetof(struct funcnode, n);
8070 blocksize = funcblocksize;
8071 f = ckmalloc(blocksize + funcstringsize);
8072 funcblock = (char *) f + offsetof(struct funcnode, n);
8073 funcstring = (char *) f + blocksize;
8080 * Define a shell function.
8083 defun(char *name, union node *func)
8085 struct cmdentry entry;
8088 entry.cmdtype = CMDFUNCTION;
8089 entry.u.func = copyfunc(func);
8090 addcmdentry(name, &entry);
8094 /* Reasons for skipping commands (see comment on breakcmd routine) */
8095 #define SKIPBREAK (1 << 0)
8096 #define SKIPCONT (1 << 1)
8097 #define SKIPFUNC (1 << 2)
8098 #define SKIPFILE (1 << 3)
8099 #define SKIPEVAL (1 << 4)
8100 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8101 static int skipcount; /* number of levels to skip */
8102 static int funcnest; /* depth of function calls */
8103 static int loopnest; /* current loop nesting level */
8105 /* Forward decl way out to parsing code - dotrap needs it */
8106 static int evalstring(char *s, int mask);
8108 /* Called to execute a trap.
8109 * Single callsite - at the end of evaltree().
8110 * If we return non-zero, exaltree raises EXEXIT exception.
8112 * Perhaps we should avoid entering new trap handlers
8113 * while we are executing a trap handler. [is it a TODO?]
8122 savestatus = exitstatus;
8126 TRACE(("dotrap entered\n"));
8127 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8134 /* non-trapped SIGINT is handled separately by raise_interrupt,
8135 * don't upset it by resetting gotsig[SIGINT-1] */
8136 if (sig == SIGINT && !t)
8139 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8143 want_exexit = evalstring(t, SKIPEVAL);
8144 exitstatus = savestatus;
8146 TRACE(("dotrap returns %d\n", want_exexit));
8151 TRACE(("dotrap returns 0\n"));
8155 /* forward declarations - evaluation is fairly recursive business... */
8156 static void evalloop(union node *, int);
8157 static void evalfor(union node *, int);
8158 static void evalcase(union node *, int);
8159 static void evalsubshell(union node *, int);
8160 static void expredir(union node *);
8161 static void evalpipe(union node *, int);
8162 static void evalcommand(union node *, int);
8163 static int evalbltin(const struct builtincmd *, int, char **);
8164 static void prehash(union node *);
8167 * Evaluate a parse tree. The value is left in the global variable
8171 evaltree(union node *n, int flags)
8173 struct jmploc *volatile savehandler = exception_handler;
8174 struct jmploc jmploc;
8176 void (*evalfn)(union node *, int);
8180 SAVE_INT(int_level);
8183 TRACE(("evaltree(NULL) called\n"));
8186 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8188 exception_handler = &jmploc;
8190 int err = setjmp(jmploc.loc);
8192 /* if it was a signal, check for trap handlers */
8193 if (exception_type == EXSIG) {
8194 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8195 exception_type, err));
8198 /* continue on the way out */
8199 TRACE(("exception %d in evaltree, propagating err=%d\n",
8200 exception_type, err));
8201 exception_handler = savehandler;
8202 longjmp(exception_handler->loc, err);
8209 out1fmt("Node type = %d\n", n->type);
8214 evaltree(n->nnot.com, EV_TESTED);
8215 status = !exitstatus;
8218 expredir(n->nredir.redirect);
8219 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8221 evaltree(n->nredir.n, flags & EV_TESTED);
8222 status = exitstatus;
8224 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8227 evalfn = evalcommand;
8229 if (eflag && !(flags & EV_TESTED))
8241 evalfn = evalsubshell;
8254 #error NAND + 1 != NOR
8256 #if NOR + 1 != NSEMI
8257 #error NOR + 1 != NSEMI
8259 unsigned is_or = n->type - NAND;
8262 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8264 if (!exitstatus == is_or)
8277 evaltree(n->nif.test, EV_TESTED);
8280 if (exitstatus == 0) {
8284 if (n->nif.elsepart) {
8285 n = n->nif.elsepart;
8290 defun(n->narg.text, n->narg.next);
8294 exitstatus = status;
8299 exception_handler = savehandler;
8301 if (checkexit & exitstatus)
8302 evalskip |= SKIPEVAL;
8303 else if (pending_sig && dotrap())
8306 if (flags & EV_EXIT) {
8308 raise_exception(EXEXIT);
8311 RESTORE_INT(int_level);
8312 TRACE(("leaving evaltree (no interrupts)\n"));
8315 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8318 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8321 evalloop(union node *n, int flags)
8331 evaltree(n->nbinary.ch1, EV_TESTED);
8334 if (evalskip == SKIPCONT && --skipcount <= 0) {
8338 if (evalskip == SKIPBREAK && --skipcount <= 0)
8343 if (n->type != NWHILE)
8347 evaltree(n->nbinary.ch2, flags);
8348 status = exitstatus;
8353 exitstatus = status;
8357 evalfor(union node *n, int flags)
8359 struct arglist arglist;
8362 struct stackmark smark;
8364 setstackmark(&smark);
8365 arglist.list = NULL;
8366 arglist.lastp = &arglist.list;
8367 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8368 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8373 *arglist.lastp = NULL;
8378 for (sp = arglist.list; sp; sp = sp->next) {
8379 setvar(n->nfor.var, sp->text, 0);
8380 evaltree(n->nfor.body, flags);
8382 if (evalskip == SKIPCONT && --skipcount <= 0) {
8386 if (evalskip == SKIPBREAK && --skipcount <= 0)
8393 popstackmark(&smark);
8397 evalcase(union node *n, int flags)
8401 struct arglist arglist;
8402 struct stackmark smark;
8404 setstackmark(&smark);
8405 arglist.list = NULL;
8406 arglist.lastp = &arglist.list;
8407 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8409 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8410 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8411 if (casematch(patp, arglist.list->text)) {
8412 if (evalskip == 0) {
8413 evaltree(cp->nclist.body, flags);
8420 popstackmark(&smark);
8424 * Kick off a subshell to evaluate a tree.
8427 evalsubshell(union node *n, int flags)
8430 int backgnd = (n->type == NBACKGND);
8433 expredir(n->nredir.redirect);
8434 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8437 jp = makejob(/*n,*/ 1);
8438 if (forkshell(jp, n, backgnd) == 0) {
8443 flags &= ~EV_TESTED;
8445 redirect(n->nredir.redirect, 0);
8446 evaltreenr(n->nredir.n, flags);
8451 status = waitforjob(jp);
8452 exitstatus = status;
8457 * Compute the names of the files in a redirection list.
8459 static void fixredir(union node *, const char *, int);
8461 expredir(union node *n)
8465 for (redir = n; redir; redir = redir->nfile.next) {
8469 fn.lastp = &fn.list;
8470 switch (redir->type) {
8474 #if ENABLE_ASH_BASH_COMPAT
8479 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8480 #if ENABLE_ASH_BASH_COMPAT
8483 redir->nfile.expfname = fn.list->text;
8486 case NTOFD: /* >& */
8487 if (redir->ndup.vname) {
8488 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8489 if (fn.list == NULL)
8490 ash_msg_and_raise_error("redir error");
8491 #if ENABLE_ASH_BASH_COMPAT
8492 //FIXME: we used expandarg with different args!
8493 if (!isdigit_str9(fn.list->text)) {
8494 /* >&file, not >&fd */
8495 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8496 ash_msg_and_raise_error("redir error");
8498 goto store_expfname;
8501 fixredir(redir, fn.list->text, 1);
8509 * Evaluate a pipeline. All the processes in the pipeline are children
8510 * of the process creating the pipeline. (This differs from some versions
8511 * of the shell, which make the last process in a pipeline the parent
8515 evalpipe(union node *n, int flags)
8518 struct nodelist *lp;
8523 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8525 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8529 jp = makejob(/*n,*/ pipelen);
8531 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8535 if (pipe(pip) < 0) {
8537 ash_msg_and_raise_error("pipe call failed");
8540 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8553 evaltreenr(lp->n, flags);
8559 /* Don't want to trigger debugging */
8563 if (n->npipe.pipe_backgnd == 0) {
8564 exitstatus = waitforjob(jp);
8565 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8571 * Controls whether the shell is interactive or not.
8574 setinteractive(int on)
8576 static smallint is_interactive;
8578 if (++on == is_interactive)
8580 is_interactive = on;
8584 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8585 if (is_interactive > 1) {
8586 /* Looks like they want an interactive shell */
8587 static smallint did_banner;
8590 /* note: ash and hush share this string */
8591 out1fmt("\n\n%s %s\n"
8592 "Enter 'help' for a list of built-in commands."
8595 "built-in shell (ash)"
8609 setinteractive(iflag);
8611 #if ENABLE_FEATURE_EDITING_VI
8613 line_input_state->flags |= VI_MODE;
8615 line_input_state->flags &= ~VI_MODE;
8617 viflag = 0; /* forcibly keep the option off */
8621 static struct localvar *localvars;
8624 * Called after a function returns.
8625 * Interrupts must be off.
8630 struct localvar *lvp;
8633 while ((lvp = localvars) != NULL) {
8634 localvars = lvp->next;
8636 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8637 if (vp == NULL) { /* $- saved */
8638 memcpy(optlist, lvp->text, sizeof(optlist));
8639 free((char*)lvp->text);
8641 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8645 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8646 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8647 free((char*)vp->text);
8648 vp->flags = lvp->flags;
8649 vp->text = lvp->text;
8656 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8658 volatile struct shparam saveparam;
8659 struct localvar *volatile savelocalvars;
8660 struct jmploc *volatile savehandler;
8661 struct jmploc jmploc;
8664 saveparam = shellparam;
8665 savelocalvars = localvars;
8666 e = setjmp(jmploc.loc);
8671 savehandler = exception_handler;
8672 exception_handler = &jmploc;
8674 shellparam.malloced = 0;
8678 shellparam.nparam = argc - 1;
8679 shellparam.p = argv + 1;
8680 #if ENABLE_ASH_GETOPTS
8681 shellparam.optind = 1;
8682 shellparam.optoff = -1;
8684 evaltree(&func->n, flags & EV_TESTED);
8690 localvars = savelocalvars;
8691 freeparam(&shellparam);
8692 shellparam = saveparam;
8693 exception_handler = savehandler;
8695 evalskip &= ~SKIPFUNC;
8699 #if ENABLE_ASH_CMDCMD
8701 parse_command_args(char **argv, const char **path)
8714 if (c == '-' && !*cp) {
8721 *path = bb_default_path;
8724 /* run 'typecmd' for other options */
8735 * Make a variable a local variable. When a variable is made local, it's
8736 * value and flags are saved in a localvar structure. The saved values
8737 * will be restored when the shell function returns. We handle the name
8738 * "-" as a special case.
8743 struct localvar *lvp;
8748 lvp = ckzalloc(sizeof(struct localvar));
8749 if (LONE_DASH(name)) {
8751 p = ckmalloc(sizeof(optlist));
8752 lvp->text = memcpy(p, optlist, sizeof(optlist));
8757 vpp = hashvar(name);
8758 vp = *findvar(vpp, name);
8759 eq = strchr(name, '=');
8762 setvareq(name, VSTRFIXED);
8764 setvar(name, NULL, VSTRFIXED);
8765 vp = *vpp; /* the new variable */
8766 lvp->flags = VUNSET;
8768 lvp->text = vp->text;
8769 lvp->flags = vp->flags;
8770 vp->flags |= VSTRFIXED|VTEXTFIXED;
8776 lvp->next = localvars;
8782 * The "local" command.
8784 static int FAST_FUNC
8785 localcmd(int argc UNUSED_PARAM, char **argv)
8790 while ((name = *argv++) != NULL) {
8796 static int FAST_FUNC
8797 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8802 static int FAST_FUNC
8803 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8808 static int FAST_FUNC
8809 execcmd(int argc UNUSED_PARAM, char **argv)
8812 iflag = 0; /* exit on error */
8815 shellexec(argv + 1, pathval(), 0);
8821 * The return command.
8823 static int FAST_FUNC
8824 returncmd(int argc UNUSED_PARAM, char **argv)
8827 * If called outside a function, do what ksh does;
8828 * skip the rest of the file.
8830 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8831 return argv[1] ? number(argv[1]) : exitstatus;
8834 /* Forward declarations for builtintab[] */
8835 static int breakcmd(int, char **) FAST_FUNC;
8836 static int dotcmd(int, char **) FAST_FUNC;
8837 static int evalcmd(int, char **) FAST_FUNC;
8838 static int exitcmd(int, char **) FAST_FUNC;
8839 static int exportcmd(int, char **) FAST_FUNC;
8840 #if ENABLE_ASH_GETOPTS
8841 static int getoptscmd(int, char **) FAST_FUNC;
8843 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8844 static int helpcmd(int, char **) FAST_FUNC;
8846 #if ENABLE_SH_MATH_SUPPORT
8847 static int letcmd(int, char **) FAST_FUNC;
8849 static int readcmd(int, char **) FAST_FUNC;
8850 static int setcmd(int, char **) FAST_FUNC;
8851 static int shiftcmd(int, char **) FAST_FUNC;
8852 static int timescmd(int, char **) FAST_FUNC;
8853 static int trapcmd(int, char **) FAST_FUNC;
8854 static int umaskcmd(int, char **) FAST_FUNC;
8855 static int unsetcmd(int, char **) FAST_FUNC;
8856 static int ulimitcmd(int, char **) FAST_FUNC;
8858 #define BUILTIN_NOSPEC "0"
8859 #define BUILTIN_SPECIAL "1"
8860 #define BUILTIN_REGULAR "2"
8861 #define BUILTIN_SPEC_REG "3"
8862 #define BUILTIN_ASSIGN "4"
8863 #define BUILTIN_SPEC_ASSG "5"
8864 #define BUILTIN_REG_ASSG "6"
8865 #define BUILTIN_SPEC_REG_ASSG "7"
8867 /* Stubs for calling non-FAST_FUNC's */
8868 #if ENABLE_ASH_BUILTIN_ECHO
8869 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8871 #if ENABLE_ASH_BUILTIN_PRINTF
8872 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8874 #if ENABLE_ASH_BUILTIN_TEST
8875 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8878 /* Keep these in proper order since it is searched via bsearch() */
8879 static const struct builtincmd builtintab[] = {
8880 { BUILTIN_SPEC_REG "." , dotcmd },
8881 { BUILTIN_SPEC_REG ":" , truecmd },
8882 #if ENABLE_ASH_BUILTIN_TEST
8883 { BUILTIN_REGULAR "[" , testcmd },
8884 #if ENABLE_ASH_BASH_COMPAT
8885 { BUILTIN_REGULAR "[[" , testcmd },
8888 #if ENABLE_ASH_ALIAS
8889 { BUILTIN_REG_ASSG "alias" , aliascmd },
8892 { BUILTIN_REGULAR "bg" , fg_bgcmd },
8894 { BUILTIN_SPEC_REG "break" , breakcmd },
8895 { BUILTIN_REGULAR "cd" , cdcmd },
8896 { BUILTIN_NOSPEC "chdir" , cdcmd },
8897 #if ENABLE_ASH_CMDCMD
8898 { BUILTIN_REGULAR "command" , commandcmd },
8900 { BUILTIN_SPEC_REG "continue", breakcmd },
8901 #if ENABLE_ASH_BUILTIN_ECHO
8902 { BUILTIN_REGULAR "echo" , echocmd },
8904 { BUILTIN_SPEC_REG "eval" , evalcmd },
8905 { BUILTIN_SPEC_REG "exec" , execcmd },
8906 { BUILTIN_SPEC_REG "exit" , exitcmd },
8907 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
8908 { BUILTIN_REGULAR "false" , falsecmd },
8910 { BUILTIN_REGULAR "fg" , fg_bgcmd },
8912 #if ENABLE_ASH_GETOPTS
8913 { BUILTIN_REGULAR "getopts" , getoptscmd },
8915 { BUILTIN_NOSPEC "hash" , hashcmd },
8916 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8917 { BUILTIN_NOSPEC "help" , helpcmd },
8920 { BUILTIN_REGULAR "jobs" , jobscmd },
8921 { BUILTIN_REGULAR "kill" , killcmd },
8923 #if ENABLE_SH_MATH_SUPPORT
8924 { BUILTIN_NOSPEC "let" , letcmd },
8926 { BUILTIN_ASSIGN "local" , localcmd },
8927 #if ENABLE_ASH_BUILTIN_PRINTF
8928 { BUILTIN_REGULAR "printf" , printfcmd },
8930 { BUILTIN_NOSPEC "pwd" , pwdcmd },
8931 { BUILTIN_REGULAR "read" , readcmd },
8932 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8933 { BUILTIN_SPEC_REG "return" , returncmd },
8934 { BUILTIN_SPEC_REG "set" , setcmd },
8935 { BUILTIN_SPEC_REG "shift" , shiftcmd },
8936 #if ENABLE_ASH_BASH_COMPAT
8937 { BUILTIN_SPEC_REG "source" , dotcmd },
8939 #if ENABLE_ASH_BUILTIN_TEST
8940 { BUILTIN_REGULAR "test" , testcmd },
8942 { BUILTIN_SPEC_REG "times" , timescmd },
8943 { BUILTIN_SPEC_REG "trap" , trapcmd },
8944 { BUILTIN_REGULAR "true" , truecmd },
8945 { BUILTIN_NOSPEC "type" , typecmd },
8946 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
8947 { BUILTIN_REGULAR "umask" , umaskcmd },
8948 #if ENABLE_ASH_ALIAS
8949 { BUILTIN_REGULAR "unalias" , unaliascmd },
8951 { BUILTIN_SPEC_REG "unset" , unsetcmd },
8952 { BUILTIN_REGULAR "wait" , waitcmd },
8955 /* Should match the above table! */
8956 #define COMMANDCMD (builtintab + \
8958 1 * ENABLE_ASH_BUILTIN_TEST + \
8959 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8960 1 * ENABLE_ASH_ALIAS + \
8961 1 * ENABLE_ASH_JOB_CONTROL + \
8963 #define EXECCMD (builtintab + \
8965 1 * ENABLE_ASH_BUILTIN_TEST + \
8966 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8967 1 * ENABLE_ASH_ALIAS + \
8968 1 * ENABLE_ASH_JOB_CONTROL + \
8970 1 * ENABLE_ASH_CMDCMD + \
8972 ENABLE_ASH_BUILTIN_ECHO + \
8976 * Search the table of builtin commands.
8978 static struct builtincmd *
8979 find_builtin(const char *name)
8981 struct builtincmd *bp;
8984 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8991 * Execute a simple command.
8994 isassignment(const char *p)
8996 const char *q = endofname(p);
9001 static int FAST_FUNC
9002 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9004 /* Preserve exitstatus of a previous possible redirection
9005 * as POSIX mandates */
9006 return back_exitstatus;
9009 evalcommand(union node *cmd, int flags)
9011 static const struct builtincmd null_bltin = {
9012 "\0\0", bltincmd /* why three NULs? */
9014 struct stackmark smark;
9016 struct arglist arglist;
9017 struct arglist varlist;
9020 const struct strlist *sp;
9021 struct cmdentry cmdentry;
9028 struct builtincmd *bcmd;
9029 smallint cmd_is_exec;
9030 smallint pseudovarflag = 0;
9032 /* First expand the arguments. */
9033 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9034 setstackmark(&smark);
9035 back_exitstatus = 0;
9037 cmdentry.cmdtype = CMDBUILTIN;
9038 cmdentry.u.cmd = &null_bltin;
9039 varlist.lastp = &varlist.list;
9040 *varlist.lastp = NULL;
9041 arglist.lastp = &arglist.list;
9042 *arglist.lastp = NULL;
9045 if (cmd->ncmd.args) {
9046 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9047 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9050 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9051 struct strlist **spp;
9053 spp = arglist.lastp;
9054 if (pseudovarflag && isassignment(argp->narg.text))
9055 expandarg(argp, &arglist, EXP_VARTILDE);
9057 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9059 for (sp = *spp; sp; sp = sp->next)
9063 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9064 for (sp = arglist.list; sp; sp = sp->next) {
9065 TRACE(("evalcommand arg: %s\n", sp->text));
9066 *nargv++ = sp->text;
9071 if (iflag && funcnest == 0 && argc > 0)
9072 lastarg = nargv[-1];
9075 expredir(cmd->ncmd.redirect);
9076 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9079 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9080 struct strlist **spp;
9083 spp = varlist.lastp;
9084 expandarg(argp, &varlist, EXP_VARTILDE);
9087 * Modify the command lookup path, if a PATH= assignment
9091 if (varequal(p, path))
9095 /* Print the command if xflag is set. */
9098 const char *p = " %s";
9101 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9104 for (n = 0; n < 2; n++) {
9106 fdprintf(preverrout_fd, p, sp->text);
9114 safe_write(preverrout_fd, "\n", 1);
9120 /* Now locate the command. */
9122 const char *oldpath;
9123 int cmd_flag = DO_ERR;
9128 find_command(argv[0], &cmdentry, cmd_flag, path);
9129 if (cmdentry.cmdtype == CMDUNKNOWN) {
9130 flush_stdout_stderr();
9135 /* implement bltin and command here */
9136 if (cmdentry.cmdtype != CMDBUILTIN)
9139 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9140 if (cmdentry.u.cmd == EXECCMD)
9142 #if ENABLE_ASH_CMDCMD
9143 if (cmdentry.u.cmd == COMMANDCMD) {
9145 nargv = parse_command_args(argv, &path);
9148 argc -= nargv - argv;
9150 cmd_flag |= DO_NOFUNC;
9158 /* We have a redirection error. */
9160 raise_exception(EXERROR);
9162 exitstatus = status;
9166 /* Execute the command. */
9167 switch (cmdentry.cmdtype) {
9170 #if ENABLE_FEATURE_SH_NOFORK
9171 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9172 * around run_nofork_applet() call.
9173 * (2) Should this check also be done in forkshell()?
9174 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9176 /* find_command() encodes applet_no as (-2 - applet_no) */
9177 int applet_no = (- cmdentry.u.index - 2);
9178 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9179 listsetvar(varlist.list, VEXPORT|VSTACK);
9180 /* run <applet>_main() */
9181 exitstatus = run_nofork_applet(applet_no, argv);
9185 /* Can we avoid forking off? For example, very last command
9186 * in a script or a subshell does not need forking,
9187 * we can just exec it.
9189 if (!(flags & EV_EXIT) || may_have_traps) {
9190 /* No, forking off a child is necessary */
9192 jp = makejob(/*cmd,*/ 1);
9193 if (forkshell(jp, cmd, FORK_FG) != 0) {
9195 exitstatus = waitforjob(jp);
9197 TRACE(("forked child exited with %d\n", exitstatus));
9202 /* fall through to exec'ing external program */
9204 listsetvar(varlist.list, VEXPORT|VSTACK);
9205 shellexec(argv, path, cmdentry.u.index);
9209 cmdenviron = varlist.list;
9211 struct strlist *list = cmdenviron;
9213 if (spclbltin > 0 || argc == 0) {
9215 if (cmd_is_exec && argc > 1)
9218 listsetvar(list, i);
9220 /* Tight loop with builtins only:
9221 * "while kill -0 $child; do true; done"
9222 * will never exit even if $child died, unless we do this
9223 * to reap the zombie and make kill detect that it's gone: */
9224 dowait(DOWAIT_NONBLOCK, NULL);
9226 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9228 int i = exception_type;
9233 exit_status = 128 + SIGINT;
9235 exit_status = 128 + pending_sig;
9236 exitstatus = exit_status;
9237 if (i == EXINT || spclbltin > 0) {
9239 longjmp(exception_handler->loc, 1);
9246 listsetvar(varlist.list, 0);
9247 /* See above for the rationale */
9248 dowait(DOWAIT_NONBLOCK, NULL);
9249 if (evalfun(cmdentry.u.func, argc, argv, flags))
9256 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9258 /* dsl: I think this is intended to be used to support
9259 * '_' in 'vi' command mode during line editing...
9260 * However I implemented that within libedit itself.
9262 setvar("_", lastarg, 0);
9264 popstackmark(&smark);
9268 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9270 char *volatile savecmdname;
9271 struct jmploc *volatile savehandler;
9272 struct jmploc jmploc;
9275 savecmdname = commandname;
9276 i = setjmp(jmploc.loc);
9279 savehandler = exception_handler;
9280 exception_handler = &jmploc;
9281 commandname = argv[0];
9283 optptr = NULL; /* initialize nextopt */
9284 exitstatus = (*cmd->builtin)(argc, argv);
9285 flush_stdout_stderr();
9287 exitstatus |= ferror(stdout);
9289 commandname = savecmdname;
9290 exception_handler = savehandler;
9296 goodname(const char *p)
9298 return !*endofname(p);
9303 * Search for a command. This is called before we fork so that the
9304 * location of the command will be available in the parent as well as
9305 * the child. The check for "goodname" is an overly conservative
9306 * check that the name will not be subject to expansion.
9309 prehash(union node *n)
9311 struct cmdentry entry;
9313 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9314 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9318 /* ============ Builtin commands
9320 * Builtin commands whose functions are closely tied to evaluation
9321 * are implemented here.
9325 * Handle break and continue commands. Break, continue, and return are
9326 * all handled by setting the evalskip flag. The evaluation routines
9327 * above all check this flag, and if it is set they start skipping
9328 * commands rather than executing them. The variable skipcount is
9329 * the number of loops to break/continue, or the number of function
9330 * levels to return. (The latter is always 1.) It should probably
9331 * be an error to break out of more loops than exist, but it isn't
9332 * in the standard shell so we don't make it one here.
9334 static int FAST_FUNC
9335 breakcmd(int argc UNUSED_PARAM, char **argv)
9337 int n = argv[1] ? number(argv[1]) : 1;
9340 ash_msg_and_raise_error(msg_illnum, argv[1]);
9344 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9351 /* ============ input.c
9353 * This implements the input routines used by the parser.
9357 INPUT_PUSH_FILE = 1,
9358 INPUT_NOFILE_OK = 2,
9361 static smallint checkkwd;
9362 /* values of checkkwd variable */
9363 #define CHKALIAS 0x1
9368 * Push a string back onto the input at this current parsefile level.
9369 * We handle aliases this way.
9371 #if !ENABLE_ASH_ALIAS
9372 #define pushstring(s, ap) pushstring(s)
9375 pushstring(char *s, struct alias *ap)
9382 if (g_parsefile->strpush) {
9383 sp = ckzalloc(sizeof(*sp));
9384 sp->prev = g_parsefile->strpush;
9386 sp = &(g_parsefile->basestrpush);
9388 g_parsefile->strpush = sp;
9389 sp->prev_string = g_parsefile->next_to_pgetc;
9390 sp->prev_left_in_line = g_parsefile->left_in_line;
9391 #if ENABLE_ASH_ALIAS
9394 ap->flag |= ALIASINUSE;
9398 g_parsefile->next_to_pgetc = s;
9399 g_parsefile->left_in_line = len;
9406 struct strpush *sp = g_parsefile->strpush;
9409 #if ENABLE_ASH_ALIAS
9411 if (g_parsefile->next_to_pgetc[-1] == ' '
9412 || g_parsefile->next_to_pgetc[-1] == '\t'
9414 checkkwd |= CHKALIAS;
9416 if (sp->string != sp->ap->val) {
9419 sp->ap->flag &= ~ALIASINUSE;
9420 if (sp->ap->flag & ALIASDEAD) {
9421 unalias(sp->ap->name);
9425 g_parsefile->next_to_pgetc = sp->prev_string;
9426 g_parsefile->left_in_line = sp->prev_left_in_line;
9427 g_parsefile->strpush = sp->prev;
9428 if (sp != &(g_parsefile->basestrpush))
9433 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9434 //it peeks whether it is &>, and then pushes back both chars.
9435 //This function needs to save last *next_to_pgetc to buf[0]
9436 //to make two pungetc() reliable. Currently,
9437 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9442 char *buf = g_parsefile->buf;
9444 g_parsefile->next_to_pgetc = buf;
9445 #if ENABLE_FEATURE_EDITING
9447 if (!iflag || g_parsefile->fd != STDIN_FILENO)
9448 nr = nonblock_safe_read(g_parsefile->fd, buf, IBUFSIZ - 1);
9450 #if ENABLE_FEATURE_TAB_COMPLETION
9451 line_input_state->path_lookup = pathval();
9453 nr = read_line_input(cmdedit_prompt, buf, IBUFSIZ, line_input_state);
9455 /* Ctrl+C pressed */
9464 if (nr < 0 && errno == 0) {
9465 /* Ctrl+D pressed */
9470 nr = nonblock_safe_read(g_parsefile->fd, buf, IBUFSIZ - 1);
9474 /* nonblock_safe_read() handles this problem */
9476 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9477 int flags = fcntl(0, F_GETFL);
9478 if (flags >= 0 && (flags & O_NONBLOCK)) {
9479 flags &= ~O_NONBLOCK;
9480 if (fcntl(0, F_SETFL, flags) >= 0) {
9481 out2str("sh: turning off NDELAY mode\n");
9492 * Refill the input buffer and return the next input character:
9494 * 1) If a string was pushed back on the input, pop it;
9495 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9496 * or we are reading from a string so we can't refill the buffer,
9498 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9499 * 4) Process input up to the next newline, deleting nul characters.
9501 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9502 #define pgetc_debug(...) ((void)0)
9509 while (g_parsefile->strpush) {
9510 #if ENABLE_ASH_ALIAS
9511 if (g_parsefile->left_in_line == -1
9512 && g_parsefile->strpush->ap
9513 && g_parsefile->next_to_pgetc[-1] != ' '
9514 && g_parsefile->next_to_pgetc[-1] != '\t'
9516 pgetc_debug("preadbuffer PEOA");
9521 /* try "pgetc" now: */
9522 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9523 g_parsefile->left_in_line,
9524 g_parsefile->next_to_pgetc,
9525 g_parsefile->next_to_pgetc);
9526 if (--g_parsefile->left_in_line >= 0)
9527 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9529 /* on both branches above g_parsefile->left_in_line < 0.
9530 * "pgetc" needs refilling.
9533 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9534 * pungetc() may increment it a few times.
9535 * Assuming it won't increment it to less than -90.
9537 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9538 pgetc_debug("preadbuffer PEOF1");
9539 /* even in failure keep left_in_line and next_to_pgetc
9540 * in lock step, for correct multi-layer pungetc.
9541 * left_in_line was decremented before preadbuffer(),
9542 * must inc next_to_pgetc: */
9543 g_parsefile->next_to_pgetc++;
9547 more = g_parsefile->left_in_buffer;
9549 flush_stdout_stderr();
9553 /* don't try reading again */
9554 g_parsefile->left_in_line = -99;
9555 pgetc_debug("preadbuffer PEOF2");
9556 g_parsefile->next_to_pgetc++;
9561 /* Find out where's the end of line.
9562 * Set g_parsefile->left_in_line
9563 * and g_parsefile->left_in_buffer acordingly.
9564 * NUL chars are deleted.
9566 q = g_parsefile->next_to_pgetc;
9574 memmove(q, q + 1, more);
9578 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9584 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9585 if (g_parsefile->left_in_line < 0)
9590 g_parsefile->left_in_buffer = more;
9595 out2str(g_parsefile->next_to_pgetc);
9599 pgetc_debug("preadbuffer at %d:%p'%s'",
9600 g_parsefile->left_in_line,
9601 g_parsefile->next_to_pgetc,
9602 g_parsefile->next_to_pgetc);
9603 return (unsigned char)*g_parsefile->next_to_pgetc++;
9606 #define pgetc_as_macro() \
9607 (--g_parsefile->left_in_line >= 0 \
9608 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9615 pgetc_debug("pgetc_fast at %d:%p'%s'",
9616 g_parsefile->left_in_line,
9617 g_parsefile->next_to_pgetc,
9618 g_parsefile->next_to_pgetc);
9619 return pgetc_as_macro();
9622 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9623 # define pgetc_fast() pgetc()
9625 # define pgetc_fast() pgetc_as_macro()
9628 #if ENABLE_ASH_ALIAS
9630 pgetc_without_PEOA(void)
9634 pgetc_debug("pgetc_fast at %d:%p'%s'",
9635 g_parsefile->left_in_line,
9636 g_parsefile->next_to_pgetc,
9637 g_parsefile->next_to_pgetc);
9639 } while (c == PEOA);
9643 # define pgetc_without_PEOA() pgetc()
9647 * Read a line from the script.
9650 pfgets(char *line, int len)
9656 while (--nleft > 0) {
9657 c = pgetc_without_PEOA();
9672 * Undo the last call to pgetc. Only one character may be pushed back.
9673 * PEOF may be pushed back.
9678 g_parsefile->left_in_line++;
9679 g_parsefile->next_to_pgetc--;
9680 pgetc_debug("pushed back to %d:%p'%s'",
9681 g_parsefile->left_in_line,
9682 g_parsefile->next_to_pgetc,
9683 g_parsefile->next_to_pgetc);
9687 * To handle the "." command, a stack of input files is used. Pushfile
9688 * adds a new entry to the stack and popfile restores the previous level.
9693 struct parsefile *pf;
9695 pf = ckzalloc(sizeof(*pf));
9696 pf->prev = g_parsefile;
9698 /*pf->strpush = NULL; - ckzalloc did it */
9699 /*pf->basestrpush.prev = NULL;*/
9706 struct parsefile *pf = g_parsefile;
9714 g_parsefile = pf->prev;
9720 * Return to top level.
9725 while (g_parsefile != &basepf)
9730 * Close the file(s) that the shell is reading commands from. Called
9731 * after a fork is done.
9737 if (g_parsefile->fd > 0) {
9738 close(g_parsefile->fd);
9739 g_parsefile->fd = 0;
9744 * Like setinputfile, but takes an open file descriptor. Call this with
9748 setinputfd(int fd, int push)
9750 close_on_exec_on(fd);
9753 g_parsefile->buf = NULL;
9755 g_parsefile->fd = fd;
9756 if (g_parsefile->buf == NULL)
9757 g_parsefile->buf = ckmalloc(IBUFSIZ);
9758 g_parsefile->left_in_buffer = 0;
9759 g_parsefile->left_in_line = 0;
9760 g_parsefile->linno = 1;
9764 * Set the input to take input from a file. If push is set, push the
9765 * old input onto the stack first.
9768 setinputfile(const char *fname, int flags)
9774 fd = open(fname, O_RDONLY);
9776 if (flags & INPUT_NOFILE_OK)
9778 ash_msg_and_raise_error("can't open '%s'", fname);
9781 fd2 = copyfd(fd, 10);
9784 ash_msg_and_raise_error("out of file descriptors");
9787 setinputfd(fd, flags & INPUT_PUSH_FILE);
9794 * Like setinputfile, but takes input from a string.
9797 setinputstring(char *string)
9801 g_parsefile->next_to_pgetc = string;
9802 g_parsefile->left_in_line = strlen(string);
9803 g_parsefile->buf = NULL;
9804 g_parsefile->linno = 1;
9809 /* ============ mail.c
9811 * Routines to check for mail.
9816 #define MAXMBOXES 10
9818 /* times of mailboxes */
9819 static time_t mailtime[MAXMBOXES];
9820 /* Set if MAIL or MAILPATH is changed. */
9821 static smallint mail_var_path_changed;
9824 * Print appropriate message(s) if mail has arrived.
9825 * If mail_var_path_changed is set,
9826 * then the value of MAIL has mail_var_path_changed,
9827 * so we just update the values.
9836 struct stackmark smark;
9839 setstackmark(&smark);
9840 mpath = mpathset() ? mpathval() : mailval();
9841 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9842 p = path_advance(&mpath, nullstr);
9847 for (q = p; *q; q++)
9853 q[-1] = '\0'; /* delete trailing '/' */
9854 if (stat(p, &statb) < 0) {
9858 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9861 pathopt ? pathopt : "you have mail"
9864 *mtp = statb.st_mtime;
9866 mail_var_path_changed = 0;
9867 popstackmark(&smark);
9870 static void FAST_FUNC
9871 changemail(const char *val UNUSED_PARAM)
9873 mail_var_path_changed = 1;
9876 #endif /* ASH_MAIL */
9879 /* ============ ??? */
9882 * Set the shell parameters.
9885 setparam(char **argv)
9891 for (nparam = 0; argv[nparam]; nparam++)
9893 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9895 *ap++ = ckstrdup(*argv++);
9898 freeparam(&shellparam);
9899 shellparam.malloced = 1;
9900 shellparam.nparam = nparam;
9901 shellparam.p = newparam;
9902 #if ENABLE_ASH_GETOPTS
9903 shellparam.optind = 1;
9904 shellparam.optoff = -1;
9909 * Process shell options. The global variable argptr contains a pointer
9910 * to the argument list; we advance it past the options.
9912 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9913 * For a non-interactive shell, an error condition encountered
9914 * by a special built-in ... shall cause the shell to write a diagnostic message
9915 * to standard error and exit as shown in the following table:
9916 * Error Special Built-In
9918 * Utility syntax error (option or operand error) Shall exit
9920 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9921 * we see that bash does not do that (set "finishes" with error code 1 instead,
9922 * and shell continues), and people rely on this behavior!
9924 * set -o barfoo 2>/dev/null
9927 * Oh well. Let's mimic that.
9930 plus_minus_o(char *name, int val)
9935 for (i = 0; i < NOPTS; i++) {
9936 if (strcmp(name, optnames(i)) == 0) {
9941 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9944 for (i = 0; i < NOPTS; i++) {
9946 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9948 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9954 setoption(int flag, int val)
9958 for (i = 0; i < NOPTS; i++) {
9959 if (optletters(i) == flag) {
9964 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9968 options(int cmdline)
9976 while ((p = *argptr) != NULL) {
9978 if (c != '-' && c != '+')
9981 val = 0; /* val = 0 if c == '+' */
9984 if (p[0] == '\0' || LONE_DASH(p)) {
9986 /* "-" means turn off -x and -v */
9989 /* "--" means reset params */
9990 else if (*argptr == NULL)
9993 break; /* "-" or "--" terminates options */
9996 /* first char was + or - */
9997 while ((c = *p++) != '\0') {
9998 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9999 if (c == 'c' && cmdline) {
10000 minusc = p; /* command is after shell args */
10001 } else if (c == 'o') {
10002 if (plus_minus_o(*argptr, val)) {
10003 /* it already printed err message */
10004 return 1; /* error */
10008 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10010 /* bash does not accept +-login, we also won't */
10011 } else if (cmdline && val && (c == '-')) { /* long options */
10012 if (strcmp(p, "login") == 0)
10024 * The shift builtin command.
10026 static int FAST_FUNC
10027 shiftcmd(int argc UNUSED_PARAM, char **argv)
10034 n = number(argv[1]);
10035 if (n > shellparam.nparam)
10036 n = 0; /* bash compat, was = shellparam.nparam; */
10038 shellparam.nparam -= n;
10039 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10040 if (shellparam.malloced)
10043 ap2 = shellparam.p;
10044 while ((*ap2++ = *ap1++) != NULL)
10046 #if ENABLE_ASH_GETOPTS
10047 shellparam.optind = 1;
10048 shellparam.optoff = -1;
10055 * POSIX requires that 'set' (but not export or readonly) output the
10056 * variables in lexicographic order - by the locale's collating order (sigh).
10057 * Maybe we could keep them in an ordered balanced binary tree
10058 * instead of hashed lists.
10059 * For now just roll 'em through qsort for printing...
10062 showvars(const char *sep_prefix, int on, int off)
10065 char **ep, **epend;
10067 ep = listvars(on, off, &epend);
10068 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10070 sep = *sep_prefix ? " " : sep_prefix;
10072 for (; ep < epend; ep++) {
10076 p = strchrnul(*ep, '=');
10079 q = single_quote(++p);
10080 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10086 * The set command builtin.
10088 static int FAST_FUNC
10089 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10094 return showvars(nullstr, 0, VUNSET);
10097 if (!options(0)) { /* if no parse error... */
10100 if (*argptr != NULL) {
10108 #if ENABLE_ASH_RANDOM_SUPPORT
10109 static void FAST_FUNC
10110 change_random(const char *value)
10114 if (value == NULL) {
10115 /* "get", generate */
10116 t = next_random(&random_gen);
10117 /* set without recursion */
10118 setvar(vrandom.text, utoa(t), VNOFUNC);
10119 vrandom.flags &= ~VNOFUNC;
10122 t = strtoul(value, NULL, 10);
10123 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10128 #if ENABLE_ASH_GETOPTS
10130 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10139 if (*param_optind < 1)
10141 optnext = optfirst + *param_optind - 1;
10143 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10146 p = optnext[-1] + *optoff;
10147 if (p == NULL || *p == '\0') {
10148 /* Current word is done, advance */
10150 if (p == NULL || *p != '-' || *++p == '\0') {
10157 if (LONE_DASH(p)) /* check for "--" */
10162 for (q = optstr; *q != c;) {
10164 if (optstr[0] == ':') {
10167 err |= setvarsafe("OPTARG", s, 0);
10169 fprintf(stderr, "Illegal option -%c\n", c);
10170 unsetvar("OPTARG");
10180 if (*p == '\0' && (p = *optnext) == NULL) {
10181 if (optstr[0] == ':') {
10184 err |= setvarsafe("OPTARG", s, 0);
10187 fprintf(stderr, "No arg for -%c option\n", c);
10188 unsetvar("OPTARG");
10196 err |= setvarsafe("OPTARG", p, 0);
10199 err |= setvarsafe("OPTARG", nullstr, 0);
10201 *optoff = p ? p - *(optnext - 1) : -1;
10202 *param_optind = optnext - optfirst + 1;
10203 fmtstr(s, sizeof(s), "%d", *param_optind);
10204 err |= setvarsafe("OPTIND", s, VNOFUNC);
10207 err |= setvarsafe(optvar, s, 0);
10211 flush_stdout_stderr();
10212 raise_exception(EXERROR);
10218 * The getopts builtin. Shellparam.optnext points to the next argument
10219 * to be processed. Shellparam.optptr points to the next character to
10220 * be processed in the current argument. If shellparam.optnext is NULL,
10221 * then it's the first time getopts has been called.
10223 static int FAST_FUNC
10224 getoptscmd(int argc, char **argv)
10229 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10231 optbase = shellparam.p;
10232 if (shellparam.optind > shellparam.nparam + 1) {
10233 shellparam.optind = 1;
10234 shellparam.optoff = -1;
10237 optbase = &argv[3];
10238 if (shellparam.optind > argc - 2) {
10239 shellparam.optind = 1;
10240 shellparam.optoff = -1;
10244 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10245 &shellparam.optoff);
10247 #endif /* ASH_GETOPTS */
10250 /* ============ Shell parser */
10253 struct heredoc *next; /* next here document in list */
10254 union node *here; /* redirection node */
10255 char *eofmark; /* string indicating end of input */
10256 smallint striptabs; /* if set, strip leading tabs */
10259 static smallint tokpushback; /* last token pushed back */
10260 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10261 static smallint quoteflag; /* set if (part of) last token was quoted */
10262 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10263 static struct heredoc *heredoclist; /* list of here documents to read */
10264 static char *wordtext; /* text of last word returned by readtoken */
10265 static struct nodelist *backquotelist;
10266 static union node *redirnode;
10267 static struct heredoc *heredoc;
10269 static const char *
10270 tokname(char *buf, int tok)
10273 return tokname_array[tok] + 1;
10274 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10278 /* raise_error_unexpected_syntax:
10279 * Called when an unexpected token is read during the parse. The argument
10280 * is the token that is expected, or -1 if more than one type of token can
10281 * occur at this point.
10283 static void raise_error_unexpected_syntax(int) NORETURN;
10285 raise_error_unexpected_syntax(int token)
10291 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10293 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10294 raise_error_syntax(msg);
10298 #define EOFMARKLEN 79
10300 /* parsing is heavily cross-recursive, need these forward decls */
10301 static union node *andor(void);
10302 static union node *pipeline(void);
10303 static union node *parse_command(void);
10304 static void parseheredoc(void);
10305 static char peektoken(void);
10306 static int readtoken(void);
10308 static union node *
10311 union node *n1, *n2, *n3;
10314 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10315 if (nlflag == 2 && peektoken())
10321 if (tok == TBACKGND) {
10322 if (n2->type == NPIPE) {
10323 n2->npipe.pipe_backgnd = 1;
10325 if (n2->type != NREDIR) {
10326 n3 = stzalloc(sizeof(struct nredir));
10328 /*n3->nredir.redirect = NULL; - stzalloc did it */
10331 n2->type = NBACKGND;
10337 n3 = stzalloc(sizeof(struct nbinary));
10339 n3->nbinary.ch1 = n1;
10340 n3->nbinary.ch2 = n2;
10356 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10364 pungetc(); /* push back EOF on input */
10368 raise_error_unexpected_syntax(-1);
10375 static union node *
10378 union node *n1, *n2, *n3;
10386 } else if (t == TOR) {
10392 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10394 n3 = stzalloc(sizeof(struct nbinary));
10396 n3->nbinary.ch1 = n1;
10397 n3->nbinary.ch2 = n2;
10402 static union node *
10405 union node *n1, *n2, *pipenode;
10406 struct nodelist *lp, *prev;
10410 TRACE(("pipeline: entered\n"));
10411 if (readtoken() == TNOT) {
10413 checkkwd = CHKKWD | CHKALIAS;
10416 n1 = parse_command();
10417 if (readtoken() == TPIPE) {
10418 pipenode = stzalloc(sizeof(struct npipe));
10419 pipenode->type = NPIPE;
10420 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10421 lp = stzalloc(sizeof(struct nodelist));
10422 pipenode->npipe.cmdlist = lp;
10426 lp = stzalloc(sizeof(struct nodelist));
10427 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10428 lp->n = parse_command();
10430 } while (readtoken() == TPIPE);
10436 n2 = stzalloc(sizeof(struct nnot));
10444 static union node *
10449 n = stzalloc(sizeof(struct narg));
10451 /*n->narg.next = NULL; - stzalloc did it */
10452 n->narg.text = wordtext;
10453 n->narg.backquote = backquotelist;
10458 fixredir(union node *n, const char *text, int err)
10462 TRACE(("Fix redir %s %d\n", text, err));
10464 n->ndup.vname = NULL;
10466 fd = bb_strtou(text, NULL, 10);
10467 if (!errno && fd >= 0)
10468 n->ndup.dupfd = fd;
10469 else if (LONE_DASH(text))
10470 n->ndup.dupfd = -1;
10473 raise_error_syntax("bad fd number");
10474 n->ndup.vname = makename();
10479 * Returns true if the text contains nothing to expand (no dollar signs
10483 noexpand(const char *text)
10487 while ((c = *text++) != '\0') {
10488 if (c == CTLQUOTEMARK)
10492 else if (SIT(c, BASESYNTAX) == CCTL)
10501 union node *n = redirnode;
10503 if (readtoken() != TWORD)
10504 raise_error_unexpected_syntax(-1);
10505 if (n->type == NHERE) {
10506 struct heredoc *here = heredoc;
10510 if (quoteflag == 0)
10512 TRACE(("Here document %d\n", n->type));
10513 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10514 raise_error_syntax("illegal eof marker for << redirection");
10515 rmescapes(wordtext, 0);
10516 here->eofmark = wordtext;
10518 if (heredoclist == NULL)
10519 heredoclist = here;
10521 for (p = heredoclist; p->next; p = p->next)
10525 } else if (n->type == NTOFD || n->type == NFROMFD) {
10526 fixredir(n, wordtext, 0);
10528 n->nfile.fname = makename();
10532 static union node *
10535 union node *args, **app;
10536 union node *n = NULL;
10537 union node *vars, **vpp;
10538 union node **rpp, *redir;
10540 #if ENABLE_ASH_BASH_COMPAT
10541 smallint double_brackets_flag = 0;
10551 savecheckkwd = CHKALIAS;
10554 checkkwd = savecheckkwd;
10557 #if ENABLE_ASH_BASH_COMPAT
10558 case TAND: /* "&&" */
10559 case TOR: /* "||" */
10560 if (!double_brackets_flag) {
10564 wordtext = (char *) (t == TAND ? "-a" : "-o");
10567 n = stzalloc(sizeof(struct narg));
10569 /*n->narg.next = NULL; - stzalloc did it */
10570 n->narg.text = wordtext;
10571 #if ENABLE_ASH_BASH_COMPAT
10572 if (strcmp("[[", wordtext) == 0)
10573 double_brackets_flag = 1;
10574 else if (strcmp("]]", wordtext) == 0)
10575 double_brackets_flag = 0;
10577 n->narg.backquote = backquotelist;
10578 if (savecheckkwd && isassignment(wordtext)) {
10580 vpp = &n->narg.next;
10583 app = &n->narg.next;
10588 *rpp = n = redirnode;
10589 rpp = &n->nfile.next;
10590 parsefname(); /* read name of redirection file */
10593 if (args && app == &args->narg.next
10596 struct builtincmd *bcmd;
10599 /* We have a function */
10600 if (readtoken() != TRP)
10601 raise_error_unexpected_syntax(TRP);
10602 name = n->narg.text;
10603 if (!goodname(name)
10604 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10606 raise_error_syntax("bad function name");
10609 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10610 n->narg.next = parse_command();
10623 n = stzalloc(sizeof(struct ncmd));
10625 n->ncmd.args = args;
10626 n->ncmd.assign = vars;
10627 n->ncmd.redirect = redir;
10631 static union node *
10632 parse_command(void)
10634 union node *n1, *n2;
10635 union node *ap, **app;
10636 union node *cp, **cpp;
10637 union node *redir, **rpp;
10644 switch (readtoken()) {
10646 raise_error_unexpected_syntax(-1);
10649 n1 = stzalloc(sizeof(struct nif));
10651 n1->nif.test = list(0);
10652 if (readtoken() != TTHEN)
10653 raise_error_unexpected_syntax(TTHEN);
10654 n1->nif.ifpart = list(0);
10656 while (readtoken() == TELIF) {
10657 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10658 n2 = n2->nif.elsepart;
10660 n2->nif.test = list(0);
10661 if (readtoken() != TTHEN)
10662 raise_error_unexpected_syntax(TTHEN);
10663 n2->nif.ifpart = list(0);
10665 if (lasttoken == TELSE)
10666 n2->nif.elsepart = list(0);
10668 n2->nif.elsepart = NULL;
10676 n1 = stzalloc(sizeof(struct nbinary));
10677 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10678 n1->nbinary.ch1 = list(0);
10681 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
10682 got == TWORD ? wordtext : ""));
10683 raise_error_unexpected_syntax(TDO);
10685 n1->nbinary.ch2 = list(0);
10690 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10691 raise_error_syntax("bad for loop variable");
10692 n1 = stzalloc(sizeof(struct nfor));
10694 n1->nfor.var = wordtext;
10695 checkkwd = CHKKWD | CHKALIAS;
10696 if (readtoken() == TIN) {
10698 while (readtoken() == TWORD) {
10699 n2 = stzalloc(sizeof(struct narg));
10701 /*n2->narg.next = NULL; - stzalloc did it */
10702 n2->narg.text = wordtext;
10703 n2->narg.backquote = backquotelist;
10705 app = &n2->narg.next;
10708 n1->nfor.args = ap;
10709 if (lasttoken != TNL && lasttoken != TSEMI)
10710 raise_error_unexpected_syntax(-1);
10712 n2 = stzalloc(sizeof(struct narg));
10714 /*n2->narg.next = NULL; - stzalloc did it */
10715 n2->narg.text = (char *)dolatstr;
10716 /*n2->narg.backquote = NULL;*/
10717 n1->nfor.args = n2;
10719 * Newline or semicolon here is optional (but note
10720 * that the original Bourne shell only allowed NL).
10722 if (lasttoken != TNL && lasttoken != TSEMI)
10725 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10726 if (readtoken() != TDO)
10727 raise_error_unexpected_syntax(TDO);
10728 n1->nfor.body = list(0);
10732 n1 = stzalloc(sizeof(struct ncase));
10734 if (readtoken() != TWORD)
10735 raise_error_unexpected_syntax(TWORD);
10736 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10738 /*n2->narg.next = NULL; - stzalloc did it */
10739 n2->narg.text = wordtext;
10740 n2->narg.backquote = backquotelist;
10742 checkkwd = CHKKWD | CHKALIAS;
10743 } while (readtoken() == TNL);
10744 if (lasttoken != TIN)
10745 raise_error_unexpected_syntax(TIN);
10746 cpp = &n1->ncase.cases;
10748 checkkwd = CHKNL | CHKKWD;
10750 while (t != TESAC) {
10751 if (lasttoken == TLP)
10753 *cpp = cp = stzalloc(sizeof(struct nclist));
10755 app = &cp->nclist.pattern;
10757 *app = ap = stzalloc(sizeof(struct narg));
10759 /*ap->narg.next = NULL; - stzalloc did it */
10760 ap->narg.text = wordtext;
10761 ap->narg.backquote = backquotelist;
10762 if (readtoken() != TPIPE)
10764 app = &ap->narg.next;
10767 //ap->narg.next = NULL;
10768 if (lasttoken != TRP)
10769 raise_error_unexpected_syntax(TRP);
10770 cp->nclist.body = list(2);
10772 cpp = &cp->nclist.next;
10774 checkkwd = CHKNL | CHKKWD;
10778 raise_error_unexpected_syntax(TENDCASE);
10785 n1 = stzalloc(sizeof(struct nredir));
10786 n1->type = NSUBSHELL;
10787 n1->nredir.n = list(0);
10788 /*n1->nredir.redirect = NULL; - stzalloc did it */
10798 return simplecmd();
10801 if (readtoken() != t)
10802 raise_error_unexpected_syntax(t);
10805 /* Now check for redirection which may follow command */
10806 checkkwd = CHKKWD | CHKALIAS;
10808 while (readtoken() == TREDIR) {
10809 *rpp = n2 = redirnode;
10810 rpp = &n2->nfile.next;
10816 if (n1->type != NSUBSHELL) {
10817 n2 = stzalloc(sizeof(struct nredir));
10822 n1->nredir.redirect = redir;
10827 #if ENABLE_ASH_BASH_COMPAT
10828 static int decode_dollar_squote(void)
10830 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10836 p = strchr(C_escapes, c);
10841 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10845 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10847 } else if (c == 'x') { /* \xHH */
10851 } while (isxdigit(c) && --cnt);
10853 if (cnt == 3) { /* \x but next char is "bad" */
10857 } else { /* simple seq like \\ or \t */
10862 c = bb_process_escape_sequence((void*)&p);
10863 } else { /* unrecognized "\z": print both chars unless ' or " */
10864 if (c != '\'' && c != '"') {
10866 c |= 0x100; /* "please encode \, then me" */
10874 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10875 * is not NULL, read a here document. In the latter case, eofmark is the
10876 * word which marks the end of the document and striptabs is true if
10877 * leading tabs should be stripped from the document. The argument c
10878 * is the first character of the input token or document.
10880 * Because C does not have internal subroutines, I have simulated them
10881 * using goto's to implement the subroutine linkage. The following macros
10882 * will run code that appears at the end of readtoken1.
10884 #define CHECKEND() {goto checkend; checkend_return:;}
10885 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10886 #define PARSESUB() {goto parsesub; parsesub_return:;}
10887 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10888 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10889 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10891 readtoken1(int c, int syntax, char *eofmark, int striptabs)
10893 /* NB: syntax parameter fits into smallint */
10894 /* c parameter is an unsigned char or PEOF or PEOA */
10897 char line[EOFMARKLEN + 1];
10898 struct nodelist *bqlist;
10902 smallint prevsyntax; /* syntax before arithmetic */
10903 #if ENABLE_ASH_EXPAND_PRMT
10904 smallint pssyntax; /* we are expanding a prompt string */
10906 int varnest; /* levels of variables expansion */
10907 int arinest; /* levels of arithmetic expansion */
10908 int parenlevel; /* levels of parens in arithmetic */
10909 int dqvarnest; /* levels of variables expansion within double quotes */
10911 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10914 /* Avoid longjmp clobbering */
10920 (void) &parenlevel;
10923 (void) &prevsyntax;
10926 startlinno = g_parsefile->linno;
10931 #if ENABLE_ASH_EXPAND_PRMT
10932 pssyntax = (syntax == PSSYNTAX);
10936 dblquote = (syntax == DQSYNTAX);
10942 STARTSTACKSTR(out);
10944 /* For each line, until end of word */
10946 CHECKEND(); /* set c to PEOF if at end of here document */
10947 for (;;) { /* until end of line or end of word */
10948 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10949 switch (SIT(c, syntax)) {
10950 case CNL: /* '\n' */
10951 if (syntax == BASESYNTAX)
10952 goto endword; /* exit outer loop */
10954 g_parsefile->linno++;
10958 goto loop; /* continue outer loop */
10963 if (eofmark == NULL || dblquote)
10964 USTPUTC(CTLESC, out);
10965 #if ENABLE_ASH_BASH_COMPAT
10966 if (c == '\\' && bash_dollar_squote) {
10967 c = decode_dollar_squote();
10969 USTPUTC('\\', out);
10970 c = (unsigned char)c;
10976 case CBACK: /* backslash */
10977 c = pgetc_without_PEOA();
10979 USTPUTC(CTLESC, out);
10980 USTPUTC('\\', out);
10982 } else if (c == '\n') {
10986 #if ENABLE_ASH_EXPAND_PRMT
10987 if (c == '$' && pssyntax) {
10988 USTPUTC(CTLESC, out);
10989 USTPUTC('\\', out);
10992 if (dblquote && c != '\\'
10993 && c != '`' && c != '$'
10994 && (c != '"' || eofmark != NULL)
10996 USTPUTC(CTLESC, out);
10997 USTPUTC('\\', out);
10999 if (SIT(c, SQSYNTAX) == CCTL)
11000 USTPUTC(CTLESC, out);
11008 if (eofmark == NULL) {
11009 USTPUTC(CTLQUOTEMARK, out);
11017 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11018 if (eofmark != NULL && arinest == 0
11023 if (dqvarnest == 0) {
11024 syntax = BASESYNTAX;
11031 case CVAR: /* '$' */
11032 PARSESUB(); /* parse substitution */
11034 case CENDVAR: /* '}' */
11037 if (dqvarnest > 0) {
11040 USTPUTC(CTLENDVAR, out);
11045 #if ENABLE_SH_MATH_SUPPORT
11046 case CLP: /* '(' in arithmetic */
11050 case CRP: /* ')' in arithmetic */
11051 if (parenlevel > 0) {
11055 if (pgetc() == ')') {
11056 if (--arinest == 0) {
11057 USTPUTC(CTLENDARI, out);
11058 syntax = prevsyntax;
11059 dblquote = (syntax == DQSYNTAX);
11064 * unbalanced parens
11065 * (don't 2nd guess - no error)
11073 case CBQUOTE: /* '`' */
11077 goto endword; /* exit outer loop */
11081 if (varnest == 0) {
11082 #if ENABLE_ASH_BASH_COMPAT
11084 if (pgetc() == '>')
11085 c = 0x100 + '>'; /* flag &> */
11089 goto endword; /* exit outer loop */
11091 IF_ASH_ALIAS(if (c != PEOA))
11099 #if ENABLE_SH_MATH_SUPPORT
11100 if (syntax == ARISYNTAX)
11101 raise_error_syntax("missing '))'");
11103 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11104 raise_error_syntax("unterminated quoted string");
11105 if (varnest != 0) {
11106 startlinno = g_parsefile->linno;
11108 raise_error_syntax("missing '}'");
11110 USTPUTC('\0', out);
11111 len = out - (char *)stackblock();
11112 out = stackblock();
11113 if (eofmark == NULL) {
11114 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11117 if (isdigit_str9(out)) {
11118 PARSEREDIR(); /* passed as params: out, c */
11119 lasttoken = TREDIR;
11122 /* else: non-number X seen, interpret it
11123 * as "NNNX>file" = "NNNX >file" */
11127 quoteflag = quotef;
11128 backquotelist = bqlist;
11129 grabstackblock(len);
11133 /* end of readtoken routine */
11136 * Check to see whether we are at the end of the here document. When this
11137 * is called, c is set to the first character of the next input line. If
11138 * we are at the end of the here document, this routine sets the c to PEOF.
11142 #if ENABLE_ASH_ALIAS
11144 c = pgetc_without_PEOA();
11147 while (c == '\t') {
11148 c = pgetc_without_PEOA();
11151 if (c == *eofmark) {
11152 if (pfgets(line, sizeof(line)) != NULL) {
11156 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11158 if (*p == '\n' && *q == '\0') {
11160 g_parsefile->linno++;
11161 needprompt = doprompt;
11163 pushstring(line, NULL);
11168 goto checkend_return;
11172 * Parse a redirection operator. The variable "out" points to a string
11173 * specifying the fd to be redirected. The variable "c" contains the
11174 * first character of the redirection operator.
11177 /* out is already checked to be a valid number or "" */
11178 int fd = (*out == '\0' ? -1 : atoi(out));
11181 np = stzalloc(sizeof(struct nfile));
11186 np->type = NAPPEND;
11188 np->type = NCLOBBER;
11191 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11197 #if ENABLE_ASH_BASH_COMPAT
11198 else if (c == 0x100 + '>') { /* this flags &> redirection */
11200 pgetc(); /* this is '>', no need to check */
11204 else { /* c == '<' */
11205 /*np->nfile.fd = 0; - stzalloc did it */
11209 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11210 np = stzalloc(sizeof(struct nhere));
11211 /*np->nfile.fd = 0; - stzalloc did it */
11214 heredoc = stzalloc(sizeof(struct heredoc));
11215 heredoc->here = np;
11218 heredoc->striptabs = 1;
11220 /*heredoc->striptabs = 0; - stzalloc did it */
11226 np->type = NFROMFD;
11230 np->type = NFROMTO;
11242 goto parseredir_return;
11246 * Parse a substitution. At this point, we have read the dollar sign
11247 * and nothing else.
11250 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11251 * (assuming ascii char codes, as the original implementation did) */
11252 #define is_special(c) \
11253 (((unsigned)(c) - 33 < 32) \
11254 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11256 unsigned char subtype;
11260 static const char types[] ALIGN1 = "}-+?=";
11263 if (c > 255 /* PEOA or PEOF */
11264 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11266 #if ENABLE_ASH_BASH_COMPAT
11268 bash_dollar_squote = 1;
11273 } else if (c == '(') { /* $(command) or $((arith)) */
11274 if (pgetc() == '(') {
11275 #if ENABLE_SH_MATH_SUPPORT
11278 raise_error_syntax("you disabled math support for $((arith)) syntax");
11285 USTPUTC(CTLVAR, out);
11286 typeloc = out - (char *)stackblock();
11287 USTPUTC(VSNORMAL, out);
11288 subtype = VSNORMAL;
11296 subtype = VSLENGTH;
11300 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11304 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11305 } else if (isdigit(c)) {
11309 } while (isdigit(c));
11310 } else if (is_special(c)) {
11315 raise_error_syntax("bad substitution");
11317 if (c != '}' && subtype == VSLENGTH)
11322 if (subtype == 0) {
11326 #if ENABLE_ASH_BASH_COMPAT
11327 if (c == ':' || c == '$' || isdigit(c)) {
11329 subtype = VSSUBSTR;
11336 p = strchr(types, c);
11339 subtype = p - types + VSNORMAL;
11344 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11352 #if ENABLE_ASH_BASH_COMPAT
11354 subtype = VSREPLACE;
11357 subtype++; /* VSREPLACEALL */
11366 if (dblquote || arinest)
11368 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11369 if (subtype != VSNORMAL) {
11371 if (dblquote || arinest) {
11376 goto parsesub_return;
11380 * Called to parse command substitutions. Newstyle is set if the command
11381 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11382 * list of commands (passed by reference), and savelen is the number of
11383 * characters on the top of the stack which must be preserved.
11386 struct nodelist **nlpp;
11389 char *volatile str;
11390 struct jmploc jmploc;
11391 struct jmploc *volatile savehandler;
11393 smallint saveprompt = 0;
11396 (void) &saveprompt;
11398 savepbq = parsebackquote;
11399 if (setjmp(jmploc.loc)) {
11401 parsebackquote = 0;
11402 exception_handler = savehandler;
11403 longjmp(exception_handler->loc, 1);
11407 savelen = out - (char *)stackblock();
11409 str = ckmalloc(savelen);
11410 memcpy(str, stackblock(), savelen);
11412 savehandler = exception_handler;
11413 exception_handler = &jmploc;
11416 /* We must read until the closing backquote, giving special
11417 treatment to some slashes, and then push the string and
11418 reread it as input, interpreting it normally. */
11425 STARTSTACKSTR(pout);
11438 g_parsefile->linno++;
11442 * If eating a newline, avoid putting
11443 * the newline into the new character
11444 * stream (via the STPUTC after the
11449 if (pc != '\\' && pc != '`' && pc != '$'
11450 && (!dblquote || pc != '"')
11452 STPUTC('\\', pout);
11454 if (pc <= 255 /* not PEOA or PEOF */) {
11460 IF_ASH_ALIAS(case PEOA:)
11461 startlinno = g_parsefile->linno;
11462 raise_error_syntax("EOF in backquote substitution");
11465 g_parsefile->linno++;
11466 needprompt = doprompt;
11475 STPUTC('\0', pout);
11476 psavelen = pout - (char *)stackblock();
11477 if (psavelen > 0) {
11478 pstr = grabstackstr(pout);
11479 setinputstring(pstr);
11484 nlpp = &(*nlpp)->next;
11485 *nlpp = stzalloc(sizeof(**nlpp));
11486 /* (*nlpp)->next = NULL; - stzalloc did it */
11487 parsebackquote = oldstyle;
11490 saveprompt = doprompt;
11497 doprompt = saveprompt;
11498 else if (readtoken() != TRP)
11499 raise_error_unexpected_syntax(TRP);
11504 * Start reading from old file again, ignoring any pushed back
11505 * tokens left from the backquote parsing
11510 while (stackblocksize() <= savelen)
11512 STARTSTACKSTR(out);
11514 memcpy(out, str, savelen);
11515 STADJUST(savelen, out);
11521 parsebackquote = savepbq;
11522 exception_handler = savehandler;
11523 if (arinest || dblquote)
11524 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11526 USTPUTC(CTLBACKQ, out);
11528 goto parsebackq_oldreturn;
11529 goto parsebackq_newreturn;
11532 #if ENABLE_SH_MATH_SUPPORT
11534 * Parse an arithmetic expansion (indicate start of one and set state)
11537 if (++arinest == 1) {
11538 prevsyntax = syntax;
11539 syntax = ARISYNTAX;
11540 USTPUTC(CTLARI, out);
11547 * we collapse embedded arithmetic expansion to
11548 * parenthesis, which should be equivalent
11552 goto parsearith_return;
11556 } /* end of readtoken */
11559 * Read the next input token.
11560 * If the token is a word, we set backquotelist to the list of cmds in
11561 * backquotes. We set quoteflag to true if any part of the word was
11563 * If the token is TREDIR, then we set redirnode to a structure containing
11565 * In all cases, the variable startlinno is set to the number of the line
11566 * on which the token starts.
11568 * [Change comment: here documents and internal procedures]
11569 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11570 * word parsing code into a separate routine. In this case, readtoken
11571 * doesn't need to have any internal procedures, but parseword does.
11572 * We could also make parseoperator in essence the main routine, and
11573 * have parseword (readtoken1?) handle both words and redirection.]
11575 #define NEW_xxreadtoken
11576 #ifdef NEW_xxreadtoken
11577 /* singles must be first! */
11578 static const char xxreadtoken_chars[7] ALIGN1 = {
11579 '\n', '(', ')', /* singles */
11580 '&', '|', ';', /* doubles */
11584 #define xxreadtoken_singles 3
11585 #define xxreadtoken_doubles 3
11587 static const char xxreadtoken_tokens[] ALIGN1 = {
11588 TNL, TLP, TRP, /* only single occurrence allowed */
11589 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11590 TEOF, /* corresponds to trailing nul */
11591 TAND, TOR, TENDCASE /* if double occurrence */
11606 startlinno = g_parsefile->linno;
11607 for (;;) { /* until token or start of word found */
11609 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11613 while ((c = pgetc()) != '\n' && c != PEOF)
11616 } else if (c == '\\') {
11617 if (pgetc() != '\n') {
11619 break; /* return readtoken1(...) */
11621 startlinno = ++g_parsefile->linno;
11627 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11630 g_parsefile->linno++;
11631 needprompt = doprompt;
11634 p = strchr(xxreadtoken_chars, c);
11636 break; /* return readtoken1(...) */
11638 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11640 if (cc == c) { /* double occurrence? */
11641 p += xxreadtoken_doubles + 1;
11644 #if ENABLE_ASH_BASH_COMPAT
11645 if (c == '&' && cc == '>') /* &> */
11646 break; /* return readtoken1(...) */
11651 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11656 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11658 #else /* old xxreadtoken */
11659 #define RETURN(token) return lasttoken = token
11672 startlinno = g_parsefile->linno;
11673 for (;;) { /* until token or start of word found */
11676 case ' ': case '\t':
11677 IF_ASH_ALIAS(case PEOA:)
11680 while ((c = pgetc()) != '\n' && c != PEOF)
11685 if (pgetc() == '\n') {
11686 startlinno = ++g_parsefile->linno;
11694 g_parsefile->linno++;
11695 needprompt = doprompt;
11700 if (pgetc() == '&')
11705 if (pgetc() == '|')
11710 if (pgetc() == ';')
11723 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11726 #endif /* old xxreadtoken */
11733 smallint alreadyseen = tokpushback;
11736 #if ENABLE_ASH_ALIAS
11745 if (checkkwd & CHKNL) {
11752 if (t != TWORD || quoteflag) {
11757 * check for keywords
11759 if (checkkwd & CHKKWD) {
11760 const char *const *pp;
11762 pp = findkwd(wordtext);
11764 lasttoken = t = pp - tokname_array;
11765 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
11770 if (checkkwd & CHKALIAS) {
11771 #if ENABLE_ASH_ALIAS
11773 ap = lookupalias(wordtext, 1);
11776 pushstring(ap->val, ap);
11786 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11788 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11800 return tokname_array[t][0];
11804 * Read and parse a command. Returns NODE_EOF on end of file.
11805 * (NULL is a valid parse tree indicating a blank line.)
11807 static union node *
11808 parsecmd(int interact)
11813 doprompt = interact;
11815 setprompt(doprompt);
11827 * Input any here documents.
11832 struct heredoc *here;
11835 here = heredoclist;
11836 heredoclist = NULL;
11842 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11843 here->eofmark, here->striptabs);
11844 n = stzalloc(sizeof(struct narg));
11845 n->narg.type = NARG;
11846 /*n->narg.next = NULL; - stzalloc did it */
11847 n->narg.text = wordtext;
11848 n->narg.backquote = backquotelist;
11849 here->here->nhere.doc = n;
11856 * called by editline -- any expansions to the prompt should be added here.
11858 #if ENABLE_ASH_EXPAND_PRMT
11859 static const char *
11860 expandstr(const char *ps)
11864 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11865 * and token processing _can_ alter it (delete NULs etc). */
11866 setinputstring((char *)ps);
11867 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11870 n.narg.type = NARG;
11871 n.narg.next = NULL;
11872 n.narg.text = wordtext;
11873 n.narg.backquote = backquotelist;
11875 expandarg(&n, NULL, 0);
11876 return stackblock();
11881 * Execute a command or commands contained in a string.
11884 evalstring(char *s, int mask)
11887 struct stackmark smark;
11891 setstackmark(&smark);
11894 while ((n = parsecmd(0)) != NODE_EOF) {
11896 popstackmark(&smark);
11909 * The eval command.
11911 static int FAST_FUNC
11912 evalcmd(int argc UNUSED_PARAM, char **argv)
11921 STARTSTACKSTR(concat);
11923 concat = stack_putstr(p, concat);
11927 STPUTC(' ', concat);
11929 STPUTC('\0', concat);
11930 p = grabstackstr(concat);
11932 evalstring(p, ~SKIPEVAL);
11939 * Read and execute commands.
11940 * "Top" is nonzero for the top level command loop;
11941 * it turns on prompting if the shell is interactive.
11947 struct stackmark smark;
11951 TRACE(("cmdloop(%d) called\n", top));
11955 setstackmark(&smark);
11958 showjobs(stderr, SHOW_CHANGED);
11961 if (iflag && top) {
11963 #if ENABLE_ASH_MAIL
11967 n = parsecmd(inter);
11969 if (DEBUG > 2 && debug && (n != NODE_EOF))
11972 if (n == NODE_EOF) {
11973 if (!top || numeof >= 50)
11975 if (!stoppedjobs()) {
11978 out2str("\nUse \"exit\" to leave shell.\n");
11981 } else if (nflag == 0) {
11982 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11987 popstackmark(&smark);
11992 return skip & SKIPEVAL;
11999 * Take commands from a file. To be compatible we should do a path
12000 * search for the file, which is necessary to find sub-commands.
12003 find_dot_file(char *name)
12006 const char *path = pathval();
12009 /* don't try this for absolute or relative paths */
12010 if (strchr(name, '/'))
12013 /* IIRC standards do not say whether . is to be searched.
12014 * And it is even smaller this way, making it unconditional for now:
12016 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12021 while ((fullname = path_advance(&path, name)) != NULL) {
12023 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12025 * Don't bother freeing here, since it will
12026 * be freed by the caller.
12030 if (fullname != name)
12031 stunalloc(fullname);
12034 /* not found in the PATH */
12035 ash_msg_and_raise_error("%s: not found", name);
12039 static int FAST_FUNC
12040 dotcmd(int argc, char **argv)
12043 struct strlist *sp;
12044 volatile struct shparam saveparam;
12046 for (sp = cmdenviron; sp; sp = sp->next)
12047 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12050 /* bash says: "bash: .: filename argument required" */
12051 return 2; /* bash compat */
12054 /* "false; . empty_file; echo $?" should print 0, not 1: */
12057 fullname = find_dot_file(argv[1]);
12061 if (argc) { /* argc > 0, argv[0] != NULL */
12062 saveparam = shellparam;
12063 shellparam.malloced = 0;
12064 shellparam.nparam = argc;
12065 shellparam.p = argv;
12068 setinputfile(fullname, INPUT_PUSH_FILE);
12069 commandname = fullname;
12074 freeparam(&shellparam);
12075 shellparam = saveparam;
12081 static int FAST_FUNC
12082 exitcmd(int argc UNUSED_PARAM, char **argv)
12087 exitstatus = number(argv[1]);
12088 raise_exception(EXEXIT);
12093 * Read a file containing shell functions.
12096 readcmdfile(char *name)
12098 setinputfile(name, INPUT_PUSH_FILE);
12104 /* ============ find_command inplementation */
12107 * Resolve a command name. If you change this routine, you may have to
12108 * change the shellexec routine as well.
12111 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12113 struct tblentry *cmdp;
12120 struct builtincmd *bcmd;
12122 /* If name contains a slash, don't use PATH or hash table */
12123 if (strchr(name, '/') != NULL) {
12124 entry->u.index = -1;
12125 if (act & DO_ABS) {
12126 while (stat(name, &statb) < 0) {
12128 if (errno == EINTR)
12131 entry->cmdtype = CMDUNKNOWN;
12135 entry->cmdtype = CMDNORMAL;
12139 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12141 updatetbl = (path == pathval());
12144 if (strstr(path, "%builtin") != NULL)
12145 act |= DO_ALTBLTIN;
12148 /* If name is in the table, check answer will be ok */
12149 cmdp = cmdlookup(name, 0);
12150 if (cmdp != NULL) {
12153 switch (cmdp->cmdtype) {
12171 } else if (cmdp->rehash == 0)
12172 /* if not invalidated by cd, we're done */
12176 /* If %builtin not in path, check for builtin next */
12177 bcmd = find_builtin(name);
12179 if (IS_BUILTIN_REGULAR(bcmd))
12180 goto builtin_success;
12181 if (act & DO_ALTPATH) {
12182 if (!(act & DO_ALTBLTIN))
12183 goto builtin_success;
12184 } else if (builtinloc <= 0) {
12185 goto builtin_success;
12189 #if ENABLE_FEATURE_SH_STANDALONE
12191 int applet_no = find_applet_by_name(name);
12192 if (applet_no >= 0) {
12193 entry->cmdtype = CMDNORMAL;
12194 entry->u.index = -2 - applet_no;
12200 /* We have to search path. */
12201 prev = -1; /* where to start */
12202 if (cmdp && cmdp->rehash) { /* doing a rehash */
12203 if (cmdp->cmdtype == CMDBUILTIN)
12206 prev = cmdp->param.index;
12212 while ((fullname = path_advance(&path, name)) != NULL) {
12213 stunalloc(fullname);
12214 /* NB: code below will still use fullname
12215 * despite it being "unallocated" */
12218 if (prefix(pathopt, "builtin")) {
12220 goto builtin_success;
12223 if ((act & DO_NOFUNC)
12224 || !prefix(pathopt, "func")
12225 ) { /* ignore unimplemented options */
12229 /* if rehash, don't redo absolute path names */
12230 if (fullname[0] == '/' && idx <= prev) {
12233 TRACE(("searchexec \"%s\": no change\n", name));
12236 while (stat(fullname, &statb) < 0) {
12238 if (errno == EINTR)
12241 if (errno != ENOENT && errno != ENOTDIR)
12245 e = EACCES; /* if we fail, this will be the error */
12246 if (!S_ISREG(statb.st_mode))
12248 if (pathopt) { /* this is a %func directory */
12249 stalloc(strlen(fullname) + 1);
12250 /* NB: stalloc will return space pointed by fullname
12251 * (because we don't have any intervening allocations
12252 * between stunalloc above and this stalloc) */
12253 readcmdfile(fullname);
12254 cmdp = cmdlookup(name, 0);
12255 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12256 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12257 stunalloc(fullname);
12260 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12262 entry->cmdtype = CMDNORMAL;
12263 entry->u.index = idx;
12267 cmdp = cmdlookup(name, 1);
12268 cmdp->cmdtype = CMDNORMAL;
12269 cmdp->param.index = idx;
12274 /* We failed. If there was an entry for this command, delete it */
12275 if (cmdp && updatetbl)
12276 delete_cmd_entry();
12278 ash_msg("%s: %s", name, errmsg(e, "not found"));
12279 entry->cmdtype = CMDUNKNOWN;
12284 entry->cmdtype = CMDBUILTIN;
12285 entry->u.cmd = bcmd;
12289 cmdp = cmdlookup(name, 1);
12290 cmdp->cmdtype = CMDBUILTIN;
12291 cmdp->param.cmd = bcmd;
12295 entry->cmdtype = cmdp->cmdtype;
12296 entry->u = cmdp->param;
12300 /* ============ trap.c */
12303 * The trap builtin.
12305 static int FAST_FUNC
12306 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12310 int signo, exitcode;
12315 for (signo = 0; signo < NSIG; signo++) {
12316 char *tr = trap_ptr[signo];
12318 /* note: bash adds "SIG", but only if invoked
12319 * as "bash". If called as "sh", or if set -o posix,
12320 * then it prints short signal names.
12321 * We are printing short names: */
12322 out1fmt("trap -- %s %s\n",
12324 get_signame(signo));
12325 /* trap_ptr != trap only if we are in special-cased `trap` code.
12326 * In this case, we will exit very soon, no need to free(). */
12327 /* if (trap_ptr != trap && tp[0]) */
12332 if (trap_ptr != trap) {
12345 signo = get_signum(*ap);
12347 /* Mimic bash message exactly */
12348 ash_msg("%s: invalid signal specification", *ap);
12354 if (LONE_DASH(action))
12357 action = ckstrdup(action);
12361 may_have_traps = 1;
12362 trap[signo] = action;
12373 /* ============ Builtins */
12375 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12377 * Lists available builtins
12379 static int FAST_FUNC
12380 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12386 "Built-in commands:\n"
12387 "------------------\n");
12388 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12389 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12390 builtintab[i].name + 1);
12396 #if ENABLE_FEATURE_SH_STANDALONE
12398 const char *a = applet_names;
12400 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12405 a += strlen(a) + 1;
12410 return EXIT_SUCCESS;
12412 #endif /* FEATURE_SH_EXTRA_QUIET */
12415 * The export and readonly commands.
12417 static int FAST_FUNC
12418 exportcmd(int argc UNUSED_PARAM, char **argv)
12424 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12426 if (nextopt("p") != 'p') {
12431 p = strchr(name, '=');
12435 vp = *findvar(hashvar(name), name);
12441 setvar(name, p, flag);
12442 } while ((name = *++aptr) != NULL);
12446 showvars(argv[0], flag, 0);
12451 * Delete a function if it exists.
12454 unsetfunc(const char *name)
12456 struct tblentry *cmdp;
12458 cmdp = cmdlookup(name, 0);
12459 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12460 delete_cmd_entry();
12464 * The unset builtin command. We unset the function before we unset the
12465 * variable to allow a function to be unset when there is a readonly variable
12466 * with the same name.
12468 static int FAST_FUNC
12469 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12476 while ((i = nextopt("vf")) != '\0') {
12480 for (ap = argptr; *ap; ap++) {
12496 #include <sys/times.h>
12498 static const unsigned char timescmd_str[] ALIGN1 = {
12499 ' ', offsetof(struct tms, tms_utime),
12500 '\n', offsetof(struct tms, tms_stime),
12501 ' ', offsetof(struct tms, tms_cutime),
12502 '\n', offsetof(struct tms, tms_cstime),
12506 static int FAST_FUNC
12507 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12509 long clk_tck, s, t;
12510 const unsigned char *p;
12513 clk_tck = sysconf(_SC_CLK_TCK);
12518 t = *(clock_t *)(((char *) &buf) + p[1]);
12520 out1fmt("%ldm%ld.%.3lds%c",
12522 ((t - s * clk_tck) * 1000) / clk_tck,
12524 } while (*(p += 2));
12529 #if ENABLE_SH_MATH_SUPPORT
12531 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12532 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12534 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12536 static int FAST_FUNC
12537 letcmd(int argc UNUSED_PARAM, char **argv)
12543 ash_msg_and_raise_error("expression expected");
12545 i = ash_arith(*argv);
12550 #endif /* SH_MATH_SUPPORT */
12553 /* ============ miscbltin.c
12555 * Miscellaneous builtins.
12560 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
12561 typedef enum __rlimit_resource rlim_t;
12565 * The read builtin. Options:
12566 * -r Do not interpret '\' specially
12567 * -s Turn off echo (tty only)
12568 * -n NCHARS Read NCHARS max
12569 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12570 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12571 * -u FD Read from given FD instead of fd 0
12572 * This uses unbuffered input, which may be avoidable in some cases.
12573 * TODO: bash also has:
12574 * -a ARRAY Read into array[0],[1],etc
12575 * -d DELIM End on DELIM char, not newline
12576 * -e Use line editing (tty only)
12578 static int FAST_FUNC
12579 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12581 char *opt_n = NULL;
12582 char *opt_p = NULL;
12583 char *opt_t = NULL;
12584 char *opt_u = NULL;
12585 int read_flags = 0;
12589 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12598 read_flags |= BUILTIN_READ_SILENT;
12604 read_flags |= BUILTIN_READ_RAW;
12614 r = shell_builtin_read(setvar2,
12616 bltinlookup("IFS"), /* can be NULL */
12624 if ((uintptr_t)r > 1)
12625 ash_msg_and_raise_error(r);
12627 return (uintptr_t)r;
12630 static int FAST_FUNC
12631 umaskcmd(int argc UNUSED_PARAM, char **argv)
12633 static const char permuser[3] ALIGN1 = "ugo";
12634 static const char permmode[3] ALIGN1 = "rwx";
12635 static const short permmask[] ALIGN2 = {
12636 S_IRUSR, S_IWUSR, S_IXUSR,
12637 S_IRGRP, S_IWGRP, S_IXGRP,
12638 S_IROTH, S_IWOTH, S_IXOTH
12641 /* TODO: use bb_parse_mode() instead */
12646 int symbolic_mode = 0;
12648 while (nextopt("S") != '\0') {
12659 if (symbolic_mode) {
12663 for (i = 0; i < 3; i++) {
12666 *p++ = permuser[i];
12668 for (j = 0; j < 3; j++) {
12669 if ((mask & permmask[3 * i + j]) == 0) {
12670 *p++ = permmode[j];
12678 out1fmt("%.4o\n", mask);
12681 if (isdigit((unsigned char) *ap)) {
12684 if (*ap >= '8' || *ap < '0')
12685 ash_msg_and_raise_error(msg_illnum, argv[1]);
12686 mask = (mask << 3) + (*ap - '0');
12687 } while (*++ap != '\0');
12690 mask = ~mask & 0777;
12691 if (!bb_parse_mode(ap, &mask)) {
12692 ash_msg_and_raise_error("illegal mode: %s", ap);
12694 umask(~mask & 0777);
12700 static int FAST_FUNC
12701 ulimitcmd(int argc UNUSED_PARAM, char **argv)
12703 return shell_builtin_ulimit(argv);
12706 /* ============ main() and helpers */
12709 * Called to exit the shell.
12711 static void exitshell(void) NORETURN;
12719 status = exitstatus;
12720 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12721 if (setjmp(loc.loc)) {
12722 if (exception_type == EXEXIT)
12723 /* dash bug: it just does _exit(exitstatus) here
12724 * but we have to do setjobctl(0) first!
12725 * (bug is still not fixed in dash-0.5.3 - if you run dash
12726 * under Midnight Commander, on exit from dash MC is backgrounded) */
12727 status = exitstatus;
12730 exception_handler = &loc;
12737 flush_stdout_stderr();
12747 /* from input.c: */
12748 /* we will never free this */
12749 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
12752 signal(SIGCHLD, SIG_DFL);
12753 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12754 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12756 signal(SIGHUP, SIG_DFL);
12762 struct stat st1, st2;
12765 for (envp = environ; envp && *envp; envp++) {
12766 if (strchr(*envp, '=')) {
12767 setvareq(*envp, VEXPORT|VTEXTFIXED);
12771 setvar("PPID", utoa(getppid()), 0);
12773 p = lookupvar("PWD");
12775 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12776 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12783 * Process the shell command line arguments.
12786 procargs(char **argv)
12789 const char *xminusc;
12794 /* if (xargv[0]) - mmm, this is always true! */
12796 for (i = 0; i < NOPTS; i++)
12800 /* it already printed err message */
12801 raise_exception(EXERROR);
12805 if (*xargv == NULL) {
12807 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12810 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12814 for (i = 0; i < NOPTS; i++)
12815 if (optlist[i] == 2)
12820 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12825 } else if (!sflag) {
12826 setinputfile(*xargv, 0);
12829 commandname = arg0;
12832 shellparam.p = xargv;
12833 #if ENABLE_ASH_GETOPTS
12834 shellparam.optind = 1;
12835 shellparam.optoff = -1;
12837 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
12839 shellparam.nparam++;
12846 * Read /etc/profile or .profile.
12849 read_profile(const char *name)
12853 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12862 * This routine is called when an error or an interrupt occurs in an
12863 * interactive shell and control is returned to the main command loop.
12871 /* from input.c: */
12872 g_parsefile->left_in_buffer = 0;
12873 g_parsefile->left_in_line = 0; /* clear input buffer */
12875 /* from parser.c: */
12878 /* from redir.c: */
12879 clearredir(/*drop:*/ 0);
12883 static short profile_buf[16384];
12884 extern int etext();
12888 * Main routine. We initialize things, parse the arguments, execute
12889 * profiles if we're a login shell, and then call cmdloop to execute
12890 * commands. The setjmp call sets up the location to jump to when an
12891 * exception occurs. When an exception occurs the variable "state"
12892 * is used to figure out how far we had gotten.
12894 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
12895 int ash_main(int argc UNUSED_PARAM, char **argv)
12897 const char *shinit;
12898 volatile smallint state;
12899 struct jmploc jmploc;
12900 struct stackmark smark;
12902 /* Initialize global data */
12906 #if ENABLE_ASH_ALIAS
12912 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12915 #if ENABLE_FEATURE_EDITING
12916 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12919 if (setjmp(jmploc.loc)) {
12925 e = exception_type;
12929 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12932 outcslow('\n', stderr);
12934 popstackmark(&smark);
12935 FORCE_INT_ON; /* enable interrupts */
12944 exception_handler = &jmploc;
12947 TRACE(("Shell args: "));
12948 trace_puts_args(argv);
12950 rootpid = getpid();
12953 setstackmark(&smark);
12956 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
12958 const char *hp = lookupvar("HISTFILE");
12961 hp = lookupvar("HOME");
12963 char *defhp = concat_path_file(hp, ".ash_history");
12964 setvar("HISTFILE", defhp, 0);
12970 if (/* argv[0] && */ argv[0][0] == '-')
12974 read_profile("/etc/profile");
12977 read_profile(".profile");
12983 getuid() == geteuid() && getgid() == getegid() &&
12987 shinit = lookupvar("ENV");
12988 if (shinit != NULL && *shinit != '\0') {
12989 read_profile(shinit);
12995 /* evalstring pushes parsefile stack.
12996 * Ensure we don't falsely claim that 0 (stdin)
12997 * is one of stacked source fds.
12998 * Testcase: ash -c 'exec 1>&0' must not complain. */
13000 g_parsefile->fd = -1;
13001 evalstring(minusc, 0);
13004 if (sflag || minusc == NULL) {
13005 #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13007 const char *hp = lookupvar("HISTFILE");
13009 line_input_state->hist_file = hp;
13012 state4: /* XXX ??? - why isn't this before the "if" statement */
13020 extern void _mcleanup(void);
13030 * Copyright (c) 1989, 1991, 1993, 1994
13031 * The Regents of the University of California. All rights reserved.
13033 * This code is derived from software contributed to Berkeley by
13034 * Kenneth Almquist.
13036 * Redistribution and use in source and binary forms, with or without
13037 * modification, are permitted provided that the following conditions
13039 * 1. Redistributions of source code must retain the above copyright
13040 * notice, this list of conditions and the following disclaimer.
13041 * 2. Redistributions in binary form must reproduce the above copyright
13042 * notice, this list of conditions and the following disclaimer in the
13043 * documentation and/or other materials provided with the distribution.
13044 * 3. Neither the name of the University nor the names of its contributors
13045 * may be used to endorse or promote products derived from this software
13046 * without specific prior written permission.
13048 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13049 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13050 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13051 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13052 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13053 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13054 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13055 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13056 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13057 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF