1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
20 * The following should be set to reflect the type of system you have:
21 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22 * define SYSV if you are running under System V.
23 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24 * define DEBUG=2 to compile in and turn on debugging.
26 * When debugging is on, debugging info will be written to ./trace and
27 * a quit signal will generate a core dump.
30 /* Tweak debug output verbosity here */
37 #define JOBS ENABLE_ASH_JOB_CONTROL
45 #include "busybox.h" /* for applet_names */
46 //TODO: pull in some .h and find out do we have SINGLE_APPLET_MAIN?
47 //#include "applet_tables.h" doesn't work
52 #include "shell_common.h"
53 #include "builtin_read.h"
54 #include "builtin_ulimit.h"
56 #if ENABLE_ASH_RANDOM_SUPPORT
59 # define CLEAR_RANDOM_T(rnd) ((void)0)
62 #if defined SINGLE_APPLET_MAIN
63 /* STANDALONE does not make sense, and won't compile */
64 # undef CONFIG_FEATURE_SH_STANDALONE
65 # undef ENABLE_FEATURE_SH_STANDALONE
66 # undef IF_FEATURE_SH_STANDALONE
67 # undef IF_NOT_FEATURE_SH_STANDALONE(...)
68 # define ENABLE_FEATURE_SH_STANDALONE 0
69 # define IF_FEATURE_SH_STANDALONE(...)
70 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
74 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
78 # error "Do not even bother, ash will not run on NOMMU machine"
82 /* ============ Hash table sizes. Configurable. */
86 #define CMDTABLESIZE 31 /* should be prime */
89 /* ============ Shell options */
91 static const char *const optletters_optnames[] = {
106 #if ENABLE_ASH_BASH_COMPAT
115 #define optletters(n) optletters_optnames[n][0]
116 #define optnames(n) (optletters_optnames[n] + 1)
118 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
121 /* ============ Misc data */
123 static const char homestr[] ALIGN1 = "HOME";
124 static const char snlfmt[] ALIGN1 = "%s\n";
125 static const char msg_illnum[] ALIGN1 = "Illegal number: %s";
128 * We enclose jmp_buf in a structure so that we can declare pointers to
129 * jump locations. The global variable handler contains the location to
130 * jump to when an exception occurs, and the global variable exception_type
131 * contains a code identifying the exception. To implement nested
132 * exception handlers, the user should save the value of handler on entry
133 * to an inner scope, set handler to point to a jmploc structure for the
134 * inner scope, and restore handler on exit from the scope.
140 struct globals_misc {
141 /* pid of main shell */
143 /* shell level: 0 for the main shell, 1 for its children, and so on */
145 #define rootshell (!shlvl)
146 char *minusc; /* argument to -c option */
148 char *curdir; // = nullstr; /* current working directory */
149 char *physdir; // = nullstr; /* physical working directory */
151 char *arg0; /* value of $0 */
153 struct jmploc *exception_handler;
155 volatile int suppress_int; /* counter */
156 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
157 /* last pending signal */
158 volatile /*sig_atomic_t*/ smallint pending_sig;
159 smallint exception_type; /* kind of exception (0..5) */
161 #define EXINT 0 /* SIGINT received */
162 #define EXERROR 1 /* a generic error */
163 #define EXSHELLPROC 2 /* execute a shell procedure */
164 #define EXEXEC 3 /* command execution failed */
165 #define EXEXIT 4 /* exit the shell */
166 #define EXSIG 5 /* trapped signal in wait(1) */
169 char nullstr[1]; /* zero length string */
172 #define eflag optlist[0]
173 #define fflag optlist[1]
174 #define Iflag optlist[2]
175 #define iflag optlist[3]
176 #define mflag optlist[4]
177 #define nflag optlist[5]
178 #define sflag optlist[6]
179 #define xflag optlist[7]
180 #define vflag optlist[8]
181 #define Cflag optlist[9]
182 #define aflag optlist[10]
183 #define bflag optlist[11]
184 #define uflag optlist[12]
185 #define viflag optlist[13]
186 #if ENABLE_ASH_BASH_COMPAT
187 # define pipefail optlist[14]
192 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
193 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
196 /* trap handler commands */
198 * Sigmode records the current value of the signal handlers for the various
199 * modes. A value of zero means that the current handler is not known.
200 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
202 char sigmode[NSIG - 1];
203 #define S_DFL 1 /* default signal handling (SIG_DFL) */
204 #define S_CATCH 2 /* signal is caught */
205 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
206 #define S_HARD_IGN 4 /* signal is ignored permenantly */
208 /* indicates specified signal received */
209 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
211 char **trap_ptr; /* used only by "trap hack" */
213 /* Rarely referenced stuff */
214 #if ENABLE_ASH_RANDOM_SUPPORT
217 pid_t backgndpid; /* pid of last background process */
218 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
220 extern struct globals_misc *const ash_ptr_to_globals_misc;
221 #define G_misc (*ash_ptr_to_globals_misc)
222 #define rootpid (G_misc.rootpid )
223 #define shlvl (G_misc.shlvl )
224 #define minusc (G_misc.minusc )
225 #define curdir (G_misc.curdir )
226 #define physdir (G_misc.physdir )
227 #define arg0 (G_misc.arg0 )
228 #define exception_handler (G_misc.exception_handler)
229 #define exception_type (G_misc.exception_type )
230 #define suppress_int (G_misc.suppress_int )
231 #define pending_int (G_misc.pending_int )
232 #define pending_sig (G_misc.pending_sig )
233 #define isloginsh (G_misc.isloginsh )
234 #define nullstr (G_misc.nullstr )
235 #define optlist (G_misc.optlist )
236 #define sigmode (G_misc.sigmode )
237 #define gotsig (G_misc.gotsig )
238 #define trap (G_misc.trap )
239 #define trap_ptr (G_misc.trap_ptr )
240 #define random_gen (G_misc.random_gen )
241 #define backgndpid (G_misc.backgndpid )
242 #define job_warning (G_misc.job_warning)
243 #define INIT_G_misc() do { \
244 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
252 /* ============ DEBUG */
254 static void trace_printf(const char *fmt, ...);
255 static void trace_vprintf(const char *fmt, va_list va);
256 # define TRACE(param) trace_printf param
257 # define TRACEV(param) trace_vprintf param
258 # define close(fd) do { \
260 if (close(dfd) < 0) \
261 bb_error_msg("bug on %d: closing %d(0x%x)", \
262 __LINE__, dfd, dfd); \
265 # define TRACE(param)
266 # define TRACEV(param)
270 /* ============ Utility functions */
271 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
273 static int isdigit_str9(const char *str)
275 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
276 while (--maxlen && isdigit(*str))
278 return (*str == '\0');
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 onsig() */
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 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->fd)
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 *text; /* name=value */
1715 void (*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 {
1770 void (*func)(const char *) FAST_FUNC;
1771 } varinit_data[] = {
1772 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1774 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1775 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", 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\0", change_random },
1787 #if ENABLE_LOCALE_SUPPORT
1788 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1789 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
1791 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1792 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", 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].text = varinit_data[i].text; \
1821 varinit[i].func = varinit_data[i].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.text + 4)
1853 #define ifsset() ((vifs.flags & VUNSET) == 0)
1855 # define mailval() (vmail.text + 5)
1856 # define mpathval() (vmpath.text + 9)
1857 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1859 #define pathval() (vpath.text + 5)
1860 #define ps1val() (vps1.text + 4)
1861 #define ps2val() (vps2.text + 4)
1862 #define ps4val() (vps4.text + 4)
1863 #if ENABLE_ASH_GETOPTS
1864 # define optindval() (voptind.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 varequal(const char *a, const char *b)
1926 return !varcmp(a, b);
1930 * Find the appropriate entry in the hash table from the name.
1932 static struct var **
1933 hashvar(const char *p)
1937 hashval = ((unsigned char) *p) << 4;
1938 while (*p && *p != '=')
1939 hashval += (unsigned char) *p++;
1940 return &vartab[hashval % VTABSIZE];
1944 vpcmp(const void *a, const void *b)
1946 return varcmp(*(const char **)a, *(const char **)b);
1950 * This routine initializes the builtin variables.
1960 * PS1 depends on uid
1962 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1963 vps1.text = "PS1=\\w \\$ ";
1966 vps1.text = "PS1=# ";
1969 end = vp + ARRAY_SIZE(varinit);
1971 vpp = hashvar(vp->text);
1974 } while (++vp < end);
1977 static struct var **
1978 findvar(struct var **vpp, const char *name)
1980 for (; *vpp; vpp = &(*vpp)->next) {
1981 if (varequal((*vpp)->text, name)) {
1989 * Find the value of a variable. Returns NULL if not set.
1991 static const char* FAST_FUNC
1992 lookupvar(const char *name)
1996 v = *findvar(hashvar(name), name);
1998 #if ENABLE_ASH_RANDOM_SUPPORT
2000 * Dynamic variables are implemented roughly the same way they are
2001 * in bash. Namely, they're "special" so long as they aren't unset.
2002 * As soon as they're unset, they're no longer dynamic, and dynamic
2003 * lookup will no longer happen at that point. -- PFM.
2005 if ((v->flags & VDYNAMIC))
2008 if (!(v->flags & VUNSET))
2009 return strchrnul(v->text, '=') + 1;
2015 * Search the environment of a builtin command.
2018 bltinlookup(const char *name)
2022 for (sp = cmdenviron; sp; sp = sp->next) {
2023 if (varequal(sp->text, name))
2024 return strchrnul(sp->text, '=') + 1;
2026 return lookupvar(name);
2030 * Same as setvar except that the variable and value are passed in
2031 * the first argument as name=value. Since the first argument will
2032 * be actually stored in the table, it should not be a string that
2034 * Called with interrupts off.
2037 setvareq(char *s, int flags)
2039 struct var *vp, **vpp;
2042 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2043 vp = *findvar(vpp, s);
2045 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2048 if (flags & VNOSAVE)
2051 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2057 if (vp->func && (flags & VNOFUNC) == 0)
2058 (*vp->func)(strchrnul(s, '=') + 1);
2060 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2061 free((char*)vp->text);
2063 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2068 vp = ckzalloc(sizeof(*vp));
2070 /*vp->func = NULL; - ckzalloc did it */
2073 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2080 * Set the value of a variable. The flags argument is ored with the
2081 * flags of the variable. If val is NULL, the variable is unset.
2084 setvar(const char *name, const char *val, int flags)
2091 q = endofname(name);
2092 p = strchrnul(q, '=');
2094 if (!namelen || p != q)
2095 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2100 vallen = strlen(val);
2103 nameeq = ckmalloc(namelen + vallen + 2);
2104 p = (char *)memcpy(nameeq, name, namelen) + namelen;
2107 p = (char *)memcpy(p, val, vallen) + vallen;
2110 setvareq(nameeq, flags | VNOSAVE);
2114 static void FAST_FUNC
2115 setvar2(const char *name, const char *val)
2117 setvar(name, val, 0);
2120 #if ENABLE_ASH_GETOPTS
2122 * Safe version of setvar, returns 1 on success 0 on failure.
2125 setvarsafe(const char *name, const char *val, int flags)
2128 volatile int saveint;
2129 struct jmploc *volatile savehandler = exception_handler;
2130 struct jmploc jmploc;
2133 if (setjmp(jmploc.loc))
2136 exception_handler = &jmploc;
2137 setvar(name, val, flags);
2140 exception_handler = savehandler;
2141 RESTORE_INT(saveint);
2147 * Unset the specified variable.
2150 unsetvar(const char *s)
2156 vpp = findvar(hashvar(s), s);
2160 int flags = vp->flags;
2163 if (flags & VREADONLY)
2165 #if ENABLE_ASH_RANDOM_SUPPORT
2166 vp->flags &= ~VDYNAMIC;
2170 if ((flags & VSTRFIXED) == 0) {
2172 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2173 free((char*)vp->text);
2179 vp->flags &= ~VEXPORT;
2189 * Process a linked list of variable assignments.
2192 listsetvar(struct strlist *list_set_var, int flags)
2194 struct strlist *lp = list_set_var;
2200 setvareq(lp->text, flags);
2207 * Generate a list of variables satisfying the given conditions.
2210 listvars(int on, int off, char ***end)
2221 for (vp = *vpp; vp; vp = vp->next) {
2222 if ((vp->flags & mask) == on) {
2223 if (ep == stackstrend())
2224 ep = growstackstr();
2225 *ep++ = (char *) vp->text;
2228 } while (++vpp < vartab + VTABSIZE);
2229 if (ep == stackstrend())
2230 ep = growstackstr();
2234 return grabstackstr(ep);
2238 /* ============ Path search helper
2240 * The variable path (passed by reference) should be set to the start
2241 * of the path before the first call; path_advance will update
2242 * this value as it proceeds. Successive calls to path_advance will return
2243 * the possible path expansions in sequence. If an option (indicated by
2244 * a percent sign) appears in the path entry then the global variable
2245 * pathopt will be set to point to it; otherwise pathopt will be set to
2248 static const char *pathopt; /* set by path_advance */
2251 path_advance(const char **path, const char *name)
2261 for (p = start; *p && *p != ':' && *p != '%'; p++)
2263 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2264 while (stackblocksize() < len)
2268 memcpy(q, start, p - start);
2276 while (*p && *p != ':')
2283 return stalloc(len);
2287 /* ============ Prompt */
2289 static smallint doprompt; /* if set, prompt the user */
2290 static smallint needprompt; /* true if interactive and at start of line */
2292 #if ENABLE_FEATURE_EDITING
2293 static line_input_t *line_input_state;
2294 static const char *cmdedit_prompt;
2296 putprompt(const char *s)
2298 if (ENABLE_ASH_EXPAND_PRMT) {
2299 free((char*)cmdedit_prompt);
2300 cmdedit_prompt = ckstrdup(s);
2307 putprompt(const char *s)
2313 #if ENABLE_ASH_EXPAND_PRMT
2314 /* expandstr() needs parsing machinery, so it is far away ahead... */
2315 static const char *expandstr(const char *ps);
2317 #define expandstr(s) s
2321 setprompt(int whichprompt)
2324 #if ENABLE_ASH_EXPAND_PRMT
2325 struct stackmark smark;
2330 switch (whichprompt) {
2340 #if ENABLE_ASH_EXPAND_PRMT
2341 setstackmark(&smark);
2342 stalloc(stackblocksize());
2344 putprompt(expandstr(prompt));
2345 #if ENABLE_ASH_EXPAND_PRMT
2346 popstackmark(&smark);
2351 /* ============ The cd and pwd commands */
2353 #define CD_PHYSICAL 1
2363 while ((i = nextopt("LP")) != '\0') {
2365 flags ^= CD_PHYSICAL;
2374 * Update curdir (the name of the current directory) in response to a
2378 updatepwd(const char *dir)
2385 cdcomppath = ststrdup(dir);
2388 if (curdir == nullstr)
2390 new = stack_putstr(curdir, new);
2392 new = makestrspace(strlen(dir) + 2, new);
2393 lim = (char *)stackblock() + 1;
2397 if (new > lim && *lim == '/')
2402 if (dir[1] == '/' && dir[2] != '/') {
2408 p = strtok(cdcomppath, "/");
2412 if (p[1] == '.' && p[2] == '\0') {
2424 new = stack_putstr(p, new);
2432 return stackblock();
2436 * Find out what the current directory is. If we already know the current
2437 * directory, this routine returns immediately.
2442 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2443 return dir ? dir : nullstr;
2447 setpwd(const char *val, int setold)
2451 oldcur = dir = curdir;
2454 setvar("OLDPWD", oldcur, VEXPORT);
2457 if (physdir != nullstr) {
2458 if (physdir != oldcur)
2462 if (oldcur == val || !val) {
2468 dir = ckstrdup(val);
2469 if (oldcur != dir && oldcur != nullstr) {
2474 setvar("PWD", dir, VEXPORT);
2477 static void hashcd(void);
2480 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2481 * know that the current directory has changed.
2484 docd(const char *dest, int flags)
2486 const char *dir = NULL;
2489 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2492 if (!(flags & CD_PHYSICAL)) {
2493 dir = updatepwd(dest);
2507 static int FAST_FUNC
2508 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2520 dest = bltinlookup(homestr);
2521 else if (LONE_DASH(dest)) {
2522 dest = bltinlookup("OLDPWD");
2544 path = bltinlookup("CDPATH");
2553 p = path_advance(&path, dest);
2554 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2558 if (!docd(p, flags))
2563 ash_msg_and_raise_error("can't cd to %s", dest);
2566 if (flags & CD_PRINT)
2567 out1fmt(snlfmt, curdir);
2571 static int FAST_FUNC
2572 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2575 const char *dir = curdir;
2579 if (physdir == nullstr)
2583 out1fmt(snlfmt, dir);
2588 /* ============ ... */
2591 #define IBUFSIZ COMMON_BUFSIZE
2592 /* buffer for top level input file */
2593 #define basebuf bb_common_bufsiz1
2595 /* Syntax classes */
2596 #define CWORD 0 /* character is nothing special */
2597 #define CNL 1 /* newline character */
2598 #define CBACK 2 /* a backslash character */
2599 #define CSQUOTE 3 /* single quote */
2600 #define CDQUOTE 4 /* double quote */
2601 #define CENDQUOTE 5 /* a terminating quote */
2602 #define CBQUOTE 6 /* backwards single quote */
2603 #define CVAR 7 /* a dollar sign */
2604 #define CENDVAR 8 /* a '}' character */
2605 #define CLP 9 /* a left paren in arithmetic */
2606 #define CRP 10 /* a right paren in arithmetic */
2607 #define CENDFILE 11 /* end of file */
2608 #define CCTL 12 /* like CWORD, except it must be escaped */
2609 #define CSPCL 13 /* these terminate a word */
2610 #define CIGN 14 /* character should be ignored */
2613 #if ENABLE_ASH_ALIAS
2617 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2619 #if ENABLE_SH_MATH_SUPPORT
2620 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2622 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2624 static const uint16_t S_I_T[] = {
2625 #if ENABLE_ASH_ALIAS
2626 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2628 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2629 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2630 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2631 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2632 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2633 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2634 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2635 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2636 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2637 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2638 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2639 #if !USE_SIT_FUNCTION
2640 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2641 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2642 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2646 /* Constants below must match table above */
2648 #if ENABLE_ASH_ALIAS
2649 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2651 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2652 CNL_CNL_CNL_CNL , /* 2 */
2653 CWORD_CCTL_CCTL_CWORD , /* 3 */
2654 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2655 CVAR_CVAR_CWORD_CVAR , /* 5 */
2656 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2657 CSPCL_CWORD_CWORD_CLP , /* 7 */
2658 CSPCL_CWORD_CWORD_CRP , /* 8 */
2659 CBACK_CBACK_CCTL_CBACK , /* 9 */
2660 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2661 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2662 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2663 CWORD_CWORD_CWORD_CWORD , /* 13 */
2664 CCTL_CCTL_CCTL_CCTL , /* 14 */
2667 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2668 * caller must ensure proper cast on it if c is *char_ptr!
2670 /* Values for syntax param */
2671 #define BASESYNTAX 0 /* not in quotes */
2672 #define DQSYNTAX 1 /* in double quotes */
2673 #define SQSYNTAX 2 /* in single quotes */
2674 #define ARISYNTAX 3 /* in arithmetic */
2675 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2677 #if USE_SIT_FUNCTION
2680 SIT(int c, int syntax)
2682 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2683 # if ENABLE_ASH_ALIAS
2684 static const uint8_t syntax_index_table[] ALIGN1 = {
2685 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2686 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2687 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2691 static const uint8_t syntax_index_table[] ALIGN1 = {
2692 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2693 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2694 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2703 # if ENABLE_ASH_ALIAS
2709 /* Cast is purely for paranoia here,
2710 * just in case someone passed signed char to us */
2711 if ((unsigned char)c >= CTL_FIRST
2712 && (unsigned char)c <= CTL_LAST
2716 s = strchrnul(spec_symbls, c);
2719 indx = syntax_index_table[s - spec_symbls];
2721 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2724 #else /* !USE_SIT_FUNCTION */
2726 static const uint8_t syntax_index_table[] = {
2727 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2728 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2738 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2739 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2760 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2761 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2762 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2763 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2764 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2765 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2766 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2767 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2768 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2769 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2770 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2771 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2772 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2773 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2774 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2775 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2776 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2777 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2778 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2779 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2780 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2781 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2782 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2783 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2784 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2785 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2786 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2787 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2788 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2789 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2790 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2791 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2792 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2793 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2794 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2795 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2796 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2797 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2800 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2802 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2803 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2814 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2815 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2816 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2817 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2819 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2820 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2821 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2822 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2823 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2824 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2825 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2848 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2849 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2850 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2851 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2852 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2853 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2854 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2855 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2856 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2858 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2859 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2860 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2861 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2862 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2863 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2864 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2865 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 162 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 163 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 164 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 165 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 166 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 167 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 168 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 169 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 170 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 171 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 172 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 173 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 174 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 175 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 176 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 177 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 178 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 179 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 180 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 181 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 182 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 183 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 184 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 185 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 186 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 187 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 188 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 189 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 190 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 191 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 192 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 193 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 194 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 195 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 196 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 197 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 198 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 199 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 200 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 201 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 202 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 203 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 204 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 205 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 206 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 207 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 208 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 209 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 210 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 211 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 212 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 213 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 214 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 215 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 216 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 217 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 218 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 219 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 220 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 221 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 222 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 223 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 224 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 225 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 226 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 227 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 228 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 229 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 231 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 232 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 233 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 234 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 235 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 236 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 237 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 238 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 239 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 241 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 242 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 243 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 244 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 245 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 246 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 247 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 248 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 249 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 250 */ CWORD_CWORD_CWORD_CWORD,
2979 /* 251 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 252 */ CWORD_CWORD_CWORD_CWORD,
2981 /* 253 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 254 */ CWORD_CWORD_CWORD_CWORD,
2983 /* 255 */ CWORD_CWORD_CWORD_CWORD,
2984 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2985 # if ENABLE_ASH_ALIAS
2986 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
2990 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
2992 #endif /* !USE_SIT_FUNCTION */
2995 /* ============ Alias handling */
2997 #if ENABLE_ASH_ALIAS
2999 #define ALIASINUSE 1
3010 static struct alias **atab; // [ATABSIZE];
3011 #define INIT_G_alias() do { \
3012 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3016 static struct alias **
3017 __lookupalias(const char *name) {
3018 unsigned int hashval;
3025 ch = (unsigned char)*p;
3029 ch = (unsigned char)*++p;
3031 app = &atab[hashval % ATABSIZE];
3033 for (; *app; app = &(*app)->next) {
3034 if (strcmp(name, (*app)->name) == 0) {
3042 static struct alias *
3043 lookupalias(const char *name, int check)
3045 struct alias *ap = *__lookupalias(name);
3047 if (check && ap && (ap->flag & ALIASINUSE))
3052 static struct alias *
3053 freealias(struct alias *ap)
3057 if (ap->flag & ALIASINUSE) {
3058 ap->flag |= ALIASDEAD;
3070 setalias(const char *name, const char *val)
3072 struct alias *ap, **app;
3074 app = __lookupalias(name);
3078 if (!(ap->flag & ALIASINUSE)) {
3081 ap->val = ckstrdup(val);
3082 ap->flag &= ~ALIASDEAD;
3085 ap = ckzalloc(sizeof(struct alias));
3086 ap->name = ckstrdup(name);
3087 ap->val = ckstrdup(val);
3088 /*ap->flag = 0; - ckzalloc did it */
3089 /*ap->next = NULL;*/
3096 unalias(const char *name)
3100 app = __lookupalias(name);
3104 *app = freealias(*app);
3115 struct alias *ap, **app;
3119 for (i = 0; i < ATABSIZE; i++) {
3121 for (ap = *app; ap; ap = *app) {
3122 *app = freealias(*app);
3132 printalias(const struct alias *ap)
3134 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3138 * TODO - sort output
3140 static int FAST_FUNC
3141 aliascmd(int argc UNUSED_PARAM, char **argv)
3150 for (i = 0; i < ATABSIZE; i++) {
3151 for (ap = atab[i]; ap; ap = ap->next) {
3157 while ((n = *++argv) != NULL) {
3158 v = strchr(n+1, '=');
3159 if (v == NULL) { /* n+1: funny ksh stuff */
3160 ap = *__lookupalias(n);
3162 fprintf(stderr, "%s: %s not found\n", "alias", n);
3175 static int FAST_FUNC
3176 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3180 while ((i = nextopt("a")) != '\0') {
3186 for (i = 0; *argptr; argptr++) {
3187 if (unalias(*argptr)) {
3188 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3196 #endif /* ASH_ALIAS */
3199 /* ============ jobs.c */
3201 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3204 #define FORK_NOJOB 2
3206 /* mode flags for showjob(s) */
3207 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3208 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3209 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3212 * A job structure contains information about a job. A job is either a
3213 * single process or a set of processes contained in a pipeline. In the
3214 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3218 pid_t ps_pid; /* process id */
3219 int ps_status; /* last process status from wait() */
3220 char *ps_cmd; /* text of command being run */
3224 struct procstat ps0; /* status of process */
3225 struct procstat *ps; /* status or processes when more than one */
3227 int stopstatus; /* status of a stopped job */
3230 nprocs: 16, /* number of processes */
3232 #define JOBRUNNING 0 /* at least one proc running */
3233 #define JOBSTOPPED 1 /* all procs are stopped */
3234 #define JOBDONE 2 /* all procs are completed */
3236 sigint: 1, /* job was killed by SIGINT */
3237 jobctl: 1, /* job running under job control */
3239 waited: 1, /* true if this entry has been waited for */
3240 used: 1, /* true if this entry is in used */
3241 changed: 1; /* true if status has changed */
3242 struct job *prev_job; /* previous job */
3245 static struct job *makejob(/*union node *,*/ int);
3246 static int forkshell(struct job *, union node *, int);
3247 static int waitforjob(struct job *);
3250 enum { doing_jobctl = 0 };
3251 #define setjobctl(on) do {} while (0)
3253 static smallint doing_jobctl; //references:8
3254 static void setjobctl(int);
3261 ignoresig(int signo)
3263 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3264 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3265 /* No, need to do it */
3266 signal(signo, SIG_IGN);
3268 sigmode[signo - 1] = S_HARD_IGN;
3272 * Signal handler. Only one usage site - in setsignal()
3277 gotsig[signo - 1] = 1;
3279 if (signo == SIGINT && !trap[SIGINT]) {
3280 if (!suppress_int) {
3282 raise_interrupt(); /* does not return */
3286 pending_sig = signo;
3291 * Set the signal handler for the specified signal. The routine figures
3292 * out what it should be set to.
3295 setsignal(int signo)
3298 char cur_act, new_act;
3299 struct sigaction act;
3303 if (t != NULL) { /* trap for this sig is set */
3305 if (t[0] == '\0') /* trap is "": ignore this sig */
3309 if (rootshell && new_act == S_DFL) {
3312 if (iflag || minusc || sflag == 0)
3321 * "In all cases, bash ignores SIGQUIT. Non-builtin
3322 * commands run by bash have signal handlers
3323 * set to the values inherited by the shell
3324 * from its parent". */
3340 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3341 //whereas we have to restore it to what shell got on entry
3342 //from the parent. See comment above
3344 t = &sigmode[signo - 1];
3347 /* current setting is not yet known */
3348 if (sigaction(signo, NULL, &act)) {
3349 /* pretend it worked; maybe we should give a warning,
3350 * but other shells don't. We don't alter sigmode,
3351 * so we retry every time.
3352 * btw, in Linux it never fails. --vda */
3355 if (act.sa_handler == SIG_IGN) {
3356 cur_act = S_HARD_IGN;
3358 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3360 cur_act = S_IGN; /* don't hard ignore these */
3364 if (cur_act == S_HARD_IGN || cur_act == new_act)
3367 act.sa_handler = SIG_DFL;
3370 act.sa_handler = onsig;
3371 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3372 sigfillset(&act.sa_mask); /* ditto */
3375 act.sa_handler = SIG_IGN;
3378 sigaction_set(signo, &act);
3383 /* mode flags for set_curjob */
3384 #define CUR_DELETE 2
3385 #define CUR_RUNNING 1
3386 #define CUR_STOPPED 0
3388 /* mode flags for dowait */
3389 #define DOWAIT_NONBLOCK WNOHANG
3390 #define DOWAIT_BLOCK 0
3393 /* pgrp of shell on invocation */
3394 static int initialpgrp; //references:2
3395 static int ttyfd = -1; //5
3398 static struct job *jobtab; //5
3400 static unsigned njobs; //4
3402 static struct job *curjob; //lots
3403 /* number of presumed living untracked jobs */
3404 static int jobless; //4
3407 set_curjob(struct job *jp, unsigned mode)
3410 struct job **jpp, **curp;
3412 /* first remove from list */
3413 jpp = curp = &curjob;
3418 jpp = &jp1->prev_job;
3420 *jpp = jp1->prev_job;
3422 /* Then re-insert in correct position */
3430 /* job being deleted */
3433 /* newly created job or backgrounded job,
3434 put after all stopped jobs. */
3438 if (!jp1 || jp1->state != JOBSTOPPED)
3441 jpp = &jp1->prev_job;
3447 /* newly stopped job - becomes curjob */
3448 jp->prev_job = *jpp;
3456 jobno(const struct job *jp)
3458 return jp - jobtab + 1;
3463 * Convert a job name to a job structure.
3466 #define getjob(name, getctl) getjob(name)
3469 getjob(const char *name, int getctl)
3473 const char *err_msg = "%s: no such job";
3477 char *(*match)(const char *, const char *);
3492 if (c == '+' || c == '%') {
3494 err_msg = "No current job";
3500 err_msg = "No previous job";
3511 jp = jobtab + num - 1;
3526 if (match(jp->ps[0].ps_cmd, p)) {
3530 err_msg = "%s: ambiguous";
3540 err_msg = "job %s not created under job control";
3541 if (getctl && jp->jobctl == 0)
3546 ash_msg_and_raise_error(err_msg, name);
3550 * Mark a job structure as unused.
3553 freejob(struct job *jp)
3555 struct procstat *ps;
3559 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3560 if (ps->ps_cmd != nullstr)
3563 if (jp->ps != &jp->ps0)
3566 set_curjob(jp, CUR_DELETE);
3572 xtcsetpgrp(int fd, pid_t pgrp)
3574 if (tcsetpgrp(fd, pgrp))
3575 ash_msg_and_raise_error("can't set tty process group (%m)");
3579 * Turn job control on and off.
3581 * Note: This code assumes that the third arg to ioctl is a character
3582 * pointer, which is true on Berkeley systems but not System V. Since
3583 * System V doesn't have job control yet, this isn't a problem now.
3585 * Called with interrupts off.
3593 if (on == doing_jobctl || rootshell == 0)
3597 ofd = fd = open(_PATH_TTY, O_RDWR);
3599 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3600 * That sometimes helps to acquire controlling tty.
3601 * Obviously, a workaround for bugs when someone
3602 * failed to provide a controlling tty to bash! :) */
3608 fd = fcntl(fd, F_DUPFD, 10);
3613 /* fd is a tty at this point */
3614 close_on_exec_on(fd);
3615 do { /* while we are in the background */
3616 pgrp = tcgetpgrp(fd);
3619 ash_msg("can't access tty; job control turned off");
3623 if (pgrp == getpgrp())
3634 xtcsetpgrp(fd, pgrp);
3636 /* turning job control off */
3639 /* was xtcsetpgrp, but this can make exiting ash
3640 * loop forever if pty is already deleted */
3641 tcsetpgrp(fd, pgrp);
3655 static int FAST_FUNC
3656 killcmd(int argc, char **argv)
3659 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3661 if (argv[i][0] == '%') {
3662 struct job *jp = getjob(argv[i], 0);
3663 unsigned pid = jp->ps[0].ps_pid;
3664 /* Enough space for ' -NNN<nul>' */
3665 argv[i] = alloca(sizeof(int)*3 + 3);
3666 /* kill_main has matching code to expect
3667 * leading space. Needed to not confuse
3668 * negative pids with "kill -SIGNAL_NO" syntax */
3669 sprintf(argv[i], " -%u", pid);
3671 } while (argv[++i]);
3673 return kill_main(argc, argv);
3677 showpipe(struct job *jp /*, FILE *out*/)
3679 struct procstat *ps;
3680 struct procstat *psend;
3682 psend = jp->ps + jp->nprocs;
3683 for (ps = jp->ps + 1; ps < psend; ps++)
3684 printf(" | %s", ps->ps_cmd);
3685 outcslow('\n', stdout);
3686 flush_stdout_stderr();
3691 restartjob(struct job *jp, int mode)
3693 struct procstat *ps;
3699 if (jp->state == JOBDONE)
3701 jp->state = JOBRUNNING;
3702 pgid = jp->ps[0].ps_pid;
3703 if (mode == FORK_FG)
3704 xtcsetpgrp(ttyfd, pgid);
3705 killpg(pgid, SIGCONT);
3709 if (WIFSTOPPED(ps->ps_status)) {
3715 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3720 static int FAST_FUNC
3721 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3727 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3731 jp = getjob(*argv, 1);
3732 if (mode == FORK_BG) {
3733 set_curjob(jp, CUR_RUNNING);
3734 printf("[%d] ", jobno(jp));
3736 out1str(jp->ps[0].ps_cmd);
3737 showpipe(jp /*, stdout*/);
3738 retval = restartjob(jp, mode);
3739 } while (*argv && *++argv);
3745 sprint_status(char *s, int status, int sigonly)
3751 if (!WIFEXITED(status)) {
3753 if (WIFSTOPPED(status))
3754 st = WSTOPSIG(status);
3757 st = WTERMSIG(status);
3759 if (st == SIGINT || st == SIGPIPE)
3762 if (WIFSTOPPED(status))
3767 col = fmtstr(s, 32, strsignal(st));
3768 if (WCOREDUMP(status)) {
3769 col += fmtstr(s + col, 16, " (core dumped)");
3771 } else if (!sigonly) {
3772 st = WEXITSTATUS(status);
3774 col = fmtstr(s, 16, "Done(%d)", st);
3776 col = fmtstr(s, 16, "Done");
3783 dowait(int wait_flags, struct job *job)
3788 struct job *thisjob;
3791 TRACE(("dowait(0x%x) called\n", wait_flags));
3793 /* Do a wait system call. If job control is compiled in, we accept
3794 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3795 * NB: _not_ safe_waitpid, we need to detect EINTR */
3797 wait_flags |= WUNTRACED;
3798 pid = waitpid(-1, &status, wait_flags);
3799 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3800 pid, status, errno, strerror(errno)));
3806 for (jp = curjob; jp; jp = jp->prev_job) {
3807 struct procstat *ps;
3808 struct procstat *psend;
3809 if (jp->state == JOBDONE)
3813 psend = ps + jp->nprocs;
3815 if (ps->ps_pid == pid) {
3816 TRACE(("Job %d: changing status of proc %d "
3817 "from 0x%x to 0x%x\n",
3818 jobno(jp), pid, ps->ps_status, status));
3819 ps->ps_status = status;
3822 if (ps->ps_status == -1)
3825 if (state == JOBRUNNING)
3827 if (WIFSTOPPED(ps->ps_status)) {
3828 jp->stopstatus = ps->ps_status;
3832 } while (++ps < psend);
3837 if (!WIFSTOPPED(status))
3843 if (state != JOBRUNNING) {
3844 thisjob->changed = 1;
3846 if (thisjob->state != state) {
3847 TRACE(("Job %d: changing state from %d to %d\n",
3848 jobno(thisjob), thisjob->state, state));
3849 thisjob->state = state;
3851 if (state == JOBSTOPPED) {
3852 set_curjob(thisjob, CUR_STOPPED);
3861 if (thisjob && thisjob == job) {
3865 len = sprint_status(s, status, 1);
3876 blocking_wait_with_raise_on_sig(struct job *job)
3878 pid_t pid = dowait(DOWAIT_BLOCK, job);
3879 if (pid <= 0 && pending_sig)
3880 raise_exception(EXSIG);
3886 showjob(FILE *out, struct job *jp, int mode)
3888 struct procstat *ps;
3889 struct procstat *psend;
3896 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
3897 /* just output process (group) id of pipeline */
3898 fprintf(out, "%d\n", ps->ps_pid);
3902 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3907 else if (curjob && jp == curjob->prev_job)
3910 if (mode & SHOW_PIDS)
3911 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
3913 psend = ps + jp->nprocs;
3915 if (jp->state == JOBRUNNING) {
3916 strcpy(s + col, "Running");
3917 col += sizeof("Running") - 1;
3919 int status = psend[-1].ps_status;
3920 if (jp->state == JOBSTOPPED)
3921 status = jp->stopstatus;
3922 col += sprint_status(s + col, status, 0);
3924 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
3926 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3927 * or prints several "PID | <cmdN>" lines,
3928 * depending on SHOW_PIDS bit.
3929 * We do not print status of individual processes
3930 * between PID and <cmdN>. bash does it, but not very well:
3931 * first line shows overall job status, not process status,
3932 * making it impossible to know 1st process status.
3936 /* for each process */
3939 if (mode & SHOW_PIDS)
3940 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
3942 fprintf(out, "%s%*c%s%s",
3944 33 - col >= 0 ? 33 - col : 0, ' ',
3945 ps == jp->ps ? "" : "| ",
3948 } while (++ps != psend);
3949 outcslow('\n', out);
3953 if (jp->state == JOBDONE) {
3954 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3960 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3961 * statuses have changed since the last call to showjobs.
3964 showjobs(FILE *out, int mode)
3968 TRACE(("showjobs(0x%x) called\n", mode));
3970 /* Handle all finished jobs */
3971 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
3974 for (jp = curjob; jp; jp = jp->prev_job) {
3975 if (!(mode & SHOW_CHANGED) || jp->changed) {
3976 showjob(out, jp, mode);
3981 static int FAST_FUNC
3982 jobscmd(int argc UNUSED_PARAM, char **argv)
3987 while ((m = nextopt("lp")) != '\0') {
3991 mode |= SHOW_ONLY_PGID;
3997 showjob(stdout, getjob(*argv, 0), mode);
4000 showjobs(stdout, mode);
4007 /* Called only on finished or stopped jobs (no members are running) */
4009 getstatus(struct job *job)
4013 struct procstat *ps;
4015 /* Fetch last member's status */
4016 ps = job->ps + job->nprocs - 1;
4017 status = ps->ps_status;
4019 /* "set -o pipefail" mode: use last _nonzero_ status */
4020 while (status == 0 && --ps >= job->ps)
4021 status = ps->ps_status;
4024 retval = WEXITSTATUS(status);
4025 if (!WIFEXITED(status)) {
4027 retval = WSTOPSIG(status);
4028 if (!WIFSTOPPED(status))
4031 /* XXX: limits number of signals */
4032 retval = WTERMSIG(status);
4034 if (retval == SIGINT)
4040 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4041 jobno(job), job->nprocs, status, retval));
4045 static int FAST_FUNC
4046 waitcmd(int argc UNUSED_PARAM, char **argv)
4053 raise_exception(EXSIG);
4060 /* wait for all jobs */
4064 if (!jp) /* no running procs */
4066 if (jp->state == JOBRUNNING)
4072 * "When bash is waiting for an asynchronous command via
4073 * the wait builtin, the reception of a signal for which a trap
4074 * has been set will cause the wait builtin to return immediately
4075 * with an exit status greater than 128, immediately after which
4076 * the trap is executed."
4077 * Do we do it that way? */
4078 blocking_wait_with_raise_on_sig(NULL);
4084 if (**argv != '%') {
4085 pid_t pid = number(*argv);
4090 if (job->ps[job->nprocs - 1].ps_pid == pid)
4092 job = job->prev_job;
4095 job = getjob(*argv, 0);
4096 /* loop until process terminated or stopped */
4097 while (job->state == JOBRUNNING)
4098 blocking_wait_with_raise_on_sig(NULL);
4100 retval = getstatus(job);
4113 struct job *jp, *jq;
4115 len = njobs * sizeof(*jp);
4117 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4119 offset = (char *)jp - (char *)jq;
4121 /* Relocate pointers */
4124 jq = (struct job *)((char *)jq + l);
4128 #define joff(p) ((struct job *)((char *)(p) + l))
4129 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4130 if (joff(jp)->ps == &jq->ps0)
4131 jmove(joff(jp)->ps);
4132 if (joff(jp)->prev_job)
4133 jmove(joff(jp)->prev_job);
4143 jp = (struct job *)((char *)jp + len);
4147 } while (--jq >= jp);
4152 * Return a new job structure.
4153 * Called with interrupts off.
4156 makejob(/*union node *node,*/ int nprocs)
4161 for (i = njobs, jp = jobtab; ; jp++) {
4168 if (jp->state != JOBDONE || !jp->waited)
4177 memset(jp, 0, sizeof(*jp));
4179 /* jp->jobctl is a bitfield.
4180 * "jp->jobctl |= jobctl" likely to give awful code */
4184 jp->prev_job = curjob;
4189 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4191 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4198 * Return a string identifying a command (to be printed by the
4201 static char *cmdnextc;
4204 cmdputs(const char *s)
4206 static const char vstype[VSTYPE + 1][3] = {
4207 "", "}", "-", "+", "?", "=",
4208 "%", "%%", "#", "##"
4209 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4212 const char *p, *str;
4216 unsigned char subtype = 0;
4220 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4222 while ((c = *p++) != '\0') {
4230 if ((subtype & VSTYPE) == VSLENGTH)
4234 if (!(subtype & VSQUOTE) == !(quoted & 1))
4240 str = "\"}" + !(quoted & 1);
4247 case CTLBACKQ+CTLQUOTE:
4250 #if ENABLE_SH_MATH_SUPPORT
4265 if ((subtype & VSTYPE) != VSNORMAL)
4267 str = vstype[subtype & VSTYPE];
4268 if (subtype & VSNUL)
4277 /* These can only happen inside quotes */
4290 while ((c = *str++) != '\0') {
4293 } /* while *p++ not NUL */
4296 USTPUTC('"', nextc);
4302 /* cmdtxt() and cmdlist() call each other */
4303 static void cmdtxt(union node *n);
4306 cmdlist(union node *np, int sep)
4308 for (; np; np = np->narg.next) {
4312 if (sep && np->narg.next)
4318 cmdtxt(union node *n)
4321 struct nodelist *lp;
4332 lp = n->npipe.cmdlist;
4350 cmdtxt(n->nbinary.ch1);
4366 cmdtxt(n->nif.test);
4368 if (n->nif.elsepart) {
4369 cmdtxt(n->nif.ifpart);
4371 n = n->nif.elsepart;
4389 cmdtxt(n->nbinary.ch1);
4399 cmdputs(n->nfor.var);
4401 cmdlist(n->nfor.args, 1);
4406 cmdputs(n->narg.text);
4410 cmdlist(n->ncmd.args, 1);
4411 cmdlist(n->ncmd.redirect, 0);
4424 cmdputs(n->ncase.expr->narg.text);
4426 for (np = n->ncase.cases; np; np = np->nclist.next) {
4427 cmdtxt(np->nclist.pattern);
4429 cmdtxt(np->nclist.body);
4443 #if ENABLE_ASH_BASH_COMPAT
4458 cmdputs(utoa(n->nfile.fd));
4460 if (n->type == NTOFD || n->type == NFROMFD) {
4461 cmdputs(utoa(n->ndup.dupfd));
4470 commandtext(union node *n)
4474 STARTSTACKSTR(cmdnextc);
4476 name = stackblock();
4477 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4478 name, cmdnextc, cmdnextc));
4479 return ckstrdup(name);
4484 * Fork off a subshell. If we are doing job control, give the subshell its
4485 * own process group. Jp is a job structure that the job is to be added to.
4486 * N is the command that will be evaluated by the child. Both jp and n may
4487 * be NULL. The mode parameter can be one of the following:
4488 * FORK_FG - Fork off a foreground process.
4489 * FORK_BG - Fork off a background process.
4490 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4491 * process group even if job control is on.
4493 * When job control is turned off, background processes have their standard
4494 * input redirected to /dev/null (except for the second and later processes
4497 * Called with interrupts off.
4500 * Clear traps on a fork.
4507 for (tp = trap; tp < &trap[NSIG]; tp++) {
4508 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4510 if (trap_ptr == trap)
4512 /* else: it "belongs" to trap_ptr vector, don't free */
4514 if ((tp - trap) != 0)
4515 setsignal(tp - trap);
4521 /* Lives far away from here, needed for forkchild */
4522 static void closescript(void);
4524 /* Called after fork(), in child */
4525 static NOINLINE void
4526 forkchild(struct job *jp, union node *n, int mode)
4530 TRACE(("Child shell %d\n", getpid()));
4534 /* man bash: "Non-builtin commands run by bash have signal handlers
4535 * set to the values inherited by the shell from its parent".
4536 * Do we do it correctly? */
4540 if (mode == FORK_NOJOB /* is it `xxx` ? */
4541 && n && n->type == NCMD /* is it single cmd? */
4542 /* && n->ncmd.args->type == NARG - always true? */
4543 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4544 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4545 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4547 TRACE(("Trap hack\n"));
4548 /* Awful hack for `trap` or $(trap).
4550 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4551 * contains an example where "trap" is executed in a subshell:
4553 * save_traps=$(trap)
4555 * eval "$save_traps"
4557 * Standard does not say that "trap" in subshell shall print
4558 * parent shell's traps. It only says that its output
4559 * must have suitable form, but then, in the above example
4560 * (which is not supposed to be normative), it implies that.
4562 * bash (and probably other shell) does implement it
4563 * (traps are reset to defaults, but "trap" still shows them),
4564 * but as a result, "trap" logic is hopelessly messed up:
4567 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4568 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4569 * # true | trap <--- trap is in subshell - no output (ditto)
4570 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4571 * trap -- 'echo Ho' SIGWINCH
4572 * # echo `(trap)` <--- in subshell in subshell - output
4573 * trap -- 'echo Ho' SIGWINCH
4574 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4575 * trap -- 'echo Ho' SIGWINCH
4577 * The rules when to forget and when to not forget traps
4578 * get really complex and nonsensical.
4580 * Our solution: ONLY bare $(trap) or `trap` is special.
4582 /* Save trap handler strings for trap builtin to print */
4583 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4584 /* Fall through into clearing traps */
4588 /* do job control only in root shell */
4590 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4593 if (jp->nprocs == 0)
4596 pgrp = jp->ps[0].ps_pid;
4597 /* this can fail because we are doing it in the parent also */
4599 if (mode == FORK_FG)
4600 xtcsetpgrp(ttyfd, pgrp);
4605 if (mode == FORK_BG) {
4606 /* man bash: "When job control is not in effect,
4607 * asynchronous commands ignore SIGINT and SIGQUIT" */
4610 if (jp->nprocs == 0) {
4612 if (open(bb_dev_null, O_RDONLY) != 0)
4613 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4617 if (iflag) { /* why if iflag only? */
4622 * "In all cases, bash ignores SIGQUIT. Non-builtin
4623 * commands run by bash have signal handlers
4624 * set to the values inherited by the shell
4626 * Take care of the second rule: */
4630 if (n && n->type == NCMD
4631 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4633 TRACE(("Job hack\n"));
4634 /* "jobs": we do not want to clear job list for it,
4635 * instead we remove only _its_ own_ job from job list.
4636 * This makes "jobs .... | cat" more useful.
4642 for (jp = curjob; jp; jp = jp->prev_job)
4647 /* Called after fork(), in parent */
4649 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4652 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4654 TRACE(("In parent shell: child = %d\n", pid));
4656 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4662 if (mode != FORK_NOJOB && jp->jobctl) {
4665 if (jp->nprocs == 0)
4668 pgrp = jp->ps[0].ps_pid;
4669 /* This can fail because we are doing it in the child also */
4673 if (mode == FORK_BG) {
4674 backgndpid = pid; /* set $! */
4675 set_curjob(jp, CUR_RUNNING);
4678 struct procstat *ps = &jp->ps[jp->nprocs++];
4681 ps->ps_cmd = nullstr;
4683 if (doing_jobctl && n)
4684 ps->ps_cmd = commandtext(n);
4690 forkshell(struct job *jp, union node *n, int mode)
4694 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4697 TRACE(("Fork failed, errno=%d", errno));
4700 ash_msg_and_raise_error("can't fork");
4703 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4704 forkchild(jp, n, mode);
4706 forkparent(jp, n, mode, pid);
4712 * Wait for job to finish.
4714 * Under job control we have the problem that while a child process
4715 * is running interrupts generated by the user are sent to the child
4716 * but not to the shell. This means that an infinite loop started by
4717 * an interactive user may be hard to kill. With job control turned off,
4718 * an interactive user may place an interactive program inside a loop.
4719 * If the interactive program catches interrupts, the user doesn't want
4720 * these interrupts to also abort the loop. The approach we take here
4721 * is to have the shell ignore interrupt signals while waiting for a
4722 * foreground process to terminate, and then send itself an interrupt
4723 * signal if the child process was terminated by an interrupt signal.
4724 * Unfortunately, some programs want to do a bit of cleanup and then
4725 * exit on interrupt; unless these processes terminate themselves by
4726 * sending a signal to themselves (instead of calling exit) they will
4727 * confuse this approach.
4729 * Called with interrupts off.
4732 waitforjob(struct job *jp)
4736 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4739 while (jp->state == JOBRUNNING) {
4740 /* In non-interactive shells, we _can_ get
4741 * a keyboard signal here and be EINTRed,
4742 * but we just loop back, waiting for command to complete.
4745 * "If bash is waiting for a command to complete and receives
4746 * a signal for which a trap has been set, the trap
4747 * will not be executed until the command completes."
4749 * Reality is that even if trap is not set, bash
4750 * will not act on the signal until command completes.
4751 * Try this. sleep5intoff.c:
4752 * #include <signal.h>
4753 * #include <unistd.h>
4756 * sigemptyset(&set);
4757 * sigaddset(&set, SIGINT);
4758 * sigaddset(&set, SIGQUIT);
4759 * sigprocmask(SIG_BLOCK, &set, NULL);
4763 * $ bash -c './sleep5intoff; echo hi'
4764 * ^C^C^C^C <--- pressing ^C once a second
4766 * $ bash -c './sleep5intoff; echo hi'
4767 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4770 dowait(DOWAIT_BLOCK, jp);
4777 xtcsetpgrp(ttyfd, rootpid);
4779 * This is truly gross.
4780 * If we're doing job control, then we did a TIOCSPGRP which
4781 * caused us (the shell) to no longer be in the controlling
4782 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4783 * intuit from the subprocess exit status whether a SIGINT
4784 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4786 if (jp->sigint) /* TODO: do the same with all signals */
4787 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4789 if (jp->state == JOBDONE)
4796 * return 1 if there are stopped jobs, otherwise 0
4808 if (jp && jp->state == JOBSTOPPED) {
4809 out2str("You have stopped jobs.\n");
4818 /* ============ redir.c
4820 * Code for dealing with input/output redirection.
4823 #define EMPTY -2 /* marks an unused slot in redirtab */
4824 #define CLOSED -3 /* marks a slot of previously-closed fd */
4827 * Open a file in noclobber mode.
4828 * The code was copied from bash.
4831 noclobberopen(const char *fname)
4834 struct stat finfo, finfo2;
4837 * If the file exists and is a regular file, return an error
4840 r = stat(fname, &finfo);
4841 if (r == 0 && S_ISREG(finfo.st_mode)) {
4847 * If the file was not present (r != 0), make sure we open it
4848 * exclusively so that if it is created before we open it, our open
4849 * will fail. Make sure that we do not truncate an existing file.
4850 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4851 * file was not a regular file, we leave O_EXCL off.
4854 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4855 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4857 /* If the open failed, return the file descriptor right away. */
4862 * OK, the open succeeded, but the file may have been changed from a
4863 * non-regular file to a regular file between the stat and the open.
4864 * We are assuming that the O_EXCL open handles the case where FILENAME
4865 * did not exist and is symlinked to an existing file between the stat
4870 * If we can open it and fstat the file descriptor, and neither check
4871 * revealed that it was a regular file, and the file has not been
4872 * replaced, return the file descriptor.
4874 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4875 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4878 /* The file has been replaced. badness. */
4885 * Handle here documents. Normally we fork off a process to write the
4886 * data to a pipe. If the document is short, we can stuff the data in
4887 * the pipe without forking.
4889 /* openhere needs this forward reference */
4890 static void expandhere(union node *arg, int fd);
4892 openhere(union node *redir)
4898 ash_msg_and_raise_error("pipe call failed");
4899 if (redir->type == NHERE) {
4900 len = strlen(redir->nhere.doc->narg.text);
4901 if (len <= PIPE_BUF) {
4902 full_write(pip[1], redir->nhere.doc->narg.text, len);
4906 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4909 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4910 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4911 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4912 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4913 signal(SIGPIPE, SIG_DFL);
4914 if (redir->type == NHERE)
4915 full_write(pip[1], redir->nhere.doc->narg.text, len);
4917 expandhere(redir->nhere.doc, pip[1]);
4918 _exit(EXIT_SUCCESS);
4926 openredirect(union node *redir)
4931 switch (redir->nfile.type) {
4933 fname = redir->nfile.expfname;
4934 f = open(fname, O_RDONLY);
4939 fname = redir->nfile.expfname;
4940 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4945 #if ENABLE_ASH_BASH_COMPAT
4948 /* Take care of noclobber mode. */
4950 fname = redir->nfile.expfname;
4951 f = noclobberopen(fname);
4958 fname = redir->nfile.expfname;
4959 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4964 fname = redir->nfile.expfname;
4965 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4973 /* Fall through to eliminate warning. */
4974 /* Our single caller does this itself */
4981 f = openhere(redir);
4987 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4989 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
4993 * Copy a file descriptor to be >= to. Returns -1
4994 * if the source file descriptor is closed, EMPTY if there are no unused
4995 * file descriptors left.
4997 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
4998 * old code was doing close(to) prior to copyfd() to achieve the same */
5000 COPYFD_EXACT = (int)~(INT_MAX),
5001 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5004 copyfd(int from, int to)
5008 if (to & COPYFD_EXACT) {
5009 to &= ~COPYFD_EXACT;
5011 newfd = dup2(from, to);
5013 newfd = fcntl(from, F_DUPFD, to);
5016 if (errno == EMFILE)
5018 /* Happens when source fd is not open: try "echo >&99" */
5019 ash_msg_and_raise_error("%d: %m", from);
5024 /* Struct def and variable are moved down to the first usage site */
5029 struct redirtab *next;
5032 struct two_fd_t two_fd[];
5034 #define redirlist (G_var.redirlist)
5036 static int need_to_remember(struct redirtab *rp, int fd)
5040 if (!rp) /* remembering was not requested */
5043 for (i = 0; i < rp->pair_count; i++) {
5044 if (rp->two_fd[i].orig == fd) {
5045 /* already remembered */
5052 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5053 static int is_hidden_fd(struct redirtab *rp, int fd)
5056 struct parsefile *pf;
5069 fd |= COPYFD_RESTORE;
5070 for (i = 0; i < rp->pair_count; i++) {
5071 if (rp->two_fd[i].copy == fd) {
5079 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5080 * old file descriptors are stashed away so that the redirection can be
5081 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5082 * standard output, and the standard error if it becomes a duplicate of
5083 * stdout, is saved in memory.
5085 /* flags passed to redirect */
5086 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5087 #define REDIR_SAVEFD2 03 /* set preverrout */
5089 redirect(union node *redir, int flags)
5091 struct redirtab *sv;
5096 int copied_fd2 = -1;
5106 if (flags & REDIR_PUSH) {
5107 union node *tmp = redir;
5110 #if ENABLE_ASH_BASH_COMPAT
5111 if (tmp->nfile.type == NTO2)
5114 tmp = tmp->nfile.next;
5116 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5117 sv->next = redirlist;
5118 sv->pair_count = sv_pos;
5120 sv->nullredirs = g_nullredirs - 1;
5122 while (sv_pos > 0) {
5124 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5129 fd = redir->nfile.fd;
5130 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5131 int right_fd = redir->ndup.dupfd;
5132 /* redirect from/to same file descriptor? */
5135 /* echo >&10 and 10 is a fd opened to the sh script? */
5136 if (is_hidden_fd(sv, right_fd)) {
5137 errno = EBADF; /* as if it is closed */
5138 ash_msg_and_raise_error("%d: %m", right_fd);
5142 newfd = openredirect(redir); /* always >= 0 */
5144 /* Descriptor wasn't open before redirect.
5145 * Mark it for close in the future */
5146 if (need_to_remember(sv, fd)) {
5147 goto remember_to_close;
5152 #if ENABLE_ASH_BASH_COMPAT
5155 if (need_to_remember(sv, fd)) {
5156 /* Copy old descriptor */
5157 i = fcntl(fd, F_DUPFD, 10);
5158 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5159 * are closed in popredir() in the child, preventing them from leaking
5160 * into child. (popredir() also cleans up the mess in case of failures)
5165 /* Strange error (e.g. "too many files" EMFILE?) */
5169 ash_msg_and_raise_error("%d: %m", fd);
5172 /* EBADF: it is not open - good, remember to close it */
5175 } else { /* fd is open, save its copy */
5176 /* "exec fd>&-" should not close fds
5177 * which point to script file(s).
5178 * Force them to be restored afterwards */
5179 if (is_hidden_fd(sv, fd))
5180 i |= COPYFD_RESTORE;
5184 sv->two_fd[sv_pos].orig = fd;
5185 sv->two_fd[sv_pos].copy = i;
5189 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5190 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5191 /* Don't want to trigger debugging */
5195 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5197 } else if (fd != newfd) { /* move newfd to fd */
5198 copyfd(newfd, fd | COPYFD_EXACT);
5199 #if ENABLE_ASH_BASH_COMPAT
5200 if (!(redir->nfile.type == NTO2 && fd == 2))
5204 #if ENABLE_ASH_BASH_COMPAT
5205 if (redir->nfile.type == NTO2 && fd == 1) {
5206 /* We already redirected it to fd 1, now copy it to 2 */
5212 } while ((redir = redir->nfile.next) != NULL);
5215 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5216 preverrout_fd = copied_fd2;
5220 * Undo the effects of the last redirection.
5223 popredir(int drop, int restore)
5225 struct redirtab *rp;
5228 if (--g_nullredirs >= 0)
5232 for (i = 0; i < rp->pair_count; i++) {
5233 int fd = rp->two_fd[i].orig;
5234 int copy = rp->two_fd[i].copy;
5235 if (copy == CLOSED) {
5240 if (copy != EMPTY) {
5241 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5242 copy &= ~COPYFD_RESTORE;
5244 copyfd(copy, fd | COPYFD_EXACT);
5246 close(copy & ~COPYFD_RESTORE);
5249 redirlist = rp->next;
5250 g_nullredirs = rp->nullredirs;
5256 * Undo all redirections. Called on error or interrupt.
5260 * Discard all saved file descriptors.
5263 clearredir(int drop)
5269 popredir(drop, /*restore:*/ 0);
5274 redirectsafe(union node *redir, int flags)
5277 volatile int saveint;
5278 struct jmploc *volatile savehandler = exception_handler;
5279 struct jmploc jmploc;
5282 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5283 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5285 exception_handler = &jmploc;
5286 redirect(redir, flags);
5288 exception_handler = savehandler;
5289 if (err && exception_type != EXERROR)
5290 longjmp(exception_handler->loc, 1);
5291 RESTORE_INT(saveint);
5296 /* ============ Routines to expand arguments to commands
5298 * We have to deal with backquotes, shell variables, and file metacharacters.
5301 #if ENABLE_SH_MATH_SUPPORT
5303 ash_arith(const char *s)
5305 arith_eval_hooks_t math_hooks;
5309 math_hooks.lookupvar = lookupvar;
5310 math_hooks.setvar = setvar2;
5311 math_hooks.endofname = endofname;
5314 result = arith(s, &errcode, &math_hooks);
5317 ash_msg_and_raise_error("exponent less than 0");
5319 ash_msg_and_raise_error("divide by zero");
5321 ash_msg_and_raise_error("expression recursion loop detected");
5322 raise_error_syntax(s);
5333 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5334 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5335 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5336 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5337 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5338 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5339 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5340 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5341 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5345 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5346 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5347 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5348 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5349 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5352 * Structure specifying which parts of the string should be searched
5353 * for IFS characters.
5356 struct ifsregion *next; /* next region in list */
5357 int begoff; /* offset of start of region */
5358 int endoff; /* offset of end of region */
5359 int nulonly; /* search for nul bytes only */
5363 struct strlist *list;
5364 struct strlist **lastp;
5367 /* output of current string */
5368 static char *expdest;
5369 /* list of back quote expressions */
5370 static struct nodelist *argbackq;
5371 /* first struct in list of ifs regions */
5372 static struct ifsregion ifsfirst;
5373 /* last struct in list */
5374 static struct ifsregion *ifslastp;
5375 /* holds expanded arg list */
5376 static struct arglist exparg;
5386 expdest = makestrspace(32, expdest);
5387 len = fmtstr(expdest, 32, arith_t_fmt, num);
5388 STADJUST(len, expdest);
5393 esclen(const char *start, const char *p)
5397 while (p > start && (unsigned char)*--p == CTLESC) {
5404 * Remove any CTLESC characters from a string.
5407 rmescapes(char *str, int flag)
5409 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5413 unsigned protect_against_glob;
5416 p = strpbrk(str, qchars);
5422 if (flag & RMESCAPE_ALLOC) {
5423 size_t len = p - str;
5424 size_t fulllen = len + strlen(p) + 1;
5426 if (flag & RMESCAPE_GROW) {
5427 r = makestrspace(fulllen, expdest);
5428 } else if (flag & RMESCAPE_HEAP) {
5429 r = ckmalloc(fulllen);
5431 r = stalloc(fulllen);
5435 q = (char *)memcpy(q, str, len) + len;
5439 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5440 globbing = flag & RMESCAPE_GLOB;
5441 protect_against_glob = globbing;
5443 if ((unsigned char)*p == CTLQUOTEMARK) {
5444 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5445 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5446 // Note: both inquotes and protect_against_glob only affect whether
5447 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5448 inquotes = ~inquotes;
5450 protect_against_glob = globbing;
5454 /* naked back slash */
5455 protect_against_glob = 0;
5458 if ((unsigned char)*p == CTLESC) {
5460 if (protect_against_glob && inquotes && *p != '/') {
5464 protect_against_glob = globbing;
5469 if (flag & RMESCAPE_GROW) {
5471 STADJUST(q - r + 1, expdest);
5475 #define pmatch(a, b) !fnmatch((a), (b), 0)
5478 * Prepare a pattern for a expmeta (internal glob(3)) call.
5480 * Returns an stalloced string.
5483 preglob(const char *pattern, int quoted, int flag)
5485 flag |= RMESCAPE_GLOB;
5487 flag |= RMESCAPE_QUOTED;
5489 return rmescapes((char *)pattern, flag);
5493 * Put a string on the stack.
5496 memtodest(const char *p, size_t len, int syntax, int quotes)
5500 q = makestrspace(quotes ? len * 2 : len, q);
5503 unsigned char c = *p++;
5507 int n = SIT(c, syntax);
5508 if (n == CCTL || n == CBACK)
5518 strtodest(const char *p, int syntax, int quotes)
5520 memtodest(p, strlen(p), syntax, quotes);
5524 * Record the fact that we have to scan this region of the
5525 * string for IFS characters.
5528 recordregion(int start, int end, int nulonly)
5530 struct ifsregion *ifsp;
5532 if (ifslastp == NULL) {
5536 ifsp = ckzalloc(sizeof(*ifsp));
5537 /*ifsp->next = NULL; - ckzalloc did it */
5538 ifslastp->next = ifsp;
5542 ifslastp->begoff = start;
5543 ifslastp->endoff = end;
5544 ifslastp->nulonly = nulonly;
5548 removerecordregions(int endoff)
5550 if (ifslastp == NULL)
5553 if (ifsfirst.endoff > endoff) {
5554 while (ifsfirst.next != NULL) {
5555 struct ifsregion *ifsp;
5557 ifsp = ifsfirst.next->next;
5558 free(ifsfirst.next);
5559 ifsfirst.next = ifsp;
5562 if (ifsfirst.begoff > endoff)
5565 ifslastp = &ifsfirst;
5566 ifsfirst.endoff = endoff;
5571 ifslastp = &ifsfirst;
5572 while (ifslastp->next && ifslastp->next->begoff < endoff)
5573 ifslastp=ifslastp->next;
5574 while (ifslastp->next != NULL) {
5575 struct ifsregion *ifsp;
5577 ifsp = ifslastp->next->next;
5578 free(ifslastp->next);
5579 ifslastp->next = ifsp;
5582 if (ifslastp->endoff > endoff)
5583 ifslastp->endoff = endoff;
5587 exptilde(char *startp, char *p, int flags)
5593 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5598 while ((c = *++p) != '\0') {
5605 if (flags & EXP_VARTILDE)
5615 if (*name == '\0') {
5616 home = lookupvar(homestr);
5618 pw = getpwnam(name);
5623 if (!home || !*home)
5626 startloc = expdest - (char *)stackblock();
5627 strtodest(home, SQSYNTAX, quotes);
5628 recordregion(startloc, expdest - (char *)stackblock(), 0);
5636 * Execute a command inside back quotes. If it's a builtin command, we
5637 * want to save its output in a block obtained from malloc. Otherwise
5638 * we fork off a subprocess and get the output of the command via a pipe.
5639 * Should be called with interrupts off.
5641 struct backcmd { /* result of evalbackcmd */
5642 int fd; /* file descriptor to read from */
5643 int nleft; /* number of chars in buffer */
5644 char *buf; /* buffer */
5645 struct job *jp; /* job structure for command */
5648 /* These forward decls are needed to use "eval" code for backticks handling: */
5649 static uint8_t back_exitstatus; /* exit status of backquoted command */
5650 #define EV_EXIT 01 /* exit after evaluating tree */
5651 static void evaltree(union node *, int);
5653 static void FAST_FUNC
5654 evalbackcmd(union node *n, struct backcmd *result)
5665 saveherefd = herefd;
5673 ash_msg_and_raise_error("pipe call failed");
5674 jp = makejob(/*n,*/ 1);
5675 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5680 copyfd(pip[1], 1 | COPYFD_EXACT);
5684 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5688 result->fd = pip[0];
5691 herefd = saveherefd;
5693 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5694 result->fd, result->buf, result->nleft, result->jp));
5698 * Expand stuff in backwards quotes.
5701 expbackq(union node *cmd, int quoted, int quotes)
5709 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5710 struct stackmark smark;
5713 setstackmark(&smark);
5715 startloc = dest - (char *)stackblock();
5717 evalbackcmd(cmd, &in);
5718 popstackmark(&smark);
5725 memtodest(p, i, syntax, quotes);
5729 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5730 TRACE(("expbackq: read returns %d\n", i));
5739 back_exitstatus = waitforjob(in.jp);
5743 /* Eat all trailing newlines */
5745 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5750 recordregion(startloc, dest - (char *)stackblock(), 0);
5751 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5752 (dest - (char *)stackblock()) - startloc,
5753 (dest - (char *)stackblock()) - startloc,
5754 stackblock() + startloc));
5757 #if ENABLE_SH_MATH_SUPPORT
5759 * Expand arithmetic expression. Backup to start of expression,
5760 * evaluate, place result in (backed up) result, adjust string position.
5773 * This routine is slightly over-complicated for
5774 * efficiency. Next we scan backwards looking for the
5775 * start of arithmetic.
5777 start = stackblock();
5784 while ((unsigned char)*p != CTLARI) {
5788 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5793 esc = esclen(start, p);
5803 removerecordregions(begoff);
5810 rmescapes(p + 2, 0);
5812 len = cvtnum(ash_arith(p + 2));
5815 recordregion(begoff, begoff + len, 0);
5819 /* argstr needs it */
5820 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5823 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5824 * characters to allow for further processing. Otherwise treat
5825 * $@ like $* since no splitting will be performed.
5827 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5828 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5829 * for correct expansion of "B=$A" word.
5832 argstr(char *p, int flags, struct strlist *var_str_list)
5834 static const char spclchars[] ALIGN1 = {
5842 CTLBACKQ | CTLQUOTE,
5843 #if ENABLE_SH_MATH_SUPPORT
5848 const char *reject = spclchars;
5849 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5850 int breakall = flags & EXP_WORD;
5855 if (!(flags & EXP_VARTILDE)) {
5857 } else if (flags & EXP_VARTILDE2) {
5862 if (flags & EXP_TILDE) {
5865 flags &= ~EXP_TILDE;
5868 if (*q == CTLESC && (flags & EXP_QWORD))
5871 p = exptilde(p, q, flags);
5874 startloc = expdest - (char *)stackblock();
5878 length += strcspn(p + length, reject);
5882 #if ENABLE_SH_MATH_SUPPORT
5886 /* c == '=' || c == ':' || c == CTLENDARI */
5892 expdest = stack_nputstr(p, length, expdest);
5893 newloc = expdest - (char *)stackblock();
5894 if (breakall && !inquotes && newloc > startloc) {
5895 recordregion(startloc, newloc, 0);
5906 if (flags & EXP_VARTILDE2) {
5910 flags |= EXP_VARTILDE2;
5915 * sort of a hack - expand tildes in variable
5916 * assignments (after the first '=' and after ':'s).
5925 case CTLENDVAR: /* ??? */
5928 /* "$@" syntax adherence hack */
5930 && memcmp(p, dolatstr, 4) == 0
5931 && ( p[4] == CTLQUOTEMARK
5932 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5935 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
5938 inquotes = !inquotes;
5951 p = evalvar(p, flags, var_str_list);
5955 case CTLBACKQ|CTLQUOTE:
5956 expbackq(argbackq->n, c, quotes);
5957 argbackq = argbackq->next;
5959 #if ENABLE_SH_MATH_SUPPORT
5972 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
5975 // This commented out code was added by James Simmons <jsimmons@infradead.org>
5976 // as part of a larger change when he added support for ${var/a/b}.
5977 // However, it broke # and % operators:
5981 //echo ${var#ab} abcdcd abcdcd
5982 //echo ${var##ab} abcdcd abcdcd
5983 //echo ${var#a*b} abcdcd ababcdcd (!)
5984 //echo ${var##a*b} cdcd cdcd
5985 //echo ${var#?} babcdcd ababcdcd (!)
5986 //echo ${var##?} babcdcd babcdcd
5987 //echo ${var#*} ababcdcd babcdcd (!)
5989 //echo ${var%cd} ababcd ababcd
5990 //echo ${var%%cd} ababcd abab (!)
5991 //echo ${var%c*d} ababcd ababcd
5992 //echo ${var%%c*d} abab ababcdcd (!)
5993 //echo ${var%?} ababcdc ababcdc
5994 //echo ${var%%?} ababcdc ababcdcd (!)
5995 //echo ${var%*} ababcdcd ababcdcd
5998 // Commenting it back out helped. Remove it completely if it really
6001 char *loc, *loc2; //, *full;
6007 int match; // = strlen(str);
6008 const char *s = loc2;
6015 match = pmatch(str, s); // this line was deleted
6017 // // chop off end if its '*'
6018 // full = strrchr(str, '*');
6019 // if (full && full != str)
6022 // // If str starts with '*' replace with s.
6023 // if ((*str == '*') && strlen(s) >= match) {
6024 // full = xstrdup(s);
6025 // strncpy(full+strlen(s)-match+1, str+1, match-1);
6027 // full = xstrndup(str, match);
6028 // match = strncmp(s, full, strlen(full));
6032 if (match) // if (!match)
6034 if (quotes && (unsigned char)*loc == CTLESC)
6043 scanright(char *startp, char *rmesc, char *rmescend, char *pattern, int quotes, int match_at_start)
6045 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6046 int try2optimize = match_at_start;
6052 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6053 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6054 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6056 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6057 * and on each iteration they go back two/one char until they reach the beginning.
6058 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6060 /* TODO: document in what other circumstances we are called. */
6062 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6065 const char *s = loc2;
6066 if (match_at_start) {
6070 match = pmatch(pattern, s);
6071 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6075 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6077 /* Maybe we can optimize this:
6078 * if pattern ends with unescaped *, we can avoid checking
6079 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6080 * it wont match truncated "raw_value_of_" strings too.
6082 unsigned plen = strlen(pattern);
6083 /* Does it end with "*"? */
6084 if (plen != 0 && pattern[--plen] == '*') {
6085 /* "xxxx*" is not escaped */
6086 /* "xxx\*" is escaped */
6087 /* "xx\\*" is not escaped */
6088 /* "x\\\*" is escaped */
6090 while (plen != 0 && pattern[--plen] == '\\')
6093 break; /* ends with unescaped "*" */
6101 esc = esclen(startp, loc);
6112 static void varunset(const char *, const char *, const char *, int) NORETURN;
6114 varunset(const char *end, const char *var, const char *umsg, int varflags)
6120 msg = "parameter not set";
6122 if ((unsigned char)*end == CTLENDVAR) {
6123 if (varflags & VSNUL)
6129 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6132 #if ENABLE_ASH_BASH_COMPAT
6134 parse_sub_pattern(char *arg, int inquotes)
6136 char *idx, *repl = NULL;
6145 /* Only the first '/' seen is our separator */
6152 if (!inquotes && c == '\\' && arg[1] == '\\')
6153 arg++; /* skip both \\, not just first one */
6160 #endif /* ENABLE_ASH_BASH_COMPAT */
6163 subevalvar(char *p, char *str, int strloc, int subtype,
6164 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6166 struct nodelist *saveargbackq = argbackq;
6169 char *rmesc, *rmescend;
6170 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6171 IF_ASH_BASH_COMPAT(char null = '\0';)
6172 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6173 int saveherefd = herefd;
6174 int amount, workloc, resetloc;
6176 char *(*scan)(char*, char*, char*, char*, int, int);
6179 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6181 STPUTC('\0', expdest);
6182 herefd = saveherefd;
6183 argbackq = saveargbackq;
6184 startp = (char *)stackblock() + startloc;
6188 setvar(str, startp, 0);
6189 amount = startp - expdest;
6190 STADJUST(amount, expdest);
6193 #if ENABLE_ASH_BASH_COMPAT
6195 loc = str = stackblock() + strloc;
6196 /* Read POS in ${var:POS:LEN} */
6197 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6198 len = str - startp - 1;
6200 /* *loc != '\0', guaranteed by parser */
6204 /* Adjust the length by the number of escapes */
6205 for (ptr = startp; ptr < (str - 1); ptr++) {
6206 if ((unsigned char)*ptr == CTLESC) {
6214 if (*loc++ == ':') {
6218 /* Skip POS in ${var:POS:LEN} */
6220 while (*loc && *loc != ':') {
6222 * bash complains on: var=qwe; echo ${var:1a:123}
6224 ash_msg_and_raise_error(msg_illnum, str);
6228 if (*loc++ == ':') {
6232 if (pos >= orig_len) {
6236 if (len > (orig_len - pos))
6237 len = orig_len - pos;
6239 for (str = startp; pos; str++, pos--) {
6240 if (quotes && (unsigned char)*str == CTLESC)
6243 for (loc = startp; len; len--) {
6244 if (quotes && (unsigned char)*str == CTLESC)
6249 amount = loc - expdest;
6250 STADJUST(amount, expdest);
6255 varunset(p, str, startp, varflags);
6258 resetloc = expdest - (char *)stackblock();
6260 /* We'll comeback here if we grow the stack while handling
6261 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6262 * stack will need rebasing, and we'll need to remove our work
6265 IF_ASH_BASH_COMPAT(restart:)
6267 amount = expdest - ((char *)stackblock() + resetloc);
6268 STADJUST(-amount, expdest);
6269 startp = (char *)stackblock() + startloc;
6272 rmescend = (char *)stackblock() + strloc;
6274 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6275 if (rmesc != startp) {
6277 startp = (char *)stackblock() + startloc;
6281 str = (char *)stackblock() + strloc;
6282 preglob(str, varflags & VSQUOTE, 0);
6283 workloc = expdest - (char *)stackblock();
6285 #if ENABLE_ASH_BASH_COMPAT
6286 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6290 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6295 /* If there's no pattern to match, return the expansion unmolested */
6304 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6306 /* No match, advance */
6307 char *restart_detect = stackblock();
6309 STPUTC(*idx, expdest);
6310 if (quotes && (unsigned char)*idx == CTLESC) {
6313 STPUTC(*idx, expdest);
6315 if (stackblock() != restart_detect)
6320 /* continue; - prone to quadratic behavior, smarter code: */
6323 if (str[0] == '*') {
6324 /* Pattern is "*foo". If "*foo" does not match "long_string",
6325 * it would never match "ong_string" etc, no point in trying.
6332 if (subtype == VSREPLACEALL) {
6334 if (quotes && (unsigned char)*idx == CTLESC)
6343 for (loc = repl; *loc; loc++) {
6344 char *restart_detect = stackblock();
6345 STPUTC(*loc, expdest);
6346 if (stackblock() != restart_detect)
6351 if (subtype == VSREPLACE) {
6353 char *restart_detect = stackblock();
6354 STPUTC(*idx, expdest);
6355 if (stackblock() != restart_detect)
6364 /* We've put the replaced text into a buffer at workloc, now
6365 * move it to the right place and adjust the stack.
6367 startp = stackblock() + startloc;
6368 STPUTC('\0', expdest);
6369 memmove(startp, stackblock() + workloc, len);
6370 startp[len++] = '\0';
6371 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6372 STADJUST(-amount, expdest);
6375 #endif /* ENABLE_ASH_BASH_COMPAT */
6377 subtype -= VSTRIMRIGHT;
6379 if (subtype < 0 || subtype > 7)
6382 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6383 zero = subtype >> 1;
6384 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6385 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6387 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6390 memmove(startp, loc, str - loc);
6391 loc = startp + (str - loc) - 1;
6394 amount = loc - expdest;
6395 STADJUST(amount, expdest);
6401 * Add the value of a specialized variable to the stack string.
6402 * name parameter (examples):
6403 * ash -c 'echo $1' name:'1='
6404 * ash -c 'echo $qwe' name:'qwe='
6405 * ash -c 'echo $$' name:'$='
6406 * ash -c 'echo ${$}' name:'$='
6407 * ash -c 'echo ${$##q}' name:'$=q'
6408 * ash -c 'echo ${#$}' name:'$='
6409 * note: examples with bad shell syntax:
6410 * ash -c 'echo ${#$1}' name:'$=1'
6411 * ash -c 'echo ${#1#}' name:'1=#'
6413 static NOINLINE ssize_t
6414 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6421 int subtype = varflags & VSTYPE;
6422 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6423 int quoted = varflags & VSQUOTE;
6424 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6434 num = shellparam.nparam;
6442 goto check_1char_name;
6444 expdest = makestrspace(NOPTS, expdest);
6445 for (i = NOPTS - 1; i >= 0; i--) {
6447 USTPUTC(optletters(i), expdest);
6453 /* handles cases similar to ${#$1} */
6454 if (name[2] != '\0')
6455 raise_error_syntax("bad substitution");
6462 if (quoted && (flags & EXP_FULL)) {
6463 /* note: this is not meant as PEOF value */
6464 sep = 1 << CHAR_BIT;
6469 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6470 i = SIT(sep, syntax);
6471 if (quotes && (i == CCTL || i == CBACK))
6477 while ((p = *ap++) != NULL) {
6480 partlen = strlen(p);
6483 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6484 memtodest(p, partlen, syntax, quotes);
6490 if (subtype == VSPLUS || subtype == VSLENGTH) {
6496 /* note: may put NUL despite sep != 0
6497 * (see sep = 1 << CHAR_BIT above) */
6503 } /* case '@' and '*' */
6514 num = atoi(name); /* number(name) fails on ${N#str} etc */
6515 if (num < 0 || num > shellparam.nparam)
6517 p = num ? shellparam.p[num - 1] : arg0;
6520 /* NB: name has form "VAR=..." */
6522 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6523 * which should be considered before we check variables. */
6525 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6529 str = var_str_list->text;
6530 eq = strchr(str, '=');
6531 if (!eq) /* stop at first non-assignment */
6534 if (name_len == (unsigned)(eq - str)
6535 && strncmp(str, name, name_len) == 0
6538 /* goto value; - WRONG! */
6539 /* think "A=1 A=2 B=$A" */
6541 var_str_list = var_str_list->next;
6542 } while (var_str_list);
6546 p = lookupvar(name);
6552 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6553 memtodest(p, len, syntax, quotes);
6557 if (subtype == VSPLUS || subtype == VSLENGTH)
6558 STADJUST(-len, expdest);
6563 * Expand a variable, and return a pointer to the next character in the
6567 evalvar(char *p, int flags, struct strlist *var_str_list)
6578 varflags = (unsigned char) *p++;
6579 subtype = varflags & VSTYPE;
6580 quoted = varflags & VSQUOTE;
6582 easy = (!quoted || (*var == '@' && shellparam.nparam));
6583 startloc = expdest - (char *)stackblock();
6584 p = strchr(p, '=') + 1;
6587 varlen = varvalue(var, varflags, flags, var_str_list);
6588 if (varflags & VSNUL)
6591 if (subtype == VSPLUS) {
6592 varlen = -1 - varlen;
6596 if (subtype == VSMINUS) {
6600 p, flags | EXP_TILDE |
6601 (quoted ? EXP_QWORD : EXP_WORD),
6611 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6613 if (subevalvar(p, var, /* strloc: */ 0,
6614 subtype, startloc, varflags,
6620 * Remove any recorded regions beyond
6623 removerecordregions(startloc);
6633 if (varlen < 0 && uflag)
6634 varunset(p, var, 0, 0);
6636 if (subtype == VSLENGTH) {
6637 cvtnum(varlen > 0 ? varlen : 0);
6641 if (subtype == VSNORMAL) {
6652 case VSTRIMRIGHTMAX:
6653 #if ENABLE_ASH_BASH_COMPAT
6666 * Terminate the string and start recording the pattern
6669 STPUTC('\0', expdest);
6670 patloc = expdest - (char *)stackblock();
6671 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6673 //TODO: | EXP_REDIR too? All other such places do it too
6674 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6677 int amount = expdest - (
6678 (char *)stackblock() + patloc - 1
6680 STADJUST(-amount, expdest);
6682 /* Remove any recorded regions beyond start of variable */
6683 removerecordregions(startloc);
6685 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6689 if (subtype != VSNORMAL) { /* skip to end of alternative */
6692 unsigned char c = *p++;
6695 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6697 argbackq = argbackq->next;
6698 } else if (c == CTLVAR) {
6699 if ((*p++ & VSTYPE) != VSNORMAL)
6701 } else if (c == CTLENDVAR) {
6711 * Break the argument string into pieces based upon IFS and add the
6712 * strings to the argument list. The regions of the string to be
6713 * searched for IFS characters have been stored by recordregion.
6716 ifsbreakup(char *string, struct arglist *arglist)
6718 struct ifsregion *ifsp;
6723 const char *ifs, *realifs;
6728 if (ifslastp != NULL) {
6731 realifs = ifsset() ? ifsval() : defifs;
6734 p = string + ifsp->begoff;
6735 nulonly = ifsp->nulonly;
6736 ifs = nulonly ? nullstr : realifs;
6738 while (p < string + ifsp->endoff) {
6740 if ((unsigned char)*p == CTLESC)
6742 if (!strchr(ifs, *p)) {
6747 ifsspc = (strchr(defifs, *p) != NULL);
6748 /* Ignore IFS whitespace at start */
6749 if (q == start && ifsspc) {
6755 sp = stzalloc(sizeof(*sp));
6757 *arglist->lastp = sp;
6758 arglist->lastp = &sp->next;
6762 if (p >= string + ifsp->endoff) {
6766 if ((unsigned char)*p == CTLESC)
6768 if (strchr(ifs, *p) == NULL) {
6772 if (strchr(defifs, *p) == NULL) {
6787 } while (ifsp != NULL);
6796 sp = stzalloc(sizeof(*sp));
6798 *arglist->lastp = sp;
6799 arglist->lastp = &sp->next;
6805 struct ifsregion *p;
6810 struct ifsregion *ifsp;
6816 ifsfirst.next = NULL;
6821 * Add a file name to the list.
6824 addfname(const char *name)
6828 sp = stzalloc(sizeof(*sp));
6829 sp->text = ststrdup(name);
6831 exparg.lastp = &sp->next;
6834 static char *expdir;
6837 * Do metacharacter (i.e. *, ?, [...]) expansion.
6840 expmeta(char *enddir, char *name)
6855 for (p = name; *p; p++) {
6856 if (*p == '*' || *p == '?')
6858 else if (*p == '[') {
6865 if (*q == '/' || *q == '\0')
6872 } else if (*p == '\\')
6874 else if (*p == '/') {
6881 if (metaflag == 0) { /* we've reached the end of the file name */
6882 if (enddir != expdir)
6890 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6901 } while (p < start);
6903 if (enddir == expdir) {
6905 } else if (enddir == expdir + 1 && *expdir == '/') {
6914 if (enddir != expdir)
6916 if (*endname == 0) {
6928 while (!pending_int && (dp = readdir(dirp)) != NULL) {
6929 if (dp->d_name[0] == '.' && !matchdot)
6931 if (pmatch(start, dp->d_name)) {
6933 strcpy(enddir, dp->d_name);
6936 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6939 expmeta(p, endname);
6948 static struct strlist *
6949 msort(struct strlist *list, int len)
6951 struct strlist *p, *q = NULL;
6952 struct strlist **lpp;
6960 for (n = half; --n >= 0;) {
6964 q->next = NULL; /* terminate first half of list */
6965 q = msort(list, half); /* sort first half of list */
6966 p = msort(p, len - half); /* sort second half */
6969 #if ENABLE_LOCALE_SUPPORT
6970 if (strcoll(p->text, q->text) < 0)
6972 if (strcmp(p->text, q->text) < 0)
6996 * Sort the results of file name expansion. It calculates the number of
6997 * strings to sort and then calls msort (short for merge sort) to do the
7000 static struct strlist *
7001 expsort(struct strlist *str)
7007 for (sp = str; sp; sp = sp->next)
7009 return msort(str, len);
7013 expandmeta(struct strlist *str /*, int flag*/)
7015 static const char metachars[] ALIGN1 = {
7018 /* TODO - EXP_REDIR */
7021 struct strlist **savelastp;
7027 if (!strpbrk(str->text, metachars))
7029 savelastp = exparg.lastp;
7032 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7034 int i = strlen(str->text);
7035 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7043 if (exparg.lastp == savelastp) {
7048 *exparg.lastp = str;
7049 rmescapes(str->text, 0);
7050 exparg.lastp = &str->next;
7052 *exparg.lastp = NULL;
7053 *savelastp = sp = expsort(*savelastp);
7054 while (sp->next != NULL)
7056 exparg.lastp = &sp->next;
7063 * Perform variable substitution and command substitution on an argument,
7064 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7065 * perform splitting and file name expansion. When arglist is NULL, perform
7066 * here document expansion.
7069 expandarg(union node *arg, struct arglist *arglist, int flag)
7074 argbackq = arg->narg.backquote;
7075 STARTSTACKSTR(expdest);
7076 ifsfirst.next = NULL;
7078 argstr(arg->narg.text, flag,
7079 /* var_str_list: */ arglist ? arglist->list : NULL);
7080 p = _STPUTC('\0', expdest);
7082 if (arglist == NULL) {
7083 return; /* here document expanded */
7085 p = grabstackstr(p);
7086 exparg.lastp = &exparg.list;
7090 if (flag & EXP_FULL) {
7091 ifsbreakup(p, &exparg);
7092 *exparg.lastp = NULL;
7093 exparg.lastp = &exparg.list;
7094 expandmeta(exparg.list /*, flag*/);
7096 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7098 sp = stzalloc(sizeof(*sp));
7101 exparg.lastp = &sp->next;
7105 *exparg.lastp = NULL;
7107 *arglist->lastp = exparg.list;
7108 arglist->lastp = exparg.lastp;
7113 * Expand shell variables and backquotes inside a here document.
7116 expandhere(union node *arg, int fd)
7119 expandarg(arg, (struct arglist *)NULL, 0);
7120 full_write(fd, stackblock(), expdest - (char *)stackblock());
7124 * Returns true if the pattern matches the string.
7127 patmatch(char *pattern, const char *string)
7129 return pmatch(preglob(pattern, 0, 0), string);
7133 * See if a pattern matches in a case statement.
7136 casematch(union node *pattern, char *val)
7138 struct stackmark smark;
7141 setstackmark(&smark);
7142 argbackq = pattern->narg.backquote;
7143 STARTSTACKSTR(expdest);
7145 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7146 /* var_str_list: */ NULL);
7147 STACKSTRNUL(expdest);
7148 result = patmatch(stackblock(), val);
7149 popstackmark(&smark);
7154 /* ============ find_command */
7158 int (*builtin)(int, char **) FAST_FUNC;
7159 /* unsigned flags; */
7161 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7162 /* "regular" builtins always take precedence over commands,
7163 * regardless of PATH=....%builtin... position */
7164 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7165 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7168 smallint cmdtype; /* CMDxxx */
7171 /* index >= 0 for commands without path (slashes) */
7172 /* (TODO: what exactly does the value mean? PATH position?) */
7173 /* index == -1 for commands with slashes */
7174 /* index == (-2 - applet_no) for NOFORK applets */
7175 const struct builtincmd *cmd;
7176 struct funcnode *func;
7179 /* values of cmdtype */
7180 #define CMDUNKNOWN -1 /* no entry in table for command */
7181 #define CMDNORMAL 0 /* command is an executable program */
7182 #define CMDFUNCTION 1 /* command is a shell function */
7183 #define CMDBUILTIN 2 /* command is a shell builtin */
7185 /* action to find_command() */
7186 #define DO_ERR 0x01 /* prints errors */
7187 #define DO_ABS 0x02 /* checks absolute paths */
7188 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7189 #define DO_ALTPATH 0x08 /* using alternate path */
7190 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7192 static void find_command(char *, struct cmdentry *, int, const char *);
7195 /* ============ Hashing commands */
7198 * When commands are first encountered, they are entered in a hash table.
7199 * This ensures that a full path search will not have to be done for them
7200 * on each invocation.
7202 * We should investigate converting to a linear search, even though that
7203 * would make the command name "hash" a misnomer.
7207 struct tblentry *next; /* next entry in hash chain */
7208 union param param; /* definition of builtin function */
7209 smallint cmdtype; /* CMDxxx */
7210 char rehash; /* if set, cd done since entry created */
7211 char cmdname[1]; /* name of command */
7214 static struct tblentry **cmdtable;
7215 #define INIT_G_cmdtable() do { \
7216 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7219 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7223 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7227 #if ENABLE_FEATURE_SH_STANDALONE
7228 if (applet_no >= 0) {
7229 if (APPLET_IS_NOEXEC(applet_no)) {
7232 run_applet_no_and_exit(applet_no, argv);
7234 /* re-exec ourselves with the new arguments */
7235 execve(bb_busybox_exec_path, argv, envp);
7236 /* If they called chroot or otherwise made the binary no longer
7237 * executable, fall through */
7244 execve(cmd, argv, envp);
7245 } while (errno == EINTR);
7247 execve(cmd, argv, envp);
7253 if (errno == ENOEXEC) {
7257 for (ap = argv; *ap; ap++)
7259 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7261 ap[0] = cmd = (char *)DEFAULT_SHELL;
7264 while ((*ap++ = *argv++) != NULL)
7273 * Exec a program. Never returns. If you change this routine, you may
7274 * have to change the find_command routine as well.
7276 static void shellexec(char **, const char *, int) NORETURN;
7278 shellexec(char **argv, const char *path, int idx)
7284 #if ENABLE_FEATURE_SH_STANDALONE
7288 clearredir(/*drop:*/ 1);
7289 envp = listvars(VEXPORT, VUNSET, 0);
7290 if (strchr(argv[0], '/') != NULL
7291 #if ENABLE_FEATURE_SH_STANDALONE
7292 || (applet_no = find_applet_by_name(argv[0])) >= 0
7295 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7299 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7300 if (--idx < 0 && pathopt == NULL) {
7301 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7302 if (errno != ENOENT && errno != ENOTDIR)
7309 /* Map to POSIX errors */
7321 exitstatus = exerrno;
7322 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7323 argv[0], e, suppress_int));
7324 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7329 printentry(struct tblentry *cmdp)
7335 idx = cmdp->param.index;
7338 name = path_advance(&path, cmdp->cmdname);
7340 } while (--idx >= 0);
7341 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7345 * Clear out command entries. The argument specifies the first entry in
7346 * PATH which has changed.
7349 clearcmdentry(int firstchange)
7351 struct tblentry **tblp;
7352 struct tblentry **pp;
7353 struct tblentry *cmdp;
7356 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7358 while ((cmdp = *pp) != NULL) {
7359 if ((cmdp->cmdtype == CMDNORMAL &&
7360 cmdp->param.index >= firstchange)
7361 || (cmdp->cmdtype == CMDBUILTIN &&
7362 builtinloc >= firstchange)
7375 * Locate a command in the command hash table. If "add" is nonzero,
7376 * add the command to the table if it is not already present. The
7377 * variable "lastcmdentry" is set to point to the address of the link
7378 * pointing to the entry, so that delete_cmd_entry can delete the
7381 * Interrupts must be off if called with add != 0.
7383 static struct tblentry **lastcmdentry;
7385 static struct tblentry *
7386 cmdlookup(const char *name, int add)
7388 unsigned int hashval;
7390 struct tblentry *cmdp;
7391 struct tblentry **pp;
7394 hashval = (unsigned char)*p << 4;
7396 hashval += (unsigned char)*p++;
7398 pp = &cmdtable[hashval % CMDTABLESIZE];
7399 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7400 if (strcmp(cmdp->cmdname, name) == 0)
7404 if (add && cmdp == NULL) {
7405 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7407 /* + 1 - already done because
7408 * tblentry::cmdname is char[1] */);
7409 /*cmdp->next = NULL; - ckzalloc did it */
7410 cmdp->cmdtype = CMDUNKNOWN;
7411 strcpy(cmdp->cmdname, name);
7418 * Delete the command entry returned on the last lookup.
7421 delete_cmd_entry(void)
7423 struct tblentry *cmdp;
7426 cmdp = *lastcmdentry;
7427 *lastcmdentry = cmdp->next;
7428 if (cmdp->cmdtype == CMDFUNCTION)
7429 freefunc(cmdp->param.func);
7435 * Add a new command entry, replacing any existing command entry for
7436 * the same name - except special builtins.
7439 addcmdentry(char *name, struct cmdentry *entry)
7441 struct tblentry *cmdp;
7443 cmdp = cmdlookup(name, 1);
7444 if (cmdp->cmdtype == CMDFUNCTION) {
7445 freefunc(cmdp->param.func);
7447 cmdp->cmdtype = entry->cmdtype;
7448 cmdp->param = entry->u;
7452 static int FAST_FUNC
7453 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7455 struct tblentry **pp;
7456 struct tblentry *cmdp;
7458 struct cmdentry entry;
7461 if (nextopt("r") != '\0') {
7466 if (*argptr == NULL) {
7467 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7468 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7469 if (cmdp->cmdtype == CMDNORMAL)
7477 while ((name = *argptr) != NULL) {
7478 cmdp = cmdlookup(name, 0);
7480 && (cmdp->cmdtype == CMDNORMAL
7481 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7485 find_command(name, &entry, DO_ERR, pathval());
7486 if (entry.cmdtype == CMDUNKNOWN)
7494 * Called when a cd is done. Marks all commands so the next time they
7495 * are executed they will be rehashed.
7500 struct tblentry **pp;
7501 struct tblentry *cmdp;
7503 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7504 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7505 if (cmdp->cmdtype == CMDNORMAL
7506 || (cmdp->cmdtype == CMDBUILTIN
7507 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7517 * Fix command hash table when PATH changed.
7518 * Called before PATH is changed. The argument is the new value of PATH;
7519 * pathval() still returns the old value at this point.
7520 * Called with interrupts off.
7522 static void FAST_FUNC
7523 changepath(const char *new)
7531 firstchange = 9999; /* assume no change */
7537 if ((*old == '\0' && *new == ':')
7538 || (*old == ':' && *new == '\0'))
7540 old = new; /* ignore subsequent differences */
7544 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7550 if (builtinloc < 0 && idx_bltin >= 0)
7551 builtinloc = idx_bltin; /* zap builtins */
7552 if (builtinloc >= 0 && idx_bltin < 0)
7554 clearcmdentry(firstchange);
7555 builtinloc = idx_bltin;
7570 #define TENDBQUOTE 12
7587 typedef smallint token_id_t;
7589 /* first char is indicating which tokens mark the end of a list */
7590 static const char *const tokname_array[] = {
7604 #define KWDOFFSET 13
7605 /* the following are keywords */
7627 static char buf[16];
7630 //if (tok < TSEMI) return tokname_array[tok] + 1;
7631 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7636 sprintf(buf + (tok >= TSEMI), "%s%c",
7637 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7641 /* Wrapper around strcmp for qsort/bsearch/... */
7643 pstrcmp(const void *a, const void *b)
7645 return strcmp((char*) a, (*(char**) b) + 1);
7648 static const char *const *
7649 findkwd(const char *s)
7651 return bsearch(s, tokname_array + KWDOFFSET,
7652 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7653 sizeof(tokname_array[0]), pstrcmp);
7657 * Locate and print what a word is...
7660 describe_command(char *command, int describe_command_verbose)
7662 struct cmdentry entry;
7663 struct tblentry *cmdp;
7664 #if ENABLE_ASH_ALIAS
7665 const struct alias *ap;
7667 const char *path = pathval();
7669 if (describe_command_verbose) {
7673 /* First look at the keywords */
7674 if (findkwd(command)) {
7675 out1str(describe_command_verbose ? " is a shell keyword" : command);
7679 #if ENABLE_ASH_ALIAS
7680 /* Then look at the aliases */
7681 ap = lookupalias(command, 0);
7683 if (!describe_command_verbose) {
7688 out1fmt(" is an alias for %s", ap->val);
7692 /* Then check if it is a tracked alias */
7693 cmdp = cmdlookup(command, 0);
7695 entry.cmdtype = cmdp->cmdtype;
7696 entry.u = cmdp->param;
7698 /* Finally use brute force */
7699 find_command(command, &entry, DO_ABS, path);
7702 switch (entry.cmdtype) {
7704 int j = entry.u.index;
7710 p = path_advance(&path, command);
7714 if (describe_command_verbose) {
7716 (cmdp ? " a tracked alias for" : nullstr), p
7725 if (describe_command_verbose) {
7726 out1str(" is a shell function");
7733 if (describe_command_verbose) {
7734 out1fmt(" is a %sshell builtin",
7735 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7736 "special " : nullstr
7744 if (describe_command_verbose) {
7745 out1str(": not found\n");
7754 static int FAST_FUNC
7755 typecmd(int argc UNUSED_PARAM, char **argv)
7761 /* type -p ... ? (we don't bother checking for 'p') */
7762 if (argv[1] && argv[1][0] == '-') {
7767 err |= describe_command(argv[i++], verbose);
7772 #if ENABLE_ASH_CMDCMD
7773 static int FAST_FUNC
7774 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7782 while ((c = nextopt("pvV")) != '\0')
7784 verify |= VERIFY_VERBOSE;
7786 verify |= VERIFY_BRIEF;
7791 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7792 if (verify && (*argptr != NULL)) {
7793 return describe_command(*argptr, verify - VERIFY_BRIEF);
7801 /* ============ eval.c */
7803 static int funcblocksize; /* size of structures in function */
7804 static int funcstringsize; /* size of strings in node */
7805 static void *funcblock; /* block to allocate function from */
7806 static char *funcstring; /* block to allocate strings from */
7808 /* flags in argument to evaltree */
7809 #define EV_EXIT 01 /* exit after evaluating tree */
7810 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7811 #define EV_BACKCMD 04 /* command executing within back quotes */
7813 static const uint8_t nodesize[N_NUMBER] = {
7814 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7815 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7816 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7817 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7818 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7819 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7820 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7821 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7822 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7823 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7824 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7825 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7826 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7827 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7828 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7829 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7830 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7831 #if ENABLE_ASH_BASH_COMPAT
7832 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7834 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7835 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7836 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7837 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7838 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7839 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7840 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7841 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7842 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7845 static void calcsize(union node *n);
7848 sizenodelist(struct nodelist *lp)
7851 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7858 calcsize(union node *n)
7862 funcblocksize += nodesize[n->type];
7865 calcsize(n->ncmd.redirect);
7866 calcsize(n->ncmd.args);
7867 calcsize(n->ncmd.assign);
7870 sizenodelist(n->npipe.cmdlist);
7875 calcsize(n->nredir.redirect);
7876 calcsize(n->nredir.n);
7883 calcsize(n->nbinary.ch2);
7884 calcsize(n->nbinary.ch1);
7887 calcsize(n->nif.elsepart);
7888 calcsize(n->nif.ifpart);
7889 calcsize(n->nif.test);
7892 funcstringsize += strlen(n->nfor.var) + 1;
7893 calcsize(n->nfor.body);
7894 calcsize(n->nfor.args);
7897 calcsize(n->ncase.cases);
7898 calcsize(n->ncase.expr);
7901 calcsize(n->nclist.body);
7902 calcsize(n->nclist.pattern);
7903 calcsize(n->nclist.next);
7907 sizenodelist(n->narg.backquote);
7908 funcstringsize += strlen(n->narg.text) + 1;
7909 calcsize(n->narg.next);
7912 #if ENABLE_ASH_BASH_COMPAT
7919 calcsize(n->nfile.fname);
7920 calcsize(n->nfile.next);
7924 calcsize(n->ndup.vname);
7925 calcsize(n->ndup.next);
7929 calcsize(n->nhere.doc);
7930 calcsize(n->nhere.next);
7933 calcsize(n->nnot.com);
7939 nodeckstrdup(char *s)
7941 char *rtn = funcstring;
7943 strcpy(funcstring, s);
7944 funcstring += strlen(s) + 1;
7948 static union node *copynode(union node *);
7950 static struct nodelist *
7951 copynodelist(struct nodelist *lp)
7953 struct nodelist *start;
7954 struct nodelist **lpp;
7959 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7960 (*lpp)->n = copynode(lp->n);
7962 lpp = &(*lpp)->next;
7969 copynode(union node *n)
7976 funcblock = (char *) funcblock + nodesize[n->type];
7980 new->ncmd.redirect = copynode(n->ncmd.redirect);
7981 new->ncmd.args = copynode(n->ncmd.args);
7982 new->ncmd.assign = copynode(n->ncmd.assign);
7985 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7986 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
7991 new->nredir.redirect = copynode(n->nredir.redirect);
7992 new->nredir.n = copynode(n->nredir.n);
7999 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8000 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8003 new->nif.elsepart = copynode(n->nif.elsepart);
8004 new->nif.ifpart = copynode(n->nif.ifpart);
8005 new->nif.test = copynode(n->nif.test);
8008 new->nfor.var = nodeckstrdup(n->nfor.var);
8009 new->nfor.body = copynode(n->nfor.body);
8010 new->nfor.args = copynode(n->nfor.args);
8013 new->ncase.cases = copynode(n->ncase.cases);
8014 new->ncase.expr = copynode(n->ncase.expr);
8017 new->nclist.body = copynode(n->nclist.body);
8018 new->nclist.pattern = copynode(n->nclist.pattern);
8019 new->nclist.next = copynode(n->nclist.next);
8023 new->narg.backquote = copynodelist(n->narg.backquote);
8024 new->narg.text = nodeckstrdup(n->narg.text);
8025 new->narg.next = copynode(n->narg.next);
8028 #if ENABLE_ASH_BASH_COMPAT
8035 new->nfile.fname = copynode(n->nfile.fname);
8036 new->nfile.fd = n->nfile.fd;
8037 new->nfile.next = copynode(n->nfile.next);
8041 new->ndup.vname = copynode(n->ndup.vname);
8042 new->ndup.dupfd = n->ndup.dupfd;
8043 new->ndup.fd = n->ndup.fd;
8044 new->ndup.next = copynode(n->ndup.next);
8048 new->nhere.doc = copynode(n->nhere.doc);
8049 new->nhere.fd = n->nhere.fd;
8050 new->nhere.next = copynode(n->nhere.next);
8053 new->nnot.com = copynode(n->nnot.com);
8056 new->type = n->type;
8061 * Make a copy of a parse tree.
8063 static struct funcnode *
8064 copyfunc(union node *n)
8069 funcblocksize = offsetof(struct funcnode, n);
8072 blocksize = funcblocksize;
8073 f = ckmalloc(blocksize + funcstringsize);
8074 funcblock = (char *) f + offsetof(struct funcnode, n);
8075 funcstring = (char *) f + blocksize;
8082 * Define a shell function.
8085 defun(char *name, union node *func)
8087 struct cmdentry entry;
8090 entry.cmdtype = CMDFUNCTION;
8091 entry.u.func = copyfunc(func);
8092 addcmdentry(name, &entry);
8096 /* Reasons for skipping commands (see comment on breakcmd routine) */
8097 #define SKIPBREAK (1 << 0)
8098 #define SKIPCONT (1 << 1)
8099 #define SKIPFUNC (1 << 2)
8100 #define SKIPFILE (1 << 3)
8101 #define SKIPEVAL (1 << 4)
8102 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8103 static int skipcount; /* number of levels to skip */
8104 static int funcnest; /* depth of function calls */
8105 static int loopnest; /* current loop nesting level */
8107 /* Forward decl way out to parsing code - dotrap needs it */
8108 static int evalstring(char *s, int mask);
8110 /* Called to execute a trap.
8111 * Single callsite - at the end of evaltree().
8112 * If we return non-zero, exaltree raises EXEXIT exception.
8114 * Perhaps we should avoid entering new trap handlers
8115 * while we are executing a trap handler. [is it a TODO?]
8124 savestatus = exitstatus;
8128 TRACE(("dotrap entered\n"));
8129 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8136 /* non-trapped SIGINT is handled separately by raise_interrupt,
8137 * don't upset it by resetting gotsig[SIGINT-1] */
8138 if (sig == SIGINT && !t)
8141 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8145 want_exexit = evalstring(t, SKIPEVAL);
8146 exitstatus = savestatus;
8148 TRACE(("dotrap returns %d\n", want_exexit));
8153 TRACE(("dotrap returns 0\n"));
8157 /* forward declarations - evaluation is fairly recursive business... */
8158 static void evalloop(union node *, int);
8159 static void evalfor(union node *, int);
8160 static void evalcase(union node *, int);
8161 static void evalsubshell(union node *, int);
8162 static void expredir(union node *);
8163 static void evalpipe(union node *, int);
8164 static void evalcommand(union node *, int);
8165 static int evalbltin(const struct builtincmd *, int, char **);
8166 static void prehash(union node *);
8169 * Evaluate a parse tree. The value is left in the global variable
8173 evaltree(union node *n, int flags)
8175 struct jmploc *volatile savehandler = exception_handler;
8176 struct jmploc jmploc;
8178 void (*evalfn)(union node *, int);
8182 SAVE_INT(int_level);
8185 TRACE(("evaltree(NULL) called\n"));
8188 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8190 exception_handler = &jmploc;
8192 int err = setjmp(jmploc.loc);
8194 /* if it was a signal, check for trap handlers */
8195 if (exception_type == EXSIG) {
8196 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8197 exception_type, err));
8200 /* continue on the way out */
8201 TRACE(("exception %d in evaltree, propagating err=%d\n",
8202 exception_type, err));
8203 exception_handler = savehandler;
8204 longjmp(exception_handler->loc, err);
8211 out1fmt("Node type = %d\n", n->type);
8216 evaltree(n->nnot.com, EV_TESTED);
8217 status = !exitstatus;
8220 expredir(n->nredir.redirect);
8221 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8223 evaltree(n->nredir.n, flags & EV_TESTED);
8224 status = exitstatus;
8226 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8229 evalfn = evalcommand;
8231 if (eflag && !(flags & EV_TESTED))
8243 evalfn = evalsubshell;
8256 #error NAND + 1 != NOR
8258 #if NOR + 1 != NSEMI
8259 #error NOR + 1 != NSEMI
8261 unsigned is_or = n->type - NAND;
8264 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8266 if (!exitstatus == is_or)
8279 evaltree(n->nif.test, EV_TESTED);
8282 if (exitstatus == 0) {
8286 if (n->nif.elsepart) {
8287 n = n->nif.elsepart;
8292 defun(n->narg.text, n->narg.next);
8296 exitstatus = status;
8301 exception_handler = savehandler;
8303 if (checkexit & exitstatus)
8304 evalskip |= SKIPEVAL;
8305 else if (pending_sig && dotrap())
8308 if (flags & EV_EXIT) {
8310 raise_exception(EXEXIT);
8313 RESTORE_INT(int_level);
8314 TRACE(("leaving evaltree (no interrupts)\n"));
8317 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8320 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8323 evalloop(union node *n, int flags)
8333 evaltree(n->nbinary.ch1, EV_TESTED);
8336 if (evalskip == SKIPCONT && --skipcount <= 0) {
8340 if (evalskip == SKIPBREAK && --skipcount <= 0)
8345 if (n->type != NWHILE)
8349 evaltree(n->nbinary.ch2, flags);
8350 status = exitstatus;
8355 exitstatus = status;
8359 evalfor(union node *n, int flags)
8361 struct arglist arglist;
8364 struct stackmark smark;
8366 setstackmark(&smark);
8367 arglist.list = NULL;
8368 arglist.lastp = &arglist.list;
8369 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8370 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8375 *arglist.lastp = NULL;
8380 for (sp = arglist.list; sp; sp = sp->next) {
8381 setvar(n->nfor.var, sp->text, 0);
8382 evaltree(n->nfor.body, flags);
8384 if (evalskip == SKIPCONT && --skipcount <= 0) {
8388 if (evalskip == SKIPBREAK && --skipcount <= 0)
8395 popstackmark(&smark);
8399 evalcase(union node *n, int flags)
8403 struct arglist arglist;
8404 struct stackmark smark;
8406 setstackmark(&smark);
8407 arglist.list = NULL;
8408 arglist.lastp = &arglist.list;
8409 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8411 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8412 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8413 if (casematch(patp, arglist.list->text)) {
8414 if (evalskip == 0) {
8415 evaltree(cp->nclist.body, flags);
8422 popstackmark(&smark);
8426 * Kick off a subshell to evaluate a tree.
8429 evalsubshell(union node *n, int flags)
8432 int backgnd = (n->type == NBACKGND);
8435 expredir(n->nredir.redirect);
8436 if (!backgnd && flags & EV_EXIT && !trap[0])
8439 jp = makejob(/*n,*/ 1);
8440 if (forkshell(jp, n, backgnd) == 0) {
8444 flags &=~ EV_TESTED;
8446 redirect(n->nredir.redirect, 0);
8447 evaltreenr(n->nredir.n, flags);
8452 status = waitforjob(jp);
8453 exitstatus = status;
8458 * Compute the names of the files in a redirection list.
8460 static void fixredir(union node *, const char *, int);
8462 expredir(union node *n)
8466 for (redir = n; redir; redir = redir->nfile.next) {
8470 fn.lastp = &fn.list;
8471 switch (redir->type) {
8475 #if ENABLE_ASH_BASH_COMPAT
8480 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8481 #if ENABLE_ASH_BASH_COMPAT
8484 redir->nfile.expfname = fn.list->text;
8487 case NTOFD: /* >& */
8488 if (redir->ndup.vname) {
8489 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8490 if (fn.list == NULL)
8491 ash_msg_and_raise_error("redir error");
8492 #if ENABLE_ASH_BASH_COMPAT
8493 //FIXME: we used expandarg with different args!
8494 if (!isdigit_str9(fn.list->text)) {
8495 /* >&file, not >&fd */
8496 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8497 ash_msg_and_raise_error("redir error");
8499 goto store_expfname;
8502 fixredir(redir, fn.list->text, 1);
8510 * Evaluate a pipeline. All the processes in the pipeline are children
8511 * of the process creating the pipeline. (This differs from some versions
8512 * of the shell, which make the last process in a pipeline the parent
8516 evalpipe(union node *n, int flags)
8519 struct nodelist *lp;
8524 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8526 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8530 jp = makejob(/*n,*/ pipelen);
8532 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8536 if (pipe(pip) < 0) {
8538 ash_msg_and_raise_error("pipe call failed");
8541 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8554 evaltreenr(lp->n, flags);
8560 /* Don't want to trigger debugging */
8564 if (n->npipe.pipe_backgnd == 0) {
8565 exitstatus = waitforjob(jp);
8566 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8572 * Controls whether the shell is interactive or not.
8575 setinteractive(int on)
8577 static smallint is_interactive;
8579 if (++on == is_interactive)
8581 is_interactive = on;
8585 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8586 if (is_interactive > 1) {
8587 /* Looks like they want an interactive shell */
8588 static smallint did_banner;
8591 /* note: ash and hush share this string */
8592 out1fmt("\n\n%s %s\n"
8593 "Enter 'help' for a list of built-in commands."
8596 "built-in shell (ash)"
8610 setinteractive(iflag);
8612 #if ENABLE_FEATURE_EDITING_VI
8614 line_input_state->flags |= VI_MODE;
8616 line_input_state->flags &= ~VI_MODE;
8618 viflag = 0; /* forcibly keep the option off */
8622 static struct localvar *localvars;
8625 * Called after a function returns.
8626 * Interrupts must be off.
8631 struct localvar *lvp;
8634 while ((lvp = localvars) != NULL) {
8635 localvars = lvp->next;
8637 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8638 if (vp == NULL) { /* $- saved */
8639 memcpy(optlist, lvp->text, sizeof(optlist));
8640 free((char*)lvp->text);
8642 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8646 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8647 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8648 free((char*)vp->text);
8649 vp->flags = lvp->flags;
8650 vp->text = lvp->text;
8657 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8659 volatile struct shparam saveparam;
8660 struct localvar *volatile savelocalvars;
8661 struct jmploc *volatile savehandler;
8662 struct jmploc jmploc;
8665 saveparam = shellparam;
8666 savelocalvars = localvars;
8667 e = setjmp(jmploc.loc);
8672 savehandler = exception_handler;
8673 exception_handler = &jmploc;
8675 shellparam.malloced = 0;
8679 shellparam.nparam = argc - 1;
8680 shellparam.p = argv + 1;
8681 #if ENABLE_ASH_GETOPTS
8682 shellparam.optind = 1;
8683 shellparam.optoff = -1;
8685 evaltree(&func->n, flags & EV_TESTED);
8691 localvars = savelocalvars;
8692 freeparam(&shellparam);
8693 shellparam = saveparam;
8694 exception_handler = savehandler;
8696 evalskip &= ~SKIPFUNC;
8700 #if ENABLE_ASH_CMDCMD
8702 parse_command_args(char **argv, const char **path)
8715 if (c == '-' && !*cp) {
8722 *path = bb_default_path;
8725 /* run 'typecmd' for other options */
8736 * Make a variable a local variable. When a variable is made local, it's
8737 * value and flags are saved in a localvar structure. The saved values
8738 * will be restored when the shell function returns. We handle the name
8739 * "-" as a special case.
8744 struct localvar *lvp;
8749 lvp = ckzalloc(sizeof(struct localvar));
8750 if (LONE_DASH(name)) {
8752 p = ckmalloc(sizeof(optlist));
8753 lvp->text = memcpy(p, optlist, sizeof(optlist));
8758 vpp = hashvar(name);
8759 vp = *findvar(vpp, name);
8760 eq = strchr(name, '=');
8763 setvareq(name, VSTRFIXED);
8765 setvar(name, NULL, VSTRFIXED);
8766 vp = *vpp; /* the new variable */
8767 lvp->flags = VUNSET;
8769 lvp->text = vp->text;
8770 lvp->flags = vp->flags;
8771 vp->flags |= VSTRFIXED|VTEXTFIXED;
8777 lvp->next = localvars;
8783 * The "local" command.
8785 static int FAST_FUNC
8786 localcmd(int argc UNUSED_PARAM, char **argv)
8791 while ((name = *argv++) != NULL) {
8797 static int FAST_FUNC
8798 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8803 static int FAST_FUNC
8804 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8809 static int FAST_FUNC
8810 execcmd(int argc UNUSED_PARAM, char **argv)
8813 iflag = 0; /* exit on error */
8816 shellexec(argv + 1, pathval(), 0);
8822 * The return command.
8824 static int FAST_FUNC
8825 returncmd(int argc UNUSED_PARAM, char **argv)
8828 * If called outside a function, do what ksh does;
8829 * skip the rest of the file.
8831 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8832 return argv[1] ? number(argv[1]) : exitstatus;
8835 /* Forward declarations for builtintab[] */
8836 static int breakcmd(int, char **) FAST_FUNC;
8837 static int dotcmd(int, char **) FAST_FUNC;
8838 static int evalcmd(int, char **) FAST_FUNC;
8839 static int exitcmd(int, char **) FAST_FUNC;
8840 static int exportcmd(int, char **) FAST_FUNC;
8841 #if ENABLE_ASH_GETOPTS
8842 static int getoptscmd(int, char **) FAST_FUNC;
8844 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8845 static int helpcmd(int, char **) FAST_FUNC;
8847 #if ENABLE_SH_MATH_SUPPORT
8848 static int letcmd(int, char **) FAST_FUNC;
8850 static int readcmd(int, char **) FAST_FUNC;
8851 static int setcmd(int, char **) FAST_FUNC;
8852 static int shiftcmd(int, char **) FAST_FUNC;
8853 static int timescmd(int, char **) FAST_FUNC;
8854 static int trapcmd(int, char **) FAST_FUNC;
8855 static int umaskcmd(int, char **) FAST_FUNC;
8856 static int unsetcmd(int, char **) FAST_FUNC;
8857 static int ulimitcmd(int, char **) FAST_FUNC;
8859 #define BUILTIN_NOSPEC "0"
8860 #define BUILTIN_SPECIAL "1"
8861 #define BUILTIN_REGULAR "2"
8862 #define BUILTIN_SPEC_REG "3"
8863 #define BUILTIN_ASSIGN "4"
8864 #define BUILTIN_SPEC_ASSG "5"
8865 #define BUILTIN_REG_ASSG "6"
8866 #define BUILTIN_SPEC_REG_ASSG "7"
8868 /* Stubs for calling non-FAST_FUNC's */
8869 #if ENABLE_ASH_BUILTIN_ECHO
8870 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8872 #if ENABLE_ASH_BUILTIN_PRINTF
8873 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8875 #if ENABLE_ASH_BUILTIN_TEST
8876 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8879 /* Keep these in proper order since it is searched via bsearch() */
8880 static const struct builtincmd builtintab[] = {
8881 { BUILTIN_SPEC_REG ".", dotcmd },
8882 { BUILTIN_SPEC_REG ":", truecmd },
8883 #if ENABLE_ASH_BUILTIN_TEST
8884 { BUILTIN_REGULAR "[", testcmd },
8885 #if ENABLE_ASH_BASH_COMPAT
8886 { BUILTIN_REGULAR "[[", testcmd },
8889 #if ENABLE_ASH_ALIAS
8890 { BUILTIN_REG_ASSG "alias", aliascmd },
8893 { BUILTIN_REGULAR "bg", fg_bgcmd },
8895 { BUILTIN_SPEC_REG "break", breakcmd },
8896 { BUILTIN_REGULAR "cd", cdcmd },
8897 { BUILTIN_NOSPEC "chdir", cdcmd },
8898 #if ENABLE_ASH_CMDCMD
8899 { BUILTIN_REGULAR "command", commandcmd },
8901 { BUILTIN_SPEC_REG "continue", breakcmd },
8902 #if ENABLE_ASH_BUILTIN_ECHO
8903 { BUILTIN_REGULAR "echo", echocmd },
8905 { BUILTIN_SPEC_REG "eval", evalcmd },
8906 { BUILTIN_SPEC_REG "exec", execcmd },
8907 { BUILTIN_SPEC_REG "exit", exitcmd },
8908 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8909 { BUILTIN_REGULAR "false", falsecmd },
8911 { BUILTIN_REGULAR "fg", fg_bgcmd },
8913 #if ENABLE_ASH_GETOPTS
8914 { BUILTIN_REGULAR "getopts", getoptscmd },
8916 { BUILTIN_NOSPEC "hash", hashcmd },
8917 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8918 { BUILTIN_NOSPEC "help", helpcmd },
8921 { BUILTIN_REGULAR "jobs", jobscmd },
8922 { BUILTIN_REGULAR "kill", killcmd },
8924 #if ENABLE_SH_MATH_SUPPORT
8925 { BUILTIN_NOSPEC "let", letcmd },
8927 { BUILTIN_ASSIGN "local", localcmd },
8928 #if ENABLE_ASH_BUILTIN_PRINTF
8929 { BUILTIN_REGULAR "printf", printfcmd },
8931 { BUILTIN_NOSPEC "pwd", pwdcmd },
8932 { BUILTIN_REGULAR "read", readcmd },
8933 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8934 { BUILTIN_SPEC_REG "return", returncmd },
8935 { BUILTIN_SPEC_REG "set", setcmd },
8936 { BUILTIN_SPEC_REG "shift", shiftcmd },
8937 { BUILTIN_SPEC_REG "source", dotcmd },
8938 #if ENABLE_ASH_BUILTIN_TEST
8939 { BUILTIN_REGULAR "test", testcmd },
8941 { BUILTIN_SPEC_REG "times", timescmd },
8942 { BUILTIN_SPEC_REG "trap", trapcmd },
8943 { BUILTIN_REGULAR "true", truecmd },
8944 { BUILTIN_NOSPEC "type", typecmd },
8945 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8946 { BUILTIN_REGULAR "umask", umaskcmd },
8947 #if ENABLE_ASH_ALIAS
8948 { BUILTIN_REGULAR "unalias", unaliascmd },
8950 { BUILTIN_SPEC_REG "unset", unsetcmd },
8951 { BUILTIN_REGULAR "wait", waitcmd },
8954 /* Should match the above table! */
8955 #define COMMANDCMD (builtintab + \
8957 1 * ENABLE_ASH_BUILTIN_TEST + \
8958 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8959 1 * ENABLE_ASH_ALIAS + \
8960 1 * ENABLE_ASH_JOB_CONTROL + \
8962 #define EXECCMD (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 1 * ENABLE_ASH_CMDCMD + \
8971 ENABLE_ASH_BUILTIN_ECHO + \
8975 * Search the table of builtin commands.
8977 static struct builtincmd *
8978 find_builtin(const char *name)
8980 struct builtincmd *bp;
8983 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8990 * Execute a simple command.
8993 isassignment(const char *p)
8995 const char *q = endofname(p);
9000 static int FAST_FUNC
9001 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9003 /* Preserve exitstatus of a previous possible redirection
9004 * as POSIX mandates */
9005 return back_exitstatus;
9008 evalcommand(union node *cmd, int flags)
9010 static const struct builtincmd null_bltin = {
9011 "\0\0", bltincmd /* why three NULs? */
9013 struct stackmark smark;
9015 struct arglist arglist;
9016 struct arglist varlist;
9019 const struct strlist *sp;
9020 struct cmdentry cmdentry;
9027 struct builtincmd *bcmd;
9028 smallint cmd_is_exec;
9029 smallint pseudovarflag = 0;
9031 /* First expand the arguments. */
9032 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9033 setstackmark(&smark);
9034 back_exitstatus = 0;
9036 cmdentry.cmdtype = CMDBUILTIN;
9037 cmdentry.u.cmd = &null_bltin;
9038 varlist.lastp = &varlist.list;
9039 *varlist.lastp = NULL;
9040 arglist.lastp = &arglist.list;
9041 *arglist.lastp = NULL;
9044 if (cmd->ncmd.args) {
9045 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9046 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9049 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9050 struct strlist **spp;
9052 spp = arglist.lastp;
9053 if (pseudovarflag && isassignment(argp->narg.text))
9054 expandarg(argp, &arglist, EXP_VARTILDE);
9056 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9058 for (sp = *spp; sp; sp = sp->next)
9062 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9063 for (sp = arglist.list; sp; sp = sp->next) {
9064 TRACE(("evalcommand arg: %s\n", sp->text));
9065 *nargv++ = sp->text;
9070 if (iflag && funcnest == 0 && argc > 0)
9071 lastarg = nargv[-1];
9074 expredir(cmd->ncmd.redirect);
9075 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9078 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9079 struct strlist **spp;
9082 spp = varlist.lastp;
9083 expandarg(argp, &varlist, EXP_VARTILDE);
9086 * Modify the command lookup path, if a PATH= assignment
9090 if (varequal(p, path))
9094 /* Print the command if xflag is set. */
9097 const char *p = " %s";
9100 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9103 for (n = 0; n < 2; n++) {
9105 fdprintf(preverrout_fd, p, sp->text);
9113 safe_write(preverrout_fd, "\n", 1);
9119 /* Now locate the command. */
9121 const char *oldpath;
9122 int cmd_flag = DO_ERR;
9127 find_command(argv[0], &cmdentry, cmd_flag, path);
9128 if (cmdentry.cmdtype == CMDUNKNOWN) {
9129 flush_stdout_stderr();
9134 /* implement bltin and command here */
9135 if (cmdentry.cmdtype != CMDBUILTIN)
9138 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9139 if (cmdentry.u.cmd == EXECCMD)
9141 #if ENABLE_ASH_CMDCMD
9142 if (cmdentry.u.cmd == COMMANDCMD) {
9144 nargv = parse_command_args(argv, &path);
9147 argc -= nargv - argv;
9149 cmd_flag |= DO_NOFUNC;
9157 /* We have a redirection error. */
9159 raise_exception(EXERROR);
9161 exitstatus = status;
9165 /* Execute the command. */
9166 switch (cmdentry.cmdtype) {
9169 #if ENABLE_FEATURE_SH_NOFORK
9170 /* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9171 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
9173 /* find_command() encodes applet_no as (-2 - applet_no) */
9174 int applet_no = (- cmdentry.u.index - 2);
9175 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9176 listsetvar(varlist.list, VEXPORT|VSTACK);
9177 /* run <applet>_main() */
9178 exitstatus = run_nofork_applet(applet_no, argv);
9183 /* Fork off a child process if necessary. */
9184 if (!(flags & EV_EXIT) || trap[0]) {
9186 jp = makejob(/*cmd,*/ 1);
9187 if (forkshell(jp, cmd, FORK_FG) != 0) {
9188 exitstatus = waitforjob(jp);
9190 TRACE(("forked child exited with %d\n", exitstatus));
9195 listsetvar(varlist.list, VEXPORT|VSTACK);
9196 shellexec(argv, path, cmdentry.u.index);
9200 cmdenviron = varlist.list;
9202 struct strlist *list = cmdenviron;
9204 if (spclbltin > 0 || argc == 0) {
9206 if (cmd_is_exec && argc > 1)
9209 listsetvar(list, i);
9211 /* Tight loop with builtins only:
9212 * "while kill -0 $child; do true; done"
9213 * will never exit even if $child died, unless we do this
9214 * to reap the zombie and make kill detect that it's gone: */
9215 dowait(DOWAIT_NONBLOCK, NULL);
9217 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9219 int i = exception_type;
9224 exit_status = 128 + SIGINT;
9226 exit_status = 128 + pending_sig;
9227 exitstatus = exit_status;
9228 if (i == EXINT || spclbltin > 0) {
9230 longjmp(exception_handler->loc, 1);
9237 listsetvar(varlist.list, 0);
9238 /* See above for the rationale */
9239 dowait(DOWAIT_NONBLOCK, NULL);
9240 if (evalfun(cmdentry.u.func, argc, argv, flags))
9246 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9248 /* dsl: I think this is intended to be used to support
9249 * '_' in 'vi' command mode during line editing...
9250 * However I implemented that within libedit itself.
9252 setvar("_", lastarg, 0);
9254 popstackmark(&smark);
9258 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9260 char *volatile savecmdname;
9261 struct jmploc *volatile savehandler;
9262 struct jmploc jmploc;
9265 savecmdname = commandname;
9266 i = setjmp(jmploc.loc);
9269 savehandler = exception_handler;
9270 exception_handler = &jmploc;
9271 commandname = argv[0];
9273 optptr = NULL; /* initialize nextopt */
9274 exitstatus = (*cmd->builtin)(argc, argv);
9275 flush_stdout_stderr();
9277 exitstatus |= ferror(stdout);
9279 commandname = savecmdname;
9280 exception_handler = savehandler;
9286 goodname(const char *p)
9288 return !*endofname(p);
9293 * Search for a command. This is called before we fork so that the
9294 * location of the command will be available in the parent as well as
9295 * the child. The check for "goodname" is an overly conservative
9296 * check that the name will not be subject to expansion.
9299 prehash(union node *n)
9301 struct cmdentry entry;
9303 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9304 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9308 /* ============ Builtin commands
9310 * Builtin commands whose functions are closely tied to evaluation
9311 * are implemented here.
9315 * Handle break and continue commands. Break, continue, and return are
9316 * all handled by setting the evalskip flag. The evaluation routines
9317 * above all check this flag, and if it is set they start skipping
9318 * commands rather than executing them. The variable skipcount is
9319 * the number of loops to break/continue, or the number of function
9320 * levels to return. (The latter is always 1.) It should probably
9321 * be an error to break out of more loops than exist, but it isn't
9322 * in the standard shell so we don't make it one here.
9324 static int FAST_FUNC
9325 breakcmd(int argc UNUSED_PARAM, char **argv)
9327 int n = argv[1] ? number(argv[1]) : 1;
9330 ash_msg_and_raise_error(msg_illnum, argv[1]);
9334 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9341 /* ============ input.c
9343 * This implements the input routines used by the parser.
9347 INPUT_PUSH_FILE = 1,
9348 INPUT_NOFILE_OK = 2,
9351 static smallint checkkwd;
9352 /* values of checkkwd variable */
9353 #define CHKALIAS 0x1
9358 * Push a string back onto the input at this current parsefile level.
9359 * We handle aliases this way.
9361 #if !ENABLE_ASH_ALIAS
9362 #define pushstring(s, ap) pushstring(s)
9365 pushstring(char *s, struct alias *ap)
9372 if (g_parsefile->strpush) {
9373 sp = ckzalloc(sizeof(*sp));
9374 sp->prev = g_parsefile->strpush;
9376 sp = &(g_parsefile->basestrpush);
9378 g_parsefile->strpush = sp;
9379 sp->prev_string = g_parsefile->next_to_pgetc;
9380 sp->prev_left_in_line = g_parsefile->left_in_line;
9381 #if ENABLE_ASH_ALIAS
9384 ap->flag |= ALIASINUSE;
9388 g_parsefile->next_to_pgetc = s;
9389 g_parsefile->left_in_line = len;
9396 struct strpush *sp = g_parsefile->strpush;
9399 #if ENABLE_ASH_ALIAS
9401 if (g_parsefile->next_to_pgetc[-1] == ' '
9402 || g_parsefile->next_to_pgetc[-1] == '\t'
9404 checkkwd |= CHKALIAS;
9406 if (sp->string != sp->ap->val) {
9409 sp->ap->flag &= ~ALIASINUSE;
9410 if (sp->ap->flag & ALIASDEAD) {
9411 unalias(sp->ap->name);
9415 g_parsefile->next_to_pgetc = sp->prev_string;
9416 g_parsefile->left_in_line = sp->prev_left_in_line;
9417 g_parsefile->strpush = sp->prev;
9418 if (sp != &(g_parsefile->basestrpush))
9423 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9424 //it peeks whether it is &>, and then pushes back both chars.
9425 //This function needs to save last *next_to_pgetc to buf[0]
9426 //to make two pungetc() reliable. Currently,
9427 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9432 char *buf = g_parsefile->buf;
9434 g_parsefile->next_to_pgetc = buf;
9435 #if ENABLE_FEATURE_EDITING
9437 if (!iflag || g_parsefile->fd != STDIN_FILENO)
9438 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9440 #if ENABLE_FEATURE_TAB_COMPLETION
9441 line_input_state->path_lookup = pathval();
9443 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9445 /* Ctrl+C pressed */
9454 if (nr < 0 && errno == 0) {
9455 /* Ctrl+D pressed */
9460 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9464 /* nonblock_safe_read() handles this problem */
9466 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9467 int flags = fcntl(0, F_GETFL);
9468 if (flags >= 0 && (flags & O_NONBLOCK)) {
9469 flags &= ~O_NONBLOCK;
9470 if (fcntl(0, F_SETFL, flags) >= 0) {
9471 out2str("sh: turning off NDELAY mode\n");
9482 * Refill the input buffer and return the next input character:
9484 * 1) If a string was pushed back on the input, pop it;
9485 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9486 * or we are reading from a string so we can't refill the buffer,
9488 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9489 * 4) Process input up to the next newline, deleting nul characters.
9491 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9492 #define pgetc_debug(...) ((void)0)
9499 while (g_parsefile->strpush) {
9500 #if ENABLE_ASH_ALIAS
9501 if (g_parsefile->left_in_line == -1
9502 && g_parsefile->strpush->ap
9503 && g_parsefile->next_to_pgetc[-1] != ' '
9504 && g_parsefile->next_to_pgetc[-1] != '\t'
9506 pgetc_debug("preadbuffer PEOA");
9511 /* try "pgetc" now: */
9512 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9513 g_parsefile->left_in_line,
9514 g_parsefile->next_to_pgetc,
9515 g_parsefile->next_to_pgetc);
9516 if (--g_parsefile->left_in_line >= 0)
9517 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9519 /* on both branches above g_parsefile->left_in_line < 0.
9520 * "pgetc" needs refilling.
9523 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9524 * pungetc() may increment it a few times.
9525 * Assuming it won't increment it to less than -90.
9527 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9528 pgetc_debug("preadbuffer PEOF1");
9529 /* even in failure keep left_in_line and next_to_pgetc
9530 * in lock step, for correct multi-layer pungetc.
9531 * left_in_line was decremented before preadbuffer(),
9532 * must inc next_to_pgetc: */
9533 g_parsefile->next_to_pgetc++;
9537 more = g_parsefile->left_in_buffer;
9539 flush_stdout_stderr();
9543 /* don't try reading again */
9544 g_parsefile->left_in_line = -99;
9545 pgetc_debug("preadbuffer PEOF2");
9546 g_parsefile->next_to_pgetc++;
9551 /* Find out where's the end of line.
9552 * Set g_parsefile->left_in_line
9553 * and g_parsefile->left_in_buffer acordingly.
9554 * NUL chars are deleted.
9556 q = g_parsefile->next_to_pgetc;
9564 memmove(q, q + 1, more);
9568 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9574 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9575 if (g_parsefile->left_in_line < 0)
9580 g_parsefile->left_in_buffer = more;
9585 out2str(g_parsefile->next_to_pgetc);
9589 pgetc_debug("preadbuffer at %d:%p'%s'",
9590 g_parsefile->left_in_line,
9591 g_parsefile->next_to_pgetc,
9592 g_parsefile->next_to_pgetc);
9593 return (unsigned char)*g_parsefile->next_to_pgetc++;
9596 #define pgetc_as_macro() \
9597 (--g_parsefile->left_in_line >= 0 \
9598 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9605 pgetc_debug("pgetc_fast at %d:%p'%s'",
9606 g_parsefile->left_in_line,
9607 g_parsefile->next_to_pgetc,
9608 g_parsefile->next_to_pgetc);
9609 return pgetc_as_macro();
9612 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9613 # define pgetc_fast() pgetc()
9615 # define pgetc_fast() pgetc_as_macro()
9618 #if ENABLE_ASH_ALIAS
9620 pgetc_without_PEOA(void)
9624 pgetc_debug("pgetc_fast at %d:%p'%s'",
9625 g_parsefile->left_in_line,
9626 g_parsefile->next_to_pgetc,
9627 g_parsefile->next_to_pgetc);
9629 } while (c == PEOA);
9633 # define pgetc_without_PEOA() pgetc()
9637 * Read a line from the script.
9640 pfgets(char *line, int len)
9646 while (--nleft > 0) {
9647 c = pgetc_without_PEOA();
9662 * Undo the last call to pgetc. Only one character may be pushed back.
9663 * PEOF may be pushed back.
9668 g_parsefile->left_in_line++;
9669 g_parsefile->next_to_pgetc--;
9670 pgetc_debug("pushed back to %d:%p'%s'",
9671 g_parsefile->left_in_line,
9672 g_parsefile->next_to_pgetc,
9673 g_parsefile->next_to_pgetc);
9677 * To handle the "." command, a stack of input files is used. Pushfile
9678 * adds a new entry to the stack and popfile restores the previous level.
9683 struct parsefile *pf;
9685 pf = ckzalloc(sizeof(*pf));
9686 pf->prev = g_parsefile;
9688 /*pf->strpush = NULL; - ckzalloc did it */
9689 /*pf->basestrpush.prev = NULL;*/
9696 struct parsefile *pf = g_parsefile;
9704 g_parsefile = pf->prev;
9710 * Return to top level.
9715 while (g_parsefile != &basepf)
9720 * Close the file(s) that the shell is reading commands from. Called
9721 * after a fork is done.
9727 if (g_parsefile->fd > 0) {
9728 close(g_parsefile->fd);
9729 g_parsefile->fd = 0;
9734 * Like setinputfile, but takes an open file descriptor. Call this with
9738 setinputfd(int fd, int push)
9740 close_on_exec_on(fd);
9743 g_parsefile->buf = NULL;
9745 g_parsefile->fd = fd;
9746 if (g_parsefile->buf == NULL)
9747 g_parsefile->buf = ckmalloc(IBUFSIZ);
9748 g_parsefile->left_in_buffer = 0;
9749 g_parsefile->left_in_line = 0;
9750 g_parsefile->linno = 1;
9754 * Set the input to take input from a file. If push is set, push the
9755 * old input onto the stack first.
9758 setinputfile(const char *fname, int flags)
9764 fd = open(fname, O_RDONLY);
9766 if (flags & INPUT_NOFILE_OK)
9768 ash_msg_and_raise_error("can't open '%s'", fname);
9771 fd2 = copyfd(fd, 10);
9774 ash_msg_and_raise_error("out of file descriptors");
9777 setinputfd(fd, flags & INPUT_PUSH_FILE);
9784 * Like setinputfile, but takes input from a string.
9787 setinputstring(char *string)
9791 g_parsefile->next_to_pgetc = string;
9792 g_parsefile->left_in_line = strlen(string);
9793 g_parsefile->buf = NULL;
9794 g_parsefile->linno = 1;
9799 /* ============ mail.c
9801 * Routines to check for mail.
9806 #define MAXMBOXES 10
9808 /* times of mailboxes */
9809 static time_t mailtime[MAXMBOXES];
9810 /* Set if MAIL or MAILPATH is changed. */
9811 static smallint mail_var_path_changed;
9814 * Print appropriate message(s) if mail has arrived.
9815 * If mail_var_path_changed is set,
9816 * then the value of MAIL has mail_var_path_changed,
9817 * so we just update the values.
9826 struct stackmark smark;
9829 setstackmark(&smark);
9830 mpath = mpathset() ? mpathval() : mailval();
9831 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9832 p = path_advance(&mpath, nullstr);
9837 for (q = p; *q; q++)
9843 q[-1] = '\0'; /* delete trailing '/' */
9844 if (stat(p, &statb) < 0) {
9848 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9851 pathopt ? pathopt : "you have mail"
9854 *mtp = statb.st_mtime;
9856 mail_var_path_changed = 0;
9857 popstackmark(&smark);
9860 static void FAST_FUNC
9861 changemail(const char *val UNUSED_PARAM)
9863 mail_var_path_changed = 1;
9866 #endif /* ASH_MAIL */
9869 /* ============ ??? */
9872 * Set the shell parameters.
9875 setparam(char **argv)
9881 for (nparam = 0; argv[nparam]; nparam++)
9883 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9885 *ap++ = ckstrdup(*argv++);
9888 freeparam(&shellparam);
9889 shellparam.malloced = 1;
9890 shellparam.nparam = nparam;
9891 shellparam.p = newparam;
9892 #if ENABLE_ASH_GETOPTS
9893 shellparam.optind = 1;
9894 shellparam.optoff = -1;
9899 * Process shell options. The global variable argptr contains a pointer
9900 * to the argument list; we advance it past the options.
9902 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9903 * For a non-interactive shell, an error condition encountered
9904 * by a special built-in ... shall cause the shell to write a diagnostic message
9905 * to standard error and exit as shown in the following table:
9906 * Error Special Built-In
9908 * Utility syntax error (option or operand error) Shall exit
9910 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9911 * we see that bash does not do that (set "finishes" with error code 1 instead,
9912 * and shell continues), and people rely on this behavior!
9914 * set -o barfoo 2>/dev/null
9917 * Oh well. Let's mimic that.
9920 plus_minus_o(char *name, int val)
9925 for (i = 0; i < NOPTS; i++) {
9926 if (strcmp(name, optnames(i)) == 0) {
9931 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9934 for (i = 0; i < NOPTS; i++) {
9936 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9938 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9944 setoption(int flag, int val)
9948 for (i = 0; i < NOPTS; i++) {
9949 if (optletters(i) == flag) {
9954 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9958 options(int cmdline)
9966 while ((p = *argptr) != NULL) {
9968 if (c != '-' && c != '+')
9971 val = 0; /* val = 0 if c == '+' */
9974 if (p[0] == '\0' || LONE_DASH(p)) {
9976 /* "-" means turn off -x and -v */
9979 /* "--" means reset params */
9980 else if (*argptr == NULL)
9983 break; /* "-" or "--" terminates options */
9986 /* first char was + or - */
9987 while ((c = *p++) != '\0') {
9988 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9989 if (c == 'c' && cmdline) {
9990 minusc = p; /* command is after shell args */
9991 } else if (c == 'o') {
9992 if (plus_minus_o(*argptr, val)) {
9993 /* it already printed err message */
9994 return 1; /* error */
9998 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10000 /* bash does not accept +-login, we also won't */
10001 } else if (cmdline && val && (c == '-')) { /* long options */
10002 if (strcmp(p, "login") == 0)
10014 * The shift builtin command.
10016 static int FAST_FUNC
10017 shiftcmd(int argc UNUSED_PARAM, char **argv)
10024 n = number(argv[1]);
10025 if (n > shellparam.nparam)
10026 n = 0; /* bash compat, was = shellparam.nparam; */
10028 shellparam.nparam -= n;
10029 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10030 if (shellparam.malloced)
10033 ap2 = shellparam.p;
10034 while ((*ap2++ = *ap1++) != NULL)
10036 #if ENABLE_ASH_GETOPTS
10037 shellparam.optind = 1;
10038 shellparam.optoff = -1;
10045 * POSIX requires that 'set' (but not export or readonly) output the
10046 * variables in lexicographic order - by the locale's collating order (sigh).
10047 * Maybe we could keep them in an ordered balanced binary tree
10048 * instead of hashed lists.
10049 * For now just roll 'em through qsort for printing...
10052 showvars(const char *sep_prefix, int on, int off)
10055 char **ep, **epend;
10057 ep = listvars(on, off, &epend);
10058 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10060 sep = *sep_prefix ? " " : sep_prefix;
10062 for (; ep < epend; ep++) {
10066 p = strchrnul(*ep, '=');
10069 q = single_quote(++p);
10070 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10076 * The set command builtin.
10078 static int FAST_FUNC
10079 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10084 return showvars(nullstr, 0, VUNSET);
10087 if (!options(0)) { /* if no parse error... */
10090 if (*argptr != NULL) {
10098 #if ENABLE_ASH_RANDOM_SUPPORT
10099 static void FAST_FUNC
10100 change_random(const char *value)
10104 if (value == NULL) {
10105 /* "get", generate */
10106 t = next_random(&random_gen);
10107 /* set without recursion */
10108 setvar(vrandom.text, utoa(t), VNOFUNC);
10109 vrandom.flags &= ~VNOFUNC;
10112 t = strtoul(value, NULL, 10);
10113 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10118 #if ENABLE_ASH_GETOPTS
10120 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10129 if (*param_optind < 1)
10131 optnext = optfirst + *param_optind - 1;
10133 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10136 p = optnext[-1] + *optoff;
10137 if (p == NULL || *p == '\0') {
10138 /* Current word is done, advance */
10140 if (p == NULL || *p != '-' || *++p == '\0') {
10147 if (LONE_DASH(p)) /* check for "--" */
10152 for (q = optstr; *q != c;) {
10154 if (optstr[0] == ':') {
10157 err |= setvarsafe("OPTARG", s, 0);
10159 fprintf(stderr, "Illegal option -%c\n", c);
10160 unsetvar("OPTARG");
10170 if (*p == '\0' && (p = *optnext) == NULL) {
10171 if (optstr[0] == ':') {
10174 err |= setvarsafe("OPTARG", s, 0);
10177 fprintf(stderr, "No arg for -%c option\n", c);
10178 unsetvar("OPTARG");
10186 err |= setvarsafe("OPTARG", p, 0);
10189 err |= setvarsafe("OPTARG", nullstr, 0);
10191 *optoff = p ? p - *(optnext - 1) : -1;
10192 *param_optind = optnext - optfirst + 1;
10193 fmtstr(s, sizeof(s), "%d", *param_optind);
10194 err |= setvarsafe("OPTIND", s, VNOFUNC);
10197 err |= setvarsafe(optvar, s, 0);
10201 flush_stdout_stderr();
10202 raise_exception(EXERROR);
10208 * The getopts builtin. Shellparam.optnext points to the next argument
10209 * to be processed. Shellparam.optptr points to the next character to
10210 * be processed in the current argument. If shellparam.optnext is NULL,
10211 * then it's the first time getopts has been called.
10213 static int FAST_FUNC
10214 getoptscmd(int argc, char **argv)
10219 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10221 optbase = shellparam.p;
10222 if (shellparam.optind > shellparam.nparam + 1) {
10223 shellparam.optind = 1;
10224 shellparam.optoff = -1;
10227 optbase = &argv[3];
10228 if (shellparam.optind > argc - 2) {
10229 shellparam.optind = 1;
10230 shellparam.optoff = -1;
10234 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10235 &shellparam.optoff);
10237 #endif /* ASH_GETOPTS */
10240 /* ============ Shell parser */
10243 struct heredoc *next; /* next here document in list */
10244 union node *here; /* redirection node */
10245 char *eofmark; /* string indicating end of input */
10246 smallint striptabs; /* if set, strip leading tabs */
10249 static smallint tokpushback; /* last token pushed back */
10250 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10251 static smallint quoteflag; /* set if (part of) last token was quoted */
10252 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10253 static struct heredoc *heredoclist; /* list of here documents to read */
10254 static char *wordtext; /* text of last word returned by readtoken */
10255 static struct nodelist *backquotelist;
10256 static union node *redirnode;
10257 static struct heredoc *heredoc;
10260 * Called when an unexpected token is read during the parse. The argument
10261 * is the token that is expected, or -1 if more than one type of token can
10262 * occur at this point.
10264 static void raise_error_unexpected_syntax(int) NORETURN;
10266 raise_error_unexpected_syntax(int token)
10271 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
10273 sprintf(msg + l, " (expecting %s)", tokname(token));
10274 raise_error_syntax(msg);
10278 #define EOFMARKLEN 79
10280 /* parsing is heavily cross-recursive, need these forward decls */
10281 static union node *andor(void);
10282 static union node *pipeline(void);
10283 static union node *parse_command(void);
10284 static void parseheredoc(void);
10285 static char peektoken(void);
10286 static int readtoken(void);
10288 static union node *
10291 union node *n1, *n2, *n3;
10294 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10295 if (nlflag == 2 && peektoken())
10301 if (tok == TBACKGND) {
10302 if (n2->type == NPIPE) {
10303 n2->npipe.pipe_backgnd = 1;
10305 if (n2->type != NREDIR) {
10306 n3 = stzalloc(sizeof(struct nredir));
10308 /*n3->nredir.redirect = NULL; - stzalloc did it */
10311 n2->type = NBACKGND;
10317 n3 = stzalloc(sizeof(struct nbinary));
10319 n3->nbinary.ch1 = n1;
10320 n3->nbinary.ch2 = n2;
10336 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10344 pungetc(); /* push back EOF on input */
10348 raise_error_unexpected_syntax(-1);
10355 static union node *
10358 union node *n1, *n2, *n3;
10366 } else if (t == TOR) {
10372 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10374 n3 = stzalloc(sizeof(struct nbinary));
10376 n3->nbinary.ch1 = n1;
10377 n3->nbinary.ch2 = n2;
10382 static union node *
10385 union node *n1, *n2, *pipenode;
10386 struct nodelist *lp, *prev;
10390 TRACE(("pipeline: entered\n"));
10391 if (readtoken() == TNOT) {
10393 checkkwd = CHKKWD | CHKALIAS;
10396 n1 = parse_command();
10397 if (readtoken() == TPIPE) {
10398 pipenode = stzalloc(sizeof(struct npipe));
10399 pipenode->type = NPIPE;
10400 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10401 lp = stzalloc(sizeof(struct nodelist));
10402 pipenode->npipe.cmdlist = lp;
10406 lp = stzalloc(sizeof(struct nodelist));
10407 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10408 lp->n = parse_command();
10410 } while (readtoken() == TPIPE);
10416 n2 = stzalloc(sizeof(struct nnot));
10424 static union node *
10429 n = stzalloc(sizeof(struct narg));
10431 /*n->narg.next = NULL; - stzalloc did it */
10432 n->narg.text = wordtext;
10433 n->narg.backquote = backquotelist;
10438 fixredir(union node *n, const char *text, int err)
10442 TRACE(("Fix redir %s %d\n", text, err));
10444 n->ndup.vname = NULL;
10446 fd = bb_strtou(text, NULL, 10);
10447 if (!errno && fd >= 0)
10448 n->ndup.dupfd = fd;
10449 else if (LONE_DASH(text))
10450 n->ndup.dupfd = -1;
10453 raise_error_syntax("bad fd number");
10454 n->ndup.vname = makename();
10459 * Returns true if the text contains nothing to expand (no dollar signs
10463 noexpand(const char *text)
10467 while ((c = *text++) != '\0') {
10468 if (c == CTLQUOTEMARK)
10472 else if (SIT(c, BASESYNTAX) == CCTL)
10481 union node *n = redirnode;
10483 if (readtoken() != TWORD)
10484 raise_error_unexpected_syntax(-1);
10485 if (n->type == NHERE) {
10486 struct heredoc *here = heredoc;
10490 if (quoteflag == 0)
10492 TRACE(("Here document %d\n", n->type));
10493 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10494 raise_error_syntax("illegal eof marker for << redirection");
10495 rmescapes(wordtext, 0);
10496 here->eofmark = wordtext;
10498 if (heredoclist == NULL)
10499 heredoclist = here;
10501 for (p = heredoclist; p->next; p = p->next)
10505 } else if (n->type == NTOFD || n->type == NFROMFD) {
10506 fixredir(n, wordtext, 0);
10508 n->nfile.fname = makename();
10512 static union node *
10515 union node *args, **app;
10516 union node *n = NULL;
10517 union node *vars, **vpp;
10518 union node **rpp, *redir;
10520 #if ENABLE_ASH_BASH_COMPAT
10521 smallint double_brackets_flag = 0;
10531 savecheckkwd = CHKALIAS;
10534 checkkwd = savecheckkwd;
10537 #if ENABLE_ASH_BASH_COMPAT
10538 case TAND: /* "&&" */
10539 case TOR: /* "||" */
10540 if (!double_brackets_flag) {
10544 wordtext = (char *) (t == TAND ? "-a" : "-o");
10547 n = stzalloc(sizeof(struct narg));
10549 /*n->narg.next = NULL; - stzalloc did it */
10550 n->narg.text = wordtext;
10551 #if ENABLE_ASH_BASH_COMPAT
10552 if (strcmp("[[", wordtext) == 0)
10553 double_brackets_flag = 1;
10554 else if (strcmp("]]", wordtext) == 0)
10555 double_brackets_flag = 0;
10557 n->narg.backquote = backquotelist;
10558 if (savecheckkwd && isassignment(wordtext)) {
10560 vpp = &n->narg.next;
10563 app = &n->narg.next;
10568 *rpp = n = redirnode;
10569 rpp = &n->nfile.next;
10570 parsefname(); /* read name of redirection file */
10573 if (args && app == &args->narg.next
10576 struct builtincmd *bcmd;
10579 /* We have a function */
10580 if (readtoken() != TRP)
10581 raise_error_unexpected_syntax(TRP);
10582 name = n->narg.text;
10583 if (!goodname(name)
10584 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10586 raise_error_syntax("bad function name");
10589 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10590 n->narg.next = parse_command();
10603 n = stzalloc(sizeof(struct ncmd));
10605 n->ncmd.args = args;
10606 n->ncmd.assign = vars;
10607 n->ncmd.redirect = redir;
10611 static union node *
10612 parse_command(void)
10614 union node *n1, *n2;
10615 union node *ap, **app;
10616 union node *cp, **cpp;
10617 union node *redir, **rpp;
10624 switch (readtoken()) {
10626 raise_error_unexpected_syntax(-1);
10629 n1 = stzalloc(sizeof(struct nif));
10631 n1->nif.test = list(0);
10632 if (readtoken() != TTHEN)
10633 raise_error_unexpected_syntax(TTHEN);
10634 n1->nif.ifpart = list(0);
10636 while (readtoken() == TELIF) {
10637 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10638 n2 = n2->nif.elsepart;
10640 n2->nif.test = list(0);
10641 if (readtoken() != TTHEN)
10642 raise_error_unexpected_syntax(TTHEN);
10643 n2->nif.ifpart = list(0);
10645 if (lasttoken == TELSE)
10646 n2->nif.elsepart = list(0);
10648 n2->nif.elsepart = NULL;
10656 n1 = stzalloc(sizeof(struct nbinary));
10657 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10658 n1->nbinary.ch1 = list(0);
10661 TRACE(("expecting DO got %s %s\n", tokname(got),
10662 got == TWORD ? wordtext : ""));
10663 raise_error_unexpected_syntax(TDO);
10665 n1->nbinary.ch2 = list(0);
10670 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10671 raise_error_syntax("bad for loop variable");
10672 n1 = stzalloc(sizeof(struct nfor));
10674 n1->nfor.var = wordtext;
10675 checkkwd = CHKKWD | CHKALIAS;
10676 if (readtoken() == TIN) {
10678 while (readtoken() == TWORD) {
10679 n2 = stzalloc(sizeof(struct narg));
10681 /*n2->narg.next = NULL; - stzalloc did it */
10682 n2->narg.text = wordtext;
10683 n2->narg.backquote = backquotelist;
10685 app = &n2->narg.next;
10688 n1->nfor.args = ap;
10689 if (lasttoken != TNL && lasttoken != TSEMI)
10690 raise_error_unexpected_syntax(-1);
10692 n2 = stzalloc(sizeof(struct narg));
10694 /*n2->narg.next = NULL; - stzalloc did it */
10695 n2->narg.text = (char *)dolatstr;
10696 /*n2->narg.backquote = NULL;*/
10697 n1->nfor.args = n2;
10699 * Newline or semicolon here is optional (but note
10700 * that the original Bourne shell only allowed NL).
10702 if (lasttoken != TNL && lasttoken != TSEMI)
10705 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10706 if (readtoken() != TDO)
10707 raise_error_unexpected_syntax(TDO);
10708 n1->nfor.body = list(0);
10712 n1 = stzalloc(sizeof(struct ncase));
10714 if (readtoken() != TWORD)
10715 raise_error_unexpected_syntax(TWORD);
10716 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10718 /*n2->narg.next = NULL; - stzalloc did it */
10719 n2->narg.text = wordtext;
10720 n2->narg.backquote = backquotelist;
10722 checkkwd = CHKKWD | CHKALIAS;
10723 } while (readtoken() == TNL);
10724 if (lasttoken != TIN)
10725 raise_error_unexpected_syntax(TIN);
10726 cpp = &n1->ncase.cases;
10728 checkkwd = CHKNL | CHKKWD;
10730 while (t != TESAC) {
10731 if (lasttoken == TLP)
10733 *cpp = cp = stzalloc(sizeof(struct nclist));
10735 app = &cp->nclist.pattern;
10737 *app = ap = stzalloc(sizeof(struct narg));
10739 /*ap->narg.next = NULL; - stzalloc did it */
10740 ap->narg.text = wordtext;
10741 ap->narg.backquote = backquotelist;
10742 if (readtoken() != TPIPE)
10744 app = &ap->narg.next;
10747 //ap->narg.next = NULL;
10748 if (lasttoken != TRP)
10749 raise_error_unexpected_syntax(TRP);
10750 cp->nclist.body = list(2);
10752 cpp = &cp->nclist.next;
10754 checkkwd = CHKNL | CHKKWD;
10758 raise_error_unexpected_syntax(TENDCASE);
10765 n1 = stzalloc(sizeof(struct nredir));
10766 n1->type = NSUBSHELL;
10767 n1->nredir.n = list(0);
10768 /*n1->nredir.redirect = NULL; - stzalloc did it */
10778 return simplecmd();
10781 if (readtoken() != t)
10782 raise_error_unexpected_syntax(t);
10785 /* Now check for redirection which may follow command */
10786 checkkwd = CHKKWD | CHKALIAS;
10788 while (readtoken() == TREDIR) {
10789 *rpp = n2 = redirnode;
10790 rpp = &n2->nfile.next;
10796 if (n1->type != NSUBSHELL) {
10797 n2 = stzalloc(sizeof(struct nredir));
10802 n1->nredir.redirect = redir;
10807 #if ENABLE_ASH_BASH_COMPAT
10808 static int decode_dollar_squote(void)
10810 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10816 p = strchr(C_escapes, c);
10821 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10825 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10827 } else if (c == 'x') { /* \xHH */
10831 } while (isxdigit(c) && --cnt);
10833 if (cnt == 3) { /* \x but next char is "bad" */
10837 } else { /* simple seq like \\ or \t */
10842 c = bb_process_escape_sequence((void*)&p);
10843 } else { /* unrecognized "\z": print both chars unless ' or " */
10844 if (c != '\'' && c != '"') {
10846 c |= 0x100; /* "please encode \, then me" */
10854 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10855 * is not NULL, read a here document. In the latter case, eofmark is the
10856 * word which marks the end of the document and striptabs is true if
10857 * leading tabs should be stripped from the document. The argument c
10858 * is the first character of the input token or document.
10860 * Because C does not have internal subroutines, I have simulated them
10861 * using goto's to implement the subroutine linkage. The following macros
10862 * will run code that appears at the end of readtoken1.
10864 #define CHECKEND() {goto checkend; checkend_return:;}
10865 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10866 #define PARSESUB() {goto parsesub; parsesub_return:;}
10867 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10868 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10869 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10871 readtoken1(int c, int syntax, char *eofmark, int striptabs)
10873 /* NB: syntax parameter fits into smallint */
10874 /* c parameter is an unsigned char or PEOF or PEOA */
10877 char line[EOFMARKLEN + 1];
10878 struct nodelist *bqlist;
10882 smallint prevsyntax; /* syntax before arithmetic */
10883 #if ENABLE_ASH_EXPAND_PRMT
10884 smallint pssyntax; /* we are expanding a prompt string */
10886 int varnest; /* levels of variables expansion */
10887 int arinest; /* levels of arithmetic expansion */
10888 int parenlevel; /* levels of parens in arithmetic */
10889 int dqvarnest; /* levels of variables expansion within double quotes */
10891 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10894 /* Avoid longjmp clobbering */
10900 (void) &parenlevel;
10903 (void) &prevsyntax;
10906 startlinno = g_parsefile->linno;
10911 #if ENABLE_ASH_EXPAND_PRMT
10912 pssyntax = (syntax == PSSYNTAX);
10916 dblquote = (syntax == DQSYNTAX);
10922 STARTSTACKSTR(out);
10924 /* For each line, until end of word */
10926 CHECKEND(); /* set c to PEOF if at end of here document */
10927 for (;;) { /* until end of line or end of word */
10928 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10929 switch (SIT(c, syntax)) {
10930 case CNL: /* '\n' */
10931 if (syntax == BASESYNTAX)
10932 goto endword; /* exit outer loop */
10934 g_parsefile->linno++;
10938 goto loop; /* continue outer loop */
10943 if (eofmark == NULL || dblquote)
10944 USTPUTC(CTLESC, out);
10945 #if ENABLE_ASH_BASH_COMPAT
10946 if (c == '\\' && bash_dollar_squote) {
10947 c = decode_dollar_squote();
10949 USTPUTC('\\', out);
10950 c = (unsigned char)c;
10956 case CBACK: /* backslash */
10957 c = pgetc_without_PEOA();
10959 USTPUTC(CTLESC, out);
10960 USTPUTC('\\', out);
10962 } else if (c == '\n') {
10966 #if ENABLE_ASH_EXPAND_PRMT
10967 if (c == '$' && pssyntax) {
10968 USTPUTC(CTLESC, out);
10969 USTPUTC('\\', out);
10972 if (dblquote && c != '\\'
10973 && c != '`' && c != '$'
10974 && (c != '"' || eofmark != NULL)
10976 USTPUTC(CTLESC, out);
10977 USTPUTC('\\', out);
10979 if (SIT(c, SQSYNTAX) == CCTL)
10980 USTPUTC(CTLESC, out);
10988 if (eofmark == NULL) {
10989 USTPUTC(CTLQUOTEMARK, out);
10997 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
10998 if (eofmark != NULL && arinest == 0
11003 if (dqvarnest == 0) {
11004 syntax = BASESYNTAX;
11011 case CVAR: /* '$' */
11012 PARSESUB(); /* parse substitution */
11014 case CENDVAR: /* '}' */
11017 if (dqvarnest > 0) {
11020 USTPUTC(CTLENDVAR, out);
11025 #if ENABLE_SH_MATH_SUPPORT
11026 case CLP: /* '(' in arithmetic */
11030 case CRP: /* ')' in arithmetic */
11031 if (parenlevel > 0) {
11035 if (pgetc() == ')') {
11036 if (--arinest == 0) {
11037 USTPUTC(CTLENDARI, out);
11038 syntax = prevsyntax;
11039 dblquote = (syntax == DQSYNTAX);
11044 * unbalanced parens
11045 * (don't 2nd guess - no error)
11053 case CBQUOTE: /* '`' */
11057 goto endword; /* exit outer loop */
11061 if (varnest == 0) {
11062 #if ENABLE_ASH_BASH_COMPAT
11064 if (pgetc() == '>')
11065 c = 0x100 + '>'; /* flag &> */
11069 goto endword; /* exit outer loop */
11071 IF_ASH_ALIAS(if (c != PEOA))
11079 #if ENABLE_SH_MATH_SUPPORT
11080 if (syntax == ARISYNTAX)
11081 raise_error_syntax("missing '))'");
11083 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11084 raise_error_syntax("unterminated quoted string");
11085 if (varnest != 0) {
11086 startlinno = g_parsefile->linno;
11088 raise_error_syntax("missing '}'");
11090 USTPUTC('\0', out);
11091 len = out - (char *)stackblock();
11092 out = stackblock();
11093 if (eofmark == NULL) {
11094 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11097 if (isdigit_str9(out)) {
11098 PARSEREDIR(); /* passed as params: out, c */
11099 lasttoken = TREDIR;
11102 /* else: non-number X seen, interpret it
11103 * as "NNNX>file" = "NNNX >file" */
11107 quoteflag = quotef;
11108 backquotelist = bqlist;
11109 grabstackblock(len);
11113 /* end of readtoken routine */
11116 * Check to see whether we are at the end of the here document. When this
11117 * is called, c is set to the first character of the next input line. If
11118 * we are at the end of the here document, this routine sets the c to PEOF.
11122 #if ENABLE_ASH_ALIAS
11124 c = pgetc_without_PEOA();
11127 while (c == '\t') {
11128 c = pgetc_without_PEOA();
11131 if (c == *eofmark) {
11132 if (pfgets(line, sizeof(line)) != NULL) {
11136 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11138 if (*p == '\n' && *q == '\0') {
11140 g_parsefile->linno++;
11141 needprompt = doprompt;
11143 pushstring(line, NULL);
11148 goto checkend_return;
11152 * Parse a redirection operator. The variable "out" points to a string
11153 * specifying the fd to be redirected. The variable "c" contains the
11154 * first character of the redirection operator.
11157 /* out is already checked to be a valid number or "" */
11158 int fd = (*out == '\0' ? -1 : atoi(out));
11161 np = stzalloc(sizeof(struct nfile));
11166 np->type = NAPPEND;
11168 np->type = NCLOBBER;
11171 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11177 #if ENABLE_ASH_BASH_COMPAT
11178 else if (c == 0x100 + '>') { /* this flags &> redirection */
11180 pgetc(); /* this is '>', no need to check */
11184 else { /* c == '<' */
11185 /*np->nfile.fd = 0; - stzalloc did it */
11189 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11190 np = stzalloc(sizeof(struct nhere));
11191 /*np->nfile.fd = 0; - stzalloc did it */
11194 heredoc = stzalloc(sizeof(struct heredoc));
11195 heredoc->here = np;
11198 heredoc->striptabs = 1;
11200 /*heredoc->striptabs = 0; - stzalloc did it */
11206 np->type = NFROMFD;
11210 np->type = NFROMTO;
11222 goto parseredir_return;
11226 * Parse a substitution. At this point, we have read the dollar sign
11227 * and nothing else.
11230 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11231 * (assuming ascii char codes, as the original implementation did) */
11232 #define is_special(c) \
11233 (((unsigned)(c) - 33 < 32) \
11234 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11236 unsigned char subtype;
11240 static const char types[] ALIGN1 = "}-+?=";
11243 if (c > 255 /* PEOA or PEOF */
11244 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11246 #if ENABLE_ASH_BASH_COMPAT
11248 bash_dollar_squote = 1;
11253 } else if (c == '(') { /* $(command) or $((arith)) */
11254 if (pgetc() == '(') {
11255 #if ENABLE_SH_MATH_SUPPORT
11258 raise_error_syntax("you disabled math support for $((arith)) syntax");
11265 USTPUTC(CTLVAR, out);
11266 typeloc = out - (char *)stackblock();
11267 USTPUTC(VSNORMAL, out);
11268 subtype = VSNORMAL;
11276 subtype = VSLENGTH;
11280 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11284 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11285 } else if (isdigit(c)) {
11289 } while (isdigit(c));
11290 } else if (is_special(c)) {
11295 raise_error_syntax("bad substitution");
11297 if (c != '}' && subtype == VSLENGTH)
11302 if (subtype == 0) {
11306 #if ENABLE_ASH_BASH_COMPAT
11307 if (c == ':' || c == '$' || isdigit(c)) {
11309 subtype = VSSUBSTR;
11316 p = strchr(types, c);
11319 subtype = p - types + VSNORMAL;
11324 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11332 #if ENABLE_ASH_BASH_COMPAT
11334 subtype = VSREPLACE;
11337 subtype++; /* VSREPLACEALL */
11346 if (dblquote || arinest)
11348 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11349 if (subtype != VSNORMAL) {
11351 if (dblquote || arinest) {
11356 goto parsesub_return;
11360 * Called to parse command substitutions. Newstyle is set if the command
11361 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11362 * list of commands (passed by reference), and savelen is the number of
11363 * characters on the top of the stack which must be preserved.
11366 struct nodelist **nlpp;
11369 char *volatile str;
11370 struct jmploc jmploc;
11371 struct jmploc *volatile savehandler;
11373 smallint saveprompt = 0;
11376 (void) &saveprompt;
11378 savepbq = parsebackquote;
11379 if (setjmp(jmploc.loc)) {
11381 parsebackquote = 0;
11382 exception_handler = savehandler;
11383 longjmp(exception_handler->loc, 1);
11387 savelen = out - (char *)stackblock();
11389 str = ckmalloc(savelen);
11390 memcpy(str, stackblock(), savelen);
11392 savehandler = exception_handler;
11393 exception_handler = &jmploc;
11396 /* We must read until the closing backquote, giving special
11397 treatment to some slashes, and then push the string and
11398 reread it as input, interpreting it normally. */
11405 STARTSTACKSTR(pout);
11418 g_parsefile->linno++;
11422 * If eating a newline, avoid putting
11423 * the newline into the new character
11424 * stream (via the STPUTC after the
11429 if (pc != '\\' && pc != '`' && pc != '$'
11430 && (!dblquote || pc != '"')
11432 STPUTC('\\', pout);
11434 if (pc <= 255 /* not PEOA or PEOF */) {
11440 IF_ASH_ALIAS(case PEOA:)
11441 startlinno = g_parsefile->linno;
11442 raise_error_syntax("EOF in backquote substitution");
11445 g_parsefile->linno++;
11446 needprompt = doprompt;
11455 STPUTC('\0', pout);
11456 psavelen = pout - (char *)stackblock();
11457 if (psavelen > 0) {
11458 pstr = grabstackstr(pout);
11459 setinputstring(pstr);
11464 nlpp = &(*nlpp)->next;
11465 *nlpp = stzalloc(sizeof(**nlpp));
11466 /* (*nlpp)->next = NULL; - stzalloc did it */
11467 parsebackquote = oldstyle;
11470 saveprompt = doprompt;
11477 doprompt = saveprompt;
11478 else if (readtoken() != TRP)
11479 raise_error_unexpected_syntax(TRP);
11484 * Start reading from old file again, ignoring any pushed back
11485 * tokens left from the backquote parsing
11490 while (stackblocksize() <= savelen)
11492 STARTSTACKSTR(out);
11494 memcpy(out, str, savelen);
11495 STADJUST(savelen, out);
11501 parsebackquote = savepbq;
11502 exception_handler = savehandler;
11503 if (arinest || dblquote)
11504 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11506 USTPUTC(CTLBACKQ, out);
11508 goto parsebackq_oldreturn;
11509 goto parsebackq_newreturn;
11512 #if ENABLE_SH_MATH_SUPPORT
11514 * Parse an arithmetic expansion (indicate start of one and set state)
11517 if (++arinest == 1) {
11518 prevsyntax = syntax;
11519 syntax = ARISYNTAX;
11520 USTPUTC(CTLARI, out);
11527 * we collapse embedded arithmetic expansion to
11528 * parenthesis, which should be equivalent
11532 goto parsearith_return;
11536 } /* end of readtoken */
11539 * Read the next input token.
11540 * If the token is a word, we set backquotelist to the list of cmds in
11541 * backquotes. We set quoteflag to true if any part of the word was
11543 * If the token is TREDIR, then we set redirnode to a structure containing
11545 * In all cases, the variable startlinno is set to the number of the line
11546 * on which the token starts.
11548 * [Change comment: here documents and internal procedures]
11549 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11550 * word parsing code into a separate routine. In this case, readtoken
11551 * doesn't need to have any internal procedures, but parseword does.
11552 * We could also make parseoperator in essence the main routine, and
11553 * have parseword (readtoken1?) handle both words and redirection.]
11555 #define NEW_xxreadtoken
11556 #ifdef NEW_xxreadtoken
11557 /* singles must be first! */
11558 static const char xxreadtoken_chars[7] ALIGN1 = {
11559 '\n', '(', ')', /* singles */
11560 '&', '|', ';', /* doubles */
11564 #define xxreadtoken_singles 3
11565 #define xxreadtoken_doubles 3
11567 static const char xxreadtoken_tokens[] ALIGN1 = {
11568 TNL, TLP, TRP, /* only single occurrence allowed */
11569 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11570 TEOF, /* corresponds to trailing nul */
11571 TAND, TOR, TENDCASE /* if double occurrence */
11586 startlinno = g_parsefile->linno;
11587 for (;;) { /* until token or start of word found */
11589 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11593 while ((c = pgetc()) != '\n' && c != PEOF)
11596 } else if (c == '\\') {
11597 if (pgetc() != '\n') {
11599 break; /* return readtoken1(...) */
11601 startlinno = ++g_parsefile->linno;
11607 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11610 g_parsefile->linno++;
11611 needprompt = doprompt;
11614 p = strchr(xxreadtoken_chars, c);
11616 break; /* return readtoken1(...) */
11618 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11620 if (cc == c) { /* double occurrence? */
11621 p += xxreadtoken_doubles + 1;
11624 #if ENABLE_ASH_BASH_COMPAT
11625 if (c == '&' && cc == '>') /* &> */
11626 break; /* return readtoken1(...) */
11631 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11636 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11638 #else /* old xxreadtoken */
11639 #define RETURN(token) return lasttoken = token
11652 startlinno = g_parsefile->linno;
11653 for (;;) { /* until token or start of word found */
11656 case ' ': case '\t':
11657 IF_ASH_ALIAS(case PEOA:)
11660 while ((c = pgetc()) != '\n' && c != PEOF)
11665 if (pgetc() == '\n') {
11666 startlinno = ++g_parsefile->linno;
11674 g_parsefile->linno++;
11675 needprompt = doprompt;
11680 if (pgetc() == '&')
11685 if (pgetc() == '|')
11690 if (pgetc() == ';')
11703 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11706 #endif /* old xxreadtoken */
11713 smallint alreadyseen = tokpushback;
11716 #if ENABLE_ASH_ALIAS
11725 if (checkkwd & CHKNL) {
11732 if (t != TWORD || quoteflag) {
11737 * check for keywords
11739 if (checkkwd & CHKKWD) {
11740 const char *const *pp;
11742 pp = findkwd(wordtext);
11744 lasttoken = t = pp - tokname_array;
11745 TRACE(("keyword %s recognized\n", tokname(t)));
11750 if (checkkwd & CHKALIAS) {
11751 #if ENABLE_ASH_ALIAS
11753 ap = lookupalias(wordtext, 1);
11756 pushstring(ap->val, ap);
11766 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11768 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11780 return tokname_array[t][0];
11784 * Read and parse a command. Returns NODE_EOF on end of file.
11785 * (NULL is a valid parse tree indicating a blank line.)
11787 static union node *
11788 parsecmd(int interact)
11793 doprompt = interact;
11795 setprompt(doprompt);
11807 * Input any here documents.
11812 struct heredoc *here;
11815 here = heredoclist;
11816 heredoclist = NULL;
11822 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11823 here->eofmark, here->striptabs);
11824 n = stzalloc(sizeof(struct narg));
11825 n->narg.type = NARG;
11826 /*n->narg.next = NULL; - stzalloc did it */
11827 n->narg.text = wordtext;
11828 n->narg.backquote = backquotelist;
11829 here->here->nhere.doc = n;
11836 * called by editline -- any expansions to the prompt should be added here.
11838 #if ENABLE_ASH_EXPAND_PRMT
11839 static const char *
11840 expandstr(const char *ps)
11844 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11845 * and token processing _can_ alter it (delete NULs etc). */
11846 setinputstring((char *)ps);
11847 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11850 n.narg.type = NARG;
11851 n.narg.next = NULL;
11852 n.narg.text = wordtext;
11853 n.narg.backquote = backquotelist;
11855 expandarg(&n, NULL, 0);
11856 return stackblock();
11861 * Execute a command or commands contained in a string.
11864 evalstring(char *s, int mask)
11867 struct stackmark smark;
11871 setstackmark(&smark);
11874 while ((n = parsecmd(0)) != NODE_EOF) {
11876 popstackmark(&smark);
11889 * The eval command.
11891 static int FAST_FUNC
11892 evalcmd(int argc UNUSED_PARAM, char **argv)
11901 STARTSTACKSTR(concat);
11903 concat = stack_putstr(p, concat);
11907 STPUTC(' ', concat);
11909 STPUTC('\0', concat);
11910 p = grabstackstr(concat);
11912 evalstring(p, ~SKIPEVAL);
11919 * Read and execute commands.
11920 * "Top" is nonzero for the top level command loop;
11921 * it turns on prompting if the shell is interactive.
11927 struct stackmark smark;
11931 TRACE(("cmdloop(%d) called\n", top));
11935 setstackmark(&smark);
11938 showjobs(stderr, SHOW_CHANGED);
11941 if (iflag && top) {
11943 #if ENABLE_ASH_MAIL
11947 n = parsecmd(inter);
11949 if (DEBUG > 2 && debug && (n != NODE_EOF))
11952 if (n == NODE_EOF) {
11953 if (!top || numeof >= 50)
11955 if (!stoppedjobs()) {
11958 out2str("\nUse \"exit\" to leave shell.\n");
11961 } else if (nflag == 0) {
11962 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11967 popstackmark(&smark);
11972 return skip & SKIPEVAL;
11979 * Take commands from a file. To be compatible we should do a path
11980 * search for the file, which is necessary to find sub-commands.
11983 find_dot_file(char *name)
11986 const char *path = pathval();
11989 /* don't try this for absolute or relative paths */
11990 if (strchr(name, '/'))
11993 /* IIRC standards do not say whether . is to be searched.
11994 * And it is even smaller this way, making it unconditional for now:
11996 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12001 while ((fullname = path_advance(&path, name)) != NULL) {
12003 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12005 * Don't bother freeing here, since it will
12006 * be freed by the caller.
12010 if (fullname != name)
12011 stunalloc(fullname);
12014 /* not found in the PATH */
12015 ash_msg_and_raise_error("%s: not found", name);
12019 static int FAST_FUNC
12020 dotcmd(int argc, char **argv)
12022 struct strlist *sp;
12023 volatile struct shparam saveparam;
12026 for (sp = cmdenviron; sp; sp = sp->next)
12027 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12029 if (argv[1]) { /* That's what SVR2 does */
12030 char *fullname = find_dot_file(argv[1]);
12033 if (argc) { /* argc > 0, argv[0] != NULL */
12034 saveparam = shellparam;
12035 shellparam.malloced = 0;
12036 shellparam.nparam = argc;
12037 shellparam.p = argv;
12040 setinputfile(fullname, INPUT_PUSH_FILE);
12041 commandname = fullname;
12046 freeparam(&shellparam);
12047 shellparam = saveparam;
12049 status = exitstatus;
12054 static int FAST_FUNC
12055 exitcmd(int argc UNUSED_PARAM, char **argv)
12060 exitstatus = number(argv[1]);
12061 raise_exception(EXEXIT);
12066 * Read a file containing shell functions.
12069 readcmdfile(char *name)
12071 setinputfile(name, INPUT_PUSH_FILE);
12077 /* ============ find_command inplementation */
12080 * Resolve a command name. If you change this routine, you may have to
12081 * change the shellexec routine as well.
12084 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12086 struct tblentry *cmdp;
12093 struct builtincmd *bcmd;
12095 /* If name contains a slash, don't use PATH or hash table */
12096 if (strchr(name, '/') != NULL) {
12097 entry->u.index = -1;
12098 if (act & DO_ABS) {
12099 while (stat(name, &statb) < 0) {
12101 if (errno == EINTR)
12104 entry->cmdtype = CMDUNKNOWN;
12108 entry->cmdtype = CMDNORMAL;
12112 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12114 updatetbl = (path == pathval());
12117 if (strstr(path, "%builtin") != NULL)
12118 act |= DO_ALTBLTIN;
12121 /* If name is in the table, check answer will be ok */
12122 cmdp = cmdlookup(name, 0);
12123 if (cmdp != NULL) {
12126 switch (cmdp->cmdtype) {
12144 } else if (cmdp->rehash == 0)
12145 /* if not invalidated by cd, we're done */
12149 /* If %builtin not in path, check for builtin next */
12150 bcmd = find_builtin(name);
12152 if (IS_BUILTIN_REGULAR(bcmd))
12153 goto builtin_success;
12154 if (act & DO_ALTPATH) {
12155 if (!(act & DO_ALTBLTIN))
12156 goto builtin_success;
12157 } else if (builtinloc <= 0) {
12158 goto builtin_success;
12162 #if ENABLE_FEATURE_SH_STANDALONE
12164 int applet_no = find_applet_by_name(name);
12165 if (applet_no >= 0) {
12166 entry->cmdtype = CMDNORMAL;
12167 entry->u.index = -2 - applet_no;
12173 /* We have to search path. */
12174 prev = -1; /* where to start */
12175 if (cmdp && cmdp->rehash) { /* doing a rehash */
12176 if (cmdp->cmdtype == CMDBUILTIN)
12179 prev = cmdp->param.index;
12185 while ((fullname = path_advance(&path, name)) != NULL) {
12186 stunalloc(fullname);
12187 /* NB: code below will still use fullname
12188 * despite it being "unallocated" */
12191 if (prefix(pathopt, "builtin")) {
12193 goto builtin_success;
12196 if ((act & DO_NOFUNC)
12197 || !prefix(pathopt, "func")
12198 ) { /* ignore unimplemented options */
12202 /* if rehash, don't redo absolute path names */
12203 if (fullname[0] == '/' && idx <= prev) {
12206 TRACE(("searchexec \"%s\": no change\n", name));
12209 while (stat(fullname, &statb) < 0) {
12211 if (errno == EINTR)
12214 if (errno != ENOENT && errno != ENOTDIR)
12218 e = EACCES; /* if we fail, this will be the error */
12219 if (!S_ISREG(statb.st_mode))
12221 if (pathopt) { /* this is a %func directory */
12222 stalloc(strlen(fullname) + 1);
12223 /* NB: stalloc will return space pointed by fullname
12224 * (because we don't have any intervening allocations
12225 * between stunalloc above and this stalloc) */
12226 readcmdfile(fullname);
12227 cmdp = cmdlookup(name, 0);
12228 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12229 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12230 stunalloc(fullname);
12233 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12235 entry->cmdtype = CMDNORMAL;
12236 entry->u.index = idx;
12240 cmdp = cmdlookup(name, 1);
12241 cmdp->cmdtype = CMDNORMAL;
12242 cmdp->param.index = idx;
12247 /* We failed. If there was an entry for this command, delete it */
12248 if (cmdp && updatetbl)
12249 delete_cmd_entry();
12251 ash_msg("%s: %s", name, errmsg(e, "not found"));
12252 entry->cmdtype = CMDUNKNOWN;
12257 entry->cmdtype = CMDBUILTIN;
12258 entry->u.cmd = bcmd;
12262 cmdp = cmdlookup(name, 1);
12263 cmdp->cmdtype = CMDBUILTIN;
12264 cmdp->param.cmd = bcmd;
12268 entry->cmdtype = cmdp->cmdtype;
12269 entry->u = cmdp->param;
12273 /* ============ trap.c */
12276 * The trap builtin.
12278 static int FAST_FUNC
12279 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12288 for (signo = 0; signo < NSIG; signo++) {
12289 char *tr = trap_ptr[signo];
12291 /* note: bash adds "SIG", but only if invoked
12292 * as "bash". If called as "sh", or if set -o posix,
12293 * then it prints short signal names.
12294 * We are printing short names: */
12295 out1fmt("trap -- %s %s\n",
12297 get_signame(signo));
12298 /* trap_ptr != trap only if we are in special-cased `trap` code.
12299 * In this case, we will exit very soon, no need to free(). */
12300 /* if (trap_ptr != trap && tp[0]) */
12305 if (trap_ptr != trap) {
12317 signo = get_signum(*ap);
12319 ash_msg_and_raise_error("%s: bad trap", *ap);
12322 if (LONE_DASH(action))
12325 action = ckstrdup(action);
12328 trap[signo] = action;
12338 /* ============ Builtins */
12340 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12342 * Lists available builtins
12344 static int FAST_FUNC
12345 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12351 "Built-in commands:\n"
12352 "------------------\n");
12353 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12354 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12355 builtintab[i].name + 1);
12361 #if ENABLE_FEATURE_SH_STANDALONE
12363 const char *a = applet_names;
12365 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12370 a += strlen(a) + 1;
12375 return EXIT_SUCCESS;
12377 #endif /* FEATURE_SH_EXTRA_QUIET */
12380 * The export and readonly commands.
12382 static int FAST_FUNC
12383 exportcmd(int argc UNUSED_PARAM, char **argv)
12389 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12391 if (nextopt("p") != 'p') {
12396 p = strchr(name, '=');
12400 vp = *findvar(hashvar(name), name);
12406 setvar(name, p, flag);
12407 } while ((name = *++aptr) != NULL);
12411 showvars(argv[0], flag, 0);
12416 * Delete a function if it exists.
12419 unsetfunc(const char *name)
12421 struct tblentry *cmdp;
12423 cmdp = cmdlookup(name, 0);
12424 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12425 delete_cmd_entry();
12429 * The unset builtin command. We unset the function before we unset the
12430 * variable to allow a function to be unset when there is a readonly variable
12431 * with the same name.
12433 static int FAST_FUNC
12434 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12441 while ((i = nextopt("vf")) != '\0') {
12445 for (ap = argptr; *ap; ap++) {
12461 #include <sys/times.h>
12463 static const unsigned char timescmd_str[] ALIGN1 = {
12464 ' ', offsetof(struct tms, tms_utime),
12465 '\n', offsetof(struct tms, tms_stime),
12466 ' ', offsetof(struct tms, tms_cutime),
12467 '\n', offsetof(struct tms, tms_cstime),
12471 static int FAST_FUNC
12472 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12474 long clk_tck, s, t;
12475 const unsigned char *p;
12478 clk_tck = sysconf(_SC_CLK_TCK);
12483 t = *(clock_t *)(((char *) &buf) + p[1]);
12485 out1fmt("%ldm%ld.%.3lds%c",
12487 ((t - s * clk_tck) * 1000) / clk_tck,
12489 } while (*(p += 2));
12494 #if ENABLE_SH_MATH_SUPPORT
12496 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12497 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12499 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12501 static int FAST_FUNC
12502 letcmd(int argc UNUSED_PARAM, char **argv)
12508 ash_msg_and_raise_error("expression expected");
12510 i = ash_arith(*argv);
12515 #endif /* SH_MATH_SUPPORT */
12518 /* ============ miscbltin.c
12520 * Miscellaneous builtins.
12525 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
12526 typedef enum __rlimit_resource rlim_t;
12530 * The read builtin. Options:
12531 * -r Do not interpret '\' specially
12532 * -s Turn off echo (tty only)
12533 * -n NCHARS Read NCHARS max
12534 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12535 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12536 * -u FD Read from given FD instead of fd 0
12537 * This uses unbuffered input, which may be avoidable in some cases.
12538 * TODO: bash also has:
12539 * -a ARRAY Read into array[0],[1],etc
12540 * -d DELIM End on DELIM char, not newline
12541 * -e Use line editing (tty only)
12543 static int FAST_FUNC
12544 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12546 char *opt_n = NULL;
12547 char *opt_p = NULL;
12548 char *opt_t = NULL;
12549 char *opt_u = NULL;
12550 int read_flags = 0;
12554 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12563 read_flags |= BUILTIN_READ_SILENT;
12569 read_flags |= BUILTIN_READ_RAW;
12579 r = shell_builtin_read(setvar2,
12581 bltinlookup("IFS"), /* can be NULL */
12589 if ((uintptr_t)r > 1)
12590 ash_msg_and_raise_error(r);
12592 return (uintptr_t)r;
12595 static int FAST_FUNC
12596 umaskcmd(int argc UNUSED_PARAM, char **argv)
12598 static const char permuser[3] ALIGN1 = "ugo";
12599 static const char permmode[3] ALIGN1 = "rwx";
12600 static const short permmask[] ALIGN2 = {
12601 S_IRUSR, S_IWUSR, S_IXUSR,
12602 S_IRGRP, S_IWGRP, S_IXGRP,
12603 S_IROTH, S_IWOTH, S_IXOTH
12606 /* TODO: use bb_parse_mode() instead */
12611 int symbolic_mode = 0;
12613 while (nextopt("S") != '\0') {
12624 if (symbolic_mode) {
12628 for (i = 0; i < 3; i++) {
12631 *p++ = permuser[i];
12633 for (j = 0; j < 3; j++) {
12634 if ((mask & permmask[3 * i + j]) == 0) {
12635 *p++ = permmode[j];
12643 out1fmt("%.4o\n", mask);
12646 if (isdigit((unsigned char) *ap)) {
12649 if (*ap >= '8' || *ap < '0')
12650 ash_msg_and_raise_error(msg_illnum, argv[1]);
12651 mask = (mask << 3) + (*ap - '0');
12652 } while (*++ap != '\0');
12655 mask = ~mask & 0777;
12656 if (!bb_parse_mode(ap, &mask)) {
12657 ash_msg_and_raise_error("illegal mode: %s", ap);
12659 umask(~mask & 0777);
12665 static int FAST_FUNC
12666 ulimitcmd(int argc UNUSED_PARAM, char **argv)
12668 return shell_builtin_ulimit(argv);
12671 /* ============ main() and helpers */
12674 * Called to exit the shell.
12676 static void exitshell(void) NORETURN;
12684 status = exitstatus;
12685 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12686 if (setjmp(loc.loc)) {
12687 if (exception_type == EXEXIT)
12688 /* dash bug: it just does _exit(exitstatus) here
12689 * but we have to do setjobctl(0) first!
12690 * (bug is still not fixed in dash-0.5.3 - if you run dash
12691 * under Midnight Commander, on exit from dash MC is backgrounded) */
12692 status = exitstatus;
12695 exception_handler = &loc;
12702 flush_stdout_stderr();
12712 /* from input.c: */
12713 basepf.next_to_pgetc = basepf.buf = basebuf;
12716 signal(SIGCHLD, SIG_DFL);
12717 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12718 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12720 signal(SIGHUP, SIG_DFL);
12726 struct stat st1, st2;
12729 for (envp = environ; envp && *envp; envp++) {
12730 if (strchr(*envp, '=')) {
12731 setvareq(*envp, VEXPORT|VTEXTFIXED);
12735 setvar("PPID", utoa(getppid()), 0);
12737 p = lookupvar("PWD");
12739 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12740 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12747 * Process the shell command line arguments.
12750 procargs(char **argv)
12753 const char *xminusc;
12758 /* if (xargv[0]) - mmm, this is always true! */
12760 for (i = 0; i < NOPTS; i++)
12764 /* it already printed err message */
12765 raise_exception(EXERROR);
12769 if (*xargv == NULL) {
12771 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12774 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12778 for (i = 0; i < NOPTS; i++)
12779 if (optlist[i] == 2)
12784 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12789 } else if (!sflag) {
12790 setinputfile(*xargv, 0);
12793 commandname = arg0;
12796 shellparam.p = xargv;
12797 #if ENABLE_ASH_GETOPTS
12798 shellparam.optind = 1;
12799 shellparam.optoff = -1;
12801 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
12803 shellparam.nparam++;
12810 * Read /etc/profile or .profile.
12813 read_profile(const char *name)
12817 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12826 * This routine is called when an error or an interrupt occurs in an
12827 * interactive shell and control is returned to the main command loop.
12835 /* from input.c: */
12836 g_parsefile->left_in_buffer = 0;
12837 g_parsefile->left_in_line = 0; /* clear input buffer */
12839 /* from parser.c: */
12842 /* from redir.c: */
12843 clearredir(/*drop:*/ 0);
12847 static short profile_buf[16384];
12848 extern int etext();
12852 * Main routine. We initialize things, parse the arguments, execute
12853 * profiles if we're a login shell, and then call cmdloop to execute
12854 * commands. The setjmp call sets up the location to jump to when an
12855 * exception occurs. When an exception occurs the variable "state"
12856 * is used to figure out how far we had gotten.
12858 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
12859 int ash_main(int argc UNUSED_PARAM, char **argv)
12861 const char *shinit;
12862 volatile smallint state;
12863 struct jmploc jmploc;
12864 struct stackmark smark;
12866 /* Initialize global data */
12870 #if ENABLE_ASH_ALIAS
12876 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12879 #if ENABLE_FEATURE_EDITING
12880 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12883 if (setjmp(jmploc.loc)) {
12889 e = exception_type;
12893 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12896 outcslow('\n', stderr);
12898 popstackmark(&smark);
12899 FORCE_INT_ON; /* enable interrupts */
12908 exception_handler = &jmploc;
12911 TRACE(("Shell args: "));
12912 trace_puts_args(argv);
12914 rootpid = getpid();
12917 setstackmark(&smark);
12920 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
12922 const char *hp = lookupvar("HISTFILE");
12925 hp = lookupvar("HOME");
12927 char *defhp = concat_path_file(hp, ".ash_history");
12928 setvar("HISTFILE", defhp, 0);
12934 if (/* argv[0] && */ argv[0][0] == '-')
12938 read_profile("/etc/profile");
12941 read_profile(".profile");
12947 getuid() == geteuid() && getgid() == getegid() &&
12951 shinit = lookupvar("ENV");
12952 if (shinit != NULL && *shinit != '\0') {
12953 read_profile(shinit);
12959 /* evalstring pushes parsefile stack.
12960 * Ensure we don't falsely claim that 0 (stdin)
12961 * is one of stacked source fds.
12962 * Testcase: ash -c 'exec 1>&0' must not complain. */
12964 g_parsefile->fd = -1;
12965 evalstring(minusc, 0);
12968 if (sflag || minusc == NULL) {
12969 #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
12971 const char *hp = lookupvar("HISTFILE");
12973 line_input_state->hist_file = hp;
12976 state4: /* XXX ??? - why isn't this before the "if" statement */
12984 extern void _mcleanup(void);
12994 * Copyright (c) 1989, 1991, 1993, 1994
12995 * The Regents of the University of California. All rights reserved.
12997 * This code is derived from software contributed to Berkeley by
12998 * Kenneth Almquist.
13000 * Redistribution and use in source and binary forms, with or without
13001 * modification, are permitted provided that the following conditions
13003 * 1. Redistributions of source code must retain the above copyright
13004 * notice, this list of conditions and the following disclaimer.
13005 * 2. Redistributions in binary form must reproduce the above copyright
13006 * notice, this list of conditions and the following disclaimer in the
13007 * documentation and/or other materials provided with the distribution.
13008 * 3. Neither the name of the University nor the names of its contributors
13009 * may be used to endorse or promote products derived from this software
13010 * without specific prior written permission.
13012 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13013 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13014 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13015 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13016 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13017 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13018 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13019 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13020 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13021 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF