1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
20 * The following should be set to reflect the type of system you have:
21 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22 * define SYSV if you are running under System V.
23 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24 * define DEBUG=2 to compile in and turn on debugging.
26 * When debugging is on, debugging info will be written to ./trace and
27 * a quit signal will generate a core dump.
30 /* Tweak debug output verbosity here */
37 #define JOBS ENABLE_ASH_JOB_CONTROL
45 #include "busybox.h" /* for applet_names */
50 #include "shell_common.h"
51 #include "builtin_read.h"
52 #include "builtin_ulimit.h"
54 #if ENABLE_ASH_RANDOM_SUPPORT
57 # define CLEAR_RANDOM_T(rnd) ((void)0)
60 #define SKIP_definitions 1
61 #include "applet_tables.h"
62 #undef SKIP_definitions
64 /* STANDALONE does not make sense, and won't compile */
65 # undef CONFIG_FEATURE_SH_STANDALONE
66 # undef ENABLE_FEATURE_SH_STANDALONE
67 # undef IF_FEATURE_SH_STANDALONE
68 # undef IF_NOT_FEATURE_SH_STANDALONE
69 # define ENABLE_FEATURE_SH_STANDALONE 0
70 # define IF_FEATURE_SH_STANDALONE(...)
71 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
75 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
79 # error "Do not even bother, ash will not run on NOMMU machine"
83 /* ============ Hash table sizes. Configurable. */
87 #define CMDTABLESIZE 31 /* should be prime */
90 /* ============ Shell options */
92 static const char *const optletters_optnames[] = {
107 #if ENABLE_ASH_BASH_COMPAT
116 #define optletters(n) optletters_optnames[n][0]
117 #define optnames(n) (optletters_optnames[n] + 1)
119 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
122 /* ============ Misc data */
124 static const char homestr[] ALIGN1 = "HOME";
125 static const char snlfmt[] ALIGN1 = "%s\n";
126 static const char msg_illnum[] ALIGN1 = "Illegal number: %s";
129 * We enclose jmp_buf in a structure so that we can declare pointers to
130 * jump locations. The global variable handler contains the location to
131 * jump to when an exception occurs, and the global variable exception_type
132 * contains a code identifying the exception. To implement nested
133 * exception handlers, the user should save the value of handler on entry
134 * to an inner scope, set handler to point to a jmploc structure for the
135 * inner scope, and restore handler on exit from the scope.
141 struct globals_misc {
142 /* pid of main shell */
144 /* shell level: 0 for the main shell, 1 for its children, and so on */
146 #define rootshell (!shlvl)
147 char *minusc; /* argument to -c option */
149 char *curdir; // = nullstr; /* current working directory */
150 char *physdir; // = nullstr; /* physical working directory */
152 char *arg0; /* value of $0 */
154 struct jmploc *exception_handler;
156 volatile int suppress_int; /* counter */
157 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
158 /* last pending signal */
159 volatile /*sig_atomic_t*/ smallint pending_sig;
160 smallint exception_type; /* kind of exception (0..5) */
162 #define EXINT 0 /* SIGINT received */
163 #define EXERROR 1 /* a generic error */
164 #define EXSHELLPROC 2 /* execute a shell procedure */
165 #define EXEXEC 3 /* command execution failed */
166 #define EXEXIT 4 /* exit the shell */
167 #define EXSIG 5 /* trapped signal in wait(1) */
170 char nullstr[1]; /* zero length string */
173 #define eflag optlist[0]
174 #define fflag optlist[1]
175 #define Iflag optlist[2]
176 #define iflag optlist[3]
177 #define mflag optlist[4]
178 #define nflag optlist[5]
179 #define sflag optlist[6]
180 #define xflag optlist[7]
181 #define vflag optlist[8]
182 #define Cflag optlist[9]
183 #define aflag optlist[10]
184 #define bflag optlist[11]
185 #define uflag optlist[12]
186 #define viflag optlist[13]
187 #if ENABLE_ASH_BASH_COMPAT
188 # define pipefail optlist[14]
193 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
194 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
197 /* trap handler commands */
199 * Sigmode records the current value of the signal handlers for the various
200 * modes. A value of zero means that the current handler is not known.
201 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
203 char sigmode[NSIG - 1];
204 #define S_DFL 1 /* default signal handling (SIG_DFL) */
205 #define S_CATCH 2 /* signal is caught */
206 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
207 #define S_HARD_IGN 4 /* signal is ignored permenantly */
209 /* indicates specified signal received */
210 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
212 char **trap_ptr; /* used only by "trap hack" */
214 /* Rarely referenced stuff */
215 #if ENABLE_ASH_RANDOM_SUPPORT
218 pid_t backgndpid; /* pid of last background process */
219 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
221 extern struct globals_misc *const ash_ptr_to_globals_misc;
222 #define G_misc (*ash_ptr_to_globals_misc)
223 #define rootpid (G_misc.rootpid )
224 #define shlvl (G_misc.shlvl )
225 #define minusc (G_misc.minusc )
226 #define curdir (G_misc.curdir )
227 #define physdir (G_misc.physdir )
228 #define arg0 (G_misc.arg0 )
229 #define exception_handler (G_misc.exception_handler)
230 #define exception_type (G_misc.exception_type )
231 #define suppress_int (G_misc.suppress_int )
232 #define pending_int (G_misc.pending_int )
233 #define pending_sig (G_misc.pending_sig )
234 #define isloginsh (G_misc.isloginsh )
235 #define nullstr (G_misc.nullstr )
236 #define optlist (G_misc.optlist )
237 #define sigmode (G_misc.sigmode )
238 #define gotsig (G_misc.gotsig )
239 #define trap (G_misc.trap )
240 #define trap_ptr (G_misc.trap_ptr )
241 #define random_gen (G_misc.random_gen )
242 #define backgndpid (G_misc.backgndpid )
243 #define job_warning (G_misc.job_warning)
244 #define INIT_G_misc() do { \
245 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
253 /* ============ DEBUG */
255 static void trace_printf(const char *fmt, ...);
256 static void trace_vprintf(const char *fmt, va_list va);
257 # define TRACE(param) trace_printf param
258 # define TRACEV(param) trace_vprintf param
259 # define close(fd) do { \
261 if (close(dfd) < 0) \
262 bb_error_msg("bug on %d: closing %d(0x%x)", \
263 __LINE__, dfd, dfd); \
266 # define TRACE(param)
267 # define TRACEV(param)
271 /* ============ Utility functions */
272 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
274 static int isdigit_str9(const char *str)
276 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
277 while (--maxlen && isdigit(*str))
279 return (*str == '\0');
283 /* ============ Interrupts / exceptions */
285 * These macros allow the user to suspend the handling of interrupt signals
286 * over a period of time. This is similar to SIGHOLD or to sigblock, but
287 * much more efficient and portable. (But hacking the kernel is so much
288 * more fun than worrying about efficiency and portability. :-))
290 #define INT_OFF do { \
296 * Called to raise an exception. Since C doesn't include exceptions, we
297 * just do a longjmp to the exception handler. The type of exception is
298 * stored in the global variable "exception_type".
300 static void raise_exception(int) NORETURN;
302 raise_exception(int e)
305 if (exception_handler == NULL)
310 longjmp(exception_handler->loc, 1);
313 #define raise_exception(e) do { \
314 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
315 raise_exception(e); \
320 * Called from trap.c when a SIGINT is received. (If the user specifies
321 * that SIGINT is to be trapped or ignored using the trap builtin, then
322 * this routine is not called.) Suppressint is nonzero when interrupts
323 * are held using the INT_OFF macro. (The test for iflag is just
324 * defensive programming.)
326 static void raise_interrupt(void) NORETURN;
328 raise_interrupt(void)
333 /* Signal is not automatically unmasked after it is raised,
334 * do it ourself - unmask all signals */
335 sigprocmask_allsigs(SIG_UNBLOCK);
336 /* pending_sig = 0; - now done in onsig() */
339 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
340 if (!(rootshell && iflag)) {
341 /* Kill ourself with SIGINT */
342 signal(SIGINT, SIG_DFL);
347 raise_exception(ex_type);
351 #define raise_interrupt() do { \
352 TRACE(("raising interrupt on line %d\n", __LINE__)); \
357 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
361 if (--suppress_int == 0 && pending_int) {
365 #define INT_ON int_on()
366 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
374 #define FORCE_INT_ON force_int_on()
376 #define SAVE_INT(v) ((v) = suppress_int)
378 #define RESTORE_INT(v) do { \
380 suppress_int = (v); \
381 if (suppress_int == 0 && pending_int) \
386 /* ============ Stdout/stderr output */
389 outstr(const char *p, FILE *file)
397 flush_stdout_stderr(void)
405 outcslow(int c, FILE *dest)
413 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
415 out1fmt(const char *fmt, ...)
422 r = vprintf(fmt, ap);
428 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
430 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
437 ret = vsnprintf(outbuf, length, fmt, ap);
444 out1str(const char *p)
450 out2str(const char *p)
453 flush_stdout_stderr();
457 /* ============ Parser structures */
459 /* control characters in argument strings */
460 #define CTL_FIRST CTLESC
461 #define CTLESC ((unsigned char)'\201') /* escape next character */
462 #define CTLVAR ((unsigned char)'\202') /* variable defn */
463 #define CTLENDVAR ((unsigned char)'\203')
464 #define CTLBACKQ ((unsigned char)'\204')
465 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
466 /* CTLBACKQ | CTLQUOTE == '\205' */
467 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
468 #define CTLENDARI ((unsigned char)'\207')
469 #define CTLQUOTEMARK ((unsigned char)'\210')
470 #define CTL_LAST CTLQUOTEMARK
472 /* variable substitution byte (follows CTLVAR) */
473 #define VSTYPE 0x0f /* type of variable substitution */
474 #define VSNUL 0x10 /* colon--treat the empty string as unset */
475 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
477 /* values of VSTYPE field */
478 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
479 #define VSMINUS 0x2 /* ${var-text} */
480 #define VSPLUS 0x3 /* ${var+text} */
481 #define VSQUESTION 0x4 /* ${var?message} */
482 #define VSASSIGN 0x5 /* ${var=text} */
483 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
484 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
485 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
486 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
487 #define VSLENGTH 0xa /* ${#var} */
488 #if ENABLE_ASH_BASH_COMPAT
489 #define VSSUBSTR 0xc /* ${var:position:length} */
490 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
491 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
494 static const char dolatstr[] ALIGN1 = {
495 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
515 #if ENABLE_ASH_BASH_COMPAT
532 smallint type; /* Nxxxx */
535 union node *redirect;
540 smallint pipe_backgnd;
541 struct nodelist *cmdlist;
547 union node *redirect;
560 union node *elsepart;
587 struct nodelist *backquote;
590 /* nfile and ndup layout must match!
591 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
592 * that it is actually NTO2 (>&file), and change its type.
609 char *_unused_expfname;
628 struct nredir nredir;
629 struct nbinary nbinary;
633 struct nclist nclist;
642 * NODE_EOF is returned by parsecmd when it encounters an end of file.
643 * It must be distinct from NULL.
645 #define NODE_EOF ((union node *) -1L)
648 struct nodelist *next;
661 freefunc(struct funcnode *f)
663 if (f && --f->count < 0)
668 /* ============ Debugging output */
672 static FILE *tracefile;
675 trace_printf(const char *fmt, ...)
682 fprintf(tracefile, "%u ", (int) time(NULL));
684 fprintf(tracefile, "[%u] ", (int) getpid());
686 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
688 vfprintf(tracefile, fmt, va);
693 trace_vprintf(const char *fmt, va_list va)
698 fprintf(tracefile, "%u ", (int) time(NULL));
700 fprintf(tracefile, "[%u] ", (int) getpid());
702 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
703 vfprintf(tracefile, fmt, va);
707 trace_puts(const char *s)
715 trace_puts_quoted(char *s)
722 putc('"', tracefile);
723 for (p = s; *p; p++) {
724 switch ((unsigned char)*p) {
725 case '\n': c = 'n'; goto backslash;
726 case '\t': c = 't'; goto backslash;
727 case '\r': c = 'r'; goto backslash;
728 case '\"': c = '\"'; goto backslash;
729 case '\\': c = '\\'; goto backslash;
730 case CTLESC: c = 'e'; goto backslash;
731 case CTLVAR: c = 'v'; goto backslash;
732 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
733 case CTLBACKQ: c = 'q'; goto backslash;
734 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
736 putc('\\', tracefile);
740 if (*p >= ' ' && *p <= '~')
743 putc('\\', tracefile);
744 putc((*p >> 6) & 03, tracefile);
745 putc((*p >> 3) & 07, tracefile);
746 putc(*p & 07, tracefile);
751 putc('"', tracefile);
755 trace_puts_args(char **ap)
762 trace_puts_quoted(*ap);
764 putc('\n', tracefile);
767 putc(' ', tracefile);
782 /* leave open because libedit might be using it */
785 strcpy(s, "./trace");
787 if (!freopen(s, "a", tracefile)) {
788 fprintf(stderr, "Can't re-open %s\n", s);
793 tracefile = fopen(s, "a");
794 if (tracefile == NULL) {
795 fprintf(stderr, "Can't open %s\n", s);
801 flags = fcntl(fileno(tracefile), F_GETFL);
803 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
805 setlinebuf(tracefile);
806 fputs("\nTracing started.\n", tracefile);
810 indent(int amount, char *pfx, FILE *fp)
814 for (i = 0; i < amount; i++) {
815 if (pfx && i == amount - 1)
821 /* little circular references here... */
822 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
825 sharg(union node *arg, FILE *fp)
828 struct nodelist *bqlist;
829 unsigned char subtype;
831 if (arg->type != NARG) {
832 out1fmt("<node type %d>\n", arg->type);
835 bqlist = arg->narg.backquote;
836 for (p = arg->narg.text; *p; p++) {
837 switch ((unsigned char)*p) {
845 if (subtype == VSLENGTH)
854 switch (subtype & VSTYPE) {
887 out1fmt("<subtype %d>", subtype);
894 case CTLBACKQ|CTLQUOTE:
897 shtree(bqlist->n, -1, NULL, fp);
908 shcmd(union node *cmd, FILE *fp)
916 for (np = cmd->ncmd.args; np; np = np->narg.next) {
922 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
926 switch (np->nfile.type) {
927 case NTO: s = ">>"+1; dftfd = 1; break;
928 case NCLOBBER: s = ">|"; dftfd = 1; break;
929 case NAPPEND: s = ">>"; dftfd = 1; break;
930 #if ENABLE_ASH_BASH_COMPAT
933 case NTOFD: s = ">&"; dftfd = 1; break;
934 case NFROM: s = "<"; break;
935 case NFROMFD: s = "<&"; break;
936 case NFROMTO: s = "<>"; break;
937 default: s = "*error*"; break;
939 if (np->nfile.fd != dftfd)
940 fprintf(fp, "%d", np->nfile.fd);
942 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
943 fprintf(fp, "%d", np->ndup.dupfd);
945 sharg(np->nfile.fname, fp);
952 shtree(union node *n, int ind, char *pfx, FILE *fp)
960 indent(ind, pfx, fp);
977 shtree(n->nbinary.ch1, ind, NULL, fp);
980 shtree(n->nbinary.ch2, ind, NULL, fp);
988 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
989 shtree(lp->n, 0, NULL, fp);
993 if (n->npipe.pipe_backgnd)
999 fprintf(fp, "<node type %d>", n->type);
1007 showtree(union node *n)
1009 trace_puts("showtree called\n");
1010 shtree(n, 1, NULL, stderr);
1016 /* ============ Parser data */
1019 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1022 struct strlist *next;
1029 struct strpush *prev; /* preceding string on stack */
1031 int prev_left_in_line;
1032 #if ENABLE_ASH_ALIAS
1033 struct alias *ap; /* if push was associated with an alias */
1035 char *string; /* remember the string since it may change */
1039 struct parsefile *prev; /* preceding file on stack */
1040 int linno; /* current line */
1041 int fd; /* file descriptor (or -1 if string) */
1042 int left_in_line; /* number of chars left in this line */
1043 int left_in_buffer; /* number of chars left in this buffer past the line */
1044 char *next_to_pgetc; /* next char in buffer */
1045 char *buf; /* input buffer */
1046 struct strpush *strpush; /* for pushing strings at this level */
1047 struct strpush basestrpush; /* so pushing one is fast */
1050 static struct parsefile basepf; /* top level input file */
1051 static struct parsefile *g_parsefile = &basepf; /* current input file */
1052 static int startlinno; /* line # where last token started */
1053 static char *commandname; /* currently executing command */
1054 static struct strlist *cmdenviron; /* environment for builtin command */
1055 static uint8_t exitstatus; /* exit status of last command */
1058 /* ============ Message printing */
1061 ash_vmsg(const char *msg, va_list ap)
1063 fprintf(stderr, "%s: ", arg0);
1065 if (strcmp(arg0, commandname))
1066 fprintf(stderr, "%s: ", commandname);
1067 if (!iflag || g_parsefile->fd)
1068 fprintf(stderr, "line %d: ", startlinno);
1070 vfprintf(stderr, msg, ap);
1071 outcslow('\n', stderr);
1075 * Exverror is called to raise the error exception. If the second argument
1076 * is not NULL then error prints an error message using printf style
1077 * formatting. It then raises the error exception.
1079 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1081 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1085 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1087 TRACE(("\") pid=%d\n", getpid()));
1089 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1094 flush_stdout_stderr();
1095 raise_exception(cond);
1099 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1101 ash_msg_and_raise_error(const char *msg, ...)
1106 ash_vmsg_and_raise(EXERROR, msg, ap);
1111 static void raise_error_syntax(const char *) NORETURN;
1113 raise_error_syntax(const char *msg)
1115 ash_msg_and_raise_error("syntax error: %s", msg);
1119 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1121 ash_msg_and_raise(int cond, const char *msg, ...)
1126 ash_vmsg_and_raise(cond, msg, ap);
1132 * error/warning routines for external builtins
1135 ash_msg(const char *fmt, ...)
1145 * Return a string describing an error. The returned string may be a
1146 * pointer to a static buffer that will be overwritten on the next call.
1147 * Action describes the operation that got the error.
1150 errmsg(int e, const char *em)
1152 if (e == ENOENT || e == ENOTDIR) {
1159 /* ============ Memory allocation */
1162 /* I consider these wrappers nearly useless:
1163 * ok, they return you to nearest exception handler, but
1164 * how much memory do you leak in the process, making
1165 * memory starvation worse?
1168 ckrealloc(void * p, size_t nbytes)
1170 p = realloc(p, nbytes);
1172 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1177 ckmalloc(size_t nbytes)
1179 return ckrealloc(NULL, nbytes);
1183 ckzalloc(size_t nbytes)
1185 return memset(ckmalloc(nbytes), 0, nbytes);
1189 ckstrdup(const char *s)
1191 char *p = strdup(s);
1193 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1197 /* Using bbox equivalents. They exit if out of memory */
1198 # define ckrealloc xrealloc
1199 # define ckmalloc xmalloc
1200 # define ckzalloc xzalloc
1201 # define ckstrdup xstrdup
1205 * It appears that grabstackstr() will barf with such alignments
1206 * because stalloc() will return a string allocated in a new stackblock.
1208 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1210 /* Most machines require the value returned from malloc to be aligned
1211 * in some way. The following macro will get this right
1212 * on many machines. */
1213 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1214 /* Minimum size of a block */
1215 MINSIZE = SHELL_ALIGN(504),
1218 struct stack_block {
1219 struct stack_block *prev;
1220 char space[MINSIZE];
1224 struct stack_block *stackp;
1227 struct stackmark *marknext;
1231 struct globals_memstack {
1232 struct stack_block *g_stackp; // = &stackbase;
1233 struct stackmark *markp;
1234 char *g_stacknxt; // = stackbase.space;
1235 char *sstrend; // = stackbase.space + MINSIZE;
1236 size_t g_stacknleft; // = MINSIZE;
1237 int herefd; // = -1;
1238 struct stack_block stackbase;
1240 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1241 #define G_memstack (*ash_ptr_to_globals_memstack)
1242 #define g_stackp (G_memstack.g_stackp )
1243 #define markp (G_memstack.markp )
1244 #define g_stacknxt (G_memstack.g_stacknxt )
1245 #define sstrend (G_memstack.sstrend )
1246 #define g_stacknleft (G_memstack.g_stacknleft)
1247 #define herefd (G_memstack.herefd )
1248 #define stackbase (G_memstack.stackbase )
1249 #define INIT_G_memstack() do { \
1250 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1252 g_stackp = &stackbase; \
1253 g_stacknxt = stackbase.space; \
1254 g_stacknleft = MINSIZE; \
1255 sstrend = stackbase.space + MINSIZE; \
1260 #define stackblock() ((void *)g_stacknxt)
1261 #define stackblocksize() g_stacknleft
1264 * Parse trees for commands are allocated in lifo order, so we use a stack
1265 * to make this more efficient, and also to avoid all sorts of exception
1266 * handling code to handle interrupts in the middle of a parse.
1268 * The size 504 was chosen because the Ultrix malloc handles that size
1272 stalloc(size_t nbytes)
1277 aligned = SHELL_ALIGN(nbytes);
1278 if (aligned > g_stacknleft) {
1281 struct stack_block *sp;
1283 blocksize = aligned;
1284 if (blocksize < MINSIZE)
1285 blocksize = MINSIZE;
1286 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1287 if (len < blocksize)
1288 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1291 sp->prev = g_stackp;
1292 g_stacknxt = sp->space;
1293 g_stacknleft = blocksize;
1294 sstrend = g_stacknxt + blocksize;
1299 g_stacknxt += aligned;
1300 g_stacknleft -= aligned;
1305 stzalloc(size_t nbytes)
1307 return memset(stalloc(nbytes), 0, nbytes);
1314 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1315 write(STDERR_FILENO, "stunalloc\n", 10);
1319 g_stacknleft += g_stacknxt - (char *)p;
1324 * Like strdup but works with the ash stack.
1327 ststrdup(const char *p)
1329 size_t len = strlen(p) + 1;
1330 return memcpy(stalloc(len), p, len);
1334 setstackmark(struct stackmark *mark)
1336 mark->stackp = g_stackp;
1337 mark->stacknxt = g_stacknxt;
1338 mark->stacknleft = g_stacknleft;
1339 mark->marknext = markp;
1344 popstackmark(struct stackmark *mark)
1346 struct stack_block *sp;
1352 markp = mark->marknext;
1353 while (g_stackp != mark->stackp) {
1355 g_stackp = sp->prev;
1358 g_stacknxt = mark->stacknxt;
1359 g_stacknleft = mark->stacknleft;
1360 sstrend = mark->stacknxt + mark->stacknleft;
1365 * When the parser reads in a string, it wants to stick the string on the
1366 * stack and only adjust the stack pointer when it knows how big the
1367 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1368 * of space on top of the stack and stackblocklen returns the length of
1369 * this block. Growstackblock will grow this space by at least one byte,
1370 * possibly moving it (like realloc). Grabstackblock actually allocates the
1371 * part of the block that has been used.
1374 growstackblock(void)
1378 newlen = g_stacknleft * 2;
1379 if (newlen < g_stacknleft)
1380 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1384 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1385 struct stack_block *oldstackp;
1386 struct stackmark *xmark;
1387 struct stack_block *sp;
1388 struct stack_block *prevstackp;
1392 oldstackp = g_stackp;
1394 prevstackp = sp->prev;
1395 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1396 sp = ckrealloc(sp, grosslen);
1397 sp->prev = prevstackp;
1399 g_stacknxt = sp->space;
1400 g_stacknleft = newlen;
1401 sstrend = sp->space + newlen;
1404 * Stack marks pointing to the start of the old block
1405 * must be relocated to point to the new block
1408 while (xmark != NULL && xmark->stackp == oldstackp) {
1409 xmark->stackp = g_stackp;
1410 xmark->stacknxt = g_stacknxt;
1411 xmark->stacknleft = g_stacknleft;
1412 xmark = xmark->marknext;
1416 char *oldspace = g_stacknxt;
1417 size_t oldlen = g_stacknleft;
1418 char *p = stalloc(newlen);
1420 /* free the space we just allocated */
1421 g_stacknxt = memcpy(p, oldspace, oldlen);
1422 g_stacknleft += newlen;
1427 grabstackblock(size_t len)
1429 len = SHELL_ALIGN(len);
1431 g_stacknleft -= len;
1435 * The following routines are somewhat easier to use than the above.
1436 * The user declares a variable of type STACKSTR, which may be declared
1437 * to be a register. The macro STARTSTACKSTR initializes things. Then
1438 * the user uses the macro STPUTC to add characters to the string. In
1439 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1440 * grown as necessary. When the user is done, she can just leave the
1441 * string there and refer to it using stackblock(). Or she can allocate
1442 * the space for it using grabstackstr(). If it is necessary to allow
1443 * someone else to use the stack temporarily and then continue to grow
1444 * the string, the user should use grabstack to allocate the space, and
1445 * then call ungrabstr(p) to return to the previous mode of operation.
1447 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1448 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1449 * is space for at least one character.
1454 size_t len = stackblocksize();
1455 if (herefd >= 0 && len >= 1024) {
1456 full_write(herefd, stackblock(), len);
1457 return stackblock();
1460 return (char *)stackblock() + len;
1464 * Called from CHECKSTRSPACE.
1467 makestrspace(size_t newlen, char *p)
1469 size_t len = p - g_stacknxt;
1470 size_t size = stackblocksize();
1475 size = stackblocksize();
1477 if (nleft >= newlen)
1481 return (char *)stackblock() + len;
1485 stack_nputstr(const char *s, size_t n, char *p)
1487 p = makestrspace(n, p);
1488 p = (char *)memcpy(p, s, n) + n;
1493 stack_putstr(const char *s, char *p)
1495 return stack_nputstr(s, strlen(s), p);
1499 _STPUTC(int c, char *p)
1507 #define STARTSTACKSTR(p) ((p) = stackblock())
1508 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1509 #define CHECKSTRSPACE(n, p) do { \
1512 size_t m = sstrend - q; \
1514 (p) = makestrspace(l, q); \
1516 #define USTPUTC(c, p) (*(p)++ = (c))
1517 #define STACKSTRNUL(p) do { \
1518 if ((p) == sstrend) \
1519 (p) = growstackstr(); \
1522 #define STUNPUTC(p) (--(p))
1523 #define STTOPC(p) ((p)[-1])
1524 #define STADJUST(amount, p) ((p) += (amount))
1526 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1527 #define ungrabstackstr(s, p) stunalloc(s)
1528 #define stackstrend() ((void *)sstrend)
1531 /* ============ String helpers */
1534 * prefix -- see if pfx is a prefix of string.
1537 prefix(const char *string, const char *pfx)
1540 if (*pfx++ != *string++)
1543 return (char *) string;
1547 * Check for a valid number. This should be elsewhere.
1550 is_number(const char *p)
1555 } while (*++p != '\0');
1560 * Convert a string of digits to an integer, printing an error message on
1564 number(const char *s)
1567 ash_msg_and_raise_error(msg_illnum, s);
1572 * Produce a possibly single quoted string suitable as input to the shell.
1573 * The return string is allocated on the stack.
1576 single_quote(const char *s)
1586 len = strchrnul(s, '\'') - s;
1588 q = p = makestrspace(len + 3, p);
1591 q = (char *)memcpy(q, s, len) + len;
1600 do len++; while (*++s == '\'');
1602 q = p = makestrspace(len + 3, p);
1605 q = (char *)memcpy(q, s - len, len) + len;
1613 return stackblock();
1617 /* ============ nextopt */
1619 static char **argptr; /* argument list for builtin commands */
1620 static char *optionarg; /* set by nextopt (like getopt) */
1621 static char *optptr; /* used by nextopt */
1624 * XXX - should get rid of. Have all builtins use getopt(3).
1625 * The library getopt must have the BSD extension static variable
1626 * "optreset", otherwise it can't be used within the shell safely.
1628 * Standard option processing (a la getopt) for builtin routines.
1629 * The only argument that is passed to nextopt is the option string;
1630 * the other arguments are unnecessary. It returns the character,
1631 * or '\0' on end of input.
1634 nextopt(const char *optstring)
1641 if (p == NULL || *p == '\0') {
1642 /* We ate entire "-param", take next one */
1648 if (*++p == '\0') /* just "-" ? */
1651 if (LONE_DASH(p)) /* "--" ? */
1653 /* p => next "-param" */
1655 /* p => some option char in the middle of a "-param" */
1657 for (q = optstring; *q != c;) {
1659 ash_msg_and_raise_error("illegal option -%c", c);
1667 ash_msg_and_raise_error("no arg for -%c option", c);
1677 /* ============ Shell variables */
1680 * The parsefile structure pointed to by the global variable parsefile
1681 * contains information about the current file being read.
1684 int nparam; /* # of positional parameters (without $0) */
1685 #if ENABLE_ASH_GETOPTS
1686 int optind; /* next parameter to be processed by getopts */
1687 int optoff; /* used by getopts */
1689 unsigned char malloced; /* if parameter list dynamically allocated */
1690 char **p; /* parameter list */
1694 * Free the list of positional parameters.
1697 freeparam(volatile struct shparam *param)
1699 if (param->malloced) {
1701 ap = ap1 = param->p;
1708 #if ENABLE_ASH_GETOPTS
1709 static void FAST_FUNC getoptsreset(const char *value);
1713 struct var *next; /* next entry in hash list */
1714 int flags; /* flags are defined above */
1715 const char *text; /* name=value */
1716 void (*func)(const char *) FAST_FUNC; /* function to be called when */
1717 /* the variable gets set/unset */
1721 struct localvar *next; /* next local variable in list */
1722 struct var *vp; /* the variable that was made local */
1723 int flags; /* saved flags */
1724 const char *text; /* saved text */
1728 #define VEXPORT 0x01 /* variable is exported */
1729 #define VREADONLY 0x02 /* variable cannot be modified */
1730 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1731 #define VTEXTFIXED 0x08 /* text is statically allocated */
1732 #define VSTACK 0x10 /* text is allocated on the stack */
1733 #define VUNSET 0x20 /* the variable is not set */
1734 #define VNOFUNC 0x40 /* don't call the callback function */
1735 #define VNOSET 0x80 /* do not set variable - just readonly test */
1736 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1737 #if ENABLE_ASH_RANDOM_SUPPORT
1738 # define VDYNAMIC 0x200 /* dynamic variable */
1744 /* Need to be before varinit_data[] */
1745 #if ENABLE_LOCALE_SUPPORT
1746 static void FAST_FUNC
1747 change_lc_all(const char *value)
1749 if (value && *value != '\0')
1750 setlocale(LC_ALL, value);
1752 static void FAST_FUNC
1753 change_lc_ctype(const char *value)
1755 if (value && *value != '\0')
1756 setlocale(LC_CTYPE, value);
1760 static void chkmail(void);
1761 static void changemail(const char *) FAST_FUNC;
1763 static void changepath(const char *) FAST_FUNC;
1764 #if ENABLE_ASH_RANDOM_SUPPORT
1765 static void change_random(const char *) FAST_FUNC;
1768 static const struct {
1771 void (*func)(const char *) FAST_FUNC;
1772 } varinit_data[] = {
1773 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1775 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1776 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1778 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1779 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1780 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1781 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1782 #if ENABLE_ASH_GETOPTS
1783 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1785 #if ENABLE_ASH_RANDOM_SUPPORT
1786 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
1788 #if ENABLE_LOCALE_SUPPORT
1789 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1790 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
1792 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1793 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
1799 struct globals_var {
1800 struct shparam shellparam; /* $@ current positional parameters */
1801 struct redirtab *redirlist;
1803 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1804 struct var *vartab[VTABSIZE];
1805 struct var varinit[ARRAY_SIZE(varinit_data)];
1807 extern struct globals_var *const ash_ptr_to_globals_var;
1808 #define G_var (*ash_ptr_to_globals_var)
1809 #define shellparam (G_var.shellparam )
1810 //#define redirlist (G_var.redirlist )
1811 #define g_nullredirs (G_var.g_nullredirs )
1812 #define preverrout_fd (G_var.preverrout_fd)
1813 #define vartab (G_var.vartab )
1814 #define varinit (G_var.varinit )
1815 #define INIT_G_var() do { \
1817 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1819 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1820 varinit[i].flags = varinit_data[i].flags; \
1821 varinit[i].text = varinit_data[i].text; \
1822 varinit[i].func = varinit_data[i].func; \
1826 #define vifs varinit[0]
1828 # define vmail (&vifs)[1]
1829 # define vmpath (&vmail)[1]
1830 # define vpath (&vmpath)[1]
1832 # define vpath (&vifs)[1]
1834 #define vps1 (&vpath)[1]
1835 #define vps2 (&vps1)[1]
1836 #define vps4 (&vps2)[1]
1837 #if ENABLE_ASH_GETOPTS
1838 # define voptind (&vps4)[1]
1839 # if ENABLE_ASH_RANDOM_SUPPORT
1840 # define vrandom (&voptind)[1]
1843 # if ENABLE_ASH_RANDOM_SUPPORT
1844 # define vrandom (&vps4)[1]
1849 * The following macros access the values of the above variables.
1850 * They have to skip over the name. They return the null string
1851 * for unset variables.
1853 #define ifsval() (vifs.text + 4)
1854 #define ifsset() ((vifs.flags & VUNSET) == 0)
1856 # define mailval() (vmail.text + 5)
1857 # define mpathval() (vmpath.text + 9)
1858 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1860 #define pathval() (vpath.text + 5)
1861 #define ps1val() (vps1.text + 4)
1862 #define ps2val() (vps2.text + 4)
1863 #define ps4val() (vps4.text + 4)
1864 #if ENABLE_ASH_GETOPTS
1865 # define optindval() (voptind.text + 7)
1869 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1870 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1872 #if ENABLE_ASH_GETOPTS
1873 static void FAST_FUNC
1874 getoptsreset(const char *value)
1876 shellparam.optind = number(value);
1877 shellparam.optoff = -1;
1882 * Return of a legal variable name (a letter or underscore followed by zero or
1883 * more letters, underscores, and digits).
1885 static char* FAST_FUNC
1886 endofname(const char *name)
1894 if (!is_in_name(*p))
1901 * Compares two strings up to the first = or '\0'. The first
1902 * string must be terminated by '='; the second may be terminated by
1903 * either '=' or '\0'.
1906 varcmp(const char *p, const char *q)
1910 while ((c = *p) == (d = *q)) {
1925 varequal(const char *a, const char *b)
1927 return !varcmp(a, b);
1931 * Find the appropriate entry in the hash table from the name.
1933 static struct var **
1934 hashvar(const char *p)
1938 hashval = ((unsigned char) *p) << 4;
1939 while (*p && *p != '=')
1940 hashval += (unsigned char) *p++;
1941 return &vartab[hashval % VTABSIZE];
1945 vpcmp(const void *a, const void *b)
1947 return varcmp(*(const char **)a, *(const char **)b);
1951 * This routine initializes the builtin variables.
1961 * PS1 depends on uid
1963 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1964 vps1.text = "PS1=\\w \\$ ";
1967 vps1.text = "PS1=# ";
1970 end = vp + ARRAY_SIZE(varinit);
1972 vpp = hashvar(vp->text);
1975 } while (++vp < end);
1978 static struct var **
1979 findvar(struct var **vpp, const char *name)
1981 for (; *vpp; vpp = &(*vpp)->next) {
1982 if (varequal((*vpp)->text, name)) {
1990 * Find the value of a variable. Returns NULL if not set.
1992 static const char* FAST_FUNC
1993 lookupvar(const char *name)
1997 v = *findvar(hashvar(name), name);
1999 #if ENABLE_ASH_RANDOM_SUPPORT
2001 * Dynamic variables are implemented roughly the same way they are
2002 * in bash. Namely, they're "special" so long as they aren't unset.
2003 * As soon as they're unset, they're no longer dynamic, and dynamic
2004 * lookup will no longer happen at that point. -- PFM.
2006 if ((v->flags & VDYNAMIC))
2009 if (!(v->flags & VUNSET))
2010 return strchrnul(v->text, '=') + 1;
2016 * Search the environment of a builtin command.
2019 bltinlookup(const char *name)
2023 for (sp = cmdenviron; sp; sp = sp->next) {
2024 if (varequal(sp->text, name))
2025 return strchrnul(sp->text, '=') + 1;
2027 return lookupvar(name);
2031 * Same as setvar except that the variable and value are passed in
2032 * the first argument as name=value. Since the first argument will
2033 * be actually stored in the table, it should not be a string that
2035 * Called with interrupts off.
2038 setvareq(char *s, int flags)
2040 struct var *vp, **vpp;
2043 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2044 vp = *findvar(vpp, s);
2046 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2049 if (flags & VNOSAVE)
2052 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2058 if (vp->func && (flags & VNOFUNC) == 0)
2059 (*vp->func)(strchrnul(s, '=') + 1);
2061 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2062 free((char*)vp->text);
2064 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2069 vp = ckzalloc(sizeof(*vp));
2071 /*vp->func = NULL; - ckzalloc did it */
2074 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2081 * Set the value of a variable. The flags argument is ored with the
2082 * flags of the variable. If val is NULL, the variable is unset.
2085 setvar(const char *name, const char *val, int flags)
2092 q = endofname(name);
2093 p = strchrnul(q, '=');
2095 if (!namelen || p != q)
2096 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2101 vallen = strlen(val);
2104 nameeq = ckmalloc(namelen + vallen + 2);
2105 p = (char *)memcpy(nameeq, name, namelen) + namelen;
2108 p = (char *)memcpy(p, val, vallen) + vallen;
2111 setvareq(nameeq, flags | VNOSAVE);
2115 static void FAST_FUNC
2116 setvar2(const char *name, const char *val)
2118 setvar(name, val, 0);
2121 #if ENABLE_ASH_GETOPTS
2123 * Safe version of setvar, returns 1 on success 0 on failure.
2126 setvarsafe(const char *name, const char *val, int flags)
2129 volatile int saveint;
2130 struct jmploc *volatile savehandler = exception_handler;
2131 struct jmploc jmploc;
2134 if (setjmp(jmploc.loc))
2137 exception_handler = &jmploc;
2138 setvar(name, val, flags);
2141 exception_handler = savehandler;
2142 RESTORE_INT(saveint);
2148 * Unset the specified variable.
2151 unsetvar(const char *s)
2157 vpp = findvar(hashvar(s), s);
2161 int flags = vp->flags;
2164 if (flags & VREADONLY)
2166 #if ENABLE_ASH_RANDOM_SUPPORT
2167 vp->flags &= ~VDYNAMIC;
2171 if ((flags & VSTRFIXED) == 0) {
2173 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2174 free((char*)vp->text);
2180 vp->flags &= ~VEXPORT;
2190 * Process a linked list of variable assignments.
2193 listsetvar(struct strlist *list_set_var, int flags)
2195 struct strlist *lp = list_set_var;
2201 setvareq(lp->text, flags);
2208 * Generate a list of variables satisfying the given conditions.
2211 listvars(int on, int off, char ***end)
2222 for (vp = *vpp; vp; vp = vp->next) {
2223 if ((vp->flags & mask) == on) {
2224 if (ep == stackstrend())
2225 ep = growstackstr();
2226 *ep++ = (char *) vp->text;
2229 } while (++vpp < vartab + VTABSIZE);
2230 if (ep == stackstrend())
2231 ep = growstackstr();
2235 return grabstackstr(ep);
2239 /* ============ Path search helper
2241 * The variable path (passed by reference) should be set to the start
2242 * of the path before the first call; path_advance will update
2243 * this value as it proceeds. Successive calls to path_advance will return
2244 * the possible path expansions in sequence. If an option (indicated by
2245 * a percent sign) appears in the path entry then the global variable
2246 * pathopt will be set to point to it; otherwise pathopt will be set to
2249 static const char *pathopt; /* set by path_advance */
2252 path_advance(const char **path, const char *name)
2262 for (p = start; *p && *p != ':' && *p != '%'; p++)
2264 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2265 while (stackblocksize() < len)
2269 memcpy(q, start, p - start);
2277 while (*p && *p != ':')
2284 return stalloc(len);
2288 /* ============ Prompt */
2290 static smallint doprompt; /* if set, prompt the user */
2291 static smallint needprompt; /* true if interactive and at start of line */
2293 #if ENABLE_FEATURE_EDITING
2294 static line_input_t *line_input_state;
2295 static const char *cmdedit_prompt;
2297 putprompt(const char *s)
2299 if (ENABLE_ASH_EXPAND_PRMT) {
2300 free((char*)cmdedit_prompt);
2301 cmdedit_prompt = ckstrdup(s);
2308 putprompt(const char *s)
2314 #if ENABLE_ASH_EXPAND_PRMT
2315 /* expandstr() needs parsing machinery, so it is far away ahead... */
2316 static const char *expandstr(const char *ps);
2318 #define expandstr(s) s
2322 setprompt(int whichprompt)
2325 #if ENABLE_ASH_EXPAND_PRMT
2326 struct stackmark smark;
2331 switch (whichprompt) {
2341 #if ENABLE_ASH_EXPAND_PRMT
2342 setstackmark(&smark);
2343 stalloc(stackblocksize());
2345 putprompt(expandstr(prompt));
2346 #if ENABLE_ASH_EXPAND_PRMT
2347 popstackmark(&smark);
2352 /* ============ The cd and pwd commands */
2354 #define CD_PHYSICAL 1
2364 while ((i = nextopt("LP")) != '\0') {
2366 flags ^= CD_PHYSICAL;
2375 * Update curdir (the name of the current directory) in response to a
2379 updatepwd(const char *dir)
2386 cdcomppath = ststrdup(dir);
2389 if (curdir == nullstr)
2391 new = stack_putstr(curdir, new);
2393 new = makestrspace(strlen(dir) + 2, new);
2394 lim = (char *)stackblock() + 1;
2398 if (new > lim && *lim == '/')
2403 if (dir[1] == '/' && dir[2] != '/') {
2409 p = strtok(cdcomppath, "/");
2413 if (p[1] == '.' && p[2] == '\0') {
2425 new = stack_putstr(p, new);
2433 return stackblock();
2437 * Find out what the current directory is. If we already know the current
2438 * directory, this routine returns immediately.
2443 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2444 return dir ? dir : nullstr;
2448 setpwd(const char *val, int setold)
2452 oldcur = dir = curdir;
2455 setvar("OLDPWD", oldcur, VEXPORT);
2458 if (physdir != nullstr) {
2459 if (physdir != oldcur)
2463 if (oldcur == val || !val) {
2469 dir = ckstrdup(val);
2470 if (oldcur != dir && oldcur != nullstr) {
2475 setvar("PWD", dir, VEXPORT);
2478 static void hashcd(void);
2481 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2482 * know that the current directory has changed.
2485 docd(const char *dest, int flags)
2487 const char *dir = NULL;
2490 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2493 if (!(flags & CD_PHYSICAL)) {
2494 dir = updatepwd(dest);
2508 static int FAST_FUNC
2509 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2521 dest = bltinlookup(homestr);
2522 else if (LONE_DASH(dest)) {
2523 dest = bltinlookup("OLDPWD");
2545 path = bltinlookup("CDPATH");
2554 p = path_advance(&path, dest);
2555 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2559 if (!docd(p, flags))
2564 ash_msg_and_raise_error("can't cd to %s", dest);
2567 if (flags & CD_PRINT)
2568 out1fmt(snlfmt, curdir);
2572 static int FAST_FUNC
2573 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2576 const char *dir = curdir;
2580 if (physdir == nullstr)
2584 out1fmt(snlfmt, dir);
2589 /* ============ ... */
2592 #define IBUFSIZ COMMON_BUFSIZE
2593 /* buffer for top level input file */
2594 #define basebuf bb_common_bufsiz1
2596 /* Syntax classes */
2597 #define CWORD 0 /* character is nothing special */
2598 #define CNL 1 /* newline character */
2599 #define CBACK 2 /* a backslash character */
2600 #define CSQUOTE 3 /* single quote */
2601 #define CDQUOTE 4 /* double quote */
2602 #define CENDQUOTE 5 /* a terminating quote */
2603 #define CBQUOTE 6 /* backwards single quote */
2604 #define CVAR 7 /* a dollar sign */
2605 #define CENDVAR 8 /* a '}' character */
2606 #define CLP 9 /* a left paren in arithmetic */
2607 #define CRP 10 /* a right paren in arithmetic */
2608 #define CENDFILE 11 /* end of file */
2609 #define CCTL 12 /* like CWORD, except it must be escaped */
2610 #define CSPCL 13 /* these terminate a word */
2611 #define CIGN 14 /* character should be ignored */
2614 #if ENABLE_ASH_ALIAS
2618 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2620 #if ENABLE_SH_MATH_SUPPORT
2621 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2623 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2625 static const uint16_t S_I_T[] = {
2626 #if ENABLE_ASH_ALIAS
2627 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2629 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2630 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2631 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2632 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2633 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2634 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2635 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2636 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2637 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2638 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2639 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2640 #if !USE_SIT_FUNCTION
2641 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2642 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2643 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2647 /* Constants below must match table above */
2649 #if ENABLE_ASH_ALIAS
2650 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2652 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2653 CNL_CNL_CNL_CNL , /* 2 */
2654 CWORD_CCTL_CCTL_CWORD , /* 3 */
2655 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2656 CVAR_CVAR_CWORD_CVAR , /* 5 */
2657 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2658 CSPCL_CWORD_CWORD_CLP , /* 7 */
2659 CSPCL_CWORD_CWORD_CRP , /* 8 */
2660 CBACK_CBACK_CCTL_CBACK , /* 9 */
2661 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2662 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2663 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2664 CWORD_CWORD_CWORD_CWORD , /* 13 */
2665 CCTL_CCTL_CCTL_CCTL , /* 14 */
2668 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2669 * caller must ensure proper cast on it if c is *char_ptr!
2671 /* Values for syntax param */
2672 #define BASESYNTAX 0 /* not in quotes */
2673 #define DQSYNTAX 1 /* in double quotes */
2674 #define SQSYNTAX 2 /* in single quotes */
2675 #define ARISYNTAX 3 /* in arithmetic */
2676 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2678 #if USE_SIT_FUNCTION
2681 SIT(int c, int syntax)
2683 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2684 # if ENABLE_ASH_ALIAS
2685 static const uint8_t syntax_index_table[] ALIGN1 = {
2686 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2687 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2688 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2692 static const uint8_t syntax_index_table[] ALIGN1 = {
2693 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2694 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2695 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2704 # if ENABLE_ASH_ALIAS
2710 /* Cast is purely for paranoia here,
2711 * just in case someone passed signed char to us */
2712 if ((unsigned char)c >= CTL_FIRST
2713 && (unsigned char)c <= CTL_LAST
2717 s = strchrnul(spec_symbls, c);
2720 indx = syntax_index_table[s - spec_symbls];
2722 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2725 #else /* !USE_SIT_FUNCTION */
2727 static const uint8_t syntax_index_table[] = {
2728 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2729 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2738 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2739 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2740 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2760 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2761 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2762 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2763 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2764 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2765 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2766 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2767 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2768 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2769 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2770 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2771 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2772 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2773 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2774 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2775 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2776 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2777 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2778 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2779 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2780 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2781 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2782 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2783 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2784 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2785 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2786 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2787 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2788 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2789 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2790 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2791 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2792 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2793 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2794 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2795 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2796 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2797 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2800 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2802 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2803 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2814 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2815 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2816 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2817 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2819 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2820 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2821 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2822 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2823 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2824 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2825 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2826 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2848 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2849 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2850 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2851 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2852 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2853 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2854 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2855 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2856 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2857 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2859 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2860 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2861 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2862 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2863 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2864 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2865 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2866 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 162 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 163 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 164 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 165 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 166 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 167 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 168 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 169 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 170 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 171 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 172 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 173 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 174 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 175 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 176 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 177 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 178 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 179 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 180 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 181 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 182 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 183 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 184 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 185 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 186 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 187 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 188 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 189 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 190 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 191 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 192 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 193 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 194 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 195 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 196 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 197 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 198 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 199 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 200 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 201 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 202 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 203 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 204 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 205 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 206 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 207 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 208 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 209 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 210 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 211 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 212 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 213 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 214 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 215 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 216 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 217 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 218 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 219 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 220 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 221 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 222 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 223 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 224 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 225 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 226 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 227 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 228 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 229 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 231 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 232 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 233 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 234 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 235 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 236 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 237 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 238 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 239 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 241 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 242 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 243 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 244 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 245 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 246 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 247 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 248 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 249 */ CWORD_CWORD_CWORD_CWORD,
2979 /* 250 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 251 */ CWORD_CWORD_CWORD_CWORD,
2981 /* 252 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 253 */ CWORD_CWORD_CWORD_CWORD,
2983 /* 254 */ CWORD_CWORD_CWORD_CWORD,
2984 /* 255 */ CWORD_CWORD_CWORD_CWORD,
2985 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2986 # if ENABLE_ASH_ALIAS
2987 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
2991 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
2993 #endif /* !USE_SIT_FUNCTION */
2996 /* ============ Alias handling */
2998 #if ENABLE_ASH_ALIAS
3000 #define ALIASINUSE 1
3011 static struct alias **atab; // [ATABSIZE];
3012 #define INIT_G_alias() do { \
3013 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3017 static struct alias **
3018 __lookupalias(const char *name) {
3019 unsigned int hashval;
3026 ch = (unsigned char)*p;
3030 ch = (unsigned char)*++p;
3032 app = &atab[hashval % ATABSIZE];
3034 for (; *app; app = &(*app)->next) {
3035 if (strcmp(name, (*app)->name) == 0) {
3043 static struct alias *
3044 lookupalias(const char *name, int check)
3046 struct alias *ap = *__lookupalias(name);
3048 if (check && ap && (ap->flag & ALIASINUSE))
3053 static struct alias *
3054 freealias(struct alias *ap)
3058 if (ap->flag & ALIASINUSE) {
3059 ap->flag |= ALIASDEAD;
3071 setalias(const char *name, const char *val)
3073 struct alias *ap, **app;
3075 app = __lookupalias(name);
3079 if (!(ap->flag & ALIASINUSE)) {
3082 ap->val = ckstrdup(val);
3083 ap->flag &= ~ALIASDEAD;
3086 ap = ckzalloc(sizeof(struct alias));
3087 ap->name = ckstrdup(name);
3088 ap->val = ckstrdup(val);
3089 /*ap->flag = 0; - ckzalloc did it */
3090 /*ap->next = NULL;*/
3097 unalias(const char *name)
3101 app = __lookupalias(name);
3105 *app = freealias(*app);
3116 struct alias *ap, **app;
3120 for (i = 0; i < ATABSIZE; i++) {
3122 for (ap = *app; ap; ap = *app) {
3123 *app = freealias(*app);
3133 printalias(const struct alias *ap)
3135 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3139 * TODO - sort output
3141 static int FAST_FUNC
3142 aliascmd(int argc UNUSED_PARAM, char **argv)
3151 for (i = 0; i < ATABSIZE; i++) {
3152 for (ap = atab[i]; ap; ap = ap->next) {
3158 while ((n = *++argv) != NULL) {
3159 v = strchr(n+1, '=');
3160 if (v == NULL) { /* n+1: funny ksh stuff */
3161 ap = *__lookupalias(n);
3163 fprintf(stderr, "%s: %s not found\n", "alias", n);
3176 static int FAST_FUNC
3177 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3181 while ((i = nextopt("a")) != '\0') {
3187 for (i = 0; *argptr; argptr++) {
3188 if (unalias(*argptr)) {
3189 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3197 #endif /* ASH_ALIAS */
3200 /* ============ jobs.c */
3202 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3205 #define FORK_NOJOB 2
3207 /* mode flags for showjob(s) */
3208 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3209 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3210 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3213 * A job structure contains information about a job. A job is either a
3214 * single process or a set of processes contained in a pipeline. In the
3215 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3219 pid_t ps_pid; /* process id */
3220 int ps_status; /* last process status from wait() */
3221 char *ps_cmd; /* text of command being run */
3225 struct procstat ps0; /* status of process */
3226 struct procstat *ps; /* status or processes when more than one */
3228 int stopstatus; /* status of a stopped job */
3231 nprocs: 16, /* number of processes */
3233 #define JOBRUNNING 0 /* at least one proc running */
3234 #define JOBSTOPPED 1 /* all procs are stopped */
3235 #define JOBDONE 2 /* all procs are completed */
3237 sigint: 1, /* job was killed by SIGINT */
3238 jobctl: 1, /* job running under job control */
3240 waited: 1, /* true if this entry has been waited for */
3241 used: 1, /* true if this entry is in used */
3242 changed: 1; /* true if status has changed */
3243 struct job *prev_job; /* previous job */
3246 static struct job *makejob(/*union node *,*/ int);
3247 static int forkshell(struct job *, union node *, int);
3248 static int waitforjob(struct job *);
3251 enum { doing_jobctl = 0 };
3252 #define setjobctl(on) do {} while (0)
3254 static smallint doing_jobctl; //references:8
3255 static void setjobctl(int);
3262 ignoresig(int signo)
3264 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3265 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3266 /* No, need to do it */
3267 signal(signo, SIG_IGN);
3269 sigmode[signo - 1] = S_HARD_IGN;
3273 * Signal handler. Only one usage site - in setsignal()
3278 gotsig[signo - 1] = 1;
3280 if (signo == SIGINT && !trap[SIGINT]) {
3281 if (!suppress_int) {
3283 raise_interrupt(); /* does not return */
3287 pending_sig = signo;
3292 * Set the signal handler for the specified signal. The routine figures
3293 * out what it should be set to.
3296 setsignal(int signo)
3299 char cur_act, new_act;
3300 struct sigaction act;
3304 if (t != NULL) { /* trap for this sig is set */
3306 if (t[0] == '\0') /* trap is "": ignore this sig */
3310 if (rootshell && new_act == S_DFL) {
3313 if (iflag || minusc || sflag == 0)
3322 * "In all cases, bash ignores SIGQUIT. Non-builtin
3323 * commands run by bash have signal handlers
3324 * set to the values inherited by the shell
3325 * from its parent". */
3341 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3342 //whereas we have to restore it to what shell got on entry
3343 //from the parent. See comment above
3345 t = &sigmode[signo - 1];
3348 /* current setting is not yet known */
3349 if (sigaction(signo, NULL, &act)) {
3350 /* pretend it worked; maybe we should give a warning,
3351 * but other shells don't. We don't alter sigmode,
3352 * so we retry every time.
3353 * btw, in Linux it never fails. --vda */
3356 if (act.sa_handler == SIG_IGN) {
3357 cur_act = S_HARD_IGN;
3359 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3361 cur_act = S_IGN; /* don't hard ignore these */
3365 if (cur_act == S_HARD_IGN || cur_act == new_act)
3368 act.sa_handler = SIG_DFL;
3371 act.sa_handler = onsig;
3372 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3373 sigfillset(&act.sa_mask); /* ditto */
3376 act.sa_handler = SIG_IGN;
3379 sigaction_set(signo, &act);
3384 /* mode flags for set_curjob */
3385 #define CUR_DELETE 2
3386 #define CUR_RUNNING 1
3387 #define CUR_STOPPED 0
3389 /* mode flags for dowait */
3390 #define DOWAIT_NONBLOCK WNOHANG
3391 #define DOWAIT_BLOCK 0
3394 /* pgrp of shell on invocation */
3395 static int initialpgrp; //references:2
3396 static int ttyfd = -1; //5
3399 static struct job *jobtab; //5
3401 static unsigned njobs; //4
3403 static struct job *curjob; //lots
3404 /* number of presumed living untracked jobs */
3405 static int jobless; //4
3408 set_curjob(struct job *jp, unsigned mode)
3411 struct job **jpp, **curp;
3413 /* first remove from list */
3414 jpp = curp = &curjob;
3419 jpp = &jp1->prev_job;
3421 *jpp = jp1->prev_job;
3423 /* Then re-insert in correct position */
3431 /* job being deleted */
3434 /* newly created job or backgrounded job,
3435 put after all stopped jobs. */
3439 if (!jp1 || jp1->state != JOBSTOPPED)
3442 jpp = &jp1->prev_job;
3448 /* newly stopped job - becomes curjob */
3449 jp->prev_job = *jpp;
3457 jobno(const struct job *jp)
3459 return jp - jobtab + 1;
3464 * Convert a job name to a job structure.
3467 #define getjob(name, getctl) getjob(name)
3470 getjob(const char *name, int getctl)
3474 const char *err_msg = "%s: no such job";
3478 char *(*match)(const char *, const char *);
3493 if (c == '+' || c == '%') {
3495 err_msg = "No current job";
3501 err_msg = "No previous job";
3512 jp = jobtab + num - 1;
3527 if (match(jp->ps[0].ps_cmd, p)) {
3531 err_msg = "%s: ambiguous";
3541 err_msg = "job %s not created under job control";
3542 if (getctl && jp->jobctl == 0)
3547 ash_msg_and_raise_error(err_msg, name);
3551 * Mark a job structure as unused.
3554 freejob(struct job *jp)
3556 struct procstat *ps;
3560 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3561 if (ps->ps_cmd != nullstr)
3564 if (jp->ps != &jp->ps0)
3567 set_curjob(jp, CUR_DELETE);
3573 xtcsetpgrp(int fd, pid_t pgrp)
3575 if (tcsetpgrp(fd, pgrp))
3576 ash_msg_and_raise_error("can't set tty process group (%m)");
3580 * Turn job control on and off.
3582 * Note: This code assumes that the third arg to ioctl is a character
3583 * pointer, which is true on Berkeley systems but not System V. Since
3584 * System V doesn't have job control yet, this isn't a problem now.
3586 * Called with interrupts off.
3594 if (on == doing_jobctl || rootshell == 0)
3598 ofd = fd = open(_PATH_TTY, O_RDWR);
3600 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3601 * That sometimes helps to acquire controlling tty.
3602 * Obviously, a workaround for bugs when someone
3603 * failed to provide a controlling tty to bash! :) */
3609 fd = fcntl(fd, F_DUPFD, 10);
3614 /* fd is a tty at this point */
3615 close_on_exec_on(fd);
3616 do { /* while we are in the background */
3617 pgrp = tcgetpgrp(fd);
3620 ash_msg("can't access tty; job control turned off");
3624 if (pgrp == getpgrp())
3635 xtcsetpgrp(fd, pgrp);
3637 /* turning job control off */
3640 /* was xtcsetpgrp, but this can make exiting ash
3641 * loop forever if pty is already deleted */
3642 tcsetpgrp(fd, pgrp);
3656 static int FAST_FUNC
3657 killcmd(int argc, char **argv)
3660 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3662 if (argv[i][0] == '%') {
3663 struct job *jp = getjob(argv[i], 0);
3664 unsigned pid = jp->ps[0].ps_pid;
3665 /* Enough space for ' -NNN<nul>' */
3666 argv[i] = alloca(sizeof(int)*3 + 3);
3667 /* kill_main has matching code to expect
3668 * leading space. Needed to not confuse
3669 * negative pids with "kill -SIGNAL_NO" syntax */
3670 sprintf(argv[i], " -%u", pid);
3672 } while (argv[++i]);
3674 return kill_main(argc, argv);
3678 showpipe(struct job *jp /*, FILE *out*/)
3680 struct procstat *ps;
3681 struct procstat *psend;
3683 psend = jp->ps + jp->nprocs;
3684 for (ps = jp->ps + 1; ps < psend; ps++)
3685 printf(" | %s", ps->ps_cmd);
3686 outcslow('\n', stdout);
3687 flush_stdout_stderr();
3692 restartjob(struct job *jp, int mode)
3694 struct procstat *ps;
3700 if (jp->state == JOBDONE)
3702 jp->state = JOBRUNNING;
3703 pgid = jp->ps[0].ps_pid;
3704 if (mode == FORK_FG)
3705 xtcsetpgrp(ttyfd, pgid);
3706 killpg(pgid, SIGCONT);
3710 if (WIFSTOPPED(ps->ps_status)) {
3716 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3721 static int FAST_FUNC
3722 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3728 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3732 jp = getjob(*argv, 1);
3733 if (mode == FORK_BG) {
3734 set_curjob(jp, CUR_RUNNING);
3735 printf("[%d] ", jobno(jp));
3737 out1str(jp->ps[0].ps_cmd);
3738 showpipe(jp /*, stdout*/);
3739 retval = restartjob(jp, mode);
3740 } while (*argv && *++argv);
3746 sprint_status(char *s, int status, int sigonly)
3752 if (!WIFEXITED(status)) {
3754 if (WIFSTOPPED(status))
3755 st = WSTOPSIG(status);
3758 st = WTERMSIG(status);
3760 if (st == SIGINT || st == SIGPIPE)
3763 if (WIFSTOPPED(status))
3768 col = fmtstr(s, 32, strsignal(st));
3769 if (WCOREDUMP(status)) {
3770 col += fmtstr(s + col, 16, " (core dumped)");
3772 } else if (!sigonly) {
3773 st = WEXITSTATUS(status);
3775 col = fmtstr(s, 16, "Done(%d)", st);
3777 col = fmtstr(s, 16, "Done");
3784 dowait(int wait_flags, struct job *job)
3789 struct job *thisjob;
3792 TRACE(("dowait(0x%x) called\n", wait_flags));
3794 /* Do a wait system call. If job control is compiled in, we accept
3795 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3796 * NB: _not_ safe_waitpid, we need to detect EINTR */
3798 wait_flags |= WUNTRACED;
3799 pid = waitpid(-1, &status, wait_flags);
3800 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3801 pid, status, errno, strerror(errno)));
3807 for (jp = curjob; jp; jp = jp->prev_job) {
3808 struct procstat *ps;
3809 struct procstat *psend;
3810 if (jp->state == JOBDONE)
3814 psend = ps + jp->nprocs;
3816 if (ps->ps_pid == pid) {
3817 TRACE(("Job %d: changing status of proc %d "
3818 "from 0x%x to 0x%x\n",
3819 jobno(jp), pid, ps->ps_status, status));
3820 ps->ps_status = status;
3823 if (ps->ps_status == -1)
3826 if (state == JOBRUNNING)
3828 if (WIFSTOPPED(ps->ps_status)) {
3829 jp->stopstatus = ps->ps_status;
3833 } while (++ps < psend);
3838 if (!WIFSTOPPED(status))
3844 if (state != JOBRUNNING) {
3845 thisjob->changed = 1;
3847 if (thisjob->state != state) {
3848 TRACE(("Job %d: changing state from %d to %d\n",
3849 jobno(thisjob), thisjob->state, state));
3850 thisjob->state = state;
3852 if (state == JOBSTOPPED) {
3853 set_curjob(thisjob, CUR_STOPPED);
3862 if (thisjob && thisjob == job) {
3866 len = sprint_status(s, status, 1);
3877 blocking_wait_with_raise_on_sig(struct job *job)
3879 pid_t pid = dowait(DOWAIT_BLOCK, job);
3880 if (pid <= 0 && pending_sig)
3881 raise_exception(EXSIG);
3887 showjob(FILE *out, struct job *jp, int mode)
3889 struct procstat *ps;
3890 struct procstat *psend;
3897 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
3898 /* just output process (group) id of pipeline */
3899 fprintf(out, "%d\n", ps->ps_pid);
3903 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3908 else if (curjob && jp == curjob->prev_job)
3911 if (mode & SHOW_PIDS)
3912 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
3914 psend = ps + jp->nprocs;
3916 if (jp->state == JOBRUNNING) {
3917 strcpy(s + col, "Running");
3918 col += sizeof("Running") - 1;
3920 int status = psend[-1].ps_status;
3921 if (jp->state == JOBSTOPPED)
3922 status = jp->stopstatus;
3923 col += sprint_status(s + col, status, 0);
3925 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
3927 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3928 * or prints several "PID | <cmdN>" lines,
3929 * depending on SHOW_PIDS bit.
3930 * We do not print status of individual processes
3931 * between PID and <cmdN>. bash does it, but not very well:
3932 * first line shows overall job status, not process status,
3933 * making it impossible to know 1st process status.
3937 /* for each process */
3940 if (mode & SHOW_PIDS)
3941 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
3943 fprintf(out, "%s%*c%s%s",
3945 33 - col >= 0 ? 33 - col : 0, ' ',
3946 ps == jp->ps ? "" : "| ",
3949 } while (++ps != psend);
3950 outcslow('\n', out);
3954 if (jp->state == JOBDONE) {
3955 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3961 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3962 * statuses have changed since the last call to showjobs.
3965 showjobs(FILE *out, int mode)
3969 TRACE(("showjobs(0x%x) called\n", mode));
3971 /* Handle all finished jobs */
3972 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
3975 for (jp = curjob; jp; jp = jp->prev_job) {
3976 if (!(mode & SHOW_CHANGED) || jp->changed) {
3977 showjob(out, jp, mode);
3982 static int FAST_FUNC
3983 jobscmd(int argc UNUSED_PARAM, char **argv)
3988 while ((m = nextopt("lp")) != '\0') {
3992 mode |= SHOW_ONLY_PGID;
3998 showjob(stdout, getjob(*argv, 0), mode);
4001 showjobs(stdout, mode);
4008 /* Called only on finished or stopped jobs (no members are running) */
4010 getstatus(struct job *job)
4014 struct procstat *ps;
4016 /* Fetch last member's status */
4017 ps = job->ps + job->nprocs - 1;
4018 status = ps->ps_status;
4020 /* "set -o pipefail" mode: use last _nonzero_ status */
4021 while (status == 0 && --ps >= job->ps)
4022 status = ps->ps_status;
4025 retval = WEXITSTATUS(status);
4026 if (!WIFEXITED(status)) {
4028 retval = WSTOPSIG(status);
4029 if (!WIFSTOPPED(status))
4032 /* XXX: limits number of signals */
4033 retval = WTERMSIG(status);
4035 if (retval == SIGINT)
4041 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4042 jobno(job), job->nprocs, status, retval));
4046 static int FAST_FUNC
4047 waitcmd(int argc UNUSED_PARAM, char **argv)
4054 raise_exception(EXSIG);
4061 /* wait for all jobs */
4065 if (!jp) /* no running procs */
4067 if (jp->state == JOBRUNNING)
4073 * "When bash is waiting for an asynchronous command via
4074 * the wait builtin, the reception of a signal for which a trap
4075 * has been set will cause the wait builtin to return immediately
4076 * with an exit status greater than 128, immediately after which
4077 * the trap is executed."
4078 * Do we do it that way? */
4079 blocking_wait_with_raise_on_sig(NULL);
4085 if (**argv != '%') {
4086 pid_t pid = number(*argv);
4091 if (job->ps[job->nprocs - 1].ps_pid == pid)
4093 job = job->prev_job;
4096 job = getjob(*argv, 0);
4097 /* loop until process terminated or stopped */
4098 while (job->state == JOBRUNNING)
4099 blocking_wait_with_raise_on_sig(NULL);
4101 retval = getstatus(job);
4114 struct job *jp, *jq;
4116 len = njobs * sizeof(*jp);
4118 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4120 offset = (char *)jp - (char *)jq;
4122 /* Relocate pointers */
4125 jq = (struct job *)((char *)jq + l);
4129 #define joff(p) ((struct job *)((char *)(p) + l))
4130 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4131 if (joff(jp)->ps == &jq->ps0)
4132 jmove(joff(jp)->ps);
4133 if (joff(jp)->prev_job)
4134 jmove(joff(jp)->prev_job);
4144 jp = (struct job *)((char *)jp + len);
4148 } while (--jq >= jp);
4153 * Return a new job structure.
4154 * Called with interrupts off.
4157 makejob(/*union node *node,*/ int nprocs)
4162 for (i = njobs, jp = jobtab; ; jp++) {
4169 if (jp->state != JOBDONE || !jp->waited)
4178 memset(jp, 0, sizeof(*jp));
4180 /* jp->jobctl is a bitfield.
4181 * "jp->jobctl |= jobctl" likely to give awful code */
4185 jp->prev_job = curjob;
4190 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4192 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4199 * Return a string identifying a command (to be printed by the
4202 static char *cmdnextc;
4205 cmdputs(const char *s)
4207 static const char vstype[VSTYPE + 1][3] = {
4208 "", "}", "-", "+", "?", "=",
4209 "%", "%%", "#", "##"
4210 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4213 const char *p, *str;
4217 unsigned char subtype = 0;
4221 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4223 while ((c = *p++) != '\0') {
4231 if ((subtype & VSTYPE) == VSLENGTH)
4235 if (!(subtype & VSQUOTE) == !(quoted & 1))
4241 str = "\"}" + !(quoted & 1);
4248 case CTLBACKQ+CTLQUOTE:
4251 #if ENABLE_SH_MATH_SUPPORT
4266 if ((subtype & VSTYPE) != VSNORMAL)
4268 str = vstype[subtype & VSTYPE];
4269 if (subtype & VSNUL)
4278 /* These can only happen inside quotes */
4291 while ((c = *str++) != '\0') {
4294 } /* while *p++ not NUL */
4297 USTPUTC('"', nextc);
4303 /* cmdtxt() and cmdlist() call each other */
4304 static void cmdtxt(union node *n);
4307 cmdlist(union node *np, int sep)
4309 for (; np; np = np->narg.next) {
4313 if (sep && np->narg.next)
4319 cmdtxt(union node *n)
4322 struct nodelist *lp;
4333 lp = n->npipe.cmdlist;
4351 cmdtxt(n->nbinary.ch1);
4367 cmdtxt(n->nif.test);
4369 if (n->nif.elsepart) {
4370 cmdtxt(n->nif.ifpart);
4372 n = n->nif.elsepart;
4390 cmdtxt(n->nbinary.ch1);
4400 cmdputs(n->nfor.var);
4402 cmdlist(n->nfor.args, 1);
4407 cmdputs(n->narg.text);
4411 cmdlist(n->ncmd.args, 1);
4412 cmdlist(n->ncmd.redirect, 0);
4425 cmdputs(n->ncase.expr->narg.text);
4427 for (np = n->ncase.cases; np; np = np->nclist.next) {
4428 cmdtxt(np->nclist.pattern);
4430 cmdtxt(np->nclist.body);
4444 #if ENABLE_ASH_BASH_COMPAT
4459 cmdputs(utoa(n->nfile.fd));
4461 if (n->type == NTOFD || n->type == NFROMFD) {
4462 cmdputs(utoa(n->ndup.dupfd));
4471 commandtext(union node *n)
4475 STARTSTACKSTR(cmdnextc);
4477 name = stackblock();
4478 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4479 name, cmdnextc, cmdnextc));
4480 return ckstrdup(name);
4485 * Fork off a subshell. If we are doing job control, give the subshell its
4486 * own process group. Jp is a job structure that the job is to be added to.
4487 * N is the command that will be evaluated by the child. Both jp and n may
4488 * be NULL. The mode parameter can be one of the following:
4489 * FORK_FG - Fork off a foreground process.
4490 * FORK_BG - Fork off a background process.
4491 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4492 * process group even if job control is on.
4494 * When job control is turned off, background processes have their standard
4495 * input redirected to /dev/null (except for the second and later processes
4498 * Called with interrupts off.
4501 * Clear traps on a fork.
4508 for (tp = trap; tp < &trap[NSIG]; tp++) {
4509 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4511 if (trap_ptr == trap)
4513 /* else: it "belongs" to trap_ptr vector, don't free */
4515 if ((tp - trap) != 0)
4516 setsignal(tp - trap);
4522 /* Lives far away from here, needed for forkchild */
4523 static void closescript(void);
4525 /* Called after fork(), in child */
4526 static NOINLINE void
4527 forkchild(struct job *jp, union node *n, int mode)
4531 TRACE(("Child shell %d\n", getpid()));
4535 /* man bash: "Non-builtin commands run by bash have signal handlers
4536 * set to the values inherited by the shell from its parent".
4537 * Do we do it correctly? */
4541 if (mode == FORK_NOJOB /* is it `xxx` ? */
4542 && n && n->type == NCMD /* is it single cmd? */
4543 /* && n->ncmd.args->type == NARG - always true? */
4544 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4545 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4546 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4548 TRACE(("Trap hack\n"));
4549 /* Awful hack for `trap` or $(trap).
4551 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4552 * contains an example where "trap" is executed in a subshell:
4554 * save_traps=$(trap)
4556 * eval "$save_traps"
4558 * Standard does not say that "trap" in subshell shall print
4559 * parent shell's traps. It only says that its output
4560 * must have suitable form, but then, in the above example
4561 * (which is not supposed to be normative), it implies that.
4563 * bash (and probably other shell) does implement it
4564 * (traps are reset to defaults, but "trap" still shows them),
4565 * but as a result, "trap" logic is hopelessly messed up:
4568 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4569 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4570 * # true | trap <--- trap is in subshell - no output (ditto)
4571 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4572 * trap -- 'echo Ho' SIGWINCH
4573 * # echo `(trap)` <--- in subshell in subshell - output
4574 * trap -- 'echo Ho' SIGWINCH
4575 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4576 * trap -- 'echo Ho' SIGWINCH
4578 * The rules when to forget and when to not forget traps
4579 * get really complex and nonsensical.
4581 * Our solution: ONLY bare $(trap) or `trap` is special.
4583 /* Save trap handler strings for trap builtin to print */
4584 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4585 /* Fall through into clearing traps */
4589 /* do job control only in root shell */
4591 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4594 if (jp->nprocs == 0)
4597 pgrp = jp->ps[0].ps_pid;
4598 /* this can fail because we are doing it in the parent also */
4600 if (mode == FORK_FG)
4601 xtcsetpgrp(ttyfd, pgrp);
4606 if (mode == FORK_BG) {
4607 /* man bash: "When job control is not in effect,
4608 * asynchronous commands ignore SIGINT and SIGQUIT" */
4611 if (jp->nprocs == 0) {
4613 if (open(bb_dev_null, O_RDONLY) != 0)
4614 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4618 if (iflag) { /* why if iflag only? */
4623 * "In all cases, bash ignores SIGQUIT. Non-builtin
4624 * commands run by bash have signal handlers
4625 * set to the values inherited by the shell
4627 * Take care of the second rule: */
4631 if (n && n->type == NCMD
4632 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4634 TRACE(("Job hack\n"));
4635 /* "jobs": we do not want to clear job list for it,
4636 * instead we remove only _its_ own_ job from job list.
4637 * This makes "jobs .... | cat" more useful.
4643 for (jp = curjob; jp; jp = jp->prev_job)
4648 /* Called after fork(), in parent */
4650 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4653 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4655 TRACE(("In parent shell: child = %d\n", pid));
4657 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4663 if (mode != FORK_NOJOB && jp->jobctl) {
4666 if (jp->nprocs == 0)
4669 pgrp = jp->ps[0].ps_pid;
4670 /* This can fail because we are doing it in the child also */
4674 if (mode == FORK_BG) {
4675 backgndpid = pid; /* set $! */
4676 set_curjob(jp, CUR_RUNNING);
4679 struct procstat *ps = &jp->ps[jp->nprocs++];
4682 ps->ps_cmd = nullstr;
4684 if (doing_jobctl && n)
4685 ps->ps_cmd = commandtext(n);
4691 forkshell(struct job *jp, union node *n, int mode)
4695 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4698 TRACE(("Fork failed, errno=%d", errno));
4701 ash_msg_and_raise_error("can't fork");
4704 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4705 forkchild(jp, n, mode);
4707 forkparent(jp, n, mode, pid);
4713 * Wait for job to finish.
4715 * Under job control we have the problem that while a child process
4716 * is running interrupts generated by the user are sent to the child
4717 * but not to the shell. This means that an infinite loop started by
4718 * an interactive user may be hard to kill. With job control turned off,
4719 * an interactive user may place an interactive program inside a loop.
4720 * If the interactive program catches interrupts, the user doesn't want
4721 * these interrupts to also abort the loop. The approach we take here
4722 * is to have the shell ignore interrupt signals while waiting for a
4723 * foreground process to terminate, and then send itself an interrupt
4724 * signal if the child process was terminated by an interrupt signal.
4725 * Unfortunately, some programs want to do a bit of cleanup and then
4726 * exit on interrupt; unless these processes terminate themselves by
4727 * sending a signal to themselves (instead of calling exit) they will
4728 * confuse this approach.
4730 * Called with interrupts off.
4733 waitforjob(struct job *jp)
4737 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4740 while (jp->state == JOBRUNNING) {
4741 /* In non-interactive shells, we _can_ get
4742 * a keyboard signal here and be EINTRed,
4743 * but we just loop back, waiting for command to complete.
4746 * "If bash is waiting for a command to complete and receives
4747 * a signal for which a trap has been set, the trap
4748 * will not be executed until the command completes."
4750 * Reality is that even if trap is not set, bash
4751 * will not act on the signal until command completes.
4752 * Try this. sleep5intoff.c:
4753 * #include <signal.h>
4754 * #include <unistd.h>
4757 * sigemptyset(&set);
4758 * sigaddset(&set, SIGINT);
4759 * sigaddset(&set, SIGQUIT);
4760 * sigprocmask(SIG_BLOCK, &set, NULL);
4764 * $ bash -c './sleep5intoff; echo hi'
4765 * ^C^C^C^C <--- pressing ^C once a second
4767 * $ bash -c './sleep5intoff; echo hi'
4768 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4771 dowait(DOWAIT_BLOCK, jp);
4778 xtcsetpgrp(ttyfd, rootpid);
4780 * This is truly gross.
4781 * If we're doing job control, then we did a TIOCSPGRP which
4782 * caused us (the shell) to no longer be in the controlling
4783 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4784 * intuit from the subprocess exit status whether a SIGINT
4785 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4787 if (jp->sigint) /* TODO: do the same with all signals */
4788 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4790 if (jp->state == JOBDONE)
4797 * return 1 if there are stopped jobs, otherwise 0
4809 if (jp && jp->state == JOBSTOPPED) {
4810 out2str("You have stopped jobs.\n");
4819 /* ============ redir.c
4821 * Code for dealing with input/output redirection.
4824 #define EMPTY -2 /* marks an unused slot in redirtab */
4825 #define CLOSED -3 /* marks a slot of previously-closed fd */
4828 * Open a file in noclobber mode.
4829 * The code was copied from bash.
4832 noclobberopen(const char *fname)
4835 struct stat finfo, finfo2;
4838 * If the file exists and is a regular file, return an error
4841 r = stat(fname, &finfo);
4842 if (r == 0 && S_ISREG(finfo.st_mode)) {
4848 * If the file was not present (r != 0), make sure we open it
4849 * exclusively so that if it is created before we open it, our open
4850 * will fail. Make sure that we do not truncate an existing file.
4851 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4852 * file was not a regular file, we leave O_EXCL off.
4855 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4856 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4858 /* If the open failed, return the file descriptor right away. */
4863 * OK, the open succeeded, but the file may have been changed from a
4864 * non-regular file to a regular file between the stat and the open.
4865 * We are assuming that the O_EXCL open handles the case where FILENAME
4866 * did not exist and is symlinked to an existing file between the stat
4871 * If we can open it and fstat the file descriptor, and neither check
4872 * revealed that it was a regular file, and the file has not been
4873 * replaced, return the file descriptor.
4875 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4876 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4879 /* The file has been replaced. badness. */
4886 * Handle here documents. Normally we fork off a process to write the
4887 * data to a pipe. If the document is short, we can stuff the data in
4888 * the pipe without forking.
4890 /* openhere needs this forward reference */
4891 static void expandhere(union node *arg, int fd);
4893 openhere(union node *redir)
4899 ash_msg_and_raise_error("pipe call failed");
4900 if (redir->type == NHERE) {
4901 len = strlen(redir->nhere.doc->narg.text);
4902 if (len <= PIPE_BUF) {
4903 full_write(pip[1], redir->nhere.doc->narg.text, len);
4907 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4910 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4911 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4912 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4913 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4914 signal(SIGPIPE, SIG_DFL);
4915 if (redir->type == NHERE)
4916 full_write(pip[1], redir->nhere.doc->narg.text, len);
4918 expandhere(redir->nhere.doc, pip[1]);
4919 _exit(EXIT_SUCCESS);
4927 openredirect(union node *redir)
4932 switch (redir->nfile.type) {
4934 fname = redir->nfile.expfname;
4935 f = open(fname, O_RDONLY);
4940 fname = redir->nfile.expfname;
4941 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4946 #if ENABLE_ASH_BASH_COMPAT
4949 /* Take care of noclobber mode. */
4951 fname = redir->nfile.expfname;
4952 f = noclobberopen(fname);
4959 fname = redir->nfile.expfname;
4960 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4965 fname = redir->nfile.expfname;
4966 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4974 /* Fall through to eliminate warning. */
4975 /* Our single caller does this itself */
4982 f = openhere(redir);
4988 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4990 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
4994 * Copy a file descriptor to be >= to. Returns -1
4995 * if the source file descriptor is closed, EMPTY if there are no unused
4996 * file descriptors left.
4998 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
4999 * old code was doing close(to) prior to copyfd() to achieve the same */
5001 COPYFD_EXACT = (int)~(INT_MAX),
5002 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5005 copyfd(int from, int to)
5009 if (to & COPYFD_EXACT) {
5010 to &= ~COPYFD_EXACT;
5012 newfd = dup2(from, to);
5014 newfd = fcntl(from, F_DUPFD, to);
5017 if (errno == EMFILE)
5019 /* Happens when source fd is not open: try "echo >&99" */
5020 ash_msg_and_raise_error("%d: %m", from);
5025 /* Struct def and variable are moved down to the first usage site */
5030 struct redirtab *next;
5033 struct two_fd_t two_fd[];
5035 #define redirlist (G_var.redirlist)
5037 static int need_to_remember(struct redirtab *rp, int fd)
5041 if (!rp) /* remembering was not requested */
5044 for (i = 0; i < rp->pair_count; i++) {
5045 if (rp->two_fd[i].orig == fd) {
5046 /* already remembered */
5053 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5054 static int is_hidden_fd(struct redirtab *rp, int fd)
5057 struct parsefile *pf;
5070 fd |= COPYFD_RESTORE;
5071 for (i = 0; i < rp->pair_count; i++) {
5072 if (rp->two_fd[i].copy == fd) {
5080 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5081 * old file descriptors are stashed away so that the redirection can be
5082 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5083 * standard output, and the standard error if it becomes a duplicate of
5084 * stdout, is saved in memory.
5086 /* flags passed to redirect */
5087 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5088 #define REDIR_SAVEFD2 03 /* set preverrout */
5090 redirect(union node *redir, int flags)
5092 struct redirtab *sv;
5097 int copied_fd2 = -1;
5107 if (flags & REDIR_PUSH) {
5108 union node *tmp = redir;
5111 #if ENABLE_ASH_BASH_COMPAT
5112 if (tmp->nfile.type == NTO2)
5115 tmp = tmp->nfile.next;
5117 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5118 sv->next = redirlist;
5119 sv->pair_count = sv_pos;
5121 sv->nullredirs = g_nullredirs - 1;
5123 while (sv_pos > 0) {
5125 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5130 fd = redir->nfile.fd;
5131 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5132 int right_fd = redir->ndup.dupfd;
5133 /* redirect from/to same file descriptor? */
5136 /* echo >&10 and 10 is a fd opened to the sh script? */
5137 if (is_hidden_fd(sv, right_fd)) {
5138 errno = EBADF; /* as if it is closed */
5139 ash_msg_and_raise_error("%d: %m", right_fd);
5143 newfd = openredirect(redir); /* always >= 0 */
5145 /* Descriptor wasn't open before redirect.
5146 * Mark it for close in the future */
5147 if (need_to_remember(sv, fd)) {
5148 goto remember_to_close;
5153 #if ENABLE_ASH_BASH_COMPAT
5156 if (need_to_remember(sv, fd)) {
5157 /* Copy old descriptor */
5158 i = fcntl(fd, F_DUPFD, 10);
5159 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5160 * are closed in popredir() in the child, preventing them from leaking
5161 * into child. (popredir() also cleans up the mess in case of failures)
5166 /* Strange error (e.g. "too many files" EMFILE?) */
5170 ash_msg_and_raise_error("%d: %m", fd);
5173 /* EBADF: it is not open - good, remember to close it */
5176 } else { /* fd is open, save its copy */
5177 /* "exec fd>&-" should not close fds
5178 * which point to script file(s).
5179 * Force them to be restored afterwards */
5180 if (is_hidden_fd(sv, fd))
5181 i |= COPYFD_RESTORE;
5185 sv->two_fd[sv_pos].orig = fd;
5186 sv->two_fd[sv_pos].copy = i;
5190 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5191 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5192 /* Don't want to trigger debugging */
5196 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5198 } else if (fd != newfd) { /* move newfd to fd */
5199 copyfd(newfd, fd | COPYFD_EXACT);
5200 #if ENABLE_ASH_BASH_COMPAT
5201 if (!(redir->nfile.type == NTO2 && fd == 2))
5205 #if ENABLE_ASH_BASH_COMPAT
5206 if (redir->nfile.type == NTO2 && fd == 1) {
5207 /* We already redirected it to fd 1, now copy it to 2 */
5213 } while ((redir = redir->nfile.next) != NULL);
5216 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5217 preverrout_fd = copied_fd2;
5221 * Undo the effects of the last redirection.
5224 popredir(int drop, int restore)
5226 struct redirtab *rp;
5229 if (--g_nullredirs >= 0)
5233 for (i = 0; i < rp->pair_count; i++) {
5234 int fd = rp->two_fd[i].orig;
5235 int copy = rp->two_fd[i].copy;
5236 if (copy == CLOSED) {
5241 if (copy != EMPTY) {
5242 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5243 copy &= ~COPYFD_RESTORE;
5245 copyfd(copy, fd | COPYFD_EXACT);
5247 close(copy & ~COPYFD_RESTORE);
5250 redirlist = rp->next;
5251 g_nullredirs = rp->nullredirs;
5257 * Undo all redirections. Called on error or interrupt.
5261 * Discard all saved file descriptors.
5264 clearredir(int drop)
5270 popredir(drop, /*restore:*/ 0);
5275 redirectsafe(union node *redir, int flags)
5278 volatile int saveint;
5279 struct jmploc *volatile savehandler = exception_handler;
5280 struct jmploc jmploc;
5283 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5284 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5286 exception_handler = &jmploc;
5287 redirect(redir, flags);
5289 exception_handler = savehandler;
5290 if (err && exception_type != EXERROR)
5291 longjmp(exception_handler->loc, 1);
5292 RESTORE_INT(saveint);
5297 /* ============ Routines to expand arguments to commands
5299 * We have to deal with backquotes, shell variables, and file metacharacters.
5302 #if ENABLE_SH_MATH_SUPPORT
5304 ash_arith(const char *s)
5306 arith_eval_hooks_t math_hooks;
5310 math_hooks.lookupvar = lookupvar;
5311 math_hooks.setvar = setvar2;
5312 math_hooks.endofname = endofname;
5315 result = arith(s, &errcode, &math_hooks);
5318 ash_msg_and_raise_error("exponent less than 0");
5320 ash_msg_and_raise_error("divide by zero");
5322 ash_msg_and_raise_error("expression recursion loop detected");
5323 raise_error_syntax(s);
5334 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5335 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5336 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5337 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5338 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5339 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5340 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5341 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5342 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5346 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5347 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5348 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5349 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5350 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5353 * Structure specifying which parts of the string should be searched
5354 * for IFS characters.
5357 struct ifsregion *next; /* next region in list */
5358 int begoff; /* offset of start of region */
5359 int endoff; /* offset of end of region */
5360 int nulonly; /* search for nul bytes only */
5364 struct strlist *list;
5365 struct strlist **lastp;
5368 /* output of current string */
5369 static char *expdest;
5370 /* list of back quote expressions */
5371 static struct nodelist *argbackq;
5372 /* first struct in list of ifs regions */
5373 static struct ifsregion ifsfirst;
5374 /* last struct in list */
5375 static struct ifsregion *ifslastp;
5376 /* holds expanded arg list */
5377 static struct arglist exparg;
5387 expdest = makestrspace(32, expdest);
5388 len = fmtstr(expdest, 32, arith_t_fmt, num);
5389 STADJUST(len, expdest);
5394 esclen(const char *start, const char *p)
5398 while (p > start && (unsigned char)*--p == CTLESC) {
5405 * Remove any CTLESC characters from a string.
5408 rmescapes(char *str, int flag)
5410 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5414 unsigned protect_against_glob;
5417 p = strpbrk(str, qchars);
5423 if (flag & RMESCAPE_ALLOC) {
5424 size_t len = p - str;
5425 size_t fulllen = len + strlen(p) + 1;
5427 if (flag & RMESCAPE_GROW) {
5428 int strloc = str - (char *)stackblock();
5429 r = makestrspace(fulllen, expdest);
5430 /* p and str may be invalidated by makestrspace */
5431 str = (char *)stackblock() + strloc;
5433 } else if (flag & RMESCAPE_HEAP) {
5434 r = ckmalloc(fulllen);
5436 r = stalloc(fulllen);
5440 q = (char *)memcpy(q, str, len) + len;
5444 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5445 globbing = flag & RMESCAPE_GLOB;
5446 protect_against_glob = globbing;
5448 if ((unsigned char)*p == CTLQUOTEMARK) {
5449 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5450 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5451 // Note: both inquotes and protect_against_glob only affect whether
5452 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5453 inquotes = ~inquotes;
5455 protect_against_glob = globbing;
5459 /* naked back slash */
5460 protect_against_glob = 0;
5463 if ((unsigned char)*p == CTLESC) {
5465 if (protect_against_glob && inquotes && *p != '/') {
5469 protect_against_glob = globbing;
5474 if (flag & RMESCAPE_GROW) {
5476 STADJUST(q - r + 1, expdest);
5480 #define pmatch(a, b) !fnmatch((a), (b), 0)
5483 * Prepare a pattern for a expmeta (internal glob(3)) call.
5485 * Returns an stalloced string.
5488 preglob(const char *pattern, int quoted, int flag)
5490 flag |= RMESCAPE_GLOB;
5492 flag |= RMESCAPE_QUOTED;
5494 return rmescapes((char *)pattern, flag);
5498 * Put a string on the stack.
5501 memtodest(const char *p, size_t len, int syntax, int quotes)
5505 q = makestrspace(quotes ? len * 2 : len, q);
5508 unsigned char c = *p++;
5512 int n = SIT(c, syntax);
5513 if (n == CCTL || n == CBACK)
5523 strtodest(const char *p, int syntax, int quotes)
5525 memtodest(p, strlen(p), syntax, quotes);
5529 * Record the fact that we have to scan this region of the
5530 * string for IFS characters.
5533 recordregion(int start, int end, int nulonly)
5535 struct ifsregion *ifsp;
5537 if (ifslastp == NULL) {
5541 ifsp = ckzalloc(sizeof(*ifsp));
5542 /*ifsp->next = NULL; - ckzalloc did it */
5543 ifslastp->next = ifsp;
5547 ifslastp->begoff = start;
5548 ifslastp->endoff = end;
5549 ifslastp->nulonly = nulonly;
5553 removerecordregions(int endoff)
5555 if (ifslastp == NULL)
5558 if (ifsfirst.endoff > endoff) {
5559 while (ifsfirst.next != NULL) {
5560 struct ifsregion *ifsp;
5562 ifsp = ifsfirst.next->next;
5563 free(ifsfirst.next);
5564 ifsfirst.next = ifsp;
5567 if (ifsfirst.begoff > endoff)
5570 ifslastp = &ifsfirst;
5571 ifsfirst.endoff = endoff;
5576 ifslastp = &ifsfirst;
5577 while (ifslastp->next && ifslastp->next->begoff < endoff)
5578 ifslastp=ifslastp->next;
5579 while (ifslastp->next != NULL) {
5580 struct ifsregion *ifsp;
5582 ifsp = ifslastp->next->next;
5583 free(ifslastp->next);
5584 ifslastp->next = ifsp;
5587 if (ifslastp->endoff > endoff)
5588 ifslastp->endoff = endoff;
5592 exptilde(char *startp, char *p, int flags)
5598 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5603 while ((c = *++p) != '\0') {
5610 if (flags & EXP_VARTILDE)
5620 if (*name == '\0') {
5621 home = lookupvar(homestr);
5623 pw = getpwnam(name);
5628 if (!home || !*home)
5631 startloc = expdest - (char *)stackblock();
5632 strtodest(home, SQSYNTAX, quotes);
5633 recordregion(startloc, expdest - (char *)stackblock(), 0);
5641 * Execute a command inside back quotes. If it's a builtin command, we
5642 * want to save its output in a block obtained from malloc. Otherwise
5643 * we fork off a subprocess and get the output of the command via a pipe.
5644 * Should be called with interrupts off.
5646 struct backcmd { /* result of evalbackcmd */
5647 int fd; /* file descriptor to read from */
5648 int nleft; /* number of chars in buffer */
5649 char *buf; /* buffer */
5650 struct job *jp; /* job structure for command */
5653 /* These forward decls are needed to use "eval" code for backticks handling: */
5654 static uint8_t back_exitstatus; /* exit status of backquoted command */
5655 #define EV_EXIT 01 /* exit after evaluating tree */
5656 static void evaltree(union node *, int);
5658 static void FAST_FUNC
5659 evalbackcmd(union node *n, struct backcmd *result)
5670 saveherefd = herefd;
5678 ash_msg_and_raise_error("pipe call failed");
5679 jp = makejob(/*n,*/ 1);
5680 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5685 copyfd(pip[1], 1 | COPYFD_EXACT);
5689 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5693 result->fd = pip[0];
5696 herefd = saveherefd;
5698 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5699 result->fd, result->buf, result->nleft, result->jp));
5703 * Expand stuff in backwards quotes.
5706 expbackq(union node *cmd, int quoted, int quotes)
5714 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5715 struct stackmark smark;
5718 setstackmark(&smark);
5720 startloc = dest - (char *)stackblock();
5722 evalbackcmd(cmd, &in);
5723 popstackmark(&smark);
5730 memtodest(p, i, syntax, quotes);
5734 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5735 TRACE(("expbackq: read returns %d\n", i));
5744 back_exitstatus = waitforjob(in.jp);
5748 /* Eat all trailing newlines */
5750 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5755 recordregion(startloc, dest - (char *)stackblock(), 0);
5756 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5757 (dest - (char *)stackblock()) - startloc,
5758 (dest - (char *)stackblock()) - startloc,
5759 stackblock() + startloc));
5762 #if ENABLE_SH_MATH_SUPPORT
5764 * Expand arithmetic expression. Backup to start of expression,
5765 * evaluate, place result in (backed up) result, adjust string position.
5778 * This routine is slightly over-complicated for
5779 * efficiency. Next we scan backwards looking for the
5780 * start of arithmetic.
5782 start = stackblock();
5789 while ((unsigned char)*p != CTLARI) {
5793 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5798 esc = esclen(start, p);
5808 removerecordregions(begoff);
5815 rmescapes(p + 2, 0);
5817 len = cvtnum(ash_arith(p + 2));
5820 recordregion(begoff, begoff + len, 0);
5824 /* argstr needs it */
5825 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5828 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5829 * characters to allow for further processing. Otherwise treat
5830 * $@ like $* since no splitting will be performed.
5832 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5833 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5834 * for correct expansion of "B=$A" word.
5837 argstr(char *p, int flags, struct strlist *var_str_list)
5839 static const char spclchars[] ALIGN1 = {
5847 CTLBACKQ | CTLQUOTE,
5848 #if ENABLE_SH_MATH_SUPPORT
5853 const char *reject = spclchars;
5854 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5855 int breakall = flags & EXP_WORD;
5860 if (!(flags & EXP_VARTILDE)) {
5862 } else if (flags & EXP_VARTILDE2) {
5867 if (flags & EXP_TILDE) {
5870 flags &= ~EXP_TILDE;
5873 if (*q == CTLESC && (flags & EXP_QWORD))
5876 p = exptilde(p, q, flags);
5879 startloc = expdest - (char *)stackblock();
5883 length += strcspn(p + length, reject);
5887 #if ENABLE_SH_MATH_SUPPORT
5891 /* c == '=' || c == ':' || c == CTLENDARI */
5897 expdest = stack_nputstr(p, length, expdest);
5898 newloc = expdest - (char *)stackblock();
5899 if (breakall && !inquotes && newloc > startloc) {
5900 recordregion(startloc, newloc, 0);
5911 if (flags & EXP_VARTILDE2) {
5915 flags |= EXP_VARTILDE2;
5920 * sort of a hack - expand tildes in variable
5921 * assignments (after the first '=' and after ':'s).
5930 case CTLENDVAR: /* ??? */
5933 /* "$@" syntax adherence hack */
5935 && memcmp(p, dolatstr, 4) == 0
5936 && ( p[4] == CTLQUOTEMARK
5937 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5940 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
5943 inquotes = !inquotes;
5956 p = evalvar(p, flags, var_str_list);
5960 case CTLBACKQ|CTLQUOTE:
5961 expbackq(argbackq->n, c, quotes);
5962 argbackq = argbackq->next;
5964 #if ENABLE_SH_MATH_SUPPORT
5977 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
5980 // This commented out code was added by James Simmons <jsimmons@infradead.org>
5981 // as part of a larger change when he added support for ${var/a/b}.
5982 // However, it broke # and % operators:
5986 //echo ${var#ab} abcdcd abcdcd
5987 //echo ${var##ab} abcdcd abcdcd
5988 //echo ${var#a*b} abcdcd ababcdcd (!)
5989 //echo ${var##a*b} cdcd cdcd
5990 //echo ${var#?} babcdcd ababcdcd (!)
5991 //echo ${var##?} babcdcd babcdcd
5992 //echo ${var#*} ababcdcd babcdcd (!)
5994 //echo ${var%cd} ababcd ababcd
5995 //echo ${var%%cd} ababcd abab (!)
5996 //echo ${var%c*d} ababcd ababcd
5997 //echo ${var%%c*d} abab ababcdcd (!)
5998 //echo ${var%?} ababcdc ababcdc
5999 //echo ${var%%?} ababcdc ababcdcd (!)
6000 //echo ${var%*} ababcdcd ababcdcd
6003 // Commenting it back out helped. Remove it completely if it really
6006 char *loc, *loc2; //, *full;
6012 int match; // = strlen(str);
6013 const char *s = loc2;
6020 match = pmatch(str, s); // this line was deleted
6022 // // chop off end if its '*'
6023 // full = strrchr(str, '*');
6024 // if (full && full != str)
6027 // // If str starts with '*' replace with s.
6028 // if ((*str == '*') && strlen(s) >= match) {
6029 // full = xstrdup(s);
6030 // strncpy(full+strlen(s)-match+1, str+1, match-1);
6032 // full = xstrndup(str, match);
6033 // match = strncmp(s, full, strlen(full));
6037 if (match) // if (!match)
6039 if (quotes && (unsigned char)*loc == CTLESC)
6048 scanright(char *startp, char *rmesc, char *rmescend, char *pattern, int quotes, int match_at_start)
6050 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6051 int try2optimize = match_at_start;
6057 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6058 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6059 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6061 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6062 * and on each iteration they go back two/one char until they reach the beginning.
6063 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6065 /* TODO: document in what other circumstances we are called. */
6067 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6070 const char *s = loc2;
6071 if (match_at_start) {
6075 match = pmatch(pattern, s);
6076 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6080 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6082 /* Maybe we can optimize this:
6083 * if pattern ends with unescaped *, we can avoid checking
6084 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6085 * it wont match truncated "raw_value_of_" strings too.
6087 unsigned plen = strlen(pattern);
6088 /* Does it end with "*"? */
6089 if (plen != 0 && pattern[--plen] == '*') {
6090 /* "xxxx*" is not escaped */
6091 /* "xxx\*" is escaped */
6092 /* "xx\\*" is not escaped */
6093 /* "x\\\*" is escaped */
6095 while (plen != 0 && pattern[--plen] == '\\')
6098 break; /* ends with unescaped "*" */
6106 esc = esclen(startp, loc);
6117 static void varunset(const char *, const char *, const char *, int) NORETURN;
6119 varunset(const char *end, const char *var, const char *umsg, int varflags)
6125 msg = "parameter not set";
6127 if ((unsigned char)*end == CTLENDVAR) {
6128 if (varflags & VSNUL)
6134 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6137 #if ENABLE_ASH_BASH_COMPAT
6139 parse_sub_pattern(char *arg, int inquotes)
6141 char *idx, *repl = NULL;
6150 /* Only the first '/' seen is our separator */
6157 if (!inquotes && c == '\\' && arg[1] == '\\')
6158 arg++; /* skip both \\, not just first one */
6165 #endif /* ENABLE_ASH_BASH_COMPAT */
6168 subevalvar(char *p, char *str, int strloc, int subtype,
6169 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6171 struct nodelist *saveargbackq = argbackq;
6174 char *rmesc, *rmescend;
6175 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6176 IF_ASH_BASH_COMPAT(char null = '\0';)
6177 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6178 int saveherefd = herefd;
6179 int amount, workloc, resetloc;
6181 char *(*scan)(char*, char*, char*, char*, int, int);
6184 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6186 STPUTC('\0', expdest);
6187 herefd = saveherefd;
6188 argbackq = saveargbackq;
6189 startp = (char *)stackblock() + startloc;
6193 setvar(str, startp, 0);
6194 amount = startp - expdest;
6195 STADJUST(amount, expdest);
6198 #if ENABLE_ASH_BASH_COMPAT
6200 loc = str = stackblock() + strloc;
6201 /* Read POS in ${var:POS:LEN} */
6202 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6203 len = str - startp - 1;
6205 /* *loc != '\0', guaranteed by parser */
6209 /* Adjust the length by the number of escapes */
6210 for (ptr = startp; ptr < (str - 1); ptr++) {
6211 if ((unsigned char)*ptr == CTLESC) {
6219 if (*loc++ == ':') {
6223 /* Skip POS in ${var:POS:LEN} */
6225 while (*loc && *loc != ':') {
6227 * bash complains on: var=qwe; echo ${var:1a:123}
6229 ash_msg_and_raise_error(msg_illnum, str);
6233 if (*loc++ == ':') {
6237 if (pos >= orig_len) {
6241 if (len > (orig_len - pos))
6242 len = orig_len - pos;
6244 for (str = startp; pos; str++, pos--) {
6245 if (quotes && (unsigned char)*str == CTLESC)
6248 for (loc = startp; len; len--) {
6249 if (quotes && (unsigned char)*str == CTLESC)
6254 amount = loc - expdest;
6255 STADJUST(amount, expdest);
6260 varunset(p, str, startp, varflags);
6263 resetloc = expdest - (char *)stackblock();
6265 /* We'll comeback here if we grow the stack while handling
6266 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6267 * stack will need rebasing, and we'll need to remove our work
6270 IF_ASH_BASH_COMPAT(restart:)
6272 amount = expdest - ((char *)stackblock() + resetloc);
6273 STADJUST(-amount, expdest);
6274 startp = (char *)stackblock() + startloc;
6277 rmescend = (char *)stackblock() + strloc;
6279 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6280 if (rmesc != startp) {
6282 startp = (char *)stackblock() + startloc;
6286 str = (char *)stackblock() + strloc;
6287 preglob(str, varflags & VSQUOTE, 0);
6288 workloc = expdest - (char *)stackblock();
6290 #if ENABLE_ASH_BASH_COMPAT
6291 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6295 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6300 /* If there's no pattern to match, return the expansion unmolested */
6309 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6311 /* No match, advance */
6312 char *restart_detect = stackblock();
6314 STPUTC(*idx, expdest);
6315 if (quotes && (unsigned char)*idx == CTLESC) {
6318 STPUTC(*idx, expdest);
6320 if (stackblock() != restart_detect)
6325 /* continue; - prone to quadratic behavior, smarter code: */
6328 if (str[0] == '*') {
6329 /* Pattern is "*foo". If "*foo" does not match "long_string",
6330 * it would never match "ong_string" etc, no point in trying.
6337 if (subtype == VSREPLACEALL) {
6339 if (quotes && (unsigned char)*idx == CTLESC)
6348 for (loc = repl; *loc; loc++) {
6349 char *restart_detect = stackblock();
6350 STPUTC(*loc, expdest);
6351 if (stackblock() != restart_detect)
6356 if (subtype == VSREPLACE) {
6358 char *restart_detect = stackblock();
6359 STPUTC(*idx, expdest);
6360 if (stackblock() != restart_detect)
6369 /* We've put the replaced text into a buffer at workloc, now
6370 * move it to the right place and adjust the stack.
6372 startp = stackblock() + startloc;
6373 STPUTC('\0', expdest);
6374 memmove(startp, stackblock() + workloc, len);
6375 startp[len++] = '\0';
6376 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6377 STADJUST(-amount, expdest);
6380 #endif /* ENABLE_ASH_BASH_COMPAT */
6382 subtype -= VSTRIMRIGHT;
6384 if (subtype < 0 || subtype > 7)
6387 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6388 zero = subtype >> 1;
6389 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6390 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6392 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6395 memmove(startp, loc, str - loc);
6396 loc = startp + (str - loc) - 1;
6399 amount = loc - expdest;
6400 STADJUST(amount, expdest);
6406 * Add the value of a specialized variable to the stack string.
6407 * name parameter (examples):
6408 * ash -c 'echo $1' name:'1='
6409 * ash -c 'echo $qwe' name:'qwe='
6410 * ash -c 'echo $$' name:'$='
6411 * ash -c 'echo ${$}' name:'$='
6412 * ash -c 'echo ${$##q}' name:'$=q'
6413 * ash -c 'echo ${#$}' name:'$='
6414 * note: examples with bad shell syntax:
6415 * ash -c 'echo ${#$1}' name:'$=1'
6416 * ash -c 'echo ${#1#}' name:'1=#'
6418 static NOINLINE ssize_t
6419 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6426 int subtype = varflags & VSTYPE;
6427 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6428 int quoted = varflags & VSQUOTE;
6429 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6439 num = shellparam.nparam;
6447 goto check_1char_name;
6449 expdest = makestrspace(NOPTS, expdest);
6450 for (i = NOPTS - 1; i >= 0; i--) {
6452 USTPUTC(optletters(i), expdest);
6458 /* handles cases similar to ${#$1} */
6459 if (name[2] != '\0')
6460 raise_error_syntax("bad substitution");
6467 if (quoted && (flags & EXP_FULL)) {
6468 /* note: this is not meant as PEOF value */
6469 sep = 1 << CHAR_BIT;
6474 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6475 i = SIT(sep, syntax);
6476 if (quotes && (i == CCTL || i == CBACK))
6482 while ((p = *ap++) != NULL) {
6485 partlen = strlen(p);
6488 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6489 memtodest(p, partlen, syntax, quotes);
6495 if (subtype == VSPLUS || subtype == VSLENGTH) {
6501 /* note: may put NUL despite sep != 0
6502 * (see sep = 1 << CHAR_BIT above) */
6508 } /* case '@' and '*' */
6519 num = atoi(name); /* number(name) fails on ${N#str} etc */
6520 if (num < 0 || num > shellparam.nparam)
6522 p = num ? shellparam.p[num - 1] : arg0;
6525 /* NB: name has form "VAR=..." */
6527 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6528 * which should be considered before we check variables. */
6530 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6534 str = var_str_list->text;
6535 eq = strchr(str, '=');
6536 if (!eq) /* stop at first non-assignment */
6539 if (name_len == (unsigned)(eq - str)
6540 && strncmp(str, name, name_len) == 0
6543 /* goto value; - WRONG! */
6544 /* think "A=1 A=2 B=$A" */
6546 var_str_list = var_str_list->next;
6547 } while (var_str_list);
6551 p = lookupvar(name);
6557 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6558 memtodest(p, len, syntax, quotes);
6562 if (subtype == VSPLUS || subtype == VSLENGTH)
6563 STADJUST(-len, expdest);
6568 * Expand a variable, and return a pointer to the next character in the
6572 evalvar(char *p, int flags, struct strlist *var_str_list)
6583 varflags = (unsigned char) *p++;
6584 subtype = varflags & VSTYPE;
6585 quoted = varflags & VSQUOTE;
6587 easy = (!quoted || (*var == '@' && shellparam.nparam));
6588 startloc = expdest - (char *)stackblock();
6589 p = strchr(p, '=') + 1;
6592 varlen = varvalue(var, varflags, flags, var_str_list);
6593 if (varflags & VSNUL)
6596 if (subtype == VSPLUS) {
6597 varlen = -1 - varlen;
6601 if (subtype == VSMINUS) {
6605 p, flags | EXP_TILDE |
6606 (quoted ? EXP_QWORD : EXP_WORD),
6616 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6618 if (subevalvar(p, var, /* strloc: */ 0,
6619 subtype, startloc, varflags,
6625 * Remove any recorded regions beyond
6628 removerecordregions(startloc);
6638 if (varlen < 0 && uflag)
6639 varunset(p, var, 0, 0);
6641 if (subtype == VSLENGTH) {
6642 cvtnum(varlen > 0 ? varlen : 0);
6646 if (subtype == VSNORMAL) {
6657 case VSTRIMRIGHTMAX:
6658 #if ENABLE_ASH_BASH_COMPAT
6671 * Terminate the string and start recording the pattern
6674 STPUTC('\0', expdest);
6675 patloc = expdest - (char *)stackblock();
6676 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6678 //TODO: | EXP_REDIR too? All other such places do it too
6679 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6682 int amount = expdest - (
6683 (char *)stackblock() + patloc - 1
6685 STADJUST(-amount, expdest);
6687 /* Remove any recorded regions beyond start of variable */
6688 removerecordregions(startloc);
6690 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6694 if (subtype != VSNORMAL) { /* skip to end of alternative */
6697 unsigned char c = *p++;
6700 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6702 argbackq = argbackq->next;
6703 } else if (c == CTLVAR) {
6704 if ((*p++ & VSTYPE) != VSNORMAL)
6706 } else if (c == CTLENDVAR) {
6716 * Break the argument string into pieces based upon IFS and add the
6717 * strings to the argument list. The regions of the string to be
6718 * searched for IFS characters have been stored by recordregion.
6721 ifsbreakup(char *string, struct arglist *arglist)
6723 struct ifsregion *ifsp;
6728 const char *ifs, *realifs;
6733 if (ifslastp != NULL) {
6736 realifs = ifsset() ? ifsval() : defifs;
6739 p = string + ifsp->begoff;
6740 nulonly = ifsp->nulonly;
6741 ifs = nulonly ? nullstr : realifs;
6743 while (p < string + ifsp->endoff) {
6745 if ((unsigned char)*p == CTLESC)
6747 if (!strchr(ifs, *p)) {
6752 ifsspc = (strchr(defifs, *p) != NULL);
6753 /* Ignore IFS whitespace at start */
6754 if (q == start && ifsspc) {
6760 sp = stzalloc(sizeof(*sp));
6762 *arglist->lastp = sp;
6763 arglist->lastp = &sp->next;
6767 if (p >= string + ifsp->endoff) {
6771 if ((unsigned char)*p == CTLESC)
6773 if (strchr(ifs, *p) == NULL) {
6777 if (strchr(defifs, *p) == NULL) {
6792 } while (ifsp != NULL);
6801 sp = stzalloc(sizeof(*sp));
6803 *arglist->lastp = sp;
6804 arglist->lastp = &sp->next;
6810 struct ifsregion *p;
6815 struct ifsregion *ifsp;
6821 ifsfirst.next = NULL;
6826 * Add a file name to the list.
6829 addfname(const char *name)
6833 sp = stzalloc(sizeof(*sp));
6834 sp->text = ststrdup(name);
6836 exparg.lastp = &sp->next;
6839 static char *expdir;
6842 * Do metacharacter (i.e. *, ?, [...]) expansion.
6845 expmeta(char *enddir, char *name)
6860 for (p = name; *p; p++) {
6861 if (*p == '*' || *p == '?')
6863 else if (*p == '[') {
6870 if (*q == '/' || *q == '\0')
6877 } else if (*p == '\\')
6879 else if (*p == '/') {
6886 if (metaflag == 0) { /* we've reached the end of the file name */
6887 if (enddir != expdir)
6895 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6906 } while (p < start);
6908 if (enddir == expdir) {
6910 } else if (enddir == expdir + 1 && *expdir == '/') {
6919 if (enddir != expdir)
6921 if (*endname == 0) {
6933 while (!pending_int && (dp = readdir(dirp)) != NULL) {
6934 if (dp->d_name[0] == '.' && !matchdot)
6936 if (pmatch(start, dp->d_name)) {
6938 strcpy(enddir, dp->d_name);
6941 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6944 expmeta(p, endname);
6953 static struct strlist *
6954 msort(struct strlist *list, int len)
6956 struct strlist *p, *q = NULL;
6957 struct strlist **lpp;
6965 for (n = half; --n >= 0;) {
6969 q->next = NULL; /* terminate first half of list */
6970 q = msort(list, half); /* sort first half of list */
6971 p = msort(p, len - half); /* sort second half */
6974 #if ENABLE_LOCALE_SUPPORT
6975 if (strcoll(p->text, q->text) < 0)
6977 if (strcmp(p->text, q->text) < 0)
7001 * Sort the results of file name expansion. It calculates the number of
7002 * strings to sort and then calls msort (short for merge sort) to do the
7005 static struct strlist *
7006 expsort(struct strlist *str)
7012 for (sp = str; sp; sp = sp->next)
7014 return msort(str, len);
7018 expandmeta(struct strlist *str /*, int flag*/)
7020 static const char metachars[] ALIGN1 = {
7023 /* TODO - EXP_REDIR */
7026 struct strlist **savelastp;
7032 if (!strpbrk(str->text, metachars))
7034 savelastp = exparg.lastp;
7037 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7039 int i = strlen(str->text);
7040 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7048 if (exparg.lastp == savelastp) {
7053 *exparg.lastp = str;
7054 rmescapes(str->text, 0);
7055 exparg.lastp = &str->next;
7057 *exparg.lastp = NULL;
7058 *savelastp = sp = expsort(*savelastp);
7059 while (sp->next != NULL)
7061 exparg.lastp = &sp->next;
7068 * Perform variable substitution and command substitution on an argument,
7069 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7070 * perform splitting and file name expansion. When arglist is NULL, perform
7071 * here document expansion.
7074 expandarg(union node *arg, struct arglist *arglist, int flag)
7079 argbackq = arg->narg.backquote;
7080 STARTSTACKSTR(expdest);
7081 ifsfirst.next = NULL;
7083 argstr(arg->narg.text, flag,
7084 /* var_str_list: */ arglist ? arglist->list : NULL);
7085 p = _STPUTC('\0', expdest);
7087 if (arglist == NULL) {
7088 return; /* here document expanded */
7090 p = grabstackstr(p);
7091 exparg.lastp = &exparg.list;
7095 if (flag & EXP_FULL) {
7096 ifsbreakup(p, &exparg);
7097 *exparg.lastp = NULL;
7098 exparg.lastp = &exparg.list;
7099 expandmeta(exparg.list /*, flag*/);
7101 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7103 sp = stzalloc(sizeof(*sp));
7106 exparg.lastp = &sp->next;
7110 *exparg.lastp = NULL;
7112 *arglist->lastp = exparg.list;
7113 arglist->lastp = exparg.lastp;
7118 * Expand shell variables and backquotes inside a here document.
7121 expandhere(union node *arg, int fd)
7124 expandarg(arg, (struct arglist *)NULL, 0);
7125 full_write(fd, stackblock(), expdest - (char *)stackblock());
7129 * Returns true if the pattern matches the string.
7132 patmatch(char *pattern, const char *string)
7134 return pmatch(preglob(pattern, 0, 0), string);
7138 * See if a pattern matches in a case statement.
7141 casematch(union node *pattern, char *val)
7143 struct stackmark smark;
7146 setstackmark(&smark);
7147 argbackq = pattern->narg.backquote;
7148 STARTSTACKSTR(expdest);
7150 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7151 /* var_str_list: */ NULL);
7152 STACKSTRNUL(expdest);
7153 result = patmatch(stackblock(), val);
7154 popstackmark(&smark);
7159 /* ============ find_command */
7163 int (*builtin)(int, char **) FAST_FUNC;
7164 /* unsigned flags; */
7166 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7167 /* "regular" builtins always take precedence over commands,
7168 * regardless of PATH=....%builtin... position */
7169 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7170 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7173 smallint cmdtype; /* CMDxxx */
7176 /* index >= 0 for commands without path (slashes) */
7177 /* (TODO: what exactly does the value mean? PATH position?) */
7178 /* index == -1 for commands with slashes */
7179 /* index == (-2 - applet_no) for NOFORK applets */
7180 const struct builtincmd *cmd;
7181 struct funcnode *func;
7184 /* values of cmdtype */
7185 #define CMDUNKNOWN -1 /* no entry in table for command */
7186 #define CMDNORMAL 0 /* command is an executable program */
7187 #define CMDFUNCTION 1 /* command is a shell function */
7188 #define CMDBUILTIN 2 /* command is a shell builtin */
7190 /* action to find_command() */
7191 #define DO_ERR 0x01 /* prints errors */
7192 #define DO_ABS 0x02 /* checks absolute paths */
7193 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7194 #define DO_ALTPATH 0x08 /* using alternate path */
7195 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7197 static void find_command(char *, struct cmdentry *, int, const char *);
7200 /* ============ Hashing commands */
7203 * When commands are first encountered, they are entered in a hash table.
7204 * This ensures that a full path search will not have to be done for them
7205 * on each invocation.
7207 * We should investigate converting to a linear search, even though that
7208 * would make the command name "hash" a misnomer.
7212 struct tblentry *next; /* next entry in hash chain */
7213 union param param; /* definition of builtin function */
7214 smallint cmdtype; /* CMDxxx */
7215 char rehash; /* if set, cd done since entry created */
7216 char cmdname[1]; /* name of command */
7219 static struct tblentry **cmdtable;
7220 #define INIT_G_cmdtable() do { \
7221 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7224 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7228 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7232 #if ENABLE_FEATURE_SH_STANDALONE
7233 if (applet_no >= 0) {
7234 if (APPLET_IS_NOEXEC(applet_no)) {
7237 run_applet_no_and_exit(applet_no, argv);
7239 /* re-exec ourselves with the new arguments */
7240 execve(bb_busybox_exec_path, argv, envp);
7241 /* If they called chroot or otherwise made the binary no longer
7242 * executable, fall through */
7249 execve(cmd, argv, envp);
7250 } while (errno == EINTR);
7252 execve(cmd, argv, envp);
7258 if (errno == ENOEXEC) {
7262 for (ap = argv; *ap; ap++)
7264 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7266 ap[0] = cmd = (char *)DEFAULT_SHELL;
7269 while ((*ap++ = *argv++) != NULL)
7278 * Exec a program. Never returns. If you change this routine, you may
7279 * have to change the find_command routine as well.
7281 static void shellexec(char **, const char *, int) NORETURN;
7283 shellexec(char **argv, const char *path, int idx)
7289 #if ENABLE_FEATURE_SH_STANDALONE
7293 clearredir(/*drop:*/ 1);
7294 envp = listvars(VEXPORT, VUNSET, 0);
7295 if (strchr(argv[0], '/') != NULL
7296 #if ENABLE_FEATURE_SH_STANDALONE
7297 || (applet_no = find_applet_by_name(argv[0])) >= 0
7300 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7304 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7305 if (--idx < 0 && pathopt == NULL) {
7306 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7307 if (errno != ENOENT && errno != ENOTDIR)
7314 /* Map to POSIX errors */
7326 exitstatus = exerrno;
7327 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7328 argv[0], e, suppress_int));
7329 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7334 printentry(struct tblentry *cmdp)
7340 idx = cmdp->param.index;
7343 name = path_advance(&path, cmdp->cmdname);
7345 } while (--idx >= 0);
7346 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7350 * Clear out command entries. The argument specifies the first entry in
7351 * PATH which has changed.
7354 clearcmdentry(int firstchange)
7356 struct tblentry **tblp;
7357 struct tblentry **pp;
7358 struct tblentry *cmdp;
7361 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7363 while ((cmdp = *pp) != NULL) {
7364 if ((cmdp->cmdtype == CMDNORMAL &&
7365 cmdp->param.index >= firstchange)
7366 || (cmdp->cmdtype == CMDBUILTIN &&
7367 builtinloc >= firstchange)
7380 * Locate a command in the command hash table. If "add" is nonzero,
7381 * add the command to the table if it is not already present. The
7382 * variable "lastcmdentry" is set to point to the address of the link
7383 * pointing to the entry, so that delete_cmd_entry can delete the
7386 * Interrupts must be off if called with add != 0.
7388 static struct tblentry **lastcmdentry;
7390 static struct tblentry *
7391 cmdlookup(const char *name, int add)
7393 unsigned int hashval;
7395 struct tblentry *cmdp;
7396 struct tblentry **pp;
7399 hashval = (unsigned char)*p << 4;
7401 hashval += (unsigned char)*p++;
7403 pp = &cmdtable[hashval % CMDTABLESIZE];
7404 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7405 if (strcmp(cmdp->cmdname, name) == 0)
7409 if (add && cmdp == NULL) {
7410 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7412 /* + 1 - already done because
7413 * tblentry::cmdname is char[1] */);
7414 /*cmdp->next = NULL; - ckzalloc did it */
7415 cmdp->cmdtype = CMDUNKNOWN;
7416 strcpy(cmdp->cmdname, name);
7423 * Delete the command entry returned on the last lookup.
7426 delete_cmd_entry(void)
7428 struct tblentry *cmdp;
7431 cmdp = *lastcmdentry;
7432 *lastcmdentry = cmdp->next;
7433 if (cmdp->cmdtype == CMDFUNCTION)
7434 freefunc(cmdp->param.func);
7440 * Add a new command entry, replacing any existing command entry for
7441 * the same name - except special builtins.
7444 addcmdentry(char *name, struct cmdentry *entry)
7446 struct tblentry *cmdp;
7448 cmdp = cmdlookup(name, 1);
7449 if (cmdp->cmdtype == CMDFUNCTION) {
7450 freefunc(cmdp->param.func);
7452 cmdp->cmdtype = entry->cmdtype;
7453 cmdp->param = entry->u;
7457 static int FAST_FUNC
7458 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7460 struct tblentry **pp;
7461 struct tblentry *cmdp;
7463 struct cmdentry entry;
7466 if (nextopt("r") != '\0') {
7471 if (*argptr == NULL) {
7472 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7473 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7474 if (cmdp->cmdtype == CMDNORMAL)
7482 while ((name = *argptr) != NULL) {
7483 cmdp = cmdlookup(name, 0);
7485 && (cmdp->cmdtype == CMDNORMAL
7486 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7490 find_command(name, &entry, DO_ERR, pathval());
7491 if (entry.cmdtype == CMDUNKNOWN)
7499 * Called when a cd is done. Marks all commands so the next time they
7500 * are executed they will be rehashed.
7505 struct tblentry **pp;
7506 struct tblentry *cmdp;
7508 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7509 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7510 if (cmdp->cmdtype == CMDNORMAL
7511 || (cmdp->cmdtype == CMDBUILTIN
7512 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7522 * Fix command hash table when PATH changed.
7523 * Called before PATH is changed. The argument is the new value of PATH;
7524 * pathval() still returns the old value at this point.
7525 * Called with interrupts off.
7527 static void FAST_FUNC
7528 changepath(const char *new)
7536 firstchange = 9999; /* assume no change */
7542 if ((*old == '\0' && *new == ':')
7543 || (*old == ':' && *new == '\0'))
7545 old = new; /* ignore subsequent differences */
7549 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7555 if (builtinloc < 0 && idx_bltin >= 0)
7556 builtinloc = idx_bltin; /* zap builtins */
7557 if (builtinloc >= 0 && idx_bltin < 0)
7559 clearcmdentry(firstchange);
7560 builtinloc = idx_bltin;
7575 #define TENDBQUOTE 12
7592 typedef smallint token_id_t;
7594 /* first char is indicating which tokens mark the end of a list */
7595 static const char *const tokname_array[] = {
7609 #define KWDOFFSET 13
7610 /* the following are keywords */
7632 static char buf[16];
7635 //if (tok < TSEMI) return tokname_array[tok] + 1;
7636 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7641 sprintf(buf + (tok >= TSEMI), "%s%c",
7642 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7646 /* Wrapper around strcmp for qsort/bsearch/... */
7648 pstrcmp(const void *a, const void *b)
7650 return strcmp((char*) a, (*(char**) b) + 1);
7653 static const char *const *
7654 findkwd(const char *s)
7656 return bsearch(s, tokname_array + KWDOFFSET,
7657 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7658 sizeof(tokname_array[0]), pstrcmp);
7662 * Locate and print what a word is...
7665 describe_command(char *command, int describe_command_verbose)
7667 struct cmdentry entry;
7668 struct tblentry *cmdp;
7669 #if ENABLE_ASH_ALIAS
7670 const struct alias *ap;
7672 const char *path = pathval();
7674 if (describe_command_verbose) {
7678 /* First look at the keywords */
7679 if (findkwd(command)) {
7680 out1str(describe_command_verbose ? " is a shell keyword" : command);
7684 #if ENABLE_ASH_ALIAS
7685 /* Then look at the aliases */
7686 ap = lookupalias(command, 0);
7688 if (!describe_command_verbose) {
7693 out1fmt(" is an alias for %s", ap->val);
7697 /* Then check if it is a tracked alias */
7698 cmdp = cmdlookup(command, 0);
7700 entry.cmdtype = cmdp->cmdtype;
7701 entry.u = cmdp->param;
7703 /* Finally use brute force */
7704 find_command(command, &entry, DO_ABS, path);
7707 switch (entry.cmdtype) {
7709 int j = entry.u.index;
7715 p = path_advance(&path, command);
7719 if (describe_command_verbose) {
7721 (cmdp ? " a tracked alias for" : nullstr), p
7730 if (describe_command_verbose) {
7731 out1str(" is a shell function");
7738 if (describe_command_verbose) {
7739 out1fmt(" is a %sshell builtin",
7740 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7741 "special " : nullstr
7749 if (describe_command_verbose) {
7750 out1str(": not found\n");
7759 static int FAST_FUNC
7760 typecmd(int argc UNUSED_PARAM, char **argv)
7766 /* type -p ... ? (we don't bother checking for 'p') */
7767 if (argv[1] && argv[1][0] == '-') {
7772 err |= describe_command(argv[i++], verbose);
7777 #if ENABLE_ASH_CMDCMD
7778 static int FAST_FUNC
7779 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7787 while ((c = nextopt("pvV")) != '\0')
7789 verify |= VERIFY_VERBOSE;
7791 verify |= VERIFY_BRIEF;
7796 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7797 if (verify && (*argptr != NULL)) {
7798 return describe_command(*argptr, verify - VERIFY_BRIEF);
7806 /* ============ eval.c */
7808 static int funcblocksize; /* size of structures in function */
7809 static int funcstringsize; /* size of strings in node */
7810 static void *funcblock; /* block to allocate function from */
7811 static char *funcstring; /* block to allocate strings from */
7813 /* flags in argument to evaltree */
7814 #define EV_EXIT 01 /* exit after evaluating tree */
7815 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7816 #define EV_BACKCMD 04 /* command executing within back quotes */
7818 static const uint8_t nodesize[N_NUMBER] = {
7819 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7820 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7821 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7822 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7823 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7824 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7825 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7826 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7827 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7828 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7829 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7830 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7831 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7832 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7833 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7834 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7835 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7836 #if ENABLE_ASH_BASH_COMPAT
7837 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7839 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7840 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7841 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7842 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7843 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7844 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7845 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7846 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7847 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7850 static void calcsize(union node *n);
7853 sizenodelist(struct nodelist *lp)
7856 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7863 calcsize(union node *n)
7867 funcblocksize += nodesize[n->type];
7870 calcsize(n->ncmd.redirect);
7871 calcsize(n->ncmd.args);
7872 calcsize(n->ncmd.assign);
7875 sizenodelist(n->npipe.cmdlist);
7880 calcsize(n->nredir.redirect);
7881 calcsize(n->nredir.n);
7888 calcsize(n->nbinary.ch2);
7889 calcsize(n->nbinary.ch1);
7892 calcsize(n->nif.elsepart);
7893 calcsize(n->nif.ifpart);
7894 calcsize(n->nif.test);
7897 funcstringsize += strlen(n->nfor.var) + 1;
7898 calcsize(n->nfor.body);
7899 calcsize(n->nfor.args);
7902 calcsize(n->ncase.cases);
7903 calcsize(n->ncase.expr);
7906 calcsize(n->nclist.body);
7907 calcsize(n->nclist.pattern);
7908 calcsize(n->nclist.next);
7912 sizenodelist(n->narg.backquote);
7913 funcstringsize += strlen(n->narg.text) + 1;
7914 calcsize(n->narg.next);
7917 #if ENABLE_ASH_BASH_COMPAT
7924 calcsize(n->nfile.fname);
7925 calcsize(n->nfile.next);
7929 calcsize(n->ndup.vname);
7930 calcsize(n->ndup.next);
7934 calcsize(n->nhere.doc);
7935 calcsize(n->nhere.next);
7938 calcsize(n->nnot.com);
7944 nodeckstrdup(char *s)
7946 char *rtn = funcstring;
7948 strcpy(funcstring, s);
7949 funcstring += strlen(s) + 1;
7953 static union node *copynode(union node *);
7955 static struct nodelist *
7956 copynodelist(struct nodelist *lp)
7958 struct nodelist *start;
7959 struct nodelist **lpp;
7964 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7965 (*lpp)->n = copynode(lp->n);
7967 lpp = &(*lpp)->next;
7974 copynode(union node *n)
7981 funcblock = (char *) funcblock + nodesize[n->type];
7985 new->ncmd.redirect = copynode(n->ncmd.redirect);
7986 new->ncmd.args = copynode(n->ncmd.args);
7987 new->ncmd.assign = copynode(n->ncmd.assign);
7990 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7991 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
7996 new->nredir.redirect = copynode(n->nredir.redirect);
7997 new->nredir.n = copynode(n->nredir.n);
8004 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8005 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8008 new->nif.elsepart = copynode(n->nif.elsepart);
8009 new->nif.ifpart = copynode(n->nif.ifpart);
8010 new->nif.test = copynode(n->nif.test);
8013 new->nfor.var = nodeckstrdup(n->nfor.var);
8014 new->nfor.body = copynode(n->nfor.body);
8015 new->nfor.args = copynode(n->nfor.args);
8018 new->ncase.cases = copynode(n->ncase.cases);
8019 new->ncase.expr = copynode(n->ncase.expr);
8022 new->nclist.body = copynode(n->nclist.body);
8023 new->nclist.pattern = copynode(n->nclist.pattern);
8024 new->nclist.next = copynode(n->nclist.next);
8028 new->narg.backquote = copynodelist(n->narg.backquote);
8029 new->narg.text = nodeckstrdup(n->narg.text);
8030 new->narg.next = copynode(n->narg.next);
8033 #if ENABLE_ASH_BASH_COMPAT
8040 new->nfile.fname = copynode(n->nfile.fname);
8041 new->nfile.fd = n->nfile.fd;
8042 new->nfile.next = copynode(n->nfile.next);
8046 new->ndup.vname = copynode(n->ndup.vname);
8047 new->ndup.dupfd = n->ndup.dupfd;
8048 new->ndup.fd = n->ndup.fd;
8049 new->ndup.next = copynode(n->ndup.next);
8053 new->nhere.doc = copynode(n->nhere.doc);
8054 new->nhere.fd = n->nhere.fd;
8055 new->nhere.next = copynode(n->nhere.next);
8058 new->nnot.com = copynode(n->nnot.com);
8061 new->type = n->type;
8066 * Make a copy of a parse tree.
8068 static struct funcnode *
8069 copyfunc(union node *n)
8074 funcblocksize = offsetof(struct funcnode, n);
8077 blocksize = funcblocksize;
8078 f = ckmalloc(blocksize + funcstringsize);
8079 funcblock = (char *) f + offsetof(struct funcnode, n);
8080 funcstring = (char *) f + blocksize;
8087 * Define a shell function.
8090 defun(char *name, union node *func)
8092 struct cmdentry entry;
8095 entry.cmdtype = CMDFUNCTION;
8096 entry.u.func = copyfunc(func);
8097 addcmdentry(name, &entry);
8101 /* Reasons for skipping commands (see comment on breakcmd routine) */
8102 #define SKIPBREAK (1 << 0)
8103 #define SKIPCONT (1 << 1)
8104 #define SKIPFUNC (1 << 2)
8105 #define SKIPFILE (1 << 3)
8106 #define SKIPEVAL (1 << 4)
8107 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8108 static int skipcount; /* number of levels to skip */
8109 static int funcnest; /* depth of function calls */
8110 static int loopnest; /* current loop nesting level */
8112 /* Forward decl way out to parsing code - dotrap needs it */
8113 static int evalstring(char *s, int mask);
8115 /* Called to execute a trap.
8116 * Single callsite - at the end of evaltree().
8117 * If we return non-zero, exaltree raises EXEXIT exception.
8119 * Perhaps we should avoid entering new trap handlers
8120 * while we are executing a trap handler. [is it a TODO?]
8129 savestatus = exitstatus;
8133 TRACE(("dotrap entered\n"));
8134 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8141 /* non-trapped SIGINT is handled separately by raise_interrupt,
8142 * don't upset it by resetting gotsig[SIGINT-1] */
8143 if (sig == SIGINT && !t)
8146 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8150 want_exexit = evalstring(t, SKIPEVAL);
8151 exitstatus = savestatus;
8153 TRACE(("dotrap returns %d\n", want_exexit));
8158 TRACE(("dotrap returns 0\n"));
8162 /* forward declarations - evaluation is fairly recursive business... */
8163 static void evalloop(union node *, int);
8164 static void evalfor(union node *, int);
8165 static void evalcase(union node *, int);
8166 static void evalsubshell(union node *, int);
8167 static void expredir(union node *);
8168 static void evalpipe(union node *, int);
8169 static void evalcommand(union node *, int);
8170 static int evalbltin(const struct builtincmd *, int, char **);
8171 static void prehash(union node *);
8174 * Evaluate a parse tree. The value is left in the global variable
8178 evaltree(union node *n, int flags)
8180 struct jmploc *volatile savehandler = exception_handler;
8181 struct jmploc jmploc;
8183 void (*evalfn)(union node *, int);
8187 SAVE_INT(int_level);
8190 TRACE(("evaltree(NULL) called\n"));
8193 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8195 exception_handler = &jmploc;
8197 int err = setjmp(jmploc.loc);
8199 /* if it was a signal, check for trap handlers */
8200 if (exception_type == EXSIG) {
8201 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8202 exception_type, err));
8205 /* continue on the way out */
8206 TRACE(("exception %d in evaltree, propagating err=%d\n",
8207 exception_type, err));
8208 exception_handler = savehandler;
8209 longjmp(exception_handler->loc, err);
8216 out1fmt("Node type = %d\n", n->type);
8221 evaltree(n->nnot.com, EV_TESTED);
8222 status = !exitstatus;
8225 expredir(n->nredir.redirect);
8226 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8228 evaltree(n->nredir.n, flags & EV_TESTED);
8229 status = exitstatus;
8231 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8234 evalfn = evalcommand;
8236 if (eflag && !(flags & EV_TESTED))
8248 evalfn = evalsubshell;
8261 #error NAND + 1 != NOR
8263 #if NOR + 1 != NSEMI
8264 #error NOR + 1 != NSEMI
8266 unsigned is_or = n->type - NAND;
8269 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8271 if (!exitstatus == is_or)
8284 evaltree(n->nif.test, EV_TESTED);
8287 if (exitstatus == 0) {
8291 if (n->nif.elsepart) {
8292 n = n->nif.elsepart;
8297 defun(n->narg.text, n->narg.next);
8301 exitstatus = status;
8306 exception_handler = savehandler;
8308 if (checkexit & exitstatus)
8309 evalskip |= SKIPEVAL;
8310 else if (pending_sig && dotrap())
8313 if (flags & EV_EXIT) {
8315 raise_exception(EXEXIT);
8318 RESTORE_INT(int_level);
8319 TRACE(("leaving evaltree (no interrupts)\n"));
8322 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8325 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8328 evalloop(union node *n, int flags)
8338 evaltree(n->nbinary.ch1, EV_TESTED);
8341 if (evalskip == SKIPCONT && --skipcount <= 0) {
8345 if (evalskip == SKIPBREAK && --skipcount <= 0)
8350 if (n->type != NWHILE)
8354 evaltree(n->nbinary.ch2, flags);
8355 status = exitstatus;
8360 exitstatus = status;
8364 evalfor(union node *n, int flags)
8366 struct arglist arglist;
8369 struct stackmark smark;
8371 setstackmark(&smark);
8372 arglist.list = NULL;
8373 arglist.lastp = &arglist.list;
8374 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8375 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8380 *arglist.lastp = NULL;
8385 for (sp = arglist.list; sp; sp = sp->next) {
8386 setvar(n->nfor.var, sp->text, 0);
8387 evaltree(n->nfor.body, flags);
8389 if (evalskip == SKIPCONT && --skipcount <= 0) {
8393 if (evalskip == SKIPBREAK && --skipcount <= 0)
8400 popstackmark(&smark);
8404 evalcase(union node *n, int flags)
8408 struct arglist arglist;
8409 struct stackmark smark;
8411 setstackmark(&smark);
8412 arglist.list = NULL;
8413 arglist.lastp = &arglist.list;
8414 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8416 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8417 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8418 if (casematch(patp, arglist.list->text)) {
8419 if (evalskip == 0) {
8420 evaltree(cp->nclist.body, flags);
8427 popstackmark(&smark);
8431 * Kick off a subshell to evaluate a tree.
8434 evalsubshell(union node *n, int flags)
8437 int backgnd = (n->type == NBACKGND);
8440 expredir(n->nredir.redirect);
8441 if (!backgnd && flags & EV_EXIT && !trap[0])
8444 jp = makejob(/*n,*/ 1);
8445 if (forkshell(jp, n, backgnd) == 0) {
8449 flags &=~ EV_TESTED;
8451 redirect(n->nredir.redirect, 0);
8452 evaltreenr(n->nredir.n, flags);
8457 status = waitforjob(jp);
8458 exitstatus = status;
8463 * Compute the names of the files in a redirection list.
8465 static void fixredir(union node *, const char *, int);
8467 expredir(union node *n)
8471 for (redir = n; redir; redir = redir->nfile.next) {
8475 fn.lastp = &fn.list;
8476 switch (redir->type) {
8480 #if ENABLE_ASH_BASH_COMPAT
8485 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8486 #if ENABLE_ASH_BASH_COMPAT
8489 redir->nfile.expfname = fn.list->text;
8492 case NTOFD: /* >& */
8493 if (redir->ndup.vname) {
8494 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8495 if (fn.list == NULL)
8496 ash_msg_and_raise_error("redir error");
8497 #if ENABLE_ASH_BASH_COMPAT
8498 //FIXME: we used expandarg with different args!
8499 if (!isdigit_str9(fn.list->text)) {
8500 /* >&file, not >&fd */
8501 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8502 ash_msg_and_raise_error("redir error");
8504 goto store_expfname;
8507 fixredir(redir, fn.list->text, 1);
8515 * Evaluate a pipeline. All the processes in the pipeline are children
8516 * of the process creating the pipeline. (This differs from some versions
8517 * of the shell, which make the last process in a pipeline the parent
8521 evalpipe(union node *n, int flags)
8524 struct nodelist *lp;
8529 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8531 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8535 jp = makejob(/*n,*/ pipelen);
8537 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8541 if (pipe(pip) < 0) {
8543 ash_msg_and_raise_error("pipe call failed");
8546 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8559 evaltreenr(lp->n, flags);
8565 /* Don't want to trigger debugging */
8569 if (n->npipe.pipe_backgnd == 0) {
8570 exitstatus = waitforjob(jp);
8571 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8577 * Controls whether the shell is interactive or not.
8580 setinteractive(int on)
8582 static smallint is_interactive;
8584 if (++on == is_interactive)
8586 is_interactive = on;
8590 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8591 if (is_interactive > 1) {
8592 /* Looks like they want an interactive shell */
8593 static smallint did_banner;
8596 /* note: ash and hush share this string */
8597 out1fmt("\n\n%s %s\n"
8598 "Enter 'help' for a list of built-in commands."
8601 "built-in shell (ash)"
8615 setinteractive(iflag);
8617 #if ENABLE_FEATURE_EDITING_VI
8619 line_input_state->flags |= VI_MODE;
8621 line_input_state->flags &= ~VI_MODE;
8623 viflag = 0; /* forcibly keep the option off */
8627 static struct localvar *localvars;
8630 * Called after a function returns.
8631 * Interrupts must be off.
8636 struct localvar *lvp;
8639 while ((lvp = localvars) != NULL) {
8640 localvars = lvp->next;
8642 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8643 if (vp == NULL) { /* $- saved */
8644 memcpy(optlist, lvp->text, sizeof(optlist));
8645 free((char*)lvp->text);
8647 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8651 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8652 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8653 free((char*)vp->text);
8654 vp->flags = lvp->flags;
8655 vp->text = lvp->text;
8662 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8664 volatile struct shparam saveparam;
8665 struct localvar *volatile savelocalvars;
8666 struct jmploc *volatile savehandler;
8667 struct jmploc jmploc;
8670 saveparam = shellparam;
8671 savelocalvars = localvars;
8672 e = setjmp(jmploc.loc);
8677 savehandler = exception_handler;
8678 exception_handler = &jmploc;
8680 shellparam.malloced = 0;
8684 shellparam.nparam = argc - 1;
8685 shellparam.p = argv + 1;
8686 #if ENABLE_ASH_GETOPTS
8687 shellparam.optind = 1;
8688 shellparam.optoff = -1;
8690 evaltree(&func->n, flags & EV_TESTED);
8696 localvars = savelocalvars;
8697 freeparam(&shellparam);
8698 shellparam = saveparam;
8699 exception_handler = savehandler;
8701 evalskip &= ~SKIPFUNC;
8705 #if ENABLE_ASH_CMDCMD
8707 parse_command_args(char **argv, const char **path)
8720 if (c == '-' && !*cp) {
8727 *path = bb_default_path;
8730 /* run 'typecmd' for other options */
8741 * Make a variable a local variable. When a variable is made local, it's
8742 * value and flags are saved in a localvar structure. The saved values
8743 * will be restored when the shell function returns. We handle the name
8744 * "-" as a special case.
8749 struct localvar *lvp;
8754 lvp = ckzalloc(sizeof(struct localvar));
8755 if (LONE_DASH(name)) {
8757 p = ckmalloc(sizeof(optlist));
8758 lvp->text = memcpy(p, optlist, sizeof(optlist));
8763 vpp = hashvar(name);
8764 vp = *findvar(vpp, name);
8765 eq = strchr(name, '=');
8768 setvareq(name, VSTRFIXED);
8770 setvar(name, NULL, VSTRFIXED);
8771 vp = *vpp; /* the new variable */
8772 lvp->flags = VUNSET;
8774 lvp->text = vp->text;
8775 lvp->flags = vp->flags;
8776 vp->flags |= VSTRFIXED|VTEXTFIXED;
8782 lvp->next = localvars;
8788 * The "local" command.
8790 static int FAST_FUNC
8791 localcmd(int argc UNUSED_PARAM, char **argv)
8796 while ((name = *argv++) != NULL) {
8802 static int FAST_FUNC
8803 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8808 static int FAST_FUNC
8809 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8814 static int FAST_FUNC
8815 execcmd(int argc UNUSED_PARAM, char **argv)
8818 iflag = 0; /* exit on error */
8821 shellexec(argv + 1, pathval(), 0);
8827 * The return command.
8829 static int FAST_FUNC
8830 returncmd(int argc UNUSED_PARAM, char **argv)
8833 * If called outside a function, do what ksh does;
8834 * skip the rest of the file.
8836 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8837 return argv[1] ? number(argv[1]) : exitstatus;
8840 /* Forward declarations for builtintab[] */
8841 static int breakcmd(int, char **) FAST_FUNC;
8842 static int dotcmd(int, char **) FAST_FUNC;
8843 static int evalcmd(int, char **) FAST_FUNC;
8844 static int exitcmd(int, char **) FAST_FUNC;
8845 static int exportcmd(int, char **) FAST_FUNC;
8846 #if ENABLE_ASH_GETOPTS
8847 static int getoptscmd(int, char **) FAST_FUNC;
8849 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8850 static int helpcmd(int, char **) FAST_FUNC;
8852 #if ENABLE_SH_MATH_SUPPORT
8853 static int letcmd(int, char **) FAST_FUNC;
8855 static int readcmd(int, char **) FAST_FUNC;
8856 static int setcmd(int, char **) FAST_FUNC;
8857 static int shiftcmd(int, char **) FAST_FUNC;
8858 static int timescmd(int, char **) FAST_FUNC;
8859 static int trapcmd(int, char **) FAST_FUNC;
8860 static int umaskcmd(int, char **) FAST_FUNC;
8861 static int unsetcmd(int, char **) FAST_FUNC;
8862 static int ulimitcmd(int, char **) FAST_FUNC;
8864 #define BUILTIN_NOSPEC "0"
8865 #define BUILTIN_SPECIAL "1"
8866 #define BUILTIN_REGULAR "2"
8867 #define BUILTIN_SPEC_REG "3"
8868 #define BUILTIN_ASSIGN "4"
8869 #define BUILTIN_SPEC_ASSG "5"
8870 #define BUILTIN_REG_ASSG "6"
8871 #define BUILTIN_SPEC_REG_ASSG "7"
8873 /* Stubs for calling non-FAST_FUNC's */
8874 #if ENABLE_ASH_BUILTIN_ECHO
8875 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8877 #if ENABLE_ASH_BUILTIN_PRINTF
8878 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8880 #if ENABLE_ASH_BUILTIN_TEST
8881 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8884 /* Keep these in proper order since it is searched via bsearch() */
8885 static const struct builtincmd builtintab[] = {
8886 { BUILTIN_SPEC_REG "." , dotcmd },
8887 { BUILTIN_SPEC_REG ":" , truecmd },
8888 #if ENABLE_ASH_BUILTIN_TEST
8889 { BUILTIN_REGULAR "[" , testcmd },
8890 #if ENABLE_ASH_BASH_COMPAT
8891 { BUILTIN_REGULAR "[[" , testcmd },
8894 #if ENABLE_ASH_ALIAS
8895 { BUILTIN_REG_ASSG "alias" , aliascmd },
8898 { BUILTIN_REGULAR "bg" , fg_bgcmd },
8900 { BUILTIN_SPEC_REG "break" , breakcmd },
8901 { BUILTIN_REGULAR "cd" , cdcmd },
8902 { BUILTIN_NOSPEC "chdir" , cdcmd },
8903 #if ENABLE_ASH_CMDCMD
8904 { BUILTIN_REGULAR "command" , commandcmd },
8906 { BUILTIN_SPEC_REG "continue", breakcmd },
8907 #if ENABLE_ASH_BUILTIN_ECHO
8908 { BUILTIN_REGULAR "echo" , echocmd },
8910 { BUILTIN_SPEC_REG "eval" , evalcmd },
8911 { BUILTIN_SPEC_REG "exec" , execcmd },
8912 { BUILTIN_SPEC_REG "exit" , exitcmd },
8913 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
8914 { BUILTIN_REGULAR "false" , falsecmd },
8916 { BUILTIN_REGULAR "fg" , fg_bgcmd },
8918 #if ENABLE_ASH_GETOPTS
8919 { BUILTIN_REGULAR "getopts" , getoptscmd },
8921 { BUILTIN_NOSPEC "hash" , hashcmd },
8922 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8923 { BUILTIN_NOSPEC "help" , helpcmd },
8926 { BUILTIN_REGULAR "jobs" , jobscmd },
8927 { BUILTIN_REGULAR "kill" , killcmd },
8929 #if ENABLE_SH_MATH_SUPPORT
8930 { BUILTIN_NOSPEC "let" , letcmd },
8932 { BUILTIN_ASSIGN "local" , localcmd },
8933 #if ENABLE_ASH_BUILTIN_PRINTF
8934 { BUILTIN_REGULAR "printf" , printfcmd },
8936 { BUILTIN_NOSPEC "pwd" , pwdcmd },
8937 { BUILTIN_REGULAR "read" , readcmd },
8938 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8939 { BUILTIN_SPEC_REG "return" , returncmd },
8940 { BUILTIN_SPEC_REG "set" , setcmd },
8941 { BUILTIN_SPEC_REG "shift" , shiftcmd },
8942 { BUILTIN_SPEC_REG "source" , dotcmd },
8943 #if ENABLE_ASH_BUILTIN_TEST
8944 { BUILTIN_REGULAR "test" , testcmd },
8946 { BUILTIN_SPEC_REG "times" , timescmd },
8947 { BUILTIN_SPEC_REG "trap" , trapcmd },
8948 { BUILTIN_REGULAR "true" , truecmd },
8949 { BUILTIN_NOSPEC "type" , typecmd },
8950 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
8951 { BUILTIN_REGULAR "umask" , umaskcmd },
8952 #if ENABLE_ASH_ALIAS
8953 { BUILTIN_REGULAR "unalias" , unaliascmd },
8955 { BUILTIN_SPEC_REG "unset" , unsetcmd },
8956 { BUILTIN_REGULAR "wait" , waitcmd },
8959 /* Should match the above table! */
8960 #define COMMANDCMD (builtintab + \
8962 1 * ENABLE_ASH_BUILTIN_TEST + \
8963 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8964 1 * ENABLE_ASH_ALIAS + \
8965 1 * ENABLE_ASH_JOB_CONTROL + \
8967 #define EXECCMD (builtintab + \
8969 1 * ENABLE_ASH_BUILTIN_TEST + \
8970 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8971 1 * ENABLE_ASH_ALIAS + \
8972 1 * ENABLE_ASH_JOB_CONTROL + \
8974 1 * ENABLE_ASH_CMDCMD + \
8976 ENABLE_ASH_BUILTIN_ECHO + \
8980 * Search the table of builtin commands.
8982 static struct builtincmd *
8983 find_builtin(const char *name)
8985 struct builtincmd *bp;
8988 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8995 * Execute a simple command.
8998 isassignment(const char *p)
9000 const char *q = endofname(p);
9005 static int FAST_FUNC
9006 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9008 /* Preserve exitstatus of a previous possible redirection
9009 * as POSIX mandates */
9010 return back_exitstatus;
9013 evalcommand(union node *cmd, int flags)
9015 static const struct builtincmd null_bltin = {
9016 "\0\0", bltincmd /* why three NULs? */
9018 struct stackmark smark;
9020 struct arglist arglist;
9021 struct arglist varlist;
9024 const struct strlist *sp;
9025 struct cmdentry cmdentry;
9032 struct builtincmd *bcmd;
9033 smallint cmd_is_exec;
9034 smallint pseudovarflag = 0;
9036 /* First expand the arguments. */
9037 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9038 setstackmark(&smark);
9039 back_exitstatus = 0;
9041 cmdentry.cmdtype = CMDBUILTIN;
9042 cmdentry.u.cmd = &null_bltin;
9043 varlist.lastp = &varlist.list;
9044 *varlist.lastp = NULL;
9045 arglist.lastp = &arglist.list;
9046 *arglist.lastp = NULL;
9049 if (cmd->ncmd.args) {
9050 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9051 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9054 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9055 struct strlist **spp;
9057 spp = arglist.lastp;
9058 if (pseudovarflag && isassignment(argp->narg.text))
9059 expandarg(argp, &arglist, EXP_VARTILDE);
9061 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9063 for (sp = *spp; sp; sp = sp->next)
9067 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9068 for (sp = arglist.list; sp; sp = sp->next) {
9069 TRACE(("evalcommand arg: %s\n", sp->text));
9070 *nargv++ = sp->text;
9075 if (iflag && funcnest == 0 && argc > 0)
9076 lastarg = nargv[-1];
9079 expredir(cmd->ncmd.redirect);
9080 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9083 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9084 struct strlist **spp;
9087 spp = varlist.lastp;
9088 expandarg(argp, &varlist, EXP_VARTILDE);
9091 * Modify the command lookup path, if a PATH= assignment
9095 if (varequal(p, path))
9099 /* Print the command if xflag is set. */
9102 const char *p = " %s";
9105 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9108 for (n = 0; n < 2; n++) {
9110 fdprintf(preverrout_fd, p, sp->text);
9118 safe_write(preverrout_fd, "\n", 1);
9124 /* Now locate the command. */
9126 const char *oldpath;
9127 int cmd_flag = DO_ERR;
9132 find_command(argv[0], &cmdentry, cmd_flag, path);
9133 if (cmdentry.cmdtype == CMDUNKNOWN) {
9134 flush_stdout_stderr();
9139 /* implement bltin and command here */
9140 if (cmdentry.cmdtype != CMDBUILTIN)
9143 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9144 if (cmdentry.u.cmd == EXECCMD)
9146 #if ENABLE_ASH_CMDCMD
9147 if (cmdentry.u.cmd == COMMANDCMD) {
9149 nargv = parse_command_args(argv, &path);
9152 argc -= nargv - argv;
9154 cmd_flag |= DO_NOFUNC;
9162 /* We have a redirection error. */
9164 raise_exception(EXERROR);
9166 exitstatus = status;
9170 /* Execute the command. */
9171 switch (cmdentry.cmdtype) {
9174 #if ENABLE_FEATURE_SH_NOFORK
9175 /* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9176 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
9178 /* find_command() encodes applet_no as (-2 - applet_no) */
9179 int applet_no = (- cmdentry.u.index - 2);
9180 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9181 listsetvar(varlist.list, VEXPORT|VSTACK);
9182 /* run <applet>_main() */
9183 exitstatus = run_nofork_applet(applet_no, argv);
9188 /* Fork off a child process if necessary. */
9189 if (!(flags & EV_EXIT) || trap[0]) {
9191 jp = makejob(/*cmd,*/ 1);
9192 if (forkshell(jp, cmd, FORK_FG) != 0) {
9193 exitstatus = waitforjob(jp);
9195 TRACE(("forked child exited with %d\n", exitstatus));
9200 listsetvar(varlist.list, VEXPORT|VSTACK);
9201 shellexec(argv, path, cmdentry.u.index);
9205 cmdenviron = varlist.list;
9207 struct strlist *list = cmdenviron;
9209 if (spclbltin > 0 || argc == 0) {
9211 if (cmd_is_exec && argc > 1)
9214 listsetvar(list, i);
9216 /* Tight loop with builtins only:
9217 * "while kill -0 $child; do true; done"
9218 * will never exit even if $child died, unless we do this
9219 * to reap the zombie and make kill detect that it's gone: */
9220 dowait(DOWAIT_NONBLOCK, NULL);
9222 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9224 int i = exception_type;
9229 exit_status = 128 + SIGINT;
9231 exit_status = 128 + pending_sig;
9232 exitstatus = exit_status;
9233 if (i == EXINT || spclbltin > 0) {
9235 longjmp(exception_handler->loc, 1);
9242 listsetvar(varlist.list, 0);
9243 /* See above for the rationale */
9244 dowait(DOWAIT_NONBLOCK, NULL);
9245 if (evalfun(cmdentry.u.func, argc, argv, flags))
9251 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9253 /* dsl: I think this is intended to be used to support
9254 * '_' in 'vi' command mode during line editing...
9255 * However I implemented that within libedit itself.
9257 setvar("_", lastarg, 0);
9259 popstackmark(&smark);
9263 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9265 char *volatile savecmdname;
9266 struct jmploc *volatile savehandler;
9267 struct jmploc jmploc;
9270 savecmdname = commandname;
9271 i = setjmp(jmploc.loc);
9274 savehandler = exception_handler;
9275 exception_handler = &jmploc;
9276 commandname = argv[0];
9278 optptr = NULL; /* initialize nextopt */
9279 exitstatus = (*cmd->builtin)(argc, argv);
9280 flush_stdout_stderr();
9282 exitstatus |= ferror(stdout);
9284 commandname = savecmdname;
9285 exception_handler = savehandler;
9291 goodname(const char *p)
9293 return !*endofname(p);
9298 * Search for a command. This is called before we fork so that the
9299 * location of the command will be available in the parent as well as
9300 * the child. The check for "goodname" is an overly conservative
9301 * check that the name will not be subject to expansion.
9304 prehash(union node *n)
9306 struct cmdentry entry;
9308 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9309 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9313 /* ============ Builtin commands
9315 * Builtin commands whose functions are closely tied to evaluation
9316 * are implemented here.
9320 * Handle break and continue commands. Break, continue, and return are
9321 * all handled by setting the evalskip flag. The evaluation routines
9322 * above all check this flag, and if it is set they start skipping
9323 * commands rather than executing them. The variable skipcount is
9324 * the number of loops to break/continue, or the number of function
9325 * levels to return. (The latter is always 1.) It should probably
9326 * be an error to break out of more loops than exist, but it isn't
9327 * in the standard shell so we don't make it one here.
9329 static int FAST_FUNC
9330 breakcmd(int argc UNUSED_PARAM, char **argv)
9332 int n = argv[1] ? number(argv[1]) : 1;
9335 ash_msg_and_raise_error(msg_illnum, argv[1]);
9339 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9346 /* ============ input.c
9348 * This implements the input routines used by the parser.
9352 INPUT_PUSH_FILE = 1,
9353 INPUT_NOFILE_OK = 2,
9356 static smallint checkkwd;
9357 /* values of checkkwd variable */
9358 #define CHKALIAS 0x1
9363 * Push a string back onto the input at this current parsefile level.
9364 * We handle aliases this way.
9366 #if !ENABLE_ASH_ALIAS
9367 #define pushstring(s, ap) pushstring(s)
9370 pushstring(char *s, struct alias *ap)
9377 if (g_parsefile->strpush) {
9378 sp = ckzalloc(sizeof(*sp));
9379 sp->prev = g_parsefile->strpush;
9381 sp = &(g_parsefile->basestrpush);
9383 g_parsefile->strpush = sp;
9384 sp->prev_string = g_parsefile->next_to_pgetc;
9385 sp->prev_left_in_line = g_parsefile->left_in_line;
9386 #if ENABLE_ASH_ALIAS
9389 ap->flag |= ALIASINUSE;
9393 g_parsefile->next_to_pgetc = s;
9394 g_parsefile->left_in_line = len;
9401 struct strpush *sp = g_parsefile->strpush;
9404 #if ENABLE_ASH_ALIAS
9406 if (g_parsefile->next_to_pgetc[-1] == ' '
9407 || g_parsefile->next_to_pgetc[-1] == '\t'
9409 checkkwd |= CHKALIAS;
9411 if (sp->string != sp->ap->val) {
9414 sp->ap->flag &= ~ALIASINUSE;
9415 if (sp->ap->flag & ALIASDEAD) {
9416 unalias(sp->ap->name);
9420 g_parsefile->next_to_pgetc = sp->prev_string;
9421 g_parsefile->left_in_line = sp->prev_left_in_line;
9422 g_parsefile->strpush = sp->prev;
9423 if (sp != &(g_parsefile->basestrpush))
9428 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9429 //it peeks whether it is &>, and then pushes back both chars.
9430 //This function needs to save last *next_to_pgetc to buf[0]
9431 //to make two pungetc() reliable. Currently,
9432 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9437 char *buf = g_parsefile->buf;
9439 g_parsefile->next_to_pgetc = buf;
9440 #if ENABLE_FEATURE_EDITING
9442 if (!iflag || g_parsefile->fd != STDIN_FILENO)
9443 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9445 #if ENABLE_FEATURE_TAB_COMPLETION
9446 line_input_state->path_lookup = pathval();
9448 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9450 /* Ctrl+C pressed */
9459 if (nr < 0 && errno == 0) {
9460 /* Ctrl+D pressed */
9465 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9469 /* nonblock_safe_read() handles this problem */
9471 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9472 int flags = fcntl(0, F_GETFL);
9473 if (flags >= 0 && (flags & O_NONBLOCK)) {
9474 flags &= ~O_NONBLOCK;
9475 if (fcntl(0, F_SETFL, flags) >= 0) {
9476 out2str("sh: turning off NDELAY mode\n");
9487 * Refill the input buffer and return the next input character:
9489 * 1) If a string was pushed back on the input, pop it;
9490 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9491 * or we are reading from a string so we can't refill the buffer,
9493 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9494 * 4) Process input up to the next newline, deleting nul characters.
9496 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9497 #define pgetc_debug(...) ((void)0)
9504 while (g_parsefile->strpush) {
9505 #if ENABLE_ASH_ALIAS
9506 if (g_parsefile->left_in_line == -1
9507 && g_parsefile->strpush->ap
9508 && g_parsefile->next_to_pgetc[-1] != ' '
9509 && g_parsefile->next_to_pgetc[-1] != '\t'
9511 pgetc_debug("preadbuffer PEOA");
9516 /* try "pgetc" now: */
9517 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9518 g_parsefile->left_in_line,
9519 g_parsefile->next_to_pgetc,
9520 g_parsefile->next_to_pgetc);
9521 if (--g_parsefile->left_in_line >= 0)
9522 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9524 /* on both branches above g_parsefile->left_in_line < 0.
9525 * "pgetc" needs refilling.
9528 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9529 * pungetc() may increment it a few times.
9530 * Assuming it won't increment it to less than -90.
9532 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9533 pgetc_debug("preadbuffer PEOF1");
9534 /* even in failure keep left_in_line and next_to_pgetc
9535 * in lock step, for correct multi-layer pungetc.
9536 * left_in_line was decremented before preadbuffer(),
9537 * must inc next_to_pgetc: */
9538 g_parsefile->next_to_pgetc++;
9542 more = g_parsefile->left_in_buffer;
9544 flush_stdout_stderr();
9548 /* don't try reading again */
9549 g_parsefile->left_in_line = -99;
9550 pgetc_debug("preadbuffer PEOF2");
9551 g_parsefile->next_to_pgetc++;
9556 /* Find out where's the end of line.
9557 * Set g_parsefile->left_in_line
9558 * and g_parsefile->left_in_buffer acordingly.
9559 * NUL chars are deleted.
9561 q = g_parsefile->next_to_pgetc;
9569 memmove(q, q + 1, more);
9573 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9579 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9580 if (g_parsefile->left_in_line < 0)
9585 g_parsefile->left_in_buffer = more;
9590 out2str(g_parsefile->next_to_pgetc);
9594 pgetc_debug("preadbuffer at %d:%p'%s'",
9595 g_parsefile->left_in_line,
9596 g_parsefile->next_to_pgetc,
9597 g_parsefile->next_to_pgetc);
9598 return (unsigned char)*g_parsefile->next_to_pgetc++;
9601 #define pgetc_as_macro() \
9602 (--g_parsefile->left_in_line >= 0 \
9603 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9610 pgetc_debug("pgetc_fast at %d:%p'%s'",
9611 g_parsefile->left_in_line,
9612 g_parsefile->next_to_pgetc,
9613 g_parsefile->next_to_pgetc);
9614 return pgetc_as_macro();
9617 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9618 # define pgetc_fast() pgetc()
9620 # define pgetc_fast() pgetc_as_macro()
9623 #if ENABLE_ASH_ALIAS
9625 pgetc_without_PEOA(void)
9629 pgetc_debug("pgetc_fast at %d:%p'%s'",
9630 g_parsefile->left_in_line,
9631 g_parsefile->next_to_pgetc,
9632 g_parsefile->next_to_pgetc);
9634 } while (c == PEOA);
9638 # define pgetc_without_PEOA() pgetc()
9642 * Read a line from the script.
9645 pfgets(char *line, int len)
9651 while (--nleft > 0) {
9652 c = pgetc_without_PEOA();
9667 * Undo the last call to pgetc. Only one character may be pushed back.
9668 * PEOF may be pushed back.
9673 g_parsefile->left_in_line++;
9674 g_parsefile->next_to_pgetc--;
9675 pgetc_debug("pushed back to %d:%p'%s'",
9676 g_parsefile->left_in_line,
9677 g_parsefile->next_to_pgetc,
9678 g_parsefile->next_to_pgetc);
9682 * To handle the "." command, a stack of input files is used. Pushfile
9683 * adds a new entry to the stack and popfile restores the previous level.
9688 struct parsefile *pf;
9690 pf = ckzalloc(sizeof(*pf));
9691 pf->prev = g_parsefile;
9693 /*pf->strpush = NULL; - ckzalloc did it */
9694 /*pf->basestrpush.prev = NULL;*/
9701 struct parsefile *pf = g_parsefile;
9709 g_parsefile = pf->prev;
9715 * Return to top level.
9720 while (g_parsefile != &basepf)
9725 * Close the file(s) that the shell is reading commands from. Called
9726 * after a fork is done.
9732 if (g_parsefile->fd > 0) {
9733 close(g_parsefile->fd);
9734 g_parsefile->fd = 0;
9739 * Like setinputfile, but takes an open file descriptor. Call this with
9743 setinputfd(int fd, int push)
9745 close_on_exec_on(fd);
9748 g_parsefile->buf = NULL;
9750 g_parsefile->fd = fd;
9751 if (g_parsefile->buf == NULL)
9752 g_parsefile->buf = ckmalloc(IBUFSIZ);
9753 g_parsefile->left_in_buffer = 0;
9754 g_parsefile->left_in_line = 0;
9755 g_parsefile->linno = 1;
9759 * Set the input to take input from a file. If push is set, push the
9760 * old input onto the stack first.
9763 setinputfile(const char *fname, int flags)
9769 fd = open(fname, O_RDONLY);
9771 if (flags & INPUT_NOFILE_OK)
9773 ash_msg_and_raise_error("can't open '%s'", fname);
9776 fd2 = copyfd(fd, 10);
9779 ash_msg_and_raise_error("out of file descriptors");
9782 setinputfd(fd, flags & INPUT_PUSH_FILE);
9789 * Like setinputfile, but takes input from a string.
9792 setinputstring(char *string)
9796 g_parsefile->next_to_pgetc = string;
9797 g_parsefile->left_in_line = strlen(string);
9798 g_parsefile->buf = NULL;
9799 g_parsefile->linno = 1;
9804 /* ============ mail.c
9806 * Routines to check for mail.
9811 #define MAXMBOXES 10
9813 /* times of mailboxes */
9814 static time_t mailtime[MAXMBOXES];
9815 /* Set if MAIL or MAILPATH is changed. */
9816 static smallint mail_var_path_changed;
9819 * Print appropriate message(s) if mail has arrived.
9820 * If mail_var_path_changed is set,
9821 * then the value of MAIL has mail_var_path_changed,
9822 * so we just update the values.
9831 struct stackmark smark;
9834 setstackmark(&smark);
9835 mpath = mpathset() ? mpathval() : mailval();
9836 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9837 p = path_advance(&mpath, nullstr);
9842 for (q = p; *q; q++)
9848 q[-1] = '\0'; /* delete trailing '/' */
9849 if (stat(p, &statb) < 0) {
9853 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9856 pathopt ? pathopt : "you have mail"
9859 *mtp = statb.st_mtime;
9861 mail_var_path_changed = 0;
9862 popstackmark(&smark);
9865 static void FAST_FUNC
9866 changemail(const char *val UNUSED_PARAM)
9868 mail_var_path_changed = 1;
9871 #endif /* ASH_MAIL */
9874 /* ============ ??? */
9877 * Set the shell parameters.
9880 setparam(char **argv)
9886 for (nparam = 0; argv[nparam]; nparam++)
9888 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9890 *ap++ = ckstrdup(*argv++);
9893 freeparam(&shellparam);
9894 shellparam.malloced = 1;
9895 shellparam.nparam = nparam;
9896 shellparam.p = newparam;
9897 #if ENABLE_ASH_GETOPTS
9898 shellparam.optind = 1;
9899 shellparam.optoff = -1;
9904 * Process shell options. The global variable argptr contains a pointer
9905 * to the argument list; we advance it past the options.
9907 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9908 * For a non-interactive shell, an error condition encountered
9909 * by a special built-in ... shall cause the shell to write a diagnostic message
9910 * to standard error and exit as shown in the following table:
9911 * Error Special Built-In
9913 * Utility syntax error (option or operand error) Shall exit
9915 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9916 * we see that bash does not do that (set "finishes" with error code 1 instead,
9917 * and shell continues), and people rely on this behavior!
9919 * set -o barfoo 2>/dev/null
9922 * Oh well. Let's mimic that.
9925 plus_minus_o(char *name, int val)
9930 for (i = 0; i < NOPTS; i++) {
9931 if (strcmp(name, optnames(i)) == 0) {
9936 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9939 for (i = 0; i < NOPTS; i++) {
9941 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9943 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9949 setoption(int flag, int val)
9953 for (i = 0; i < NOPTS; i++) {
9954 if (optletters(i) == flag) {
9959 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9963 options(int cmdline)
9971 while ((p = *argptr) != NULL) {
9973 if (c != '-' && c != '+')
9976 val = 0; /* val = 0 if c == '+' */
9979 if (p[0] == '\0' || LONE_DASH(p)) {
9981 /* "-" means turn off -x and -v */
9984 /* "--" means reset params */
9985 else if (*argptr == NULL)
9988 break; /* "-" or "--" terminates options */
9991 /* first char was + or - */
9992 while ((c = *p++) != '\0') {
9993 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9994 if (c == 'c' && cmdline) {
9995 minusc = p; /* command is after shell args */
9996 } else if (c == 'o') {
9997 if (plus_minus_o(*argptr, val)) {
9998 /* it already printed err message */
9999 return 1; /* error */
10003 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10005 /* bash does not accept +-login, we also won't */
10006 } else if (cmdline && val && (c == '-')) { /* long options */
10007 if (strcmp(p, "login") == 0)
10019 * The shift builtin command.
10021 static int FAST_FUNC
10022 shiftcmd(int argc UNUSED_PARAM, char **argv)
10029 n = number(argv[1]);
10030 if (n > shellparam.nparam)
10031 n = 0; /* bash compat, was = shellparam.nparam; */
10033 shellparam.nparam -= n;
10034 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10035 if (shellparam.malloced)
10038 ap2 = shellparam.p;
10039 while ((*ap2++ = *ap1++) != NULL)
10041 #if ENABLE_ASH_GETOPTS
10042 shellparam.optind = 1;
10043 shellparam.optoff = -1;
10050 * POSIX requires that 'set' (but not export or readonly) output the
10051 * variables in lexicographic order - by the locale's collating order (sigh).
10052 * Maybe we could keep them in an ordered balanced binary tree
10053 * instead of hashed lists.
10054 * For now just roll 'em through qsort for printing...
10057 showvars(const char *sep_prefix, int on, int off)
10060 char **ep, **epend;
10062 ep = listvars(on, off, &epend);
10063 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10065 sep = *sep_prefix ? " " : sep_prefix;
10067 for (; ep < epend; ep++) {
10071 p = strchrnul(*ep, '=');
10074 q = single_quote(++p);
10075 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10081 * The set command builtin.
10083 static int FAST_FUNC
10084 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10089 return showvars(nullstr, 0, VUNSET);
10092 if (!options(0)) { /* if no parse error... */
10095 if (*argptr != NULL) {
10103 #if ENABLE_ASH_RANDOM_SUPPORT
10104 static void FAST_FUNC
10105 change_random(const char *value)
10109 if (value == NULL) {
10110 /* "get", generate */
10111 t = next_random(&random_gen);
10112 /* set without recursion */
10113 setvar(vrandom.text, utoa(t), VNOFUNC);
10114 vrandom.flags &= ~VNOFUNC;
10117 t = strtoul(value, NULL, 10);
10118 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10123 #if ENABLE_ASH_GETOPTS
10125 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10134 if (*param_optind < 1)
10136 optnext = optfirst + *param_optind - 1;
10138 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10141 p = optnext[-1] + *optoff;
10142 if (p == NULL || *p == '\0') {
10143 /* Current word is done, advance */
10145 if (p == NULL || *p != '-' || *++p == '\0') {
10152 if (LONE_DASH(p)) /* check for "--" */
10157 for (q = optstr; *q != c;) {
10159 if (optstr[0] == ':') {
10162 err |= setvarsafe("OPTARG", s, 0);
10164 fprintf(stderr, "Illegal option -%c\n", c);
10165 unsetvar("OPTARG");
10175 if (*p == '\0' && (p = *optnext) == NULL) {
10176 if (optstr[0] == ':') {
10179 err |= setvarsafe("OPTARG", s, 0);
10182 fprintf(stderr, "No arg for -%c option\n", c);
10183 unsetvar("OPTARG");
10191 err |= setvarsafe("OPTARG", p, 0);
10194 err |= setvarsafe("OPTARG", nullstr, 0);
10196 *optoff = p ? p - *(optnext - 1) : -1;
10197 *param_optind = optnext - optfirst + 1;
10198 fmtstr(s, sizeof(s), "%d", *param_optind);
10199 err |= setvarsafe("OPTIND", s, VNOFUNC);
10202 err |= setvarsafe(optvar, s, 0);
10206 flush_stdout_stderr();
10207 raise_exception(EXERROR);
10213 * The getopts builtin. Shellparam.optnext points to the next argument
10214 * to be processed. Shellparam.optptr points to the next character to
10215 * be processed in the current argument. If shellparam.optnext is NULL,
10216 * then it's the first time getopts has been called.
10218 static int FAST_FUNC
10219 getoptscmd(int argc, char **argv)
10224 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10226 optbase = shellparam.p;
10227 if (shellparam.optind > shellparam.nparam + 1) {
10228 shellparam.optind = 1;
10229 shellparam.optoff = -1;
10232 optbase = &argv[3];
10233 if (shellparam.optind > argc - 2) {
10234 shellparam.optind = 1;
10235 shellparam.optoff = -1;
10239 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10240 &shellparam.optoff);
10242 #endif /* ASH_GETOPTS */
10245 /* ============ Shell parser */
10248 struct heredoc *next; /* next here document in list */
10249 union node *here; /* redirection node */
10250 char *eofmark; /* string indicating end of input */
10251 smallint striptabs; /* if set, strip leading tabs */
10254 static smallint tokpushback; /* last token pushed back */
10255 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10256 static smallint quoteflag; /* set if (part of) last token was quoted */
10257 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10258 static struct heredoc *heredoclist; /* list of here documents to read */
10259 static char *wordtext; /* text of last word returned by readtoken */
10260 static struct nodelist *backquotelist;
10261 static union node *redirnode;
10262 static struct heredoc *heredoc;
10265 * Called when an unexpected token is read during the parse. The argument
10266 * is the token that is expected, or -1 if more than one type of token can
10267 * occur at this point.
10269 static void raise_error_unexpected_syntax(int) NORETURN;
10271 raise_error_unexpected_syntax(int token)
10276 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
10278 sprintf(msg + l, " (expecting %s)", tokname(token));
10279 raise_error_syntax(msg);
10283 #define EOFMARKLEN 79
10285 /* parsing is heavily cross-recursive, need these forward decls */
10286 static union node *andor(void);
10287 static union node *pipeline(void);
10288 static union node *parse_command(void);
10289 static void parseheredoc(void);
10290 static char peektoken(void);
10291 static int readtoken(void);
10293 static union node *
10296 union node *n1, *n2, *n3;
10299 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10300 if (nlflag == 2 && peektoken())
10306 if (tok == TBACKGND) {
10307 if (n2->type == NPIPE) {
10308 n2->npipe.pipe_backgnd = 1;
10310 if (n2->type != NREDIR) {
10311 n3 = stzalloc(sizeof(struct nredir));
10313 /*n3->nredir.redirect = NULL; - stzalloc did it */
10316 n2->type = NBACKGND;
10322 n3 = stzalloc(sizeof(struct nbinary));
10324 n3->nbinary.ch1 = n1;
10325 n3->nbinary.ch2 = n2;
10341 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10349 pungetc(); /* push back EOF on input */
10353 raise_error_unexpected_syntax(-1);
10360 static union node *
10363 union node *n1, *n2, *n3;
10371 } else if (t == TOR) {
10377 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10379 n3 = stzalloc(sizeof(struct nbinary));
10381 n3->nbinary.ch1 = n1;
10382 n3->nbinary.ch2 = n2;
10387 static union node *
10390 union node *n1, *n2, *pipenode;
10391 struct nodelist *lp, *prev;
10395 TRACE(("pipeline: entered\n"));
10396 if (readtoken() == TNOT) {
10398 checkkwd = CHKKWD | CHKALIAS;
10401 n1 = parse_command();
10402 if (readtoken() == TPIPE) {
10403 pipenode = stzalloc(sizeof(struct npipe));
10404 pipenode->type = NPIPE;
10405 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10406 lp = stzalloc(sizeof(struct nodelist));
10407 pipenode->npipe.cmdlist = lp;
10411 lp = stzalloc(sizeof(struct nodelist));
10412 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10413 lp->n = parse_command();
10415 } while (readtoken() == TPIPE);
10421 n2 = stzalloc(sizeof(struct nnot));
10429 static union node *
10434 n = stzalloc(sizeof(struct narg));
10436 /*n->narg.next = NULL; - stzalloc did it */
10437 n->narg.text = wordtext;
10438 n->narg.backquote = backquotelist;
10443 fixredir(union node *n, const char *text, int err)
10447 TRACE(("Fix redir %s %d\n", text, err));
10449 n->ndup.vname = NULL;
10451 fd = bb_strtou(text, NULL, 10);
10452 if (!errno && fd >= 0)
10453 n->ndup.dupfd = fd;
10454 else if (LONE_DASH(text))
10455 n->ndup.dupfd = -1;
10458 raise_error_syntax("bad fd number");
10459 n->ndup.vname = makename();
10464 * Returns true if the text contains nothing to expand (no dollar signs
10468 noexpand(const char *text)
10472 while ((c = *text++) != '\0') {
10473 if (c == CTLQUOTEMARK)
10477 else if (SIT(c, BASESYNTAX) == CCTL)
10486 union node *n = redirnode;
10488 if (readtoken() != TWORD)
10489 raise_error_unexpected_syntax(-1);
10490 if (n->type == NHERE) {
10491 struct heredoc *here = heredoc;
10495 if (quoteflag == 0)
10497 TRACE(("Here document %d\n", n->type));
10498 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10499 raise_error_syntax("illegal eof marker for << redirection");
10500 rmescapes(wordtext, 0);
10501 here->eofmark = wordtext;
10503 if (heredoclist == NULL)
10504 heredoclist = here;
10506 for (p = heredoclist; p->next; p = p->next)
10510 } else if (n->type == NTOFD || n->type == NFROMFD) {
10511 fixredir(n, wordtext, 0);
10513 n->nfile.fname = makename();
10517 static union node *
10520 union node *args, **app;
10521 union node *n = NULL;
10522 union node *vars, **vpp;
10523 union node **rpp, *redir;
10525 #if ENABLE_ASH_BASH_COMPAT
10526 smallint double_brackets_flag = 0;
10536 savecheckkwd = CHKALIAS;
10539 checkkwd = savecheckkwd;
10542 #if ENABLE_ASH_BASH_COMPAT
10543 case TAND: /* "&&" */
10544 case TOR: /* "||" */
10545 if (!double_brackets_flag) {
10549 wordtext = (char *) (t == TAND ? "-a" : "-o");
10552 n = stzalloc(sizeof(struct narg));
10554 /*n->narg.next = NULL; - stzalloc did it */
10555 n->narg.text = wordtext;
10556 #if ENABLE_ASH_BASH_COMPAT
10557 if (strcmp("[[", wordtext) == 0)
10558 double_brackets_flag = 1;
10559 else if (strcmp("]]", wordtext) == 0)
10560 double_brackets_flag = 0;
10562 n->narg.backquote = backquotelist;
10563 if (savecheckkwd && isassignment(wordtext)) {
10565 vpp = &n->narg.next;
10568 app = &n->narg.next;
10573 *rpp = n = redirnode;
10574 rpp = &n->nfile.next;
10575 parsefname(); /* read name of redirection file */
10578 if (args && app == &args->narg.next
10581 struct builtincmd *bcmd;
10584 /* We have a function */
10585 if (readtoken() != TRP)
10586 raise_error_unexpected_syntax(TRP);
10587 name = n->narg.text;
10588 if (!goodname(name)
10589 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10591 raise_error_syntax("bad function name");
10594 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10595 n->narg.next = parse_command();
10608 n = stzalloc(sizeof(struct ncmd));
10610 n->ncmd.args = args;
10611 n->ncmd.assign = vars;
10612 n->ncmd.redirect = redir;
10616 static union node *
10617 parse_command(void)
10619 union node *n1, *n2;
10620 union node *ap, **app;
10621 union node *cp, **cpp;
10622 union node *redir, **rpp;
10629 switch (readtoken()) {
10631 raise_error_unexpected_syntax(-1);
10634 n1 = stzalloc(sizeof(struct nif));
10636 n1->nif.test = list(0);
10637 if (readtoken() != TTHEN)
10638 raise_error_unexpected_syntax(TTHEN);
10639 n1->nif.ifpart = list(0);
10641 while (readtoken() == TELIF) {
10642 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10643 n2 = n2->nif.elsepart;
10645 n2->nif.test = list(0);
10646 if (readtoken() != TTHEN)
10647 raise_error_unexpected_syntax(TTHEN);
10648 n2->nif.ifpart = list(0);
10650 if (lasttoken == TELSE)
10651 n2->nif.elsepart = list(0);
10653 n2->nif.elsepart = NULL;
10661 n1 = stzalloc(sizeof(struct nbinary));
10662 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10663 n1->nbinary.ch1 = list(0);
10666 TRACE(("expecting DO got %s %s\n", tokname(got),
10667 got == TWORD ? wordtext : ""));
10668 raise_error_unexpected_syntax(TDO);
10670 n1->nbinary.ch2 = list(0);
10675 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10676 raise_error_syntax("bad for loop variable");
10677 n1 = stzalloc(sizeof(struct nfor));
10679 n1->nfor.var = wordtext;
10680 checkkwd = CHKKWD | CHKALIAS;
10681 if (readtoken() == TIN) {
10683 while (readtoken() == TWORD) {
10684 n2 = stzalloc(sizeof(struct narg));
10686 /*n2->narg.next = NULL; - stzalloc did it */
10687 n2->narg.text = wordtext;
10688 n2->narg.backquote = backquotelist;
10690 app = &n2->narg.next;
10693 n1->nfor.args = ap;
10694 if (lasttoken != TNL && lasttoken != TSEMI)
10695 raise_error_unexpected_syntax(-1);
10697 n2 = stzalloc(sizeof(struct narg));
10699 /*n2->narg.next = NULL; - stzalloc did it */
10700 n2->narg.text = (char *)dolatstr;
10701 /*n2->narg.backquote = NULL;*/
10702 n1->nfor.args = n2;
10704 * Newline or semicolon here is optional (but note
10705 * that the original Bourne shell only allowed NL).
10707 if (lasttoken != TNL && lasttoken != TSEMI)
10710 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10711 if (readtoken() != TDO)
10712 raise_error_unexpected_syntax(TDO);
10713 n1->nfor.body = list(0);
10717 n1 = stzalloc(sizeof(struct ncase));
10719 if (readtoken() != TWORD)
10720 raise_error_unexpected_syntax(TWORD);
10721 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10723 /*n2->narg.next = NULL; - stzalloc did it */
10724 n2->narg.text = wordtext;
10725 n2->narg.backquote = backquotelist;
10727 checkkwd = CHKKWD | CHKALIAS;
10728 } while (readtoken() == TNL);
10729 if (lasttoken != TIN)
10730 raise_error_unexpected_syntax(TIN);
10731 cpp = &n1->ncase.cases;
10733 checkkwd = CHKNL | CHKKWD;
10735 while (t != TESAC) {
10736 if (lasttoken == TLP)
10738 *cpp = cp = stzalloc(sizeof(struct nclist));
10740 app = &cp->nclist.pattern;
10742 *app = ap = stzalloc(sizeof(struct narg));
10744 /*ap->narg.next = NULL; - stzalloc did it */
10745 ap->narg.text = wordtext;
10746 ap->narg.backquote = backquotelist;
10747 if (readtoken() != TPIPE)
10749 app = &ap->narg.next;
10752 //ap->narg.next = NULL;
10753 if (lasttoken != TRP)
10754 raise_error_unexpected_syntax(TRP);
10755 cp->nclist.body = list(2);
10757 cpp = &cp->nclist.next;
10759 checkkwd = CHKNL | CHKKWD;
10763 raise_error_unexpected_syntax(TENDCASE);
10770 n1 = stzalloc(sizeof(struct nredir));
10771 n1->type = NSUBSHELL;
10772 n1->nredir.n = list(0);
10773 /*n1->nredir.redirect = NULL; - stzalloc did it */
10783 return simplecmd();
10786 if (readtoken() != t)
10787 raise_error_unexpected_syntax(t);
10790 /* Now check for redirection which may follow command */
10791 checkkwd = CHKKWD | CHKALIAS;
10793 while (readtoken() == TREDIR) {
10794 *rpp = n2 = redirnode;
10795 rpp = &n2->nfile.next;
10801 if (n1->type != NSUBSHELL) {
10802 n2 = stzalloc(sizeof(struct nredir));
10807 n1->nredir.redirect = redir;
10812 #if ENABLE_ASH_BASH_COMPAT
10813 static int decode_dollar_squote(void)
10815 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10821 p = strchr(C_escapes, c);
10826 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10830 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10832 } else if (c == 'x') { /* \xHH */
10836 } while (isxdigit(c) && --cnt);
10838 if (cnt == 3) { /* \x but next char is "bad" */
10842 } else { /* simple seq like \\ or \t */
10847 c = bb_process_escape_sequence((void*)&p);
10848 } else { /* unrecognized "\z": print both chars unless ' or " */
10849 if (c != '\'' && c != '"') {
10851 c |= 0x100; /* "please encode \, then me" */
10859 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10860 * is not NULL, read a here document. In the latter case, eofmark is the
10861 * word which marks the end of the document and striptabs is true if
10862 * leading tabs should be stripped from the document. The argument c
10863 * is the first character of the input token or document.
10865 * Because C does not have internal subroutines, I have simulated them
10866 * using goto's to implement the subroutine linkage. The following macros
10867 * will run code that appears at the end of readtoken1.
10869 #define CHECKEND() {goto checkend; checkend_return:;}
10870 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10871 #define PARSESUB() {goto parsesub; parsesub_return:;}
10872 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10873 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10874 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10876 readtoken1(int c, int syntax, char *eofmark, int striptabs)
10878 /* NB: syntax parameter fits into smallint */
10879 /* c parameter is an unsigned char or PEOF or PEOA */
10882 char line[EOFMARKLEN + 1];
10883 struct nodelist *bqlist;
10887 smallint prevsyntax; /* syntax before arithmetic */
10888 #if ENABLE_ASH_EXPAND_PRMT
10889 smallint pssyntax; /* we are expanding a prompt string */
10891 int varnest; /* levels of variables expansion */
10892 int arinest; /* levels of arithmetic expansion */
10893 int parenlevel; /* levels of parens in arithmetic */
10894 int dqvarnest; /* levels of variables expansion within double quotes */
10896 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10899 /* Avoid longjmp clobbering */
10905 (void) &parenlevel;
10908 (void) &prevsyntax;
10911 startlinno = g_parsefile->linno;
10916 #if ENABLE_ASH_EXPAND_PRMT
10917 pssyntax = (syntax == PSSYNTAX);
10921 dblquote = (syntax == DQSYNTAX);
10927 STARTSTACKSTR(out);
10929 /* For each line, until end of word */
10931 CHECKEND(); /* set c to PEOF if at end of here document */
10932 for (;;) { /* until end of line or end of word */
10933 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10934 switch (SIT(c, syntax)) {
10935 case CNL: /* '\n' */
10936 if (syntax == BASESYNTAX)
10937 goto endword; /* exit outer loop */
10939 g_parsefile->linno++;
10943 goto loop; /* continue outer loop */
10948 if (eofmark == NULL || dblquote)
10949 USTPUTC(CTLESC, out);
10950 #if ENABLE_ASH_BASH_COMPAT
10951 if (c == '\\' && bash_dollar_squote) {
10952 c = decode_dollar_squote();
10954 USTPUTC('\\', out);
10955 c = (unsigned char)c;
10961 case CBACK: /* backslash */
10962 c = pgetc_without_PEOA();
10964 USTPUTC(CTLESC, out);
10965 USTPUTC('\\', out);
10967 } else if (c == '\n') {
10971 #if ENABLE_ASH_EXPAND_PRMT
10972 if (c == '$' && pssyntax) {
10973 USTPUTC(CTLESC, out);
10974 USTPUTC('\\', out);
10977 if (dblquote && c != '\\'
10978 && c != '`' && c != '$'
10979 && (c != '"' || eofmark != NULL)
10981 USTPUTC(CTLESC, out);
10982 USTPUTC('\\', out);
10984 if (SIT(c, SQSYNTAX) == CCTL)
10985 USTPUTC(CTLESC, out);
10993 if (eofmark == NULL) {
10994 USTPUTC(CTLQUOTEMARK, out);
11002 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11003 if (eofmark != NULL && arinest == 0
11008 if (dqvarnest == 0) {
11009 syntax = BASESYNTAX;
11016 case CVAR: /* '$' */
11017 PARSESUB(); /* parse substitution */
11019 case CENDVAR: /* '}' */
11022 if (dqvarnest > 0) {
11025 USTPUTC(CTLENDVAR, out);
11030 #if ENABLE_SH_MATH_SUPPORT
11031 case CLP: /* '(' in arithmetic */
11035 case CRP: /* ')' in arithmetic */
11036 if (parenlevel > 0) {
11040 if (pgetc() == ')') {
11041 if (--arinest == 0) {
11042 USTPUTC(CTLENDARI, out);
11043 syntax = prevsyntax;
11044 dblquote = (syntax == DQSYNTAX);
11049 * unbalanced parens
11050 * (don't 2nd guess - no error)
11058 case CBQUOTE: /* '`' */
11062 goto endword; /* exit outer loop */
11066 if (varnest == 0) {
11067 #if ENABLE_ASH_BASH_COMPAT
11069 if (pgetc() == '>')
11070 c = 0x100 + '>'; /* flag &> */
11074 goto endword; /* exit outer loop */
11076 IF_ASH_ALIAS(if (c != PEOA))
11084 #if ENABLE_SH_MATH_SUPPORT
11085 if (syntax == ARISYNTAX)
11086 raise_error_syntax("missing '))'");
11088 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11089 raise_error_syntax("unterminated quoted string");
11090 if (varnest != 0) {
11091 startlinno = g_parsefile->linno;
11093 raise_error_syntax("missing '}'");
11095 USTPUTC('\0', out);
11096 len = out - (char *)stackblock();
11097 out = stackblock();
11098 if (eofmark == NULL) {
11099 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11102 if (isdigit_str9(out)) {
11103 PARSEREDIR(); /* passed as params: out, c */
11104 lasttoken = TREDIR;
11107 /* else: non-number X seen, interpret it
11108 * as "NNNX>file" = "NNNX >file" */
11112 quoteflag = quotef;
11113 backquotelist = bqlist;
11114 grabstackblock(len);
11118 /* end of readtoken routine */
11121 * Check to see whether we are at the end of the here document. When this
11122 * is called, c is set to the first character of the next input line. If
11123 * we are at the end of the here document, this routine sets the c to PEOF.
11127 #if ENABLE_ASH_ALIAS
11129 c = pgetc_without_PEOA();
11132 while (c == '\t') {
11133 c = pgetc_without_PEOA();
11136 if (c == *eofmark) {
11137 if (pfgets(line, sizeof(line)) != NULL) {
11141 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11143 if (*p == '\n' && *q == '\0') {
11145 g_parsefile->linno++;
11146 needprompt = doprompt;
11148 pushstring(line, NULL);
11153 goto checkend_return;
11157 * Parse a redirection operator. The variable "out" points to a string
11158 * specifying the fd to be redirected. The variable "c" contains the
11159 * first character of the redirection operator.
11162 /* out is already checked to be a valid number or "" */
11163 int fd = (*out == '\0' ? -1 : atoi(out));
11166 np = stzalloc(sizeof(struct nfile));
11171 np->type = NAPPEND;
11173 np->type = NCLOBBER;
11176 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11182 #if ENABLE_ASH_BASH_COMPAT
11183 else if (c == 0x100 + '>') { /* this flags &> redirection */
11185 pgetc(); /* this is '>', no need to check */
11189 else { /* c == '<' */
11190 /*np->nfile.fd = 0; - stzalloc did it */
11194 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11195 np = stzalloc(sizeof(struct nhere));
11196 /*np->nfile.fd = 0; - stzalloc did it */
11199 heredoc = stzalloc(sizeof(struct heredoc));
11200 heredoc->here = np;
11203 heredoc->striptabs = 1;
11205 /*heredoc->striptabs = 0; - stzalloc did it */
11211 np->type = NFROMFD;
11215 np->type = NFROMTO;
11227 goto parseredir_return;
11231 * Parse a substitution. At this point, we have read the dollar sign
11232 * and nothing else.
11235 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11236 * (assuming ascii char codes, as the original implementation did) */
11237 #define is_special(c) \
11238 (((unsigned)(c) - 33 < 32) \
11239 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11241 unsigned char subtype;
11245 static const char types[] ALIGN1 = "}-+?=";
11248 if (c > 255 /* PEOA or PEOF */
11249 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11251 #if ENABLE_ASH_BASH_COMPAT
11253 bash_dollar_squote = 1;
11258 } else if (c == '(') { /* $(command) or $((arith)) */
11259 if (pgetc() == '(') {
11260 #if ENABLE_SH_MATH_SUPPORT
11263 raise_error_syntax("you disabled math support for $((arith)) syntax");
11270 USTPUTC(CTLVAR, out);
11271 typeloc = out - (char *)stackblock();
11272 USTPUTC(VSNORMAL, out);
11273 subtype = VSNORMAL;
11281 subtype = VSLENGTH;
11285 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11289 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11290 } else if (isdigit(c)) {
11294 } while (isdigit(c));
11295 } else if (is_special(c)) {
11300 raise_error_syntax("bad substitution");
11302 if (c != '}' && subtype == VSLENGTH)
11307 if (subtype == 0) {
11311 #if ENABLE_ASH_BASH_COMPAT
11312 if (c == ':' || c == '$' || isdigit(c)) {
11314 subtype = VSSUBSTR;
11321 p = strchr(types, c);
11324 subtype = p - types + VSNORMAL;
11329 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11337 #if ENABLE_ASH_BASH_COMPAT
11339 subtype = VSREPLACE;
11342 subtype++; /* VSREPLACEALL */
11351 if (dblquote || arinest)
11353 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11354 if (subtype != VSNORMAL) {
11356 if (dblquote || arinest) {
11361 goto parsesub_return;
11365 * Called to parse command substitutions. Newstyle is set if the command
11366 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11367 * list of commands (passed by reference), and savelen is the number of
11368 * characters on the top of the stack which must be preserved.
11371 struct nodelist **nlpp;
11374 char *volatile str;
11375 struct jmploc jmploc;
11376 struct jmploc *volatile savehandler;
11378 smallint saveprompt = 0;
11381 (void) &saveprompt;
11383 savepbq = parsebackquote;
11384 if (setjmp(jmploc.loc)) {
11386 parsebackquote = 0;
11387 exception_handler = savehandler;
11388 longjmp(exception_handler->loc, 1);
11392 savelen = out - (char *)stackblock();
11394 str = ckmalloc(savelen);
11395 memcpy(str, stackblock(), savelen);
11397 savehandler = exception_handler;
11398 exception_handler = &jmploc;
11401 /* We must read until the closing backquote, giving special
11402 treatment to some slashes, and then push the string and
11403 reread it as input, interpreting it normally. */
11410 STARTSTACKSTR(pout);
11423 g_parsefile->linno++;
11427 * If eating a newline, avoid putting
11428 * the newline into the new character
11429 * stream (via the STPUTC after the
11434 if (pc != '\\' && pc != '`' && pc != '$'
11435 && (!dblquote || pc != '"')
11437 STPUTC('\\', pout);
11439 if (pc <= 255 /* not PEOA or PEOF */) {
11445 IF_ASH_ALIAS(case PEOA:)
11446 startlinno = g_parsefile->linno;
11447 raise_error_syntax("EOF in backquote substitution");
11450 g_parsefile->linno++;
11451 needprompt = doprompt;
11460 STPUTC('\0', pout);
11461 psavelen = pout - (char *)stackblock();
11462 if (psavelen > 0) {
11463 pstr = grabstackstr(pout);
11464 setinputstring(pstr);
11469 nlpp = &(*nlpp)->next;
11470 *nlpp = stzalloc(sizeof(**nlpp));
11471 /* (*nlpp)->next = NULL; - stzalloc did it */
11472 parsebackquote = oldstyle;
11475 saveprompt = doprompt;
11482 doprompt = saveprompt;
11483 else if (readtoken() != TRP)
11484 raise_error_unexpected_syntax(TRP);
11489 * Start reading from old file again, ignoring any pushed back
11490 * tokens left from the backquote parsing
11495 while (stackblocksize() <= savelen)
11497 STARTSTACKSTR(out);
11499 memcpy(out, str, savelen);
11500 STADJUST(savelen, out);
11506 parsebackquote = savepbq;
11507 exception_handler = savehandler;
11508 if (arinest || dblquote)
11509 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11511 USTPUTC(CTLBACKQ, out);
11513 goto parsebackq_oldreturn;
11514 goto parsebackq_newreturn;
11517 #if ENABLE_SH_MATH_SUPPORT
11519 * Parse an arithmetic expansion (indicate start of one and set state)
11522 if (++arinest == 1) {
11523 prevsyntax = syntax;
11524 syntax = ARISYNTAX;
11525 USTPUTC(CTLARI, out);
11532 * we collapse embedded arithmetic expansion to
11533 * parenthesis, which should be equivalent
11537 goto parsearith_return;
11541 } /* end of readtoken */
11544 * Read the next input token.
11545 * If the token is a word, we set backquotelist to the list of cmds in
11546 * backquotes. We set quoteflag to true if any part of the word was
11548 * If the token is TREDIR, then we set redirnode to a structure containing
11550 * In all cases, the variable startlinno is set to the number of the line
11551 * on which the token starts.
11553 * [Change comment: here documents and internal procedures]
11554 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11555 * word parsing code into a separate routine. In this case, readtoken
11556 * doesn't need to have any internal procedures, but parseword does.
11557 * We could also make parseoperator in essence the main routine, and
11558 * have parseword (readtoken1?) handle both words and redirection.]
11560 #define NEW_xxreadtoken
11561 #ifdef NEW_xxreadtoken
11562 /* singles must be first! */
11563 static const char xxreadtoken_chars[7] ALIGN1 = {
11564 '\n', '(', ')', /* singles */
11565 '&', '|', ';', /* doubles */
11569 #define xxreadtoken_singles 3
11570 #define xxreadtoken_doubles 3
11572 static const char xxreadtoken_tokens[] ALIGN1 = {
11573 TNL, TLP, TRP, /* only single occurrence allowed */
11574 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11575 TEOF, /* corresponds to trailing nul */
11576 TAND, TOR, TENDCASE /* if double occurrence */
11591 startlinno = g_parsefile->linno;
11592 for (;;) { /* until token or start of word found */
11594 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11598 while ((c = pgetc()) != '\n' && c != PEOF)
11601 } else if (c == '\\') {
11602 if (pgetc() != '\n') {
11604 break; /* return readtoken1(...) */
11606 startlinno = ++g_parsefile->linno;
11612 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11615 g_parsefile->linno++;
11616 needprompt = doprompt;
11619 p = strchr(xxreadtoken_chars, c);
11621 break; /* return readtoken1(...) */
11623 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11625 if (cc == c) { /* double occurrence? */
11626 p += xxreadtoken_doubles + 1;
11629 #if ENABLE_ASH_BASH_COMPAT
11630 if (c == '&' && cc == '>') /* &> */
11631 break; /* return readtoken1(...) */
11636 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11641 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11643 #else /* old xxreadtoken */
11644 #define RETURN(token) return lasttoken = token
11657 startlinno = g_parsefile->linno;
11658 for (;;) { /* until token or start of word found */
11661 case ' ': case '\t':
11662 IF_ASH_ALIAS(case PEOA:)
11665 while ((c = pgetc()) != '\n' && c != PEOF)
11670 if (pgetc() == '\n') {
11671 startlinno = ++g_parsefile->linno;
11679 g_parsefile->linno++;
11680 needprompt = doprompt;
11685 if (pgetc() == '&')
11690 if (pgetc() == '|')
11695 if (pgetc() == ';')
11708 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11711 #endif /* old xxreadtoken */
11718 smallint alreadyseen = tokpushback;
11721 #if ENABLE_ASH_ALIAS
11730 if (checkkwd & CHKNL) {
11737 if (t != TWORD || quoteflag) {
11742 * check for keywords
11744 if (checkkwd & CHKKWD) {
11745 const char *const *pp;
11747 pp = findkwd(wordtext);
11749 lasttoken = t = pp - tokname_array;
11750 TRACE(("keyword %s recognized\n", tokname(t)));
11755 if (checkkwd & CHKALIAS) {
11756 #if ENABLE_ASH_ALIAS
11758 ap = lookupalias(wordtext, 1);
11761 pushstring(ap->val, ap);
11771 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11773 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11785 return tokname_array[t][0];
11789 * Read and parse a command. Returns NODE_EOF on end of file.
11790 * (NULL is a valid parse tree indicating a blank line.)
11792 static union node *
11793 parsecmd(int interact)
11798 doprompt = interact;
11800 setprompt(doprompt);
11812 * Input any here documents.
11817 struct heredoc *here;
11820 here = heredoclist;
11821 heredoclist = NULL;
11827 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11828 here->eofmark, here->striptabs);
11829 n = stzalloc(sizeof(struct narg));
11830 n->narg.type = NARG;
11831 /*n->narg.next = NULL; - stzalloc did it */
11832 n->narg.text = wordtext;
11833 n->narg.backquote = backquotelist;
11834 here->here->nhere.doc = n;
11841 * called by editline -- any expansions to the prompt should be added here.
11843 #if ENABLE_ASH_EXPAND_PRMT
11844 static const char *
11845 expandstr(const char *ps)
11849 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11850 * and token processing _can_ alter it (delete NULs etc). */
11851 setinputstring((char *)ps);
11852 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11855 n.narg.type = NARG;
11856 n.narg.next = NULL;
11857 n.narg.text = wordtext;
11858 n.narg.backquote = backquotelist;
11860 expandarg(&n, NULL, 0);
11861 return stackblock();
11866 * Execute a command or commands contained in a string.
11869 evalstring(char *s, int mask)
11872 struct stackmark smark;
11876 setstackmark(&smark);
11879 while ((n = parsecmd(0)) != NODE_EOF) {
11881 popstackmark(&smark);
11894 * The eval command.
11896 static int FAST_FUNC
11897 evalcmd(int argc UNUSED_PARAM, char **argv)
11906 STARTSTACKSTR(concat);
11908 concat = stack_putstr(p, concat);
11912 STPUTC(' ', concat);
11914 STPUTC('\0', concat);
11915 p = grabstackstr(concat);
11917 evalstring(p, ~SKIPEVAL);
11924 * Read and execute commands.
11925 * "Top" is nonzero for the top level command loop;
11926 * it turns on prompting if the shell is interactive.
11932 struct stackmark smark;
11936 TRACE(("cmdloop(%d) called\n", top));
11940 setstackmark(&smark);
11943 showjobs(stderr, SHOW_CHANGED);
11946 if (iflag && top) {
11948 #if ENABLE_ASH_MAIL
11952 n = parsecmd(inter);
11954 if (DEBUG > 2 && debug && (n != NODE_EOF))
11957 if (n == NODE_EOF) {
11958 if (!top || numeof >= 50)
11960 if (!stoppedjobs()) {
11963 out2str("\nUse \"exit\" to leave shell.\n");
11966 } else if (nflag == 0) {
11967 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11972 popstackmark(&smark);
11977 return skip & SKIPEVAL;
11984 * Take commands from a file. To be compatible we should do a path
11985 * search for the file, which is necessary to find sub-commands.
11988 find_dot_file(char *name)
11991 const char *path = pathval();
11994 /* don't try this for absolute or relative paths */
11995 if (strchr(name, '/'))
11998 /* IIRC standards do not say whether . is to be searched.
11999 * And it is even smaller this way, making it unconditional for now:
12001 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12006 while ((fullname = path_advance(&path, name)) != NULL) {
12008 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12010 * Don't bother freeing here, since it will
12011 * be freed by the caller.
12015 if (fullname != name)
12016 stunalloc(fullname);
12019 /* not found in the PATH */
12020 ash_msg_and_raise_error("%s: not found", name);
12024 static int FAST_FUNC
12025 dotcmd(int argc, char **argv)
12027 struct strlist *sp;
12028 volatile struct shparam saveparam;
12031 for (sp = cmdenviron; sp; sp = sp->next)
12032 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12034 if (argv[1]) { /* That's what SVR2 does */
12035 char *fullname = find_dot_file(argv[1]);
12038 if (argc) { /* argc > 0, argv[0] != NULL */
12039 saveparam = shellparam;
12040 shellparam.malloced = 0;
12041 shellparam.nparam = argc;
12042 shellparam.p = argv;
12045 setinputfile(fullname, INPUT_PUSH_FILE);
12046 commandname = fullname;
12051 freeparam(&shellparam);
12052 shellparam = saveparam;
12054 status = exitstatus;
12059 static int FAST_FUNC
12060 exitcmd(int argc UNUSED_PARAM, char **argv)
12065 exitstatus = number(argv[1]);
12066 raise_exception(EXEXIT);
12071 * Read a file containing shell functions.
12074 readcmdfile(char *name)
12076 setinputfile(name, INPUT_PUSH_FILE);
12082 /* ============ find_command inplementation */
12085 * Resolve a command name. If you change this routine, you may have to
12086 * change the shellexec routine as well.
12089 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12091 struct tblentry *cmdp;
12098 struct builtincmd *bcmd;
12100 /* If name contains a slash, don't use PATH or hash table */
12101 if (strchr(name, '/') != NULL) {
12102 entry->u.index = -1;
12103 if (act & DO_ABS) {
12104 while (stat(name, &statb) < 0) {
12106 if (errno == EINTR)
12109 entry->cmdtype = CMDUNKNOWN;
12113 entry->cmdtype = CMDNORMAL;
12117 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12119 updatetbl = (path == pathval());
12122 if (strstr(path, "%builtin") != NULL)
12123 act |= DO_ALTBLTIN;
12126 /* If name is in the table, check answer will be ok */
12127 cmdp = cmdlookup(name, 0);
12128 if (cmdp != NULL) {
12131 switch (cmdp->cmdtype) {
12149 } else if (cmdp->rehash == 0)
12150 /* if not invalidated by cd, we're done */
12154 /* If %builtin not in path, check for builtin next */
12155 bcmd = find_builtin(name);
12157 if (IS_BUILTIN_REGULAR(bcmd))
12158 goto builtin_success;
12159 if (act & DO_ALTPATH) {
12160 if (!(act & DO_ALTBLTIN))
12161 goto builtin_success;
12162 } else if (builtinloc <= 0) {
12163 goto builtin_success;
12167 #if ENABLE_FEATURE_SH_STANDALONE
12169 int applet_no = find_applet_by_name(name);
12170 if (applet_no >= 0) {
12171 entry->cmdtype = CMDNORMAL;
12172 entry->u.index = -2 - applet_no;
12178 /* We have to search path. */
12179 prev = -1; /* where to start */
12180 if (cmdp && cmdp->rehash) { /* doing a rehash */
12181 if (cmdp->cmdtype == CMDBUILTIN)
12184 prev = cmdp->param.index;
12190 while ((fullname = path_advance(&path, name)) != NULL) {
12191 stunalloc(fullname);
12192 /* NB: code below will still use fullname
12193 * despite it being "unallocated" */
12196 if (prefix(pathopt, "builtin")) {
12198 goto builtin_success;
12201 if ((act & DO_NOFUNC)
12202 || !prefix(pathopt, "func")
12203 ) { /* ignore unimplemented options */
12207 /* if rehash, don't redo absolute path names */
12208 if (fullname[0] == '/' && idx <= prev) {
12211 TRACE(("searchexec \"%s\": no change\n", name));
12214 while (stat(fullname, &statb) < 0) {
12216 if (errno == EINTR)
12219 if (errno != ENOENT && errno != ENOTDIR)
12223 e = EACCES; /* if we fail, this will be the error */
12224 if (!S_ISREG(statb.st_mode))
12226 if (pathopt) { /* this is a %func directory */
12227 stalloc(strlen(fullname) + 1);
12228 /* NB: stalloc will return space pointed by fullname
12229 * (because we don't have any intervening allocations
12230 * between stunalloc above and this stalloc) */
12231 readcmdfile(fullname);
12232 cmdp = cmdlookup(name, 0);
12233 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12234 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12235 stunalloc(fullname);
12238 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12240 entry->cmdtype = CMDNORMAL;
12241 entry->u.index = idx;
12245 cmdp = cmdlookup(name, 1);
12246 cmdp->cmdtype = CMDNORMAL;
12247 cmdp->param.index = idx;
12252 /* We failed. If there was an entry for this command, delete it */
12253 if (cmdp && updatetbl)
12254 delete_cmd_entry();
12256 ash_msg("%s: %s", name, errmsg(e, "not found"));
12257 entry->cmdtype = CMDUNKNOWN;
12262 entry->cmdtype = CMDBUILTIN;
12263 entry->u.cmd = bcmd;
12267 cmdp = cmdlookup(name, 1);
12268 cmdp->cmdtype = CMDBUILTIN;
12269 cmdp->param.cmd = bcmd;
12273 entry->cmdtype = cmdp->cmdtype;
12274 entry->u = cmdp->param;
12278 /* ============ trap.c */
12281 * The trap builtin.
12283 static int FAST_FUNC
12284 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12288 int signo, exitcode;
12293 for (signo = 0; signo < NSIG; signo++) {
12294 char *tr = trap_ptr[signo];
12296 /* note: bash adds "SIG", but only if invoked
12297 * as "bash". If called as "sh", or if set -o posix,
12298 * then it prints short signal names.
12299 * We are printing short names: */
12300 out1fmt("trap -- %s %s\n",
12302 get_signame(signo));
12303 /* trap_ptr != trap only if we are in special-cased `trap` code.
12304 * In this case, we will exit very soon, no need to free(). */
12305 /* if (trap_ptr != trap && tp[0]) */
12310 if (trap_ptr != trap) {
12323 signo = get_signum(*ap);
12325 /* Mimic bash message exactly */
12326 ash_msg("%s: invalid signal specification", *ap);
12332 if (LONE_DASH(action))
12335 action = ckstrdup(action);
12338 trap[signo] = action;
12349 /* ============ Builtins */
12351 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12353 * Lists available builtins
12355 static int FAST_FUNC
12356 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12362 "Built-in commands:\n"
12363 "------------------\n");
12364 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12365 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12366 builtintab[i].name + 1);
12372 #if ENABLE_FEATURE_SH_STANDALONE
12374 const char *a = applet_names;
12376 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12381 a += strlen(a) + 1;
12386 return EXIT_SUCCESS;
12388 #endif /* FEATURE_SH_EXTRA_QUIET */
12391 * The export and readonly commands.
12393 static int FAST_FUNC
12394 exportcmd(int argc UNUSED_PARAM, char **argv)
12400 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12402 if (nextopt("p") != 'p') {
12407 p = strchr(name, '=');
12411 vp = *findvar(hashvar(name), name);
12417 setvar(name, p, flag);
12418 } while ((name = *++aptr) != NULL);
12422 showvars(argv[0], flag, 0);
12427 * Delete a function if it exists.
12430 unsetfunc(const char *name)
12432 struct tblentry *cmdp;
12434 cmdp = cmdlookup(name, 0);
12435 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12436 delete_cmd_entry();
12440 * The unset builtin command. We unset the function before we unset the
12441 * variable to allow a function to be unset when there is a readonly variable
12442 * with the same name.
12444 static int FAST_FUNC
12445 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12452 while ((i = nextopt("vf")) != '\0') {
12456 for (ap = argptr; *ap; ap++) {
12472 #include <sys/times.h>
12474 static const unsigned char timescmd_str[] ALIGN1 = {
12475 ' ', offsetof(struct tms, tms_utime),
12476 '\n', offsetof(struct tms, tms_stime),
12477 ' ', offsetof(struct tms, tms_cutime),
12478 '\n', offsetof(struct tms, tms_cstime),
12482 static int FAST_FUNC
12483 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12485 long clk_tck, s, t;
12486 const unsigned char *p;
12489 clk_tck = sysconf(_SC_CLK_TCK);
12494 t = *(clock_t *)(((char *) &buf) + p[1]);
12496 out1fmt("%ldm%ld.%.3lds%c",
12498 ((t - s * clk_tck) * 1000) / clk_tck,
12500 } while (*(p += 2));
12505 #if ENABLE_SH_MATH_SUPPORT
12507 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12508 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12510 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12512 static int FAST_FUNC
12513 letcmd(int argc UNUSED_PARAM, char **argv)
12519 ash_msg_and_raise_error("expression expected");
12521 i = ash_arith(*argv);
12526 #endif /* SH_MATH_SUPPORT */
12529 /* ============ miscbltin.c
12531 * Miscellaneous builtins.
12536 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
12537 typedef enum __rlimit_resource rlim_t;
12541 * The read builtin. Options:
12542 * -r Do not interpret '\' specially
12543 * -s Turn off echo (tty only)
12544 * -n NCHARS Read NCHARS max
12545 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12546 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12547 * -u FD Read from given FD instead of fd 0
12548 * This uses unbuffered input, which may be avoidable in some cases.
12549 * TODO: bash also has:
12550 * -a ARRAY Read into array[0],[1],etc
12551 * -d DELIM End on DELIM char, not newline
12552 * -e Use line editing (tty only)
12554 static int FAST_FUNC
12555 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12557 char *opt_n = NULL;
12558 char *opt_p = NULL;
12559 char *opt_t = NULL;
12560 char *opt_u = NULL;
12561 int read_flags = 0;
12565 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12574 read_flags |= BUILTIN_READ_SILENT;
12580 read_flags |= BUILTIN_READ_RAW;
12590 r = shell_builtin_read(setvar2,
12592 bltinlookup("IFS"), /* can be NULL */
12600 if ((uintptr_t)r > 1)
12601 ash_msg_and_raise_error(r);
12603 return (uintptr_t)r;
12606 static int FAST_FUNC
12607 umaskcmd(int argc UNUSED_PARAM, char **argv)
12609 static const char permuser[3] ALIGN1 = "ugo";
12610 static const char permmode[3] ALIGN1 = "rwx";
12611 static const short permmask[] ALIGN2 = {
12612 S_IRUSR, S_IWUSR, S_IXUSR,
12613 S_IRGRP, S_IWGRP, S_IXGRP,
12614 S_IROTH, S_IWOTH, S_IXOTH
12617 /* TODO: use bb_parse_mode() instead */
12622 int symbolic_mode = 0;
12624 while (nextopt("S") != '\0') {
12635 if (symbolic_mode) {
12639 for (i = 0; i < 3; i++) {
12642 *p++ = permuser[i];
12644 for (j = 0; j < 3; j++) {
12645 if ((mask & permmask[3 * i + j]) == 0) {
12646 *p++ = permmode[j];
12654 out1fmt("%.4o\n", mask);
12657 if (isdigit((unsigned char) *ap)) {
12660 if (*ap >= '8' || *ap < '0')
12661 ash_msg_and_raise_error(msg_illnum, argv[1]);
12662 mask = (mask << 3) + (*ap - '0');
12663 } while (*++ap != '\0');
12666 mask = ~mask & 0777;
12667 if (!bb_parse_mode(ap, &mask)) {
12668 ash_msg_and_raise_error("illegal mode: %s", ap);
12670 umask(~mask & 0777);
12676 static int FAST_FUNC
12677 ulimitcmd(int argc UNUSED_PARAM, char **argv)
12679 return shell_builtin_ulimit(argv);
12682 /* ============ main() and helpers */
12685 * Called to exit the shell.
12687 static void exitshell(void) NORETURN;
12695 status = exitstatus;
12696 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12697 if (setjmp(loc.loc)) {
12698 if (exception_type == EXEXIT)
12699 /* dash bug: it just does _exit(exitstatus) here
12700 * but we have to do setjobctl(0) first!
12701 * (bug is still not fixed in dash-0.5.3 - if you run dash
12702 * under Midnight Commander, on exit from dash MC is backgrounded) */
12703 status = exitstatus;
12706 exception_handler = &loc;
12713 flush_stdout_stderr();
12723 /* from input.c: */
12724 basepf.next_to_pgetc = basepf.buf = basebuf;
12727 signal(SIGCHLD, SIG_DFL);
12728 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12729 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12731 signal(SIGHUP, SIG_DFL);
12737 struct stat st1, st2;
12740 for (envp = environ; envp && *envp; envp++) {
12741 if (strchr(*envp, '=')) {
12742 setvareq(*envp, VEXPORT|VTEXTFIXED);
12746 setvar("PPID", utoa(getppid()), 0);
12748 p = lookupvar("PWD");
12750 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12751 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12758 * Process the shell command line arguments.
12761 procargs(char **argv)
12764 const char *xminusc;
12769 /* if (xargv[0]) - mmm, this is always true! */
12771 for (i = 0; i < NOPTS; i++)
12775 /* it already printed err message */
12776 raise_exception(EXERROR);
12780 if (*xargv == NULL) {
12782 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12785 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12789 for (i = 0; i < NOPTS; i++)
12790 if (optlist[i] == 2)
12795 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12800 } else if (!sflag) {
12801 setinputfile(*xargv, 0);
12804 commandname = arg0;
12807 shellparam.p = xargv;
12808 #if ENABLE_ASH_GETOPTS
12809 shellparam.optind = 1;
12810 shellparam.optoff = -1;
12812 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
12814 shellparam.nparam++;
12821 * Read /etc/profile or .profile.
12824 read_profile(const char *name)
12828 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12837 * This routine is called when an error or an interrupt occurs in an
12838 * interactive shell and control is returned to the main command loop.
12846 /* from input.c: */
12847 g_parsefile->left_in_buffer = 0;
12848 g_parsefile->left_in_line = 0; /* clear input buffer */
12850 /* from parser.c: */
12853 /* from redir.c: */
12854 clearredir(/*drop:*/ 0);
12858 static short profile_buf[16384];
12859 extern int etext();
12863 * Main routine. We initialize things, parse the arguments, execute
12864 * profiles if we're a login shell, and then call cmdloop to execute
12865 * commands. The setjmp call sets up the location to jump to when an
12866 * exception occurs. When an exception occurs the variable "state"
12867 * is used to figure out how far we had gotten.
12869 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
12870 int ash_main(int argc UNUSED_PARAM, char **argv)
12872 const char *shinit;
12873 volatile smallint state;
12874 struct jmploc jmploc;
12875 struct stackmark smark;
12877 /* Initialize global data */
12881 #if ENABLE_ASH_ALIAS
12887 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12890 #if ENABLE_FEATURE_EDITING
12891 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12894 if (setjmp(jmploc.loc)) {
12900 e = exception_type;
12904 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12907 outcslow('\n', stderr);
12909 popstackmark(&smark);
12910 FORCE_INT_ON; /* enable interrupts */
12919 exception_handler = &jmploc;
12922 TRACE(("Shell args: "));
12923 trace_puts_args(argv);
12925 rootpid = getpid();
12928 setstackmark(&smark);
12931 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
12933 const char *hp = lookupvar("HISTFILE");
12936 hp = lookupvar("HOME");
12938 char *defhp = concat_path_file(hp, ".ash_history");
12939 setvar("HISTFILE", defhp, 0);
12945 if (/* argv[0] && */ argv[0][0] == '-')
12949 read_profile("/etc/profile");
12952 read_profile(".profile");
12958 getuid() == geteuid() && getgid() == getegid() &&
12962 shinit = lookupvar("ENV");
12963 if (shinit != NULL && *shinit != '\0') {
12964 read_profile(shinit);
12970 /* evalstring pushes parsefile stack.
12971 * Ensure we don't falsely claim that 0 (stdin)
12972 * is one of stacked source fds.
12973 * Testcase: ash -c 'exec 1>&0' must not complain. */
12975 g_parsefile->fd = -1;
12976 evalstring(minusc, 0);
12979 if (sflag || minusc == NULL) {
12980 #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
12982 const char *hp = lookupvar("HISTFILE");
12984 line_input_state->hist_file = hp;
12987 state4: /* XXX ??? - why isn't this before the "if" statement */
12995 extern void _mcleanup(void);
13005 * Copyright (c) 1989, 1991, 1993, 1994
13006 * The Regents of the University of California. All rights reserved.
13008 * This code is derived from software contributed to Berkeley by
13009 * Kenneth Almquist.
13011 * Redistribution and use in source and binary forms, with or without
13012 * modification, are permitted provided that the following conditions
13014 * 1. Redistributions of source code must retain the above copyright
13015 * notice, this list of conditions and the following disclaimer.
13016 * 2. Redistributions in binary form must reproduce the above copyright
13017 * notice, this list of conditions and the following disclaimer in the
13018 * documentation and/or other materials provided with the distribution.
13019 * 3. Neither the name of the University nor the names of its contributors
13020 * may be used to endorse or promote products derived from this software
13021 * without specific prior written permission.
13023 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13024 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13025 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13026 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13027 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13028 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13029 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13030 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13031 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13032 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF