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"
52 #if ENABLE_ASH_RANDOM_SUPPORT
55 # define CLEAR_RANDOM_T(rnd) ((void)0)
58 #define SKIP_definitions 1
59 #include "applet_tables.h"
60 #undef SKIP_definitions
62 /* STANDALONE does not make sense, and won't compile */
63 # undef CONFIG_FEATURE_SH_STANDALONE
64 # undef ENABLE_FEATURE_SH_STANDALONE
65 # undef IF_FEATURE_SH_STANDALONE
66 # undef IF_NOT_FEATURE_SH_STANDALONE
67 # define ENABLE_FEATURE_SH_STANDALONE 0
68 # define IF_FEATURE_SH_STANDALONE(...)
69 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
73 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
77 # error "Do not even bother, ash will not run on NOMMU machine"
81 /* ============ Hash table sizes. Configurable. */
85 #define CMDTABLESIZE 31 /* should be prime */
88 /* ============ Shell options */
90 static const char *const optletters_optnames[] = {
105 #if ENABLE_ASH_BASH_COMPAT
114 #define optletters(n) optletters_optnames[n][0]
115 #define optnames(n) (optletters_optnames[n] + 1)
117 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
120 /* ============ Misc data */
122 #define msg_illnum "Illegal number: %s"
125 * We enclose jmp_buf in a structure so that we can declare pointers to
126 * jump locations. The global variable handler contains the location to
127 * jump to when an exception occurs, and the global variable exception_type
128 * contains a code identifying the exception. To implement nested
129 * exception handlers, the user should save the value of handler on entry
130 * to an inner scope, set handler to point to a jmploc structure for the
131 * inner scope, and restore handler on exit from the scope.
137 struct globals_misc {
138 /* pid of main shell */
140 /* shell level: 0 for the main shell, 1 for its children, and so on */
142 #define rootshell (!shlvl)
143 char *minusc; /* argument to -c option */
145 char *curdir; // = nullstr; /* current working directory */
146 char *physdir; // = nullstr; /* physical working directory */
148 char *arg0; /* value of $0 */
150 struct jmploc *exception_handler;
152 volatile int suppress_int; /* counter */
153 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
154 /* last pending signal */
155 volatile /*sig_atomic_t*/ smallint pending_sig;
156 smallint exception_type; /* kind of exception (0..5) */
158 #define EXINT 0 /* SIGINT received */
159 #define EXERROR 1 /* a generic error */
160 #define EXSHELLPROC 2 /* execute a shell procedure */
161 #define EXEXEC 3 /* command execution failed */
162 #define EXEXIT 4 /* exit the shell */
163 #define EXSIG 5 /* trapped signal in wait(1) */
166 char nullstr[1]; /* zero length string */
169 #define eflag optlist[0]
170 #define fflag optlist[1]
171 #define Iflag optlist[2]
172 #define iflag optlist[3]
173 #define mflag optlist[4]
174 #define nflag optlist[5]
175 #define sflag optlist[6]
176 #define xflag optlist[7]
177 #define vflag optlist[8]
178 #define Cflag optlist[9]
179 #define aflag optlist[10]
180 #define bflag optlist[11]
181 #define uflag optlist[12]
182 #define viflag optlist[13]
183 #if ENABLE_ASH_BASH_COMPAT
184 # define pipefail optlist[14]
189 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
190 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
193 /* trap handler commands */
195 * Sigmode records the current value of the signal handlers for the various
196 * modes. A value of zero means that the current handler is not known.
197 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
199 char sigmode[NSIG - 1];
200 #define S_DFL 1 /* default signal handling (SIG_DFL) */
201 #define S_CATCH 2 /* signal is caught */
202 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
203 #define S_HARD_IGN 4 /* signal is ignored permenantly */
205 /* indicates specified signal received */
206 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
207 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
209 char **trap_ptr; /* used only by "trap hack" */
211 /* Rarely referenced stuff */
212 #if ENABLE_ASH_RANDOM_SUPPORT
215 pid_t backgndpid; /* pid of last background process */
216 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
218 extern struct globals_misc *const ash_ptr_to_globals_misc;
219 #define G_misc (*ash_ptr_to_globals_misc)
220 #define rootpid (G_misc.rootpid )
221 #define shlvl (G_misc.shlvl )
222 #define minusc (G_misc.minusc )
223 #define curdir (G_misc.curdir )
224 #define physdir (G_misc.physdir )
225 #define arg0 (G_misc.arg0 )
226 #define exception_handler (G_misc.exception_handler)
227 #define exception_type (G_misc.exception_type )
228 #define suppress_int (G_misc.suppress_int )
229 #define pending_int (G_misc.pending_int )
230 #define pending_sig (G_misc.pending_sig )
231 #define isloginsh (G_misc.isloginsh )
232 #define nullstr (G_misc.nullstr )
233 #define optlist (G_misc.optlist )
234 #define sigmode (G_misc.sigmode )
235 #define gotsig (G_misc.gotsig )
236 #define may_have_traps (G_misc.may_have_traps )
237 #define trap (G_misc.trap )
238 #define trap_ptr (G_misc.trap_ptr )
239 #define random_gen (G_misc.random_gen )
240 #define backgndpid (G_misc.backgndpid )
241 #define job_warning (G_misc.job_warning)
242 #define INIT_G_misc() do { \
243 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
251 /* ============ DEBUG */
253 static void trace_printf(const char *fmt, ...);
254 static void trace_vprintf(const char *fmt, va_list va);
255 # define TRACE(param) trace_printf param
256 # define TRACEV(param) trace_vprintf param
257 # define close(fd) do { \
259 if (close(dfd) < 0) \
260 bb_error_msg("bug on %d: closing %d(0x%x)", \
261 __LINE__, dfd, dfd); \
264 # define TRACE(param)
265 # define TRACEV(param)
269 /* ============ Utility functions */
270 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
272 static int isdigit_str9(const char *str)
274 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
275 while (--maxlen && isdigit(*str))
277 return (*str == '\0');
280 static const char *var_end(const char *var)
289 /* ============ Interrupts / exceptions */
291 * These macros allow the user to suspend the handling of interrupt signals
292 * over a period of time. This is similar to SIGHOLD or to sigblock, but
293 * much more efficient and portable. (But hacking the kernel is so much
294 * more fun than worrying about efficiency and portability. :-))
296 #define INT_OFF do { \
302 * Called to raise an exception. Since C doesn't include exceptions, we
303 * just do a longjmp to the exception handler. The type of exception is
304 * stored in the global variable "exception_type".
306 static void raise_exception(int) NORETURN;
308 raise_exception(int e)
311 if (exception_handler == NULL)
316 longjmp(exception_handler->loc, 1);
319 #define raise_exception(e) do { \
320 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
321 raise_exception(e); \
326 * Called from trap.c when a SIGINT is received. (If the user specifies
327 * that SIGINT is to be trapped or ignored using the trap builtin, then
328 * this routine is not called.) Suppressint is nonzero when interrupts
329 * are held using the INT_OFF macro. (The test for iflag is just
330 * defensive programming.)
332 static void raise_interrupt(void) NORETURN;
334 raise_interrupt(void)
339 /* Signal is not automatically unmasked after it is raised,
340 * do it ourself - unmask all signals */
341 sigprocmask_allsigs(SIG_UNBLOCK);
342 /* pending_sig = 0; - now done in signal_handler() */
345 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
346 if (!(rootshell && iflag)) {
347 /* Kill ourself with SIGINT */
348 signal(SIGINT, SIG_DFL);
353 raise_exception(ex_type);
357 #define raise_interrupt() do { \
358 TRACE(("raising interrupt on line %d\n", __LINE__)); \
363 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
367 if (--suppress_int == 0 && pending_int) {
371 #define INT_ON int_on()
372 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
380 #define FORCE_INT_ON force_int_on()
382 #define SAVE_INT(v) ((v) = suppress_int)
384 #define RESTORE_INT(v) do { \
386 suppress_int = (v); \
387 if (suppress_int == 0 && pending_int) \
392 /* ============ Stdout/stderr output */
395 outstr(const char *p, FILE *file)
403 flush_stdout_stderr(void)
411 outcslow(int c, FILE *dest)
419 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
421 out1fmt(const char *fmt, ...)
428 r = vprintf(fmt, ap);
434 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
436 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
443 ret = vsnprintf(outbuf, length, fmt, ap);
450 out1str(const char *p)
456 out2str(const char *p)
459 flush_stdout_stderr();
463 /* ============ Parser structures */
465 /* control characters in argument strings */
466 #define CTL_FIRST CTLESC
467 #define CTLESC ((unsigned char)'\201') /* escape next character */
468 #define CTLVAR ((unsigned char)'\202') /* variable defn */
469 #define CTLENDVAR ((unsigned char)'\203')
470 #define CTLBACKQ ((unsigned char)'\204')
471 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
472 /* CTLBACKQ | CTLQUOTE == '\205' */
473 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
474 #define CTLENDARI ((unsigned char)'\207')
475 #define CTLQUOTEMARK ((unsigned char)'\210')
476 #define CTL_LAST CTLQUOTEMARK
478 /* variable substitution byte (follows CTLVAR) */
479 #define VSTYPE 0x0f /* type of variable substitution */
480 #define VSNUL 0x10 /* colon--treat the empty string as unset */
481 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
483 /* values of VSTYPE field */
484 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
485 #define VSMINUS 0x2 /* ${var-text} */
486 #define VSPLUS 0x3 /* ${var+text} */
487 #define VSQUESTION 0x4 /* ${var?message} */
488 #define VSASSIGN 0x5 /* ${var=text} */
489 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
490 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
491 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
492 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
493 #define VSLENGTH 0xa /* ${#var} */
494 #if ENABLE_ASH_BASH_COMPAT
495 #define VSSUBSTR 0xc /* ${var:position:length} */
496 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
497 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
500 static const char dolatstr[] ALIGN1 = {
501 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
521 #if ENABLE_ASH_BASH_COMPAT
538 smallint type; /* Nxxxx */
541 union node *redirect;
546 smallint pipe_backgnd;
547 struct nodelist *cmdlist;
553 union node *redirect;
566 union node *elsepart;
593 struct nodelist *backquote;
596 /* nfile and ndup layout must match!
597 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
598 * that it is actually NTO2 (>&file), and change its type.
615 char *_unused_expfname;
634 struct nredir nredir;
635 struct nbinary nbinary;
639 struct nclist nclist;
648 * NODE_EOF is returned by parsecmd when it encounters an end of file.
649 * It must be distinct from NULL.
651 #define NODE_EOF ((union node *) -1L)
654 struct nodelist *next;
667 freefunc(struct funcnode *f)
669 if (f && --f->count < 0)
674 /* ============ Debugging output */
678 static FILE *tracefile;
681 trace_printf(const char *fmt, ...)
688 fprintf(tracefile, "%u ", (int) time(NULL));
690 fprintf(tracefile, "[%u] ", (int) getpid());
692 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
694 vfprintf(tracefile, fmt, va);
699 trace_vprintf(const char *fmt, va_list va)
704 fprintf(tracefile, "%u ", (int) time(NULL));
706 fprintf(tracefile, "[%u] ", (int) getpid());
708 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
709 vfprintf(tracefile, fmt, va);
713 trace_puts(const char *s)
721 trace_puts_quoted(char *s)
728 putc('"', tracefile);
729 for (p = s; *p; p++) {
730 switch ((unsigned char)*p) {
731 case '\n': c = 'n'; goto backslash;
732 case '\t': c = 't'; goto backslash;
733 case '\r': c = 'r'; goto backslash;
734 case '\"': c = '\"'; goto backslash;
735 case '\\': c = '\\'; goto backslash;
736 case CTLESC: c = 'e'; goto backslash;
737 case CTLVAR: c = 'v'; goto backslash;
738 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
739 case CTLBACKQ: c = 'q'; goto backslash;
740 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
742 putc('\\', tracefile);
746 if (*p >= ' ' && *p <= '~')
749 putc('\\', tracefile);
750 putc((*p >> 6) & 03, tracefile);
751 putc((*p >> 3) & 07, tracefile);
752 putc(*p & 07, tracefile);
757 putc('"', tracefile);
761 trace_puts_args(char **ap)
768 trace_puts_quoted(*ap);
770 putc('\n', tracefile);
773 putc(' ', tracefile);
788 /* leave open because libedit might be using it */
791 strcpy(s, "./trace");
793 if (!freopen(s, "a", tracefile)) {
794 fprintf(stderr, "Can't re-open %s\n", s);
799 tracefile = fopen(s, "a");
800 if (tracefile == NULL) {
801 fprintf(stderr, "Can't open %s\n", s);
807 flags = fcntl(fileno(tracefile), F_GETFL);
809 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
811 setlinebuf(tracefile);
812 fputs("\nTracing started.\n", tracefile);
816 indent(int amount, char *pfx, FILE *fp)
820 for (i = 0; i < amount; i++) {
821 if (pfx && i == amount - 1)
827 /* little circular references here... */
828 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
831 sharg(union node *arg, FILE *fp)
834 struct nodelist *bqlist;
835 unsigned char subtype;
837 if (arg->type != NARG) {
838 out1fmt("<node type %d>\n", arg->type);
841 bqlist = arg->narg.backquote;
842 for (p = arg->narg.text; *p; p++) {
843 switch ((unsigned char)*p) {
851 if (subtype == VSLENGTH)
860 switch (subtype & VSTYPE) {
893 out1fmt("<subtype %d>", subtype);
900 case CTLBACKQ|CTLQUOTE:
903 shtree(bqlist->n, -1, NULL, fp);
914 shcmd(union node *cmd, FILE *fp)
922 for (np = cmd->ncmd.args; np; np = np->narg.next) {
928 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
932 switch (np->nfile.type) {
933 case NTO: s = ">>"+1; dftfd = 1; break;
934 case NCLOBBER: s = ">|"; dftfd = 1; break;
935 case NAPPEND: s = ">>"; dftfd = 1; break;
936 #if ENABLE_ASH_BASH_COMPAT
939 case NTOFD: s = ">&"; dftfd = 1; break;
940 case NFROM: s = "<"; break;
941 case NFROMFD: s = "<&"; break;
942 case NFROMTO: s = "<>"; break;
943 default: s = "*error*"; break;
945 if (np->nfile.fd != dftfd)
946 fprintf(fp, "%d", np->nfile.fd);
948 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
949 fprintf(fp, "%d", np->ndup.dupfd);
951 sharg(np->nfile.fname, fp);
958 shtree(union node *n, int ind, char *pfx, FILE *fp)
966 indent(ind, pfx, fp);
983 shtree(n->nbinary.ch1, ind, NULL, fp);
986 shtree(n->nbinary.ch2, ind, NULL, fp);
994 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
995 shtree(lp->n, 0, NULL, fp);
999 if (n->npipe.pipe_backgnd)
1005 fprintf(fp, "<node type %d>", n->type);
1013 showtree(union node *n)
1015 trace_puts("showtree called\n");
1016 shtree(n, 1, NULL, stderr);
1022 /* ============ Parser data */
1025 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1028 struct strlist *next;
1035 struct strpush *prev; /* preceding string on stack */
1037 int prev_left_in_line;
1038 #if ENABLE_ASH_ALIAS
1039 struct alias *ap; /* if push was associated with an alias */
1041 char *string; /* remember the string since it may change */
1045 struct parsefile *prev; /* preceding file on stack */
1046 int linno; /* current line */
1047 int pf_fd; /* file descriptor (or -1 if string) */
1048 int left_in_line; /* number of chars left in this line */
1049 int left_in_buffer; /* number of chars left in this buffer past the line */
1050 char *next_to_pgetc; /* next char in buffer */
1051 char *buf; /* input buffer */
1052 struct strpush *strpush; /* for pushing strings at this level */
1053 struct strpush basestrpush; /* so pushing one is fast */
1056 static struct parsefile basepf; /* top level input file */
1057 static struct parsefile *g_parsefile = &basepf; /* current input file */
1058 static int startlinno; /* line # where last token started */
1059 static char *commandname; /* currently executing command */
1060 static struct strlist *cmdenviron; /* environment for builtin command */
1061 static uint8_t exitstatus; /* exit status of last command */
1064 /* ============ Message printing */
1067 ash_vmsg(const char *msg, va_list ap)
1069 fprintf(stderr, "%s: ", arg0);
1071 if (strcmp(arg0, commandname))
1072 fprintf(stderr, "%s: ", commandname);
1073 if (!iflag || g_parsefile->pf_fd > 0)
1074 fprintf(stderr, "line %d: ", startlinno);
1076 vfprintf(stderr, msg, ap);
1077 outcslow('\n', stderr);
1081 * Exverror is called to raise the error exception. If the second argument
1082 * is not NULL then error prints an error message using printf style
1083 * formatting. It then raises the error exception.
1085 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1087 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1091 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1093 TRACE(("\") pid=%d\n", getpid()));
1095 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1100 flush_stdout_stderr();
1101 raise_exception(cond);
1105 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1107 ash_msg_and_raise_error(const char *msg, ...)
1112 ash_vmsg_and_raise(EXERROR, msg, ap);
1117 static void raise_error_syntax(const char *) NORETURN;
1119 raise_error_syntax(const char *msg)
1121 ash_msg_and_raise_error("syntax error: %s", msg);
1125 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1127 ash_msg_and_raise(int cond, const char *msg, ...)
1132 ash_vmsg_and_raise(cond, msg, ap);
1138 * error/warning routines for external builtins
1141 ash_msg(const char *fmt, ...)
1151 * Return a string describing an error. The returned string may be a
1152 * pointer to a static buffer that will be overwritten on the next call.
1153 * Action describes the operation that got the error.
1156 errmsg(int e, const char *em)
1158 if (e == ENOENT || e == ENOTDIR) {
1165 /* ============ Memory allocation */
1168 /* I consider these wrappers nearly useless:
1169 * ok, they return you to nearest exception handler, but
1170 * how much memory do you leak in the process, making
1171 * memory starvation worse?
1174 ckrealloc(void * p, size_t nbytes)
1176 p = realloc(p, nbytes);
1178 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1183 ckmalloc(size_t nbytes)
1185 return ckrealloc(NULL, nbytes);
1189 ckzalloc(size_t nbytes)
1191 return memset(ckmalloc(nbytes), 0, nbytes);
1195 ckstrdup(const char *s)
1197 char *p = strdup(s);
1199 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1203 /* Using bbox equivalents. They exit if out of memory */
1204 # define ckrealloc xrealloc
1205 # define ckmalloc xmalloc
1206 # define ckzalloc xzalloc
1207 # define ckstrdup xstrdup
1211 * It appears that grabstackstr() will barf with such alignments
1212 * because stalloc() will return a string allocated in a new stackblock.
1214 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1216 /* Most machines require the value returned from malloc to be aligned
1217 * in some way. The following macro will get this right
1218 * on many machines. */
1219 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1220 /* Minimum size of a block */
1221 MINSIZE = SHELL_ALIGN(504),
1224 struct stack_block {
1225 struct stack_block *prev;
1226 char space[MINSIZE];
1230 struct stack_block *stackp;
1233 struct stackmark *marknext;
1237 struct globals_memstack {
1238 struct stack_block *g_stackp; // = &stackbase;
1239 struct stackmark *markp;
1240 char *g_stacknxt; // = stackbase.space;
1241 char *sstrend; // = stackbase.space + MINSIZE;
1242 size_t g_stacknleft; // = MINSIZE;
1243 int herefd; // = -1;
1244 struct stack_block stackbase;
1246 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1247 #define G_memstack (*ash_ptr_to_globals_memstack)
1248 #define g_stackp (G_memstack.g_stackp )
1249 #define markp (G_memstack.markp )
1250 #define g_stacknxt (G_memstack.g_stacknxt )
1251 #define sstrend (G_memstack.sstrend )
1252 #define g_stacknleft (G_memstack.g_stacknleft)
1253 #define herefd (G_memstack.herefd )
1254 #define stackbase (G_memstack.stackbase )
1255 #define INIT_G_memstack() do { \
1256 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1258 g_stackp = &stackbase; \
1259 g_stacknxt = stackbase.space; \
1260 g_stacknleft = MINSIZE; \
1261 sstrend = stackbase.space + MINSIZE; \
1266 #define stackblock() ((void *)g_stacknxt)
1267 #define stackblocksize() g_stacknleft
1270 * Parse trees for commands are allocated in lifo order, so we use a stack
1271 * to make this more efficient, and also to avoid all sorts of exception
1272 * handling code to handle interrupts in the middle of a parse.
1274 * The size 504 was chosen because the Ultrix malloc handles that size
1278 stalloc(size_t nbytes)
1283 aligned = SHELL_ALIGN(nbytes);
1284 if (aligned > g_stacknleft) {
1287 struct stack_block *sp;
1289 blocksize = aligned;
1290 if (blocksize < MINSIZE)
1291 blocksize = MINSIZE;
1292 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1293 if (len < blocksize)
1294 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1297 sp->prev = g_stackp;
1298 g_stacknxt = sp->space;
1299 g_stacknleft = blocksize;
1300 sstrend = g_stacknxt + blocksize;
1305 g_stacknxt += aligned;
1306 g_stacknleft -= aligned;
1311 stzalloc(size_t nbytes)
1313 return memset(stalloc(nbytes), 0, nbytes);
1320 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1321 write(STDERR_FILENO, "stunalloc\n", 10);
1325 g_stacknleft += g_stacknxt - (char *)p;
1330 * Like strdup but works with the ash stack.
1333 ststrdup(const char *p)
1335 size_t len = strlen(p) + 1;
1336 return memcpy(stalloc(len), p, len);
1340 setstackmark(struct stackmark *mark)
1342 mark->stackp = g_stackp;
1343 mark->stacknxt = g_stacknxt;
1344 mark->stacknleft = g_stacknleft;
1345 mark->marknext = markp;
1350 popstackmark(struct stackmark *mark)
1352 struct stack_block *sp;
1358 markp = mark->marknext;
1359 while (g_stackp != mark->stackp) {
1361 g_stackp = sp->prev;
1364 g_stacknxt = mark->stacknxt;
1365 g_stacknleft = mark->stacknleft;
1366 sstrend = mark->stacknxt + mark->stacknleft;
1371 * When the parser reads in a string, it wants to stick the string on the
1372 * stack and only adjust the stack pointer when it knows how big the
1373 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1374 * of space on top of the stack and stackblocklen returns the length of
1375 * this block. Growstackblock will grow this space by at least one byte,
1376 * possibly moving it (like realloc). Grabstackblock actually allocates the
1377 * part of the block that has been used.
1380 growstackblock(void)
1384 newlen = g_stacknleft * 2;
1385 if (newlen < g_stacknleft)
1386 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1390 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1391 struct stack_block *oldstackp;
1392 struct stackmark *xmark;
1393 struct stack_block *sp;
1394 struct stack_block *prevstackp;
1398 oldstackp = g_stackp;
1400 prevstackp = sp->prev;
1401 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1402 sp = ckrealloc(sp, grosslen);
1403 sp->prev = prevstackp;
1405 g_stacknxt = sp->space;
1406 g_stacknleft = newlen;
1407 sstrend = sp->space + newlen;
1410 * Stack marks pointing to the start of the old block
1411 * must be relocated to point to the new block
1414 while (xmark != NULL && xmark->stackp == oldstackp) {
1415 xmark->stackp = g_stackp;
1416 xmark->stacknxt = g_stacknxt;
1417 xmark->stacknleft = g_stacknleft;
1418 xmark = xmark->marknext;
1422 char *oldspace = g_stacknxt;
1423 size_t oldlen = g_stacknleft;
1424 char *p = stalloc(newlen);
1426 /* free the space we just allocated */
1427 g_stacknxt = memcpy(p, oldspace, oldlen);
1428 g_stacknleft += newlen;
1433 grabstackblock(size_t len)
1435 len = SHELL_ALIGN(len);
1437 g_stacknleft -= len;
1441 * The following routines are somewhat easier to use than the above.
1442 * The user declares a variable of type STACKSTR, which may be declared
1443 * to be a register. The macro STARTSTACKSTR initializes things. Then
1444 * the user uses the macro STPUTC to add characters to the string. In
1445 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1446 * grown as necessary. When the user is done, she can just leave the
1447 * string there and refer to it using stackblock(). Or she can allocate
1448 * the space for it using grabstackstr(). If it is necessary to allow
1449 * someone else to use the stack temporarily and then continue to grow
1450 * the string, the user should use grabstack to allocate the space, and
1451 * then call ungrabstr(p) to return to the previous mode of operation.
1453 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1454 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1455 * is space for at least one character.
1460 size_t len = stackblocksize();
1461 if (herefd >= 0 && len >= 1024) {
1462 full_write(herefd, stackblock(), len);
1463 return stackblock();
1466 return (char *)stackblock() + len;
1470 * Called from CHECKSTRSPACE.
1473 makestrspace(size_t newlen, char *p)
1475 size_t len = p - g_stacknxt;
1476 size_t size = stackblocksize();
1481 size = stackblocksize();
1483 if (nleft >= newlen)
1487 return (char *)stackblock() + len;
1491 stack_nputstr(const char *s, size_t n, char *p)
1493 p = makestrspace(n, p);
1494 p = (char *)memcpy(p, s, n) + n;
1499 stack_putstr(const char *s, char *p)
1501 return stack_nputstr(s, strlen(s), p);
1505 _STPUTC(int c, char *p)
1513 #define STARTSTACKSTR(p) ((p) = stackblock())
1514 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1515 #define CHECKSTRSPACE(n, p) do { \
1518 size_t m = sstrend - q; \
1520 (p) = makestrspace(l, q); \
1522 #define USTPUTC(c, p) (*(p)++ = (c))
1523 #define STACKSTRNUL(p) do { \
1524 if ((p) == sstrend) \
1525 (p) = growstackstr(); \
1528 #define STUNPUTC(p) (--(p))
1529 #define STTOPC(p) ((p)[-1])
1530 #define STADJUST(amount, p) ((p) += (amount))
1532 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1533 #define ungrabstackstr(s, p) stunalloc(s)
1534 #define stackstrend() ((void *)sstrend)
1537 /* ============ String helpers */
1540 * prefix -- see if pfx is a prefix of string.
1543 prefix(const char *string, const char *pfx)
1546 if (*pfx++ != *string++)
1549 return (char *) string;
1553 * Check for a valid number. This should be elsewhere.
1556 is_number(const char *p)
1561 } while (*++p != '\0');
1566 * Convert a string of digits to an integer, printing an error message on
1570 number(const char *s)
1573 ash_msg_and_raise_error(msg_illnum, s);
1578 * Produce a possibly single quoted string suitable as input to the shell.
1579 * The return string is allocated on the stack.
1582 single_quote(const char *s)
1592 len = strchrnul(s, '\'') - s;
1594 q = p = makestrspace(len + 3, p);
1597 q = (char *)memcpy(q, s, len) + len;
1606 do len++; while (*++s == '\'');
1608 q = p = makestrspace(len + 3, p);
1611 q = (char *)memcpy(q, s - len, len) + len;
1619 return stackblock();
1623 /* ============ nextopt */
1625 static char **argptr; /* argument list for builtin commands */
1626 static char *optionarg; /* set by nextopt (like getopt) */
1627 static char *optptr; /* used by nextopt */
1630 * XXX - should get rid of. Have all builtins use getopt(3).
1631 * The library getopt must have the BSD extension static variable
1632 * "optreset", otherwise it can't be used within the shell safely.
1634 * Standard option processing (a la getopt) for builtin routines.
1635 * The only argument that is passed to nextopt is the option string;
1636 * the other arguments are unnecessary. It returns the character,
1637 * or '\0' on end of input.
1640 nextopt(const char *optstring)
1647 if (p == NULL || *p == '\0') {
1648 /* We ate entire "-param", take next one */
1654 if (*++p == '\0') /* just "-" ? */
1657 if (LONE_DASH(p)) /* "--" ? */
1659 /* p => next "-param" */
1661 /* p => some option char in the middle of a "-param" */
1663 for (q = optstring; *q != c;) {
1665 ash_msg_and_raise_error("illegal option -%c", c);
1673 ash_msg_and_raise_error("no arg for -%c option", c);
1683 /* ============ Shell variables */
1686 * The parsefile structure pointed to by the global variable parsefile
1687 * contains information about the current file being read.
1690 int nparam; /* # of positional parameters (without $0) */
1691 #if ENABLE_ASH_GETOPTS
1692 int optind; /* next parameter to be processed by getopts */
1693 int optoff; /* used by getopts */
1695 unsigned char malloced; /* if parameter list dynamically allocated */
1696 char **p; /* parameter list */
1700 * Free the list of positional parameters.
1703 freeparam(volatile struct shparam *param)
1705 if (param->malloced) {
1707 ap = ap1 = param->p;
1714 #if ENABLE_ASH_GETOPTS
1715 static void FAST_FUNC getoptsreset(const char *value);
1719 struct var *next; /* next entry in hash list */
1720 int flags; /* flags are defined above */
1721 const char *var_text; /* name=value */
1722 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1723 /* the variable gets set/unset */
1727 struct localvar *next; /* next local variable in list */
1728 struct var *vp; /* the variable that was made local */
1729 int flags; /* saved flags */
1730 const char *text; /* saved text */
1734 #define VEXPORT 0x01 /* variable is exported */
1735 #define VREADONLY 0x02 /* variable cannot be modified */
1736 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1737 #define VTEXTFIXED 0x08 /* text is statically allocated */
1738 #define VSTACK 0x10 /* text is allocated on the stack */
1739 #define VUNSET 0x20 /* the variable is not set */
1740 #define VNOFUNC 0x40 /* don't call the callback function */
1741 #define VNOSET 0x80 /* do not set variable - just readonly test */
1742 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1743 #if ENABLE_ASH_RANDOM_SUPPORT
1744 # define VDYNAMIC 0x200 /* dynamic variable */
1750 /* Need to be before varinit_data[] */
1751 #if ENABLE_LOCALE_SUPPORT
1752 static void FAST_FUNC
1753 change_lc_all(const char *value)
1755 if (value && *value != '\0')
1756 setlocale(LC_ALL, value);
1758 static void FAST_FUNC
1759 change_lc_ctype(const char *value)
1761 if (value && *value != '\0')
1762 setlocale(LC_CTYPE, value);
1766 static void chkmail(void);
1767 static void changemail(const char *) FAST_FUNC;
1769 static void changepath(const char *) FAST_FUNC;
1770 #if ENABLE_ASH_RANDOM_SUPPORT
1771 static void change_random(const char *) FAST_FUNC;
1774 static const struct {
1776 const char *var_text;
1777 void (*var_func)(const char *) FAST_FUNC;
1778 } varinit_data[] = {
1779 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1781 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1782 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1784 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1785 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1786 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1787 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1788 #if ENABLE_ASH_GETOPTS
1789 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1791 #if ENABLE_ASH_RANDOM_SUPPORT
1792 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1794 #if ENABLE_LOCALE_SUPPORT
1795 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1796 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1798 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1799 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1805 struct globals_var {
1806 struct shparam shellparam; /* $@ current positional parameters */
1807 struct redirtab *redirlist;
1809 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1810 struct var *vartab[VTABSIZE];
1811 struct var varinit[ARRAY_SIZE(varinit_data)];
1813 extern struct globals_var *const ash_ptr_to_globals_var;
1814 #define G_var (*ash_ptr_to_globals_var)
1815 #define shellparam (G_var.shellparam )
1816 //#define redirlist (G_var.redirlist )
1817 #define g_nullredirs (G_var.g_nullredirs )
1818 #define preverrout_fd (G_var.preverrout_fd)
1819 #define vartab (G_var.vartab )
1820 #define varinit (G_var.varinit )
1821 #define INIT_G_var() do { \
1823 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1825 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1826 varinit[i].flags = varinit_data[i].flags; \
1827 varinit[i].var_text = varinit_data[i].var_text; \
1828 varinit[i].var_func = varinit_data[i].var_func; \
1832 #define vifs varinit[0]
1834 # define vmail (&vifs)[1]
1835 # define vmpath (&vmail)[1]
1836 # define vpath (&vmpath)[1]
1838 # define vpath (&vifs)[1]
1840 #define vps1 (&vpath)[1]
1841 #define vps2 (&vps1)[1]
1842 #define vps4 (&vps2)[1]
1843 #if ENABLE_ASH_GETOPTS
1844 # define voptind (&vps4)[1]
1845 # if ENABLE_ASH_RANDOM_SUPPORT
1846 # define vrandom (&voptind)[1]
1849 # if ENABLE_ASH_RANDOM_SUPPORT
1850 # define vrandom (&vps4)[1]
1855 * The following macros access the values of the above variables.
1856 * They have to skip over the name. They return the null string
1857 * for unset variables.
1859 #define ifsval() (vifs.var_text + 4)
1860 #define ifsset() ((vifs.flags & VUNSET) == 0)
1862 # define mailval() (vmail.var_text + 5)
1863 # define mpathval() (vmpath.var_text + 9)
1864 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1866 #define pathval() (vpath.var_text + 5)
1867 #define ps1val() (vps1.var_text + 4)
1868 #define ps2val() (vps2.var_text + 4)
1869 #define ps4val() (vps4.var_text + 4)
1870 #if ENABLE_ASH_GETOPTS
1871 # define optindval() (voptind.var_text + 7)
1875 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1876 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1878 #if ENABLE_ASH_GETOPTS
1879 static void FAST_FUNC
1880 getoptsreset(const char *value)
1882 shellparam.optind = number(value);
1883 shellparam.optoff = -1;
1888 * Return of a legal variable name (a letter or underscore followed by zero or
1889 * more letters, underscores, and digits).
1891 static char* FAST_FUNC
1892 endofname(const char *name)
1900 if (!is_in_name(*p))
1907 * Compares two strings up to the first = or '\0'. The first
1908 * string must be terminated by '='; the second may be terminated by
1909 * either '=' or '\0'.
1912 varcmp(const char *p, const char *q)
1916 while ((c = *p) == (d = *q)) {
1931 * Find the appropriate entry in the hash table from the name.
1933 static struct var **
1934 hashvar(const char *p)
1938 hashval = ((unsigned char) *p) << 4;
1939 while (*p && *p != '=')
1940 hashval += (unsigned char) *p++;
1941 return &vartab[hashval % VTABSIZE];
1945 vpcmp(const void *a, const void *b)
1947 return varcmp(*(const char **)a, *(const char **)b);
1951 * This routine initializes the builtin variables.
1961 * PS1 depends on uid
1963 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1964 vps1.var_text = "PS1=\\w \\$ ";
1967 vps1.var_text = "PS1=# ";
1970 end = vp + ARRAY_SIZE(varinit);
1972 vpp = hashvar(vp->var_text);
1975 } while (++vp < end);
1978 static struct var **
1979 findvar(struct var **vpp, const char *name)
1981 for (; *vpp; vpp = &(*vpp)->next) {
1982 if (varcmp((*vpp)->var_text, name) == 0) {
1990 * Find the value of a variable. Returns NULL if not set.
1992 static const char* FAST_FUNC
1993 lookupvar(const char *name)
1997 v = *findvar(hashvar(name), name);
1999 #if ENABLE_ASH_RANDOM_SUPPORT
2001 * Dynamic variables are implemented roughly the same way they are
2002 * in bash. Namely, they're "special" so long as they aren't unset.
2003 * As soon as they're unset, they're no longer dynamic, and dynamic
2004 * lookup will no longer happen at that point. -- PFM.
2006 if (v->flags & VDYNAMIC)
2009 if (!(v->flags & VUNSET))
2010 return var_end(v->var_text);
2016 * Search the environment of a builtin command.
2019 bltinlookup(const char *name)
2023 for (sp = cmdenviron; sp; sp = sp->next) {
2024 if (varcmp(sp->text, name) == 0)
2025 return var_end(sp->text);
2027 return lookupvar(name);
2031 * Same as setvar except that the variable and value are passed in
2032 * the first argument as name=value. Since the first argument will
2033 * be actually stored in the table, it should not be a string that
2035 * Called with interrupts off.
2038 setvareq(char *s, int flags)
2040 struct var *vp, **vpp;
2043 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2044 vp = *findvar(vpp, s);
2046 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2049 if (flags & VNOSAVE)
2052 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2058 if (vp->var_func && !(flags & VNOFUNC))
2059 vp->var_func(var_end(s));
2061 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2062 free((char*)vp->var_text);
2064 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2066 /* variable s is not found */
2069 vp = ckzalloc(sizeof(*vp));
2071 /*vp->func = NULL; - ckzalloc did it */
2074 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2081 * Set the value of a variable. The flags argument is ored with the
2082 * flags of the variable. If val is NULL, the variable is unset.
2085 setvar(const char *name, const char *val, int flags)
2092 q = endofname(name);
2093 p = strchrnul(q, '=');
2095 if (!namelen || p != q)
2096 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2101 vallen = strlen(val);
2104 nameeq = ckmalloc(namelen + vallen + 2);
2105 p = (char *)memcpy(nameeq, name, namelen) + namelen;
2108 p = (char *)memcpy(p, val, vallen) + vallen;
2111 setvareq(nameeq, flags | VNOSAVE);
2115 static void FAST_FUNC
2116 setvar2(const char *name, const char *val)
2118 setvar(name, val, 0);
2121 #if ENABLE_ASH_GETOPTS
2123 * Safe version of setvar, returns 1 on success 0 on failure.
2126 setvarsafe(const char *name, const char *val, int flags)
2129 volatile int saveint;
2130 struct jmploc *volatile savehandler = exception_handler;
2131 struct jmploc jmploc;
2134 if (setjmp(jmploc.loc))
2137 exception_handler = &jmploc;
2138 setvar(name, val, flags);
2141 exception_handler = savehandler;
2142 RESTORE_INT(saveint);
2148 * Unset the specified variable.
2151 unsetvar(const char *s)
2157 vpp = findvar(hashvar(s), s);
2161 int flags = vp->flags;
2164 if (flags & VREADONLY)
2166 #if ENABLE_ASH_RANDOM_SUPPORT
2167 vp->flags &= ~VDYNAMIC;
2171 if ((flags & VSTRFIXED) == 0) {
2173 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2174 free((char*)vp->var_text);
2180 vp->flags &= ~VEXPORT;
2190 * Process a linked list of variable assignments.
2193 listsetvar(struct strlist *list_set_var, int flags)
2195 struct strlist *lp = list_set_var;
2201 setvareq(lp->text, flags);
2208 * Generate a list of variables satisfying the given conditions.
2211 listvars(int on, int off, char ***end)
2222 for (vp = *vpp; vp; vp = vp->next) {
2223 if ((vp->flags & mask) == on) {
2224 if (ep == stackstrend())
2225 ep = growstackstr();
2226 *ep++ = (char*)vp->var_text;
2229 } while (++vpp < vartab + VTABSIZE);
2230 if (ep == stackstrend())
2231 ep = growstackstr();
2235 return grabstackstr(ep);
2239 /* ============ Path search helper
2241 * The variable path (passed by reference) should be set to the start
2242 * of the path before the first call; path_advance will update
2243 * this value as it proceeds. Successive calls to path_advance will return
2244 * the possible path expansions in sequence. If an option (indicated by
2245 * a percent sign) appears in the path entry then the global variable
2246 * pathopt will be set to point to it; otherwise pathopt will be set to
2249 static const char *pathopt; /* set by path_advance */
2252 path_advance(const char **path, const char *name)
2262 for (p = start; *p && *p != ':' && *p != '%'; p++)
2264 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2265 while (stackblocksize() < len)
2269 memcpy(q, start, p - start);
2277 while (*p && *p != ':')
2284 return stalloc(len);
2288 /* ============ Prompt */
2290 static smallint doprompt; /* if set, prompt the user */
2291 static smallint needprompt; /* true if interactive and at start of line */
2293 #if ENABLE_FEATURE_EDITING
2294 static line_input_t *line_input_state;
2295 static const char *cmdedit_prompt;
2297 putprompt(const char *s)
2299 if (ENABLE_ASH_EXPAND_PRMT) {
2300 free((char*)cmdedit_prompt);
2301 cmdedit_prompt = ckstrdup(s);
2308 putprompt(const char *s)
2314 #if ENABLE_ASH_EXPAND_PRMT
2315 /* expandstr() needs parsing machinery, so it is far away ahead... */
2316 static const char *expandstr(const char *ps);
2318 #define expandstr(s) s
2322 setprompt(int whichprompt)
2325 #if ENABLE_ASH_EXPAND_PRMT
2326 struct stackmark smark;
2331 switch (whichprompt) {
2341 #if ENABLE_ASH_EXPAND_PRMT
2342 setstackmark(&smark);
2343 stalloc(stackblocksize());
2345 putprompt(expandstr(prompt));
2346 #if ENABLE_ASH_EXPAND_PRMT
2347 popstackmark(&smark);
2352 /* ============ The cd and pwd commands */
2354 #define CD_PHYSICAL 1
2364 while ((i = nextopt("LP")) != '\0') {
2366 flags ^= CD_PHYSICAL;
2375 * Update curdir (the name of the current directory) in response to a
2379 updatepwd(const char *dir)
2386 cdcomppath = ststrdup(dir);
2389 if (curdir == nullstr)
2391 new = stack_putstr(curdir, new);
2393 new = makestrspace(strlen(dir) + 2, new);
2394 lim = (char *)stackblock() + 1;
2398 if (new > lim && *lim == '/')
2403 if (dir[1] == '/' && dir[2] != '/') {
2409 p = strtok(cdcomppath, "/");
2413 if (p[1] == '.' && p[2] == '\0') {
2425 new = stack_putstr(p, new);
2433 return stackblock();
2437 * Find out what the current directory is. If we already know the current
2438 * directory, this routine returns immediately.
2443 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2444 return dir ? dir : nullstr;
2448 setpwd(const char *val, int setold)
2452 oldcur = dir = curdir;
2455 setvar("OLDPWD", oldcur, VEXPORT);
2458 if (physdir != nullstr) {
2459 if (physdir != oldcur)
2463 if (oldcur == val || !val) {
2469 dir = ckstrdup(val);
2470 if (oldcur != dir && oldcur != nullstr) {
2475 setvar("PWD", dir, VEXPORT);
2478 static void hashcd(void);
2481 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2482 * know that the current directory has changed.
2485 docd(const char *dest, int flags)
2487 const char *dir = NULL;
2490 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2493 if (!(flags & CD_PHYSICAL)) {
2494 dir = updatepwd(dest);
2508 static int FAST_FUNC
2509 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2521 dest = bltinlookup("HOME");
2522 else if (LONE_DASH(dest)) {
2523 dest = bltinlookup("OLDPWD");
2545 path = bltinlookup("CDPATH");
2554 p = path_advance(&path, dest);
2555 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2559 if (!docd(p, flags))
2564 ash_msg_and_raise_error("can't cd to %s", dest);
2567 if (flags & CD_PRINT)
2568 out1fmt("%s\n", curdir);
2572 static int FAST_FUNC
2573 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2576 const char *dir = curdir;
2580 if (physdir == nullstr)
2584 out1fmt("%s\n", dir);
2589 /* ============ ... */
2592 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2594 /* Syntax classes */
2595 #define CWORD 0 /* character is nothing special */
2596 #define CNL 1 /* newline character */
2597 #define CBACK 2 /* a backslash character */
2598 #define CSQUOTE 3 /* single quote */
2599 #define CDQUOTE 4 /* double quote */
2600 #define CENDQUOTE 5 /* a terminating quote */
2601 #define CBQUOTE 6 /* backwards single quote */
2602 #define CVAR 7 /* a dollar sign */
2603 #define CENDVAR 8 /* a '}' character */
2604 #define CLP 9 /* a left paren in arithmetic */
2605 #define CRP 10 /* a right paren in arithmetic */
2606 #define CENDFILE 11 /* end of file */
2607 #define CCTL 12 /* like CWORD, except it must be escaped */
2608 #define CSPCL 13 /* these terminate a word */
2609 #define CIGN 14 /* character should be ignored */
2612 #if ENABLE_ASH_ALIAS
2616 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2618 #if ENABLE_SH_MATH_SUPPORT
2619 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2621 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2623 static const uint16_t S_I_T[] = {
2624 #if ENABLE_ASH_ALIAS
2625 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2627 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2628 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2629 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2630 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2631 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2632 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2633 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2634 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2635 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2636 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2637 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2638 #if !USE_SIT_FUNCTION
2639 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2640 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2641 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2645 /* Constants below must match table above */
2647 #if ENABLE_ASH_ALIAS
2648 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2650 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2651 CNL_CNL_CNL_CNL , /* 2 */
2652 CWORD_CCTL_CCTL_CWORD , /* 3 */
2653 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2654 CVAR_CVAR_CWORD_CVAR , /* 5 */
2655 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2656 CSPCL_CWORD_CWORD_CLP , /* 7 */
2657 CSPCL_CWORD_CWORD_CRP , /* 8 */
2658 CBACK_CBACK_CCTL_CBACK , /* 9 */
2659 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2660 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2661 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2662 CWORD_CWORD_CWORD_CWORD , /* 13 */
2663 CCTL_CCTL_CCTL_CCTL , /* 14 */
2666 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2667 * caller must ensure proper cast on it if c is *char_ptr!
2669 /* Values for syntax param */
2670 #define BASESYNTAX 0 /* not in quotes */
2671 #define DQSYNTAX 1 /* in double quotes */
2672 #define SQSYNTAX 2 /* in single quotes */
2673 #define ARISYNTAX 3 /* in arithmetic */
2674 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2676 #if USE_SIT_FUNCTION
2679 SIT(int c, int syntax)
2681 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2682 # if ENABLE_ASH_ALIAS
2683 static const uint8_t syntax_index_table[] ALIGN1 = {
2684 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2685 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2686 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2690 static const uint8_t syntax_index_table[] ALIGN1 = {
2691 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2692 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2693 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2702 # if ENABLE_ASH_ALIAS
2708 /* Cast is purely for paranoia here,
2709 * just in case someone passed signed char to us */
2710 if ((unsigned char)c >= CTL_FIRST
2711 && (unsigned char)c <= CTL_LAST
2715 s = strchrnul(spec_symbls, c);
2718 indx = syntax_index_table[s - spec_symbls];
2720 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2723 #else /* !USE_SIT_FUNCTION */
2725 static const uint8_t syntax_index_table[] = {
2726 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2727 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2728 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2737 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2738 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2739 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2760 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2761 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2762 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2763 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2764 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2765 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2766 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2767 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2768 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2769 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2770 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2771 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2772 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2773 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2774 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2775 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2776 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2777 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2778 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2779 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2780 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2781 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2782 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2783 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2784 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2785 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2786 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2787 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2788 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2789 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2790 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2791 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2792 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2793 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2794 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2795 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2796 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2797 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2800 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2802 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2803 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2814 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2815 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2816 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2817 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2819 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2820 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2821 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2822 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2823 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2824 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2825 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2848 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2849 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2850 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2851 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2852 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2853 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2854 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2855 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2857 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2858 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2859 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2860 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2861 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2862 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2863 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2864 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 162 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 163 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 164 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 165 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 166 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 167 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 168 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 169 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 170 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 171 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 172 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 173 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 174 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 175 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 176 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 177 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 178 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 179 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 180 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 181 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 182 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 183 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 184 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 185 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 186 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 187 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 188 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 189 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 190 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 191 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 192 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 193 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 194 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 195 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 196 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 197 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 198 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 199 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 200 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 201 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 202 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 203 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 204 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 205 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 206 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 207 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 208 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 209 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 210 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 211 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 212 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 213 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 214 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 215 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 216 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 217 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 218 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 219 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 220 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 221 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 222 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 223 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 224 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 225 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 226 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 227 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 228 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 229 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 231 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 232 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 233 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 234 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 235 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 236 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 237 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 238 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 239 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 241 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 242 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 243 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 244 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 245 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 246 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 247 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 248 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 249 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 250 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 251 */ CWORD_CWORD_CWORD_CWORD,
2979 /* 252 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 253 */ CWORD_CWORD_CWORD_CWORD,
2981 /* 254 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 255 */ CWORD_CWORD_CWORD_CWORD,
2983 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2984 # if ENABLE_ASH_ALIAS
2985 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
2989 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
2991 #endif /* !USE_SIT_FUNCTION */
2994 /* ============ Alias handling */
2996 #if ENABLE_ASH_ALIAS
2998 #define ALIASINUSE 1
3009 static struct alias **atab; // [ATABSIZE];
3010 #define INIT_G_alias() do { \
3011 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3015 static struct alias **
3016 __lookupalias(const char *name) {
3017 unsigned int hashval;
3024 ch = (unsigned char)*p;
3028 ch = (unsigned char)*++p;
3030 app = &atab[hashval % ATABSIZE];
3032 for (; *app; app = &(*app)->next) {
3033 if (strcmp(name, (*app)->name) == 0) {
3041 static struct alias *
3042 lookupalias(const char *name, int check)
3044 struct alias *ap = *__lookupalias(name);
3046 if (check && ap && (ap->flag & ALIASINUSE))
3051 static struct alias *
3052 freealias(struct alias *ap)
3056 if (ap->flag & ALIASINUSE) {
3057 ap->flag |= ALIASDEAD;
3069 setalias(const char *name, const char *val)
3071 struct alias *ap, **app;
3073 app = __lookupalias(name);
3077 if (!(ap->flag & ALIASINUSE)) {
3080 ap->val = ckstrdup(val);
3081 ap->flag &= ~ALIASDEAD;
3084 ap = ckzalloc(sizeof(struct alias));
3085 ap->name = ckstrdup(name);
3086 ap->val = ckstrdup(val);
3087 /*ap->flag = 0; - ckzalloc did it */
3088 /*ap->next = NULL;*/
3095 unalias(const char *name)
3099 app = __lookupalias(name);
3103 *app = freealias(*app);
3114 struct alias *ap, **app;
3118 for (i = 0; i < ATABSIZE; i++) {
3120 for (ap = *app; ap; ap = *app) {
3121 *app = freealias(*app);
3131 printalias(const struct alias *ap)
3133 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3137 * TODO - sort output
3139 static int FAST_FUNC
3140 aliascmd(int argc UNUSED_PARAM, char **argv)
3149 for (i = 0; i < ATABSIZE; i++) {
3150 for (ap = atab[i]; ap; ap = ap->next) {
3156 while ((n = *++argv) != NULL) {
3157 v = strchr(n+1, '=');
3158 if (v == NULL) { /* n+1: funny ksh stuff */
3159 ap = *__lookupalias(n);
3161 fprintf(stderr, "%s: %s not found\n", "alias", n);
3174 static int FAST_FUNC
3175 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3179 while ((i = nextopt("a")) != '\0') {
3185 for (i = 0; *argptr; argptr++) {
3186 if (unalias(*argptr)) {
3187 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3195 #endif /* ASH_ALIAS */
3198 /* ============ jobs.c */
3200 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3203 #define FORK_NOJOB 2
3205 /* mode flags for showjob(s) */
3206 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3207 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3208 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3211 * A job structure contains information about a job. A job is either a
3212 * single process or a set of processes contained in a pipeline. In the
3213 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3217 pid_t ps_pid; /* process id */
3218 int ps_status; /* last process status from wait() */
3219 char *ps_cmd; /* text of command being run */
3223 struct procstat ps0; /* status of process */
3224 struct procstat *ps; /* status or processes when more than one */
3226 int stopstatus; /* status of a stopped job */
3229 nprocs: 16, /* number of processes */
3231 #define JOBRUNNING 0 /* at least one proc running */
3232 #define JOBSTOPPED 1 /* all procs are stopped */
3233 #define JOBDONE 2 /* all procs are completed */
3235 sigint: 1, /* job was killed by SIGINT */
3236 jobctl: 1, /* job running under job control */
3238 waited: 1, /* true if this entry has been waited for */
3239 used: 1, /* true if this entry is in used */
3240 changed: 1; /* true if status has changed */
3241 struct job *prev_job; /* previous job */
3244 static struct job *makejob(/*union node *,*/ int);
3245 static int forkshell(struct job *, union node *, int);
3246 static int waitforjob(struct job *);
3249 enum { doing_jobctl = 0 };
3250 #define setjobctl(on) do {} while (0)
3252 static smallint doing_jobctl; //references:8
3253 static void setjobctl(int);
3260 ignoresig(int signo)
3262 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3263 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3264 /* No, need to do it */
3265 signal(signo, SIG_IGN);
3267 sigmode[signo - 1] = S_HARD_IGN;
3271 * Only one usage site - in setsignal()
3274 signal_handler(int signo)
3276 gotsig[signo - 1] = 1;
3278 if (signo == SIGINT && !trap[SIGINT]) {
3279 if (!suppress_int) {
3281 raise_interrupt(); /* does not return */
3285 pending_sig = signo;
3290 * Set the signal handler for the specified signal. The routine figures
3291 * out what it should be set to.
3294 setsignal(int signo)
3297 char cur_act, new_act;
3298 struct sigaction act;
3302 if (t != NULL) { /* trap for this sig is set */
3304 if (t[0] == '\0') /* trap is "": ignore this sig */
3308 if (rootshell && new_act == S_DFL) {
3311 if (iflag || minusc || sflag == 0)
3320 * "In all cases, bash ignores SIGQUIT. Non-builtin
3321 * commands run by bash have signal handlers
3322 * set to the values inherited by the shell
3323 * from its parent". */
3339 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3340 //whereas we have to restore it to what shell got on entry
3341 //from the parent. See comment above
3343 t = &sigmode[signo - 1];
3346 /* current setting is not yet known */
3347 if (sigaction(signo, NULL, &act)) {
3348 /* pretend it worked; maybe we should give a warning,
3349 * but other shells don't. We don't alter sigmode,
3350 * so we retry every time.
3351 * btw, in Linux it never fails. --vda */
3354 if (act.sa_handler == SIG_IGN) {
3355 cur_act = S_HARD_IGN;
3357 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3359 cur_act = S_IGN; /* don't hard ignore these */
3363 if (cur_act == S_HARD_IGN || cur_act == new_act)
3366 act.sa_handler = SIG_DFL;
3369 act.sa_handler = signal_handler;
3370 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3371 sigfillset(&act.sa_mask); /* ditto */
3374 act.sa_handler = SIG_IGN;
3377 sigaction_set(signo, &act);
3382 /* mode flags for set_curjob */
3383 #define CUR_DELETE 2
3384 #define CUR_RUNNING 1
3385 #define CUR_STOPPED 0
3387 /* mode flags for dowait */
3388 #define DOWAIT_NONBLOCK WNOHANG
3389 #define DOWAIT_BLOCK 0
3392 /* pgrp of shell on invocation */
3393 static int initialpgrp; //references:2
3394 static int ttyfd = -1; //5
3397 static struct job *jobtab; //5
3399 static unsigned njobs; //4
3401 static struct job *curjob; //lots
3402 /* number of presumed living untracked jobs */
3403 static int jobless; //4
3406 set_curjob(struct job *jp, unsigned mode)
3409 struct job **jpp, **curp;
3411 /* first remove from list */
3412 jpp = curp = &curjob;
3417 jpp = &jp1->prev_job;
3419 *jpp = jp1->prev_job;
3421 /* Then re-insert in correct position */
3429 /* job being deleted */
3432 /* newly created job or backgrounded job,
3433 put after all stopped jobs. */
3437 if (!jp1 || jp1->state != JOBSTOPPED)
3440 jpp = &jp1->prev_job;
3446 /* newly stopped job - becomes curjob */
3447 jp->prev_job = *jpp;
3455 jobno(const struct job *jp)
3457 return jp - jobtab + 1;
3462 * Convert a job name to a job structure.
3465 #define getjob(name, getctl) getjob(name)
3468 getjob(const char *name, int getctl)
3472 const char *err_msg = "%s: no such job";
3476 char *(*match)(const char *, const char *);
3491 if (c == '+' || c == '%') {
3493 err_msg = "No current job";
3499 err_msg = "No previous job";
3510 jp = jobtab + num - 1;
3525 if (match(jp->ps[0].ps_cmd, p)) {
3529 err_msg = "%s: ambiguous";
3539 err_msg = "job %s not created under job control";
3540 if (getctl && jp->jobctl == 0)
3545 ash_msg_and_raise_error(err_msg, name);
3549 * Mark a job structure as unused.
3552 freejob(struct job *jp)
3554 struct procstat *ps;
3558 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3559 if (ps->ps_cmd != nullstr)
3562 if (jp->ps != &jp->ps0)
3565 set_curjob(jp, CUR_DELETE);
3571 xtcsetpgrp(int fd, pid_t pgrp)
3573 if (tcsetpgrp(fd, pgrp))
3574 ash_msg_and_raise_error("can't set tty process group (%m)");
3578 * Turn job control on and off.
3580 * Note: This code assumes that the third arg to ioctl is a character
3581 * pointer, which is true on Berkeley systems but not System V. Since
3582 * System V doesn't have job control yet, this isn't a problem now.
3584 * Called with interrupts off.
3592 if (on == doing_jobctl || rootshell == 0)
3596 ofd = fd = open(_PATH_TTY, O_RDWR);
3598 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3599 * That sometimes helps to acquire controlling tty.
3600 * Obviously, a workaround for bugs when someone
3601 * failed to provide a controlling tty to bash! :) */
3607 fd = fcntl(fd, F_DUPFD, 10);
3612 /* fd is a tty at this point */
3613 close_on_exec_on(fd);
3614 do { /* while we are in the background */
3615 pgrp = tcgetpgrp(fd);
3618 ash_msg("can't access tty; job control turned off");
3622 if (pgrp == getpgrp())
3633 xtcsetpgrp(fd, pgrp);
3635 /* turning job control off */
3638 /* was xtcsetpgrp, but this can make exiting ash
3639 * loop forever if pty is already deleted */
3640 tcsetpgrp(fd, pgrp);
3654 static int FAST_FUNC
3655 killcmd(int argc, char **argv)
3658 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3660 if (argv[i][0] == '%') {
3661 struct job *jp = getjob(argv[i], 0);
3662 unsigned pid = jp->ps[0].ps_pid;
3663 /* Enough space for ' -NNN<nul>' */
3664 argv[i] = alloca(sizeof(int)*3 + 3);
3665 /* kill_main has matching code to expect
3666 * leading space. Needed to not confuse
3667 * negative pids with "kill -SIGNAL_NO" syntax */
3668 sprintf(argv[i], " -%u", pid);
3670 } while (argv[++i]);
3672 return kill_main(argc, argv);
3676 showpipe(struct job *jp /*, FILE *out*/)
3678 struct procstat *ps;
3679 struct procstat *psend;
3681 psend = jp->ps + jp->nprocs;
3682 for (ps = jp->ps + 1; ps < psend; ps++)
3683 printf(" | %s", ps->ps_cmd);
3684 outcslow('\n', stdout);
3685 flush_stdout_stderr();
3690 restartjob(struct job *jp, int mode)
3692 struct procstat *ps;
3698 if (jp->state == JOBDONE)
3700 jp->state = JOBRUNNING;
3701 pgid = jp->ps[0].ps_pid;
3702 if (mode == FORK_FG)
3703 xtcsetpgrp(ttyfd, pgid);
3704 killpg(pgid, SIGCONT);
3708 if (WIFSTOPPED(ps->ps_status)) {
3714 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3719 static int FAST_FUNC
3720 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3726 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3730 jp = getjob(*argv, 1);
3731 if (mode == FORK_BG) {
3732 set_curjob(jp, CUR_RUNNING);
3733 printf("[%d] ", jobno(jp));
3735 out1str(jp->ps[0].ps_cmd);
3736 showpipe(jp /*, stdout*/);
3737 retval = restartjob(jp, mode);
3738 } while (*argv && *++argv);
3744 sprint_status(char *s, int status, int sigonly)
3750 if (!WIFEXITED(status)) {
3752 if (WIFSTOPPED(status))
3753 st = WSTOPSIG(status);
3756 st = WTERMSIG(status);
3758 if (st == SIGINT || st == SIGPIPE)
3761 if (WIFSTOPPED(status))
3766 col = fmtstr(s, 32, strsignal(st));
3767 if (WCOREDUMP(status)) {
3768 col += fmtstr(s + col, 16, " (core dumped)");
3770 } else if (!sigonly) {
3771 st = WEXITSTATUS(status);
3773 col = fmtstr(s, 16, "Done(%d)", st);
3775 col = fmtstr(s, 16, "Done");
3782 dowait(int wait_flags, struct job *job)
3787 struct job *thisjob;
3790 TRACE(("dowait(0x%x) called\n", wait_flags));
3792 /* Do a wait system call. If job control is compiled in, we accept
3793 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3794 * NB: _not_ safe_waitpid, we need to detect EINTR */
3796 wait_flags |= WUNTRACED;
3797 pid = waitpid(-1, &status, wait_flags);
3798 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3799 pid, status, errno, strerror(errno)));
3805 for (jp = curjob; jp; jp = jp->prev_job) {
3806 struct procstat *ps;
3807 struct procstat *psend;
3808 if (jp->state == JOBDONE)
3812 psend = ps + jp->nprocs;
3814 if (ps->ps_pid == pid) {
3815 TRACE(("Job %d: changing status of proc %d "
3816 "from 0x%x to 0x%x\n",
3817 jobno(jp), pid, ps->ps_status, status));
3818 ps->ps_status = status;
3821 if (ps->ps_status == -1)
3824 if (state == JOBRUNNING)
3826 if (WIFSTOPPED(ps->ps_status)) {
3827 jp->stopstatus = ps->ps_status;
3831 } while (++ps < psend);
3836 if (!WIFSTOPPED(status))
3842 if (state != JOBRUNNING) {
3843 thisjob->changed = 1;
3845 if (thisjob->state != state) {
3846 TRACE(("Job %d: changing state from %d to %d\n",
3847 jobno(thisjob), thisjob->state, state));
3848 thisjob->state = state;
3850 if (state == JOBSTOPPED) {
3851 set_curjob(thisjob, CUR_STOPPED);
3860 if (thisjob && thisjob == job) {
3864 len = sprint_status(s, status, 1);
3875 blocking_wait_with_raise_on_sig(void)
3877 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
3878 if (pid <= 0 && pending_sig)
3879 raise_exception(EXSIG);
3885 showjob(FILE *out, struct job *jp, int mode)
3887 struct procstat *ps;
3888 struct procstat *psend;
3895 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
3896 /* just output process (group) id of pipeline */
3897 fprintf(out, "%d\n", ps->ps_pid);
3901 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3906 else if (curjob && jp == curjob->prev_job)
3909 if (mode & SHOW_PIDS)
3910 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
3912 psend = ps + jp->nprocs;
3914 if (jp->state == JOBRUNNING) {
3915 strcpy(s + col, "Running");
3916 col += sizeof("Running") - 1;
3918 int status = psend[-1].ps_status;
3919 if (jp->state == JOBSTOPPED)
3920 status = jp->stopstatus;
3921 col += sprint_status(s + col, status, 0);
3923 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
3925 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3926 * or prints several "PID | <cmdN>" lines,
3927 * depending on SHOW_PIDS bit.
3928 * We do not print status of individual processes
3929 * between PID and <cmdN>. bash does it, but not very well:
3930 * first line shows overall job status, not process status,
3931 * making it impossible to know 1st process status.
3935 /* for each process */
3938 if (mode & SHOW_PIDS)
3939 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
3941 fprintf(out, "%s%*c%s%s",
3943 33 - col >= 0 ? 33 - col : 0, ' ',
3944 ps == jp->ps ? "" : "| ",
3947 } while (++ps != psend);
3948 outcslow('\n', out);
3952 if (jp->state == JOBDONE) {
3953 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3959 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3960 * statuses have changed since the last call to showjobs.
3963 showjobs(FILE *out, int mode)
3967 TRACE(("showjobs(0x%x) called\n", mode));
3969 /* Handle all finished jobs */
3970 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
3973 for (jp = curjob; jp; jp = jp->prev_job) {
3974 if (!(mode & SHOW_CHANGED) || jp->changed) {
3975 showjob(out, jp, mode);
3980 static int FAST_FUNC
3981 jobscmd(int argc UNUSED_PARAM, char **argv)
3986 while ((m = nextopt("lp")) != '\0') {
3990 mode |= SHOW_ONLY_PGID;
3996 showjob(stdout, getjob(*argv, 0), mode);
3999 showjobs(stdout, mode);
4006 /* Called only on finished or stopped jobs (no members are running) */
4008 getstatus(struct job *job)
4012 struct procstat *ps;
4014 /* Fetch last member's status */
4015 ps = job->ps + job->nprocs - 1;
4016 status = ps->ps_status;
4018 /* "set -o pipefail" mode: use last _nonzero_ status */
4019 while (status == 0 && --ps >= job->ps)
4020 status = ps->ps_status;
4023 retval = WEXITSTATUS(status);
4024 if (!WIFEXITED(status)) {
4026 retval = WSTOPSIG(status);
4027 if (!WIFSTOPPED(status))
4030 /* XXX: limits number of signals */
4031 retval = WTERMSIG(status);
4033 if (retval == SIGINT)
4039 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4040 jobno(job), job->nprocs, status, retval));
4044 static int FAST_FUNC
4045 waitcmd(int argc UNUSED_PARAM, char **argv)
4052 raise_exception(EXSIG);
4059 /* wait for all jobs */
4063 if (!jp) /* no running procs */
4065 if (jp->state == JOBRUNNING)
4070 blocking_wait_with_raise_on_sig();
4072 * "When bash is waiting for an asynchronous command via
4073 * the wait builtin, the reception of a signal for which a trap
4074 * has been set will cause the wait builtin to return immediately
4075 * with an exit status greater than 128, immediately after which
4076 * the trap is executed."
4078 * blocking_wait_with_raise_on_sig raises signal handlers
4079 * if it gets no pid (pid < 0). However,
4080 * if child sends us a signal *and immediately exits*,
4081 * blocking_wait_with_raise_on_sig gets pid > 0
4082 * and does not handle pending_sig. Check this case: */
4084 raise_exception(EXSIG);
4090 if (**argv != '%') {
4091 pid_t pid = number(*argv);
4096 if (job->ps[job->nprocs - 1].ps_pid == pid)
4098 job = job->prev_job;
4101 job = getjob(*argv, 0);
4102 /* loop until process terminated or stopped */
4103 while (job->state == JOBRUNNING)
4104 blocking_wait_with_raise_on_sig();
4106 retval = getstatus(job);
4119 struct job *jp, *jq;
4121 len = njobs * sizeof(*jp);
4123 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4125 offset = (char *)jp - (char *)jq;
4127 /* Relocate pointers */
4130 jq = (struct job *)((char *)jq + l);
4134 #define joff(p) ((struct job *)((char *)(p) + l))
4135 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4136 if (joff(jp)->ps == &jq->ps0)
4137 jmove(joff(jp)->ps);
4138 if (joff(jp)->prev_job)
4139 jmove(joff(jp)->prev_job);
4149 jp = (struct job *)((char *)jp + len);
4153 } while (--jq >= jp);
4158 * Return a new job structure.
4159 * Called with interrupts off.
4162 makejob(/*union node *node,*/ int nprocs)
4167 for (i = njobs, jp = jobtab; ; jp++) {
4174 if (jp->state != JOBDONE || !jp->waited)
4183 memset(jp, 0, sizeof(*jp));
4185 /* jp->jobctl is a bitfield.
4186 * "jp->jobctl |= jobctl" likely to give awful code */
4190 jp->prev_job = curjob;
4195 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4197 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4204 * Return a string identifying a command (to be printed by the
4207 static char *cmdnextc;
4210 cmdputs(const char *s)
4212 static const char vstype[VSTYPE + 1][3] = {
4213 "", "}", "-", "+", "?", "=",
4214 "%", "%%", "#", "##"
4215 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4218 const char *p, *str;
4222 unsigned char subtype = 0;
4226 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4228 while ((c = *p++) != '\0') {
4236 if ((subtype & VSTYPE) == VSLENGTH)
4240 if (!(subtype & VSQUOTE) == !(quoted & 1))
4246 str = "\"}" + !(quoted & 1);
4253 case CTLBACKQ+CTLQUOTE:
4256 #if ENABLE_SH_MATH_SUPPORT
4271 if ((subtype & VSTYPE) != VSNORMAL)
4273 str = vstype[subtype & VSTYPE];
4274 if (subtype & VSNUL)
4283 /* These can only happen inside quotes */
4296 while ((c = *str++) != '\0') {
4299 } /* while *p++ not NUL */
4302 USTPUTC('"', nextc);
4308 /* cmdtxt() and cmdlist() call each other */
4309 static void cmdtxt(union node *n);
4312 cmdlist(union node *np, int sep)
4314 for (; np; np = np->narg.next) {
4318 if (sep && np->narg.next)
4324 cmdtxt(union node *n)
4327 struct nodelist *lp;
4338 lp = n->npipe.cmdlist;
4356 cmdtxt(n->nbinary.ch1);
4372 cmdtxt(n->nif.test);
4374 if (n->nif.elsepart) {
4375 cmdtxt(n->nif.ifpart);
4377 n = n->nif.elsepart;
4395 cmdtxt(n->nbinary.ch1);
4405 cmdputs(n->nfor.var);
4407 cmdlist(n->nfor.args, 1);
4412 cmdputs(n->narg.text);
4416 cmdlist(n->ncmd.args, 1);
4417 cmdlist(n->ncmd.redirect, 0);
4430 cmdputs(n->ncase.expr->narg.text);
4432 for (np = n->ncase.cases; np; np = np->nclist.next) {
4433 cmdtxt(np->nclist.pattern);
4435 cmdtxt(np->nclist.body);
4449 #if ENABLE_ASH_BASH_COMPAT
4464 cmdputs(utoa(n->nfile.fd));
4466 if (n->type == NTOFD || n->type == NFROMFD) {
4467 cmdputs(utoa(n->ndup.dupfd));
4476 commandtext(union node *n)
4480 STARTSTACKSTR(cmdnextc);
4482 name = stackblock();
4483 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4484 name, cmdnextc, cmdnextc));
4485 return ckstrdup(name);
4490 * Fork off a subshell. If we are doing job control, give the subshell its
4491 * own process group. Jp is a job structure that the job is to be added to.
4492 * N is the command that will be evaluated by the child. Both jp and n may
4493 * be NULL. The mode parameter can be one of the following:
4494 * FORK_FG - Fork off a foreground process.
4495 * FORK_BG - Fork off a background process.
4496 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4497 * process group even if job control is on.
4499 * When job control is turned off, background processes have their standard
4500 * input redirected to /dev/null (except for the second and later processes
4503 * Called with interrupts off.
4506 * Clear traps on a fork.
4513 for (tp = trap; tp < &trap[NSIG]; tp++) {
4514 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4516 if (trap_ptr == trap)
4518 /* else: it "belongs" to trap_ptr vector, don't free */
4520 if ((tp - trap) != 0)
4521 setsignal(tp - trap);
4527 /* Lives far away from here, needed for forkchild */
4528 static void closescript(void);
4530 /* Called after fork(), in child */
4531 static NOINLINE void
4532 forkchild(struct job *jp, union node *n, int mode)
4536 TRACE(("Child shell %d\n", getpid()));
4540 /* man bash: "Non-builtin commands run by bash have signal handlers
4541 * set to the values inherited by the shell from its parent".
4542 * Do we do it correctly? */
4546 if (mode == FORK_NOJOB /* is it `xxx` ? */
4547 && n && n->type == NCMD /* is it single cmd? */
4548 /* && n->ncmd.args->type == NARG - always true? */
4549 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4550 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4551 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4553 TRACE(("Trap hack\n"));
4554 /* Awful hack for `trap` or $(trap).
4556 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4557 * contains an example where "trap" is executed in a subshell:
4559 * save_traps=$(trap)
4561 * eval "$save_traps"
4563 * Standard does not say that "trap" in subshell shall print
4564 * parent shell's traps. It only says that its output
4565 * must have suitable form, but then, in the above example
4566 * (which is not supposed to be normative), it implies that.
4568 * bash (and probably other shell) does implement it
4569 * (traps are reset to defaults, but "trap" still shows them),
4570 * but as a result, "trap" logic is hopelessly messed up:
4573 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4574 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4575 * # true | trap <--- trap is in subshell - no output (ditto)
4576 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4577 * trap -- 'echo Ho' SIGWINCH
4578 * # echo `(trap)` <--- in subshell in subshell - output
4579 * trap -- 'echo Ho' SIGWINCH
4580 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4581 * trap -- 'echo Ho' SIGWINCH
4583 * The rules when to forget and when to not forget traps
4584 * get really complex and nonsensical.
4586 * Our solution: ONLY bare $(trap) or `trap` is special.
4588 /* Save trap handler strings for trap builtin to print */
4589 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4590 /* Fall through into clearing traps */
4594 /* do job control only in root shell */
4596 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4599 if (jp->nprocs == 0)
4602 pgrp = jp->ps[0].ps_pid;
4603 /* this can fail because we are doing it in the parent also */
4605 if (mode == FORK_FG)
4606 xtcsetpgrp(ttyfd, pgrp);
4611 if (mode == FORK_BG) {
4612 /* man bash: "When job control is not in effect,
4613 * asynchronous commands ignore SIGINT and SIGQUIT" */
4616 if (jp->nprocs == 0) {
4618 if (open(bb_dev_null, O_RDONLY) != 0)
4619 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4623 if (iflag) { /* why if iflag only? */
4628 * "In all cases, bash ignores SIGQUIT. Non-builtin
4629 * commands run by bash have signal handlers
4630 * set to the values inherited by the shell
4632 * Take care of the second rule: */
4636 if (n && n->type == NCMD
4637 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4639 TRACE(("Job hack\n"));
4640 /* "jobs": we do not want to clear job list for it,
4641 * instead we remove only _its_ own_ job from job list.
4642 * This makes "jobs .... | cat" more useful.
4648 for (jp = curjob; jp; jp = jp->prev_job)
4653 /* Called after fork(), in parent */
4655 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4658 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4660 TRACE(("In parent shell: child = %d\n", pid));
4662 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4668 if (mode != FORK_NOJOB && jp->jobctl) {
4671 if (jp->nprocs == 0)
4674 pgrp = jp->ps[0].ps_pid;
4675 /* This can fail because we are doing it in the child also */
4679 if (mode == FORK_BG) {
4680 backgndpid = pid; /* set $! */
4681 set_curjob(jp, CUR_RUNNING);
4684 struct procstat *ps = &jp->ps[jp->nprocs++];
4687 ps->ps_cmd = nullstr;
4689 if (doing_jobctl && n)
4690 ps->ps_cmd = commandtext(n);
4696 forkshell(struct job *jp, union node *n, int mode)
4700 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4703 TRACE(("Fork failed, errno=%d", errno));
4706 ash_msg_and_raise_error("can't fork");
4709 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4710 forkchild(jp, n, mode);
4712 forkparent(jp, n, mode, pid);
4718 * Wait for job to finish.
4720 * Under job control we have the problem that while a child process
4721 * is running interrupts generated by the user are sent to the child
4722 * but not to the shell. This means that an infinite loop started by
4723 * an interactive user may be hard to kill. With job control turned off,
4724 * an interactive user may place an interactive program inside a loop.
4725 * If the interactive program catches interrupts, the user doesn't want
4726 * these interrupts to also abort the loop. The approach we take here
4727 * is to have the shell ignore interrupt signals while waiting for a
4728 * foreground process to terminate, and then send itself an interrupt
4729 * signal if the child process was terminated by an interrupt signal.
4730 * Unfortunately, some programs want to do a bit of cleanup and then
4731 * exit on interrupt; unless these processes terminate themselves by
4732 * sending a signal to themselves (instead of calling exit) they will
4733 * confuse this approach.
4735 * Called with interrupts off.
4738 waitforjob(struct job *jp)
4742 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4745 while (jp->state == JOBRUNNING) {
4746 /* In non-interactive shells, we _can_ get
4747 * a keyboard signal here and be EINTRed,
4748 * but we just loop back, waiting for command to complete.
4751 * "If bash is waiting for a command to complete and receives
4752 * a signal for which a trap has been set, the trap
4753 * will not be executed until the command completes."
4755 * Reality is that even if trap is not set, bash
4756 * will not act on the signal until command completes.
4757 * Try this. sleep5intoff.c:
4758 * #include <signal.h>
4759 * #include <unistd.h>
4762 * sigemptyset(&set);
4763 * sigaddset(&set, SIGINT);
4764 * sigaddset(&set, SIGQUIT);
4765 * sigprocmask(SIG_BLOCK, &set, NULL);
4769 * $ bash -c './sleep5intoff; echo hi'
4770 * ^C^C^C^C <--- pressing ^C once a second
4772 * $ bash -c './sleep5intoff; echo hi'
4773 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4776 dowait(DOWAIT_BLOCK, jp);
4783 xtcsetpgrp(ttyfd, rootpid);
4785 * This is truly gross.
4786 * If we're doing job control, then we did a TIOCSPGRP which
4787 * caused us (the shell) to no longer be in the controlling
4788 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4789 * intuit from the subprocess exit status whether a SIGINT
4790 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4792 if (jp->sigint) /* TODO: do the same with all signals */
4793 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4795 if (jp->state == JOBDONE)
4802 * return 1 if there are stopped jobs, otherwise 0
4814 if (jp && jp->state == JOBSTOPPED) {
4815 out2str("You have stopped jobs.\n");
4824 /* ============ redir.c
4826 * Code for dealing with input/output redirection.
4829 #define EMPTY -2 /* marks an unused slot in redirtab */
4830 #define CLOSED -3 /* marks a slot of previously-closed fd */
4833 * Open a file in noclobber mode.
4834 * The code was copied from bash.
4837 noclobberopen(const char *fname)
4840 struct stat finfo, finfo2;
4843 * If the file exists and is a regular file, return an error
4846 r = stat(fname, &finfo);
4847 if (r == 0 && S_ISREG(finfo.st_mode)) {
4853 * If the file was not present (r != 0), make sure we open it
4854 * exclusively so that if it is created before we open it, our open
4855 * will fail. Make sure that we do not truncate an existing file.
4856 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4857 * file was not a regular file, we leave O_EXCL off.
4860 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4861 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4863 /* If the open failed, return the file descriptor right away. */
4868 * OK, the open succeeded, but the file may have been changed from a
4869 * non-regular file to a regular file between the stat and the open.
4870 * We are assuming that the O_EXCL open handles the case where FILENAME
4871 * did not exist and is symlinked to an existing file between the stat
4876 * If we can open it and fstat the file descriptor, and neither check
4877 * revealed that it was a regular file, and the file has not been
4878 * replaced, return the file descriptor.
4880 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4881 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4884 /* The file has been replaced. badness. */
4891 * Handle here documents. Normally we fork off a process to write the
4892 * data to a pipe. If the document is short, we can stuff the data in
4893 * the pipe without forking.
4895 /* openhere needs this forward reference */
4896 static void expandhere(union node *arg, int fd);
4898 openhere(union node *redir)
4904 ash_msg_and_raise_error("pipe call failed");
4905 if (redir->type == NHERE) {
4906 len = strlen(redir->nhere.doc->narg.text);
4907 if (len <= PIPE_BUF) {
4908 full_write(pip[1], redir->nhere.doc->narg.text, len);
4912 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4915 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4916 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4917 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4918 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4919 signal(SIGPIPE, SIG_DFL);
4920 if (redir->type == NHERE)
4921 full_write(pip[1], redir->nhere.doc->narg.text, len);
4923 expandhere(redir->nhere.doc, pip[1]);
4924 _exit(EXIT_SUCCESS);
4932 openredirect(union node *redir)
4937 switch (redir->nfile.type) {
4939 fname = redir->nfile.expfname;
4940 f = open(fname, O_RDONLY);
4945 fname = redir->nfile.expfname;
4946 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4951 #if ENABLE_ASH_BASH_COMPAT
4954 /* Take care of noclobber mode. */
4956 fname = redir->nfile.expfname;
4957 f = noclobberopen(fname);
4964 fname = redir->nfile.expfname;
4965 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4970 fname = redir->nfile.expfname;
4971 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4979 /* Fall through to eliminate warning. */
4980 /* Our single caller does this itself */
4987 f = openhere(redir);
4993 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4995 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
4999 * Copy a file descriptor to be >= to. Returns -1
5000 * if the source file descriptor is closed, EMPTY if there are no unused
5001 * file descriptors left.
5003 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5004 * old code was doing close(to) prior to copyfd() to achieve the same */
5006 COPYFD_EXACT = (int)~(INT_MAX),
5007 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5010 copyfd(int from, int to)
5014 if (to & COPYFD_EXACT) {
5015 to &= ~COPYFD_EXACT;
5017 newfd = dup2(from, to);
5019 newfd = fcntl(from, F_DUPFD, to);
5022 if (errno == EMFILE)
5024 /* Happens when source fd is not open: try "echo >&99" */
5025 ash_msg_and_raise_error("%d: %m", from);
5030 /* Struct def and variable are moved down to the first usage site */
5035 struct redirtab *next;
5038 struct two_fd_t two_fd[];
5040 #define redirlist (G_var.redirlist)
5042 static int need_to_remember(struct redirtab *rp, int fd)
5046 if (!rp) /* remembering was not requested */
5049 for (i = 0; i < rp->pair_count; i++) {
5050 if (rp->two_fd[i].orig == fd) {
5051 /* already remembered */
5058 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5059 static int is_hidden_fd(struct redirtab *rp, int fd)
5062 struct parsefile *pf;
5066 /* Check open scripts' fds */
5069 /* We skip pf_fd == 0 case because of the following case:
5070 * $ ash # running ash interactively
5072 * and in script.sh: "exec 9>&0".
5073 * Even though top-level pf_fd _is_ 0,
5074 * it's still ok to use it: "read" builtin uses it,
5075 * why should we cripple "exec" builtin?
5077 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5085 /* Check saved fds of redirects */
5086 fd |= COPYFD_RESTORE;
5087 for (i = 0; i < rp->pair_count; i++) {
5088 if (rp->two_fd[i].copy == fd) {
5096 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5097 * old file descriptors are stashed away so that the redirection can be
5098 * undone by calling popredir.
5100 /* flags passed to redirect */
5101 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5102 #define REDIR_SAVEFD2 03 /* set preverrout */
5104 redirect(union node *redir, int flags)
5106 struct redirtab *sv;
5111 int copied_fd2 = -1;
5121 if (flags & REDIR_PUSH) {
5122 union node *tmp = redir;
5125 #if ENABLE_ASH_BASH_COMPAT
5126 if (tmp->nfile.type == NTO2)
5129 tmp = tmp->nfile.next;
5131 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5132 sv->next = redirlist;
5133 sv->pair_count = sv_pos;
5135 sv->nullredirs = g_nullredirs - 1;
5137 while (sv_pos > 0) {
5139 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5145 fd = redir->nfile.fd;
5146 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5147 right_fd = redir->ndup.dupfd;
5148 //bb_error_msg("doing %d > %d", fd, right_fd);
5149 /* redirect from/to same file descriptor? */
5152 /* "echo >&10" and 10 is a fd opened to a sh script? */
5153 if (is_hidden_fd(sv, right_fd)) {
5154 errno = EBADF; /* as if it is closed */
5155 ash_msg_and_raise_error("%d: %m", right_fd);
5159 newfd = openredirect(redir); /* always >= 0 */
5161 /* Descriptor wasn't open before redirect.
5162 * Mark it for close in the future */
5163 if (need_to_remember(sv, fd)) {
5164 goto remember_to_close;
5169 #if ENABLE_ASH_BASH_COMPAT
5172 if (need_to_remember(sv, fd)) {
5173 /* Copy old descriptor */
5174 /* Careful to not accidentally "save"
5175 * to the same fd as right side fd in N>&M */
5176 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5177 i = fcntl(fd, F_DUPFD, minfd);
5178 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5179 * are closed in popredir() in the child, preventing them from leaking
5180 * into child. (popredir() also cleans up the mess in case of failures)
5185 /* Strange error (e.g. "too many files" EMFILE?) */
5189 ash_msg_and_raise_error("%d: %m", fd);
5192 /* EBADF: it is not open - good, remember to close it */
5195 } else { /* fd is open, save its copy */
5196 /* "exec fd>&-" should not close fds
5197 * which point to script file(s).
5198 * Force them to be restored afterwards */
5199 if (is_hidden_fd(sv, fd))
5200 i |= COPYFD_RESTORE;
5204 sv->two_fd[sv_pos].orig = fd;
5205 sv->two_fd[sv_pos].copy = i;
5209 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5210 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5211 /* Don't want to trigger debugging */
5215 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5217 } else if (fd != newfd) { /* move newfd to fd */
5218 copyfd(newfd, fd | COPYFD_EXACT);
5219 #if ENABLE_ASH_BASH_COMPAT
5220 if (!(redir->nfile.type == NTO2 && fd == 2))
5224 #if ENABLE_ASH_BASH_COMPAT
5225 if (redir->nfile.type == NTO2 && fd == 1) {
5226 /* We already redirected it to fd 1, now copy it to 2 */
5232 } while ((redir = redir->nfile.next) != NULL);
5235 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5236 preverrout_fd = copied_fd2;
5240 * Undo the effects of the last redirection.
5243 popredir(int drop, int restore)
5245 struct redirtab *rp;
5248 if (--g_nullredirs >= 0)
5252 for (i = 0; i < rp->pair_count; i++) {
5253 int fd = rp->two_fd[i].orig;
5254 int copy = rp->two_fd[i].copy;
5255 if (copy == CLOSED) {
5260 if (copy != EMPTY) {
5261 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5262 copy &= ~COPYFD_RESTORE;
5264 copyfd(copy, fd | COPYFD_EXACT);
5266 close(copy & ~COPYFD_RESTORE);
5269 redirlist = rp->next;
5270 g_nullredirs = rp->nullredirs;
5276 * Undo all redirections. Called on error or interrupt.
5280 * Discard all saved file descriptors.
5283 clearredir(int drop)
5289 popredir(drop, /*restore:*/ 0);
5294 redirectsafe(union node *redir, int flags)
5297 volatile int saveint;
5298 struct jmploc *volatile savehandler = exception_handler;
5299 struct jmploc jmploc;
5302 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5303 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5305 exception_handler = &jmploc;
5306 redirect(redir, flags);
5308 exception_handler = savehandler;
5309 if (err && exception_type != EXERROR)
5310 longjmp(exception_handler->loc, 1);
5311 RESTORE_INT(saveint);
5316 /* ============ Routines to expand arguments to commands
5318 * We have to deal with backquotes, shell variables, and file metacharacters.
5321 #if ENABLE_SH_MATH_SUPPORT
5323 ash_arith(const char *s)
5325 arith_eval_hooks_t math_hooks;
5329 math_hooks.lookupvar = lookupvar;
5330 math_hooks.setvar = setvar2;
5331 math_hooks.endofname = endofname;
5334 result = arith(s, &errcode, &math_hooks);
5337 ash_msg_and_raise_error("exponent less than 0");
5339 ash_msg_and_raise_error("divide by zero");
5341 ash_msg_and_raise_error("expression recursion loop detected");
5342 raise_error_syntax(s);
5353 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5354 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5355 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5356 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5357 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5358 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5359 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5360 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5361 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5365 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5366 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5367 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5368 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5369 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5372 * Structure specifying which parts of the string should be searched
5373 * for IFS characters.
5376 struct ifsregion *next; /* next region in list */
5377 int begoff; /* offset of start of region */
5378 int endoff; /* offset of end of region */
5379 int nulonly; /* search for nul bytes only */
5383 struct strlist *list;
5384 struct strlist **lastp;
5387 /* output of current string */
5388 static char *expdest;
5389 /* list of back quote expressions */
5390 static struct nodelist *argbackq;
5391 /* first struct in list of ifs regions */
5392 static struct ifsregion ifsfirst;
5393 /* last struct in list */
5394 static struct ifsregion *ifslastp;
5395 /* holds expanded arg list */
5396 static struct arglist exparg;
5406 expdest = makestrspace(32, expdest);
5407 len = fmtstr(expdest, 32, arith_t_fmt, num);
5408 STADJUST(len, expdest);
5413 esclen(const char *start, const char *p)
5417 while (p > start && (unsigned char)*--p == CTLESC) {
5424 * Remove any CTLESC characters from a string.
5427 rmescapes(char *str, int flag)
5429 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5433 unsigned protect_against_glob;
5436 p = strpbrk(str, qchars);
5442 if (flag & RMESCAPE_ALLOC) {
5443 size_t len = p - str;
5444 size_t fulllen = len + strlen(p) + 1;
5446 if (flag & RMESCAPE_GROW) {
5447 int strloc = str - (char *)stackblock();
5448 r = makestrspace(fulllen, expdest);
5449 /* p and str may be invalidated by makestrspace */
5450 str = (char *)stackblock() + strloc;
5452 } else if (flag & RMESCAPE_HEAP) {
5453 r = ckmalloc(fulllen);
5455 r = stalloc(fulllen);
5459 q = (char *)memcpy(q, str, len) + len;
5463 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5464 globbing = flag & RMESCAPE_GLOB;
5465 protect_against_glob = globbing;
5467 if ((unsigned char)*p == CTLQUOTEMARK) {
5468 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5469 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5470 // Note: both inquotes and protect_against_glob only affect whether
5471 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5472 inquotes = ~inquotes;
5474 protect_against_glob = globbing;
5478 /* naked back slash */
5479 protect_against_glob = 0;
5482 if ((unsigned char)*p == CTLESC) {
5484 if (protect_against_glob && inquotes && *p != '/') {
5488 protect_against_glob = globbing;
5493 if (flag & RMESCAPE_GROW) {
5495 STADJUST(q - r + 1, expdest);
5499 #define pmatch(a, b) !fnmatch((a), (b), 0)
5502 * Prepare a pattern for a expmeta (internal glob(3)) call.
5504 * Returns an stalloced string.
5507 preglob(const char *pattern, int quoted, int flag)
5509 flag |= RMESCAPE_GLOB;
5511 flag |= RMESCAPE_QUOTED;
5513 return rmescapes((char *)pattern, flag);
5517 * Put a string on the stack.
5520 memtodest(const char *p, size_t len, int syntax, int quotes)
5524 q = makestrspace(quotes ? len * 2 : len, q);
5527 unsigned char c = *p++;
5531 int n = SIT(c, syntax);
5532 if (n == CCTL || n == CBACK)
5542 strtodest(const char *p, int syntax, int quotes)
5544 memtodest(p, strlen(p), syntax, quotes);
5548 * Record the fact that we have to scan this region of the
5549 * string for IFS characters.
5552 recordregion(int start, int end, int nulonly)
5554 struct ifsregion *ifsp;
5556 if (ifslastp == NULL) {
5560 ifsp = ckzalloc(sizeof(*ifsp));
5561 /*ifsp->next = NULL; - ckzalloc did it */
5562 ifslastp->next = ifsp;
5566 ifslastp->begoff = start;
5567 ifslastp->endoff = end;
5568 ifslastp->nulonly = nulonly;
5572 removerecordregions(int endoff)
5574 if (ifslastp == NULL)
5577 if (ifsfirst.endoff > endoff) {
5578 while (ifsfirst.next != NULL) {
5579 struct ifsregion *ifsp;
5581 ifsp = ifsfirst.next->next;
5582 free(ifsfirst.next);
5583 ifsfirst.next = ifsp;
5586 if (ifsfirst.begoff > endoff)
5589 ifslastp = &ifsfirst;
5590 ifsfirst.endoff = endoff;
5595 ifslastp = &ifsfirst;
5596 while (ifslastp->next && ifslastp->next->begoff < endoff)
5597 ifslastp=ifslastp->next;
5598 while (ifslastp->next != NULL) {
5599 struct ifsregion *ifsp;
5601 ifsp = ifslastp->next->next;
5602 free(ifslastp->next);
5603 ifslastp->next = ifsp;
5606 if (ifslastp->endoff > endoff)
5607 ifslastp->endoff = endoff;
5611 exptilde(char *startp, char *p, int flags)
5617 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5622 while ((c = *++p) != '\0') {
5629 if (flags & EXP_VARTILDE)
5639 if (*name == '\0') {
5640 home = lookupvar("HOME");
5642 pw = getpwnam(name);
5647 if (!home || !*home)
5650 startloc = expdest - (char *)stackblock();
5651 strtodest(home, SQSYNTAX, quotes);
5652 recordregion(startloc, expdest - (char *)stackblock(), 0);
5660 * Execute a command inside back quotes. If it's a builtin command, we
5661 * want to save its output in a block obtained from malloc. Otherwise
5662 * we fork off a subprocess and get the output of the command via a pipe.
5663 * Should be called with interrupts off.
5665 struct backcmd { /* result of evalbackcmd */
5666 int fd; /* file descriptor to read from */
5667 int nleft; /* number of chars in buffer */
5668 char *buf; /* buffer */
5669 struct job *jp; /* job structure for command */
5672 /* These forward decls are needed to use "eval" code for backticks handling: */
5673 static uint8_t back_exitstatus; /* exit status of backquoted command */
5674 #define EV_EXIT 01 /* exit after evaluating tree */
5675 static void evaltree(union node *, int);
5677 static void FAST_FUNC
5678 evalbackcmd(union node *n, struct backcmd *result)
5689 saveherefd = herefd;
5697 ash_msg_and_raise_error("pipe call failed");
5698 jp = makejob(/*n,*/ 1);
5699 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5704 copyfd(pip[1], 1 | COPYFD_EXACT);
5708 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5712 result->fd = pip[0];
5715 herefd = saveherefd;
5717 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5718 result->fd, result->buf, result->nleft, result->jp));
5722 * Expand stuff in backwards quotes.
5725 expbackq(union node *cmd, int quoted, int quotes)
5733 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5734 struct stackmark smark;
5737 setstackmark(&smark);
5739 startloc = dest - (char *)stackblock();
5741 evalbackcmd(cmd, &in);
5742 popstackmark(&smark);
5749 memtodest(p, i, syntax, quotes);
5753 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5754 TRACE(("expbackq: read returns %d\n", i));
5763 back_exitstatus = waitforjob(in.jp);
5767 /* Eat all trailing newlines */
5769 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5774 recordregion(startloc, dest - (char *)stackblock(), 0);
5775 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5776 (dest - (char *)stackblock()) - startloc,
5777 (dest - (char *)stackblock()) - startloc,
5778 stackblock() + startloc));
5781 #if ENABLE_SH_MATH_SUPPORT
5783 * Expand arithmetic expression. Backup to start of expression,
5784 * evaluate, place result in (backed up) result, adjust string position.
5797 * This routine is slightly over-complicated for
5798 * efficiency. Next we scan backwards looking for the
5799 * start of arithmetic.
5801 start = stackblock();
5808 while ((unsigned char)*p != CTLARI) {
5812 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5817 esc = esclen(start, p);
5827 removerecordregions(begoff);
5834 rmescapes(p + 2, 0);
5836 len = cvtnum(ash_arith(p + 2));
5839 recordregion(begoff, begoff + len, 0);
5843 /* argstr needs it */
5844 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5847 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5848 * characters to allow for further processing. Otherwise treat
5849 * $@ like $* since no splitting will be performed.
5851 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5852 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5853 * for correct expansion of "B=$A" word.
5856 argstr(char *p, int flags, struct strlist *var_str_list)
5858 static const char spclchars[] ALIGN1 = {
5866 CTLBACKQ | CTLQUOTE,
5867 #if ENABLE_SH_MATH_SUPPORT
5872 const char *reject = spclchars;
5873 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5874 int breakall = flags & EXP_WORD;
5879 if (!(flags & EXP_VARTILDE)) {
5881 } else if (flags & EXP_VARTILDE2) {
5886 if (flags & EXP_TILDE) {
5889 flags &= ~EXP_TILDE;
5892 if (*q == CTLESC && (flags & EXP_QWORD))
5895 p = exptilde(p, q, flags);
5898 startloc = expdest - (char *)stackblock();
5902 length += strcspn(p + length, reject);
5906 #if ENABLE_SH_MATH_SUPPORT
5910 /* c == '=' || c == ':' || c == CTLENDARI */
5916 expdest = stack_nputstr(p, length, expdest);
5917 newloc = expdest - (char *)stackblock();
5918 if (breakall && !inquotes && newloc > startloc) {
5919 recordregion(startloc, newloc, 0);
5930 if (flags & EXP_VARTILDE2) {
5934 flags |= EXP_VARTILDE2;
5939 * sort of a hack - expand tildes in variable
5940 * assignments (after the first '=' and after ':'s).
5949 case CTLENDVAR: /* ??? */
5952 /* "$@" syntax adherence hack */
5954 && memcmp(p, dolatstr, 4) == 0
5955 && ( p[4] == CTLQUOTEMARK
5956 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5959 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
5962 inquotes = !inquotes;
5975 p = evalvar(p, flags, var_str_list);
5979 case CTLBACKQ|CTLQUOTE:
5980 expbackq(argbackq->n, c, quotes);
5981 argbackq = argbackq->next;
5983 #if ENABLE_SH_MATH_SUPPORT
5996 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
5999 // This commented out code was added by James Simmons <jsimmons@infradead.org>
6000 // as part of a larger change when he added support for ${var/a/b}.
6001 // However, it broke # and % operators:
6005 //echo ${var#ab} abcdcd abcdcd
6006 //echo ${var##ab} abcdcd abcdcd
6007 //echo ${var#a*b} abcdcd ababcdcd (!)
6008 //echo ${var##a*b} cdcd cdcd
6009 //echo ${var#?} babcdcd ababcdcd (!)
6010 //echo ${var##?} babcdcd babcdcd
6011 //echo ${var#*} ababcdcd babcdcd (!)
6013 //echo ${var%cd} ababcd ababcd
6014 //echo ${var%%cd} ababcd abab (!)
6015 //echo ${var%c*d} ababcd ababcd
6016 //echo ${var%%c*d} abab ababcdcd (!)
6017 //echo ${var%?} ababcdc ababcdc
6018 //echo ${var%%?} ababcdc ababcdcd (!)
6019 //echo ${var%*} ababcdcd ababcdcd
6022 // Commenting it back out helped. Remove it completely if it really
6025 char *loc, *loc2; //, *full;
6031 int match; // = strlen(str);
6032 const char *s = loc2;
6039 match = pmatch(str, s); // this line was deleted
6041 // // chop off end if its '*'
6042 // full = strrchr(str, '*');
6043 // if (full && full != str)
6046 // // If str starts with '*' replace with s.
6047 // if ((*str == '*') && strlen(s) >= match) {
6048 // full = xstrdup(s);
6049 // strncpy(full+strlen(s)-match+1, str+1, match-1);
6051 // full = xstrndup(str, match);
6052 // match = strncmp(s, full, strlen(full));
6056 if (match) // if (!match)
6058 if (quotes && (unsigned char)*loc == CTLESC)
6067 scanright(char *startp, char *rmesc, char *rmescend, char *pattern, int quotes, int match_at_start)
6069 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6070 int try2optimize = match_at_start;
6076 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6077 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6078 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6080 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6081 * and on each iteration they go back two/one char until they reach the beginning.
6082 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6084 /* TODO: document in what other circumstances we are called. */
6086 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6089 const char *s = loc2;
6090 if (match_at_start) {
6094 match = pmatch(pattern, s);
6095 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6099 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6101 /* Maybe we can optimize this:
6102 * if pattern ends with unescaped *, we can avoid checking
6103 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6104 * it wont match truncated "raw_value_of_" strings too.
6106 unsigned plen = strlen(pattern);
6107 /* Does it end with "*"? */
6108 if (plen != 0 && pattern[--plen] == '*') {
6109 /* "xxxx*" is not escaped */
6110 /* "xxx\*" is escaped */
6111 /* "xx\\*" is not escaped */
6112 /* "x\\\*" is escaped */
6114 while (plen != 0 && pattern[--plen] == '\\')
6117 break; /* ends with unescaped "*" */
6125 esc = esclen(startp, loc);
6136 static void varunset(const char *, const char *, const char *, int) NORETURN;
6138 varunset(const char *end, const char *var, const char *umsg, int varflags)
6144 msg = "parameter not set";
6146 if ((unsigned char)*end == CTLENDVAR) {
6147 if (varflags & VSNUL)
6153 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6156 #if ENABLE_ASH_BASH_COMPAT
6158 parse_sub_pattern(char *arg, int inquotes)
6160 char *idx, *repl = NULL;
6169 /* Only the first '/' seen is our separator */
6176 if (!inquotes && c == '\\' && arg[1] == '\\')
6177 arg++; /* skip both \\, not just first one */
6184 #endif /* ENABLE_ASH_BASH_COMPAT */
6187 subevalvar(char *p, char *str, int strloc, int subtype,
6188 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6190 struct nodelist *saveargbackq = argbackq;
6193 char *rmesc, *rmescend;
6194 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6195 IF_ASH_BASH_COMPAT(char null = '\0';)
6196 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6197 int saveherefd = herefd;
6198 int amount, workloc, resetloc;
6200 char *(*scan)(char*, char*, char*, char*, int, int);
6203 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6205 STPUTC('\0', expdest);
6206 herefd = saveherefd;
6207 argbackq = saveargbackq;
6208 startp = (char *)stackblock() + startloc;
6212 setvar(str, startp, 0);
6213 amount = startp - expdest;
6214 STADJUST(amount, expdest);
6217 #if ENABLE_ASH_BASH_COMPAT
6219 loc = str = stackblock() + strloc;
6220 /* Read POS in ${var:POS:LEN} */
6221 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6222 len = str - startp - 1;
6224 /* *loc != '\0', guaranteed by parser */
6228 /* Adjust the length by the number of escapes */
6229 for (ptr = startp; ptr < (str - 1); ptr++) {
6230 if ((unsigned char)*ptr == CTLESC) {
6238 if (*loc++ == ':') {
6242 /* Skip POS in ${var:POS:LEN} */
6244 while (*loc && *loc != ':') {
6246 * bash complains on: var=qwe; echo ${var:1a:123}
6248 ash_msg_and_raise_error(msg_illnum, str);
6252 if (*loc++ == ':') {
6256 if (pos >= orig_len) {
6260 if (len > (orig_len - pos))
6261 len = orig_len - pos;
6263 for (str = startp; pos; str++, pos--) {
6264 if (quotes && (unsigned char)*str == CTLESC)
6267 for (loc = startp; len; len--) {
6268 if (quotes && (unsigned char)*str == CTLESC)
6273 amount = loc - expdest;
6274 STADJUST(amount, expdest);
6279 varunset(p, str, startp, varflags);
6282 resetloc = expdest - (char *)stackblock();
6284 /* We'll comeback here if we grow the stack while handling
6285 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6286 * stack will need rebasing, and we'll need to remove our work
6289 IF_ASH_BASH_COMPAT(restart:)
6291 amount = expdest - ((char *)stackblock() + resetloc);
6292 STADJUST(-amount, expdest);
6293 startp = (char *)stackblock() + startloc;
6296 rmescend = (char *)stackblock() + strloc;
6298 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6299 if (rmesc != startp) {
6301 startp = (char *)stackblock() + startloc;
6305 str = (char *)stackblock() + strloc;
6306 preglob(str, varflags & VSQUOTE, 0);
6307 workloc = expdest - (char *)stackblock();
6309 #if ENABLE_ASH_BASH_COMPAT
6310 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6314 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6319 /* If there's no pattern to match, return the expansion unmolested */
6328 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6330 /* No match, advance */
6331 char *restart_detect = stackblock();
6333 STPUTC(*idx, expdest);
6334 if (quotes && (unsigned char)*idx == CTLESC) {
6337 STPUTC(*idx, expdest);
6339 if (stackblock() != restart_detect)
6344 /* continue; - prone to quadratic behavior, smarter code: */
6347 if (str[0] == '*') {
6348 /* Pattern is "*foo". If "*foo" does not match "long_string",
6349 * it would never match "ong_string" etc, no point in trying.
6356 if (subtype == VSREPLACEALL) {
6358 if (quotes && (unsigned char)*idx == CTLESC)
6367 for (loc = repl; *loc; loc++) {
6368 char *restart_detect = stackblock();
6369 STPUTC(*loc, expdest);
6370 if (stackblock() != restart_detect)
6375 if (subtype == VSREPLACE) {
6377 char *restart_detect = stackblock();
6378 STPUTC(*idx, expdest);
6379 if (stackblock() != restart_detect)
6388 /* We've put the replaced text into a buffer at workloc, now
6389 * move it to the right place and adjust the stack.
6391 startp = stackblock() + startloc;
6392 STPUTC('\0', expdest);
6393 memmove(startp, stackblock() + workloc, len);
6394 startp[len++] = '\0';
6395 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6396 STADJUST(-amount, expdest);
6399 #endif /* ENABLE_ASH_BASH_COMPAT */
6401 subtype -= VSTRIMRIGHT;
6403 if (subtype < 0 || subtype > 7)
6406 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6407 zero = subtype >> 1;
6408 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6409 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6411 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6414 memmove(startp, loc, str - loc);
6415 loc = startp + (str - loc) - 1;
6418 amount = loc - expdest;
6419 STADJUST(amount, expdest);
6425 * Add the value of a specialized variable to the stack string.
6426 * name parameter (examples):
6427 * ash -c 'echo $1' name:'1='
6428 * ash -c 'echo $qwe' name:'qwe='
6429 * ash -c 'echo $$' name:'$='
6430 * ash -c 'echo ${$}' name:'$='
6431 * ash -c 'echo ${$##q}' name:'$=q'
6432 * ash -c 'echo ${#$}' name:'$='
6433 * note: examples with bad shell syntax:
6434 * ash -c 'echo ${#$1}' name:'$=1'
6435 * ash -c 'echo ${#1#}' name:'1=#'
6437 static NOINLINE ssize_t
6438 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6445 int subtype = varflags & VSTYPE;
6446 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6447 int quoted = varflags & VSQUOTE;
6448 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6458 num = shellparam.nparam;
6466 goto check_1char_name;
6468 expdest = makestrspace(NOPTS, expdest);
6469 for (i = NOPTS - 1; i >= 0; i--) {
6471 USTPUTC(optletters(i), expdest);
6477 /* handles cases similar to ${#$1} */
6478 if (name[2] != '\0')
6479 raise_error_syntax("bad substitution");
6486 if (quoted && (flags & EXP_FULL)) {
6487 /* note: this is not meant as PEOF value */
6488 sep = 1 << CHAR_BIT;
6493 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6494 i = SIT(sep, syntax);
6495 if (quotes && (i == CCTL || i == CBACK))
6501 while ((p = *ap++) != NULL) {
6504 partlen = strlen(p);
6507 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6508 memtodest(p, partlen, syntax, quotes);
6514 if (subtype == VSPLUS || subtype == VSLENGTH) {
6520 /* note: may put NUL despite sep != 0
6521 * (see sep = 1 << CHAR_BIT above) */
6527 } /* case '@' and '*' */
6538 num = atoi(name); /* number(name) fails on ${N#str} etc */
6539 if (num < 0 || num > shellparam.nparam)
6541 p = num ? shellparam.p[num - 1] : arg0;
6544 /* NB: name has form "VAR=..." */
6546 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6547 * which should be considered before we check variables. */
6549 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6553 str = var_str_list->text;
6554 eq = strchr(str, '=');
6555 if (!eq) /* stop at first non-assignment */
6558 if (name_len == (unsigned)(eq - str)
6559 && strncmp(str, name, name_len) == 0
6562 /* goto value; - WRONG! */
6563 /* think "A=1 A=2 B=$A" */
6565 var_str_list = var_str_list->next;
6566 } while (var_str_list);
6570 p = lookupvar(name);
6576 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6577 memtodest(p, len, syntax, quotes);
6581 if (subtype == VSPLUS || subtype == VSLENGTH)
6582 STADJUST(-len, expdest);
6587 * Expand a variable, and return a pointer to the next character in the
6591 evalvar(char *p, int flags, struct strlist *var_str_list)
6602 varflags = (unsigned char) *p++;
6603 subtype = varflags & VSTYPE;
6604 quoted = varflags & VSQUOTE;
6606 easy = (!quoted || (*var == '@' && shellparam.nparam));
6607 startloc = expdest - (char *)stackblock();
6608 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6611 varlen = varvalue(var, varflags, flags, var_str_list);
6612 if (varflags & VSNUL)
6615 if (subtype == VSPLUS) {
6616 varlen = -1 - varlen;
6620 if (subtype == VSMINUS) {
6624 p, flags | EXP_TILDE |
6625 (quoted ? EXP_QWORD : EXP_WORD),
6635 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6637 if (subevalvar(p, var, /* strloc: */ 0,
6638 subtype, startloc, varflags,
6644 * Remove any recorded regions beyond
6647 removerecordregions(startloc);
6657 if (varlen < 0 && uflag)
6658 varunset(p, var, 0, 0);
6660 if (subtype == VSLENGTH) {
6661 cvtnum(varlen > 0 ? varlen : 0);
6665 if (subtype == VSNORMAL) {
6676 case VSTRIMRIGHTMAX:
6677 #if ENABLE_ASH_BASH_COMPAT
6690 * Terminate the string and start recording the pattern
6693 STPUTC('\0', expdest);
6694 patloc = expdest - (char *)stackblock();
6695 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6697 //TODO: | EXP_REDIR too? All other such places do it too
6698 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6701 int amount = expdest - (
6702 (char *)stackblock() + patloc - 1
6704 STADJUST(-amount, expdest);
6706 /* Remove any recorded regions beyond start of variable */
6707 removerecordregions(startloc);
6709 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6713 if (subtype != VSNORMAL) { /* skip to end of alternative */
6716 unsigned char c = *p++;
6719 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6721 argbackq = argbackq->next;
6722 } else if (c == CTLVAR) {
6723 if ((*p++ & VSTYPE) != VSNORMAL)
6725 } else if (c == CTLENDVAR) {
6735 * Break the argument string into pieces based upon IFS and add the
6736 * strings to the argument list. The regions of the string to be
6737 * searched for IFS characters have been stored by recordregion.
6740 ifsbreakup(char *string, struct arglist *arglist)
6742 struct ifsregion *ifsp;
6747 const char *ifs, *realifs;
6752 if (ifslastp != NULL) {
6755 realifs = ifsset() ? ifsval() : defifs;
6758 p = string + ifsp->begoff;
6759 nulonly = ifsp->nulonly;
6760 ifs = nulonly ? nullstr : realifs;
6762 while (p < string + ifsp->endoff) {
6764 if ((unsigned char)*p == CTLESC)
6766 if (!strchr(ifs, *p)) {
6771 ifsspc = (strchr(defifs, *p) != NULL);
6772 /* Ignore IFS whitespace at start */
6773 if (q == start && ifsspc) {
6779 sp = stzalloc(sizeof(*sp));
6781 *arglist->lastp = sp;
6782 arglist->lastp = &sp->next;
6786 if (p >= string + ifsp->endoff) {
6790 if ((unsigned char)*p == CTLESC)
6792 if (strchr(ifs, *p) == NULL) {
6796 if (strchr(defifs, *p) == NULL) {
6811 } while (ifsp != NULL);
6820 sp = stzalloc(sizeof(*sp));
6822 *arglist->lastp = sp;
6823 arglist->lastp = &sp->next;
6829 struct ifsregion *p;
6834 struct ifsregion *ifsp;
6840 ifsfirst.next = NULL;
6845 * Add a file name to the list.
6848 addfname(const char *name)
6852 sp = stzalloc(sizeof(*sp));
6853 sp->text = ststrdup(name);
6855 exparg.lastp = &sp->next;
6858 static char *expdir;
6861 * Do metacharacter (i.e. *, ?, [...]) expansion.
6864 expmeta(char *enddir, char *name)
6879 for (p = name; *p; p++) {
6880 if (*p == '*' || *p == '?')
6882 else if (*p == '[') {
6889 if (*q == '/' || *q == '\0')
6896 } else if (*p == '\\')
6898 else if (*p == '/') {
6905 if (metaflag == 0) { /* we've reached the end of the file name */
6906 if (enddir != expdir)
6914 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6925 } while (p < start);
6927 if (enddir == expdir) {
6929 } else if (enddir == expdir + 1 && *expdir == '/') {
6938 if (enddir != expdir)
6940 if (*endname == 0) {
6952 while (!pending_int && (dp = readdir(dirp)) != NULL) {
6953 if (dp->d_name[0] == '.' && !matchdot)
6955 if (pmatch(start, dp->d_name)) {
6957 strcpy(enddir, dp->d_name);
6960 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6963 expmeta(p, endname);
6972 static struct strlist *
6973 msort(struct strlist *list, int len)
6975 struct strlist *p, *q = NULL;
6976 struct strlist **lpp;
6984 for (n = half; --n >= 0;) {
6988 q->next = NULL; /* terminate first half of list */
6989 q = msort(list, half); /* sort first half of list */
6990 p = msort(p, len - half); /* sort second half */
6993 #if ENABLE_LOCALE_SUPPORT
6994 if (strcoll(p->text, q->text) < 0)
6996 if (strcmp(p->text, q->text) < 0)
7020 * Sort the results of file name expansion. It calculates the number of
7021 * strings to sort and then calls msort (short for merge sort) to do the
7024 static struct strlist *
7025 expsort(struct strlist *str)
7031 for (sp = str; sp; sp = sp->next)
7033 return msort(str, len);
7037 expandmeta(struct strlist *str /*, int flag*/)
7039 static const char metachars[] ALIGN1 = {
7042 /* TODO - EXP_REDIR */
7045 struct strlist **savelastp;
7051 if (!strpbrk(str->text, metachars))
7053 savelastp = exparg.lastp;
7056 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7058 int i = strlen(str->text);
7059 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7067 if (exparg.lastp == savelastp) {
7072 *exparg.lastp = str;
7073 rmescapes(str->text, 0);
7074 exparg.lastp = &str->next;
7076 *exparg.lastp = NULL;
7077 *savelastp = sp = expsort(*savelastp);
7078 while (sp->next != NULL)
7080 exparg.lastp = &sp->next;
7087 * Perform variable substitution and command substitution on an argument,
7088 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7089 * perform splitting and file name expansion. When arglist is NULL, perform
7090 * here document expansion.
7093 expandarg(union node *arg, struct arglist *arglist, int flag)
7098 argbackq = arg->narg.backquote;
7099 STARTSTACKSTR(expdest);
7100 ifsfirst.next = NULL;
7102 argstr(arg->narg.text, flag,
7103 /* var_str_list: */ arglist ? arglist->list : NULL);
7104 p = _STPUTC('\0', expdest);
7106 if (arglist == NULL) {
7107 return; /* here document expanded */
7109 p = grabstackstr(p);
7110 exparg.lastp = &exparg.list;
7114 if (flag & EXP_FULL) {
7115 ifsbreakup(p, &exparg);
7116 *exparg.lastp = NULL;
7117 exparg.lastp = &exparg.list;
7118 expandmeta(exparg.list /*, flag*/);
7120 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7122 sp = stzalloc(sizeof(*sp));
7125 exparg.lastp = &sp->next;
7129 *exparg.lastp = NULL;
7131 *arglist->lastp = exparg.list;
7132 arglist->lastp = exparg.lastp;
7137 * Expand shell variables and backquotes inside a here document.
7140 expandhere(union node *arg, int fd)
7143 expandarg(arg, (struct arglist *)NULL, 0);
7144 full_write(fd, stackblock(), expdest - (char *)stackblock());
7148 * Returns true if the pattern matches the string.
7151 patmatch(char *pattern, const char *string)
7153 return pmatch(preglob(pattern, 0, 0), string);
7157 * See if a pattern matches in a case statement.
7160 casematch(union node *pattern, char *val)
7162 struct stackmark smark;
7165 setstackmark(&smark);
7166 argbackq = pattern->narg.backquote;
7167 STARTSTACKSTR(expdest);
7169 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7170 /* var_str_list: */ NULL);
7171 STACKSTRNUL(expdest);
7172 result = patmatch(stackblock(), val);
7173 popstackmark(&smark);
7178 /* ============ find_command */
7182 int (*builtin)(int, char **) FAST_FUNC;
7183 /* unsigned flags; */
7185 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7186 /* "regular" builtins always take precedence over commands,
7187 * regardless of PATH=....%builtin... position */
7188 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7189 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7192 smallint cmdtype; /* CMDxxx */
7195 /* index >= 0 for commands without path (slashes) */
7196 /* (TODO: what exactly does the value mean? PATH position?) */
7197 /* index == -1 for commands with slashes */
7198 /* index == (-2 - applet_no) for NOFORK applets */
7199 const struct builtincmd *cmd;
7200 struct funcnode *func;
7203 /* values of cmdtype */
7204 #define CMDUNKNOWN -1 /* no entry in table for command */
7205 #define CMDNORMAL 0 /* command is an executable program */
7206 #define CMDFUNCTION 1 /* command is a shell function */
7207 #define CMDBUILTIN 2 /* command is a shell builtin */
7209 /* action to find_command() */
7210 #define DO_ERR 0x01 /* prints errors */
7211 #define DO_ABS 0x02 /* checks absolute paths */
7212 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7213 #define DO_ALTPATH 0x08 /* using alternate path */
7214 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7216 static void find_command(char *, struct cmdentry *, int, const char *);
7219 /* ============ Hashing commands */
7222 * When commands are first encountered, they are entered in a hash table.
7223 * This ensures that a full path search will not have to be done for them
7224 * on each invocation.
7226 * We should investigate converting to a linear search, even though that
7227 * would make the command name "hash" a misnomer.
7231 struct tblentry *next; /* next entry in hash chain */
7232 union param param; /* definition of builtin function */
7233 smallint cmdtype; /* CMDxxx */
7234 char rehash; /* if set, cd done since entry created */
7235 char cmdname[1]; /* name of command */
7238 static struct tblentry **cmdtable;
7239 #define INIT_G_cmdtable() do { \
7240 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7243 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7247 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7251 #if ENABLE_FEATURE_SH_STANDALONE
7252 if (applet_no >= 0) {
7253 if (APPLET_IS_NOEXEC(applet_no)) {
7256 run_applet_no_and_exit(applet_no, argv);
7258 /* re-exec ourselves with the new arguments */
7259 execve(bb_busybox_exec_path, argv, envp);
7260 /* If they called chroot or otherwise made the binary no longer
7261 * executable, fall through */
7268 execve(cmd, argv, envp);
7269 } while (errno == EINTR);
7271 execve(cmd, argv, envp);
7277 if (errno == ENOEXEC) {
7281 for (ap = argv; *ap; ap++)
7283 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7285 ap[0] = cmd = (char *)DEFAULT_SHELL;
7288 while ((*ap++ = *argv++) != NULL)
7297 * Exec a program. Never returns. If you change this routine, you may
7298 * have to change the find_command routine as well.
7300 static void shellexec(char **, const char *, int) NORETURN;
7302 shellexec(char **argv, const char *path, int idx)
7308 #if ENABLE_FEATURE_SH_STANDALONE
7312 clearredir(/*drop:*/ 1);
7313 envp = listvars(VEXPORT, VUNSET, 0);
7314 if (strchr(argv[0], '/') != NULL
7315 #if ENABLE_FEATURE_SH_STANDALONE
7316 || (applet_no = find_applet_by_name(argv[0])) >= 0
7319 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7323 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7324 if (--idx < 0 && pathopt == NULL) {
7325 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7326 if (errno != ENOENT && errno != ENOTDIR)
7333 /* Map to POSIX errors */
7345 exitstatus = exerrno;
7346 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7347 argv[0], e, suppress_int));
7348 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7353 printentry(struct tblentry *cmdp)
7359 idx = cmdp->param.index;
7362 name = path_advance(&path, cmdp->cmdname);
7364 } while (--idx >= 0);
7365 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7369 * Clear out command entries. The argument specifies the first entry in
7370 * PATH which has changed.
7373 clearcmdentry(int firstchange)
7375 struct tblentry **tblp;
7376 struct tblentry **pp;
7377 struct tblentry *cmdp;
7380 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7382 while ((cmdp = *pp) != NULL) {
7383 if ((cmdp->cmdtype == CMDNORMAL &&
7384 cmdp->param.index >= firstchange)
7385 || (cmdp->cmdtype == CMDBUILTIN &&
7386 builtinloc >= firstchange)
7399 * Locate a command in the command hash table. If "add" is nonzero,
7400 * add the command to the table if it is not already present. The
7401 * variable "lastcmdentry" is set to point to the address of the link
7402 * pointing to the entry, so that delete_cmd_entry can delete the
7405 * Interrupts must be off if called with add != 0.
7407 static struct tblentry **lastcmdentry;
7409 static struct tblentry *
7410 cmdlookup(const char *name, int add)
7412 unsigned int hashval;
7414 struct tblentry *cmdp;
7415 struct tblentry **pp;
7418 hashval = (unsigned char)*p << 4;
7420 hashval += (unsigned char)*p++;
7422 pp = &cmdtable[hashval % CMDTABLESIZE];
7423 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7424 if (strcmp(cmdp->cmdname, name) == 0)
7428 if (add && cmdp == NULL) {
7429 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7431 /* + 1 - already done because
7432 * tblentry::cmdname is char[1] */);
7433 /*cmdp->next = NULL; - ckzalloc did it */
7434 cmdp->cmdtype = CMDUNKNOWN;
7435 strcpy(cmdp->cmdname, name);
7442 * Delete the command entry returned on the last lookup.
7445 delete_cmd_entry(void)
7447 struct tblentry *cmdp;
7450 cmdp = *lastcmdentry;
7451 *lastcmdentry = cmdp->next;
7452 if (cmdp->cmdtype == CMDFUNCTION)
7453 freefunc(cmdp->param.func);
7459 * Add a new command entry, replacing any existing command entry for
7460 * the same name - except special builtins.
7463 addcmdentry(char *name, struct cmdentry *entry)
7465 struct tblentry *cmdp;
7467 cmdp = cmdlookup(name, 1);
7468 if (cmdp->cmdtype == CMDFUNCTION) {
7469 freefunc(cmdp->param.func);
7471 cmdp->cmdtype = entry->cmdtype;
7472 cmdp->param = entry->u;
7476 static int FAST_FUNC
7477 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7479 struct tblentry **pp;
7480 struct tblentry *cmdp;
7482 struct cmdentry entry;
7485 if (nextopt("r") != '\0') {
7490 if (*argptr == NULL) {
7491 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7492 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7493 if (cmdp->cmdtype == CMDNORMAL)
7501 while ((name = *argptr) != NULL) {
7502 cmdp = cmdlookup(name, 0);
7504 && (cmdp->cmdtype == CMDNORMAL
7505 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7509 find_command(name, &entry, DO_ERR, pathval());
7510 if (entry.cmdtype == CMDUNKNOWN)
7518 * Called when a cd is done. Marks all commands so the next time they
7519 * are executed they will be rehashed.
7524 struct tblentry **pp;
7525 struct tblentry *cmdp;
7527 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7528 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7529 if (cmdp->cmdtype == CMDNORMAL
7530 || (cmdp->cmdtype == CMDBUILTIN
7531 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7541 * Fix command hash table when PATH changed.
7542 * Called before PATH is changed. The argument is the new value of PATH;
7543 * pathval() still returns the old value at this point.
7544 * Called with interrupts off.
7546 static void FAST_FUNC
7547 changepath(const char *new)
7555 firstchange = 9999; /* assume no change */
7561 if ((*old == '\0' && *new == ':')
7562 || (*old == ':' && *new == '\0')
7566 old = new; /* ignore subsequent differences */
7570 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7577 if (builtinloc < 0 && idx_bltin >= 0)
7578 builtinloc = idx_bltin; /* zap builtins */
7579 if (builtinloc >= 0 && idx_bltin < 0)
7581 clearcmdentry(firstchange);
7582 builtinloc = idx_bltin;
7597 #define TENDBQUOTE 12
7614 typedef smallint token_id_t;
7616 /* first char is indicating which tokens mark the end of a list */
7617 static const char *const tokname_array[] = {
7631 #define KWDOFFSET 13
7632 /* the following are keywords */
7651 /* Wrapper around strcmp for qsort/bsearch/... */
7653 pstrcmp(const void *a, const void *b)
7655 return strcmp((char*) a, (*(char**) b) + 1);
7658 static const char *const *
7659 findkwd(const char *s)
7661 return bsearch(s, tokname_array + KWDOFFSET,
7662 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7663 sizeof(tokname_array[0]), pstrcmp);
7667 * Locate and print what a word is...
7670 describe_command(char *command, int describe_command_verbose)
7672 struct cmdentry entry;
7673 struct tblentry *cmdp;
7674 #if ENABLE_ASH_ALIAS
7675 const struct alias *ap;
7677 const char *path = pathval();
7679 if (describe_command_verbose) {
7683 /* First look at the keywords */
7684 if (findkwd(command)) {
7685 out1str(describe_command_verbose ? " is a shell keyword" : command);
7689 #if ENABLE_ASH_ALIAS
7690 /* Then look at the aliases */
7691 ap = lookupalias(command, 0);
7693 if (!describe_command_verbose) {
7698 out1fmt(" is an alias for %s", ap->val);
7702 /* Then check if it is a tracked alias */
7703 cmdp = cmdlookup(command, 0);
7705 entry.cmdtype = cmdp->cmdtype;
7706 entry.u = cmdp->param;
7708 /* Finally use brute force */
7709 find_command(command, &entry, DO_ABS, path);
7712 switch (entry.cmdtype) {
7714 int j = entry.u.index;
7720 p = path_advance(&path, command);
7724 if (describe_command_verbose) {
7726 (cmdp ? " a tracked alias for" : nullstr), p
7735 if (describe_command_verbose) {
7736 out1str(" is a shell function");
7743 if (describe_command_verbose) {
7744 out1fmt(" is a %sshell builtin",
7745 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7746 "special " : nullstr
7754 if (describe_command_verbose) {
7755 out1str(": not found\n");
7764 static int FAST_FUNC
7765 typecmd(int argc UNUSED_PARAM, char **argv)
7771 /* type -p ... ? (we don't bother checking for 'p') */
7772 if (argv[1] && argv[1][0] == '-') {
7777 err |= describe_command(argv[i++], verbose);
7782 #if ENABLE_ASH_CMDCMD
7783 static int FAST_FUNC
7784 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7792 while ((c = nextopt("pvV")) != '\0')
7794 verify |= VERIFY_VERBOSE;
7796 verify |= VERIFY_BRIEF;
7801 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7802 if (verify && (*argptr != NULL)) {
7803 return describe_command(*argptr, verify - VERIFY_BRIEF);
7811 /* ============ eval.c */
7813 static int funcblocksize; /* size of structures in function */
7814 static int funcstringsize; /* size of strings in node */
7815 static void *funcblock; /* block to allocate function from */
7816 static char *funcstring; /* block to allocate strings from */
7818 /* flags in argument to evaltree */
7819 #define EV_EXIT 01 /* exit after evaluating tree */
7820 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7821 #define EV_BACKCMD 04 /* command executing within back quotes */
7823 static const uint8_t nodesize[N_NUMBER] = {
7824 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7825 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7826 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7827 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7828 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7829 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7830 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7831 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7832 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7833 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7834 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7835 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7836 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7837 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7838 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7839 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7840 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7841 #if ENABLE_ASH_BASH_COMPAT
7842 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7844 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7845 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7846 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7847 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7848 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7849 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7850 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7851 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7852 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7855 static void calcsize(union node *n);
7858 sizenodelist(struct nodelist *lp)
7861 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7868 calcsize(union node *n)
7872 funcblocksize += nodesize[n->type];
7875 calcsize(n->ncmd.redirect);
7876 calcsize(n->ncmd.args);
7877 calcsize(n->ncmd.assign);
7880 sizenodelist(n->npipe.cmdlist);
7885 calcsize(n->nredir.redirect);
7886 calcsize(n->nredir.n);
7893 calcsize(n->nbinary.ch2);
7894 calcsize(n->nbinary.ch1);
7897 calcsize(n->nif.elsepart);
7898 calcsize(n->nif.ifpart);
7899 calcsize(n->nif.test);
7902 funcstringsize += strlen(n->nfor.var) + 1;
7903 calcsize(n->nfor.body);
7904 calcsize(n->nfor.args);
7907 calcsize(n->ncase.cases);
7908 calcsize(n->ncase.expr);
7911 calcsize(n->nclist.body);
7912 calcsize(n->nclist.pattern);
7913 calcsize(n->nclist.next);
7917 sizenodelist(n->narg.backquote);
7918 funcstringsize += strlen(n->narg.text) + 1;
7919 calcsize(n->narg.next);
7922 #if ENABLE_ASH_BASH_COMPAT
7929 calcsize(n->nfile.fname);
7930 calcsize(n->nfile.next);
7934 calcsize(n->ndup.vname);
7935 calcsize(n->ndup.next);
7939 calcsize(n->nhere.doc);
7940 calcsize(n->nhere.next);
7943 calcsize(n->nnot.com);
7949 nodeckstrdup(char *s)
7951 char *rtn = funcstring;
7953 strcpy(funcstring, s);
7954 funcstring += strlen(s) + 1;
7958 static union node *copynode(union node *);
7960 static struct nodelist *
7961 copynodelist(struct nodelist *lp)
7963 struct nodelist *start;
7964 struct nodelist **lpp;
7969 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7970 (*lpp)->n = copynode(lp->n);
7972 lpp = &(*lpp)->next;
7979 copynode(union node *n)
7986 funcblock = (char *) funcblock + nodesize[n->type];
7990 new->ncmd.redirect = copynode(n->ncmd.redirect);
7991 new->ncmd.args = copynode(n->ncmd.args);
7992 new->ncmd.assign = copynode(n->ncmd.assign);
7995 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7996 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8001 new->nredir.redirect = copynode(n->nredir.redirect);
8002 new->nredir.n = copynode(n->nredir.n);
8009 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8010 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8013 new->nif.elsepart = copynode(n->nif.elsepart);
8014 new->nif.ifpart = copynode(n->nif.ifpart);
8015 new->nif.test = copynode(n->nif.test);
8018 new->nfor.var = nodeckstrdup(n->nfor.var);
8019 new->nfor.body = copynode(n->nfor.body);
8020 new->nfor.args = copynode(n->nfor.args);
8023 new->ncase.cases = copynode(n->ncase.cases);
8024 new->ncase.expr = copynode(n->ncase.expr);
8027 new->nclist.body = copynode(n->nclist.body);
8028 new->nclist.pattern = copynode(n->nclist.pattern);
8029 new->nclist.next = copynode(n->nclist.next);
8033 new->narg.backquote = copynodelist(n->narg.backquote);
8034 new->narg.text = nodeckstrdup(n->narg.text);
8035 new->narg.next = copynode(n->narg.next);
8038 #if ENABLE_ASH_BASH_COMPAT
8045 new->nfile.fname = copynode(n->nfile.fname);
8046 new->nfile.fd = n->nfile.fd;
8047 new->nfile.next = copynode(n->nfile.next);
8051 new->ndup.vname = copynode(n->ndup.vname);
8052 new->ndup.dupfd = n->ndup.dupfd;
8053 new->ndup.fd = n->ndup.fd;
8054 new->ndup.next = copynode(n->ndup.next);
8058 new->nhere.doc = copynode(n->nhere.doc);
8059 new->nhere.fd = n->nhere.fd;
8060 new->nhere.next = copynode(n->nhere.next);
8063 new->nnot.com = copynode(n->nnot.com);
8066 new->type = n->type;
8071 * Make a copy of a parse tree.
8073 static struct funcnode *
8074 copyfunc(union node *n)
8079 funcblocksize = offsetof(struct funcnode, n);
8082 blocksize = funcblocksize;
8083 f = ckmalloc(blocksize + funcstringsize);
8084 funcblock = (char *) f + offsetof(struct funcnode, n);
8085 funcstring = (char *) f + blocksize;
8092 * Define a shell function.
8095 defun(char *name, union node *func)
8097 struct cmdentry entry;
8100 entry.cmdtype = CMDFUNCTION;
8101 entry.u.func = copyfunc(func);
8102 addcmdentry(name, &entry);
8106 /* Reasons for skipping commands (see comment on breakcmd routine) */
8107 #define SKIPBREAK (1 << 0)
8108 #define SKIPCONT (1 << 1)
8109 #define SKIPFUNC (1 << 2)
8110 #define SKIPFILE (1 << 3)
8111 #define SKIPEVAL (1 << 4)
8112 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8113 static int skipcount; /* number of levels to skip */
8114 static int funcnest; /* depth of function calls */
8115 static int loopnest; /* current loop nesting level */
8117 /* Forward decl way out to parsing code - dotrap needs it */
8118 static int evalstring(char *s, int mask);
8120 /* Called to execute a trap.
8121 * Single callsite - at the end of evaltree().
8122 * If we return non-zero, exaltree raises EXEXIT exception.
8124 * Perhaps we should avoid entering new trap handlers
8125 * while we are executing a trap handler. [is it a TODO?]
8134 savestatus = exitstatus;
8138 TRACE(("dotrap entered\n"));
8139 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8146 /* non-trapped SIGINT is handled separately by raise_interrupt,
8147 * don't upset it by resetting gotsig[SIGINT-1] */
8148 if (sig == SIGINT && !t)
8151 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8155 want_exexit = evalstring(t, SKIPEVAL);
8156 exitstatus = savestatus;
8158 TRACE(("dotrap returns %d\n", want_exexit));
8163 TRACE(("dotrap returns 0\n"));
8167 /* forward declarations - evaluation is fairly recursive business... */
8168 static void evalloop(union node *, int);
8169 static void evalfor(union node *, int);
8170 static void evalcase(union node *, int);
8171 static void evalsubshell(union node *, int);
8172 static void expredir(union node *);
8173 static void evalpipe(union node *, int);
8174 static void evalcommand(union node *, int);
8175 static int evalbltin(const struct builtincmd *, int, char **);
8176 static void prehash(union node *);
8179 * Evaluate a parse tree. The value is left in the global variable
8183 evaltree(union node *n, int flags)
8185 struct jmploc *volatile savehandler = exception_handler;
8186 struct jmploc jmploc;
8188 void (*evalfn)(union node *, int);
8192 SAVE_INT(int_level);
8195 TRACE(("evaltree(NULL) called\n"));
8198 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8200 exception_handler = &jmploc;
8202 int err = setjmp(jmploc.loc);
8204 /* if it was a signal, check for trap handlers */
8205 if (exception_type == EXSIG) {
8206 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8207 exception_type, err));
8210 /* continue on the way out */
8211 TRACE(("exception %d in evaltree, propagating err=%d\n",
8212 exception_type, err));
8213 exception_handler = savehandler;
8214 longjmp(exception_handler->loc, err);
8221 out1fmt("Node type = %d\n", n->type);
8226 evaltree(n->nnot.com, EV_TESTED);
8227 status = !exitstatus;
8230 expredir(n->nredir.redirect);
8231 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8233 evaltree(n->nredir.n, flags & EV_TESTED);
8234 status = exitstatus;
8236 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8239 evalfn = evalcommand;
8241 if (eflag && !(flags & EV_TESTED))
8253 evalfn = evalsubshell;
8266 #error NAND + 1 != NOR
8268 #if NOR + 1 != NSEMI
8269 #error NOR + 1 != NSEMI
8271 unsigned is_or = n->type - NAND;
8274 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8276 if (!exitstatus == is_or)
8289 evaltree(n->nif.test, EV_TESTED);
8292 if (exitstatus == 0) {
8296 if (n->nif.elsepart) {
8297 n = n->nif.elsepart;
8302 defun(n->narg.text, n->narg.next);
8306 exitstatus = status;
8311 exception_handler = savehandler;
8313 if (checkexit & exitstatus)
8314 evalskip |= SKIPEVAL;
8315 else if (pending_sig && dotrap())
8318 if (flags & EV_EXIT) {
8320 raise_exception(EXEXIT);
8323 RESTORE_INT(int_level);
8324 TRACE(("leaving evaltree (no interrupts)\n"));
8327 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8330 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8333 evalloop(union node *n, int flags)
8343 evaltree(n->nbinary.ch1, EV_TESTED);
8346 if (evalskip == SKIPCONT && --skipcount <= 0) {
8350 if (evalskip == SKIPBREAK && --skipcount <= 0)
8355 if (n->type != NWHILE)
8359 evaltree(n->nbinary.ch2, flags);
8360 status = exitstatus;
8365 exitstatus = status;
8369 evalfor(union node *n, int flags)
8371 struct arglist arglist;
8374 struct stackmark smark;
8376 setstackmark(&smark);
8377 arglist.list = NULL;
8378 arglist.lastp = &arglist.list;
8379 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8380 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8385 *arglist.lastp = NULL;
8390 for (sp = arglist.list; sp; sp = sp->next) {
8391 setvar(n->nfor.var, sp->text, 0);
8392 evaltree(n->nfor.body, flags);
8394 if (evalskip == SKIPCONT && --skipcount <= 0) {
8398 if (evalskip == SKIPBREAK && --skipcount <= 0)
8405 popstackmark(&smark);
8409 evalcase(union node *n, int flags)
8413 struct arglist arglist;
8414 struct stackmark smark;
8416 setstackmark(&smark);
8417 arglist.list = NULL;
8418 arglist.lastp = &arglist.list;
8419 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8421 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8422 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8423 if (casematch(patp, arglist.list->text)) {
8424 if (evalskip == 0) {
8425 evaltree(cp->nclist.body, flags);
8432 popstackmark(&smark);
8436 * Kick off a subshell to evaluate a tree.
8439 evalsubshell(union node *n, int flags)
8442 int backgnd = (n->type == NBACKGND);
8445 expredir(n->nredir.redirect);
8446 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8449 jp = makejob(/*n,*/ 1);
8450 if (forkshell(jp, n, backgnd) == 0) {
8455 flags &= ~EV_TESTED;
8457 redirect(n->nredir.redirect, 0);
8458 evaltreenr(n->nredir.n, flags);
8463 status = waitforjob(jp);
8464 exitstatus = status;
8469 * Compute the names of the files in a redirection list.
8471 static void fixredir(union node *, const char *, int);
8473 expredir(union node *n)
8477 for (redir = n; redir; redir = redir->nfile.next) {
8481 fn.lastp = &fn.list;
8482 switch (redir->type) {
8486 #if ENABLE_ASH_BASH_COMPAT
8491 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8492 #if ENABLE_ASH_BASH_COMPAT
8495 redir->nfile.expfname = fn.list->text;
8498 case NTOFD: /* >& */
8499 if (redir->ndup.vname) {
8500 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8501 if (fn.list == NULL)
8502 ash_msg_and_raise_error("redir error");
8503 #if ENABLE_ASH_BASH_COMPAT
8504 //FIXME: we used expandarg with different args!
8505 if (!isdigit_str9(fn.list->text)) {
8506 /* >&file, not >&fd */
8507 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8508 ash_msg_and_raise_error("redir error");
8510 goto store_expfname;
8513 fixredir(redir, fn.list->text, 1);
8521 * Evaluate a pipeline. All the processes in the pipeline are children
8522 * of the process creating the pipeline. (This differs from some versions
8523 * of the shell, which make the last process in a pipeline the parent
8527 evalpipe(union node *n, int flags)
8530 struct nodelist *lp;
8535 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8537 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8541 jp = makejob(/*n,*/ pipelen);
8543 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8547 if (pipe(pip) < 0) {
8549 ash_msg_and_raise_error("pipe call failed");
8552 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8565 evaltreenr(lp->n, flags);
8571 /* Don't want to trigger debugging */
8575 if (n->npipe.pipe_backgnd == 0) {
8576 exitstatus = waitforjob(jp);
8577 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8583 * Controls whether the shell is interactive or not.
8586 setinteractive(int on)
8588 static smallint is_interactive;
8590 if (++on == is_interactive)
8592 is_interactive = on;
8596 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8597 if (is_interactive > 1) {
8598 /* Looks like they want an interactive shell */
8599 static smallint did_banner;
8602 /* note: ash and hush share this string */
8603 out1fmt("\n\n%s %s\n"
8604 "Enter 'help' for a list of built-in commands."
8607 "built-in shell (ash)"
8621 setinteractive(iflag);
8623 #if ENABLE_FEATURE_EDITING_VI
8625 line_input_state->flags |= VI_MODE;
8627 line_input_state->flags &= ~VI_MODE;
8629 viflag = 0; /* forcibly keep the option off */
8633 static struct localvar *localvars;
8636 * Called after a function returns.
8637 * Interrupts must be off.
8642 struct localvar *lvp;
8645 while ((lvp = localvars) != NULL) {
8646 localvars = lvp->next;
8648 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8649 if (vp == NULL) { /* $- saved */
8650 memcpy(optlist, lvp->text, sizeof(optlist));
8651 free((char*)lvp->text);
8653 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8654 unsetvar(vp->var_text);
8657 vp->var_func(var_end(lvp->text));
8658 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8659 free((char*)vp->var_text);
8660 vp->flags = lvp->flags;
8661 vp->var_text = lvp->text;
8668 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8670 volatile struct shparam saveparam;
8671 struct localvar *volatile savelocalvars;
8672 struct jmploc *volatile savehandler;
8673 struct jmploc jmploc;
8676 saveparam = shellparam;
8677 savelocalvars = localvars;
8678 e = setjmp(jmploc.loc);
8683 savehandler = exception_handler;
8684 exception_handler = &jmploc;
8686 shellparam.malloced = 0;
8690 shellparam.nparam = argc - 1;
8691 shellparam.p = argv + 1;
8692 #if ENABLE_ASH_GETOPTS
8693 shellparam.optind = 1;
8694 shellparam.optoff = -1;
8696 evaltree(&func->n, flags & EV_TESTED);
8702 localvars = savelocalvars;
8703 freeparam(&shellparam);
8704 shellparam = saveparam;
8705 exception_handler = savehandler;
8707 evalskip &= ~SKIPFUNC;
8711 #if ENABLE_ASH_CMDCMD
8713 parse_command_args(char **argv, const char **path)
8726 if (c == '-' && !*cp) {
8733 *path = bb_default_path;
8736 /* run 'typecmd' for other options */
8747 * Make a variable a local variable. When a variable is made local, it's
8748 * value and flags are saved in a localvar structure. The saved values
8749 * will be restored when the shell function returns. We handle the name
8750 * "-" as a special case.
8755 struct localvar *lvp;
8760 lvp = ckzalloc(sizeof(struct localvar));
8761 if (LONE_DASH(name)) {
8763 p = ckmalloc(sizeof(optlist));
8764 lvp->text = memcpy(p, optlist, sizeof(optlist));
8769 vpp = hashvar(name);
8770 vp = *findvar(vpp, name);
8771 eq = strchr(name, '=');
8774 setvareq(name, VSTRFIXED);
8776 setvar(name, NULL, VSTRFIXED);
8777 vp = *vpp; /* the new variable */
8778 lvp->flags = VUNSET;
8780 lvp->text = vp->var_text;
8781 lvp->flags = vp->flags;
8782 vp->flags |= VSTRFIXED|VTEXTFIXED;
8788 lvp->next = localvars;
8794 * The "local" command.
8796 static int FAST_FUNC
8797 localcmd(int argc UNUSED_PARAM, char **argv)
8802 while ((name = *argv++) != NULL) {
8808 static int FAST_FUNC
8809 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8814 static int FAST_FUNC
8815 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8820 static int FAST_FUNC
8821 execcmd(int argc UNUSED_PARAM, char **argv)
8824 iflag = 0; /* exit on error */
8827 shellexec(argv + 1, pathval(), 0);
8833 * The return command.
8835 static int FAST_FUNC
8836 returncmd(int argc UNUSED_PARAM, char **argv)
8839 * If called outside a function, do what ksh does;
8840 * skip the rest of the file.
8842 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8843 return argv[1] ? number(argv[1]) : exitstatus;
8846 /* Forward declarations for builtintab[] */
8847 static int breakcmd(int, char **) FAST_FUNC;
8848 static int dotcmd(int, char **) FAST_FUNC;
8849 static int evalcmd(int, char **) FAST_FUNC;
8850 static int exitcmd(int, char **) FAST_FUNC;
8851 static int exportcmd(int, char **) FAST_FUNC;
8852 #if ENABLE_ASH_GETOPTS
8853 static int getoptscmd(int, char **) FAST_FUNC;
8855 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8856 static int helpcmd(int, char **) FAST_FUNC;
8858 #if ENABLE_SH_MATH_SUPPORT
8859 static int letcmd(int, char **) FAST_FUNC;
8861 static int readcmd(int, char **) FAST_FUNC;
8862 static int setcmd(int, char **) FAST_FUNC;
8863 static int shiftcmd(int, char **) FAST_FUNC;
8864 static int timescmd(int, char **) FAST_FUNC;
8865 static int trapcmd(int, char **) FAST_FUNC;
8866 static int umaskcmd(int, char **) FAST_FUNC;
8867 static int unsetcmd(int, char **) FAST_FUNC;
8868 static int ulimitcmd(int, char **) FAST_FUNC;
8870 #define BUILTIN_NOSPEC "0"
8871 #define BUILTIN_SPECIAL "1"
8872 #define BUILTIN_REGULAR "2"
8873 #define BUILTIN_SPEC_REG "3"
8874 #define BUILTIN_ASSIGN "4"
8875 #define BUILTIN_SPEC_ASSG "5"
8876 #define BUILTIN_REG_ASSG "6"
8877 #define BUILTIN_SPEC_REG_ASSG "7"
8879 /* Stubs for calling non-FAST_FUNC's */
8880 #if ENABLE_ASH_BUILTIN_ECHO
8881 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8883 #if ENABLE_ASH_BUILTIN_PRINTF
8884 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8886 #if ENABLE_ASH_BUILTIN_TEST
8887 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8890 /* Keep these in proper order since it is searched via bsearch() */
8891 static const struct builtincmd builtintab[] = {
8892 { BUILTIN_SPEC_REG "." , dotcmd },
8893 { BUILTIN_SPEC_REG ":" , truecmd },
8894 #if ENABLE_ASH_BUILTIN_TEST
8895 { BUILTIN_REGULAR "[" , testcmd },
8896 #if ENABLE_ASH_BASH_COMPAT
8897 { BUILTIN_REGULAR "[[" , testcmd },
8900 #if ENABLE_ASH_ALIAS
8901 { BUILTIN_REG_ASSG "alias" , aliascmd },
8904 { BUILTIN_REGULAR "bg" , fg_bgcmd },
8906 { BUILTIN_SPEC_REG "break" , breakcmd },
8907 { BUILTIN_REGULAR "cd" , cdcmd },
8908 { BUILTIN_NOSPEC "chdir" , cdcmd },
8909 #if ENABLE_ASH_CMDCMD
8910 { BUILTIN_REGULAR "command" , commandcmd },
8912 { BUILTIN_SPEC_REG "continue", breakcmd },
8913 #if ENABLE_ASH_BUILTIN_ECHO
8914 { BUILTIN_REGULAR "echo" , echocmd },
8916 { BUILTIN_SPEC_REG "eval" , evalcmd },
8917 { BUILTIN_SPEC_REG "exec" , execcmd },
8918 { BUILTIN_SPEC_REG "exit" , exitcmd },
8919 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
8920 { BUILTIN_REGULAR "false" , falsecmd },
8922 { BUILTIN_REGULAR "fg" , fg_bgcmd },
8924 #if ENABLE_ASH_GETOPTS
8925 { BUILTIN_REGULAR "getopts" , getoptscmd },
8927 { BUILTIN_NOSPEC "hash" , hashcmd },
8928 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8929 { BUILTIN_NOSPEC "help" , helpcmd },
8932 { BUILTIN_REGULAR "jobs" , jobscmd },
8933 { BUILTIN_REGULAR "kill" , killcmd },
8935 #if ENABLE_SH_MATH_SUPPORT
8936 { BUILTIN_NOSPEC "let" , letcmd },
8938 { BUILTIN_ASSIGN "local" , localcmd },
8939 #if ENABLE_ASH_BUILTIN_PRINTF
8940 { BUILTIN_REGULAR "printf" , printfcmd },
8942 { BUILTIN_NOSPEC "pwd" , pwdcmd },
8943 { BUILTIN_REGULAR "read" , readcmd },
8944 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8945 { BUILTIN_SPEC_REG "return" , returncmd },
8946 { BUILTIN_SPEC_REG "set" , setcmd },
8947 { BUILTIN_SPEC_REG "shift" , shiftcmd },
8948 #if ENABLE_ASH_BASH_COMPAT
8949 { BUILTIN_SPEC_REG "source" , dotcmd },
8951 #if ENABLE_ASH_BUILTIN_TEST
8952 { BUILTIN_REGULAR "test" , testcmd },
8954 { BUILTIN_SPEC_REG "times" , timescmd },
8955 { BUILTIN_SPEC_REG "trap" , trapcmd },
8956 { BUILTIN_REGULAR "true" , truecmd },
8957 { BUILTIN_NOSPEC "type" , typecmd },
8958 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
8959 { BUILTIN_REGULAR "umask" , umaskcmd },
8960 #if ENABLE_ASH_ALIAS
8961 { BUILTIN_REGULAR "unalias" , unaliascmd },
8963 { BUILTIN_SPEC_REG "unset" , unsetcmd },
8964 { BUILTIN_REGULAR "wait" , waitcmd },
8967 /* Should match the above table! */
8968 #define COMMANDCMD (builtintab + \
8970 1 * ENABLE_ASH_BUILTIN_TEST + \
8971 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8972 1 * ENABLE_ASH_ALIAS + \
8973 1 * ENABLE_ASH_JOB_CONTROL + \
8975 #define EXECCMD (builtintab + \
8977 1 * ENABLE_ASH_BUILTIN_TEST + \
8978 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8979 1 * ENABLE_ASH_ALIAS + \
8980 1 * ENABLE_ASH_JOB_CONTROL + \
8982 1 * ENABLE_ASH_CMDCMD + \
8984 ENABLE_ASH_BUILTIN_ECHO + \
8988 * Search the table of builtin commands.
8990 static struct builtincmd *
8991 find_builtin(const char *name)
8993 struct builtincmd *bp;
8996 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9003 * Execute a simple command.
9006 isassignment(const char *p)
9008 const char *q = endofname(p);
9013 static int FAST_FUNC
9014 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9016 /* Preserve exitstatus of a previous possible redirection
9017 * as POSIX mandates */
9018 return back_exitstatus;
9021 evalcommand(union node *cmd, int flags)
9023 static const struct builtincmd null_bltin = {
9024 "\0\0", bltincmd /* why three NULs? */
9026 struct stackmark smark;
9028 struct arglist arglist;
9029 struct arglist varlist;
9032 const struct strlist *sp;
9033 struct cmdentry cmdentry;
9040 struct builtincmd *bcmd;
9041 smallint cmd_is_exec;
9042 smallint pseudovarflag = 0;
9044 /* First expand the arguments. */
9045 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9046 setstackmark(&smark);
9047 back_exitstatus = 0;
9049 cmdentry.cmdtype = CMDBUILTIN;
9050 cmdentry.u.cmd = &null_bltin;
9051 varlist.lastp = &varlist.list;
9052 *varlist.lastp = NULL;
9053 arglist.lastp = &arglist.list;
9054 *arglist.lastp = NULL;
9057 if (cmd->ncmd.args) {
9058 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9059 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9062 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9063 struct strlist **spp;
9065 spp = arglist.lastp;
9066 if (pseudovarflag && isassignment(argp->narg.text))
9067 expandarg(argp, &arglist, EXP_VARTILDE);
9069 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9071 for (sp = *spp; sp; sp = sp->next)
9075 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9076 for (sp = arglist.list; sp; sp = sp->next) {
9077 TRACE(("evalcommand arg: %s\n", sp->text));
9078 *nargv++ = sp->text;
9083 if (iflag && funcnest == 0 && argc > 0)
9084 lastarg = nargv[-1];
9087 expredir(cmd->ncmd.redirect);
9088 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9090 path = vpath.var_text;
9091 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9092 struct strlist **spp;
9095 spp = varlist.lastp;
9096 expandarg(argp, &varlist, EXP_VARTILDE);
9099 * Modify the command lookup path, if a PATH= assignment
9103 if (varcmp(p, path) == 0)
9107 /* Print the command if xflag is set. */
9110 const char *p = " %s";
9113 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9116 for (n = 0; n < 2; n++) {
9118 fdprintf(preverrout_fd, p, sp->text);
9126 safe_write(preverrout_fd, "\n", 1);
9132 /* Now locate the command. */
9134 const char *oldpath;
9135 int cmd_flag = DO_ERR;
9140 find_command(argv[0], &cmdentry, cmd_flag, path);
9141 if (cmdentry.cmdtype == CMDUNKNOWN) {
9142 flush_stdout_stderr();
9147 /* implement bltin and command here */
9148 if (cmdentry.cmdtype != CMDBUILTIN)
9151 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9152 if (cmdentry.u.cmd == EXECCMD)
9154 #if ENABLE_ASH_CMDCMD
9155 if (cmdentry.u.cmd == COMMANDCMD) {
9157 nargv = parse_command_args(argv, &path);
9160 argc -= nargv - argv;
9162 cmd_flag |= DO_NOFUNC;
9170 /* We have a redirection error. */
9172 raise_exception(EXERROR);
9174 exitstatus = status;
9178 /* Execute the command. */
9179 switch (cmdentry.cmdtype) {
9182 #if ENABLE_FEATURE_SH_NOFORK
9183 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9184 * around run_nofork_applet() call.
9185 * (2) Should this check also be done in forkshell()?
9186 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9188 /* find_command() encodes applet_no as (-2 - applet_no) */
9189 int applet_no = (- cmdentry.u.index - 2);
9190 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9191 listsetvar(varlist.list, VEXPORT|VSTACK);
9192 /* run <applet>_main() */
9193 exitstatus = run_nofork_applet(applet_no, argv);
9197 /* Can we avoid forking off? For example, very last command
9198 * in a script or a subshell does not need forking,
9199 * we can just exec it.
9201 if (!(flags & EV_EXIT) || may_have_traps) {
9202 /* No, forking off a child is necessary */
9204 jp = makejob(/*cmd,*/ 1);
9205 if (forkshell(jp, cmd, FORK_FG) != 0) {
9207 exitstatus = waitforjob(jp);
9209 TRACE(("forked child exited with %d\n", exitstatus));
9214 /* fall through to exec'ing external program */
9216 listsetvar(varlist.list, VEXPORT|VSTACK);
9217 shellexec(argv, path, cmdentry.u.index);
9221 cmdenviron = varlist.list;
9223 struct strlist *list = cmdenviron;
9225 if (spclbltin > 0 || argc == 0) {
9227 if (cmd_is_exec && argc > 1)
9230 listsetvar(list, i);
9232 /* Tight loop with builtins only:
9233 * "while kill -0 $child; do true; done"
9234 * will never exit even if $child died, unless we do this
9235 * to reap the zombie and make kill detect that it's gone: */
9236 dowait(DOWAIT_NONBLOCK, NULL);
9238 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9240 int i = exception_type;
9245 exit_status = 128 + SIGINT;
9247 exit_status = 128 + pending_sig;
9248 exitstatus = exit_status;
9249 if (i == EXINT || spclbltin > 0) {
9251 longjmp(exception_handler->loc, 1);
9258 listsetvar(varlist.list, 0);
9259 /* See above for the rationale */
9260 dowait(DOWAIT_NONBLOCK, NULL);
9261 if (evalfun(cmdentry.u.func, argc, argv, flags))
9268 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9270 /* dsl: I think this is intended to be used to support
9271 * '_' in 'vi' command mode during line editing...
9272 * However I implemented that within libedit itself.
9274 setvar("_", lastarg, 0);
9276 popstackmark(&smark);
9280 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9282 char *volatile savecmdname;
9283 struct jmploc *volatile savehandler;
9284 struct jmploc jmploc;
9287 savecmdname = commandname;
9288 i = setjmp(jmploc.loc);
9291 savehandler = exception_handler;
9292 exception_handler = &jmploc;
9293 commandname = argv[0];
9295 optptr = NULL; /* initialize nextopt */
9296 exitstatus = (*cmd->builtin)(argc, argv);
9297 flush_stdout_stderr();
9299 exitstatus |= ferror(stdout);
9301 commandname = savecmdname;
9302 exception_handler = savehandler;
9308 goodname(const char *p)
9310 return !*endofname(p);
9315 * Search for a command. This is called before we fork so that the
9316 * location of the command will be available in the parent as well as
9317 * the child. The check for "goodname" is an overly conservative
9318 * check that the name will not be subject to expansion.
9321 prehash(union node *n)
9323 struct cmdentry entry;
9325 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9326 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9330 /* ============ Builtin commands
9332 * Builtin commands whose functions are closely tied to evaluation
9333 * are implemented here.
9337 * Handle break and continue commands. Break, continue, and return are
9338 * all handled by setting the evalskip flag. The evaluation routines
9339 * above all check this flag, and if it is set they start skipping
9340 * commands rather than executing them. The variable skipcount is
9341 * the number of loops to break/continue, or the number of function
9342 * levels to return. (The latter is always 1.) It should probably
9343 * be an error to break out of more loops than exist, but it isn't
9344 * in the standard shell so we don't make it one here.
9346 static int FAST_FUNC
9347 breakcmd(int argc UNUSED_PARAM, char **argv)
9349 int n = argv[1] ? number(argv[1]) : 1;
9352 ash_msg_and_raise_error(msg_illnum, argv[1]);
9356 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9363 /* ============ input.c
9365 * This implements the input routines used by the parser.
9369 INPUT_PUSH_FILE = 1,
9370 INPUT_NOFILE_OK = 2,
9373 static smallint checkkwd;
9374 /* values of checkkwd variable */
9375 #define CHKALIAS 0x1
9380 * Push a string back onto the input at this current parsefile level.
9381 * We handle aliases this way.
9383 #if !ENABLE_ASH_ALIAS
9384 #define pushstring(s, ap) pushstring(s)
9387 pushstring(char *s, struct alias *ap)
9394 if (g_parsefile->strpush) {
9395 sp = ckzalloc(sizeof(*sp));
9396 sp->prev = g_parsefile->strpush;
9398 sp = &(g_parsefile->basestrpush);
9400 g_parsefile->strpush = sp;
9401 sp->prev_string = g_parsefile->next_to_pgetc;
9402 sp->prev_left_in_line = g_parsefile->left_in_line;
9403 #if ENABLE_ASH_ALIAS
9406 ap->flag |= ALIASINUSE;
9410 g_parsefile->next_to_pgetc = s;
9411 g_parsefile->left_in_line = len;
9418 struct strpush *sp = g_parsefile->strpush;
9421 #if ENABLE_ASH_ALIAS
9423 if (g_parsefile->next_to_pgetc[-1] == ' '
9424 || g_parsefile->next_to_pgetc[-1] == '\t'
9426 checkkwd |= CHKALIAS;
9428 if (sp->string != sp->ap->val) {
9431 sp->ap->flag &= ~ALIASINUSE;
9432 if (sp->ap->flag & ALIASDEAD) {
9433 unalias(sp->ap->name);
9437 g_parsefile->next_to_pgetc = sp->prev_string;
9438 g_parsefile->left_in_line = sp->prev_left_in_line;
9439 g_parsefile->strpush = sp->prev;
9440 if (sp != &(g_parsefile->basestrpush))
9445 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9446 //it peeks whether it is &>, and then pushes back both chars.
9447 //This function needs to save last *next_to_pgetc to buf[0]
9448 //to make two pungetc() reliable. Currently,
9449 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9454 char *buf = g_parsefile->buf;
9456 g_parsefile->next_to_pgetc = buf;
9457 #if ENABLE_FEATURE_EDITING
9459 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9460 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9462 #if ENABLE_FEATURE_TAB_COMPLETION
9463 line_input_state->path_lookup = pathval();
9465 nr = read_line_input(cmdedit_prompt, buf, IBUFSIZ, line_input_state);
9467 /* Ctrl+C pressed */
9476 if (nr < 0 && errno == 0) {
9477 /* Ctrl+D pressed */
9482 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9486 /* nonblock_safe_read() handles this problem */
9488 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9489 int flags = fcntl(0, F_GETFL);
9490 if (flags >= 0 && (flags & O_NONBLOCK)) {
9491 flags &= ~O_NONBLOCK;
9492 if (fcntl(0, F_SETFL, flags) >= 0) {
9493 out2str("sh: turning off NDELAY mode\n");
9504 * Refill the input buffer and return the next input character:
9506 * 1) If a string was pushed back on the input, pop it;
9507 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9508 * or we are reading from a string so we can't refill the buffer,
9510 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9511 * 4) Process input up to the next newline, deleting nul characters.
9513 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9514 #define pgetc_debug(...) ((void)0)
9521 while (g_parsefile->strpush) {
9522 #if ENABLE_ASH_ALIAS
9523 if (g_parsefile->left_in_line == -1
9524 && g_parsefile->strpush->ap
9525 && g_parsefile->next_to_pgetc[-1] != ' '
9526 && g_parsefile->next_to_pgetc[-1] != '\t'
9528 pgetc_debug("preadbuffer PEOA");
9533 /* try "pgetc" now: */
9534 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9535 g_parsefile->left_in_line,
9536 g_parsefile->next_to_pgetc,
9537 g_parsefile->next_to_pgetc);
9538 if (--g_parsefile->left_in_line >= 0)
9539 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9541 /* on both branches above g_parsefile->left_in_line < 0.
9542 * "pgetc" needs refilling.
9545 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9546 * pungetc() may increment it a few times.
9547 * Assuming it won't increment it to less than -90.
9549 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9550 pgetc_debug("preadbuffer PEOF1");
9551 /* even in failure keep left_in_line and next_to_pgetc
9552 * in lock step, for correct multi-layer pungetc.
9553 * left_in_line was decremented before preadbuffer(),
9554 * must inc next_to_pgetc: */
9555 g_parsefile->next_to_pgetc++;
9559 more = g_parsefile->left_in_buffer;
9561 flush_stdout_stderr();
9565 /* don't try reading again */
9566 g_parsefile->left_in_line = -99;
9567 pgetc_debug("preadbuffer PEOF2");
9568 g_parsefile->next_to_pgetc++;
9573 /* Find out where's the end of line.
9574 * Set g_parsefile->left_in_line
9575 * and g_parsefile->left_in_buffer acordingly.
9576 * NUL chars are deleted.
9578 q = g_parsefile->next_to_pgetc;
9586 memmove(q, q + 1, more);
9590 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9596 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9597 if (g_parsefile->left_in_line < 0)
9602 g_parsefile->left_in_buffer = more;
9607 out2str(g_parsefile->next_to_pgetc);
9611 pgetc_debug("preadbuffer at %d:%p'%s'",
9612 g_parsefile->left_in_line,
9613 g_parsefile->next_to_pgetc,
9614 g_parsefile->next_to_pgetc);
9615 return (unsigned char)*g_parsefile->next_to_pgetc++;
9618 #define pgetc_as_macro() \
9619 (--g_parsefile->left_in_line >= 0 \
9620 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9627 pgetc_debug("pgetc_fast at %d:%p'%s'",
9628 g_parsefile->left_in_line,
9629 g_parsefile->next_to_pgetc,
9630 g_parsefile->next_to_pgetc);
9631 return pgetc_as_macro();
9634 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9635 # define pgetc_fast() pgetc()
9637 # define pgetc_fast() pgetc_as_macro()
9640 #if ENABLE_ASH_ALIAS
9642 pgetc_without_PEOA(void)
9646 pgetc_debug("pgetc_fast at %d:%p'%s'",
9647 g_parsefile->left_in_line,
9648 g_parsefile->next_to_pgetc,
9649 g_parsefile->next_to_pgetc);
9651 } while (c == PEOA);
9655 # define pgetc_without_PEOA() pgetc()
9659 * Read a line from the script.
9662 pfgets(char *line, int len)
9668 while (--nleft > 0) {
9669 c = pgetc_without_PEOA();
9684 * Undo the last call to pgetc. Only one character may be pushed back.
9685 * PEOF may be pushed back.
9690 g_parsefile->left_in_line++;
9691 g_parsefile->next_to_pgetc--;
9692 pgetc_debug("pushed back to %d:%p'%s'",
9693 g_parsefile->left_in_line,
9694 g_parsefile->next_to_pgetc,
9695 g_parsefile->next_to_pgetc);
9699 * To handle the "." command, a stack of input files is used. Pushfile
9700 * adds a new entry to the stack and popfile restores the previous level.
9705 struct parsefile *pf;
9707 pf = ckzalloc(sizeof(*pf));
9708 pf->prev = g_parsefile;
9710 /*pf->strpush = NULL; - ckzalloc did it */
9711 /*pf->basestrpush.prev = NULL;*/
9718 struct parsefile *pf = g_parsefile;
9726 g_parsefile = pf->prev;
9732 * Return to top level.
9737 while (g_parsefile != &basepf)
9742 * Close the file(s) that the shell is reading commands from. Called
9743 * after a fork is done.
9749 if (g_parsefile->pf_fd > 0) {
9750 close(g_parsefile->pf_fd);
9751 g_parsefile->pf_fd = 0;
9756 * Like setinputfile, but takes an open file descriptor. Call this with
9760 setinputfd(int fd, int push)
9762 close_on_exec_on(fd);
9765 g_parsefile->buf = NULL;
9767 g_parsefile->pf_fd = fd;
9768 if (g_parsefile->buf == NULL)
9769 g_parsefile->buf = ckmalloc(IBUFSIZ);
9770 g_parsefile->left_in_buffer = 0;
9771 g_parsefile->left_in_line = 0;
9772 g_parsefile->linno = 1;
9776 * Set the input to take input from a file. If push is set, push the
9777 * old input onto the stack first.
9780 setinputfile(const char *fname, int flags)
9786 fd = open(fname, O_RDONLY);
9788 if (flags & INPUT_NOFILE_OK)
9790 ash_msg_and_raise_error("can't open '%s'", fname);
9793 fd2 = copyfd(fd, 10);
9796 ash_msg_and_raise_error("out of file descriptors");
9799 setinputfd(fd, flags & INPUT_PUSH_FILE);
9806 * Like setinputfile, but takes input from a string.
9809 setinputstring(char *string)
9813 g_parsefile->next_to_pgetc = string;
9814 g_parsefile->left_in_line = strlen(string);
9815 g_parsefile->buf = NULL;
9816 g_parsefile->linno = 1;
9821 /* ============ mail.c
9823 * Routines to check for mail.
9828 #define MAXMBOXES 10
9830 /* times of mailboxes */
9831 static time_t mailtime[MAXMBOXES];
9832 /* Set if MAIL or MAILPATH is changed. */
9833 static smallint mail_var_path_changed;
9836 * Print appropriate message(s) if mail has arrived.
9837 * If mail_var_path_changed is set,
9838 * then the value of MAIL has mail_var_path_changed,
9839 * so we just update the values.
9848 struct stackmark smark;
9851 setstackmark(&smark);
9852 mpath = mpathset() ? mpathval() : mailval();
9853 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9854 p = path_advance(&mpath, nullstr);
9859 for (q = p; *q; q++)
9865 q[-1] = '\0'; /* delete trailing '/' */
9866 if (stat(p, &statb) < 0) {
9870 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9873 pathopt ? pathopt : "you have mail"
9876 *mtp = statb.st_mtime;
9878 mail_var_path_changed = 0;
9879 popstackmark(&smark);
9882 static void FAST_FUNC
9883 changemail(const char *val UNUSED_PARAM)
9885 mail_var_path_changed = 1;
9888 #endif /* ASH_MAIL */
9891 /* ============ ??? */
9894 * Set the shell parameters.
9897 setparam(char **argv)
9903 for (nparam = 0; argv[nparam]; nparam++)
9905 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9907 *ap++ = ckstrdup(*argv++);
9910 freeparam(&shellparam);
9911 shellparam.malloced = 1;
9912 shellparam.nparam = nparam;
9913 shellparam.p = newparam;
9914 #if ENABLE_ASH_GETOPTS
9915 shellparam.optind = 1;
9916 shellparam.optoff = -1;
9921 * Process shell options. The global variable argptr contains a pointer
9922 * to the argument list; we advance it past the options.
9924 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9925 * For a non-interactive shell, an error condition encountered
9926 * by a special built-in ... shall cause the shell to write a diagnostic message
9927 * to standard error and exit as shown in the following table:
9928 * Error Special Built-In
9930 * Utility syntax error (option or operand error) Shall exit
9932 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9933 * we see that bash does not do that (set "finishes" with error code 1 instead,
9934 * and shell continues), and people rely on this behavior!
9936 * set -o barfoo 2>/dev/null
9939 * Oh well. Let's mimic that.
9942 plus_minus_o(char *name, int val)
9947 for (i = 0; i < NOPTS; i++) {
9948 if (strcmp(name, optnames(i)) == 0) {
9953 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9956 for (i = 0; i < NOPTS; i++) {
9958 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9960 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9966 setoption(int flag, int val)
9970 for (i = 0; i < NOPTS; i++) {
9971 if (optletters(i) == flag) {
9976 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9980 options(int cmdline)
9988 while ((p = *argptr) != NULL) {
9990 if (c != '-' && c != '+')
9993 val = 0; /* val = 0 if c == '+' */
9996 if (p[0] == '\0' || LONE_DASH(p)) {
9998 /* "-" means turn off -x and -v */
10001 /* "--" means reset params */
10002 else if (*argptr == NULL)
10005 break; /* "-" or "--" terminates options */
10008 /* first char was + or - */
10009 while ((c = *p++) != '\0') {
10010 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10011 if (c == 'c' && cmdline) {
10012 minusc = p; /* command is after shell args */
10013 } else if (c == 'o') {
10014 if (plus_minus_o(*argptr, val)) {
10015 /* it already printed err message */
10016 return 1; /* error */
10020 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10022 /* bash does not accept +-login, we also won't */
10023 } else if (cmdline && val && (c == '-')) { /* long options */
10024 if (strcmp(p, "login") == 0)
10036 * The shift builtin command.
10038 static int FAST_FUNC
10039 shiftcmd(int argc UNUSED_PARAM, char **argv)
10046 n = number(argv[1]);
10047 if (n > shellparam.nparam)
10048 n = 0; /* bash compat, was = shellparam.nparam; */
10050 shellparam.nparam -= n;
10051 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10052 if (shellparam.malloced)
10055 ap2 = shellparam.p;
10056 while ((*ap2++ = *ap1++) != NULL)
10058 #if ENABLE_ASH_GETOPTS
10059 shellparam.optind = 1;
10060 shellparam.optoff = -1;
10067 * POSIX requires that 'set' (but not export or readonly) output the
10068 * variables in lexicographic order - by the locale's collating order (sigh).
10069 * Maybe we could keep them in an ordered balanced binary tree
10070 * instead of hashed lists.
10071 * For now just roll 'em through qsort for printing...
10074 showvars(const char *sep_prefix, int on, int off)
10077 char **ep, **epend;
10079 ep = listvars(on, off, &epend);
10080 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10082 sep = *sep_prefix ? " " : sep_prefix;
10084 for (; ep < epend; ep++) {
10088 p = strchrnul(*ep, '=');
10091 q = single_quote(++p);
10092 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10098 * The set command builtin.
10100 static int FAST_FUNC
10101 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10106 return showvars(nullstr, 0, VUNSET);
10109 if (!options(0)) { /* if no parse error... */
10112 if (*argptr != NULL) {
10120 #if ENABLE_ASH_RANDOM_SUPPORT
10121 static void FAST_FUNC
10122 change_random(const char *value)
10126 if (value == NULL) {
10127 /* "get", generate */
10128 t = next_random(&random_gen);
10129 /* set without recursion */
10130 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10131 vrandom.flags &= ~VNOFUNC;
10134 t = strtoul(value, NULL, 10);
10135 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10140 #if ENABLE_ASH_GETOPTS
10142 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10151 if (*param_optind < 1)
10153 optnext = optfirst + *param_optind - 1;
10155 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10158 p = optnext[-1] + *optoff;
10159 if (p == NULL || *p == '\0') {
10160 /* Current word is done, advance */
10162 if (p == NULL || *p != '-' || *++p == '\0') {
10169 if (LONE_DASH(p)) /* check for "--" */
10174 for (q = optstr; *q != c;) {
10176 if (optstr[0] == ':') {
10179 err |= setvarsafe("OPTARG", s, 0);
10181 fprintf(stderr, "Illegal option -%c\n", c);
10182 unsetvar("OPTARG");
10192 if (*p == '\0' && (p = *optnext) == NULL) {
10193 if (optstr[0] == ':') {
10196 err |= setvarsafe("OPTARG", s, 0);
10199 fprintf(stderr, "No arg for -%c option\n", c);
10200 unsetvar("OPTARG");
10208 err |= setvarsafe("OPTARG", p, 0);
10211 err |= setvarsafe("OPTARG", nullstr, 0);
10213 *optoff = p ? p - *(optnext - 1) : -1;
10214 *param_optind = optnext - optfirst + 1;
10215 fmtstr(s, sizeof(s), "%d", *param_optind);
10216 err |= setvarsafe("OPTIND", s, VNOFUNC);
10219 err |= setvarsafe(optvar, s, 0);
10223 flush_stdout_stderr();
10224 raise_exception(EXERROR);
10230 * The getopts builtin. Shellparam.optnext points to the next argument
10231 * to be processed. Shellparam.optptr points to the next character to
10232 * be processed in the current argument. If shellparam.optnext is NULL,
10233 * then it's the first time getopts has been called.
10235 static int FAST_FUNC
10236 getoptscmd(int argc, char **argv)
10241 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10243 optbase = shellparam.p;
10244 if (shellparam.optind > shellparam.nparam + 1) {
10245 shellparam.optind = 1;
10246 shellparam.optoff = -1;
10249 optbase = &argv[3];
10250 if (shellparam.optind > argc - 2) {
10251 shellparam.optind = 1;
10252 shellparam.optoff = -1;
10256 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10257 &shellparam.optoff);
10259 #endif /* ASH_GETOPTS */
10262 /* ============ Shell parser */
10265 struct heredoc *next; /* next here document in list */
10266 union node *here; /* redirection node */
10267 char *eofmark; /* string indicating end of input */
10268 smallint striptabs; /* if set, strip leading tabs */
10271 static smallint tokpushback; /* last token pushed back */
10272 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10273 static smallint quoteflag; /* set if (part of) last token was quoted */
10274 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10275 static struct heredoc *heredoclist; /* list of here documents to read */
10276 static char *wordtext; /* text of last word returned by readtoken */
10277 static struct nodelist *backquotelist;
10278 static union node *redirnode;
10279 static struct heredoc *heredoc;
10281 static const char *
10282 tokname(char *buf, int tok)
10285 return tokname_array[tok] + 1;
10286 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10290 /* raise_error_unexpected_syntax:
10291 * Called when an unexpected token is read during the parse. The argument
10292 * is the token that is expected, or -1 if more than one type of token can
10293 * occur at this point.
10295 static void raise_error_unexpected_syntax(int) NORETURN;
10297 raise_error_unexpected_syntax(int token)
10303 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10305 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10306 raise_error_syntax(msg);
10310 #define EOFMARKLEN 79
10312 /* parsing is heavily cross-recursive, need these forward decls */
10313 static union node *andor(void);
10314 static union node *pipeline(void);
10315 static union node *parse_command(void);
10316 static void parseheredoc(void);
10317 static char peektoken(void);
10318 static int readtoken(void);
10320 static union node *
10323 union node *n1, *n2, *n3;
10326 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10327 if (nlflag == 2 && peektoken())
10333 if (tok == TBACKGND) {
10334 if (n2->type == NPIPE) {
10335 n2->npipe.pipe_backgnd = 1;
10337 if (n2->type != NREDIR) {
10338 n3 = stzalloc(sizeof(struct nredir));
10340 /*n3->nredir.redirect = NULL; - stzalloc did it */
10343 n2->type = NBACKGND;
10349 n3 = stzalloc(sizeof(struct nbinary));
10351 n3->nbinary.ch1 = n1;
10352 n3->nbinary.ch2 = n2;
10368 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10376 pungetc(); /* push back EOF on input */
10380 raise_error_unexpected_syntax(-1);
10387 static union node *
10390 union node *n1, *n2, *n3;
10398 } else if (t == TOR) {
10404 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10406 n3 = stzalloc(sizeof(struct nbinary));
10408 n3->nbinary.ch1 = n1;
10409 n3->nbinary.ch2 = n2;
10414 static union node *
10417 union node *n1, *n2, *pipenode;
10418 struct nodelist *lp, *prev;
10422 TRACE(("pipeline: entered\n"));
10423 if (readtoken() == TNOT) {
10425 checkkwd = CHKKWD | CHKALIAS;
10428 n1 = parse_command();
10429 if (readtoken() == TPIPE) {
10430 pipenode = stzalloc(sizeof(struct npipe));
10431 pipenode->type = NPIPE;
10432 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10433 lp = stzalloc(sizeof(struct nodelist));
10434 pipenode->npipe.cmdlist = lp;
10438 lp = stzalloc(sizeof(struct nodelist));
10439 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10440 lp->n = parse_command();
10442 } while (readtoken() == TPIPE);
10448 n2 = stzalloc(sizeof(struct nnot));
10456 static union node *
10461 n = stzalloc(sizeof(struct narg));
10463 /*n->narg.next = NULL; - stzalloc did it */
10464 n->narg.text = wordtext;
10465 n->narg.backquote = backquotelist;
10470 fixredir(union node *n, const char *text, int err)
10474 TRACE(("Fix redir %s %d\n", text, err));
10476 n->ndup.vname = NULL;
10478 fd = bb_strtou(text, NULL, 10);
10479 if (!errno && fd >= 0)
10480 n->ndup.dupfd = fd;
10481 else if (LONE_DASH(text))
10482 n->ndup.dupfd = -1;
10485 raise_error_syntax("bad fd number");
10486 n->ndup.vname = makename();
10491 * Returns true if the text contains nothing to expand (no dollar signs
10495 noexpand(const char *text)
10499 while ((c = *text++) != '\0') {
10500 if (c == CTLQUOTEMARK)
10504 else if (SIT(c, BASESYNTAX) == CCTL)
10513 union node *n = redirnode;
10515 if (readtoken() != TWORD)
10516 raise_error_unexpected_syntax(-1);
10517 if (n->type == NHERE) {
10518 struct heredoc *here = heredoc;
10522 if (quoteflag == 0)
10524 TRACE(("Here document %d\n", n->type));
10525 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10526 raise_error_syntax("illegal eof marker for << redirection");
10527 rmescapes(wordtext, 0);
10528 here->eofmark = wordtext;
10530 if (heredoclist == NULL)
10531 heredoclist = here;
10533 for (p = heredoclist; p->next; p = p->next)
10537 } else if (n->type == NTOFD || n->type == NFROMFD) {
10538 fixredir(n, wordtext, 0);
10540 n->nfile.fname = makename();
10544 static union node *
10547 union node *args, **app;
10548 union node *n = NULL;
10549 union node *vars, **vpp;
10550 union node **rpp, *redir;
10552 #if ENABLE_ASH_BASH_COMPAT
10553 smallint double_brackets_flag = 0;
10563 savecheckkwd = CHKALIAS;
10566 checkkwd = savecheckkwd;
10569 #if ENABLE_ASH_BASH_COMPAT
10570 case TAND: /* "&&" */
10571 case TOR: /* "||" */
10572 if (!double_brackets_flag) {
10576 wordtext = (char *) (t == TAND ? "-a" : "-o");
10579 n = stzalloc(sizeof(struct narg));
10581 /*n->narg.next = NULL; - stzalloc did it */
10582 n->narg.text = wordtext;
10583 #if ENABLE_ASH_BASH_COMPAT
10584 if (strcmp("[[", wordtext) == 0)
10585 double_brackets_flag = 1;
10586 else if (strcmp("]]", wordtext) == 0)
10587 double_brackets_flag = 0;
10589 n->narg.backquote = backquotelist;
10590 if (savecheckkwd && isassignment(wordtext)) {
10592 vpp = &n->narg.next;
10595 app = &n->narg.next;
10600 *rpp = n = redirnode;
10601 rpp = &n->nfile.next;
10602 parsefname(); /* read name of redirection file */
10605 if (args && app == &args->narg.next
10608 struct builtincmd *bcmd;
10611 /* We have a function */
10612 if (readtoken() != TRP)
10613 raise_error_unexpected_syntax(TRP);
10614 name = n->narg.text;
10615 if (!goodname(name)
10616 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10618 raise_error_syntax("bad function name");
10621 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10622 n->narg.next = parse_command();
10635 n = stzalloc(sizeof(struct ncmd));
10637 n->ncmd.args = args;
10638 n->ncmd.assign = vars;
10639 n->ncmd.redirect = redir;
10643 static union node *
10644 parse_command(void)
10646 union node *n1, *n2;
10647 union node *ap, **app;
10648 union node *cp, **cpp;
10649 union node *redir, **rpp;
10656 switch (readtoken()) {
10658 raise_error_unexpected_syntax(-1);
10661 n1 = stzalloc(sizeof(struct nif));
10663 n1->nif.test = list(0);
10664 if (readtoken() != TTHEN)
10665 raise_error_unexpected_syntax(TTHEN);
10666 n1->nif.ifpart = list(0);
10668 while (readtoken() == TELIF) {
10669 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10670 n2 = n2->nif.elsepart;
10672 n2->nif.test = list(0);
10673 if (readtoken() != TTHEN)
10674 raise_error_unexpected_syntax(TTHEN);
10675 n2->nif.ifpart = list(0);
10677 if (lasttoken == TELSE)
10678 n2->nif.elsepart = list(0);
10680 n2->nif.elsepart = NULL;
10688 n1 = stzalloc(sizeof(struct nbinary));
10689 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10690 n1->nbinary.ch1 = list(0);
10693 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
10694 got == TWORD ? wordtext : ""));
10695 raise_error_unexpected_syntax(TDO);
10697 n1->nbinary.ch2 = list(0);
10702 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10703 raise_error_syntax("bad for loop variable");
10704 n1 = stzalloc(sizeof(struct nfor));
10706 n1->nfor.var = wordtext;
10707 checkkwd = CHKKWD | CHKALIAS;
10708 if (readtoken() == TIN) {
10710 while (readtoken() == TWORD) {
10711 n2 = stzalloc(sizeof(struct narg));
10713 /*n2->narg.next = NULL; - stzalloc did it */
10714 n2->narg.text = wordtext;
10715 n2->narg.backquote = backquotelist;
10717 app = &n2->narg.next;
10720 n1->nfor.args = ap;
10721 if (lasttoken != TNL && lasttoken != TSEMI)
10722 raise_error_unexpected_syntax(-1);
10724 n2 = stzalloc(sizeof(struct narg));
10726 /*n2->narg.next = NULL; - stzalloc did it */
10727 n2->narg.text = (char *)dolatstr;
10728 /*n2->narg.backquote = NULL;*/
10729 n1->nfor.args = n2;
10731 * Newline or semicolon here is optional (but note
10732 * that the original Bourne shell only allowed NL).
10734 if (lasttoken != TNL && lasttoken != TSEMI)
10737 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10738 if (readtoken() != TDO)
10739 raise_error_unexpected_syntax(TDO);
10740 n1->nfor.body = list(0);
10744 n1 = stzalloc(sizeof(struct ncase));
10746 if (readtoken() != TWORD)
10747 raise_error_unexpected_syntax(TWORD);
10748 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10750 /*n2->narg.next = NULL; - stzalloc did it */
10751 n2->narg.text = wordtext;
10752 n2->narg.backquote = backquotelist;
10754 checkkwd = CHKKWD | CHKALIAS;
10755 } while (readtoken() == TNL);
10756 if (lasttoken != TIN)
10757 raise_error_unexpected_syntax(TIN);
10758 cpp = &n1->ncase.cases;
10760 checkkwd = CHKNL | CHKKWD;
10762 while (t != TESAC) {
10763 if (lasttoken == TLP)
10765 *cpp = cp = stzalloc(sizeof(struct nclist));
10767 app = &cp->nclist.pattern;
10769 *app = ap = stzalloc(sizeof(struct narg));
10771 /*ap->narg.next = NULL; - stzalloc did it */
10772 ap->narg.text = wordtext;
10773 ap->narg.backquote = backquotelist;
10774 if (readtoken() != TPIPE)
10776 app = &ap->narg.next;
10779 //ap->narg.next = NULL;
10780 if (lasttoken != TRP)
10781 raise_error_unexpected_syntax(TRP);
10782 cp->nclist.body = list(2);
10784 cpp = &cp->nclist.next;
10786 checkkwd = CHKNL | CHKKWD;
10790 raise_error_unexpected_syntax(TENDCASE);
10797 n1 = stzalloc(sizeof(struct nredir));
10798 n1->type = NSUBSHELL;
10799 n1->nredir.n = list(0);
10800 /*n1->nredir.redirect = NULL; - stzalloc did it */
10810 return simplecmd();
10813 if (readtoken() != t)
10814 raise_error_unexpected_syntax(t);
10817 /* Now check for redirection which may follow command */
10818 checkkwd = CHKKWD | CHKALIAS;
10820 while (readtoken() == TREDIR) {
10821 *rpp = n2 = redirnode;
10822 rpp = &n2->nfile.next;
10828 if (n1->type != NSUBSHELL) {
10829 n2 = stzalloc(sizeof(struct nredir));
10834 n1->nredir.redirect = redir;
10839 #if ENABLE_ASH_BASH_COMPAT
10840 static int decode_dollar_squote(void)
10842 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10848 p = strchr(C_escapes, c);
10853 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10857 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10859 } else if (c == 'x') { /* \xHH */
10863 } while (isxdigit(c) && --cnt);
10865 if (cnt == 3) { /* \x but next char is "bad" */
10869 } else { /* simple seq like \\ or \t */
10874 c = bb_process_escape_sequence((void*)&p);
10875 } else { /* unrecognized "\z": print both chars unless ' or " */
10876 if (c != '\'' && c != '"') {
10878 c |= 0x100; /* "please encode \, then me" */
10886 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10887 * is not NULL, read a here document. In the latter case, eofmark is the
10888 * word which marks the end of the document and striptabs is true if
10889 * leading tabs should be stripped from the document. The argument c
10890 * is the first character of the input token or document.
10892 * Because C does not have internal subroutines, I have simulated them
10893 * using goto's to implement the subroutine linkage. The following macros
10894 * will run code that appears at the end of readtoken1.
10896 #define CHECKEND() {goto checkend; checkend_return:;}
10897 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10898 #define PARSESUB() {goto parsesub; parsesub_return:;}
10899 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10900 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10901 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10903 readtoken1(int c, int syntax, char *eofmark, int striptabs)
10905 /* NB: syntax parameter fits into smallint */
10906 /* c parameter is an unsigned char or PEOF or PEOA */
10909 char line[EOFMARKLEN + 1];
10910 struct nodelist *bqlist;
10914 smallint prevsyntax; /* syntax before arithmetic */
10915 #if ENABLE_ASH_EXPAND_PRMT
10916 smallint pssyntax; /* we are expanding a prompt string */
10918 int varnest; /* levels of variables expansion */
10919 int arinest; /* levels of arithmetic expansion */
10920 int parenlevel; /* levels of parens in arithmetic */
10921 int dqvarnest; /* levels of variables expansion within double quotes */
10923 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10926 /* Avoid longjmp clobbering */
10932 (void) &parenlevel;
10935 (void) &prevsyntax;
10938 startlinno = g_parsefile->linno;
10943 #if ENABLE_ASH_EXPAND_PRMT
10944 pssyntax = (syntax == PSSYNTAX);
10948 dblquote = (syntax == DQSYNTAX);
10954 STARTSTACKSTR(out);
10956 /* For each line, until end of word */
10958 CHECKEND(); /* set c to PEOF if at end of here document */
10959 for (;;) { /* until end of line or end of word */
10960 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10961 switch (SIT(c, syntax)) {
10962 case CNL: /* '\n' */
10963 if (syntax == BASESYNTAX)
10964 goto endword; /* exit outer loop */
10966 g_parsefile->linno++;
10970 goto loop; /* continue outer loop */
10975 if (eofmark == NULL || dblquote)
10976 USTPUTC(CTLESC, out);
10977 #if ENABLE_ASH_BASH_COMPAT
10978 if (c == '\\' && bash_dollar_squote) {
10979 c = decode_dollar_squote();
10981 USTPUTC('\\', out);
10982 c = (unsigned char)c;
10988 case CBACK: /* backslash */
10989 c = pgetc_without_PEOA();
10991 USTPUTC(CTLESC, out);
10992 USTPUTC('\\', out);
10994 } else if (c == '\n') {
10998 #if ENABLE_ASH_EXPAND_PRMT
10999 if (c == '$' && pssyntax) {
11000 USTPUTC(CTLESC, out);
11001 USTPUTC('\\', out);
11004 if (dblquote && c != '\\'
11005 && c != '`' && c != '$'
11006 && (c != '"' || eofmark != NULL)
11008 USTPUTC(CTLESC, out);
11009 USTPUTC('\\', out);
11011 if (SIT(c, SQSYNTAX) == CCTL)
11012 USTPUTC(CTLESC, out);
11020 if (eofmark == NULL) {
11021 USTPUTC(CTLQUOTEMARK, out);
11029 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11030 if (eofmark != NULL && arinest == 0
11035 if (dqvarnest == 0) {
11036 syntax = BASESYNTAX;
11043 case CVAR: /* '$' */
11044 PARSESUB(); /* parse substitution */
11046 case CENDVAR: /* '}' */
11049 if (dqvarnest > 0) {
11052 USTPUTC(CTLENDVAR, out);
11057 #if ENABLE_SH_MATH_SUPPORT
11058 case CLP: /* '(' in arithmetic */
11062 case CRP: /* ')' in arithmetic */
11063 if (parenlevel > 0) {
11067 if (pgetc() == ')') {
11068 if (--arinest == 0) {
11069 USTPUTC(CTLENDARI, out);
11070 syntax = prevsyntax;
11071 dblquote = (syntax == DQSYNTAX);
11076 * unbalanced parens
11077 * (don't 2nd guess - no error)
11085 case CBQUOTE: /* '`' */
11089 goto endword; /* exit outer loop */
11093 if (varnest == 0) {
11094 #if ENABLE_ASH_BASH_COMPAT
11096 if (pgetc() == '>')
11097 c = 0x100 + '>'; /* flag &> */
11101 goto endword; /* exit outer loop */
11103 IF_ASH_ALIAS(if (c != PEOA))
11111 #if ENABLE_SH_MATH_SUPPORT
11112 if (syntax == ARISYNTAX)
11113 raise_error_syntax("missing '))'");
11115 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11116 raise_error_syntax("unterminated quoted string");
11117 if (varnest != 0) {
11118 startlinno = g_parsefile->linno;
11120 raise_error_syntax("missing '}'");
11122 USTPUTC('\0', out);
11123 len = out - (char *)stackblock();
11124 out = stackblock();
11125 if (eofmark == NULL) {
11126 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11129 if (isdigit_str9(out)) {
11130 PARSEREDIR(); /* passed as params: out, c */
11131 lasttoken = TREDIR;
11134 /* else: non-number X seen, interpret it
11135 * as "NNNX>file" = "NNNX >file" */
11139 quoteflag = quotef;
11140 backquotelist = bqlist;
11141 grabstackblock(len);
11145 /* end of readtoken routine */
11148 * Check to see whether we are at the end of the here document. When this
11149 * is called, c is set to the first character of the next input line. If
11150 * we are at the end of the here document, this routine sets the c to PEOF.
11154 #if ENABLE_ASH_ALIAS
11156 c = pgetc_without_PEOA();
11159 while (c == '\t') {
11160 c = pgetc_without_PEOA();
11163 if (c == *eofmark) {
11164 if (pfgets(line, sizeof(line)) != NULL) {
11168 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11170 if (*p == '\n' && *q == '\0') {
11172 g_parsefile->linno++;
11173 needprompt = doprompt;
11175 pushstring(line, NULL);
11180 goto checkend_return;
11184 * Parse a redirection operator. The variable "out" points to a string
11185 * specifying the fd to be redirected. The variable "c" contains the
11186 * first character of the redirection operator.
11189 /* out is already checked to be a valid number or "" */
11190 int fd = (*out == '\0' ? -1 : atoi(out));
11193 np = stzalloc(sizeof(struct nfile));
11198 np->type = NAPPEND;
11200 np->type = NCLOBBER;
11203 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11209 #if ENABLE_ASH_BASH_COMPAT
11210 else if (c == 0x100 + '>') { /* this flags &> redirection */
11212 pgetc(); /* this is '>', no need to check */
11216 else { /* c == '<' */
11217 /*np->nfile.fd = 0; - stzalloc did it */
11221 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11222 np = stzalloc(sizeof(struct nhere));
11223 /*np->nfile.fd = 0; - stzalloc did it */
11226 heredoc = stzalloc(sizeof(struct heredoc));
11227 heredoc->here = np;
11230 heredoc->striptabs = 1;
11232 /*heredoc->striptabs = 0; - stzalloc did it */
11238 np->type = NFROMFD;
11242 np->type = NFROMTO;
11254 goto parseredir_return;
11258 * Parse a substitution. At this point, we have read the dollar sign
11259 * and nothing else.
11262 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11263 * (assuming ascii char codes, as the original implementation did) */
11264 #define is_special(c) \
11265 (((unsigned)(c) - 33 < 32) \
11266 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11268 unsigned char subtype;
11272 static const char types[] ALIGN1 = "}-+?=";
11275 if (c > 255 /* PEOA or PEOF */
11276 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11278 #if ENABLE_ASH_BASH_COMPAT
11280 bash_dollar_squote = 1;
11285 } else if (c == '(') { /* $(command) or $((arith)) */
11286 if (pgetc() == '(') {
11287 #if ENABLE_SH_MATH_SUPPORT
11290 raise_error_syntax("you disabled math support for $((arith)) syntax");
11297 USTPUTC(CTLVAR, out);
11298 typeloc = out - (char *)stackblock();
11299 USTPUTC(VSNORMAL, out);
11300 subtype = VSNORMAL;
11308 subtype = VSLENGTH;
11312 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11316 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11317 } else if (isdigit(c)) {
11321 } while (isdigit(c));
11322 } else if (is_special(c)) {
11327 raise_error_syntax("bad substitution");
11329 if (c != '}' && subtype == VSLENGTH)
11334 if (subtype == 0) {
11338 #if ENABLE_ASH_BASH_COMPAT
11339 if (c == ':' || c == '$' || isdigit(c)) {
11341 subtype = VSSUBSTR;
11348 p = strchr(types, c);
11351 subtype = p - types + VSNORMAL;
11356 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11364 #if ENABLE_ASH_BASH_COMPAT
11366 subtype = VSREPLACE;
11369 subtype++; /* VSREPLACEALL */
11378 if (dblquote || arinest)
11380 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11381 if (subtype != VSNORMAL) {
11383 if (dblquote || arinest) {
11388 goto parsesub_return;
11392 * Called to parse command substitutions. Newstyle is set if the command
11393 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11394 * list of commands (passed by reference), and savelen is the number of
11395 * characters on the top of the stack which must be preserved.
11398 struct nodelist **nlpp;
11401 char *volatile str;
11402 struct jmploc jmploc;
11403 struct jmploc *volatile savehandler;
11405 smallint saveprompt = 0;
11408 (void) &saveprompt;
11410 savepbq = parsebackquote;
11411 if (setjmp(jmploc.loc)) {
11413 parsebackquote = 0;
11414 exception_handler = savehandler;
11415 longjmp(exception_handler->loc, 1);
11419 savelen = out - (char *)stackblock();
11421 str = ckmalloc(savelen);
11422 memcpy(str, stackblock(), savelen);
11424 savehandler = exception_handler;
11425 exception_handler = &jmploc;
11428 /* We must read until the closing backquote, giving special
11429 treatment to some slashes, and then push the string and
11430 reread it as input, interpreting it normally. */
11437 STARTSTACKSTR(pout);
11450 g_parsefile->linno++;
11454 * If eating a newline, avoid putting
11455 * the newline into the new character
11456 * stream (via the STPUTC after the
11461 if (pc != '\\' && pc != '`' && pc != '$'
11462 && (!dblquote || pc != '"')
11464 STPUTC('\\', pout);
11466 if (pc <= 255 /* not PEOA or PEOF */) {
11472 IF_ASH_ALIAS(case PEOA:)
11473 startlinno = g_parsefile->linno;
11474 raise_error_syntax("EOF in backquote substitution");
11477 g_parsefile->linno++;
11478 needprompt = doprompt;
11487 STPUTC('\0', pout);
11488 psavelen = pout - (char *)stackblock();
11489 if (psavelen > 0) {
11490 pstr = grabstackstr(pout);
11491 setinputstring(pstr);
11496 nlpp = &(*nlpp)->next;
11497 *nlpp = stzalloc(sizeof(**nlpp));
11498 /* (*nlpp)->next = NULL; - stzalloc did it */
11499 parsebackquote = oldstyle;
11502 saveprompt = doprompt;
11509 doprompt = saveprompt;
11510 else if (readtoken() != TRP)
11511 raise_error_unexpected_syntax(TRP);
11516 * Start reading from old file again, ignoring any pushed back
11517 * tokens left from the backquote parsing
11522 while (stackblocksize() <= savelen)
11524 STARTSTACKSTR(out);
11526 memcpy(out, str, savelen);
11527 STADJUST(savelen, out);
11533 parsebackquote = savepbq;
11534 exception_handler = savehandler;
11535 if (arinest || dblquote)
11536 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11538 USTPUTC(CTLBACKQ, out);
11540 goto parsebackq_oldreturn;
11541 goto parsebackq_newreturn;
11544 #if ENABLE_SH_MATH_SUPPORT
11546 * Parse an arithmetic expansion (indicate start of one and set state)
11549 if (++arinest == 1) {
11550 prevsyntax = syntax;
11551 syntax = ARISYNTAX;
11552 USTPUTC(CTLARI, out);
11559 * we collapse embedded arithmetic expansion to
11560 * parenthesis, which should be equivalent
11564 goto parsearith_return;
11568 } /* end of readtoken */
11571 * Read the next input token.
11572 * If the token is a word, we set backquotelist to the list of cmds in
11573 * backquotes. We set quoteflag to true if any part of the word was
11575 * If the token is TREDIR, then we set redirnode to a structure containing
11577 * In all cases, the variable startlinno is set to the number of the line
11578 * on which the token starts.
11580 * [Change comment: here documents and internal procedures]
11581 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11582 * word parsing code into a separate routine. In this case, readtoken
11583 * doesn't need to have any internal procedures, but parseword does.
11584 * We could also make parseoperator in essence the main routine, and
11585 * have parseword (readtoken1?) handle both words and redirection.]
11587 #define NEW_xxreadtoken
11588 #ifdef NEW_xxreadtoken
11589 /* singles must be first! */
11590 static const char xxreadtoken_chars[7] ALIGN1 = {
11591 '\n', '(', ')', /* singles */
11592 '&', '|', ';', /* doubles */
11596 #define xxreadtoken_singles 3
11597 #define xxreadtoken_doubles 3
11599 static const char xxreadtoken_tokens[] ALIGN1 = {
11600 TNL, TLP, TRP, /* only single occurrence allowed */
11601 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11602 TEOF, /* corresponds to trailing nul */
11603 TAND, TOR, TENDCASE /* if double occurrence */
11618 startlinno = g_parsefile->linno;
11619 for (;;) { /* until token or start of word found */
11621 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11625 while ((c = pgetc()) != '\n' && c != PEOF)
11628 } else if (c == '\\') {
11629 if (pgetc() != '\n') {
11631 break; /* return readtoken1(...) */
11633 startlinno = ++g_parsefile->linno;
11639 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11642 g_parsefile->linno++;
11643 needprompt = doprompt;
11646 p = strchr(xxreadtoken_chars, c);
11648 break; /* return readtoken1(...) */
11650 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11652 if (cc == c) { /* double occurrence? */
11653 p += xxreadtoken_doubles + 1;
11656 #if ENABLE_ASH_BASH_COMPAT
11657 if (c == '&' && cc == '>') /* &> */
11658 break; /* return readtoken1(...) */
11663 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11668 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11670 #else /* old xxreadtoken */
11671 #define RETURN(token) return lasttoken = token
11684 startlinno = g_parsefile->linno;
11685 for (;;) { /* until token or start of word found */
11688 case ' ': case '\t':
11689 IF_ASH_ALIAS(case PEOA:)
11692 while ((c = pgetc()) != '\n' && c != PEOF)
11697 if (pgetc() == '\n') {
11698 startlinno = ++g_parsefile->linno;
11706 g_parsefile->linno++;
11707 needprompt = doprompt;
11712 if (pgetc() == '&')
11717 if (pgetc() == '|')
11722 if (pgetc() == ';')
11735 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11738 #endif /* old xxreadtoken */
11745 smallint alreadyseen = tokpushback;
11748 #if ENABLE_ASH_ALIAS
11757 if (checkkwd & CHKNL) {
11764 if (t != TWORD || quoteflag) {
11769 * check for keywords
11771 if (checkkwd & CHKKWD) {
11772 const char *const *pp;
11774 pp = findkwd(wordtext);
11776 lasttoken = t = pp - tokname_array;
11777 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
11782 if (checkkwd & CHKALIAS) {
11783 #if ENABLE_ASH_ALIAS
11785 ap = lookupalias(wordtext, 1);
11788 pushstring(ap->val, ap);
11798 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11800 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11812 return tokname_array[t][0];
11816 * Read and parse a command. Returns NODE_EOF on end of file.
11817 * (NULL is a valid parse tree indicating a blank line.)
11819 static union node *
11820 parsecmd(int interact)
11825 doprompt = interact;
11827 setprompt(doprompt);
11839 * Input any here documents.
11844 struct heredoc *here;
11847 here = heredoclist;
11848 heredoclist = NULL;
11854 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11855 here->eofmark, here->striptabs);
11856 n = stzalloc(sizeof(struct narg));
11857 n->narg.type = NARG;
11858 /*n->narg.next = NULL; - stzalloc did it */
11859 n->narg.text = wordtext;
11860 n->narg.backquote = backquotelist;
11861 here->here->nhere.doc = n;
11868 * called by editline -- any expansions to the prompt should be added here.
11870 #if ENABLE_ASH_EXPAND_PRMT
11871 static const char *
11872 expandstr(const char *ps)
11876 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11877 * and token processing _can_ alter it (delete NULs etc). */
11878 setinputstring((char *)ps);
11879 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11882 n.narg.type = NARG;
11883 n.narg.next = NULL;
11884 n.narg.text = wordtext;
11885 n.narg.backquote = backquotelist;
11887 expandarg(&n, NULL, 0);
11888 return stackblock();
11893 * Execute a command or commands contained in a string.
11896 evalstring(char *s, int mask)
11899 struct stackmark smark;
11903 setstackmark(&smark);
11906 while ((n = parsecmd(0)) != NODE_EOF) {
11908 popstackmark(&smark);
11921 * The eval command.
11923 static int FAST_FUNC
11924 evalcmd(int argc UNUSED_PARAM, char **argv)
11933 STARTSTACKSTR(concat);
11935 concat = stack_putstr(p, concat);
11939 STPUTC(' ', concat);
11941 STPUTC('\0', concat);
11942 p = grabstackstr(concat);
11944 evalstring(p, ~SKIPEVAL);
11951 * Read and execute commands.
11952 * "Top" is nonzero for the top level command loop;
11953 * it turns on prompting if the shell is interactive.
11959 struct stackmark smark;
11963 TRACE(("cmdloop(%d) called\n", top));
11967 setstackmark(&smark);
11970 showjobs(stderr, SHOW_CHANGED);
11973 if (iflag && top) {
11975 #if ENABLE_ASH_MAIL
11979 n = parsecmd(inter);
11981 if (DEBUG > 2 && debug && (n != NODE_EOF))
11984 if (n == NODE_EOF) {
11985 if (!top || numeof >= 50)
11987 if (!stoppedjobs()) {
11990 out2str("\nUse \"exit\" to leave shell.\n");
11993 } else if (nflag == 0) {
11994 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11999 popstackmark(&smark);
12004 return skip & SKIPEVAL;
12011 * Take commands from a file. To be compatible we should do a path
12012 * search for the file, which is necessary to find sub-commands.
12015 find_dot_file(char *name)
12018 const char *path = pathval();
12021 /* don't try this for absolute or relative paths */
12022 if (strchr(name, '/'))
12025 /* IIRC standards do not say whether . is to be searched.
12026 * And it is even smaller this way, making it unconditional for now:
12028 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12033 while ((fullname = path_advance(&path, name)) != NULL) {
12035 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12037 * Don't bother freeing here, since it will
12038 * be freed by the caller.
12042 if (fullname != name)
12043 stunalloc(fullname);
12046 /* not found in the PATH */
12047 ash_msg_and_raise_error("%s: not found", name);
12051 static int FAST_FUNC
12052 dotcmd(int argc, char **argv)
12055 struct strlist *sp;
12056 volatile struct shparam saveparam;
12058 for (sp = cmdenviron; sp; sp = sp->next)
12059 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12062 /* bash says: "bash: .: filename argument required" */
12063 return 2; /* bash compat */
12066 /* "false; . empty_file; echo $?" should print 0, not 1: */
12069 fullname = find_dot_file(argv[1]);
12073 if (argc) { /* argc > 0, argv[0] != NULL */
12074 saveparam = shellparam;
12075 shellparam.malloced = 0;
12076 shellparam.nparam = argc;
12077 shellparam.p = argv;
12080 setinputfile(fullname, INPUT_PUSH_FILE);
12081 commandname = fullname;
12086 freeparam(&shellparam);
12087 shellparam = saveparam;
12093 static int FAST_FUNC
12094 exitcmd(int argc UNUSED_PARAM, char **argv)
12099 exitstatus = number(argv[1]);
12100 raise_exception(EXEXIT);
12105 * Read a file containing shell functions.
12108 readcmdfile(char *name)
12110 setinputfile(name, INPUT_PUSH_FILE);
12116 /* ============ find_command inplementation */
12119 * Resolve a command name. If you change this routine, you may have to
12120 * change the shellexec routine as well.
12123 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12125 struct tblentry *cmdp;
12132 struct builtincmd *bcmd;
12134 /* If name contains a slash, don't use PATH or hash table */
12135 if (strchr(name, '/') != NULL) {
12136 entry->u.index = -1;
12137 if (act & DO_ABS) {
12138 while (stat(name, &statb) < 0) {
12140 if (errno == EINTR)
12143 entry->cmdtype = CMDUNKNOWN;
12147 entry->cmdtype = CMDNORMAL;
12151 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12153 updatetbl = (path == pathval());
12156 if (strstr(path, "%builtin") != NULL)
12157 act |= DO_ALTBLTIN;
12160 /* If name is in the table, check answer will be ok */
12161 cmdp = cmdlookup(name, 0);
12162 if (cmdp != NULL) {
12165 switch (cmdp->cmdtype) {
12183 } else if (cmdp->rehash == 0)
12184 /* if not invalidated by cd, we're done */
12188 /* If %builtin not in path, check for builtin next */
12189 bcmd = find_builtin(name);
12191 if (IS_BUILTIN_REGULAR(bcmd))
12192 goto builtin_success;
12193 if (act & DO_ALTPATH) {
12194 if (!(act & DO_ALTBLTIN))
12195 goto builtin_success;
12196 } else if (builtinloc <= 0) {
12197 goto builtin_success;
12201 #if ENABLE_FEATURE_SH_STANDALONE
12203 int applet_no = find_applet_by_name(name);
12204 if (applet_no >= 0) {
12205 entry->cmdtype = CMDNORMAL;
12206 entry->u.index = -2 - applet_no;
12212 /* We have to search path. */
12213 prev = -1; /* where to start */
12214 if (cmdp && cmdp->rehash) { /* doing a rehash */
12215 if (cmdp->cmdtype == CMDBUILTIN)
12218 prev = cmdp->param.index;
12224 while ((fullname = path_advance(&path, name)) != NULL) {
12225 stunalloc(fullname);
12226 /* NB: code below will still use fullname
12227 * despite it being "unallocated" */
12230 if (prefix(pathopt, "builtin")) {
12232 goto builtin_success;
12235 if ((act & DO_NOFUNC)
12236 || !prefix(pathopt, "func")
12237 ) { /* ignore unimplemented options */
12241 /* if rehash, don't redo absolute path names */
12242 if (fullname[0] == '/' && idx <= prev) {
12245 TRACE(("searchexec \"%s\": no change\n", name));
12248 while (stat(fullname, &statb) < 0) {
12250 if (errno == EINTR)
12253 if (errno != ENOENT && errno != ENOTDIR)
12257 e = EACCES; /* if we fail, this will be the error */
12258 if (!S_ISREG(statb.st_mode))
12260 if (pathopt) { /* this is a %func directory */
12261 stalloc(strlen(fullname) + 1);
12262 /* NB: stalloc will return space pointed by fullname
12263 * (because we don't have any intervening allocations
12264 * between stunalloc above and this stalloc) */
12265 readcmdfile(fullname);
12266 cmdp = cmdlookup(name, 0);
12267 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12268 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12269 stunalloc(fullname);
12272 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12274 entry->cmdtype = CMDNORMAL;
12275 entry->u.index = idx;
12279 cmdp = cmdlookup(name, 1);
12280 cmdp->cmdtype = CMDNORMAL;
12281 cmdp->param.index = idx;
12286 /* We failed. If there was an entry for this command, delete it */
12287 if (cmdp && updatetbl)
12288 delete_cmd_entry();
12290 ash_msg("%s: %s", name, errmsg(e, "not found"));
12291 entry->cmdtype = CMDUNKNOWN;
12296 entry->cmdtype = CMDBUILTIN;
12297 entry->u.cmd = bcmd;
12301 cmdp = cmdlookup(name, 1);
12302 cmdp->cmdtype = CMDBUILTIN;
12303 cmdp->param.cmd = bcmd;
12307 entry->cmdtype = cmdp->cmdtype;
12308 entry->u = cmdp->param;
12312 /* ============ trap.c */
12315 * The trap builtin.
12317 static int FAST_FUNC
12318 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12322 int signo, exitcode;
12327 for (signo = 0; signo < NSIG; signo++) {
12328 char *tr = trap_ptr[signo];
12330 /* note: bash adds "SIG", but only if invoked
12331 * as "bash". If called as "sh", or if set -o posix,
12332 * then it prints short signal names.
12333 * We are printing short names: */
12334 out1fmt("trap -- %s %s\n",
12336 get_signame(signo));
12337 /* trap_ptr != trap only if we are in special-cased `trap` code.
12338 * In this case, we will exit very soon, no need to free(). */
12339 /* if (trap_ptr != trap && tp[0]) */
12344 if (trap_ptr != trap) {
12357 signo = get_signum(*ap);
12359 /* Mimic bash message exactly */
12360 ash_msg("%s: invalid signal specification", *ap);
12366 if (LONE_DASH(action))
12369 action = ckstrdup(action);
12373 may_have_traps = 1;
12374 trap[signo] = action;
12385 /* ============ Builtins */
12387 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12389 * Lists available builtins
12391 static int FAST_FUNC
12392 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12398 "Built-in commands:\n"
12399 "------------------\n");
12400 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12401 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12402 builtintab[i].name + 1);
12408 #if ENABLE_FEATURE_SH_STANDALONE
12410 const char *a = applet_names;
12412 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12417 a += strlen(a) + 1;
12422 return EXIT_SUCCESS;
12424 #endif /* FEATURE_SH_EXTRA_QUIET */
12427 * The export and readonly commands.
12429 static int FAST_FUNC
12430 exportcmd(int argc UNUSED_PARAM, char **argv)
12436 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12438 if (nextopt("p") != 'p') {
12443 p = strchr(name, '=');
12447 vp = *findvar(hashvar(name), name);
12453 setvar(name, p, flag);
12454 } while ((name = *++aptr) != NULL);
12458 showvars(argv[0], flag, 0);
12463 * Delete a function if it exists.
12466 unsetfunc(const char *name)
12468 struct tblentry *cmdp;
12470 cmdp = cmdlookup(name, 0);
12471 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12472 delete_cmd_entry();
12476 * The unset builtin command. We unset the function before we unset the
12477 * variable to allow a function to be unset when there is a readonly variable
12478 * with the same name.
12480 static int FAST_FUNC
12481 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12488 while ((i = nextopt("vf")) != '\0') {
12492 for (ap = argptr; *ap; ap++) {
12508 #include <sys/times.h>
12510 static const unsigned char timescmd_str[] ALIGN1 = {
12511 ' ', offsetof(struct tms, tms_utime),
12512 '\n', offsetof(struct tms, tms_stime),
12513 ' ', offsetof(struct tms, tms_cutime),
12514 '\n', offsetof(struct tms, tms_cstime),
12518 static int FAST_FUNC
12519 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12521 long clk_tck, s, t;
12522 const unsigned char *p;
12525 clk_tck = sysconf(_SC_CLK_TCK);
12530 t = *(clock_t *)(((char *) &buf) + p[1]);
12532 out1fmt("%ldm%ld.%.3lds%c",
12534 ((t - s * clk_tck) * 1000) / clk_tck,
12536 } while (*(p += 2));
12541 #if ENABLE_SH_MATH_SUPPORT
12543 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12544 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12546 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12548 static int FAST_FUNC
12549 letcmd(int argc UNUSED_PARAM, char **argv)
12555 ash_msg_and_raise_error("expression expected");
12557 i = ash_arith(*argv);
12562 #endif /* SH_MATH_SUPPORT */
12565 /* ============ miscbltin.c
12567 * Miscellaneous builtins.
12572 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
12573 typedef enum __rlimit_resource rlim_t;
12577 * The read builtin. Options:
12578 * -r Do not interpret '\' specially
12579 * -s Turn off echo (tty only)
12580 * -n NCHARS Read NCHARS max
12581 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12582 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12583 * -u FD Read from given FD instead of fd 0
12584 * This uses unbuffered input, which may be avoidable in some cases.
12585 * TODO: bash also has:
12586 * -a ARRAY Read into array[0],[1],etc
12587 * -d DELIM End on DELIM char, not newline
12588 * -e Use line editing (tty only)
12590 static int FAST_FUNC
12591 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12593 char *opt_n = NULL;
12594 char *opt_p = NULL;
12595 char *opt_t = NULL;
12596 char *opt_u = NULL;
12597 int read_flags = 0;
12601 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12610 read_flags |= BUILTIN_READ_SILENT;
12616 read_flags |= BUILTIN_READ_RAW;
12626 r = shell_builtin_read(setvar2,
12628 bltinlookup("IFS"), /* can be NULL */
12636 if ((uintptr_t)r > 1)
12637 ash_msg_and_raise_error(r);
12639 return (uintptr_t)r;
12642 static int FAST_FUNC
12643 umaskcmd(int argc UNUSED_PARAM, char **argv)
12645 static const char permuser[3] ALIGN1 = "ugo";
12646 static const char permmode[3] ALIGN1 = "rwx";
12647 static const short permmask[] ALIGN2 = {
12648 S_IRUSR, S_IWUSR, S_IXUSR,
12649 S_IRGRP, S_IWGRP, S_IXGRP,
12650 S_IROTH, S_IWOTH, S_IXOTH
12653 /* TODO: use bb_parse_mode() instead */
12658 int symbolic_mode = 0;
12660 while (nextopt("S") != '\0') {
12671 if (symbolic_mode) {
12675 for (i = 0; i < 3; i++) {
12678 *p++ = permuser[i];
12680 for (j = 0; j < 3; j++) {
12681 if ((mask & permmask[3 * i + j]) == 0) {
12682 *p++ = permmode[j];
12690 out1fmt("%.4o\n", mask);
12693 if (isdigit((unsigned char) *ap)) {
12696 if (*ap >= '8' || *ap < '0')
12697 ash_msg_and_raise_error(msg_illnum, argv[1]);
12698 mask = (mask << 3) + (*ap - '0');
12699 } while (*++ap != '\0');
12702 mask = ~mask & 0777;
12703 if (!bb_parse_mode(ap, &mask)) {
12704 ash_msg_and_raise_error("illegal mode: %s", ap);
12706 umask(~mask & 0777);
12712 static int FAST_FUNC
12713 ulimitcmd(int argc UNUSED_PARAM, char **argv)
12715 return shell_builtin_ulimit(argv);
12718 /* ============ main() and helpers */
12721 * Called to exit the shell.
12723 static void exitshell(void) NORETURN;
12731 status = exitstatus;
12732 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12733 if (setjmp(loc.loc)) {
12734 if (exception_type == EXEXIT)
12735 /* dash bug: it just does _exit(exitstatus) here
12736 * but we have to do setjobctl(0) first!
12737 * (bug is still not fixed in dash-0.5.3 - if you run dash
12738 * under Midnight Commander, on exit from dash MC is backgrounded) */
12739 status = exitstatus;
12742 exception_handler = &loc;
12749 flush_stdout_stderr();
12759 /* from input.c: */
12760 /* we will never free this */
12761 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
12764 signal(SIGCHLD, SIG_DFL);
12765 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12766 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12768 signal(SIGHUP, SIG_DFL);
12774 struct stat st1, st2;
12777 for (envp = environ; envp && *envp; envp++) {
12778 if (strchr(*envp, '=')) {
12779 setvareq(*envp, VEXPORT|VTEXTFIXED);
12783 setvar("PPID", utoa(getppid()), 0);
12785 p = lookupvar("PWD");
12787 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12788 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12795 * Process the shell command line arguments.
12798 procargs(char **argv)
12801 const char *xminusc;
12806 /* if (xargv[0]) - mmm, this is always true! */
12808 for (i = 0; i < NOPTS; i++)
12812 /* it already printed err message */
12813 raise_exception(EXERROR);
12817 if (*xargv == NULL) {
12819 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12822 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12826 for (i = 0; i < NOPTS; i++)
12827 if (optlist[i] == 2)
12832 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12837 } else if (!sflag) {
12838 setinputfile(*xargv, 0);
12841 commandname = arg0;
12844 shellparam.p = xargv;
12845 #if ENABLE_ASH_GETOPTS
12846 shellparam.optind = 1;
12847 shellparam.optoff = -1;
12849 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
12851 shellparam.nparam++;
12858 * Read /etc/profile or .profile.
12861 read_profile(const char *name)
12865 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12874 * This routine is called when an error or an interrupt occurs in an
12875 * interactive shell and control is returned to the main command loop.
12883 /* from input.c: */
12884 g_parsefile->left_in_buffer = 0;
12885 g_parsefile->left_in_line = 0; /* clear input buffer */
12887 /* from parser.c: */
12890 /* from redir.c: */
12891 clearredir(/*drop:*/ 0);
12895 static short profile_buf[16384];
12896 extern int etext();
12900 * Main routine. We initialize things, parse the arguments, execute
12901 * profiles if we're a login shell, and then call cmdloop to execute
12902 * commands. The setjmp call sets up the location to jump to when an
12903 * exception occurs. When an exception occurs the variable "state"
12904 * is used to figure out how far we had gotten.
12906 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
12907 int ash_main(int argc UNUSED_PARAM, char **argv)
12909 const char *shinit;
12910 volatile smallint state;
12911 struct jmploc jmploc;
12912 struct stackmark smark;
12914 /* Initialize global data */
12918 #if ENABLE_ASH_ALIAS
12924 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12927 #if ENABLE_FEATURE_EDITING
12928 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12931 if (setjmp(jmploc.loc)) {
12937 e = exception_type;
12941 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12944 outcslow('\n', stderr);
12946 popstackmark(&smark);
12947 FORCE_INT_ON; /* enable interrupts */
12956 exception_handler = &jmploc;
12959 TRACE(("Shell args: "));
12960 trace_puts_args(argv);
12962 rootpid = getpid();
12965 setstackmark(&smark);
12968 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
12970 const char *hp = lookupvar("HISTFILE");
12973 hp = lookupvar("HOME");
12975 char *defhp = concat_path_file(hp, ".ash_history");
12976 setvar("HISTFILE", defhp, 0);
12982 if (/* argv[0] && */ argv[0][0] == '-')
12986 read_profile("/etc/profile");
12989 read_profile(".profile");
12995 getuid() == geteuid() && getgid() == getegid() &&
12999 shinit = lookupvar("ENV");
13000 if (shinit != NULL && *shinit != '\0') {
13001 read_profile(shinit);
13007 /* evalstring pushes parsefile stack.
13008 * Ensure we don't falsely claim that 0 (stdin)
13009 * is one of stacked source fds.
13010 * Testcase: ash -c 'exec 1>&0' must not complain. */
13011 // if (!sflag) g_parsefile->pf_fd = -1;
13012 // ^^ not necessary since now we special-case fd 0
13013 // in is_hidden_fd() to not be considered "hidden fd"
13014 evalstring(minusc, 0);
13017 if (sflag || minusc == NULL) {
13018 #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13020 const char *hp = lookupvar("HISTFILE");
13022 line_input_state->hist_file = hp;
13025 state4: /* XXX ??? - why isn't this before the "if" statement */
13033 extern void _mcleanup(void);
13043 * Copyright (c) 1989, 1991, 1993, 1994
13044 * The Regents of the University of California. All rights reserved.
13046 * This code is derived from software contributed to Berkeley by
13047 * Kenneth Almquist.
13049 * Redistribution and use in source and binary forms, with or without
13050 * modification, are permitted provided that the following conditions
13052 * 1. Redistributions of source code must retain the above copyright
13053 * notice, this list of conditions and the following disclaimer.
13054 * 2. Redistributions in binary form must reproduce the above copyright
13055 * notice, this list of conditions and the following disclaimer in the
13056 * documentation and/or other materials provided with the distribution.
13057 * 3. Neither the name of the University nor the names of its contributors
13058 * may be used to endorse or promote products derived from this software
13059 * without specific prior written permission.
13061 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13062 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13063 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13064 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13065 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13066 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13067 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13068 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13069 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13070 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF