1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
20 * The following should be set to reflect the type of system you have:
21 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22 * define SYSV if you are running under System V.
23 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24 * define DEBUG=2 to compile in and turn on debugging.
26 * When debugging is on, debugging info will be written to ./trace and
27 * a quit signal will generate a core dump.
30 /* Tweak debug output verbosity here */
37 #define JOBS ENABLE_ASH_JOB_CONTROL
39 #include "busybox.h" /* for applet_names */
43 #include <sys/times.h>
45 #include "shell_common.h"
47 #if ENABLE_ASH_RANDOM_SUPPORT
50 # define CLEAR_RANDOM_T(rnd) ((void)0)
53 #include "NUM_APPLETS.h"
55 /* STANDALONE does not make sense, and won't compile */
56 # undef CONFIG_FEATURE_SH_STANDALONE
57 # undef ENABLE_FEATURE_SH_STANDALONE
58 # undef IF_FEATURE_SH_STANDALONE
59 # undef IF_NOT_FEATURE_SH_STANDALONE
60 # define ENABLE_FEATURE_SH_STANDALONE 0
61 # define IF_FEATURE_SH_STANDALONE(...)
62 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
66 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
70 # error "Do not even bother, ash will not run on NOMMU machine"
74 /* ============ Hash table sizes. Configurable. */
78 #define CMDTABLESIZE 31 /* should be prime */
81 /* ============ Shell options */
83 static const char *const optletters_optnames[] = {
98 #if ENABLE_ASH_BASH_COMPAT
107 #define optletters(n) optletters_optnames[n][0]
108 #define optnames(n) (optletters_optnames[n] + 1)
110 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
113 /* ============ Misc data */
115 #define msg_illnum "Illegal number: %s"
118 * We enclose jmp_buf in a structure so that we can declare pointers to
119 * jump locations. The global variable handler contains the location to
120 * jump to when an exception occurs, and the global variable exception_type
121 * contains a code identifying the exception. To implement nested
122 * exception handlers, the user should save the value of handler on entry
123 * to an inner scope, set handler to point to a jmploc structure for the
124 * inner scope, and restore handler on exit from the scope.
130 struct globals_misc {
131 /* pid of main shell */
133 /* shell level: 0 for the main shell, 1 for its children, and so on */
135 #define rootshell (!shlvl)
136 char *minusc; /* argument to -c option */
138 char *curdir; // = nullstr; /* current working directory */
139 char *physdir; // = nullstr; /* physical working directory */
141 char *arg0; /* value of $0 */
143 struct jmploc *exception_handler;
145 volatile int suppress_int; /* counter */
146 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
147 /* last pending signal */
148 volatile /*sig_atomic_t*/ smallint pending_sig;
149 smallint exception_type; /* kind of exception (0..5) */
151 #define EXINT 0 /* SIGINT received */
152 #define EXERROR 1 /* a generic error */
153 #define EXSHELLPROC 2 /* execute a shell procedure */
154 #define EXEXEC 3 /* command execution failed */
155 #define EXEXIT 4 /* exit the shell */
156 #define EXSIG 5 /* trapped signal in wait(1) */
159 char nullstr[1]; /* zero length string */
162 #define eflag optlist[0]
163 #define fflag optlist[1]
164 #define Iflag optlist[2]
165 #define iflag optlist[3]
166 #define mflag optlist[4]
167 #define nflag optlist[5]
168 #define sflag optlist[6]
169 #define xflag optlist[7]
170 #define vflag optlist[8]
171 #define Cflag optlist[9]
172 #define aflag optlist[10]
173 #define bflag optlist[11]
174 #define uflag optlist[12]
175 #define viflag optlist[13]
176 #if ENABLE_ASH_BASH_COMPAT
177 # define pipefail optlist[14]
182 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
183 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
186 /* trap handler commands */
188 * Sigmode records the current value of the signal handlers for the various
189 * modes. A value of zero means that the current handler is not known.
190 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
192 char sigmode[NSIG - 1];
193 #define S_DFL 1 /* default signal handling (SIG_DFL) */
194 #define S_CATCH 2 /* signal is caught */
195 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
196 #define S_HARD_IGN 4 /* signal is ignored permenantly */
198 /* indicates specified signal received */
199 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
200 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
202 char **trap_ptr; /* used only by "trap hack" */
204 /* Rarely referenced stuff */
205 #if ENABLE_ASH_RANDOM_SUPPORT
208 pid_t backgndpid; /* pid of last background process */
209 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
211 extern struct globals_misc *const ash_ptr_to_globals_misc;
212 #define G_misc (*ash_ptr_to_globals_misc)
213 #define rootpid (G_misc.rootpid )
214 #define shlvl (G_misc.shlvl )
215 #define minusc (G_misc.minusc )
216 #define curdir (G_misc.curdir )
217 #define physdir (G_misc.physdir )
218 #define arg0 (G_misc.arg0 )
219 #define exception_handler (G_misc.exception_handler)
220 #define exception_type (G_misc.exception_type )
221 #define suppress_int (G_misc.suppress_int )
222 #define pending_int (G_misc.pending_int )
223 #define pending_sig (G_misc.pending_sig )
224 #define isloginsh (G_misc.isloginsh )
225 #define nullstr (G_misc.nullstr )
226 #define optlist (G_misc.optlist )
227 #define sigmode (G_misc.sigmode )
228 #define gotsig (G_misc.gotsig )
229 #define may_have_traps (G_misc.may_have_traps )
230 #define trap (G_misc.trap )
231 #define trap_ptr (G_misc.trap_ptr )
232 #define random_gen (G_misc.random_gen )
233 #define backgndpid (G_misc.backgndpid )
234 #define job_warning (G_misc.job_warning)
235 #define INIT_G_misc() do { \
236 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
244 /* ============ DEBUG */
246 static void trace_printf(const char *fmt, ...);
247 static void trace_vprintf(const char *fmt, va_list va);
248 # define TRACE(param) trace_printf param
249 # define TRACEV(param) trace_vprintf param
250 # define close(fd) do { \
252 if (close(dfd) < 0) \
253 bb_error_msg("bug on %d: closing %d(0x%x)", \
254 __LINE__, dfd, dfd); \
257 # define TRACE(param)
258 # define TRACEV(param)
262 /* ============ Utility functions */
263 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
265 static int isdigit_str9(const char *str)
267 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
268 while (--maxlen && isdigit(*str))
270 return (*str == '\0');
273 static const char *var_end(const char *var)
282 /* ============ Interrupts / exceptions */
284 * These macros allow the user to suspend the handling of interrupt signals
285 * over a period of time. This is similar to SIGHOLD or to sigblock, but
286 * much more efficient and portable. (But hacking the kernel is so much
287 * more fun than worrying about efficiency and portability. :-))
289 #define INT_OFF do { \
295 * Called to raise an exception. Since C doesn't include exceptions, we
296 * just do a longjmp to the exception handler. The type of exception is
297 * stored in the global variable "exception_type".
299 static void raise_exception(int) NORETURN;
301 raise_exception(int e)
304 if (exception_handler == NULL)
309 longjmp(exception_handler->loc, 1);
312 #define raise_exception(e) do { \
313 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
314 raise_exception(e); \
319 * Called from trap.c when a SIGINT is received. (If the user specifies
320 * that SIGINT is to be trapped or ignored using the trap builtin, then
321 * this routine is not called.) Suppressint is nonzero when interrupts
322 * are held using the INT_OFF macro. (The test for iflag is just
323 * defensive programming.)
325 static void raise_interrupt(void) NORETURN;
327 raise_interrupt(void)
332 /* Signal is not automatically unmasked after it is raised,
333 * do it ourself - unmask all signals */
334 sigprocmask_allsigs(SIG_UNBLOCK);
335 /* pending_sig = 0; - now done in signal_handler() */
338 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
339 if (!(rootshell && iflag)) {
340 /* Kill ourself with SIGINT */
341 signal(SIGINT, SIG_DFL);
346 raise_exception(ex_type);
350 #define raise_interrupt() do { \
351 TRACE(("raising interrupt on line %d\n", __LINE__)); \
356 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
360 if (--suppress_int == 0 && pending_int) {
364 #define INT_ON int_on()
365 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
373 #define FORCE_INT_ON force_int_on()
375 #define SAVE_INT(v) ((v) = suppress_int)
377 #define RESTORE_INT(v) do { \
379 suppress_int = (v); \
380 if (suppress_int == 0 && pending_int) \
385 /* ============ Stdout/stderr output */
388 outstr(const char *p, FILE *file)
396 flush_stdout_stderr(void)
404 outcslow(int c, FILE *dest)
412 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
414 out1fmt(const char *fmt, ...)
421 r = vprintf(fmt, ap);
427 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
429 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
436 ret = vsnprintf(outbuf, length, fmt, ap);
443 out1str(const char *p)
449 out2str(const char *p)
452 flush_stdout_stderr();
456 /* ============ Parser structures */
458 /* control characters in argument strings */
459 #define CTL_FIRST CTLESC
460 #define CTLESC ((unsigned char)'\201') /* escape next character */
461 #define CTLVAR ((unsigned char)'\202') /* variable defn */
462 #define CTLENDVAR ((unsigned char)'\203')
463 #define CTLBACKQ ((unsigned char)'\204')
464 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
465 /* CTLBACKQ | CTLQUOTE == '\205' */
466 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
467 #define CTLENDARI ((unsigned char)'\207')
468 #define CTLQUOTEMARK ((unsigned char)'\210')
469 #define CTL_LAST CTLQUOTEMARK
471 /* variable substitution byte (follows CTLVAR) */
472 #define VSTYPE 0x0f /* type of variable substitution */
473 #define VSNUL 0x10 /* colon--treat the empty string as unset */
474 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
476 /* values of VSTYPE field */
477 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
478 #define VSMINUS 0x2 /* ${var-text} */
479 #define VSPLUS 0x3 /* ${var+text} */
480 #define VSQUESTION 0x4 /* ${var?message} */
481 #define VSASSIGN 0x5 /* ${var=text} */
482 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
483 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
484 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
485 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
486 #define VSLENGTH 0xa /* ${#var} */
487 #if ENABLE_ASH_BASH_COMPAT
488 #define VSSUBSTR 0xc /* ${var:position:length} */
489 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
490 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
493 static const char dolatstr[] ALIGN1 = {
494 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
514 #if ENABLE_ASH_BASH_COMPAT
531 smallint type; /* Nxxxx */
534 union node *redirect;
539 smallint pipe_backgnd;
540 struct nodelist *cmdlist;
546 union node *redirect;
559 union node *elsepart;
586 struct nodelist *backquote;
589 /* nfile and ndup layout must match!
590 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
591 * that it is actually NTO2 (>&file), and change its type.
608 char *_unused_expfname;
627 struct nredir nredir;
628 struct nbinary nbinary;
632 struct nclist nclist;
641 * NODE_EOF is returned by parsecmd when it encounters an end of file.
642 * It must be distinct from NULL.
644 #define NODE_EOF ((union node *) -1L)
647 struct nodelist *next;
660 freefunc(struct funcnode *f)
662 if (f && --f->count < 0)
667 /* ============ Debugging output */
671 static FILE *tracefile;
674 trace_printf(const char *fmt, ...)
681 fprintf(tracefile, "%u ", (int) time(NULL));
683 fprintf(tracefile, "[%u] ", (int) getpid());
685 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
687 vfprintf(tracefile, fmt, va);
692 trace_vprintf(const char *fmt, va_list va)
697 fprintf(tracefile, "%u ", (int) time(NULL));
699 fprintf(tracefile, "[%u] ", (int) getpid());
701 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
702 vfprintf(tracefile, fmt, va);
706 trace_puts(const char *s)
714 trace_puts_quoted(char *s)
721 putc('"', tracefile);
722 for (p = s; *p; p++) {
723 switch ((unsigned char)*p) {
724 case '\n': c = 'n'; goto backslash;
725 case '\t': c = 't'; goto backslash;
726 case '\r': c = 'r'; goto backslash;
727 case '\"': c = '\"'; goto backslash;
728 case '\\': c = '\\'; goto backslash;
729 case CTLESC: c = 'e'; goto backslash;
730 case CTLVAR: c = 'v'; goto backslash;
731 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
732 case CTLBACKQ: c = 'q'; goto backslash;
733 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
735 putc('\\', tracefile);
739 if (*p >= ' ' && *p <= '~')
742 putc('\\', tracefile);
743 putc((*p >> 6) & 03, tracefile);
744 putc((*p >> 3) & 07, tracefile);
745 putc(*p & 07, tracefile);
750 putc('"', tracefile);
754 trace_puts_args(char **ap)
761 trace_puts_quoted(*ap);
763 putc('\n', tracefile);
766 putc(' ', tracefile);
781 /* leave open because libedit might be using it */
784 strcpy(s, "./trace");
786 if (!freopen(s, "a", tracefile)) {
787 fprintf(stderr, "Can't re-open %s\n", s);
792 tracefile = fopen(s, "a");
793 if (tracefile == NULL) {
794 fprintf(stderr, "Can't open %s\n", s);
800 flags = fcntl(fileno(tracefile), F_GETFL);
802 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
804 setlinebuf(tracefile);
805 fputs("\nTracing started.\n", tracefile);
809 indent(int amount, char *pfx, FILE *fp)
813 for (i = 0; i < amount; i++) {
814 if (pfx && i == amount - 1)
820 /* little circular references here... */
821 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
824 sharg(union node *arg, FILE *fp)
827 struct nodelist *bqlist;
828 unsigned char subtype;
830 if (arg->type != NARG) {
831 out1fmt("<node type %d>\n", arg->type);
834 bqlist = arg->narg.backquote;
835 for (p = arg->narg.text; *p; p++) {
836 switch ((unsigned char)*p) {
844 if (subtype == VSLENGTH)
853 switch (subtype & VSTYPE) {
886 out1fmt("<subtype %d>", subtype);
893 case CTLBACKQ|CTLQUOTE:
896 shtree(bqlist->n, -1, NULL, fp);
907 shcmd(union node *cmd, FILE *fp)
915 for (np = cmd->ncmd.args; np; np = np->narg.next) {
921 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
925 switch (np->nfile.type) {
926 case NTO: s = ">>"+1; dftfd = 1; break;
927 case NCLOBBER: s = ">|"; dftfd = 1; break;
928 case NAPPEND: s = ">>"; dftfd = 1; break;
929 #if ENABLE_ASH_BASH_COMPAT
932 case NTOFD: s = ">&"; dftfd = 1; break;
933 case NFROM: s = "<"; break;
934 case NFROMFD: s = "<&"; break;
935 case NFROMTO: s = "<>"; break;
936 default: s = "*error*"; break;
938 if (np->nfile.fd != dftfd)
939 fprintf(fp, "%d", np->nfile.fd);
941 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
942 fprintf(fp, "%d", np->ndup.dupfd);
944 sharg(np->nfile.fname, fp);
951 shtree(union node *n, int ind, char *pfx, FILE *fp)
959 indent(ind, pfx, fp);
976 shtree(n->nbinary.ch1, ind, NULL, fp);
979 shtree(n->nbinary.ch2, ind, NULL, fp);
987 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
988 shtree(lp->n, 0, NULL, fp);
992 if (n->npipe.pipe_backgnd)
998 fprintf(fp, "<node type %d>", n->type);
1006 showtree(union node *n)
1008 trace_puts("showtree called\n");
1009 shtree(n, 1, NULL, stderr);
1015 /* ============ Parser data */
1018 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1021 struct strlist *next;
1028 struct strpush *prev; /* preceding string on stack */
1030 int prev_left_in_line;
1031 #if ENABLE_ASH_ALIAS
1032 struct alias *ap; /* if push was associated with an alias */
1034 char *string; /* remember the string since it may change */
1038 struct parsefile *prev; /* preceding file on stack */
1039 int linno; /* current line */
1040 int pf_fd; /* file descriptor (or -1 if string) */
1041 int left_in_line; /* number of chars left in this line */
1042 int left_in_buffer; /* number of chars left in this buffer past the line */
1043 char *next_to_pgetc; /* next char in buffer */
1044 char *buf; /* input buffer */
1045 struct strpush *strpush; /* for pushing strings at this level */
1046 struct strpush basestrpush; /* so pushing one is fast */
1049 static struct parsefile basepf; /* top level input file */
1050 static struct parsefile *g_parsefile = &basepf; /* current input file */
1051 static int startlinno; /* line # where last token started */
1052 static char *commandname; /* currently executing command */
1053 static struct strlist *cmdenviron; /* environment for builtin command */
1054 static uint8_t exitstatus; /* exit status of last command */
1057 /* ============ Message printing */
1060 ash_vmsg(const char *msg, va_list ap)
1062 fprintf(stderr, "%s: ", arg0);
1064 if (strcmp(arg0, commandname))
1065 fprintf(stderr, "%s: ", commandname);
1066 if (!iflag || g_parsefile->pf_fd > 0)
1067 fprintf(stderr, "line %d: ", startlinno);
1069 vfprintf(stderr, msg, ap);
1070 outcslow('\n', stderr);
1074 * Exverror is called to raise the error exception. If the second argument
1075 * is not NULL then error prints an error message using printf style
1076 * formatting. It then raises the error exception.
1078 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1080 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1084 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1086 TRACE(("\") pid=%d\n", getpid()));
1088 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1093 flush_stdout_stderr();
1094 raise_exception(cond);
1098 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1100 ash_msg_and_raise_error(const char *msg, ...)
1105 ash_vmsg_and_raise(EXERROR, msg, ap);
1110 static void raise_error_syntax(const char *) NORETURN;
1112 raise_error_syntax(const char *msg)
1114 ash_msg_and_raise_error("syntax error: %s", msg);
1118 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1120 ash_msg_and_raise(int cond, const char *msg, ...)
1125 ash_vmsg_and_raise(cond, msg, ap);
1131 * error/warning routines for external builtins
1134 ash_msg(const char *fmt, ...)
1144 * Return a string describing an error. The returned string may be a
1145 * pointer to a static buffer that will be overwritten on the next call.
1146 * Action describes the operation that got the error.
1149 errmsg(int e, const char *em)
1151 if (e == ENOENT || e == ENOTDIR) {
1158 /* ============ Memory allocation */
1161 /* I consider these wrappers nearly useless:
1162 * ok, they return you to nearest exception handler, but
1163 * how much memory do you leak in the process, making
1164 * memory starvation worse?
1167 ckrealloc(void * p, size_t nbytes)
1169 p = realloc(p, nbytes);
1171 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1176 ckmalloc(size_t nbytes)
1178 return ckrealloc(NULL, nbytes);
1182 ckzalloc(size_t nbytes)
1184 return memset(ckmalloc(nbytes), 0, nbytes);
1188 ckstrdup(const char *s)
1190 char *p = strdup(s);
1192 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1196 /* Using bbox equivalents. They exit if out of memory */
1197 # define ckrealloc xrealloc
1198 # define ckmalloc xmalloc
1199 # define ckzalloc xzalloc
1200 # define ckstrdup xstrdup
1204 * It appears that grabstackstr() will barf with such alignments
1205 * because stalloc() will return a string allocated in a new stackblock.
1207 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1209 /* Most machines require the value returned from malloc to be aligned
1210 * in some way. The following macro will get this right
1211 * on many machines. */
1212 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1213 /* Minimum size of a block */
1214 MINSIZE = SHELL_ALIGN(504),
1217 struct stack_block {
1218 struct stack_block *prev;
1219 char space[MINSIZE];
1223 struct stack_block *stackp;
1226 struct stackmark *marknext;
1230 struct globals_memstack {
1231 struct stack_block *g_stackp; // = &stackbase;
1232 struct stackmark *markp;
1233 char *g_stacknxt; // = stackbase.space;
1234 char *sstrend; // = stackbase.space + MINSIZE;
1235 size_t g_stacknleft; // = MINSIZE;
1236 int herefd; // = -1;
1237 struct stack_block stackbase;
1239 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1240 #define G_memstack (*ash_ptr_to_globals_memstack)
1241 #define g_stackp (G_memstack.g_stackp )
1242 #define markp (G_memstack.markp )
1243 #define g_stacknxt (G_memstack.g_stacknxt )
1244 #define sstrend (G_memstack.sstrend )
1245 #define g_stacknleft (G_memstack.g_stacknleft)
1246 #define herefd (G_memstack.herefd )
1247 #define stackbase (G_memstack.stackbase )
1248 #define INIT_G_memstack() do { \
1249 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1251 g_stackp = &stackbase; \
1252 g_stacknxt = stackbase.space; \
1253 g_stacknleft = MINSIZE; \
1254 sstrend = stackbase.space + MINSIZE; \
1259 #define stackblock() ((void *)g_stacknxt)
1260 #define stackblocksize() g_stacknleft
1263 * Parse trees for commands are allocated in lifo order, so we use a stack
1264 * to make this more efficient, and also to avoid all sorts of exception
1265 * handling code to handle interrupts in the middle of a parse.
1267 * The size 504 was chosen because the Ultrix malloc handles that size
1271 stalloc(size_t nbytes)
1276 aligned = SHELL_ALIGN(nbytes);
1277 if (aligned > g_stacknleft) {
1280 struct stack_block *sp;
1282 blocksize = aligned;
1283 if (blocksize < MINSIZE)
1284 blocksize = MINSIZE;
1285 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1286 if (len < blocksize)
1287 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1290 sp->prev = g_stackp;
1291 g_stacknxt = sp->space;
1292 g_stacknleft = blocksize;
1293 sstrend = g_stacknxt + blocksize;
1298 g_stacknxt += aligned;
1299 g_stacknleft -= aligned;
1304 stzalloc(size_t nbytes)
1306 return memset(stalloc(nbytes), 0, nbytes);
1313 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1314 write(STDERR_FILENO, "stunalloc\n", 10);
1318 g_stacknleft += g_stacknxt - (char *)p;
1323 * Like strdup but works with the ash stack.
1326 ststrdup(const char *p)
1328 size_t len = strlen(p) + 1;
1329 return memcpy(stalloc(len), p, len);
1333 setstackmark(struct stackmark *mark)
1335 mark->stackp = g_stackp;
1336 mark->stacknxt = g_stacknxt;
1337 mark->stacknleft = g_stacknleft;
1338 mark->marknext = markp;
1343 popstackmark(struct stackmark *mark)
1345 struct stack_block *sp;
1351 markp = mark->marknext;
1352 while (g_stackp != mark->stackp) {
1354 g_stackp = sp->prev;
1357 g_stacknxt = mark->stacknxt;
1358 g_stacknleft = mark->stacknleft;
1359 sstrend = mark->stacknxt + mark->stacknleft;
1364 * When the parser reads in a string, it wants to stick the string on the
1365 * stack and only adjust the stack pointer when it knows how big the
1366 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1367 * of space on top of the stack and stackblocklen returns the length of
1368 * this block. Growstackblock will grow this space by at least one byte,
1369 * possibly moving it (like realloc). Grabstackblock actually allocates the
1370 * part of the block that has been used.
1373 growstackblock(void)
1377 newlen = g_stacknleft * 2;
1378 if (newlen < g_stacknleft)
1379 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1383 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1384 struct stack_block *oldstackp;
1385 struct stackmark *xmark;
1386 struct stack_block *sp;
1387 struct stack_block *prevstackp;
1391 oldstackp = g_stackp;
1393 prevstackp = sp->prev;
1394 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1395 sp = ckrealloc(sp, grosslen);
1396 sp->prev = prevstackp;
1398 g_stacknxt = sp->space;
1399 g_stacknleft = newlen;
1400 sstrend = sp->space + newlen;
1403 * Stack marks pointing to the start of the old block
1404 * must be relocated to point to the new block
1407 while (xmark != NULL && xmark->stackp == oldstackp) {
1408 xmark->stackp = g_stackp;
1409 xmark->stacknxt = g_stacknxt;
1410 xmark->stacknleft = g_stacknleft;
1411 xmark = xmark->marknext;
1415 char *oldspace = g_stacknxt;
1416 size_t oldlen = g_stacknleft;
1417 char *p = stalloc(newlen);
1419 /* free the space we just allocated */
1420 g_stacknxt = memcpy(p, oldspace, oldlen);
1421 g_stacknleft += newlen;
1426 grabstackblock(size_t len)
1428 len = SHELL_ALIGN(len);
1430 g_stacknleft -= len;
1434 * The following routines are somewhat easier to use than the above.
1435 * The user declares a variable of type STACKSTR, which may be declared
1436 * to be a register. The macro STARTSTACKSTR initializes things. Then
1437 * the user uses the macro STPUTC to add characters to the string. In
1438 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1439 * grown as necessary. When the user is done, she can just leave the
1440 * string there and refer to it using stackblock(). Or she can allocate
1441 * the space for it using grabstackstr(). If it is necessary to allow
1442 * someone else to use the stack temporarily and then continue to grow
1443 * the string, the user should use grabstack to allocate the space, and
1444 * then call ungrabstr(p) to return to the previous mode of operation.
1446 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1447 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1448 * is space for at least one character.
1453 size_t len = stackblocksize();
1454 if (herefd >= 0 && len >= 1024) {
1455 full_write(herefd, stackblock(), len);
1456 return stackblock();
1459 return (char *)stackblock() + len;
1463 * Called from CHECKSTRSPACE.
1466 makestrspace(size_t newlen, char *p)
1468 size_t len = p - g_stacknxt;
1469 size_t size = stackblocksize();
1474 size = stackblocksize();
1476 if (nleft >= newlen)
1480 return (char *)stackblock() + len;
1484 stack_nputstr(const char *s, size_t n, char *p)
1486 p = makestrspace(n, p);
1487 p = (char *)memcpy(p, s, n) + n;
1492 stack_putstr(const char *s, char *p)
1494 return stack_nputstr(s, strlen(s), p);
1498 _STPUTC(int c, char *p)
1506 #define STARTSTACKSTR(p) ((p) = stackblock())
1507 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1508 #define CHECKSTRSPACE(n, p) do { \
1511 size_t m = sstrend - q; \
1513 (p) = makestrspace(l, q); \
1515 #define USTPUTC(c, p) (*(p)++ = (c))
1516 #define STACKSTRNUL(p) do { \
1517 if ((p) == sstrend) \
1518 (p) = growstackstr(); \
1521 #define STUNPUTC(p) (--(p))
1522 #define STTOPC(p) ((p)[-1])
1523 #define STADJUST(amount, p) ((p) += (amount))
1525 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1526 #define ungrabstackstr(s, p) stunalloc(s)
1527 #define stackstrend() ((void *)sstrend)
1530 /* ============ String helpers */
1533 * prefix -- see if pfx is a prefix of string.
1536 prefix(const char *string, const char *pfx)
1539 if (*pfx++ != *string++)
1542 return (char *) string;
1546 * Check for a valid number. This should be elsewhere.
1549 is_number(const char *p)
1554 } while (*++p != '\0');
1559 * Convert a string of digits to an integer, printing an error message on
1563 number(const char *s)
1566 ash_msg_and_raise_error(msg_illnum, s);
1571 * Produce a possibly single quoted string suitable as input to the shell.
1572 * The return string is allocated on the stack.
1575 single_quote(const char *s)
1585 len = strchrnul(s, '\'') - s;
1587 q = p = makestrspace(len + 3, p);
1590 q = (char *)memcpy(q, s, len) + len;
1599 do len++; while (*++s == '\'');
1601 q = p = makestrspace(len + 3, p);
1604 q = (char *)memcpy(q, s - len, len) + len;
1612 return stackblock();
1616 /* ============ nextopt */
1618 static char **argptr; /* argument list for builtin commands */
1619 static char *optionarg; /* set by nextopt (like getopt) */
1620 static char *optptr; /* used by nextopt */
1623 * XXX - should get rid of. Have all builtins use getopt(3).
1624 * The library getopt must have the BSD extension static variable
1625 * "optreset", otherwise it can't be used within the shell safely.
1627 * Standard option processing (a la getopt) for builtin routines.
1628 * The only argument that is passed to nextopt is the option string;
1629 * the other arguments are unnecessary. It returns the character,
1630 * or '\0' on end of input.
1633 nextopt(const char *optstring)
1640 if (p == NULL || *p == '\0') {
1641 /* We ate entire "-param", take next one */
1647 if (*++p == '\0') /* just "-" ? */
1650 if (LONE_DASH(p)) /* "--" ? */
1652 /* p => next "-param" */
1654 /* p => some option char in the middle of a "-param" */
1656 for (q = optstring; *q != c;) {
1658 ash_msg_and_raise_error("illegal option -%c", c);
1666 ash_msg_and_raise_error("no arg for -%c option", c);
1676 /* ============ Shell variables */
1679 * The parsefile structure pointed to by the global variable parsefile
1680 * contains information about the current file being read.
1683 int nparam; /* # of positional parameters (without $0) */
1684 #if ENABLE_ASH_GETOPTS
1685 int optind; /* next parameter to be processed by getopts */
1686 int optoff; /* used by getopts */
1688 unsigned char malloced; /* if parameter list dynamically allocated */
1689 char **p; /* parameter list */
1693 * Free the list of positional parameters.
1696 freeparam(volatile struct shparam *param)
1698 if (param->malloced) {
1700 ap = ap1 = param->p;
1707 #if ENABLE_ASH_GETOPTS
1708 static void FAST_FUNC getoptsreset(const char *value);
1712 struct var *next; /* next entry in hash list */
1713 int flags; /* flags are defined above */
1714 const char *var_text; /* name=value */
1715 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1716 /* the variable gets set/unset */
1720 struct localvar *next; /* next local variable in list */
1721 struct var *vp; /* the variable that was made local */
1722 int flags; /* saved flags */
1723 const char *text; /* saved text */
1727 #define VEXPORT 0x01 /* variable is exported */
1728 #define VREADONLY 0x02 /* variable cannot be modified */
1729 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1730 #define VTEXTFIXED 0x08 /* text is statically allocated */
1731 #define VSTACK 0x10 /* text is allocated on the stack */
1732 #define VUNSET 0x20 /* the variable is not set */
1733 #define VNOFUNC 0x40 /* don't call the callback function */
1734 #define VNOSET 0x80 /* do not set variable - just readonly test */
1735 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1736 #if ENABLE_ASH_RANDOM_SUPPORT
1737 # define VDYNAMIC 0x200 /* dynamic variable */
1743 /* Need to be before varinit_data[] */
1744 #if ENABLE_LOCALE_SUPPORT
1745 static void FAST_FUNC
1746 change_lc_all(const char *value)
1748 if (value && *value != '\0')
1749 setlocale(LC_ALL, value);
1751 static void FAST_FUNC
1752 change_lc_ctype(const char *value)
1754 if (value && *value != '\0')
1755 setlocale(LC_CTYPE, value);
1759 static void chkmail(void);
1760 static void changemail(const char *) FAST_FUNC;
1762 static void changepath(const char *) FAST_FUNC;
1763 #if ENABLE_ASH_RANDOM_SUPPORT
1764 static void change_random(const char *) FAST_FUNC;
1767 static const struct {
1769 const char *var_text;
1770 void (*var_func)(const char *) FAST_FUNC;
1771 } varinit_data[] = {
1772 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1774 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1775 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1777 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1778 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1779 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1780 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1781 #if ENABLE_ASH_GETOPTS
1782 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1784 #if ENABLE_ASH_RANDOM_SUPPORT
1785 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1787 #if ENABLE_LOCALE_SUPPORT
1788 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1789 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1791 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1792 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1798 struct globals_var {
1799 struct shparam shellparam; /* $@ current positional parameters */
1800 struct redirtab *redirlist;
1802 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1803 struct var *vartab[VTABSIZE];
1804 struct var varinit[ARRAY_SIZE(varinit_data)];
1806 extern struct globals_var *const ash_ptr_to_globals_var;
1807 #define G_var (*ash_ptr_to_globals_var)
1808 #define shellparam (G_var.shellparam )
1809 //#define redirlist (G_var.redirlist )
1810 #define g_nullredirs (G_var.g_nullredirs )
1811 #define preverrout_fd (G_var.preverrout_fd)
1812 #define vartab (G_var.vartab )
1813 #define varinit (G_var.varinit )
1814 #define INIT_G_var() do { \
1816 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1818 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1819 varinit[i].flags = varinit_data[i].flags; \
1820 varinit[i].var_text = varinit_data[i].var_text; \
1821 varinit[i].var_func = varinit_data[i].var_func; \
1825 #define vifs varinit[0]
1827 # define vmail (&vifs)[1]
1828 # define vmpath (&vmail)[1]
1829 # define vpath (&vmpath)[1]
1831 # define vpath (&vifs)[1]
1833 #define vps1 (&vpath)[1]
1834 #define vps2 (&vps1)[1]
1835 #define vps4 (&vps2)[1]
1836 #if ENABLE_ASH_GETOPTS
1837 # define voptind (&vps4)[1]
1838 # if ENABLE_ASH_RANDOM_SUPPORT
1839 # define vrandom (&voptind)[1]
1842 # if ENABLE_ASH_RANDOM_SUPPORT
1843 # define vrandom (&vps4)[1]
1848 * The following macros access the values of the above variables.
1849 * They have to skip over the name. They return the null string
1850 * for unset variables.
1852 #define ifsval() (vifs.var_text + 4)
1853 #define ifsset() ((vifs.flags & VUNSET) == 0)
1855 # define mailval() (vmail.var_text + 5)
1856 # define mpathval() (vmpath.var_text + 9)
1857 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1859 #define pathval() (vpath.var_text + 5)
1860 #define ps1val() (vps1.var_text + 4)
1861 #define ps2val() (vps2.var_text + 4)
1862 #define ps4val() (vps4.var_text + 4)
1863 #if ENABLE_ASH_GETOPTS
1864 # define optindval() (voptind.var_text + 7)
1868 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1869 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1871 #if ENABLE_ASH_GETOPTS
1872 static void FAST_FUNC
1873 getoptsreset(const char *value)
1875 shellparam.optind = number(value);
1876 shellparam.optoff = -1;
1881 * Return of a legal variable name (a letter or underscore followed by zero or
1882 * more letters, underscores, and digits).
1884 static char* FAST_FUNC
1885 endofname(const char *name)
1893 if (!is_in_name(*p))
1900 * Compares two strings up to the first = or '\0'. The first
1901 * string must be terminated by '='; the second may be terminated by
1902 * either '=' or '\0'.
1905 varcmp(const char *p, const char *q)
1909 while ((c = *p) == (d = *q)) {
1924 * Find the appropriate entry in the hash table from the name.
1926 static struct var **
1927 hashvar(const char *p)
1931 hashval = ((unsigned char) *p) << 4;
1932 while (*p && *p != '=')
1933 hashval += (unsigned char) *p++;
1934 return &vartab[hashval % VTABSIZE];
1938 vpcmp(const void *a, const void *b)
1940 return varcmp(*(const char **)a, *(const char **)b);
1944 * This routine initializes the builtin variables.
1954 * PS1 depends on uid
1956 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1957 vps1.var_text = "PS1=\\w \\$ ";
1960 vps1.var_text = "PS1=# ";
1963 end = vp + ARRAY_SIZE(varinit);
1965 vpp = hashvar(vp->var_text);
1968 } while (++vp < end);
1971 static struct var **
1972 findvar(struct var **vpp, const char *name)
1974 for (; *vpp; vpp = &(*vpp)->next) {
1975 if (varcmp((*vpp)->var_text, name) == 0) {
1983 * Find the value of a variable. Returns NULL if not set.
1985 static const char* FAST_FUNC
1986 lookupvar(const char *name)
1990 v = *findvar(hashvar(name), name);
1992 #if ENABLE_ASH_RANDOM_SUPPORT
1994 * Dynamic variables are implemented roughly the same way they are
1995 * in bash. Namely, they're "special" so long as they aren't unset.
1996 * As soon as they're unset, they're no longer dynamic, and dynamic
1997 * lookup will no longer happen at that point. -- PFM.
1999 if (v->flags & VDYNAMIC)
2002 if (!(v->flags & VUNSET))
2003 return var_end(v->var_text);
2009 * Search the environment of a builtin command.
2012 bltinlookup(const char *name)
2016 for (sp = cmdenviron; sp; sp = sp->next) {
2017 if (varcmp(sp->text, name) == 0)
2018 return var_end(sp->text);
2020 return lookupvar(name);
2024 * Same as setvar except that the variable and value are passed in
2025 * the first argument as name=value. Since the first argument will
2026 * be actually stored in the table, it should not be a string that
2028 * Called with interrupts off.
2031 setvareq(char *s, int flags)
2033 struct var *vp, **vpp;
2036 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2037 vp = *findvar(vpp, s);
2039 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2042 if (flags & VNOSAVE)
2045 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2051 if (vp->var_func && !(flags & VNOFUNC))
2052 vp->var_func(var_end(s));
2054 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2055 free((char*)vp->var_text);
2057 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2059 /* variable s is not found */
2062 vp = ckzalloc(sizeof(*vp));
2064 /*vp->func = NULL; - ckzalloc did it */
2067 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2074 * Set the value of a variable. The flags argument is ored with the
2075 * flags of the variable. If val is NULL, the variable is unset.
2078 setvar(const char *name, const char *val, int flags)
2085 q = endofname(name);
2086 p = strchrnul(q, '=');
2088 if (!namelen || p != q)
2089 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2094 vallen = strlen(val);
2097 nameeq = ckmalloc(namelen + vallen + 2);
2098 p = (char *)memcpy(nameeq, name, namelen) + namelen;
2101 p = (char *)memcpy(p, val, vallen) + vallen;
2104 setvareq(nameeq, flags | VNOSAVE);
2108 static void FAST_FUNC
2109 setvar2(const char *name, const char *val)
2111 setvar(name, val, 0);
2114 #if ENABLE_ASH_GETOPTS
2116 * Safe version of setvar, returns 1 on success 0 on failure.
2119 setvarsafe(const char *name, const char *val, int flags)
2122 volatile int saveint;
2123 struct jmploc *volatile savehandler = exception_handler;
2124 struct jmploc jmploc;
2127 if (setjmp(jmploc.loc))
2130 exception_handler = &jmploc;
2131 setvar(name, val, flags);
2134 exception_handler = savehandler;
2135 RESTORE_INT(saveint);
2141 * Unset the specified variable.
2144 unsetvar(const char *s)
2150 vpp = findvar(hashvar(s), s);
2154 int flags = vp->flags;
2157 if (flags & VREADONLY)
2159 #if ENABLE_ASH_RANDOM_SUPPORT
2160 vp->flags &= ~VDYNAMIC;
2164 if ((flags & VSTRFIXED) == 0) {
2166 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2167 free((char*)vp->var_text);
2173 vp->flags &= ~VEXPORT;
2183 * Process a linked list of variable assignments.
2186 listsetvar(struct strlist *list_set_var, int flags)
2188 struct strlist *lp = list_set_var;
2194 setvareq(lp->text, flags);
2201 * Generate a list of variables satisfying the given conditions.
2204 listvars(int on, int off, char ***end)
2215 for (vp = *vpp; vp; vp = vp->next) {
2216 if ((vp->flags & mask) == on) {
2217 if (ep == stackstrend())
2218 ep = growstackstr();
2219 *ep++ = (char*)vp->var_text;
2222 } while (++vpp < vartab + VTABSIZE);
2223 if (ep == stackstrend())
2224 ep = growstackstr();
2228 return grabstackstr(ep);
2232 /* ============ Path search helper
2234 * The variable path (passed by reference) should be set to the start
2235 * of the path before the first call; path_advance will update
2236 * this value as it proceeds. Successive calls to path_advance will return
2237 * the possible path expansions in sequence. If an option (indicated by
2238 * a percent sign) appears in the path entry then the global variable
2239 * pathopt will be set to point to it; otherwise pathopt will be set to
2242 static const char *pathopt; /* set by path_advance */
2245 path_advance(const char **path, const char *name)
2255 for (p = start; *p && *p != ':' && *p != '%'; p++)
2257 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2258 while (stackblocksize() < len)
2262 memcpy(q, start, p - start);
2270 while (*p && *p != ':')
2277 return stalloc(len);
2281 /* ============ Prompt */
2283 static smallint doprompt; /* if set, prompt the user */
2284 static smallint needprompt; /* true if interactive and at start of line */
2286 #if ENABLE_FEATURE_EDITING
2287 static line_input_t *line_input_state;
2288 static const char *cmdedit_prompt;
2290 putprompt(const char *s)
2292 if (ENABLE_ASH_EXPAND_PRMT) {
2293 free((char*)cmdedit_prompt);
2294 cmdedit_prompt = ckstrdup(s);
2301 putprompt(const char *s)
2307 #if ENABLE_ASH_EXPAND_PRMT
2308 /* expandstr() needs parsing machinery, so it is far away ahead... */
2309 static const char *expandstr(const char *ps);
2311 #define expandstr(s) s
2315 setprompt(int whichprompt)
2318 #if ENABLE_ASH_EXPAND_PRMT
2319 struct stackmark smark;
2324 switch (whichprompt) {
2334 #if ENABLE_ASH_EXPAND_PRMT
2335 setstackmark(&smark);
2336 stalloc(stackblocksize());
2338 putprompt(expandstr(prompt));
2339 #if ENABLE_ASH_EXPAND_PRMT
2340 popstackmark(&smark);
2345 /* ============ The cd and pwd commands */
2347 #define CD_PHYSICAL 1
2357 while ((i = nextopt("LP")) != '\0') {
2359 flags ^= CD_PHYSICAL;
2368 * Update curdir (the name of the current directory) in response to a
2372 updatepwd(const char *dir)
2379 cdcomppath = ststrdup(dir);
2382 if (curdir == nullstr)
2384 new = stack_putstr(curdir, new);
2386 new = makestrspace(strlen(dir) + 2, new);
2387 lim = (char *)stackblock() + 1;
2391 if (new > lim && *lim == '/')
2396 if (dir[1] == '/' && dir[2] != '/') {
2402 p = strtok(cdcomppath, "/");
2406 if (p[1] == '.' && p[2] == '\0') {
2418 new = stack_putstr(p, new);
2426 return stackblock();
2430 * Find out what the current directory is. If we already know the current
2431 * directory, this routine returns immediately.
2436 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2437 return dir ? dir : nullstr;
2441 setpwd(const char *val, int setold)
2445 oldcur = dir = curdir;
2448 setvar("OLDPWD", oldcur, VEXPORT);
2451 if (physdir != nullstr) {
2452 if (physdir != oldcur)
2456 if (oldcur == val || !val) {
2462 dir = ckstrdup(val);
2463 if (oldcur != dir && oldcur != nullstr) {
2468 setvar("PWD", dir, VEXPORT);
2471 static void hashcd(void);
2474 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2475 * know that the current directory has changed.
2478 docd(const char *dest, int flags)
2480 const char *dir = NULL;
2483 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2486 if (!(flags & CD_PHYSICAL)) {
2487 dir = updatepwd(dest);
2501 static int FAST_FUNC
2502 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2514 dest = bltinlookup("HOME");
2515 else if (LONE_DASH(dest)) {
2516 dest = bltinlookup("OLDPWD");
2538 path = bltinlookup("CDPATH");
2547 p = path_advance(&path, dest);
2548 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2552 if (!docd(p, flags))
2557 ash_msg_and_raise_error("can't cd to %s", dest);
2560 if (flags & CD_PRINT)
2561 out1fmt("%s\n", curdir);
2565 static int FAST_FUNC
2566 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2569 const char *dir = curdir;
2573 if (physdir == nullstr)
2577 out1fmt("%s\n", dir);
2582 /* ============ ... */
2585 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2587 /* Syntax classes */
2588 #define CWORD 0 /* character is nothing special */
2589 #define CNL 1 /* newline character */
2590 #define CBACK 2 /* a backslash character */
2591 #define CSQUOTE 3 /* single quote */
2592 #define CDQUOTE 4 /* double quote */
2593 #define CENDQUOTE 5 /* a terminating quote */
2594 #define CBQUOTE 6 /* backwards single quote */
2595 #define CVAR 7 /* a dollar sign */
2596 #define CENDVAR 8 /* a '}' character */
2597 #define CLP 9 /* a left paren in arithmetic */
2598 #define CRP 10 /* a right paren in arithmetic */
2599 #define CENDFILE 11 /* end of file */
2600 #define CCTL 12 /* like CWORD, except it must be escaped */
2601 #define CSPCL 13 /* these terminate a word */
2602 #define CIGN 14 /* character should be ignored */
2605 #if ENABLE_ASH_ALIAS
2609 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2611 #if ENABLE_SH_MATH_SUPPORT
2612 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2614 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2616 static const uint16_t S_I_T[] = {
2617 #if ENABLE_ASH_ALIAS
2618 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2620 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2621 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2622 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2623 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2624 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2625 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2626 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2627 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2628 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2629 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2630 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2631 #if !USE_SIT_FUNCTION
2632 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2633 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2634 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2638 /* Constants below must match table above */
2640 #if ENABLE_ASH_ALIAS
2641 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2643 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2644 CNL_CNL_CNL_CNL , /* 2 */
2645 CWORD_CCTL_CCTL_CWORD , /* 3 */
2646 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2647 CVAR_CVAR_CWORD_CVAR , /* 5 */
2648 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2649 CSPCL_CWORD_CWORD_CLP , /* 7 */
2650 CSPCL_CWORD_CWORD_CRP , /* 8 */
2651 CBACK_CBACK_CCTL_CBACK , /* 9 */
2652 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2653 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2654 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2655 CWORD_CWORD_CWORD_CWORD , /* 13 */
2656 CCTL_CCTL_CCTL_CCTL , /* 14 */
2659 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2660 * caller must ensure proper cast on it if c is *char_ptr!
2662 /* Values for syntax param */
2663 #define BASESYNTAX 0 /* not in quotes */
2664 #define DQSYNTAX 1 /* in double quotes */
2665 #define SQSYNTAX 2 /* in single quotes */
2666 #define ARISYNTAX 3 /* in arithmetic */
2667 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2669 #if USE_SIT_FUNCTION
2672 SIT(int c, int syntax)
2674 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2675 # if ENABLE_ASH_ALIAS
2676 static const uint8_t syntax_index_table[] ALIGN1 = {
2677 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2678 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2679 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2683 static const uint8_t syntax_index_table[] ALIGN1 = {
2684 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2685 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2686 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2695 # if ENABLE_ASH_ALIAS
2701 /* Cast is purely for paranoia here,
2702 * just in case someone passed signed char to us */
2703 if ((unsigned char)c >= CTL_FIRST
2704 && (unsigned char)c <= CTL_LAST
2708 s = strchrnul(spec_symbls, c);
2711 indx = syntax_index_table[s - spec_symbls];
2713 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2716 #else /* !USE_SIT_FUNCTION */
2718 static const uint8_t syntax_index_table[] = {
2719 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2720 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2721 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2722 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2723 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2724 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2725 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2726 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2727 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2728 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2730 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2731 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2738 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2739 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2753 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2754 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2755 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2756 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2757 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2758 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2759 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2760 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2761 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2762 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2763 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2764 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2765 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2766 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2767 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2768 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2769 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2770 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2771 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2772 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2773 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2774 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2775 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2776 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2777 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2778 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2779 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2780 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2781 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2782 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2783 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2784 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2785 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2786 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2787 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2788 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2789 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2790 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2791 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2792 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2793 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2794 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2795 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2796 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2797 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2800 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2802 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2803 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2812 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2813 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2814 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2815 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2816 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2817 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2819 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2820 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2821 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2822 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2823 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2824 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2825 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2845 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2846 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2847 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2848 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2850 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2851 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2852 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2853 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2854 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2855 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2856 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2857 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 162 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 163 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 164 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 165 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 166 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 167 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 168 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 169 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 170 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 171 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 172 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 173 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 174 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 175 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 176 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 177 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 178 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 179 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 180 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 181 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 182 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 183 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 184 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 185 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 186 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 187 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 188 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 189 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 190 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 191 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 192 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 193 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 194 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 195 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 196 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 197 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 198 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 199 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 200 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 201 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 202 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 203 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 204 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 205 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 206 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 207 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 208 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 209 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 210 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 211 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 212 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 213 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 214 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 215 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 216 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 217 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 218 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 219 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 220 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 221 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 222 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 223 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 224 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 225 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 226 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 227 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 228 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 229 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 231 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 232 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 233 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 234 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 235 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 236 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 237 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 238 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 239 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 241 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 242 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 243 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 244 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 245 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 246 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 247 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 248 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 249 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 250 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 251 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 252 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 253 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 254 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 255 */ CWORD_CWORD_CWORD_CWORD,
2976 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2977 # if ENABLE_ASH_ALIAS
2978 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
2982 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
2984 #endif /* !USE_SIT_FUNCTION */
2987 /* ============ Alias handling */
2989 #if ENABLE_ASH_ALIAS
2991 #define ALIASINUSE 1
3002 static struct alias **atab; // [ATABSIZE];
3003 #define INIT_G_alias() do { \
3004 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3008 static struct alias **
3009 __lookupalias(const char *name) {
3010 unsigned int hashval;
3017 ch = (unsigned char)*p;
3021 ch = (unsigned char)*++p;
3023 app = &atab[hashval % ATABSIZE];
3025 for (; *app; app = &(*app)->next) {
3026 if (strcmp(name, (*app)->name) == 0) {
3034 static struct alias *
3035 lookupalias(const char *name, int check)
3037 struct alias *ap = *__lookupalias(name);
3039 if (check && ap && (ap->flag & ALIASINUSE))
3044 static struct alias *
3045 freealias(struct alias *ap)
3049 if (ap->flag & ALIASINUSE) {
3050 ap->flag |= ALIASDEAD;
3062 setalias(const char *name, const char *val)
3064 struct alias *ap, **app;
3066 app = __lookupalias(name);
3070 if (!(ap->flag & ALIASINUSE)) {
3073 ap->val = ckstrdup(val);
3074 ap->flag &= ~ALIASDEAD;
3077 ap = ckzalloc(sizeof(struct alias));
3078 ap->name = ckstrdup(name);
3079 ap->val = ckstrdup(val);
3080 /*ap->flag = 0; - ckzalloc did it */
3081 /*ap->next = NULL;*/
3088 unalias(const char *name)
3092 app = __lookupalias(name);
3096 *app = freealias(*app);
3107 struct alias *ap, **app;
3111 for (i = 0; i < ATABSIZE; i++) {
3113 for (ap = *app; ap; ap = *app) {
3114 *app = freealias(*app);
3124 printalias(const struct alias *ap)
3126 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3130 * TODO - sort output
3132 static int FAST_FUNC
3133 aliascmd(int argc UNUSED_PARAM, char **argv)
3142 for (i = 0; i < ATABSIZE; i++) {
3143 for (ap = atab[i]; ap; ap = ap->next) {
3149 while ((n = *++argv) != NULL) {
3150 v = strchr(n+1, '=');
3151 if (v == NULL) { /* n+1: funny ksh stuff */
3152 ap = *__lookupalias(n);
3154 fprintf(stderr, "%s: %s not found\n", "alias", n);
3167 static int FAST_FUNC
3168 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3172 while ((i = nextopt("a")) != '\0') {
3178 for (i = 0; *argptr; argptr++) {
3179 if (unalias(*argptr)) {
3180 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3188 #endif /* ASH_ALIAS */
3191 /* ============ jobs.c */
3193 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3196 #define FORK_NOJOB 2
3198 /* mode flags for showjob(s) */
3199 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3200 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3201 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3204 * A job structure contains information about a job. A job is either a
3205 * single process or a set of processes contained in a pipeline. In the
3206 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3210 pid_t ps_pid; /* process id */
3211 int ps_status; /* last process status from wait() */
3212 char *ps_cmd; /* text of command being run */
3216 struct procstat ps0; /* status of process */
3217 struct procstat *ps; /* status or processes when more than one */
3219 int stopstatus; /* status of a stopped job */
3222 nprocs: 16, /* number of processes */
3224 #define JOBRUNNING 0 /* at least one proc running */
3225 #define JOBSTOPPED 1 /* all procs are stopped */
3226 #define JOBDONE 2 /* all procs are completed */
3228 sigint: 1, /* job was killed by SIGINT */
3229 jobctl: 1, /* job running under job control */
3231 waited: 1, /* true if this entry has been waited for */
3232 used: 1, /* true if this entry is in used */
3233 changed: 1; /* true if status has changed */
3234 struct job *prev_job; /* previous job */
3237 static struct job *makejob(/*union node *,*/ int);
3238 static int forkshell(struct job *, union node *, int);
3239 static int waitforjob(struct job *);
3242 enum { doing_jobctl = 0 };
3243 #define setjobctl(on) do {} while (0)
3245 static smallint doing_jobctl; //references:8
3246 static void setjobctl(int);
3253 ignoresig(int signo)
3255 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3256 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3257 /* No, need to do it */
3258 signal(signo, SIG_IGN);
3260 sigmode[signo - 1] = S_HARD_IGN;
3264 * Only one usage site - in setsignal()
3267 signal_handler(int signo)
3269 gotsig[signo - 1] = 1;
3271 if (signo == SIGINT && !trap[SIGINT]) {
3272 if (!suppress_int) {
3274 raise_interrupt(); /* does not return */
3278 pending_sig = signo;
3283 * Set the signal handler for the specified signal. The routine figures
3284 * out what it should be set to.
3287 setsignal(int signo)
3290 char cur_act, new_act;
3291 struct sigaction act;
3295 if (t != NULL) { /* trap for this sig is set */
3297 if (t[0] == '\0') /* trap is "": ignore this sig */
3301 if (rootshell && new_act == S_DFL) {
3304 if (iflag || minusc || sflag == 0)
3313 * "In all cases, bash ignores SIGQUIT. Non-builtin
3314 * commands run by bash have signal handlers
3315 * set to the values inherited by the shell
3316 * from its parent". */
3332 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3333 //whereas we have to restore it to what shell got on entry
3334 //from the parent. See comment above
3336 t = &sigmode[signo - 1];
3339 /* current setting is not yet known */
3340 if (sigaction(signo, NULL, &act)) {
3341 /* pretend it worked; maybe we should give a warning,
3342 * but other shells don't. We don't alter sigmode,
3343 * so we retry every time.
3344 * btw, in Linux it never fails. --vda */
3347 if (act.sa_handler == SIG_IGN) {
3348 cur_act = S_HARD_IGN;
3350 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3352 cur_act = S_IGN; /* don't hard ignore these */
3356 if (cur_act == S_HARD_IGN || cur_act == new_act)
3359 act.sa_handler = SIG_DFL;
3362 act.sa_handler = signal_handler;
3363 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3364 sigfillset(&act.sa_mask); /* ditto */
3367 act.sa_handler = SIG_IGN;
3370 sigaction_set(signo, &act);
3375 /* mode flags for set_curjob */
3376 #define CUR_DELETE 2
3377 #define CUR_RUNNING 1
3378 #define CUR_STOPPED 0
3380 /* mode flags for dowait */
3381 #define DOWAIT_NONBLOCK WNOHANG
3382 #define DOWAIT_BLOCK 0
3385 /* pgrp of shell on invocation */
3386 static int initialpgrp; //references:2
3387 static int ttyfd = -1; //5
3390 static struct job *jobtab; //5
3392 static unsigned njobs; //4
3394 static struct job *curjob; //lots
3395 /* number of presumed living untracked jobs */
3396 static int jobless; //4
3399 set_curjob(struct job *jp, unsigned mode)
3402 struct job **jpp, **curp;
3404 /* first remove from list */
3405 jpp = curp = &curjob;
3410 jpp = &jp1->prev_job;
3412 *jpp = jp1->prev_job;
3414 /* Then re-insert in correct position */
3422 /* job being deleted */
3425 /* newly created job or backgrounded job,
3426 put after all stopped jobs. */
3430 if (!jp1 || jp1->state != JOBSTOPPED)
3433 jpp = &jp1->prev_job;
3439 /* newly stopped job - becomes curjob */
3440 jp->prev_job = *jpp;
3448 jobno(const struct job *jp)
3450 return jp - jobtab + 1;
3455 * Convert a job name to a job structure.
3458 #define getjob(name, getctl) getjob(name)
3461 getjob(const char *name, int getctl)
3465 const char *err_msg = "%s: no such job";
3469 char *(*match)(const char *, const char *);
3484 if (c == '+' || c == '%') {
3486 err_msg = "No current job";
3492 err_msg = "No previous job";
3503 jp = jobtab + num - 1;
3518 if (match(jp->ps[0].ps_cmd, p)) {
3522 err_msg = "%s: ambiguous";
3532 err_msg = "job %s not created under job control";
3533 if (getctl && jp->jobctl == 0)
3538 ash_msg_and_raise_error(err_msg, name);
3542 * Mark a job structure as unused.
3545 freejob(struct job *jp)
3547 struct procstat *ps;
3551 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3552 if (ps->ps_cmd != nullstr)
3555 if (jp->ps != &jp->ps0)
3558 set_curjob(jp, CUR_DELETE);
3564 xtcsetpgrp(int fd, pid_t pgrp)
3566 if (tcsetpgrp(fd, pgrp))
3567 ash_msg_and_raise_error("can't set tty process group (%m)");
3571 * Turn job control on and off.
3573 * Note: This code assumes that the third arg to ioctl is a character
3574 * pointer, which is true on Berkeley systems but not System V. Since
3575 * System V doesn't have job control yet, this isn't a problem now.
3577 * Called with interrupts off.
3585 if (on == doing_jobctl || rootshell == 0)
3589 ofd = fd = open(_PATH_TTY, O_RDWR);
3591 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3592 * That sometimes helps to acquire controlling tty.
3593 * Obviously, a workaround for bugs when someone
3594 * failed to provide a controlling tty to bash! :) */
3600 fd = fcntl(fd, F_DUPFD, 10);
3605 /* fd is a tty at this point */
3606 close_on_exec_on(fd);
3607 do { /* while we are in the background */
3608 pgrp = tcgetpgrp(fd);
3611 ash_msg("can't access tty; job control turned off");
3615 if (pgrp == getpgrp())
3626 xtcsetpgrp(fd, pgrp);
3628 /* turning job control off */
3631 /* was xtcsetpgrp, but this can make exiting ash
3632 * loop forever if pty is already deleted */
3633 tcsetpgrp(fd, pgrp);
3647 static int FAST_FUNC
3648 killcmd(int argc, char **argv)
3651 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3653 if (argv[i][0] == '%') {
3654 struct job *jp = getjob(argv[i], 0);
3655 unsigned pid = jp->ps[0].ps_pid;
3656 /* Enough space for ' -NNN<nul>' */
3657 argv[i] = alloca(sizeof(int)*3 + 3);
3658 /* kill_main has matching code to expect
3659 * leading space. Needed to not confuse
3660 * negative pids with "kill -SIGNAL_NO" syntax */
3661 sprintf(argv[i], " -%u", pid);
3663 } while (argv[++i]);
3665 return kill_main(argc, argv);
3669 showpipe(struct job *jp /*, FILE *out*/)
3671 struct procstat *ps;
3672 struct procstat *psend;
3674 psend = jp->ps + jp->nprocs;
3675 for (ps = jp->ps + 1; ps < psend; ps++)
3676 printf(" | %s", ps->ps_cmd);
3677 outcslow('\n', stdout);
3678 flush_stdout_stderr();
3683 restartjob(struct job *jp, int mode)
3685 struct procstat *ps;
3691 if (jp->state == JOBDONE)
3693 jp->state = JOBRUNNING;
3694 pgid = jp->ps[0].ps_pid;
3695 if (mode == FORK_FG)
3696 xtcsetpgrp(ttyfd, pgid);
3697 killpg(pgid, SIGCONT);
3701 if (WIFSTOPPED(ps->ps_status)) {
3707 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3712 static int FAST_FUNC
3713 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3719 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3723 jp = getjob(*argv, 1);
3724 if (mode == FORK_BG) {
3725 set_curjob(jp, CUR_RUNNING);
3726 printf("[%d] ", jobno(jp));
3728 out1str(jp->ps[0].ps_cmd);
3729 showpipe(jp /*, stdout*/);
3730 retval = restartjob(jp, mode);
3731 } while (*argv && *++argv);
3737 sprint_status(char *s, int status, int sigonly)
3743 if (!WIFEXITED(status)) {
3745 if (WIFSTOPPED(status))
3746 st = WSTOPSIG(status);
3749 st = WTERMSIG(status);
3751 if (st == SIGINT || st == SIGPIPE)
3754 if (WIFSTOPPED(status))
3759 col = fmtstr(s, 32, strsignal(st));
3760 if (WCOREDUMP(status)) {
3761 col += fmtstr(s + col, 16, " (core dumped)");
3763 } else if (!sigonly) {
3764 st = WEXITSTATUS(status);
3766 col = fmtstr(s, 16, "Done(%d)", st);
3768 col = fmtstr(s, 16, "Done");
3775 dowait(int wait_flags, struct job *job)
3780 struct job *thisjob;
3783 TRACE(("dowait(0x%x) called\n", wait_flags));
3785 /* Do a wait system call. If job control is compiled in, we accept
3786 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3787 * NB: _not_ safe_waitpid, we need to detect EINTR */
3789 wait_flags |= WUNTRACED;
3790 pid = waitpid(-1, &status, wait_flags);
3791 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3792 pid, status, errno, strerror(errno)));
3798 for (jp = curjob; jp; jp = jp->prev_job) {
3799 struct procstat *ps;
3800 struct procstat *psend;
3801 if (jp->state == JOBDONE)
3805 psend = ps + jp->nprocs;
3807 if (ps->ps_pid == pid) {
3808 TRACE(("Job %d: changing status of proc %d "
3809 "from 0x%x to 0x%x\n",
3810 jobno(jp), pid, ps->ps_status, status));
3811 ps->ps_status = status;
3814 if (ps->ps_status == -1)
3817 if (state == JOBRUNNING)
3819 if (WIFSTOPPED(ps->ps_status)) {
3820 jp->stopstatus = ps->ps_status;
3824 } while (++ps < psend);
3829 if (!WIFSTOPPED(status))
3835 if (state != JOBRUNNING) {
3836 thisjob->changed = 1;
3838 if (thisjob->state != state) {
3839 TRACE(("Job %d: changing state from %d to %d\n",
3840 jobno(thisjob), thisjob->state, state));
3841 thisjob->state = state;
3843 if (state == JOBSTOPPED) {
3844 set_curjob(thisjob, CUR_STOPPED);
3853 if (thisjob && thisjob == job) {
3857 len = sprint_status(s, status, 1);
3868 blocking_wait_with_raise_on_sig(void)
3870 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
3871 if (pid <= 0 && pending_sig)
3872 raise_exception(EXSIG);
3878 showjob(FILE *out, struct job *jp, int mode)
3880 struct procstat *ps;
3881 struct procstat *psend;
3888 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
3889 /* just output process (group) id of pipeline */
3890 fprintf(out, "%d\n", ps->ps_pid);
3894 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3899 else if (curjob && jp == curjob->prev_job)
3902 if (mode & SHOW_PIDS)
3903 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
3905 psend = ps + jp->nprocs;
3907 if (jp->state == JOBRUNNING) {
3908 strcpy(s + col, "Running");
3909 col += sizeof("Running") - 1;
3911 int status = psend[-1].ps_status;
3912 if (jp->state == JOBSTOPPED)
3913 status = jp->stopstatus;
3914 col += sprint_status(s + col, status, 0);
3916 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
3918 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3919 * or prints several "PID | <cmdN>" lines,
3920 * depending on SHOW_PIDS bit.
3921 * We do not print status of individual processes
3922 * between PID and <cmdN>. bash does it, but not very well:
3923 * first line shows overall job status, not process status,
3924 * making it impossible to know 1st process status.
3928 /* for each process */
3931 if (mode & SHOW_PIDS)
3932 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
3934 fprintf(out, "%s%*c%s%s",
3936 33 - col >= 0 ? 33 - col : 0, ' ',
3937 ps == jp->ps ? "" : "| ",
3940 } while (++ps != psend);
3941 outcslow('\n', out);
3945 if (jp->state == JOBDONE) {
3946 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3952 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3953 * statuses have changed since the last call to showjobs.
3956 showjobs(FILE *out, int mode)
3960 TRACE(("showjobs(0x%x) called\n", mode));
3962 /* Handle all finished jobs */
3963 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
3966 for (jp = curjob; jp; jp = jp->prev_job) {
3967 if (!(mode & SHOW_CHANGED) || jp->changed) {
3968 showjob(out, jp, mode);
3973 static int FAST_FUNC
3974 jobscmd(int argc UNUSED_PARAM, char **argv)
3979 while ((m = nextopt("lp")) != '\0') {
3983 mode |= SHOW_ONLY_PGID;
3989 showjob(stdout, getjob(*argv, 0), mode);
3992 showjobs(stdout, mode);
3999 /* Called only on finished or stopped jobs (no members are running) */
4001 getstatus(struct job *job)
4005 struct procstat *ps;
4007 /* Fetch last member's status */
4008 ps = job->ps + job->nprocs - 1;
4009 status = ps->ps_status;
4011 /* "set -o pipefail" mode: use last _nonzero_ status */
4012 while (status == 0 && --ps >= job->ps)
4013 status = ps->ps_status;
4016 retval = WEXITSTATUS(status);
4017 if (!WIFEXITED(status)) {
4019 retval = WSTOPSIG(status);
4020 if (!WIFSTOPPED(status))
4023 /* XXX: limits number of signals */
4024 retval = WTERMSIG(status);
4026 if (retval == SIGINT)
4032 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4033 jobno(job), job->nprocs, status, retval));
4037 static int FAST_FUNC
4038 waitcmd(int argc UNUSED_PARAM, char **argv)
4045 raise_exception(EXSIG);
4052 /* wait for all jobs */
4056 if (!jp) /* no running procs */
4058 if (jp->state == JOBRUNNING)
4063 blocking_wait_with_raise_on_sig();
4065 * "When bash is waiting for an asynchronous command via
4066 * the wait builtin, the reception of a signal for which a trap
4067 * has been set will cause the wait builtin to return immediately
4068 * with an exit status greater than 128, immediately after which
4069 * the trap is executed."
4071 * blocking_wait_with_raise_on_sig raises signal handlers
4072 * if it gets no pid (pid < 0). However,
4073 * if child sends us a signal *and immediately exits*,
4074 * blocking_wait_with_raise_on_sig gets pid > 0
4075 * and does not handle pending_sig. Check this case: */
4077 raise_exception(EXSIG);
4083 if (**argv != '%') {
4084 pid_t pid = number(*argv);
4089 if (job->ps[job->nprocs - 1].ps_pid == pid)
4091 job = job->prev_job;
4094 job = getjob(*argv, 0);
4095 /* loop until process terminated or stopped */
4096 while (job->state == JOBRUNNING)
4097 blocking_wait_with_raise_on_sig();
4099 retval = getstatus(job);
4112 struct job *jp, *jq;
4114 len = njobs * sizeof(*jp);
4116 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4118 offset = (char *)jp - (char *)jq;
4120 /* Relocate pointers */
4123 jq = (struct job *)((char *)jq + l);
4127 #define joff(p) ((struct job *)((char *)(p) + l))
4128 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4129 if (joff(jp)->ps == &jq->ps0)
4130 jmove(joff(jp)->ps);
4131 if (joff(jp)->prev_job)
4132 jmove(joff(jp)->prev_job);
4142 jp = (struct job *)((char *)jp + len);
4146 } while (--jq >= jp);
4151 * Return a new job structure.
4152 * Called with interrupts off.
4155 makejob(/*union node *node,*/ int nprocs)
4160 for (i = njobs, jp = jobtab; ; jp++) {
4167 if (jp->state != JOBDONE || !jp->waited)
4176 memset(jp, 0, sizeof(*jp));
4178 /* jp->jobctl is a bitfield.
4179 * "jp->jobctl |= jobctl" likely to give awful code */
4183 jp->prev_job = curjob;
4188 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4190 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4197 * Return a string identifying a command (to be printed by the
4200 static char *cmdnextc;
4203 cmdputs(const char *s)
4205 static const char vstype[VSTYPE + 1][3] = {
4206 "", "}", "-", "+", "?", "=",
4207 "%", "%%", "#", "##"
4208 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4211 const char *p, *str;
4215 unsigned char subtype = 0;
4219 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4221 while ((c = *p++) != '\0') {
4229 if ((subtype & VSTYPE) == VSLENGTH)
4233 if (!(subtype & VSQUOTE) == !(quoted & 1))
4239 str = "\"}" + !(quoted & 1);
4246 case CTLBACKQ+CTLQUOTE:
4249 #if ENABLE_SH_MATH_SUPPORT
4264 if ((subtype & VSTYPE) != VSNORMAL)
4266 str = vstype[subtype & VSTYPE];
4267 if (subtype & VSNUL)
4276 /* These can only happen inside quotes */
4289 while ((c = *str++) != '\0') {
4292 } /* while *p++ not NUL */
4295 USTPUTC('"', nextc);
4301 /* cmdtxt() and cmdlist() call each other */
4302 static void cmdtxt(union node *n);
4305 cmdlist(union node *np, int sep)
4307 for (; np; np = np->narg.next) {
4311 if (sep && np->narg.next)
4317 cmdtxt(union node *n)
4320 struct nodelist *lp;
4331 lp = n->npipe.cmdlist;
4349 cmdtxt(n->nbinary.ch1);
4365 cmdtxt(n->nif.test);
4367 if (n->nif.elsepart) {
4368 cmdtxt(n->nif.ifpart);
4370 n = n->nif.elsepart;
4388 cmdtxt(n->nbinary.ch1);
4398 cmdputs(n->nfor.var);
4400 cmdlist(n->nfor.args, 1);
4405 cmdputs(n->narg.text);
4409 cmdlist(n->ncmd.args, 1);
4410 cmdlist(n->ncmd.redirect, 0);
4423 cmdputs(n->ncase.expr->narg.text);
4425 for (np = n->ncase.cases; np; np = np->nclist.next) {
4426 cmdtxt(np->nclist.pattern);
4428 cmdtxt(np->nclist.body);
4442 #if ENABLE_ASH_BASH_COMPAT
4457 cmdputs(utoa(n->nfile.fd));
4459 if (n->type == NTOFD || n->type == NFROMFD) {
4460 cmdputs(utoa(n->ndup.dupfd));
4469 commandtext(union node *n)
4473 STARTSTACKSTR(cmdnextc);
4475 name = stackblock();
4476 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4477 name, cmdnextc, cmdnextc));
4478 return ckstrdup(name);
4483 * Fork off a subshell. If we are doing job control, give the subshell its
4484 * own process group. Jp is a job structure that the job is to be added to.
4485 * N is the command that will be evaluated by the child. Both jp and n may
4486 * be NULL. The mode parameter can be one of the following:
4487 * FORK_FG - Fork off a foreground process.
4488 * FORK_BG - Fork off a background process.
4489 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4490 * process group even if job control is on.
4492 * When job control is turned off, background processes have their standard
4493 * input redirected to /dev/null (except for the second and later processes
4496 * Called with interrupts off.
4499 * Clear traps on a fork.
4506 for (tp = trap; tp < &trap[NSIG]; tp++) {
4507 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4509 if (trap_ptr == trap)
4511 /* else: it "belongs" to trap_ptr vector, don't free */
4513 if ((tp - trap) != 0)
4514 setsignal(tp - trap);
4520 /* Lives far away from here, needed for forkchild */
4521 static void closescript(void);
4523 /* Called after fork(), in child */
4524 static NOINLINE void
4525 forkchild(struct job *jp, union node *n, int mode)
4529 TRACE(("Child shell %d\n", getpid()));
4533 /* man bash: "Non-builtin commands run by bash have signal handlers
4534 * set to the values inherited by the shell from its parent".
4535 * Do we do it correctly? */
4539 if (mode == FORK_NOJOB /* is it `xxx` ? */
4540 && n && n->type == NCMD /* is it single cmd? */
4541 /* && n->ncmd.args->type == NARG - always true? */
4542 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4543 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4544 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4546 TRACE(("Trap hack\n"));
4547 /* Awful hack for `trap` or $(trap).
4549 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4550 * contains an example where "trap" is executed in a subshell:
4552 * save_traps=$(trap)
4554 * eval "$save_traps"
4556 * Standard does not say that "trap" in subshell shall print
4557 * parent shell's traps. It only says that its output
4558 * must have suitable form, but then, in the above example
4559 * (which is not supposed to be normative), it implies that.
4561 * bash (and probably other shell) does implement it
4562 * (traps are reset to defaults, but "trap" still shows them),
4563 * but as a result, "trap" logic is hopelessly messed up:
4566 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4567 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4568 * # true | trap <--- trap is in subshell - no output (ditto)
4569 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4570 * trap -- 'echo Ho' SIGWINCH
4571 * # echo `(trap)` <--- in subshell in subshell - output
4572 * trap -- 'echo Ho' SIGWINCH
4573 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4574 * trap -- 'echo Ho' SIGWINCH
4576 * The rules when to forget and when to not forget traps
4577 * get really complex and nonsensical.
4579 * Our solution: ONLY bare $(trap) or `trap` is special.
4581 /* Save trap handler strings for trap builtin to print */
4582 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4583 /* Fall through into clearing traps */
4587 /* do job control only in root shell */
4589 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4592 if (jp->nprocs == 0)
4595 pgrp = jp->ps[0].ps_pid;
4596 /* this can fail because we are doing it in the parent also */
4598 if (mode == FORK_FG)
4599 xtcsetpgrp(ttyfd, pgrp);
4604 if (mode == FORK_BG) {
4605 /* man bash: "When job control is not in effect,
4606 * asynchronous commands ignore SIGINT and SIGQUIT" */
4609 if (jp->nprocs == 0) {
4611 if (open(bb_dev_null, O_RDONLY) != 0)
4612 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4616 if (iflag) { /* why if iflag only? */
4621 * "In all cases, bash ignores SIGQUIT. Non-builtin
4622 * commands run by bash have signal handlers
4623 * set to the values inherited by the shell
4625 * Take care of the second rule: */
4629 if (n && n->type == NCMD
4630 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4632 TRACE(("Job hack\n"));
4633 /* "jobs": we do not want to clear job list for it,
4634 * instead we remove only _its_ own_ job from job list.
4635 * This makes "jobs .... | cat" more useful.
4641 for (jp = curjob; jp; jp = jp->prev_job)
4646 /* Called after fork(), in parent */
4648 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4651 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4653 TRACE(("In parent shell: child = %d\n", pid));
4655 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4661 if (mode != FORK_NOJOB && jp->jobctl) {
4664 if (jp->nprocs == 0)
4667 pgrp = jp->ps[0].ps_pid;
4668 /* This can fail because we are doing it in the child also */
4672 if (mode == FORK_BG) {
4673 backgndpid = pid; /* set $! */
4674 set_curjob(jp, CUR_RUNNING);
4677 struct procstat *ps = &jp->ps[jp->nprocs++];
4680 ps->ps_cmd = nullstr;
4682 if (doing_jobctl && n)
4683 ps->ps_cmd = commandtext(n);
4689 forkshell(struct job *jp, union node *n, int mode)
4693 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4696 TRACE(("Fork failed, errno=%d", errno));
4699 ash_msg_and_raise_error("can't fork");
4702 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4703 forkchild(jp, n, mode);
4705 forkparent(jp, n, mode, pid);
4711 * Wait for job to finish.
4713 * Under job control we have the problem that while a child process
4714 * is running interrupts generated by the user are sent to the child
4715 * but not to the shell. This means that an infinite loop started by
4716 * an interactive user may be hard to kill. With job control turned off,
4717 * an interactive user may place an interactive program inside a loop.
4718 * If the interactive program catches interrupts, the user doesn't want
4719 * these interrupts to also abort the loop. The approach we take here
4720 * is to have the shell ignore interrupt signals while waiting for a
4721 * foreground process to terminate, and then send itself an interrupt
4722 * signal if the child process was terminated by an interrupt signal.
4723 * Unfortunately, some programs want to do a bit of cleanup and then
4724 * exit on interrupt; unless these processes terminate themselves by
4725 * sending a signal to themselves (instead of calling exit) they will
4726 * confuse this approach.
4728 * Called with interrupts off.
4731 waitforjob(struct job *jp)
4735 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4738 while (jp->state == JOBRUNNING) {
4739 /* In non-interactive shells, we _can_ get
4740 * a keyboard signal here and be EINTRed,
4741 * but we just loop back, waiting for command to complete.
4744 * "If bash is waiting for a command to complete and receives
4745 * a signal for which a trap has been set, the trap
4746 * will not be executed until the command completes."
4748 * Reality is that even if trap is not set, bash
4749 * will not act on the signal until command completes.
4750 * Try this. sleep5intoff.c:
4751 * #include <signal.h>
4752 * #include <unistd.h>
4755 * sigemptyset(&set);
4756 * sigaddset(&set, SIGINT);
4757 * sigaddset(&set, SIGQUIT);
4758 * sigprocmask(SIG_BLOCK, &set, NULL);
4762 * $ bash -c './sleep5intoff; echo hi'
4763 * ^C^C^C^C <--- pressing ^C once a second
4765 * $ bash -c './sleep5intoff; echo hi'
4766 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4769 dowait(DOWAIT_BLOCK, jp);
4776 xtcsetpgrp(ttyfd, rootpid);
4778 * This is truly gross.
4779 * If we're doing job control, then we did a TIOCSPGRP which
4780 * caused us (the shell) to no longer be in the controlling
4781 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4782 * intuit from the subprocess exit status whether a SIGINT
4783 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4785 if (jp->sigint) /* TODO: do the same with all signals */
4786 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4788 if (jp->state == JOBDONE)
4795 * return 1 if there are stopped jobs, otherwise 0
4807 if (jp && jp->state == JOBSTOPPED) {
4808 out2str("You have stopped jobs.\n");
4817 /* ============ redir.c
4819 * Code for dealing with input/output redirection.
4822 #define EMPTY -2 /* marks an unused slot in redirtab */
4823 #define CLOSED -3 /* marks a slot of previously-closed fd */
4826 * Open a file in noclobber mode.
4827 * The code was copied from bash.
4830 noclobberopen(const char *fname)
4833 struct stat finfo, finfo2;
4836 * If the file exists and is a regular file, return an error
4839 r = stat(fname, &finfo);
4840 if (r == 0 && S_ISREG(finfo.st_mode)) {
4846 * If the file was not present (r != 0), make sure we open it
4847 * exclusively so that if it is created before we open it, our open
4848 * will fail. Make sure that we do not truncate an existing file.
4849 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4850 * file was not a regular file, we leave O_EXCL off.
4853 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4854 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4856 /* If the open failed, return the file descriptor right away. */
4861 * OK, the open succeeded, but the file may have been changed from a
4862 * non-regular file to a regular file between the stat and the open.
4863 * We are assuming that the O_EXCL open handles the case where FILENAME
4864 * did not exist and is symlinked to an existing file between the stat
4869 * If we can open it and fstat the file descriptor, and neither check
4870 * revealed that it was a regular file, and the file has not been
4871 * replaced, return the file descriptor.
4873 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4874 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4877 /* The file has been replaced. badness. */
4884 * Handle here documents. Normally we fork off a process to write the
4885 * data to a pipe. If the document is short, we can stuff the data in
4886 * the pipe without forking.
4888 /* openhere needs this forward reference */
4889 static void expandhere(union node *arg, int fd);
4891 openhere(union node *redir)
4897 ash_msg_and_raise_error("pipe call failed");
4898 if (redir->type == NHERE) {
4899 len = strlen(redir->nhere.doc->narg.text);
4900 if (len <= PIPE_BUF) {
4901 full_write(pip[1], redir->nhere.doc->narg.text, len);
4905 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4908 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4909 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4910 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4911 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4912 signal(SIGPIPE, SIG_DFL);
4913 if (redir->type == NHERE)
4914 full_write(pip[1], redir->nhere.doc->narg.text, len);
4916 expandhere(redir->nhere.doc, pip[1]);
4917 _exit(EXIT_SUCCESS);
4925 openredirect(union node *redir)
4930 switch (redir->nfile.type) {
4932 fname = redir->nfile.expfname;
4933 f = open(fname, O_RDONLY);
4938 fname = redir->nfile.expfname;
4939 f = open(fname, O_RDWR|O_CREAT, 0666);
4944 #if ENABLE_ASH_BASH_COMPAT
4947 /* Take care of noclobber mode. */
4949 fname = redir->nfile.expfname;
4950 f = noclobberopen(fname);
4957 fname = redir->nfile.expfname;
4958 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4963 fname = redir->nfile.expfname;
4964 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4972 /* Fall through to eliminate warning. */
4973 /* Our single caller does this itself */
4980 f = openhere(redir);
4986 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4988 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
4992 * Copy a file descriptor to be >= to. Returns -1
4993 * if the source file descriptor is closed, EMPTY if there are no unused
4994 * file descriptors left.
4996 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
4997 * old code was doing close(to) prior to copyfd() to achieve the same */
4999 COPYFD_EXACT = (int)~(INT_MAX),
5000 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5003 copyfd(int from, int to)
5007 if (to & COPYFD_EXACT) {
5008 to &= ~COPYFD_EXACT;
5010 newfd = dup2(from, to);
5012 newfd = fcntl(from, F_DUPFD, to);
5015 if (errno == EMFILE)
5017 /* Happens when source fd is not open: try "echo >&99" */
5018 ash_msg_and_raise_error("%d: %m", from);
5023 /* Struct def and variable are moved down to the first usage site */
5028 struct redirtab *next;
5031 struct two_fd_t two_fd[];
5033 #define redirlist (G_var.redirlist)
5035 static int need_to_remember(struct redirtab *rp, int fd)
5039 if (!rp) /* remembering was not requested */
5042 for (i = 0; i < rp->pair_count; i++) {
5043 if (rp->two_fd[i].orig == fd) {
5044 /* already remembered */
5051 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5052 static int is_hidden_fd(struct redirtab *rp, int fd)
5055 struct parsefile *pf;
5059 /* Check open scripts' fds */
5062 /* We skip pf_fd == 0 case because of the following case:
5063 * $ ash # running ash interactively
5065 * and in script.sh: "exec 9>&0".
5066 * Even though top-level pf_fd _is_ 0,
5067 * it's still ok to use it: "read" builtin uses it,
5068 * why should we cripple "exec" builtin?
5070 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5078 /* Check saved fds of redirects */
5079 fd |= COPYFD_RESTORE;
5080 for (i = 0; i < rp->pair_count; i++) {
5081 if (rp->two_fd[i].copy == fd) {
5089 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5090 * old file descriptors are stashed away so that the redirection can be
5091 * undone by calling popredir.
5093 /* flags passed to redirect */
5094 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5095 #define REDIR_SAVEFD2 03 /* set preverrout */
5097 redirect(union node *redir, int flags)
5099 struct redirtab *sv;
5104 int copied_fd2 = -1;
5114 if (flags & REDIR_PUSH) {
5115 union node *tmp = redir;
5118 #if ENABLE_ASH_BASH_COMPAT
5119 if (tmp->nfile.type == NTO2)
5122 tmp = tmp->nfile.next;
5124 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5125 sv->next = redirlist;
5126 sv->pair_count = sv_pos;
5128 sv->nullredirs = g_nullredirs - 1;
5130 while (sv_pos > 0) {
5132 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5138 fd = redir->nfile.fd;
5139 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5140 right_fd = redir->ndup.dupfd;
5141 //bb_error_msg("doing %d > %d", fd, right_fd);
5142 /* redirect from/to same file descriptor? */
5145 /* "echo >&10" and 10 is a fd opened to a sh script? */
5146 if (is_hidden_fd(sv, right_fd)) {
5147 errno = EBADF; /* as if it is closed */
5148 ash_msg_and_raise_error("%d: %m", right_fd);
5152 newfd = openredirect(redir); /* always >= 0 */
5154 /* Descriptor wasn't open before redirect.
5155 * Mark it for close in the future */
5156 if (need_to_remember(sv, fd)) {
5157 goto remember_to_close;
5162 #if ENABLE_ASH_BASH_COMPAT
5165 if (need_to_remember(sv, fd)) {
5166 /* Copy old descriptor */
5167 /* Careful to not accidentally "save"
5168 * to the same fd as right side fd in N>&M */
5169 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5170 i = fcntl(fd, F_DUPFD, minfd);
5171 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5172 * are closed in popredir() in the child, preventing them from leaking
5173 * into child. (popredir() also cleans up the mess in case of failures)
5178 /* Strange error (e.g. "too many files" EMFILE?) */
5182 ash_msg_and_raise_error("%d: %m", fd);
5185 /* EBADF: it is not open - good, remember to close it */
5188 } else { /* fd is open, save its copy */
5189 /* "exec fd>&-" should not close fds
5190 * which point to script file(s).
5191 * Force them to be restored afterwards */
5192 if (is_hidden_fd(sv, fd))
5193 i |= COPYFD_RESTORE;
5197 sv->two_fd[sv_pos].orig = fd;
5198 sv->two_fd[sv_pos].copy = i;
5202 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5203 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5204 /* Don't want to trigger debugging */
5208 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5210 } else if (fd != newfd) { /* move newfd to fd */
5211 copyfd(newfd, fd | COPYFD_EXACT);
5212 #if ENABLE_ASH_BASH_COMPAT
5213 if (!(redir->nfile.type == NTO2 && fd == 2))
5217 #if ENABLE_ASH_BASH_COMPAT
5218 if (redir->nfile.type == NTO2 && fd == 1) {
5219 /* We already redirected it to fd 1, now copy it to 2 */
5225 } while ((redir = redir->nfile.next) != NULL);
5228 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5229 preverrout_fd = copied_fd2;
5233 * Undo the effects of the last redirection.
5236 popredir(int drop, int restore)
5238 struct redirtab *rp;
5241 if (--g_nullredirs >= 0)
5245 for (i = 0; i < rp->pair_count; i++) {
5246 int fd = rp->two_fd[i].orig;
5247 int copy = rp->two_fd[i].copy;
5248 if (copy == CLOSED) {
5253 if (copy != EMPTY) {
5254 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5255 copy &= ~COPYFD_RESTORE;
5257 copyfd(copy, fd | COPYFD_EXACT);
5259 close(copy & ~COPYFD_RESTORE);
5262 redirlist = rp->next;
5263 g_nullredirs = rp->nullredirs;
5269 * Undo all redirections. Called on error or interrupt.
5273 * Discard all saved file descriptors.
5276 clearredir(int drop)
5282 popredir(drop, /*restore:*/ 0);
5287 redirectsafe(union node *redir, int flags)
5290 volatile int saveint;
5291 struct jmploc *volatile savehandler = exception_handler;
5292 struct jmploc jmploc;
5295 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5296 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5298 exception_handler = &jmploc;
5299 redirect(redir, flags);
5301 exception_handler = savehandler;
5302 if (err && exception_type != EXERROR)
5303 longjmp(exception_handler->loc, 1);
5304 RESTORE_INT(saveint);
5309 /* ============ Routines to expand arguments to commands
5311 * We have to deal with backquotes, shell variables, and file metacharacters.
5314 #if ENABLE_SH_MATH_SUPPORT
5316 ash_arith(const char *s)
5318 arith_eval_hooks_t math_hooks;
5322 math_hooks.lookupvar = lookupvar;
5323 math_hooks.setvar = setvar2;
5324 math_hooks.endofname = endofname;
5327 result = arith(s, &errcode, &math_hooks);
5330 ash_msg_and_raise_error("exponent less than 0");
5332 ash_msg_and_raise_error("divide by zero");
5334 ash_msg_and_raise_error("expression recursion loop detected");
5335 raise_error_syntax(s);
5346 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5347 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5348 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5349 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5350 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5351 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5352 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5353 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5354 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5358 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5359 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5360 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5361 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5362 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5365 * Structure specifying which parts of the string should be searched
5366 * for IFS characters.
5369 struct ifsregion *next; /* next region in list */
5370 int begoff; /* offset of start of region */
5371 int endoff; /* offset of end of region */
5372 int nulonly; /* search for nul bytes only */
5376 struct strlist *list;
5377 struct strlist **lastp;
5380 /* output of current string */
5381 static char *expdest;
5382 /* list of back quote expressions */
5383 static struct nodelist *argbackq;
5384 /* first struct in list of ifs regions */
5385 static struct ifsregion ifsfirst;
5386 /* last struct in list */
5387 static struct ifsregion *ifslastp;
5388 /* holds expanded arg list */
5389 static struct arglist exparg;
5399 expdest = makestrspace(32, expdest);
5400 len = fmtstr(expdest, 32, arith_t_fmt, num);
5401 STADJUST(len, expdest);
5406 esclen(const char *start, const char *p)
5410 while (p > start && (unsigned char)*--p == CTLESC) {
5417 * Remove any CTLESC characters from a string.
5420 rmescapes(char *str, int flag)
5422 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5426 unsigned protect_against_glob;
5429 p = strpbrk(str, qchars);
5435 if (flag & RMESCAPE_ALLOC) {
5436 size_t len = p - str;
5437 size_t fulllen = len + strlen(p) + 1;
5439 if (flag & RMESCAPE_GROW) {
5440 int strloc = str - (char *)stackblock();
5441 r = makestrspace(fulllen, expdest);
5442 /* p and str may be invalidated by makestrspace */
5443 str = (char *)stackblock() + strloc;
5445 } else if (flag & RMESCAPE_HEAP) {
5446 r = ckmalloc(fulllen);
5448 r = stalloc(fulllen);
5452 q = (char *)memcpy(q, str, len) + len;
5456 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5457 globbing = flag & RMESCAPE_GLOB;
5458 protect_against_glob = globbing;
5460 if ((unsigned char)*p == CTLQUOTEMARK) {
5461 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5462 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5463 // Note: both inquotes and protect_against_glob only affect whether
5464 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5465 inquotes = ~inquotes;
5467 protect_against_glob = globbing;
5471 /* naked back slash */
5472 protect_against_glob = 0;
5475 if ((unsigned char)*p == CTLESC) {
5477 if (protect_against_glob && inquotes && *p != '/') {
5481 protect_against_glob = globbing;
5486 if (flag & RMESCAPE_GROW) {
5488 STADJUST(q - r + 1, expdest);
5492 #define pmatch(a, b) !fnmatch((a), (b), 0)
5495 * Prepare a pattern for a expmeta (internal glob(3)) call.
5497 * Returns an stalloced string.
5500 preglob(const char *pattern, int quoted, int flag)
5502 flag |= RMESCAPE_GLOB;
5504 flag |= RMESCAPE_QUOTED;
5506 return rmescapes((char *)pattern, flag);
5510 * Put a string on the stack.
5513 memtodest(const char *p, size_t len, int syntax, int quotes)
5517 q = makestrspace(quotes ? len * 2 : len, q);
5520 unsigned char c = *p++;
5524 int n = SIT(c, syntax);
5525 if (n == CCTL || n == CBACK)
5535 strtodest(const char *p, int syntax, int quotes)
5537 memtodest(p, strlen(p), syntax, quotes);
5541 * Record the fact that we have to scan this region of the
5542 * string for IFS characters.
5545 recordregion(int start, int end, int nulonly)
5547 struct ifsregion *ifsp;
5549 if (ifslastp == NULL) {
5553 ifsp = ckzalloc(sizeof(*ifsp));
5554 /*ifsp->next = NULL; - ckzalloc did it */
5555 ifslastp->next = ifsp;
5559 ifslastp->begoff = start;
5560 ifslastp->endoff = end;
5561 ifslastp->nulonly = nulonly;
5565 removerecordregions(int endoff)
5567 if (ifslastp == NULL)
5570 if (ifsfirst.endoff > endoff) {
5571 while (ifsfirst.next != NULL) {
5572 struct ifsregion *ifsp;
5574 ifsp = ifsfirst.next->next;
5575 free(ifsfirst.next);
5576 ifsfirst.next = ifsp;
5579 if (ifsfirst.begoff > endoff)
5582 ifslastp = &ifsfirst;
5583 ifsfirst.endoff = endoff;
5588 ifslastp = &ifsfirst;
5589 while (ifslastp->next && ifslastp->next->begoff < endoff)
5590 ifslastp=ifslastp->next;
5591 while (ifslastp->next != NULL) {
5592 struct ifsregion *ifsp;
5594 ifsp = ifslastp->next->next;
5595 free(ifslastp->next);
5596 ifslastp->next = ifsp;
5599 if (ifslastp->endoff > endoff)
5600 ifslastp->endoff = endoff;
5604 exptilde(char *startp, char *p, int flags)
5610 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5615 while ((c = *++p) != '\0') {
5622 if (flags & EXP_VARTILDE)
5632 if (*name == '\0') {
5633 home = lookupvar("HOME");
5635 pw = getpwnam(name);
5640 if (!home || !*home)
5643 startloc = expdest - (char *)stackblock();
5644 strtodest(home, SQSYNTAX, quotes);
5645 recordregion(startloc, expdest - (char *)stackblock(), 0);
5653 * Execute a command inside back quotes. If it's a builtin command, we
5654 * want to save its output in a block obtained from malloc. Otherwise
5655 * we fork off a subprocess and get the output of the command via a pipe.
5656 * Should be called with interrupts off.
5658 struct backcmd { /* result of evalbackcmd */
5659 int fd; /* file descriptor to read from */
5660 int nleft; /* number of chars in buffer */
5661 char *buf; /* buffer */
5662 struct job *jp; /* job structure for command */
5665 /* These forward decls are needed to use "eval" code for backticks handling: */
5666 static uint8_t back_exitstatus; /* exit status of backquoted command */
5667 #define EV_EXIT 01 /* exit after evaluating tree */
5668 static void evaltree(union node *, int);
5670 static void FAST_FUNC
5671 evalbackcmd(union node *n, struct backcmd *result)
5682 saveherefd = herefd;
5690 ash_msg_and_raise_error("pipe call failed");
5691 jp = makejob(/*n,*/ 1);
5692 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5697 copyfd(pip[1], 1 | COPYFD_EXACT);
5701 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5705 result->fd = pip[0];
5708 herefd = saveherefd;
5710 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5711 result->fd, result->buf, result->nleft, result->jp));
5715 * Expand stuff in backwards quotes.
5718 expbackq(union node *cmd, int quoted, int quotes)
5726 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5727 struct stackmark smark;
5730 setstackmark(&smark);
5732 startloc = dest - (char *)stackblock();
5734 evalbackcmd(cmd, &in);
5735 popstackmark(&smark);
5742 memtodest(p, i, syntax, quotes);
5746 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5747 TRACE(("expbackq: read returns %d\n", i));
5756 back_exitstatus = waitforjob(in.jp);
5760 /* Eat all trailing newlines */
5762 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5767 recordregion(startloc, dest - (char *)stackblock(), 0);
5768 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5769 (dest - (char *)stackblock()) - startloc,
5770 (dest - (char *)stackblock()) - startloc,
5771 stackblock() + startloc));
5774 #if ENABLE_SH_MATH_SUPPORT
5776 * Expand arithmetic expression. Backup to start of expression,
5777 * evaluate, place result in (backed up) result, adjust string position.
5790 * This routine is slightly over-complicated for
5791 * efficiency. Next we scan backwards looking for the
5792 * start of arithmetic.
5794 start = stackblock();
5801 while ((unsigned char)*p != CTLARI) {
5805 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5810 esc = esclen(start, p);
5820 removerecordregions(begoff);
5827 rmescapes(p + 2, 0);
5829 len = cvtnum(ash_arith(p + 2));
5832 recordregion(begoff, begoff + len, 0);
5836 /* argstr needs it */
5837 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5840 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5841 * characters to allow for further processing. Otherwise treat
5842 * $@ like $* since no splitting will be performed.
5844 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5845 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5846 * for correct expansion of "B=$A" word.
5849 argstr(char *p, int flags, struct strlist *var_str_list)
5851 static const char spclchars[] ALIGN1 = {
5859 CTLBACKQ | CTLQUOTE,
5860 #if ENABLE_SH_MATH_SUPPORT
5865 const char *reject = spclchars;
5866 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5867 int breakall = flags & EXP_WORD;
5872 if (!(flags & EXP_VARTILDE)) {
5874 } else if (flags & EXP_VARTILDE2) {
5879 if (flags & EXP_TILDE) {
5882 flags &= ~EXP_TILDE;
5885 if (*q == CTLESC && (flags & EXP_QWORD))
5888 p = exptilde(p, q, flags);
5891 startloc = expdest - (char *)stackblock();
5895 length += strcspn(p + length, reject);
5899 #if ENABLE_SH_MATH_SUPPORT
5903 /* c == '=' || c == ':' || c == CTLENDARI */
5909 expdest = stack_nputstr(p, length, expdest);
5910 newloc = expdest - (char *)stackblock();
5911 if (breakall && !inquotes && newloc > startloc) {
5912 recordregion(startloc, newloc, 0);
5923 if (flags & EXP_VARTILDE2) {
5927 flags |= EXP_VARTILDE2;
5932 * sort of a hack - expand tildes in variable
5933 * assignments (after the first '=' and after ':'s).
5942 case CTLENDVAR: /* ??? */
5945 /* "$@" syntax adherence hack */
5947 && memcmp(p, dolatstr, 4) == 0
5948 && ( p[4] == CTLQUOTEMARK
5949 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5952 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
5955 inquotes = !inquotes;
5968 p = evalvar(p, flags, var_str_list);
5972 case CTLBACKQ|CTLQUOTE:
5973 expbackq(argbackq->n, c, quotes);
5974 argbackq = argbackq->next;
5976 #if ENABLE_SH_MATH_SUPPORT
5989 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
5992 // This commented out code was added by James Simmons <jsimmons@infradead.org>
5993 // as part of a larger change when he added support for ${var/a/b}.
5994 // However, it broke # and % operators:
5998 //echo ${var#ab} abcdcd abcdcd
5999 //echo ${var##ab} abcdcd abcdcd
6000 //echo ${var#a*b} abcdcd ababcdcd (!)
6001 //echo ${var##a*b} cdcd cdcd
6002 //echo ${var#?} babcdcd ababcdcd (!)
6003 //echo ${var##?} babcdcd babcdcd
6004 //echo ${var#*} ababcdcd babcdcd (!)
6006 //echo ${var%cd} ababcd ababcd
6007 //echo ${var%%cd} ababcd abab (!)
6008 //echo ${var%c*d} ababcd ababcd
6009 //echo ${var%%c*d} abab ababcdcd (!)
6010 //echo ${var%?} ababcdc ababcdc
6011 //echo ${var%%?} ababcdc ababcdcd (!)
6012 //echo ${var%*} ababcdcd ababcdcd
6015 // Commenting it back out helped. Remove it completely if it really
6018 char *loc, *loc2; //, *full;
6024 int match; // = strlen(str);
6025 const char *s = loc2;
6032 match = pmatch(str, s); // this line was deleted
6034 // // chop off end if its '*'
6035 // full = strrchr(str, '*');
6036 // if (full && full != str)
6039 // // If str starts with '*' replace with s.
6040 // if ((*str == '*') && strlen(s) >= match) {
6041 // full = xstrdup(s);
6042 // strncpy(full+strlen(s)-match+1, str+1, match-1);
6044 // full = xstrndup(str, match);
6045 // match = strncmp(s, full, strlen(full));
6049 if (match) // if (!match)
6051 if (quotes && (unsigned char)*loc == CTLESC)
6060 scanright(char *startp, char *rmesc, char *rmescend, char *pattern, int quotes, int match_at_start)
6062 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6063 int try2optimize = match_at_start;
6069 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6070 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6071 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6073 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6074 * and on each iteration they go back two/one char until they reach the beginning.
6075 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6077 /* TODO: document in what other circumstances we are called. */
6079 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6082 const char *s = loc2;
6083 if (match_at_start) {
6087 match = pmatch(pattern, s);
6088 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6092 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6094 /* Maybe we can optimize this:
6095 * if pattern ends with unescaped *, we can avoid checking
6096 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6097 * it wont match truncated "raw_value_of_" strings too.
6099 unsigned plen = strlen(pattern);
6100 /* Does it end with "*"? */
6101 if (plen != 0 && pattern[--plen] == '*') {
6102 /* "xxxx*" is not escaped */
6103 /* "xxx\*" is escaped */
6104 /* "xx\\*" is not escaped */
6105 /* "x\\\*" is escaped */
6107 while (plen != 0 && pattern[--plen] == '\\')
6110 break; /* ends with unescaped "*" */
6118 esc = esclen(startp, loc);
6129 static void varunset(const char *, const char *, const char *, int) NORETURN;
6131 varunset(const char *end, const char *var, const char *umsg, int varflags)
6137 msg = "parameter not set";
6139 if ((unsigned char)*end == CTLENDVAR) {
6140 if (varflags & VSNUL)
6146 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6149 #if ENABLE_ASH_BASH_COMPAT
6151 parse_sub_pattern(char *arg, int inquotes)
6153 char *idx, *repl = NULL;
6162 /* Only the first '/' seen is our separator */
6169 if (!inquotes && c == '\\' && arg[1] == '\\')
6170 arg++; /* skip both \\, not just first one */
6177 #endif /* ENABLE_ASH_BASH_COMPAT */
6180 subevalvar(char *p, char *str, int strloc, int subtype,
6181 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6183 struct nodelist *saveargbackq = argbackq;
6186 char *rmesc, *rmescend;
6187 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6188 IF_ASH_BASH_COMPAT(char null = '\0';)
6189 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6190 int saveherefd = herefd;
6191 int amount, workloc, resetloc;
6193 char *(*scan)(char*, char*, char*, char*, int, int);
6196 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6198 STPUTC('\0', expdest);
6199 herefd = saveherefd;
6200 argbackq = saveargbackq;
6201 startp = (char *)stackblock() + startloc;
6205 setvar(str, startp, 0);
6206 amount = startp - expdest;
6207 STADJUST(amount, expdest);
6210 #if ENABLE_ASH_BASH_COMPAT
6212 loc = str = stackblock() + strloc;
6213 /* Read POS in ${var:POS:LEN} */
6214 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6215 len = str - startp - 1;
6217 /* *loc != '\0', guaranteed by parser */
6221 /* Adjust the length by the number of escapes */
6222 for (ptr = startp; ptr < (str - 1); ptr++) {
6223 if ((unsigned char)*ptr == CTLESC) {
6231 if (*loc++ == ':') {
6235 /* Skip POS in ${var:POS:LEN} */
6237 while (*loc && *loc != ':') {
6239 * bash complains on: var=qwe; echo ${var:1a:123}
6241 ash_msg_and_raise_error(msg_illnum, str);
6245 if (*loc++ == ':') {
6249 if (pos >= orig_len) {
6253 if (len > (orig_len - pos))
6254 len = orig_len - pos;
6256 for (str = startp; pos; str++, pos--) {
6257 if (quotes && (unsigned char)*str == CTLESC)
6260 for (loc = startp; len; len--) {
6261 if (quotes && (unsigned char)*str == CTLESC)
6266 amount = loc - expdest;
6267 STADJUST(amount, expdest);
6272 varunset(p, str, startp, varflags);
6275 resetloc = expdest - (char *)stackblock();
6277 /* We'll comeback here if we grow the stack while handling
6278 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6279 * stack will need rebasing, and we'll need to remove our work
6282 IF_ASH_BASH_COMPAT(restart:)
6284 amount = expdest - ((char *)stackblock() + resetloc);
6285 STADJUST(-amount, expdest);
6286 startp = (char *)stackblock() + startloc;
6289 rmescend = (char *)stackblock() + strloc;
6291 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6292 if (rmesc != startp) {
6294 startp = (char *)stackblock() + startloc;
6298 str = (char *)stackblock() + strloc;
6299 preglob(str, varflags & VSQUOTE, 0);
6300 workloc = expdest - (char *)stackblock();
6302 #if ENABLE_ASH_BASH_COMPAT
6303 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6307 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6312 /* If there's no pattern to match, return the expansion unmolested */
6321 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6323 /* No match, advance */
6324 char *restart_detect = stackblock();
6326 STPUTC(*idx, expdest);
6327 if (quotes && (unsigned char)*idx == CTLESC) {
6330 STPUTC(*idx, expdest);
6332 if (stackblock() != restart_detect)
6337 /* continue; - prone to quadratic behavior, smarter code: */
6340 if (str[0] == '*') {
6341 /* Pattern is "*foo". If "*foo" does not match "long_string",
6342 * it would never match "ong_string" etc, no point in trying.
6349 if (subtype == VSREPLACEALL) {
6351 if (quotes && (unsigned char)*idx == CTLESC)
6360 for (loc = repl; *loc; loc++) {
6361 char *restart_detect = stackblock();
6362 STPUTC(*loc, expdest);
6363 if (stackblock() != restart_detect)
6368 if (subtype == VSREPLACE) {
6370 char *restart_detect = stackblock();
6371 STPUTC(*idx, expdest);
6372 if (stackblock() != restart_detect)
6381 /* We've put the replaced text into a buffer at workloc, now
6382 * move it to the right place and adjust the stack.
6384 startp = stackblock() + startloc;
6385 STPUTC('\0', expdest);
6386 memmove(startp, stackblock() + workloc, len);
6387 startp[len++] = '\0';
6388 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6389 STADJUST(-amount, expdest);
6392 #endif /* ENABLE_ASH_BASH_COMPAT */
6394 subtype -= VSTRIMRIGHT;
6396 if (subtype < 0 || subtype > 7)
6399 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6400 zero = subtype >> 1;
6401 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6402 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6404 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6407 memmove(startp, loc, str - loc);
6408 loc = startp + (str - loc) - 1;
6411 amount = loc - expdest;
6412 STADJUST(amount, expdest);
6418 * Add the value of a specialized variable to the stack string.
6419 * name parameter (examples):
6420 * ash -c 'echo $1' name:'1='
6421 * ash -c 'echo $qwe' name:'qwe='
6422 * ash -c 'echo $$' name:'$='
6423 * ash -c 'echo ${$}' name:'$='
6424 * ash -c 'echo ${$##q}' name:'$=q'
6425 * ash -c 'echo ${#$}' name:'$='
6426 * note: examples with bad shell syntax:
6427 * ash -c 'echo ${#$1}' name:'$=1'
6428 * ash -c 'echo ${#1#}' name:'1=#'
6430 static NOINLINE ssize_t
6431 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6438 int subtype = varflags & VSTYPE;
6439 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6440 int quoted = varflags & VSQUOTE;
6441 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6451 num = shellparam.nparam;
6459 goto check_1char_name;
6461 expdest = makestrspace(NOPTS, expdest);
6462 for (i = NOPTS - 1; i >= 0; i--) {
6464 USTPUTC(optletters(i), expdest);
6470 /* handles cases similar to ${#$1} */
6471 if (name[2] != '\0')
6472 raise_error_syntax("bad substitution");
6479 if (quoted && (flags & EXP_FULL)) {
6480 /* note: this is not meant as PEOF value */
6481 sep = 1 << CHAR_BIT;
6486 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6487 i = SIT(sep, syntax);
6488 if (quotes && (i == CCTL || i == CBACK))
6494 while ((p = *ap++) != NULL) {
6497 partlen = strlen(p);
6500 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6501 memtodest(p, partlen, syntax, quotes);
6507 if (subtype == VSPLUS || subtype == VSLENGTH) {
6513 /* note: may put NUL despite sep != 0
6514 * (see sep = 1 << CHAR_BIT above) */
6520 } /* case '@' and '*' */
6531 num = atoi(name); /* number(name) fails on ${N#str} etc */
6532 if (num < 0 || num > shellparam.nparam)
6534 p = num ? shellparam.p[num - 1] : arg0;
6537 /* NB: name has form "VAR=..." */
6539 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6540 * which should be considered before we check variables. */
6542 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6546 str = var_str_list->text;
6547 eq = strchr(str, '=');
6548 if (!eq) /* stop at first non-assignment */
6551 if (name_len == (unsigned)(eq - str)
6552 && strncmp(str, name, name_len) == 0
6555 /* goto value; - WRONG! */
6556 /* think "A=1 A=2 B=$A" */
6558 var_str_list = var_str_list->next;
6559 } while (var_str_list);
6563 p = lookupvar(name);
6569 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6570 memtodest(p, len, syntax, quotes);
6574 if (subtype == VSPLUS || subtype == VSLENGTH)
6575 STADJUST(-len, expdest);
6580 * Expand a variable, and return a pointer to the next character in the
6584 evalvar(char *p, int flags, struct strlist *var_str_list)
6595 varflags = (unsigned char) *p++;
6596 subtype = varflags & VSTYPE;
6597 quoted = varflags & VSQUOTE;
6599 easy = (!quoted || (*var == '@' && shellparam.nparam));
6600 startloc = expdest - (char *)stackblock();
6601 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6604 varlen = varvalue(var, varflags, flags, var_str_list);
6605 if (varflags & VSNUL)
6608 if (subtype == VSPLUS) {
6609 varlen = -1 - varlen;
6613 if (subtype == VSMINUS) {
6617 p, flags | EXP_TILDE |
6618 (quoted ? EXP_QWORD : EXP_WORD),
6628 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6630 if (subevalvar(p, var, /* strloc: */ 0,
6631 subtype, startloc, varflags,
6637 * Remove any recorded regions beyond
6640 removerecordregions(startloc);
6650 if (varlen < 0 && uflag)
6651 varunset(p, var, 0, 0);
6653 if (subtype == VSLENGTH) {
6654 cvtnum(varlen > 0 ? varlen : 0);
6658 if (subtype == VSNORMAL) {
6669 case VSTRIMRIGHTMAX:
6670 #if ENABLE_ASH_BASH_COMPAT
6683 * Terminate the string and start recording the pattern
6686 STPUTC('\0', expdest);
6687 patloc = expdest - (char *)stackblock();
6688 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6690 //TODO: | EXP_REDIR too? All other such places do it too
6691 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6694 int amount = expdest - (
6695 (char *)stackblock() + patloc - 1
6697 STADJUST(-amount, expdest);
6699 /* Remove any recorded regions beyond start of variable */
6700 removerecordregions(startloc);
6702 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6706 if (subtype != VSNORMAL) { /* skip to end of alternative */
6709 unsigned char c = *p++;
6712 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6714 argbackq = argbackq->next;
6715 } else if (c == CTLVAR) {
6716 if ((*p++ & VSTYPE) != VSNORMAL)
6718 } else if (c == CTLENDVAR) {
6728 * Break the argument string into pieces based upon IFS and add the
6729 * strings to the argument list. The regions of the string to be
6730 * searched for IFS characters have been stored by recordregion.
6733 ifsbreakup(char *string, struct arglist *arglist)
6735 struct ifsregion *ifsp;
6740 const char *ifs, *realifs;
6745 if (ifslastp != NULL) {
6748 realifs = ifsset() ? ifsval() : defifs;
6751 p = string + ifsp->begoff;
6752 nulonly = ifsp->nulonly;
6753 ifs = nulonly ? nullstr : realifs;
6755 while (p < string + ifsp->endoff) {
6757 if ((unsigned char)*p == CTLESC)
6759 if (!strchr(ifs, *p)) {
6764 ifsspc = (strchr(defifs, *p) != NULL);
6765 /* Ignore IFS whitespace at start */
6766 if (q == start && ifsspc) {
6772 sp = stzalloc(sizeof(*sp));
6774 *arglist->lastp = sp;
6775 arglist->lastp = &sp->next;
6779 if (p >= string + ifsp->endoff) {
6783 if ((unsigned char)*p == CTLESC)
6785 if (strchr(ifs, *p) == NULL) {
6789 if (strchr(defifs, *p) == NULL) {
6804 } while (ifsp != NULL);
6813 sp = stzalloc(sizeof(*sp));
6815 *arglist->lastp = sp;
6816 arglist->lastp = &sp->next;
6822 struct ifsregion *p;
6827 struct ifsregion *ifsp;
6833 ifsfirst.next = NULL;
6838 * Add a file name to the list.
6841 addfname(const char *name)
6845 sp = stzalloc(sizeof(*sp));
6846 sp->text = ststrdup(name);
6848 exparg.lastp = &sp->next;
6851 static char *expdir;
6854 * Do metacharacter (i.e. *, ?, [...]) expansion.
6857 expmeta(char *enddir, char *name)
6872 for (p = name; *p; p++) {
6873 if (*p == '*' || *p == '?')
6875 else if (*p == '[') {
6882 if (*q == '/' || *q == '\0')
6889 } else if (*p == '\\')
6891 else if (*p == '/') {
6898 if (metaflag == 0) { /* we've reached the end of the file name */
6899 if (enddir != expdir)
6907 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6918 } while (p < start);
6920 if (enddir == expdir) {
6922 } else if (enddir == expdir + 1 && *expdir == '/') {
6931 if (enddir != expdir)
6933 if (*endname == 0) {
6945 while (!pending_int && (dp = readdir(dirp)) != NULL) {
6946 if (dp->d_name[0] == '.' && !matchdot)
6948 if (pmatch(start, dp->d_name)) {
6950 strcpy(enddir, dp->d_name);
6953 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6956 expmeta(p, endname);
6965 static struct strlist *
6966 msort(struct strlist *list, int len)
6968 struct strlist *p, *q = NULL;
6969 struct strlist **lpp;
6977 for (n = half; --n >= 0;) {
6981 q->next = NULL; /* terminate first half of list */
6982 q = msort(list, half); /* sort first half of list */
6983 p = msort(p, len - half); /* sort second half */
6986 #if ENABLE_LOCALE_SUPPORT
6987 if (strcoll(p->text, q->text) < 0)
6989 if (strcmp(p->text, q->text) < 0)
7013 * Sort the results of file name expansion. It calculates the number of
7014 * strings to sort and then calls msort (short for merge sort) to do the
7017 static struct strlist *
7018 expsort(struct strlist *str)
7024 for (sp = str; sp; sp = sp->next)
7026 return msort(str, len);
7030 expandmeta(struct strlist *str /*, int flag*/)
7032 static const char metachars[] ALIGN1 = {
7035 /* TODO - EXP_REDIR */
7038 struct strlist **savelastp;
7044 if (!strpbrk(str->text, metachars))
7046 savelastp = exparg.lastp;
7049 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7051 int i = strlen(str->text);
7052 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7060 if (exparg.lastp == savelastp) {
7065 *exparg.lastp = str;
7066 rmescapes(str->text, 0);
7067 exparg.lastp = &str->next;
7069 *exparg.lastp = NULL;
7070 *savelastp = sp = expsort(*savelastp);
7071 while (sp->next != NULL)
7073 exparg.lastp = &sp->next;
7080 * Perform variable substitution and command substitution on an argument,
7081 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7082 * perform splitting and file name expansion. When arglist is NULL, perform
7083 * here document expansion.
7086 expandarg(union node *arg, struct arglist *arglist, int flag)
7091 argbackq = arg->narg.backquote;
7092 STARTSTACKSTR(expdest);
7093 ifsfirst.next = NULL;
7095 argstr(arg->narg.text, flag,
7096 /* var_str_list: */ arglist ? arglist->list : NULL);
7097 p = _STPUTC('\0', expdest);
7099 if (arglist == NULL) {
7100 return; /* here document expanded */
7102 p = grabstackstr(p);
7103 exparg.lastp = &exparg.list;
7107 if (flag & EXP_FULL) {
7108 ifsbreakup(p, &exparg);
7109 *exparg.lastp = NULL;
7110 exparg.lastp = &exparg.list;
7111 expandmeta(exparg.list /*, flag*/);
7113 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7115 sp = stzalloc(sizeof(*sp));
7118 exparg.lastp = &sp->next;
7122 *exparg.lastp = NULL;
7124 *arglist->lastp = exparg.list;
7125 arglist->lastp = exparg.lastp;
7130 * Expand shell variables and backquotes inside a here document.
7133 expandhere(union node *arg, int fd)
7136 expandarg(arg, (struct arglist *)NULL, 0);
7137 full_write(fd, stackblock(), expdest - (char *)stackblock());
7141 * Returns true if the pattern matches the string.
7144 patmatch(char *pattern, const char *string)
7146 return pmatch(preglob(pattern, 0, 0), string);
7150 * See if a pattern matches in a case statement.
7153 casematch(union node *pattern, char *val)
7155 struct stackmark smark;
7158 setstackmark(&smark);
7159 argbackq = pattern->narg.backquote;
7160 STARTSTACKSTR(expdest);
7162 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7163 /* var_str_list: */ NULL);
7164 STACKSTRNUL(expdest);
7165 result = patmatch(stackblock(), val);
7166 popstackmark(&smark);
7171 /* ============ find_command */
7175 int (*builtin)(int, char **) FAST_FUNC;
7176 /* unsigned flags; */
7178 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7179 /* "regular" builtins always take precedence over commands,
7180 * regardless of PATH=....%builtin... position */
7181 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7182 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7185 smallint cmdtype; /* CMDxxx */
7188 /* index >= 0 for commands without path (slashes) */
7189 /* (TODO: what exactly does the value mean? PATH position?) */
7190 /* index == -1 for commands with slashes */
7191 /* index == (-2 - applet_no) for NOFORK applets */
7192 const struct builtincmd *cmd;
7193 struct funcnode *func;
7196 /* values of cmdtype */
7197 #define CMDUNKNOWN -1 /* no entry in table for command */
7198 #define CMDNORMAL 0 /* command is an executable program */
7199 #define CMDFUNCTION 1 /* command is a shell function */
7200 #define CMDBUILTIN 2 /* command is a shell builtin */
7202 /* action to find_command() */
7203 #define DO_ERR 0x01 /* prints errors */
7204 #define DO_ABS 0x02 /* checks absolute paths */
7205 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7206 #define DO_ALTPATH 0x08 /* using alternate path */
7207 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7209 static void find_command(char *, struct cmdentry *, int, const char *);
7212 /* ============ Hashing commands */
7215 * When commands are first encountered, they are entered in a hash table.
7216 * This ensures that a full path search will not have to be done for them
7217 * on each invocation.
7219 * We should investigate converting to a linear search, even though that
7220 * would make the command name "hash" a misnomer.
7224 struct tblentry *next; /* next entry in hash chain */
7225 union param param; /* definition of builtin function */
7226 smallint cmdtype; /* CMDxxx */
7227 char rehash; /* if set, cd done since entry created */
7228 char cmdname[1]; /* name of command */
7231 static struct tblentry **cmdtable;
7232 #define INIT_G_cmdtable() do { \
7233 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7236 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7240 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7244 #if ENABLE_FEATURE_SH_STANDALONE
7245 if (applet_no >= 0) {
7246 if (APPLET_IS_NOEXEC(applet_no)) {
7250 run_applet_no_and_exit(applet_no, argv);
7252 /* re-exec ourselves with the new arguments */
7253 execve(bb_busybox_exec_path, argv, envp);
7254 /* If they called chroot or otherwise made the binary no longer
7255 * executable, fall through */
7262 execve(cmd, argv, envp);
7263 } while (errno == EINTR);
7265 execve(cmd, argv, envp);
7271 if (errno == ENOEXEC) {
7275 for (ap = argv; *ap; ap++)
7277 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7279 ap[0] = cmd = (char *)DEFAULT_SHELL;
7282 while ((*ap++ = *argv++) != NULL)
7291 * Exec a program. Never returns. If you change this routine, you may
7292 * have to change the find_command routine as well.
7294 static void shellexec(char **, const char *, int) NORETURN;
7296 shellexec(char **argv, const char *path, int idx)
7302 #if ENABLE_FEATURE_SH_STANDALONE
7306 clearredir(/*drop:*/ 1);
7307 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7308 if (strchr(argv[0], '/') != NULL
7309 #if ENABLE_FEATURE_SH_STANDALONE
7310 || (applet_no = find_applet_by_name(argv[0])) >= 0
7313 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7317 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7318 if (--idx < 0 && pathopt == NULL) {
7319 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7320 if (errno != ENOENT && errno != ENOTDIR)
7327 /* Map to POSIX errors */
7339 exitstatus = exerrno;
7340 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7341 argv[0], e, suppress_int));
7342 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7347 printentry(struct tblentry *cmdp)
7353 idx = cmdp->param.index;
7356 name = path_advance(&path, cmdp->cmdname);
7358 } while (--idx >= 0);
7359 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7363 * Clear out command entries. The argument specifies the first entry in
7364 * PATH which has changed.
7367 clearcmdentry(int firstchange)
7369 struct tblentry **tblp;
7370 struct tblentry **pp;
7371 struct tblentry *cmdp;
7374 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7376 while ((cmdp = *pp) != NULL) {
7377 if ((cmdp->cmdtype == CMDNORMAL &&
7378 cmdp->param.index >= firstchange)
7379 || (cmdp->cmdtype == CMDBUILTIN &&
7380 builtinloc >= firstchange)
7393 * Locate a command in the command hash table. If "add" is nonzero,
7394 * add the command to the table if it is not already present. The
7395 * variable "lastcmdentry" is set to point to the address of the link
7396 * pointing to the entry, so that delete_cmd_entry can delete the
7399 * Interrupts must be off if called with add != 0.
7401 static struct tblentry **lastcmdentry;
7403 static struct tblentry *
7404 cmdlookup(const char *name, int add)
7406 unsigned int hashval;
7408 struct tblentry *cmdp;
7409 struct tblentry **pp;
7412 hashval = (unsigned char)*p << 4;
7414 hashval += (unsigned char)*p++;
7416 pp = &cmdtable[hashval % CMDTABLESIZE];
7417 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7418 if (strcmp(cmdp->cmdname, name) == 0)
7422 if (add && cmdp == NULL) {
7423 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7425 /* + 1 - already done because
7426 * tblentry::cmdname is char[1] */);
7427 /*cmdp->next = NULL; - ckzalloc did it */
7428 cmdp->cmdtype = CMDUNKNOWN;
7429 strcpy(cmdp->cmdname, name);
7436 * Delete the command entry returned on the last lookup.
7439 delete_cmd_entry(void)
7441 struct tblentry *cmdp;
7444 cmdp = *lastcmdentry;
7445 *lastcmdentry = cmdp->next;
7446 if (cmdp->cmdtype == CMDFUNCTION)
7447 freefunc(cmdp->param.func);
7453 * Add a new command entry, replacing any existing command entry for
7454 * the same name - except special builtins.
7457 addcmdentry(char *name, struct cmdentry *entry)
7459 struct tblentry *cmdp;
7461 cmdp = cmdlookup(name, 1);
7462 if (cmdp->cmdtype == CMDFUNCTION) {
7463 freefunc(cmdp->param.func);
7465 cmdp->cmdtype = entry->cmdtype;
7466 cmdp->param = entry->u;
7470 static int FAST_FUNC
7471 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7473 struct tblentry **pp;
7474 struct tblentry *cmdp;
7476 struct cmdentry entry;
7479 if (nextopt("r") != '\0') {
7484 if (*argptr == NULL) {
7485 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7486 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7487 if (cmdp->cmdtype == CMDNORMAL)
7495 while ((name = *argptr) != NULL) {
7496 cmdp = cmdlookup(name, 0);
7498 && (cmdp->cmdtype == CMDNORMAL
7499 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7503 find_command(name, &entry, DO_ERR, pathval());
7504 if (entry.cmdtype == CMDUNKNOWN)
7512 * Called when a cd is done. Marks all commands so the next time they
7513 * are executed they will be rehashed.
7518 struct tblentry **pp;
7519 struct tblentry *cmdp;
7521 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7522 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7523 if (cmdp->cmdtype == CMDNORMAL
7524 || (cmdp->cmdtype == CMDBUILTIN
7525 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7535 * Fix command hash table when PATH changed.
7536 * Called before PATH is changed. The argument is the new value of PATH;
7537 * pathval() still returns the old value at this point.
7538 * Called with interrupts off.
7540 static void FAST_FUNC
7541 changepath(const char *new)
7549 firstchange = 9999; /* assume no change */
7555 if ((*old == '\0' && *new == ':')
7556 || (*old == ':' && *new == '\0')
7560 old = new; /* ignore subsequent differences */
7564 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7571 if (builtinloc < 0 && idx_bltin >= 0)
7572 builtinloc = idx_bltin; /* zap builtins */
7573 if (builtinloc >= 0 && idx_bltin < 0)
7575 clearcmdentry(firstchange);
7576 builtinloc = idx_bltin;
7591 #define TENDBQUOTE 12
7608 typedef smallint token_id_t;
7610 /* first char is indicating which tokens mark the end of a list */
7611 static const char *const tokname_array[] = {
7625 #define KWDOFFSET 13
7626 /* the following are keywords */
7645 /* Wrapper around strcmp for qsort/bsearch/... */
7647 pstrcmp(const void *a, const void *b)
7649 return strcmp((char*) a, (*(char**) b) + 1);
7652 static const char *const *
7653 findkwd(const char *s)
7655 return bsearch(s, tokname_array + KWDOFFSET,
7656 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7657 sizeof(tokname_array[0]), pstrcmp);
7661 * Locate and print what a word is...
7664 describe_command(char *command, int describe_command_verbose)
7666 struct cmdentry entry;
7667 struct tblentry *cmdp;
7668 #if ENABLE_ASH_ALIAS
7669 const struct alias *ap;
7671 const char *path = pathval();
7673 if (describe_command_verbose) {
7677 /* First look at the keywords */
7678 if (findkwd(command)) {
7679 out1str(describe_command_verbose ? " is a shell keyword" : command);
7683 #if ENABLE_ASH_ALIAS
7684 /* Then look at the aliases */
7685 ap = lookupalias(command, 0);
7687 if (!describe_command_verbose) {
7692 out1fmt(" is an alias for %s", ap->val);
7696 /* Then check if it is a tracked alias */
7697 cmdp = cmdlookup(command, 0);
7699 entry.cmdtype = cmdp->cmdtype;
7700 entry.u = cmdp->param;
7702 /* Finally use brute force */
7703 find_command(command, &entry, DO_ABS, path);
7706 switch (entry.cmdtype) {
7708 int j = entry.u.index;
7714 p = path_advance(&path, command);
7718 if (describe_command_verbose) {
7720 (cmdp ? " a tracked alias for" : nullstr), p
7729 if (describe_command_verbose) {
7730 out1str(" is a shell function");
7737 if (describe_command_verbose) {
7738 out1fmt(" is a %sshell builtin",
7739 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7740 "special " : nullstr
7748 if (describe_command_verbose) {
7749 out1str(": not found\n");
7758 static int FAST_FUNC
7759 typecmd(int argc UNUSED_PARAM, char **argv)
7765 /* type -p ... ? (we don't bother checking for 'p') */
7766 if (argv[1] && argv[1][0] == '-') {
7771 err |= describe_command(argv[i++], verbose);
7776 #if ENABLE_ASH_CMDCMD
7777 static int FAST_FUNC
7778 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7786 while ((c = nextopt("pvV")) != '\0')
7788 verify |= VERIFY_VERBOSE;
7790 verify |= VERIFY_BRIEF;
7795 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7796 if (verify && (*argptr != NULL)) {
7797 return describe_command(*argptr, verify - VERIFY_BRIEF);
7805 /* ============ eval.c */
7807 static int funcblocksize; /* size of structures in function */
7808 static int funcstringsize; /* size of strings in node */
7809 static void *funcblock; /* block to allocate function from */
7810 static char *funcstring; /* block to allocate strings from */
7812 /* flags in argument to evaltree */
7813 #define EV_EXIT 01 /* exit after evaluating tree */
7814 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7815 #define EV_BACKCMD 04 /* command executing within back quotes */
7817 static const uint8_t nodesize[N_NUMBER] = {
7818 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7819 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7820 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7821 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7822 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7823 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7824 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7825 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7826 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7827 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7828 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7829 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7830 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7831 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7832 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7833 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7834 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7835 #if ENABLE_ASH_BASH_COMPAT
7836 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7838 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7839 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7840 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7841 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7842 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7843 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7844 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7845 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7846 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7849 static void calcsize(union node *n);
7852 sizenodelist(struct nodelist *lp)
7855 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7862 calcsize(union node *n)
7866 funcblocksize += nodesize[n->type];
7869 calcsize(n->ncmd.redirect);
7870 calcsize(n->ncmd.args);
7871 calcsize(n->ncmd.assign);
7874 sizenodelist(n->npipe.cmdlist);
7879 calcsize(n->nredir.redirect);
7880 calcsize(n->nredir.n);
7887 calcsize(n->nbinary.ch2);
7888 calcsize(n->nbinary.ch1);
7891 calcsize(n->nif.elsepart);
7892 calcsize(n->nif.ifpart);
7893 calcsize(n->nif.test);
7896 funcstringsize += strlen(n->nfor.var) + 1;
7897 calcsize(n->nfor.body);
7898 calcsize(n->nfor.args);
7901 calcsize(n->ncase.cases);
7902 calcsize(n->ncase.expr);
7905 calcsize(n->nclist.body);
7906 calcsize(n->nclist.pattern);
7907 calcsize(n->nclist.next);
7911 sizenodelist(n->narg.backquote);
7912 funcstringsize += strlen(n->narg.text) + 1;
7913 calcsize(n->narg.next);
7916 #if ENABLE_ASH_BASH_COMPAT
7923 calcsize(n->nfile.fname);
7924 calcsize(n->nfile.next);
7928 calcsize(n->ndup.vname);
7929 calcsize(n->ndup.next);
7933 calcsize(n->nhere.doc);
7934 calcsize(n->nhere.next);
7937 calcsize(n->nnot.com);
7943 nodeckstrdup(char *s)
7945 char *rtn = funcstring;
7947 strcpy(funcstring, s);
7948 funcstring += strlen(s) + 1;
7952 static union node *copynode(union node *);
7954 static struct nodelist *
7955 copynodelist(struct nodelist *lp)
7957 struct nodelist *start;
7958 struct nodelist **lpp;
7963 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7964 (*lpp)->n = copynode(lp->n);
7966 lpp = &(*lpp)->next;
7973 copynode(union node *n)
7980 funcblock = (char *) funcblock + nodesize[n->type];
7984 new->ncmd.redirect = copynode(n->ncmd.redirect);
7985 new->ncmd.args = copynode(n->ncmd.args);
7986 new->ncmd.assign = copynode(n->ncmd.assign);
7989 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7990 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
7995 new->nredir.redirect = copynode(n->nredir.redirect);
7996 new->nredir.n = copynode(n->nredir.n);
8003 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8004 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8007 new->nif.elsepart = copynode(n->nif.elsepart);
8008 new->nif.ifpart = copynode(n->nif.ifpart);
8009 new->nif.test = copynode(n->nif.test);
8012 new->nfor.var = nodeckstrdup(n->nfor.var);
8013 new->nfor.body = copynode(n->nfor.body);
8014 new->nfor.args = copynode(n->nfor.args);
8017 new->ncase.cases = copynode(n->ncase.cases);
8018 new->ncase.expr = copynode(n->ncase.expr);
8021 new->nclist.body = copynode(n->nclist.body);
8022 new->nclist.pattern = copynode(n->nclist.pattern);
8023 new->nclist.next = copynode(n->nclist.next);
8027 new->narg.backquote = copynodelist(n->narg.backquote);
8028 new->narg.text = nodeckstrdup(n->narg.text);
8029 new->narg.next = copynode(n->narg.next);
8032 #if ENABLE_ASH_BASH_COMPAT
8039 new->nfile.fname = copynode(n->nfile.fname);
8040 new->nfile.fd = n->nfile.fd;
8041 new->nfile.next = copynode(n->nfile.next);
8045 new->ndup.vname = copynode(n->ndup.vname);
8046 new->ndup.dupfd = n->ndup.dupfd;
8047 new->ndup.fd = n->ndup.fd;
8048 new->ndup.next = copynode(n->ndup.next);
8052 new->nhere.doc = copynode(n->nhere.doc);
8053 new->nhere.fd = n->nhere.fd;
8054 new->nhere.next = copynode(n->nhere.next);
8057 new->nnot.com = copynode(n->nnot.com);
8060 new->type = n->type;
8065 * Make a copy of a parse tree.
8067 static struct funcnode *
8068 copyfunc(union node *n)
8073 funcblocksize = offsetof(struct funcnode, n);
8076 blocksize = funcblocksize;
8077 f = ckmalloc(blocksize + funcstringsize);
8078 funcblock = (char *) f + offsetof(struct funcnode, n);
8079 funcstring = (char *) f + blocksize;
8086 * Define a shell function.
8089 defun(char *name, union node *func)
8091 struct cmdentry entry;
8094 entry.cmdtype = CMDFUNCTION;
8095 entry.u.func = copyfunc(func);
8096 addcmdentry(name, &entry);
8100 /* Reasons for skipping commands (see comment on breakcmd routine) */
8101 #define SKIPBREAK (1 << 0)
8102 #define SKIPCONT (1 << 1)
8103 #define SKIPFUNC (1 << 2)
8104 #define SKIPFILE (1 << 3)
8105 #define SKIPEVAL (1 << 4)
8106 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8107 static int skipcount; /* number of levels to skip */
8108 static int funcnest; /* depth of function calls */
8109 static int loopnest; /* current loop nesting level */
8111 /* Forward decl way out to parsing code - dotrap needs it */
8112 static int evalstring(char *s, int mask);
8114 /* Called to execute a trap.
8115 * Single callsite - at the end of evaltree().
8116 * If we return non-zero, exaltree raises EXEXIT exception.
8118 * Perhaps we should avoid entering new trap handlers
8119 * while we are executing a trap handler. [is it a TODO?]
8128 savestatus = exitstatus;
8132 TRACE(("dotrap entered\n"));
8133 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8140 /* non-trapped SIGINT is handled separately by raise_interrupt,
8141 * don't upset it by resetting gotsig[SIGINT-1] */
8142 if (sig == SIGINT && !t)
8145 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8149 want_exexit = evalstring(t, SKIPEVAL);
8150 exitstatus = savestatus;
8152 TRACE(("dotrap returns %d\n", want_exexit));
8157 TRACE(("dotrap returns 0\n"));
8161 /* forward declarations - evaluation is fairly recursive business... */
8162 static void evalloop(union node *, int);
8163 static void evalfor(union node *, int);
8164 static void evalcase(union node *, int);
8165 static void evalsubshell(union node *, int);
8166 static void expredir(union node *);
8167 static void evalpipe(union node *, int);
8168 static void evalcommand(union node *, int);
8169 static int evalbltin(const struct builtincmd *, int, char **);
8170 static void prehash(union node *);
8173 * Evaluate a parse tree. The value is left in the global variable
8177 evaltree(union node *n, int flags)
8179 struct jmploc *volatile savehandler = exception_handler;
8180 struct jmploc jmploc;
8182 void (*evalfn)(union node *, int);
8186 SAVE_INT(int_level);
8189 TRACE(("evaltree(NULL) called\n"));
8192 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8194 exception_handler = &jmploc;
8196 int err = setjmp(jmploc.loc);
8198 /* if it was a signal, check for trap handlers */
8199 if (exception_type == EXSIG) {
8200 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8201 exception_type, err));
8204 /* continue on the way out */
8205 TRACE(("exception %d in evaltree, propagating err=%d\n",
8206 exception_type, err));
8207 exception_handler = savehandler;
8208 longjmp(exception_handler->loc, err);
8215 out1fmt("Node type = %d\n", n->type);
8220 evaltree(n->nnot.com, EV_TESTED);
8221 status = !exitstatus;
8224 expredir(n->nredir.redirect);
8225 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8227 evaltree(n->nredir.n, flags & EV_TESTED);
8228 status = exitstatus;
8230 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8233 evalfn = evalcommand;
8235 if (eflag && !(flags & EV_TESTED))
8247 evalfn = evalsubshell;
8260 #error NAND + 1 != NOR
8262 #if NOR + 1 != NSEMI
8263 #error NOR + 1 != NSEMI
8265 unsigned is_or = n->type - NAND;
8268 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8270 if (!exitstatus == is_or)
8283 evaltree(n->nif.test, EV_TESTED);
8286 if (exitstatus == 0) {
8290 if (n->nif.elsepart) {
8291 n = n->nif.elsepart;
8296 defun(n->narg.text, n->narg.next);
8300 exitstatus = status;
8305 exception_handler = savehandler;
8307 if (checkexit & exitstatus)
8308 evalskip |= SKIPEVAL;
8309 else if (pending_sig && dotrap())
8312 if (flags & EV_EXIT) {
8314 raise_exception(EXEXIT);
8317 RESTORE_INT(int_level);
8318 TRACE(("leaving evaltree (no interrupts)\n"));
8321 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8324 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8327 evalloop(union node *n, int flags)
8337 evaltree(n->nbinary.ch1, EV_TESTED);
8340 if (evalskip == SKIPCONT && --skipcount <= 0) {
8344 if (evalskip == SKIPBREAK && --skipcount <= 0)
8349 if (n->type != NWHILE)
8353 evaltree(n->nbinary.ch2, flags);
8354 status = exitstatus;
8359 exitstatus = status;
8363 evalfor(union node *n, int flags)
8365 struct arglist arglist;
8368 struct stackmark smark;
8370 setstackmark(&smark);
8371 arglist.list = NULL;
8372 arglist.lastp = &arglist.list;
8373 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8374 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8379 *arglist.lastp = NULL;
8384 for (sp = arglist.list; sp; sp = sp->next) {
8385 setvar(n->nfor.var, sp->text, 0);
8386 evaltree(n->nfor.body, flags);
8388 if (evalskip == SKIPCONT && --skipcount <= 0) {
8392 if (evalskip == SKIPBREAK && --skipcount <= 0)
8399 popstackmark(&smark);
8403 evalcase(union node *n, int flags)
8407 struct arglist arglist;
8408 struct stackmark smark;
8410 setstackmark(&smark);
8411 arglist.list = NULL;
8412 arglist.lastp = &arglist.list;
8413 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8415 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8416 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8417 if (casematch(patp, arglist.list->text)) {
8418 if (evalskip == 0) {
8419 evaltree(cp->nclist.body, flags);
8426 popstackmark(&smark);
8430 * Kick off a subshell to evaluate a tree.
8433 evalsubshell(union node *n, int flags)
8436 int backgnd = (n->type == NBACKGND);
8439 expredir(n->nredir.redirect);
8440 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8443 jp = makejob(/*n,*/ 1);
8444 if (forkshell(jp, n, backgnd) == 0) {
8449 flags &= ~EV_TESTED;
8451 redirect(n->nredir.redirect, 0);
8452 evaltreenr(n->nredir.n, flags);
8457 status = waitforjob(jp);
8458 exitstatus = status;
8463 * Compute the names of the files in a redirection list.
8465 static void fixredir(union node *, const char *, int);
8467 expredir(union node *n)
8471 for (redir = n; redir; redir = redir->nfile.next) {
8475 fn.lastp = &fn.list;
8476 switch (redir->type) {
8480 #if ENABLE_ASH_BASH_COMPAT
8485 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8486 #if ENABLE_ASH_BASH_COMPAT
8489 redir->nfile.expfname = fn.list->text;
8492 case NTOFD: /* >& */
8493 if (redir->ndup.vname) {
8494 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8495 if (fn.list == NULL)
8496 ash_msg_and_raise_error("redir error");
8497 #if ENABLE_ASH_BASH_COMPAT
8498 //FIXME: we used expandarg with different args!
8499 if (!isdigit_str9(fn.list->text)) {
8500 /* >&file, not >&fd */
8501 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8502 ash_msg_and_raise_error("redir error");
8504 goto store_expfname;
8507 fixredir(redir, fn.list->text, 1);
8515 * Evaluate a pipeline. All the processes in the pipeline are children
8516 * of the process creating the pipeline. (This differs from some versions
8517 * of the shell, which make the last process in a pipeline the parent
8521 evalpipe(union node *n, int flags)
8524 struct nodelist *lp;
8529 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8531 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8535 jp = makejob(/*n,*/ pipelen);
8537 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8541 if (pipe(pip) < 0) {
8543 ash_msg_and_raise_error("pipe call failed");
8546 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8559 evaltreenr(lp->n, flags);
8565 /* Don't want to trigger debugging */
8569 if (n->npipe.pipe_backgnd == 0) {
8570 exitstatus = waitforjob(jp);
8571 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8577 * Controls whether the shell is interactive or not.
8580 setinteractive(int on)
8582 static smallint is_interactive;
8584 if (++on == is_interactive)
8586 is_interactive = on;
8590 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8591 if (is_interactive > 1) {
8592 /* Looks like they want an interactive shell */
8593 static smallint did_banner;
8596 /* note: ash and hush share this string */
8597 out1fmt("\n\n%s %s\n"
8598 "Enter 'help' for a list of built-in commands."
8601 "built-in shell (ash)"
8615 setinteractive(iflag);
8617 #if ENABLE_FEATURE_EDITING_VI
8619 line_input_state->flags |= VI_MODE;
8621 line_input_state->flags &= ~VI_MODE;
8623 viflag = 0; /* forcibly keep the option off */
8627 static struct localvar *localvars;
8630 * Called after a function returns.
8631 * Interrupts must be off.
8636 struct localvar *lvp;
8639 while ((lvp = localvars) != NULL) {
8640 localvars = lvp->next;
8642 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8643 if (vp == NULL) { /* $- saved */
8644 memcpy(optlist, lvp->text, sizeof(optlist));
8645 free((char*)lvp->text);
8647 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8648 unsetvar(vp->var_text);
8651 vp->var_func(var_end(lvp->text));
8652 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8653 free((char*)vp->var_text);
8654 vp->flags = lvp->flags;
8655 vp->var_text = lvp->text;
8662 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8664 volatile struct shparam saveparam;
8665 struct localvar *volatile savelocalvars;
8666 struct jmploc *volatile savehandler;
8667 struct jmploc jmploc;
8670 saveparam = shellparam;
8671 savelocalvars = localvars;
8672 e = setjmp(jmploc.loc);
8677 savehandler = exception_handler;
8678 exception_handler = &jmploc;
8680 shellparam.malloced = 0;
8684 shellparam.nparam = argc - 1;
8685 shellparam.p = argv + 1;
8686 #if ENABLE_ASH_GETOPTS
8687 shellparam.optind = 1;
8688 shellparam.optoff = -1;
8690 evaltree(&func->n, flags & EV_TESTED);
8696 localvars = savelocalvars;
8697 freeparam(&shellparam);
8698 shellparam = saveparam;
8699 exception_handler = savehandler;
8701 evalskip &= ~SKIPFUNC;
8705 #if ENABLE_ASH_CMDCMD
8707 parse_command_args(char **argv, const char **path)
8720 if (c == '-' && !*cp) {
8727 *path = bb_default_path;
8730 /* run 'typecmd' for other options */
8741 * Make a variable a local variable. When a variable is made local, it's
8742 * value and flags are saved in a localvar structure. The saved values
8743 * will be restored when the shell function returns. We handle the name
8744 * "-" as a special case.
8749 struct localvar *lvp;
8754 lvp = ckzalloc(sizeof(struct localvar));
8755 if (LONE_DASH(name)) {
8757 p = ckmalloc(sizeof(optlist));
8758 lvp->text = memcpy(p, optlist, sizeof(optlist));
8763 vpp = hashvar(name);
8764 vp = *findvar(vpp, name);
8765 eq = strchr(name, '=');
8768 setvareq(name, VSTRFIXED);
8770 setvar(name, NULL, VSTRFIXED);
8771 vp = *vpp; /* the new variable */
8772 lvp->flags = VUNSET;
8774 lvp->text = vp->var_text;
8775 lvp->flags = vp->flags;
8776 vp->flags |= VSTRFIXED|VTEXTFIXED;
8782 lvp->next = localvars;
8788 * The "local" command.
8790 static int FAST_FUNC
8791 localcmd(int argc UNUSED_PARAM, char **argv)
8796 while ((name = *argv++) != NULL) {
8802 static int FAST_FUNC
8803 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8808 static int FAST_FUNC
8809 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8814 static int FAST_FUNC
8815 execcmd(int argc UNUSED_PARAM, char **argv)
8818 iflag = 0; /* exit on error */
8821 shellexec(argv + 1, pathval(), 0);
8827 * The return command.
8829 static int FAST_FUNC
8830 returncmd(int argc UNUSED_PARAM, char **argv)
8833 * If called outside a function, do what ksh does;
8834 * skip the rest of the file.
8836 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8837 return argv[1] ? number(argv[1]) : exitstatus;
8840 /* Forward declarations for builtintab[] */
8841 static int breakcmd(int, char **) FAST_FUNC;
8842 static int dotcmd(int, char **) FAST_FUNC;
8843 static int evalcmd(int, char **) FAST_FUNC;
8844 static int exitcmd(int, char **) FAST_FUNC;
8845 static int exportcmd(int, char **) FAST_FUNC;
8846 #if ENABLE_ASH_GETOPTS
8847 static int getoptscmd(int, char **) FAST_FUNC;
8849 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8850 static int helpcmd(int, char **) FAST_FUNC;
8852 #if ENABLE_SH_MATH_SUPPORT
8853 static int letcmd(int, char **) FAST_FUNC;
8855 static int readcmd(int, char **) FAST_FUNC;
8856 static int setcmd(int, char **) FAST_FUNC;
8857 static int shiftcmd(int, char **) FAST_FUNC;
8858 static int timescmd(int, char **) FAST_FUNC;
8859 static int trapcmd(int, char **) FAST_FUNC;
8860 static int umaskcmd(int, char **) FAST_FUNC;
8861 static int unsetcmd(int, char **) FAST_FUNC;
8862 static int ulimitcmd(int, char **) FAST_FUNC;
8864 #define BUILTIN_NOSPEC "0"
8865 #define BUILTIN_SPECIAL "1"
8866 #define BUILTIN_REGULAR "2"
8867 #define BUILTIN_SPEC_REG "3"
8868 #define BUILTIN_ASSIGN "4"
8869 #define BUILTIN_SPEC_ASSG "5"
8870 #define BUILTIN_REG_ASSG "6"
8871 #define BUILTIN_SPEC_REG_ASSG "7"
8873 /* Stubs for calling non-FAST_FUNC's */
8874 #if ENABLE_ASH_BUILTIN_ECHO
8875 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8877 #if ENABLE_ASH_BUILTIN_PRINTF
8878 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8880 #if ENABLE_ASH_BUILTIN_TEST
8881 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8884 /* Keep these in proper order since it is searched via bsearch() */
8885 static const struct builtincmd builtintab[] = {
8886 { BUILTIN_SPEC_REG "." , dotcmd },
8887 { BUILTIN_SPEC_REG ":" , truecmd },
8888 #if ENABLE_ASH_BUILTIN_TEST
8889 { BUILTIN_REGULAR "[" , testcmd },
8890 #if ENABLE_ASH_BASH_COMPAT
8891 { BUILTIN_REGULAR "[[" , testcmd },
8894 #if ENABLE_ASH_ALIAS
8895 { BUILTIN_REG_ASSG "alias" , aliascmd },
8898 { BUILTIN_REGULAR "bg" , fg_bgcmd },
8900 { BUILTIN_SPEC_REG "break" , breakcmd },
8901 { BUILTIN_REGULAR "cd" , cdcmd },
8902 { BUILTIN_NOSPEC "chdir" , cdcmd },
8903 #if ENABLE_ASH_CMDCMD
8904 { BUILTIN_REGULAR "command" , commandcmd },
8906 { BUILTIN_SPEC_REG "continue", breakcmd },
8907 #if ENABLE_ASH_BUILTIN_ECHO
8908 { BUILTIN_REGULAR "echo" , echocmd },
8910 { BUILTIN_SPEC_REG "eval" , evalcmd },
8911 { BUILTIN_SPEC_REG "exec" , execcmd },
8912 { BUILTIN_SPEC_REG "exit" , exitcmd },
8913 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
8914 { BUILTIN_REGULAR "false" , falsecmd },
8916 { BUILTIN_REGULAR "fg" , fg_bgcmd },
8918 #if ENABLE_ASH_GETOPTS
8919 { BUILTIN_REGULAR "getopts" , getoptscmd },
8921 { BUILTIN_NOSPEC "hash" , hashcmd },
8922 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8923 { BUILTIN_NOSPEC "help" , helpcmd },
8926 { BUILTIN_REGULAR "jobs" , jobscmd },
8927 { BUILTIN_REGULAR "kill" , killcmd },
8929 #if ENABLE_SH_MATH_SUPPORT
8930 { BUILTIN_NOSPEC "let" , letcmd },
8932 { BUILTIN_ASSIGN "local" , localcmd },
8933 #if ENABLE_ASH_BUILTIN_PRINTF
8934 { BUILTIN_REGULAR "printf" , printfcmd },
8936 { BUILTIN_NOSPEC "pwd" , pwdcmd },
8937 { BUILTIN_REGULAR "read" , readcmd },
8938 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8939 { BUILTIN_SPEC_REG "return" , returncmd },
8940 { BUILTIN_SPEC_REG "set" , setcmd },
8941 { BUILTIN_SPEC_REG "shift" , shiftcmd },
8942 #if ENABLE_ASH_BASH_COMPAT
8943 { BUILTIN_SPEC_REG "source" , dotcmd },
8945 #if ENABLE_ASH_BUILTIN_TEST
8946 { BUILTIN_REGULAR "test" , testcmd },
8948 { BUILTIN_SPEC_REG "times" , timescmd },
8949 { BUILTIN_SPEC_REG "trap" , trapcmd },
8950 { BUILTIN_REGULAR "true" , truecmd },
8951 { BUILTIN_NOSPEC "type" , typecmd },
8952 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
8953 { BUILTIN_REGULAR "umask" , umaskcmd },
8954 #if ENABLE_ASH_ALIAS
8955 { BUILTIN_REGULAR "unalias" , unaliascmd },
8957 { BUILTIN_SPEC_REG "unset" , unsetcmd },
8958 { BUILTIN_REGULAR "wait" , waitcmd },
8961 /* Should match the above table! */
8962 #define COMMANDCMD (builtintab + \
8964 1 * ENABLE_ASH_BUILTIN_TEST + \
8965 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8966 1 * ENABLE_ASH_ALIAS + \
8967 1 * ENABLE_ASH_JOB_CONTROL + \
8969 #define EXECCMD (builtintab + \
8971 1 * ENABLE_ASH_BUILTIN_TEST + \
8972 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8973 1 * ENABLE_ASH_ALIAS + \
8974 1 * ENABLE_ASH_JOB_CONTROL + \
8976 1 * ENABLE_ASH_CMDCMD + \
8978 ENABLE_ASH_BUILTIN_ECHO + \
8982 * Search the table of builtin commands.
8984 static struct builtincmd *
8985 find_builtin(const char *name)
8987 struct builtincmd *bp;
8990 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8997 * Execute a simple command.
9000 isassignment(const char *p)
9002 const char *q = endofname(p);
9007 static int FAST_FUNC
9008 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9010 /* Preserve exitstatus of a previous possible redirection
9011 * as POSIX mandates */
9012 return back_exitstatus;
9015 evalcommand(union node *cmd, int flags)
9017 static const struct builtincmd null_bltin = {
9018 "\0\0", bltincmd /* why three NULs? */
9020 struct stackmark smark;
9022 struct arglist arglist;
9023 struct arglist varlist;
9026 const struct strlist *sp;
9027 struct cmdentry cmdentry;
9034 struct builtincmd *bcmd;
9035 smallint cmd_is_exec;
9036 smallint pseudovarflag = 0;
9038 /* First expand the arguments. */
9039 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9040 setstackmark(&smark);
9041 back_exitstatus = 0;
9043 cmdentry.cmdtype = CMDBUILTIN;
9044 cmdentry.u.cmd = &null_bltin;
9045 varlist.lastp = &varlist.list;
9046 *varlist.lastp = NULL;
9047 arglist.lastp = &arglist.list;
9048 *arglist.lastp = NULL;
9051 if (cmd->ncmd.args) {
9052 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9053 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9056 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9057 struct strlist **spp;
9059 spp = arglist.lastp;
9060 if (pseudovarflag && isassignment(argp->narg.text))
9061 expandarg(argp, &arglist, EXP_VARTILDE);
9063 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9065 for (sp = *spp; sp; sp = sp->next)
9069 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9070 for (sp = arglist.list; sp; sp = sp->next) {
9071 TRACE(("evalcommand arg: %s\n", sp->text));
9072 *nargv++ = sp->text;
9077 if (iflag && funcnest == 0 && argc > 0)
9078 lastarg = nargv[-1];
9081 expredir(cmd->ncmd.redirect);
9082 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9084 path = vpath.var_text;
9085 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9086 struct strlist **spp;
9089 spp = varlist.lastp;
9090 expandarg(argp, &varlist, EXP_VARTILDE);
9093 * Modify the command lookup path, if a PATH= assignment
9097 if (varcmp(p, path) == 0)
9101 /* Print the command if xflag is set. */
9104 const char *p = " %s";
9107 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9110 for (n = 0; n < 2; n++) {
9112 fdprintf(preverrout_fd, p, sp->text);
9120 safe_write(preverrout_fd, "\n", 1);
9126 /* Now locate the command. */
9128 const char *oldpath;
9129 int cmd_flag = DO_ERR;
9134 find_command(argv[0], &cmdentry, cmd_flag, path);
9135 if (cmdentry.cmdtype == CMDUNKNOWN) {
9136 flush_stdout_stderr();
9141 /* implement bltin and command here */
9142 if (cmdentry.cmdtype != CMDBUILTIN)
9145 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9146 if (cmdentry.u.cmd == EXECCMD)
9148 #if ENABLE_ASH_CMDCMD
9149 if (cmdentry.u.cmd == COMMANDCMD) {
9151 nargv = parse_command_args(argv, &path);
9154 argc -= nargv - argv;
9156 cmd_flag |= DO_NOFUNC;
9164 /* We have a redirection error. */
9166 raise_exception(EXERROR);
9168 exitstatus = status;
9172 /* Execute the command. */
9173 switch (cmdentry.cmdtype) {
9176 #if ENABLE_FEATURE_SH_NOFORK
9177 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9178 * around run_nofork_applet() call.
9179 * (2) Should this check also be done in forkshell()?
9180 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9182 /* find_command() encodes applet_no as (-2 - applet_no) */
9183 int applet_no = (- cmdentry.u.index - 2);
9184 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9185 listsetvar(varlist.list, VEXPORT|VSTACK);
9186 /* run <applet>_main() */
9187 exitstatus = run_nofork_applet(applet_no, argv);
9191 /* Can we avoid forking off? For example, very last command
9192 * in a script or a subshell does not need forking,
9193 * we can just exec it.
9195 if (!(flags & EV_EXIT) || may_have_traps) {
9196 /* No, forking off a child is necessary */
9198 jp = makejob(/*cmd,*/ 1);
9199 if (forkshell(jp, cmd, FORK_FG) != 0) {
9201 exitstatus = waitforjob(jp);
9203 TRACE(("forked child exited with %d\n", exitstatus));
9208 /* fall through to exec'ing external program */
9210 listsetvar(varlist.list, VEXPORT|VSTACK);
9211 shellexec(argv, path, cmdentry.u.index);
9215 cmdenviron = varlist.list;
9217 struct strlist *list = cmdenviron;
9219 if (spclbltin > 0 || argc == 0) {
9221 if (cmd_is_exec && argc > 1)
9224 listsetvar(list, i);
9226 /* Tight loop with builtins only:
9227 * "while kill -0 $child; do true; done"
9228 * will never exit even if $child died, unless we do this
9229 * to reap the zombie and make kill detect that it's gone: */
9230 dowait(DOWAIT_NONBLOCK, NULL);
9232 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9234 int i = exception_type;
9239 exit_status = 128 + SIGINT;
9241 exit_status = 128 + pending_sig;
9242 exitstatus = exit_status;
9243 if (i == EXINT || spclbltin > 0) {
9245 longjmp(exception_handler->loc, 1);
9252 listsetvar(varlist.list, 0);
9253 /* See above for the rationale */
9254 dowait(DOWAIT_NONBLOCK, NULL);
9255 if (evalfun(cmdentry.u.func, argc, argv, flags))
9262 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9264 /* dsl: I think this is intended to be used to support
9265 * '_' in 'vi' command mode during line editing...
9266 * However I implemented that within libedit itself.
9268 setvar("_", lastarg, 0);
9270 popstackmark(&smark);
9274 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9276 char *volatile savecmdname;
9277 struct jmploc *volatile savehandler;
9278 struct jmploc jmploc;
9281 savecmdname = commandname;
9282 i = setjmp(jmploc.loc);
9285 savehandler = exception_handler;
9286 exception_handler = &jmploc;
9287 commandname = argv[0];
9289 optptr = NULL; /* initialize nextopt */
9290 exitstatus = (*cmd->builtin)(argc, argv);
9291 flush_stdout_stderr();
9293 exitstatus |= ferror(stdout);
9295 commandname = savecmdname;
9296 exception_handler = savehandler;
9302 goodname(const char *p)
9304 return !*endofname(p);
9309 * Search for a command. This is called before we fork so that the
9310 * location of the command will be available in the parent as well as
9311 * the child. The check for "goodname" is an overly conservative
9312 * check that the name will not be subject to expansion.
9315 prehash(union node *n)
9317 struct cmdentry entry;
9319 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9320 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9324 /* ============ Builtin commands
9326 * Builtin commands whose functions are closely tied to evaluation
9327 * are implemented here.
9331 * Handle break and continue commands. Break, continue, and return are
9332 * all handled by setting the evalskip flag. The evaluation routines
9333 * above all check this flag, and if it is set they start skipping
9334 * commands rather than executing them. The variable skipcount is
9335 * the number of loops to break/continue, or the number of function
9336 * levels to return. (The latter is always 1.) It should probably
9337 * be an error to break out of more loops than exist, but it isn't
9338 * in the standard shell so we don't make it one here.
9340 static int FAST_FUNC
9341 breakcmd(int argc UNUSED_PARAM, char **argv)
9343 int n = argv[1] ? number(argv[1]) : 1;
9346 ash_msg_and_raise_error(msg_illnum, argv[1]);
9350 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9357 /* ============ input.c
9359 * This implements the input routines used by the parser.
9363 INPUT_PUSH_FILE = 1,
9364 INPUT_NOFILE_OK = 2,
9367 static smallint checkkwd;
9368 /* values of checkkwd variable */
9369 #define CHKALIAS 0x1
9374 * Push a string back onto the input at this current parsefile level.
9375 * We handle aliases this way.
9377 #if !ENABLE_ASH_ALIAS
9378 #define pushstring(s, ap) pushstring(s)
9381 pushstring(char *s, struct alias *ap)
9388 if (g_parsefile->strpush) {
9389 sp = ckzalloc(sizeof(*sp));
9390 sp->prev = g_parsefile->strpush;
9392 sp = &(g_parsefile->basestrpush);
9394 g_parsefile->strpush = sp;
9395 sp->prev_string = g_parsefile->next_to_pgetc;
9396 sp->prev_left_in_line = g_parsefile->left_in_line;
9397 #if ENABLE_ASH_ALIAS
9400 ap->flag |= ALIASINUSE;
9404 g_parsefile->next_to_pgetc = s;
9405 g_parsefile->left_in_line = len;
9412 struct strpush *sp = g_parsefile->strpush;
9415 #if ENABLE_ASH_ALIAS
9417 if (g_parsefile->next_to_pgetc[-1] == ' '
9418 || g_parsefile->next_to_pgetc[-1] == '\t'
9420 checkkwd |= CHKALIAS;
9422 if (sp->string != sp->ap->val) {
9425 sp->ap->flag &= ~ALIASINUSE;
9426 if (sp->ap->flag & ALIASDEAD) {
9427 unalias(sp->ap->name);
9431 g_parsefile->next_to_pgetc = sp->prev_string;
9432 g_parsefile->left_in_line = sp->prev_left_in_line;
9433 g_parsefile->strpush = sp->prev;
9434 if (sp != &(g_parsefile->basestrpush))
9439 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9440 //it peeks whether it is &>, and then pushes back both chars.
9441 //This function needs to save last *next_to_pgetc to buf[0]
9442 //to make two pungetc() reliable. Currently,
9443 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9448 char *buf = g_parsefile->buf;
9450 g_parsefile->next_to_pgetc = buf;
9451 #if ENABLE_FEATURE_EDITING
9453 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9454 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9456 #if ENABLE_FEATURE_TAB_COMPLETION
9457 line_input_state->path_lookup = pathval();
9459 nr = read_line_input(cmdedit_prompt, buf, IBUFSIZ, line_input_state);
9461 /* Ctrl+C pressed */
9470 if (nr < 0 && errno == 0) {
9471 /* Ctrl+D pressed */
9476 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9480 /* nonblock_safe_read() handles this problem */
9482 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9483 int flags = fcntl(0, F_GETFL);
9484 if (flags >= 0 && (flags & O_NONBLOCK)) {
9485 flags &= ~O_NONBLOCK;
9486 if (fcntl(0, F_SETFL, flags) >= 0) {
9487 out2str("sh: turning off NDELAY mode\n");
9498 * Refill the input buffer and return the next input character:
9500 * 1) If a string was pushed back on the input, pop it;
9501 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9502 * or we are reading from a string so we can't refill the buffer,
9504 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9505 * 4) Process input up to the next newline, deleting nul characters.
9507 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9508 #define pgetc_debug(...) ((void)0)
9515 while (g_parsefile->strpush) {
9516 #if ENABLE_ASH_ALIAS
9517 if (g_parsefile->left_in_line == -1
9518 && g_parsefile->strpush->ap
9519 && g_parsefile->next_to_pgetc[-1] != ' '
9520 && g_parsefile->next_to_pgetc[-1] != '\t'
9522 pgetc_debug("preadbuffer PEOA");
9527 /* try "pgetc" now: */
9528 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9529 g_parsefile->left_in_line,
9530 g_parsefile->next_to_pgetc,
9531 g_parsefile->next_to_pgetc);
9532 if (--g_parsefile->left_in_line >= 0)
9533 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9535 /* on both branches above g_parsefile->left_in_line < 0.
9536 * "pgetc" needs refilling.
9539 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9540 * pungetc() may increment it a few times.
9541 * Assuming it won't increment it to less than -90.
9543 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9544 pgetc_debug("preadbuffer PEOF1");
9545 /* even in failure keep left_in_line and next_to_pgetc
9546 * in lock step, for correct multi-layer pungetc.
9547 * left_in_line was decremented before preadbuffer(),
9548 * must inc next_to_pgetc: */
9549 g_parsefile->next_to_pgetc++;
9553 more = g_parsefile->left_in_buffer;
9555 flush_stdout_stderr();
9559 /* don't try reading again */
9560 g_parsefile->left_in_line = -99;
9561 pgetc_debug("preadbuffer PEOF2");
9562 g_parsefile->next_to_pgetc++;
9567 /* Find out where's the end of line.
9568 * Set g_parsefile->left_in_line
9569 * and g_parsefile->left_in_buffer acordingly.
9570 * NUL chars are deleted.
9572 q = g_parsefile->next_to_pgetc;
9580 memmove(q, q + 1, more);
9584 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9590 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9591 if (g_parsefile->left_in_line < 0)
9596 g_parsefile->left_in_buffer = more;
9601 out2str(g_parsefile->next_to_pgetc);
9605 pgetc_debug("preadbuffer at %d:%p'%s'",
9606 g_parsefile->left_in_line,
9607 g_parsefile->next_to_pgetc,
9608 g_parsefile->next_to_pgetc);
9609 return (unsigned char)*g_parsefile->next_to_pgetc++;
9612 #define pgetc_as_macro() \
9613 (--g_parsefile->left_in_line >= 0 \
9614 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9621 pgetc_debug("pgetc_fast at %d:%p'%s'",
9622 g_parsefile->left_in_line,
9623 g_parsefile->next_to_pgetc,
9624 g_parsefile->next_to_pgetc);
9625 return pgetc_as_macro();
9628 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9629 # define pgetc_fast() pgetc()
9631 # define pgetc_fast() pgetc_as_macro()
9634 #if ENABLE_ASH_ALIAS
9636 pgetc_without_PEOA(void)
9640 pgetc_debug("pgetc_fast at %d:%p'%s'",
9641 g_parsefile->left_in_line,
9642 g_parsefile->next_to_pgetc,
9643 g_parsefile->next_to_pgetc);
9645 } while (c == PEOA);
9649 # define pgetc_without_PEOA() pgetc()
9653 * Read a line from the script.
9656 pfgets(char *line, int len)
9662 while (--nleft > 0) {
9663 c = pgetc_without_PEOA();
9678 * Undo the last call to pgetc. Only one character may be pushed back.
9679 * PEOF may be pushed back.
9684 g_parsefile->left_in_line++;
9685 g_parsefile->next_to_pgetc--;
9686 pgetc_debug("pushed back to %d:%p'%s'",
9687 g_parsefile->left_in_line,
9688 g_parsefile->next_to_pgetc,
9689 g_parsefile->next_to_pgetc);
9693 * To handle the "." command, a stack of input files is used. Pushfile
9694 * adds a new entry to the stack and popfile restores the previous level.
9699 struct parsefile *pf;
9701 pf = ckzalloc(sizeof(*pf));
9702 pf->prev = g_parsefile;
9704 /*pf->strpush = NULL; - ckzalloc did it */
9705 /*pf->basestrpush.prev = NULL;*/
9712 struct parsefile *pf = g_parsefile;
9720 g_parsefile = pf->prev;
9726 * Return to top level.
9731 while (g_parsefile != &basepf)
9736 * Close the file(s) that the shell is reading commands from. Called
9737 * after a fork is done.
9743 if (g_parsefile->pf_fd > 0) {
9744 close(g_parsefile->pf_fd);
9745 g_parsefile->pf_fd = 0;
9750 * Like setinputfile, but takes an open file descriptor. Call this with
9754 setinputfd(int fd, int push)
9756 close_on_exec_on(fd);
9759 g_parsefile->buf = NULL;
9761 g_parsefile->pf_fd = fd;
9762 if (g_parsefile->buf == NULL)
9763 g_parsefile->buf = ckmalloc(IBUFSIZ);
9764 g_parsefile->left_in_buffer = 0;
9765 g_parsefile->left_in_line = 0;
9766 g_parsefile->linno = 1;
9770 * Set the input to take input from a file. If push is set, push the
9771 * old input onto the stack first.
9774 setinputfile(const char *fname, int flags)
9780 fd = open(fname, O_RDONLY);
9782 if (flags & INPUT_NOFILE_OK)
9784 ash_msg_and_raise_error("can't open '%s'", fname);
9787 fd2 = copyfd(fd, 10);
9790 ash_msg_and_raise_error("out of file descriptors");
9793 setinputfd(fd, flags & INPUT_PUSH_FILE);
9800 * Like setinputfile, but takes input from a string.
9803 setinputstring(char *string)
9807 g_parsefile->next_to_pgetc = string;
9808 g_parsefile->left_in_line = strlen(string);
9809 g_parsefile->buf = NULL;
9810 g_parsefile->linno = 1;
9815 /* ============ mail.c
9817 * Routines to check for mail.
9822 #define MAXMBOXES 10
9824 /* times of mailboxes */
9825 static time_t mailtime[MAXMBOXES];
9826 /* Set if MAIL or MAILPATH is changed. */
9827 static smallint mail_var_path_changed;
9830 * Print appropriate message(s) if mail has arrived.
9831 * If mail_var_path_changed is set,
9832 * then the value of MAIL has mail_var_path_changed,
9833 * so we just update the values.
9842 struct stackmark smark;
9845 setstackmark(&smark);
9846 mpath = mpathset() ? mpathval() : mailval();
9847 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9848 p = path_advance(&mpath, nullstr);
9853 for (q = p; *q; q++)
9859 q[-1] = '\0'; /* delete trailing '/' */
9860 if (stat(p, &statb) < 0) {
9864 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9867 pathopt ? pathopt : "you have mail"
9870 *mtp = statb.st_mtime;
9872 mail_var_path_changed = 0;
9873 popstackmark(&smark);
9876 static void FAST_FUNC
9877 changemail(const char *val UNUSED_PARAM)
9879 mail_var_path_changed = 1;
9882 #endif /* ASH_MAIL */
9885 /* ============ ??? */
9888 * Set the shell parameters.
9891 setparam(char **argv)
9897 for (nparam = 0; argv[nparam]; nparam++)
9899 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9901 *ap++ = ckstrdup(*argv++);
9904 freeparam(&shellparam);
9905 shellparam.malloced = 1;
9906 shellparam.nparam = nparam;
9907 shellparam.p = newparam;
9908 #if ENABLE_ASH_GETOPTS
9909 shellparam.optind = 1;
9910 shellparam.optoff = -1;
9915 * Process shell options. The global variable argptr contains a pointer
9916 * to the argument list; we advance it past the options.
9918 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9919 * For a non-interactive shell, an error condition encountered
9920 * by a special built-in ... shall cause the shell to write a diagnostic message
9921 * to standard error and exit as shown in the following table:
9922 * Error Special Built-In
9924 * Utility syntax error (option or operand error) Shall exit
9926 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9927 * we see that bash does not do that (set "finishes" with error code 1 instead,
9928 * and shell continues), and people rely on this behavior!
9930 * set -o barfoo 2>/dev/null
9933 * Oh well. Let's mimic that.
9936 plus_minus_o(char *name, int val)
9941 for (i = 0; i < NOPTS; i++) {
9942 if (strcmp(name, optnames(i)) == 0) {
9947 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9950 for (i = 0; i < NOPTS; i++) {
9952 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9954 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9960 setoption(int flag, int val)
9964 for (i = 0; i < NOPTS; i++) {
9965 if (optletters(i) == flag) {
9970 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9974 options(int cmdline)
9982 while ((p = *argptr) != NULL) {
9984 if (c != '-' && c != '+')
9987 val = 0; /* val = 0 if c == '+' */
9990 if (p[0] == '\0' || LONE_DASH(p)) {
9992 /* "-" means turn off -x and -v */
9995 /* "--" means reset params */
9996 else if (*argptr == NULL)
9999 break; /* "-" or "--" terminates options */
10002 /* first char was + or - */
10003 while ((c = *p++) != '\0') {
10004 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10005 if (c == 'c' && cmdline) {
10006 minusc = p; /* command is after shell args */
10007 } else if (c == 'o') {
10008 if (plus_minus_o(*argptr, val)) {
10009 /* it already printed err message */
10010 return 1; /* error */
10014 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10016 /* bash does not accept +-login, we also won't */
10017 } else if (cmdline && val && (c == '-')) { /* long options */
10018 if (strcmp(p, "login") == 0)
10030 * The shift builtin command.
10032 static int FAST_FUNC
10033 shiftcmd(int argc UNUSED_PARAM, char **argv)
10040 n = number(argv[1]);
10041 if (n > shellparam.nparam)
10042 n = 0; /* bash compat, was = shellparam.nparam; */
10044 shellparam.nparam -= n;
10045 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10046 if (shellparam.malloced)
10049 ap2 = shellparam.p;
10050 while ((*ap2++ = *ap1++) != NULL)
10052 #if ENABLE_ASH_GETOPTS
10053 shellparam.optind = 1;
10054 shellparam.optoff = -1;
10061 * POSIX requires that 'set' (but not export or readonly) output the
10062 * variables in lexicographic order - by the locale's collating order (sigh).
10063 * Maybe we could keep them in an ordered balanced binary tree
10064 * instead of hashed lists.
10065 * For now just roll 'em through qsort for printing...
10068 showvars(const char *sep_prefix, int on, int off)
10071 char **ep, **epend;
10073 ep = listvars(on, off, &epend);
10074 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10076 sep = *sep_prefix ? " " : sep_prefix;
10078 for (; ep < epend; ep++) {
10082 p = strchrnul(*ep, '=');
10085 q = single_quote(++p);
10086 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10092 * The set command builtin.
10094 static int FAST_FUNC
10095 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10100 return showvars(nullstr, 0, VUNSET);
10103 if (!options(0)) { /* if no parse error... */
10106 if (*argptr != NULL) {
10114 #if ENABLE_ASH_RANDOM_SUPPORT
10115 static void FAST_FUNC
10116 change_random(const char *value)
10120 if (value == NULL) {
10121 /* "get", generate */
10122 t = next_random(&random_gen);
10123 /* set without recursion */
10124 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10125 vrandom.flags &= ~VNOFUNC;
10128 t = strtoul(value, NULL, 10);
10129 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10134 #if ENABLE_ASH_GETOPTS
10136 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10145 if (*param_optind < 1)
10147 optnext = optfirst + *param_optind - 1;
10149 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10152 p = optnext[-1] + *optoff;
10153 if (p == NULL || *p == '\0') {
10154 /* Current word is done, advance */
10156 if (p == NULL || *p != '-' || *++p == '\0') {
10163 if (LONE_DASH(p)) /* check for "--" */
10168 for (q = optstr; *q != c;) {
10170 if (optstr[0] == ':') {
10173 err |= setvarsafe("OPTARG", s, 0);
10175 fprintf(stderr, "Illegal option -%c\n", c);
10176 unsetvar("OPTARG");
10186 if (*p == '\0' && (p = *optnext) == NULL) {
10187 if (optstr[0] == ':') {
10190 err |= setvarsafe("OPTARG", s, 0);
10193 fprintf(stderr, "No arg for -%c option\n", c);
10194 unsetvar("OPTARG");
10202 err |= setvarsafe("OPTARG", p, 0);
10205 err |= setvarsafe("OPTARG", nullstr, 0);
10207 *optoff = p ? p - *(optnext - 1) : -1;
10208 *param_optind = optnext - optfirst + 1;
10209 fmtstr(s, sizeof(s), "%d", *param_optind);
10210 err |= setvarsafe("OPTIND", s, VNOFUNC);
10213 err |= setvarsafe(optvar, s, 0);
10217 flush_stdout_stderr();
10218 raise_exception(EXERROR);
10224 * The getopts builtin. Shellparam.optnext points to the next argument
10225 * to be processed. Shellparam.optptr points to the next character to
10226 * be processed in the current argument. If shellparam.optnext is NULL,
10227 * then it's the first time getopts has been called.
10229 static int FAST_FUNC
10230 getoptscmd(int argc, char **argv)
10235 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10237 optbase = shellparam.p;
10238 if (shellparam.optind > shellparam.nparam + 1) {
10239 shellparam.optind = 1;
10240 shellparam.optoff = -1;
10243 optbase = &argv[3];
10244 if (shellparam.optind > argc - 2) {
10245 shellparam.optind = 1;
10246 shellparam.optoff = -1;
10250 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10251 &shellparam.optoff);
10253 #endif /* ASH_GETOPTS */
10256 /* ============ Shell parser */
10259 struct heredoc *next; /* next here document in list */
10260 union node *here; /* redirection node */
10261 char *eofmark; /* string indicating end of input */
10262 smallint striptabs; /* if set, strip leading tabs */
10265 static smallint tokpushback; /* last token pushed back */
10266 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10267 static smallint quoteflag; /* set if (part of) last token was quoted */
10268 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10269 static struct heredoc *heredoclist; /* list of here documents to read */
10270 static char *wordtext; /* text of last word returned by readtoken */
10271 static struct nodelist *backquotelist;
10272 static union node *redirnode;
10273 static struct heredoc *heredoc;
10275 static const char *
10276 tokname(char *buf, int tok)
10279 return tokname_array[tok] + 1;
10280 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10284 /* raise_error_unexpected_syntax:
10285 * Called when an unexpected token is read during the parse. The argument
10286 * is the token that is expected, or -1 if more than one type of token can
10287 * occur at this point.
10289 static void raise_error_unexpected_syntax(int) NORETURN;
10291 raise_error_unexpected_syntax(int token)
10297 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10299 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10300 raise_error_syntax(msg);
10304 #define EOFMARKLEN 79
10306 /* parsing is heavily cross-recursive, need these forward decls */
10307 static union node *andor(void);
10308 static union node *pipeline(void);
10309 static union node *parse_command(void);
10310 static void parseheredoc(void);
10311 static char peektoken(void);
10312 static int readtoken(void);
10314 static union node *
10317 union node *n1, *n2, *n3;
10320 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10321 if (nlflag == 2 && peektoken())
10327 if (tok == TBACKGND) {
10328 if (n2->type == NPIPE) {
10329 n2->npipe.pipe_backgnd = 1;
10331 if (n2->type != NREDIR) {
10332 n3 = stzalloc(sizeof(struct nredir));
10334 /*n3->nredir.redirect = NULL; - stzalloc did it */
10337 n2->type = NBACKGND;
10343 n3 = stzalloc(sizeof(struct nbinary));
10345 n3->nbinary.ch1 = n1;
10346 n3->nbinary.ch2 = n2;
10362 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10370 pungetc(); /* push back EOF on input */
10374 raise_error_unexpected_syntax(-1);
10381 static union node *
10384 union node *n1, *n2, *n3;
10392 } else if (t == TOR) {
10398 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10400 n3 = stzalloc(sizeof(struct nbinary));
10402 n3->nbinary.ch1 = n1;
10403 n3->nbinary.ch2 = n2;
10408 static union node *
10411 union node *n1, *n2, *pipenode;
10412 struct nodelist *lp, *prev;
10416 TRACE(("pipeline: entered\n"));
10417 if (readtoken() == TNOT) {
10419 checkkwd = CHKKWD | CHKALIAS;
10422 n1 = parse_command();
10423 if (readtoken() == TPIPE) {
10424 pipenode = stzalloc(sizeof(struct npipe));
10425 pipenode->type = NPIPE;
10426 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10427 lp = stzalloc(sizeof(struct nodelist));
10428 pipenode->npipe.cmdlist = lp;
10432 lp = stzalloc(sizeof(struct nodelist));
10433 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10434 lp->n = parse_command();
10436 } while (readtoken() == TPIPE);
10442 n2 = stzalloc(sizeof(struct nnot));
10450 static union node *
10455 n = stzalloc(sizeof(struct narg));
10457 /*n->narg.next = NULL; - stzalloc did it */
10458 n->narg.text = wordtext;
10459 n->narg.backquote = backquotelist;
10464 fixredir(union node *n, const char *text, int err)
10468 TRACE(("Fix redir %s %d\n", text, err));
10470 n->ndup.vname = NULL;
10472 fd = bb_strtou(text, NULL, 10);
10473 if (!errno && fd >= 0)
10474 n->ndup.dupfd = fd;
10475 else if (LONE_DASH(text))
10476 n->ndup.dupfd = -1;
10479 raise_error_syntax("bad fd number");
10480 n->ndup.vname = makename();
10485 * Returns true if the text contains nothing to expand (no dollar signs
10489 noexpand(const char *text)
10493 while ((c = *text++) != '\0') {
10494 if (c == CTLQUOTEMARK)
10498 else if (SIT(c, BASESYNTAX) == CCTL)
10507 union node *n = redirnode;
10509 if (readtoken() != TWORD)
10510 raise_error_unexpected_syntax(-1);
10511 if (n->type == NHERE) {
10512 struct heredoc *here = heredoc;
10516 if (quoteflag == 0)
10518 TRACE(("Here document %d\n", n->type));
10519 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10520 raise_error_syntax("illegal eof marker for << redirection");
10521 rmescapes(wordtext, 0);
10522 here->eofmark = wordtext;
10524 if (heredoclist == NULL)
10525 heredoclist = here;
10527 for (p = heredoclist; p->next; p = p->next)
10531 } else if (n->type == NTOFD || n->type == NFROMFD) {
10532 fixredir(n, wordtext, 0);
10534 n->nfile.fname = makename();
10538 static union node *
10541 union node *args, **app;
10542 union node *n = NULL;
10543 union node *vars, **vpp;
10544 union node **rpp, *redir;
10546 #if ENABLE_ASH_BASH_COMPAT
10547 smallint double_brackets_flag = 0;
10557 savecheckkwd = CHKALIAS;
10560 checkkwd = savecheckkwd;
10563 #if ENABLE_ASH_BASH_COMPAT
10564 case TAND: /* "&&" */
10565 case TOR: /* "||" */
10566 if (!double_brackets_flag) {
10570 wordtext = (char *) (t == TAND ? "-a" : "-o");
10573 n = stzalloc(sizeof(struct narg));
10575 /*n->narg.next = NULL; - stzalloc did it */
10576 n->narg.text = wordtext;
10577 #if ENABLE_ASH_BASH_COMPAT
10578 if (strcmp("[[", wordtext) == 0)
10579 double_brackets_flag = 1;
10580 else if (strcmp("]]", wordtext) == 0)
10581 double_brackets_flag = 0;
10583 n->narg.backquote = backquotelist;
10584 if (savecheckkwd && isassignment(wordtext)) {
10586 vpp = &n->narg.next;
10589 app = &n->narg.next;
10594 *rpp = n = redirnode;
10595 rpp = &n->nfile.next;
10596 parsefname(); /* read name of redirection file */
10599 if (args && app == &args->narg.next
10602 struct builtincmd *bcmd;
10605 /* We have a function */
10606 if (readtoken() != TRP)
10607 raise_error_unexpected_syntax(TRP);
10608 name = n->narg.text;
10609 if (!goodname(name)
10610 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10612 raise_error_syntax("bad function name");
10615 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10616 n->narg.next = parse_command();
10629 n = stzalloc(sizeof(struct ncmd));
10631 n->ncmd.args = args;
10632 n->ncmd.assign = vars;
10633 n->ncmd.redirect = redir;
10637 static union node *
10638 parse_command(void)
10640 union node *n1, *n2;
10641 union node *ap, **app;
10642 union node *cp, **cpp;
10643 union node *redir, **rpp;
10650 switch (readtoken()) {
10652 raise_error_unexpected_syntax(-1);
10655 n1 = stzalloc(sizeof(struct nif));
10657 n1->nif.test = list(0);
10658 if (readtoken() != TTHEN)
10659 raise_error_unexpected_syntax(TTHEN);
10660 n1->nif.ifpart = list(0);
10662 while (readtoken() == TELIF) {
10663 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10664 n2 = n2->nif.elsepart;
10666 n2->nif.test = list(0);
10667 if (readtoken() != TTHEN)
10668 raise_error_unexpected_syntax(TTHEN);
10669 n2->nif.ifpart = list(0);
10671 if (lasttoken == TELSE)
10672 n2->nif.elsepart = list(0);
10674 n2->nif.elsepart = NULL;
10682 n1 = stzalloc(sizeof(struct nbinary));
10683 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10684 n1->nbinary.ch1 = list(0);
10687 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
10688 got == TWORD ? wordtext : ""));
10689 raise_error_unexpected_syntax(TDO);
10691 n1->nbinary.ch2 = list(0);
10696 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10697 raise_error_syntax("bad for loop variable");
10698 n1 = stzalloc(sizeof(struct nfor));
10700 n1->nfor.var = wordtext;
10701 checkkwd = CHKKWD | CHKALIAS;
10702 if (readtoken() == TIN) {
10704 while (readtoken() == TWORD) {
10705 n2 = stzalloc(sizeof(struct narg));
10707 /*n2->narg.next = NULL; - stzalloc did it */
10708 n2->narg.text = wordtext;
10709 n2->narg.backquote = backquotelist;
10711 app = &n2->narg.next;
10714 n1->nfor.args = ap;
10715 if (lasttoken != TNL && lasttoken != TSEMI)
10716 raise_error_unexpected_syntax(-1);
10718 n2 = stzalloc(sizeof(struct narg));
10720 /*n2->narg.next = NULL; - stzalloc did it */
10721 n2->narg.text = (char *)dolatstr;
10722 /*n2->narg.backquote = NULL;*/
10723 n1->nfor.args = n2;
10725 * Newline or semicolon here is optional (but note
10726 * that the original Bourne shell only allowed NL).
10728 if (lasttoken != TNL && lasttoken != TSEMI)
10731 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10732 if (readtoken() != TDO)
10733 raise_error_unexpected_syntax(TDO);
10734 n1->nfor.body = list(0);
10738 n1 = stzalloc(sizeof(struct ncase));
10740 if (readtoken() != TWORD)
10741 raise_error_unexpected_syntax(TWORD);
10742 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10744 /*n2->narg.next = NULL; - stzalloc did it */
10745 n2->narg.text = wordtext;
10746 n2->narg.backquote = backquotelist;
10748 checkkwd = CHKKWD | CHKALIAS;
10749 } while (readtoken() == TNL);
10750 if (lasttoken != TIN)
10751 raise_error_unexpected_syntax(TIN);
10752 cpp = &n1->ncase.cases;
10754 checkkwd = CHKNL | CHKKWD;
10756 while (t != TESAC) {
10757 if (lasttoken == TLP)
10759 *cpp = cp = stzalloc(sizeof(struct nclist));
10761 app = &cp->nclist.pattern;
10763 *app = ap = stzalloc(sizeof(struct narg));
10765 /*ap->narg.next = NULL; - stzalloc did it */
10766 ap->narg.text = wordtext;
10767 ap->narg.backquote = backquotelist;
10768 if (readtoken() != TPIPE)
10770 app = &ap->narg.next;
10773 //ap->narg.next = NULL;
10774 if (lasttoken != TRP)
10775 raise_error_unexpected_syntax(TRP);
10776 cp->nclist.body = list(2);
10778 cpp = &cp->nclist.next;
10780 checkkwd = CHKNL | CHKKWD;
10784 raise_error_unexpected_syntax(TENDCASE);
10791 n1 = stzalloc(sizeof(struct nredir));
10792 n1->type = NSUBSHELL;
10793 n1->nredir.n = list(0);
10794 /*n1->nredir.redirect = NULL; - stzalloc did it */
10804 return simplecmd();
10807 if (readtoken() != t)
10808 raise_error_unexpected_syntax(t);
10811 /* Now check for redirection which may follow command */
10812 checkkwd = CHKKWD | CHKALIAS;
10814 while (readtoken() == TREDIR) {
10815 *rpp = n2 = redirnode;
10816 rpp = &n2->nfile.next;
10822 if (n1->type != NSUBSHELL) {
10823 n2 = stzalloc(sizeof(struct nredir));
10828 n1->nredir.redirect = redir;
10833 #if ENABLE_ASH_BASH_COMPAT
10834 static int decode_dollar_squote(void)
10836 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10842 p = strchr(C_escapes, c);
10847 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10851 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10853 } else if (c == 'x') { /* \xHH */
10857 } while (isxdigit(c) && --cnt);
10859 if (cnt == 3) { /* \x but next char is "bad" */
10863 } else { /* simple seq like \\ or \t */
10868 c = bb_process_escape_sequence((void*)&p);
10869 } else { /* unrecognized "\z": print both chars unless ' or " */
10870 if (c != '\'' && c != '"') {
10872 c |= 0x100; /* "please encode \, then me" */
10880 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10881 * is not NULL, read a here document. In the latter case, eofmark is the
10882 * word which marks the end of the document and striptabs is true if
10883 * leading tabs should be stripped from the document. The argument c
10884 * is the first character of the input token or document.
10886 * Because C does not have internal subroutines, I have simulated them
10887 * using goto's to implement the subroutine linkage. The following macros
10888 * will run code that appears at the end of readtoken1.
10890 #define CHECKEND() {goto checkend; checkend_return:;}
10891 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10892 #define PARSESUB() {goto parsesub; parsesub_return:;}
10893 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10894 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10895 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10897 readtoken1(int c, int syntax, char *eofmark, int striptabs)
10899 /* NB: syntax parameter fits into smallint */
10900 /* c parameter is an unsigned char or PEOF or PEOA */
10903 char line[EOFMARKLEN + 1];
10904 struct nodelist *bqlist;
10908 smallint prevsyntax; /* syntax before arithmetic */
10909 #if ENABLE_ASH_EXPAND_PRMT
10910 smallint pssyntax; /* we are expanding a prompt string */
10912 int varnest; /* levels of variables expansion */
10913 int arinest; /* levels of arithmetic expansion */
10914 int parenlevel; /* levels of parens in arithmetic */
10915 int dqvarnest; /* levels of variables expansion within double quotes */
10917 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10920 /* Avoid longjmp clobbering */
10926 (void) &parenlevel;
10929 (void) &prevsyntax;
10932 startlinno = g_parsefile->linno;
10937 #if ENABLE_ASH_EXPAND_PRMT
10938 pssyntax = (syntax == PSSYNTAX);
10942 dblquote = (syntax == DQSYNTAX);
10948 STARTSTACKSTR(out);
10950 /* For each line, until end of word */
10952 CHECKEND(); /* set c to PEOF if at end of here document */
10953 for (;;) { /* until end of line or end of word */
10954 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10955 switch (SIT(c, syntax)) {
10956 case CNL: /* '\n' */
10957 if (syntax == BASESYNTAX)
10958 goto endword; /* exit outer loop */
10960 g_parsefile->linno++;
10964 goto loop; /* continue outer loop */
10969 if (eofmark == NULL || dblquote)
10970 USTPUTC(CTLESC, out);
10971 #if ENABLE_ASH_BASH_COMPAT
10972 if (c == '\\' && bash_dollar_squote) {
10973 c = decode_dollar_squote();
10975 USTPUTC('\\', out);
10976 c = (unsigned char)c;
10982 case CBACK: /* backslash */
10983 c = pgetc_without_PEOA();
10985 USTPUTC(CTLESC, out);
10986 USTPUTC('\\', out);
10988 } else if (c == '\n') {
10992 #if ENABLE_ASH_EXPAND_PRMT
10993 if (c == '$' && pssyntax) {
10994 USTPUTC(CTLESC, out);
10995 USTPUTC('\\', out);
10998 if (dblquote && c != '\\'
10999 && c != '`' && c != '$'
11000 && (c != '"' || eofmark != NULL)
11002 USTPUTC(CTLESC, out);
11003 USTPUTC('\\', out);
11005 if (SIT(c, SQSYNTAX) == CCTL)
11006 USTPUTC(CTLESC, out);
11014 if (eofmark == NULL) {
11015 USTPUTC(CTLQUOTEMARK, out);
11023 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11024 if (eofmark != NULL && arinest == 0
11029 if (dqvarnest == 0) {
11030 syntax = BASESYNTAX;
11037 case CVAR: /* '$' */
11038 PARSESUB(); /* parse substitution */
11040 case CENDVAR: /* '}' */
11043 if (dqvarnest > 0) {
11046 USTPUTC(CTLENDVAR, out);
11051 #if ENABLE_SH_MATH_SUPPORT
11052 case CLP: /* '(' in arithmetic */
11056 case CRP: /* ')' in arithmetic */
11057 if (parenlevel > 0) {
11061 if (pgetc() == ')') {
11062 if (--arinest == 0) {
11063 USTPUTC(CTLENDARI, out);
11064 syntax = prevsyntax;
11065 dblquote = (syntax == DQSYNTAX);
11070 * unbalanced parens
11071 * (don't 2nd guess - no error)
11079 case CBQUOTE: /* '`' */
11083 goto endword; /* exit outer loop */
11087 if (varnest == 0) {
11088 #if ENABLE_ASH_BASH_COMPAT
11090 if (pgetc() == '>')
11091 c = 0x100 + '>'; /* flag &> */
11095 goto endword; /* exit outer loop */
11097 IF_ASH_ALIAS(if (c != PEOA))
11105 #if ENABLE_SH_MATH_SUPPORT
11106 if (syntax == ARISYNTAX)
11107 raise_error_syntax("missing '))'");
11109 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11110 raise_error_syntax("unterminated quoted string");
11111 if (varnest != 0) {
11112 startlinno = g_parsefile->linno;
11114 raise_error_syntax("missing '}'");
11116 USTPUTC('\0', out);
11117 len = out - (char *)stackblock();
11118 out = stackblock();
11119 if (eofmark == NULL) {
11120 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11123 if (isdigit_str9(out)) {
11124 PARSEREDIR(); /* passed as params: out, c */
11125 lasttoken = TREDIR;
11128 /* else: non-number X seen, interpret it
11129 * as "NNNX>file" = "NNNX >file" */
11133 quoteflag = quotef;
11134 backquotelist = bqlist;
11135 grabstackblock(len);
11139 /* end of readtoken routine */
11142 * Check to see whether we are at the end of the here document. When this
11143 * is called, c is set to the first character of the next input line. If
11144 * we are at the end of the here document, this routine sets the c to PEOF.
11148 #if ENABLE_ASH_ALIAS
11150 c = pgetc_without_PEOA();
11153 while (c == '\t') {
11154 c = pgetc_without_PEOA();
11157 if (c == *eofmark) {
11158 if (pfgets(line, sizeof(line)) != NULL) {
11162 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11164 if (*p == '\n' && *q == '\0') {
11166 g_parsefile->linno++;
11167 needprompt = doprompt;
11169 pushstring(line, NULL);
11174 goto checkend_return;
11178 * Parse a redirection operator. The variable "out" points to a string
11179 * specifying the fd to be redirected. The variable "c" contains the
11180 * first character of the redirection operator.
11183 /* out is already checked to be a valid number or "" */
11184 int fd = (*out == '\0' ? -1 : atoi(out));
11187 np = stzalloc(sizeof(struct nfile));
11192 np->type = NAPPEND;
11194 np->type = NCLOBBER;
11197 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11203 #if ENABLE_ASH_BASH_COMPAT
11204 else if (c == 0x100 + '>') { /* this flags &> redirection */
11206 pgetc(); /* this is '>', no need to check */
11210 else { /* c == '<' */
11211 /*np->nfile.fd = 0; - stzalloc did it */
11215 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11216 np = stzalloc(sizeof(struct nhere));
11217 /*np->nfile.fd = 0; - stzalloc did it */
11220 heredoc = stzalloc(sizeof(struct heredoc));
11221 heredoc->here = np;
11224 heredoc->striptabs = 1;
11226 /*heredoc->striptabs = 0; - stzalloc did it */
11232 np->type = NFROMFD;
11236 np->type = NFROMTO;
11248 goto parseredir_return;
11252 * Parse a substitution. At this point, we have read the dollar sign
11253 * and nothing else.
11256 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11257 * (assuming ascii char codes, as the original implementation did) */
11258 #define is_special(c) \
11259 (((unsigned)(c) - 33 < 32) \
11260 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11262 unsigned char subtype;
11266 static const char types[] ALIGN1 = "}-+?=";
11269 if (c > 255 /* PEOA or PEOF */
11270 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11272 #if ENABLE_ASH_BASH_COMPAT
11274 bash_dollar_squote = 1;
11279 } else if (c == '(') { /* $(command) or $((arith)) */
11280 if (pgetc() == '(') {
11281 #if ENABLE_SH_MATH_SUPPORT
11284 raise_error_syntax("you disabled math support for $((arith)) syntax");
11291 USTPUTC(CTLVAR, out);
11292 typeloc = out - (char *)stackblock();
11293 USTPUTC(VSNORMAL, out);
11294 subtype = VSNORMAL;
11302 subtype = VSLENGTH;
11306 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11310 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11311 } else if (isdigit(c)) {
11315 } while (isdigit(c));
11316 } else if (is_special(c)) {
11321 raise_error_syntax("bad substitution");
11323 if (c != '}' && subtype == VSLENGTH)
11328 if (subtype == 0) {
11332 #if ENABLE_ASH_BASH_COMPAT
11333 if (c == ':' || c == '$' || isdigit(c)) {
11335 subtype = VSSUBSTR;
11342 p = strchr(types, c);
11345 subtype = p - types + VSNORMAL;
11350 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11358 #if ENABLE_ASH_BASH_COMPAT
11360 subtype = VSREPLACE;
11363 subtype++; /* VSREPLACEALL */
11372 if (dblquote || arinest)
11374 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11375 if (subtype != VSNORMAL) {
11377 if (dblquote || arinest) {
11382 goto parsesub_return;
11386 * Called to parse command substitutions. Newstyle is set if the command
11387 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11388 * list of commands (passed by reference), and savelen is the number of
11389 * characters on the top of the stack which must be preserved.
11392 struct nodelist **nlpp;
11395 char *volatile str;
11396 struct jmploc jmploc;
11397 struct jmploc *volatile savehandler;
11399 smallint saveprompt = 0;
11402 (void) &saveprompt;
11404 savepbq = parsebackquote;
11405 if (setjmp(jmploc.loc)) {
11407 parsebackquote = 0;
11408 exception_handler = savehandler;
11409 longjmp(exception_handler->loc, 1);
11413 savelen = out - (char *)stackblock();
11415 str = ckmalloc(savelen);
11416 memcpy(str, stackblock(), savelen);
11418 savehandler = exception_handler;
11419 exception_handler = &jmploc;
11422 /* We must read until the closing backquote, giving special
11423 treatment to some slashes, and then push the string and
11424 reread it as input, interpreting it normally. */
11431 STARTSTACKSTR(pout);
11444 g_parsefile->linno++;
11448 * If eating a newline, avoid putting
11449 * the newline into the new character
11450 * stream (via the STPUTC after the
11455 if (pc != '\\' && pc != '`' && pc != '$'
11456 && (!dblquote || pc != '"')
11458 STPUTC('\\', pout);
11460 if (pc <= 255 /* not PEOA or PEOF */) {
11466 IF_ASH_ALIAS(case PEOA:)
11467 startlinno = g_parsefile->linno;
11468 raise_error_syntax("EOF in backquote substitution");
11471 g_parsefile->linno++;
11472 needprompt = doprompt;
11481 STPUTC('\0', pout);
11482 psavelen = pout - (char *)stackblock();
11483 if (psavelen > 0) {
11484 pstr = grabstackstr(pout);
11485 setinputstring(pstr);
11490 nlpp = &(*nlpp)->next;
11491 *nlpp = stzalloc(sizeof(**nlpp));
11492 /* (*nlpp)->next = NULL; - stzalloc did it */
11493 parsebackquote = oldstyle;
11496 saveprompt = doprompt;
11503 doprompt = saveprompt;
11504 else if (readtoken() != TRP)
11505 raise_error_unexpected_syntax(TRP);
11510 * Start reading from old file again, ignoring any pushed back
11511 * tokens left from the backquote parsing
11516 while (stackblocksize() <= savelen)
11518 STARTSTACKSTR(out);
11520 memcpy(out, str, savelen);
11521 STADJUST(savelen, out);
11527 parsebackquote = savepbq;
11528 exception_handler = savehandler;
11529 if (arinest || dblquote)
11530 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11532 USTPUTC(CTLBACKQ, out);
11534 goto parsebackq_oldreturn;
11535 goto parsebackq_newreturn;
11538 #if ENABLE_SH_MATH_SUPPORT
11540 * Parse an arithmetic expansion (indicate start of one and set state)
11543 if (++arinest == 1) {
11544 prevsyntax = syntax;
11545 syntax = ARISYNTAX;
11546 USTPUTC(CTLARI, out);
11553 * we collapse embedded arithmetic expansion to
11554 * parenthesis, which should be equivalent
11558 goto parsearith_return;
11562 } /* end of readtoken */
11565 * Read the next input token.
11566 * If the token is a word, we set backquotelist to the list of cmds in
11567 * backquotes. We set quoteflag to true if any part of the word was
11569 * If the token is TREDIR, then we set redirnode to a structure containing
11571 * In all cases, the variable startlinno is set to the number of the line
11572 * on which the token starts.
11574 * [Change comment: here documents and internal procedures]
11575 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11576 * word parsing code into a separate routine. In this case, readtoken
11577 * doesn't need to have any internal procedures, but parseword does.
11578 * We could also make parseoperator in essence the main routine, and
11579 * have parseword (readtoken1?) handle both words and redirection.]
11581 #define NEW_xxreadtoken
11582 #ifdef NEW_xxreadtoken
11583 /* singles must be first! */
11584 static const char xxreadtoken_chars[7] ALIGN1 = {
11585 '\n', '(', ')', /* singles */
11586 '&', '|', ';', /* doubles */
11590 #define xxreadtoken_singles 3
11591 #define xxreadtoken_doubles 3
11593 static const char xxreadtoken_tokens[] ALIGN1 = {
11594 TNL, TLP, TRP, /* only single occurrence allowed */
11595 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11596 TEOF, /* corresponds to trailing nul */
11597 TAND, TOR, TENDCASE /* if double occurrence */
11612 startlinno = g_parsefile->linno;
11613 for (;;) { /* until token or start of word found */
11615 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11619 while ((c = pgetc()) != '\n' && c != PEOF)
11622 } else if (c == '\\') {
11623 if (pgetc() != '\n') {
11625 break; /* return readtoken1(...) */
11627 startlinno = ++g_parsefile->linno;
11633 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11636 g_parsefile->linno++;
11637 needprompt = doprompt;
11640 p = strchr(xxreadtoken_chars, c);
11642 break; /* return readtoken1(...) */
11644 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11646 if (cc == c) { /* double occurrence? */
11647 p += xxreadtoken_doubles + 1;
11650 #if ENABLE_ASH_BASH_COMPAT
11651 if (c == '&' && cc == '>') /* &> */
11652 break; /* return readtoken1(...) */
11657 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11662 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11664 #else /* old xxreadtoken */
11665 #define RETURN(token) return lasttoken = token
11678 startlinno = g_parsefile->linno;
11679 for (;;) { /* until token or start of word found */
11682 case ' ': case '\t':
11683 IF_ASH_ALIAS(case PEOA:)
11686 while ((c = pgetc()) != '\n' && c != PEOF)
11691 if (pgetc() == '\n') {
11692 startlinno = ++g_parsefile->linno;
11700 g_parsefile->linno++;
11701 needprompt = doprompt;
11706 if (pgetc() == '&')
11711 if (pgetc() == '|')
11716 if (pgetc() == ';')
11729 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11732 #endif /* old xxreadtoken */
11739 smallint alreadyseen = tokpushback;
11742 #if ENABLE_ASH_ALIAS
11751 if (checkkwd & CHKNL) {
11758 if (t != TWORD || quoteflag) {
11763 * check for keywords
11765 if (checkkwd & CHKKWD) {
11766 const char *const *pp;
11768 pp = findkwd(wordtext);
11770 lasttoken = t = pp - tokname_array;
11771 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
11776 if (checkkwd & CHKALIAS) {
11777 #if ENABLE_ASH_ALIAS
11779 ap = lookupalias(wordtext, 1);
11782 pushstring(ap->val, ap);
11792 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11794 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11806 return tokname_array[t][0];
11810 * Read and parse a command. Returns NODE_EOF on end of file.
11811 * (NULL is a valid parse tree indicating a blank line.)
11813 static union node *
11814 parsecmd(int interact)
11819 doprompt = interact;
11821 setprompt(doprompt);
11833 * Input any here documents.
11838 struct heredoc *here;
11841 here = heredoclist;
11842 heredoclist = NULL;
11848 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11849 here->eofmark, here->striptabs);
11850 n = stzalloc(sizeof(struct narg));
11851 n->narg.type = NARG;
11852 /*n->narg.next = NULL; - stzalloc did it */
11853 n->narg.text = wordtext;
11854 n->narg.backquote = backquotelist;
11855 here->here->nhere.doc = n;
11862 * called by editline -- any expansions to the prompt should be added here.
11864 #if ENABLE_ASH_EXPAND_PRMT
11865 static const char *
11866 expandstr(const char *ps)
11870 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11871 * and token processing _can_ alter it (delete NULs etc). */
11872 setinputstring((char *)ps);
11873 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11876 n.narg.type = NARG;
11877 n.narg.next = NULL;
11878 n.narg.text = wordtext;
11879 n.narg.backquote = backquotelist;
11881 expandarg(&n, NULL, 0);
11882 return stackblock();
11887 * Execute a command or commands contained in a string.
11890 evalstring(char *s, int mask)
11893 struct stackmark smark;
11897 setstackmark(&smark);
11900 while ((n = parsecmd(0)) != NODE_EOF) {
11902 popstackmark(&smark);
11915 * The eval command.
11917 static int FAST_FUNC
11918 evalcmd(int argc UNUSED_PARAM, char **argv)
11927 STARTSTACKSTR(concat);
11929 concat = stack_putstr(p, concat);
11933 STPUTC(' ', concat);
11935 STPUTC('\0', concat);
11936 p = grabstackstr(concat);
11938 evalstring(p, ~SKIPEVAL);
11945 * Read and execute commands.
11946 * "Top" is nonzero for the top level command loop;
11947 * it turns on prompting if the shell is interactive.
11953 struct stackmark smark;
11957 TRACE(("cmdloop(%d) called\n", top));
11961 setstackmark(&smark);
11964 showjobs(stderr, SHOW_CHANGED);
11967 if (iflag && top) {
11969 #if ENABLE_ASH_MAIL
11973 n = parsecmd(inter);
11975 if (DEBUG > 2 && debug && (n != NODE_EOF))
11978 if (n == NODE_EOF) {
11979 if (!top || numeof >= 50)
11981 if (!stoppedjobs()) {
11984 out2str("\nUse \"exit\" to leave shell.\n");
11987 } else if (nflag == 0) {
11988 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11993 popstackmark(&smark);
11998 return skip & SKIPEVAL;
12005 * Take commands from a file. To be compatible we should do a path
12006 * search for the file, which is necessary to find sub-commands.
12009 find_dot_file(char *name)
12012 const char *path = pathval();
12015 /* don't try this for absolute or relative paths */
12016 if (strchr(name, '/'))
12019 /* IIRC standards do not say whether . is to be searched.
12020 * And it is even smaller this way, making it unconditional for now:
12022 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12027 while ((fullname = path_advance(&path, name)) != NULL) {
12029 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12031 * Don't bother freeing here, since it will
12032 * be freed by the caller.
12036 if (fullname != name)
12037 stunalloc(fullname);
12040 /* not found in the PATH */
12041 ash_msg_and_raise_error("%s: not found", name);
12045 static int FAST_FUNC
12046 dotcmd(int argc, char **argv)
12049 struct strlist *sp;
12050 volatile struct shparam saveparam;
12052 for (sp = cmdenviron; sp; sp = sp->next)
12053 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12056 /* bash says: "bash: .: filename argument required" */
12057 return 2; /* bash compat */
12060 /* "false; . empty_file; echo $?" should print 0, not 1: */
12063 fullname = find_dot_file(argv[1]);
12067 if (argc) { /* argc > 0, argv[0] != NULL */
12068 saveparam = shellparam;
12069 shellparam.malloced = 0;
12070 shellparam.nparam = argc;
12071 shellparam.p = argv;
12074 setinputfile(fullname, INPUT_PUSH_FILE);
12075 commandname = fullname;
12080 freeparam(&shellparam);
12081 shellparam = saveparam;
12087 static int FAST_FUNC
12088 exitcmd(int argc UNUSED_PARAM, char **argv)
12093 exitstatus = number(argv[1]);
12094 raise_exception(EXEXIT);
12099 * Read a file containing shell functions.
12102 readcmdfile(char *name)
12104 setinputfile(name, INPUT_PUSH_FILE);
12110 /* ============ find_command inplementation */
12113 * Resolve a command name. If you change this routine, you may have to
12114 * change the shellexec routine as well.
12117 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12119 struct tblentry *cmdp;
12126 struct builtincmd *bcmd;
12128 /* If name contains a slash, don't use PATH or hash table */
12129 if (strchr(name, '/') != NULL) {
12130 entry->u.index = -1;
12131 if (act & DO_ABS) {
12132 while (stat(name, &statb) < 0) {
12134 if (errno == EINTR)
12137 entry->cmdtype = CMDUNKNOWN;
12141 entry->cmdtype = CMDNORMAL;
12145 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12147 updatetbl = (path == pathval());
12150 if (strstr(path, "%builtin") != NULL)
12151 act |= DO_ALTBLTIN;
12154 /* If name is in the table, check answer will be ok */
12155 cmdp = cmdlookup(name, 0);
12156 if (cmdp != NULL) {
12159 switch (cmdp->cmdtype) {
12177 } else if (cmdp->rehash == 0)
12178 /* if not invalidated by cd, we're done */
12182 /* If %builtin not in path, check for builtin next */
12183 bcmd = find_builtin(name);
12185 if (IS_BUILTIN_REGULAR(bcmd))
12186 goto builtin_success;
12187 if (act & DO_ALTPATH) {
12188 if (!(act & DO_ALTBLTIN))
12189 goto builtin_success;
12190 } else if (builtinloc <= 0) {
12191 goto builtin_success;
12195 #if ENABLE_FEATURE_SH_STANDALONE
12197 int applet_no = find_applet_by_name(name);
12198 if (applet_no >= 0) {
12199 entry->cmdtype = CMDNORMAL;
12200 entry->u.index = -2 - applet_no;
12206 /* We have to search path. */
12207 prev = -1; /* where to start */
12208 if (cmdp && cmdp->rehash) { /* doing a rehash */
12209 if (cmdp->cmdtype == CMDBUILTIN)
12212 prev = cmdp->param.index;
12218 while ((fullname = path_advance(&path, name)) != NULL) {
12219 stunalloc(fullname);
12220 /* NB: code below will still use fullname
12221 * despite it being "unallocated" */
12224 if (prefix(pathopt, "builtin")) {
12226 goto builtin_success;
12229 if ((act & DO_NOFUNC)
12230 || !prefix(pathopt, "func")
12231 ) { /* ignore unimplemented options */
12235 /* if rehash, don't redo absolute path names */
12236 if (fullname[0] == '/' && idx <= prev) {
12239 TRACE(("searchexec \"%s\": no change\n", name));
12242 while (stat(fullname, &statb) < 0) {
12244 if (errno == EINTR)
12247 if (errno != ENOENT && errno != ENOTDIR)
12251 e = EACCES; /* if we fail, this will be the error */
12252 if (!S_ISREG(statb.st_mode))
12254 if (pathopt) { /* this is a %func directory */
12255 stalloc(strlen(fullname) + 1);
12256 /* NB: stalloc will return space pointed by fullname
12257 * (because we don't have any intervening allocations
12258 * between stunalloc above and this stalloc) */
12259 readcmdfile(fullname);
12260 cmdp = cmdlookup(name, 0);
12261 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12262 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12263 stunalloc(fullname);
12266 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12268 entry->cmdtype = CMDNORMAL;
12269 entry->u.index = idx;
12273 cmdp = cmdlookup(name, 1);
12274 cmdp->cmdtype = CMDNORMAL;
12275 cmdp->param.index = idx;
12280 /* We failed. If there was an entry for this command, delete it */
12281 if (cmdp && updatetbl)
12282 delete_cmd_entry();
12284 ash_msg("%s: %s", name, errmsg(e, "not found"));
12285 entry->cmdtype = CMDUNKNOWN;
12290 entry->cmdtype = CMDBUILTIN;
12291 entry->u.cmd = bcmd;
12295 cmdp = cmdlookup(name, 1);
12296 cmdp->cmdtype = CMDBUILTIN;
12297 cmdp->param.cmd = bcmd;
12301 entry->cmdtype = cmdp->cmdtype;
12302 entry->u = cmdp->param;
12306 /* ============ trap.c */
12309 * The trap builtin.
12311 static int FAST_FUNC
12312 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12316 int signo, exitcode;
12321 for (signo = 0; signo < NSIG; signo++) {
12322 char *tr = trap_ptr[signo];
12324 /* note: bash adds "SIG", but only if invoked
12325 * as "bash". If called as "sh", or if set -o posix,
12326 * then it prints short signal names.
12327 * We are printing short names: */
12328 out1fmt("trap -- %s %s\n",
12330 get_signame(signo));
12331 /* trap_ptr != trap only if we are in special-cased `trap` code.
12332 * In this case, we will exit very soon, no need to free(). */
12333 /* if (trap_ptr != trap && tp[0]) */
12338 if (trap_ptr != trap) {
12351 signo = get_signum(*ap);
12353 /* Mimic bash message exactly */
12354 ash_msg("%s: invalid signal specification", *ap);
12360 if (LONE_DASH(action))
12363 action = ckstrdup(action);
12367 may_have_traps = 1;
12368 trap[signo] = action;
12379 /* ============ Builtins */
12381 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12383 * Lists available builtins
12385 static int FAST_FUNC
12386 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12392 "Built-in commands:\n"
12393 "------------------\n");
12394 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12395 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12396 builtintab[i].name + 1);
12402 #if ENABLE_FEATURE_SH_STANDALONE
12404 const char *a = applet_names;
12406 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12411 a += strlen(a) + 1;
12416 return EXIT_SUCCESS;
12418 #endif /* FEATURE_SH_EXTRA_QUIET */
12421 * The export and readonly commands.
12423 static int FAST_FUNC
12424 exportcmd(int argc UNUSED_PARAM, char **argv)
12430 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12432 if (nextopt("p") != 'p') {
12437 p = strchr(name, '=');
12441 vp = *findvar(hashvar(name), name);
12447 setvar(name, p, flag);
12448 } while ((name = *++aptr) != NULL);
12452 showvars(argv[0], flag, 0);
12457 * Delete a function if it exists.
12460 unsetfunc(const char *name)
12462 struct tblentry *cmdp;
12464 cmdp = cmdlookup(name, 0);
12465 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12466 delete_cmd_entry();
12470 * The unset builtin command. We unset the function before we unset the
12471 * variable to allow a function to be unset when there is a readonly variable
12472 * with the same name.
12474 static int FAST_FUNC
12475 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12482 while ((i = nextopt("vf")) != 0) {
12486 for (ap = argptr; *ap; ap++) {
12499 static const unsigned char timescmd_str[] ALIGN1 = {
12500 ' ', offsetof(struct tms, tms_utime),
12501 '\n', offsetof(struct tms, tms_stime),
12502 ' ', offsetof(struct tms, tms_cutime),
12503 '\n', offsetof(struct tms, tms_cstime),
12506 static int FAST_FUNC
12507 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12509 unsigned long clk_tck, s, t;
12510 const unsigned char *p;
12513 clk_tck = sysconf(_SC_CLK_TCK);
12518 t = *(clock_t *)(((char *) &buf) + p[1]);
12521 out1fmt("%lum%lu.%03lus%c",
12523 (t * 1000) / clk_tck,
12531 #if ENABLE_SH_MATH_SUPPORT
12533 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12534 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12536 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12538 static int FAST_FUNC
12539 letcmd(int argc UNUSED_PARAM, char **argv)
12545 ash_msg_and_raise_error("expression expected");
12547 i = ash_arith(*argv);
12555 * The read builtin. Options:
12556 * -r Do not interpret '\' specially
12557 * -s Turn off echo (tty only)
12558 * -n NCHARS Read NCHARS max
12559 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12560 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12561 * -u FD Read from given FD instead of fd 0
12562 * This uses unbuffered input, which may be avoidable in some cases.
12563 * TODO: bash also has:
12564 * -a ARRAY Read into array[0],[1],etc
12565 * -d DELIM End on DELIM char, not newline
12566 * -e Use line editing (tty only)
12568 static int FAST_FUNC
12569 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12571 char *opt_n = NULL;
12572 char *opt_p = NULL;
12573 char *opt_t = NULL;
12574 char *opt_u = NULL;
12575 int read_flags = 0;
12579 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12588 read_flags |= BUILTIN_READ_SILENT;
12594 read_flags |= BUILTIN_READ_RAW;
12604 r = shell_builtin_read(setvar2,
12606 bltinlookup("IFS"), /* can be NULL */
12614 if ((uintptr_t)r > 1)
12615 ash_msg_and_raise_error(r);
12617 return (uintptr_t)r;
12620 static int FAST_FUNC
12621 umaskcmd(int argc UNUSED_PARAM, char **argv)
12623 static const char permuser[3] ALIGN1 = "ugo";
12624 static const char permmode[3] ALIGN1 = "rwx";
12625 static const short permmask[] ALIGN2 = {
12626 S_IRUSR, S_IWUSR, S_IXUSR,
12627 S_IRGRP, S_IWGRP, S_IXGRP,
12628 S_IROTH, S_IWOTH, S_IXOTH
12631 /* TODO: use bb_parse_mode() instead */
12636 int symbolic_mode = 0;
12638 while (nextopt("S") != '\0') {
12649 if (symbolic_mode) {
12653 for (i = 0; i < 3; i++) {
12656 *p++ = permuser[i];
12658 for (j = 0; j < 3; j++) {
12659 if ((mask & permmask[3 * i + j]) == 0) {
12660 *p++ = permmode[j];
12668 out1fmt("%.4o\n", mask);
12671 if (isdigit((unsigned char) *ap)) {
12674 if (*ap >= '8' || *ap < '0')
12675 ash_msg_and_raise_error(msg_illnum, argv[1]);
12676 mask = (mask << 3) + (*ap - '0');
12677 } while (*++ap != '\0');
12680 mask = ~mask & 0777;
12681 if (!bb_parse_mode(ap, &mask)) {
12682 ash_msg_and_raise_error("illegal mode: %s", ap);
12684 umask(~mask & 0777);
12690 static int FAST_FUNC
12691 ulimitcmd(int argc UNUSED_PARAM, char **argv)
12693 return shell_builtin_ulimit(argv);
12696 /* ============ main() and helpers */
12699 * Called to exit the shell.
12701 static void exitshell(void) NORETURN;
12709 status = exitstatus;
12710 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12711 if (setjmp(loc.loc)) {
12712 if (exception_type == EXEXIT)
12713 /* dash bug: it just does _exit(exitstatus) here
12714 * but we have to do setjobctl(0) first!
12715 * (bug is still not fixed in dash-0.5.3 - if you run dash
12716 * under Midnight Commander, on exit from dash MC is backgrounded) */
12717 status = exitstatus;
12720 exception_handler = &loc;
12727 flush_stdout_stderr();
12737 /* from input.c: */
12738 /* we will never free this */
12739 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
12742 signal(SIGCHLD, SIG_DFL);
12743 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12744 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12746 signal(SIGHUP, SIG_DFL);
12752 struct stat st1, st2;
12755 for (envp = environ; envp && *envp; envp++) {
12756 if (strchr(*envp, '=')) {
12757 setvareq(*envp, VEXPORT|VTEXTFIXED);
12761 setvar("PPID", utoa(getppid()), 0);
12763 p = lookupvar("PWD");
12765 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12766 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12773 * Process the shell command line arguments.
12776 procargs(char **argv)
12779 const char *xminusc;
12784 /* if (xargv[0]) - mmm, this is always true! */
12786 for (i = 0; i < NOPTS; i++)
12790 /* it already printed err message */
12791 raise_exception(EXERROR);
12795 if (*xargv == NULL) {
12797 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12800 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12804 for (i = 0; i < NOPTS; i++)
12805 if (optlist[i] == 2)
12810 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12815 } else if (!sflag) {
12816 setinputfile(*xargv, 0);
12819 commandname = arg0;
12822 shellparam.p = xargv;
12823 #if ENABLE_ASH_GETOPTS
12824 shellparam.optind = 1;
12825 shellparam.optoff = -1;
12827 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
12829 shellparam.nparam++;
12836 * Read /etc/profile or .profile.
12839 read_profile(const char *name)
12843 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12852 * This routine is called when an error or an interrupt occurs in an
12853 * interactive shell and control is returned to the main command loop.
12861 /* from input.c: */
12862 g_parsefile->left_in_buffer = 0;
12863 g_parsefile->left_in_line = 0; /* clear input buffer */
12865 /* from parser.c: */
12868 /* from redir.c: */
12869 clearredir(/*drop:*/ 0);
12873 static short profile_buf[16384];
12874 extern int etext();
12878 * Main routine. We initialize things, parse the arguments, execute
12879 * profiles if we're a login shell, and then call cmdloop to execute
12880 * commands. The setjmp call sets up the location to jump to when an
12881 * exception occurs. When an exception occurs the variable "state"
12882 * is used to figure out how far we had gotten.
12884 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
12885 int ash_main(int argc UNUSED_PARAM, char **argv)
12887 const char *shinit;
12888 volatile smallint state;
12889 struct jmploc jmploc;
12890 struct stackmark smark;
12892 /* Initialize global data */
12896 #if ENABLE_ASH_ALIAS
12902 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12905 #if ENABLE_FEATURE_EDITING
12906 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12909 if (setjmp(jmploc.loc)) {
12915 e = exception_type;
12919 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12922 outcslow('\n', stderr);
12924 popstackmark(&smark);
12925 FORCE_INT_ON; /* enable interrupts */
12934 exception_handler = &jmploc;
12937 TRACE(("Shell args: "));
12938 trace_puts_args(argv);
12940 rootpid = getpid();
12943 setstackmark(&smark);
12946 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
12948 const char *hp = lookupvar("HISTFILE");
12951 hp = lookupvar("HOME");
12953 char *defhp = concat_path_file(hp, ".ash_history");
12954 setvar("HISTFILE", defhp, 0);
12960 if (/* argv[0] && */ argv[0][0] == '-')
12964 read_profile("/etc/profile");
12967 read_profile(".profile");
12973 getuid() == geteuid() && getgid() == getegid() &&
12977 shinit = lookupvar("ENV");
12978 if (shinit != NULL && *shinit != '\0') {
12979 read_profile(shinit);
12985 /* evalstring pushes parsefile stack.
12986 * Ensure we don't falsely claim that 0 (stdin)
12987 * is one of stacked source fds.
12988 * Testcase: ash -c 'exec 1>&0' must not complain. */
12989 // if (!sflag) g_parsefile->pf_fd = -1;
12990 // ^^ not necessary since now we special-case fd 0
12991 // in is_hidden_fd() to not be considered "hidden fd"
12992 evalstring(minusc, 0);
12995 if (sflag || minusc == NULL) {
12996 #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
12998 const char *hp = lookupvar("HISTFILE");
13000 line_input_state->hist_file = hp;
13003 state4: /* XXX ??? - why isn't this before the "if" statement */
13011 extern void _mcleanup(void);
13021 * Copyright (c) 1989, 1991, 1993, 1994
13022 * The Regents of the University of California. All rights reserved.
13024 * This code is derived from software contributed to Berkeley by
13025 * Kenneth Almquist.
13027 * Redistribution and use in source and binary forms, with or without
13028 * modification, are permitted provided that the following conditions
13030 * 1. Redistributions of source code must retain the above copyright
13031 * notice, this list of conditions and the following disclaimer.
13032 * 2. Redistributions in binary form must reproduce the above copyright
13033 * notice, this list of conditions and the following disclaimer in the
13034 * documentation and/or other materials provided with the distribution.
13035 * 3. Neither the name of the University nor the names of its contributors
13036 * may be used to endorse or promote products derived from this software
13037 * without specific prior written permission.
13039 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13040 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13041 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13042 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13043 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13044 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13045 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13046 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13047 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13048 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF