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 (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2594 /* Syntax classes */
2595 #define CWORD 0 /* character is nothing special */
2596 #define CNL 1 /* newline character */
2597 #define CBACK 2 /* a backslash character */
2598 #define CSQUOTE 3 /* single quote */
2599 #define CDQUOTE 4 /* double quote */
2600 #define CENDQUOTE 5 /* a terminating quote */
2601 #define CBQUOTE 6 /* backwards single quote */
2602 #define CVAR 7 /* a dollar sign */
2603 #define CENDVAR 8 /* a '}' character */
2604 #define CLP 9 /* a left paren in arithmetic */
2605 #define CRP 10 /* a right paren in arithmetic */
2606 #define CENDFILE 11 /* end of file */
2607 #define CCTL 12 /* like CWORD, except it must be escaped */
2608 #define CSPCL 13 /* these terminate a word */
2609 #define CIGN 14 /* character should be ignored */
2612 #if ENABLE_ASH_ALIAS
2616 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2618 #if ENABLE_SH_MATH_SUPPORT
2619 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2621 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2623 static const uint16_t S_I_T[] = {
2624 #if ENABLE_ASH_ALIAS
2625 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2627 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2628 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2629 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2630 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2631 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2632 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2633 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2634 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2635 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2636 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2637 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2638 #if !USE_SIT_FUNCTION
2639 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2640 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2641 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2645 /* Constants below must match table above */
2647 #if ENABLE_ASH_ALIAS
2648 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2650 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2651 CNL_CNL_CNL_CNL , /* 2 */
2652 CWORD_CCTL_CCTL_CWORD , /* 3 */
2653 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2654 CVAR_CVAR_CWORD_CVAR , /* 5 */
2655 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2656 CSPCL_CWORD_CWORD_CLP , /* 7 */
2657 CSPCL_CWORD_CWORD_CRP , /* 8 */
2658 CBACK_CBACK_CCTL_CBACK , /* 9 */
2659 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2660 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2661 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2662 CWORD_CWORD_CWORD_CWORD , /* 13 */
2663 CCTL_CCTL_CCTL_CCTL , /* 14 */
2666 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2667 * caller must ensure proper cast on it if c is *char_ptr!
2669 /* Values for syntax param */
2670 #define BASESYNTAX 0 /* not in quotes */
2671 #define DQSYNTAX 1 /* in double quotes */
2672 #define SQSYNTAX 2 /* in single quotes */
2673 #define ARISYNTAX 3 /* in arithmetic */
2674 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2676 #if USE_SIT_FUNCTION
2679 SIT(int c, int syntax)
2681 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2682 # if ENABLE_ASH_ALIAS
2683 static const uint8_t syntax_index_table[] ALIGN1 = {
2684 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2685 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2686 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2690 static const uint8_t syntax_index_table[] ALIGN1 = {
2691 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2692 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2693 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2702 # if ENABLE_ASH_ALIAS
2708 /* Cast is purely for paranoia here,
2709 * just in case someone passed signed char to us */
2710 if ((unsigned char)c >= CTL_FIRST
2711 && (unsigned char)c <= CTL_LAST
2715 s = strchrnul(spec_symbls, c);
2718 indx = syntax_index_table[s - spec_symbls];
2720 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2723 #else /* !USE_SIT_FUNCTION */
2725 static const uint8_t syntax_index_table[] = {
2726 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2727 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2728 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2737 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2738 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2739 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2760 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2761 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2762 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2763 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2764 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2765 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2766 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2767 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2768 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2769 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2770 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2771 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2772 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2773 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2774 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2775 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2776 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2777 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2778 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2779 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2780 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2781 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2782 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2783 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2784 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2785 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2786 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2787 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2788 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2789 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2790 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2791 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2792 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2793 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2794 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2795 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2796 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2797 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2800 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2802 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2803 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2814 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2815 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2816 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2817 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2819 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2820 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2821 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2822 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2823 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2824 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2825 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2848 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2849 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2850 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2851 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2852 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2853 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2854 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2855 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2857 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2858 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2859 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2860 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2861 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2862 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2863 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2864 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 162 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 163 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 164 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 165 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 166 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 167 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 168 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 169 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 170 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 171 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 172 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 173 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 174 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 175 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 176 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 177 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 178 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 179 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 180 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 181 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 182 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 183 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 184 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 185 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 186 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 187 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 188 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 189 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 190 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 191 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 192 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 193 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 194 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 195 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 196 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 197 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 198 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 199 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 200 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 201 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 202 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 203 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 204 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 205 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 206 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 207 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 208 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 209 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 210 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 211 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 212 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 213 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 214 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 215 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 216 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 217 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 218 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 219 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 220 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 221 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 222 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 223 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 224 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 225 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 226 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 227 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 228 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 229 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 231 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 232 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 233 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 234 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 235 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 236 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 237 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 238 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 239 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 241 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 242 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 243 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 244 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 245 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 246 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 247 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 248 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 249 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 250 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 251 */ CWORD_CWORD_CWORD_CWORD,
2979 /* 252 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 253 */ CWORD_CWORD_CWORD_CWORD,
2981 /* 254 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 255 */ CWORD_CWORD_CWORD_CWORD,
2983 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2984 # if ENABLE_ASH_ALIAS
2985 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
2989 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
2991 #endif /* !USE_SIT_FUNCTION */
2994 /* ============ Alias handling */
2996 #if ENABLE_ASH_ALIAS
2998 #define ALIASINUSE 1
3009 static struct alias **atab; // [ATABSIZE];
3010 #define INIT_G_alias() do { \
3011 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3015 static struct alias **
3016 __lookupalias(const char *name) {
3017 unsigned int hashval;
3024 ch = (unsigned char)*p;
3028 ch = (unsigned char)*++p;
3030 app = &atab[hashval % ATABSIZE];
3032 for (; *app; app = &(*app)->next) {
3033 if (strcmp(name, (*app)->name) == 0) {
3041 static struct alias *
3042 lookupalias(const char *name, int check)
3044 struct alias *ap = *__lookupalias(name);
3046 if (check && ap && (ap->flag & ALIASINUSE))
3051 static struct alias *
3052 freealias(struct alias *ap)
3056 if (ap->flag & ALIASINUSE) {
3057 ap->flag |= ALIASDEAD;
3069 setalias(const char *name, const char *val)
3071 struct alias *ap, **app;
3073 app = __lookupalias(name);
3077 if (!(ap->flag & ALIASINUSE)) {
3080 ap->val = ckstrdup(val);
3081 ap->flag &= ~ALIASDEAD;
3084 ap = ckzalloc(sizeof(struct alias));
3085 ap->name = ckstrdup(name);
3086 ap->val = ckstrdup(val);
3087 /*ap->flag = 0; - ckzalloc did it */
3088 /*ap->next = NULL;*/
3095 unalias(const char *name)
3099 app = __lookupalias(name);
3103 *app = freealias(*app);
3114 struct alias *ap, **app;
3118 for (i = 0; i < ATABSIZE; i++) {
3120 for (ap = *app; ap; ap = *app) {
3121 *app = freealias(*app);
3131 printalias(const struct alias *ap)
3133 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3137 * TODO - sort output
3139 static int FAST_FUNC
3140 aliascmd(int argc UNUSED_PARAM, char **argv)
3149 for (i = 0; i < ATABSIZE; i++) {
3150 for (ap = atab[i]; ap; ap = ap->next) {
3156 while ((n = *++argv) != NULL) {
3157 v = strchr(n+1, '=');
3158 if (v == NULL) { /* n+1: funny ksh stuff */
3159 ap = *__lookupalias(n);
3161 fprintf(stderr, "%s: %s not found\n", "alias", n);
3174 static int FAST_FUNC
3175 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3179 while ((i = nextopt("a")) != '\0') {
3185 for (i = 0; *argptr; argptr++) {
3186 if (unalias(*argptr)) {
3187 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3195 #endif /* ASH_ALIAS */
3198 /* ============ jobs.c */
3200 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3203 #define FORK_NOJOB 2
3205 /* mode flags for showjob(s) */
3206 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3207 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3208 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3211 * A job structure contains information about a job. A job is either a
3212 * single process or a set of processes contained in a pipeline. In the
3213 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3217 pid_t ps_pid; /* process id */
3218 int ps_status; /* last process status from wait() */
3219 char *ps_cmd; /* text of command being run */
3223 struct procstat ps0; /* status of process */
3224 struct procstat *ps; /* status or processes when more than one */
3226 int stopstatus; /* status of a stopped job */
3229 nprocs: 16, /* number of processes */
3231 #define JOBRUNNING 0 /* at least one proc running */
3232 #define JOBSTOPPED 1 /* all procs are stopped */
3233 #define JOBDONE 2 /* all procs are completed */
3235 sigint: 1, /* job was killed by SIGINT */
3236 jobctl: 1, /* job running under job control */
3238 waited: 1, /* true if this entry has been waited for */
3239 used: 1, /* true if this entry is in used */
3240 changed: 1; /* true if status has changed */
3241 struct job *prev_job; /* previous job */
3244 static struct job *makejob(/*union node *,*/ int);
3245 static int forkshell(struct job *, union node *, int);
3246 static int waitforjob(struct job *);
3249 enum { doing_jobctl = 0 };
3250 #define setjobctl(on) do {} while (0)
3252 static smallint doing_jobctl; //references:8
3253 static void setjobctl(int);
3260 ignoresig(int signo)
3262 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3263 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3264 /* No, need to do it */
3265 signal(signo, SIG_IGN);
3267 sigmode[signo - 1] = S_HARD_IGN;
3271 * Signal handler. Only one usage site - in setsignal()
3276 gotsig[signo - 1] = 1;
3278 if (signo == SIGINT && !trap[SIGINT]) {
3279 if (!suppress_int) {
3281 raise_interrupt(); /* does not return */
3285 pending_sig = signo;
3290 * Set the signal handler for the specified signal. The routine figures
3291 * out what it should be set to.
3294 setsignal(int signo)
3297 char cur_act, new_act;
3298 struct sigaction act;
3302 if (t != NULL) { /* trap for this sig is set */
3304 if (t[0] == '\0') /* trap is "": ignore this sig */
3308 if (rootshell && new_act == S_DFL) {
3311 if (iflag || minusc || sflag == 0)
3320 * "In all cases, bash ignores SIGQUIT. Non-builtin
3321 * commands run by bash have signal handlers
3322 * set to the values inherited by the shell
3323 * from its parent". */
3339 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3340 //whereas we have to restore it to what shell got on entry
3341 //from the parent. See comment above
3343 t = &sigmode[signo - 1];
3346 /* current setting is not yet known */
3347 if (sigaction(signo, NULL, &act)) {
3348 /* pretend it worked; maybe we should give a warning,
3349 * but other shells don't. We don't alter sigmode,
3350 * so we retry every time.
3351 * btw, in Linux it never fails. --vda */
3354 if (act.sa_handler == SIG_IGN) {
3355 cur_act = S_HARD_IGN;
3357 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3359 cur_act = S_IGN; /* don't hard ignore these */
3363 if (cur_act == S_HARD_IGN || cur_act == new_act)
3366 act.sa_handler = SIG_DFL;
3369 act.sa_handler = onsig;
3370 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3371 sigfillset(&act.sa_mask); /* ditto */
3374 act.sa_handler = SIG_IGN;
3377 sigaction_set(signo, &act);
3382 /* mode flags for set_curjob */
3383 #define CUR_DELETE 2
3384 #define CUR_RUNNING 1
3385 #define CUR_STOPPED 0
3387 /* mode flags for dowait */
3388 #define DOWAIT_NONBLOCK WNOHANG
3389 #define DOWAIT_BLOCK 0
3392 /* pgrp of shell on invocation */
3393 static int initialpgrp; //references:2
3394 static int ttyfd = -1; //5
3397 static struct job *jobtab; //5
3399 static unsigned njobs; //4
3401 static struct job *curjob; //lots
3402 /* number of presumed living untracked jobs */
3403 static int jobless; //4
3406 set_curjob(struct job *jp, unsigned mode)
3409 struct job **jpp, **curp;
3411 /* first remove from list */
3412 jpp = curp = &curjob;
3417 jpp = &jp1->prev_job;
3419 *jpp = jp1->prev_job;
3421 /* Then re-insert in correct position */
3429 /* job being deleted */
3432 /* newly created job or backgrounded job,
3433 put after all stopped jobs. */
3437 if (!jp1 || jp1->state != JOBSTOPPED)
3440 jpp = &jp1->prev_job;
3446 /* newly stopped job - becomes curjob */
3447 jp->prev_job = *jpp;
3455 jobno(const struct job *jp)
3457 return jp - jobtab + 1;
3462 * Convert a job name to a job structure.
3465 #define getjob(name, getctl) getjob(name)
3468 getjob(const char *name, int getctl)
3472 const char *err_msg = "%s: no such job";
3476 char *(*match)(const char *, const char *);
3491 if (c == '+' || c == '%') {
3493 err_msg = "No current job";
3499 err_msg = "No previous job";
3510 jp = jobtab + num - 1;
3525 if (match(jp->ps[0].ps_cmd, p)) {
3529 err_msg = "%s: ambiguous";
3539 err_msg = "job %s not created under job control";
3540 if (getctl && jp->jobctl == 0)
3545 ash_msg_and_raise_error(err_msg, name);
3549 * Mark a job structure as unused.
3552 freejob(struct job *jp)
3554 struct procstat *ps;
3558 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3559 if (ps->ps_cmd != nullstr)
3562 if (jp->ps != &jp->ps0)
3565 set_curjob(jp, CUR_DELETE);
3571 xtcsetpgrp(int fd, pid_t pgrp)
3573 if (tcsetpgrp(fd, pgrp))
3574 ash_msg_and_raise_error("can't set tty process group (%m)");
3578 * Turn job control on and off.
3580 * Note: This code assumes that the third arg to ioctl is a character
3581 * pointer, which is true on Berkeley systems but not System V. Since
3582 * System V doesn't have job control yet, this isn't a problem now.
3584 * Called with interrupts off.
3592 if (on == doing_jobctl || rootshell == 0)
3596 ofd = fd = open(_PATH_TTY, O_RDWR);
3598 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3599 * That sometimes helps to acquire controlling tty.
3600 * Obviously, a workaround for bugs when someone
3601 * failed to provide a controlling tty to bash! :) */
3607 fd = fcntl(fd, F_DUPFD, 10);
3612 /* fd is a tty at this point */
3613 close_on_exec_on(fd);
3614 do { /* while we are in the background */
3615 pgrp = tcgetpgrp(fd);
3618 ash_msg("can't access tty; job control turned off");
3622 if (pgrp == getpgrp())
3633 xtcsetpgrp(fd, pgrp);
3635 /* turning job control off */
3638 /* was xtcsetpgrp, but this can make exiting ash
3639 * loop forever if pty is already deleted */
3640 tcsetpgrp(fd, pgrp);
3654 static int FAST_FUNC
3655 killcmd(int argc, char **argv)
3658 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3660 if (argv[i][0] == '%') {
3661 struct job *jp = getjob(argv[i], 0);
3662 unsigned pid = jp->ps[0].ps_pid;
3663 /* Enough space for ' -NNN<nul>' */
3664 argv[i] = alloca(sizeof(int)*3 + 3);
3665 /* kill_main has matching code to expect
3666 * leading space. Needed to not confuse
3667 * negative pids with "kill -SIGNAL_NO" syntax */
3668 sprintf(argv[i], " -%u", pid);
3670 } while (argv[++i]);
3672 return kill_main(argc, argv);
3676 showpipe(struct job *jp /*, FILE *out*/)
3678 struct procstat *ps;
3679 struct procstat *psend;
3681 psend = jp->ps + jp->nprocs;
3682 for (ps = jp->ps + 1; ps < psend; ps++)
3683 printf(" | %s", ps->ps_cmd);
3684 outcslow('\n', stdout);
3685 flush_stdout_stderr();
3690 restartjob(struct job *jp, int mode)
3692 struct procstat *ps;
3698 if (jp->state == JOBDONE)
3700 jp->state = JOBRUNNING;
3701 pgid = jp->ps[0].ps_pid;
3702 if (mode == FORK_FG)
3703 xtcsetpgrp(ttyfd, pgid);
3704 killpg(pgid, SIGCONT);
3708 if (WIFSTOPPED(ps->ps_status)) {
3714 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3719 static int FAST_FUNC
3720 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3726 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3730 jp = getjob(*argv, 1);
3731 if (mode == FORK_BG) {
3732 set_curjob(jp, CUR_RUNNING);
3733 printf("[%d] ", jobno(jp));
3735 out1str(jp->ps[0].ps_cmd);
3736 showpipe(jp /*, stdout*/);
3737 retval = restartjob(jp, mode);
3738 } while (*argv && *++argv);
3744 sprint_status(char *s, int status, int sigonly)
3750 if (!WIFEXITED(status)) {
3752 if (WIFSTOPPED(status))
3753 st = WSTOPSIG(status);
3756 st = WTERMSIG(status);
3758 if (st == SIGINT || st == SIGPIPE)
3761 if (WIFSTOPPED(status))
3766 col = fmtstr(s, 32, strsignal(st));
3767 if (WCOREDUMP(status)) {
3768 col += fmtstr(s + col, 16, " (core dumped)");
3770 } else if (!sigonly) {
3771 st = WEXITSTATUS(status);
3773 col = fmtstr(s, 16, "Done(%d)", st);
3775 col = fmtstr(s, 16, "Done");
3782 dowait(int wait_flags, struct job *job)
3787 struct job *thisjob;
3790 TRACE(("dowait(0x%x) called\n", wait_flags));
3792 /* Do a wait system call. If job control is compiled in, we accept
3793 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3794 * NB: _not_ safe_waitpid, we need to detect EINTR */
3796 wait_flags |= WUNTRACED;
3797 pid = waitpid(-1, &status, wait_flags);
3798 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3799 pid, status, errno, strerror(errno)));
3805 for (jp = curjob; jp; jp = jp->prev_job) {
3806 struct procstat *ps;
3807 struct procstat *psend;
3808 if (jp->state == JOBDONE)
3812 psend = ps + jp->nprocs;
3814 if (ps->ps_pid == pid) {
3815 TRACE(("Job %d: changing status of proc %d "
3816 "from 0x%x to 0x%x\n",
3817 jobno(jp), pid, ps->ps_status, status));
3818 ps->ps_status = status;
3821 if (ps->ps_status == -1)
3824 if (state == JOBRUNNING)
3826 if (WIFSTOPPED(ps->ps_status)) {
3827 jp->stopstatus = ps->ps_status;
3831 } while (++ps < psend);
3836 if (!WIFSTOPPED(status))
3842 if (state != JOBRUNNING) {
3843 thisjob->changed = 1;
3845 if (thisjob->state != state) {
3846 TRACE(("Job %d: changing state from %d to %d\n",
3847 jobno(thisjob), thisjob->state, state));
3848 thisjob->state = state;
3850 if (state == JOBSTOPPED) {
3851 set_curjob(thisjob, CUR_STOPPED);
3860 if (thisjob && thisjob == job) {
3864 len = sprint_status(s, status, 1);
3875 blocking_wait_with_raise_on_sig(void)
3877 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
3878 if (pid <= 0 && pending_sig)
3879 raise_exception(EXSIG);
3885 showjob(FILE *out, struct job *jp, int mode)
3887 struct procstat *ps;
3888 struct procstat *psend;
3895 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
3896 /* just output process (group) id of pipeline */
3897 fprintf(out, "%d\n", ps->ps_pid);
3901 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3906 else if (curjob && jp == curjob->prev_job)
3909 if (mode & SHOW_PIDS)
3910 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
3912 psend = ps + jp->nprocs;
3914 if (jp->state == JOBRUNNING) {
3915 strcpy(s + col, "Running");
3916 col += sizeof("Running") - 1;
3918 int status = psend[-1].ps_status;
3919 if (jp->state == JOBSTOPPED)
3920 status = jp->stopstatus;
3921 col += sprint_status(s + col, status, 0);
3923 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
3925 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3926 * or prints several "PID | <cmdN>" lines,
3927 * depending on SHOW_PIDS bit.
3928 * We do not print status of individual processes
3929 * between PID and <cmdN>. bash does it, but not very well:
3930 * first line shows overall job status, not process status,
3931 * making it impossible to know 1st process status.
3935 /* for each process */
3938 if (mode & SHOW_PIDS)
3939 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
3941 fprintf(out, "%s%*c%s%s",
3943 33 - col >= 0 ? 33 - col : 0, ' ',
3944 ps == jp->ps ? "" : "| ",
3947 } while (++ps != psend);
3948 outcslow('\n', out);
3952 if (jp->state == JOBDONE) {
3953 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3959 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3960 * statuses have changed since the last call to showjobs.
3963 showjobs(FILE *out, int mode)
3967 TRACE(("showjobs(0x%x) called\n", mode));
3969 /* Handle all finished jobs */
3970 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
3973 for (jp = curjob; jp; jp = jp->prev_job) {
3974 if (!(mode & SHOW_CHANGED) || jp->changed) {
3975 showjob(out, jp, mode);
3980 static int FAST_FUNC
3981 jobscmd(int argc UNUSED_PARAM, char **argv)
3986 while ((m = nextopt("lp")) != '\0') {
3990 mode |= SHOW_ONLY_PGID;
3996 showjob(stdout, getjob(*argv, 0), mode);
3999 showjobs(stdout, mode);
4006 /* Called only on finished or stopped jobs (no members are running) */
4008 getstatus(struct job *job)
4012 struct procstat *ps;
4014 /* Fetch last member's status */
4015 ps = job->ps + job->nprocs - 1;
4016 status = ps->ps_status;
4018 /* "set -o pipefail" mode: use last _nonzero_ status */
4019 while (status == 0 && --ps >= job->ps)
4020 status = ps->ps_status;
4023 retval = WEXITSTATUS(status);
4024 if (!WIFEXITED(status)) {
4026 retval = WSTOPSIG(status);
4027 if (!WIFSTOPPED(status))
4030 /* XXX: limits number of signals */
4031 retval = WTERMSIG(status);
4033 if (retval == SIGINT)
4039 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4040 jobno(job), job->nprocs, status, retval));
4044 static int FAST_FUNC
4045 waitcmd(int argc UNUSED_PARAM, char **argv)
4052 raise_exception(EXSIG);
4059 /* wait for all jobs */
4063 if (!jp) /* no running procs */
4065 if (jp->state == JOBRUNNING)
4070 blocking_wait_with_raise_on_sig();
4072 * "When bash is waiting for an asynchronous command via
4073 * the wait builtin, the reception of a signal for which a trap
4074 * has been set will cause the wait builtin to return immediately
4075 * with an exit status greater than 128, immediately after which
4076 * the trap is executed."
4078 * blocking_wait_with_raise_on_sig raises signal handlers
4079 * if it gets no pid (pid < 0). However,
4080 * if child sends us a signal *and immediately exits*,
4081 * blocking_wait_with_raise_on_sig gets pid > 0
4082 * and does not handle pending_sig. Check this case: */
4084 raise_exception(EXSIG);
4090 if (**argv != '%') {
4091 pid_t pid = number(*argv);
4096 if (job->ps[job->nprocs - 1].ps_pid == pid)
4098 job = job->prev_job;
4101 job = getjob(*argv, 0);
4102 /* loop until process terminated or stopped */
4103 while (job->state == JOBRUNNING)
4104 blocking_wait_with_raise_on_sig();
4106 retval = getstatus(job);
4119 struct job *jp, *jq;
4121 len = njobs * sizeof(*jp);
4123 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4125 offset = (char *)jp - (char *)jq;
4127 /* Relocate pointers */
4130 jq = (struct job *)((char *)jq + l);
4134 #define joff(p) ((struct job *)((char *)(p) + l))
4135 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4136 if (joff(jp)->ps == &jq->ps0)
4137 jmove(joff(jp)->ps);
4138 if (joff(jp)->prev_job)
4139 jmove(joff(jp)->prev_job);
4149 jp = (struct job *)((char *)jp + len);
4153 } while (--jq >= jp);
4158 * Return a new job structure.
4159 * Called with interrupts off.
4162 makejob(/*union node *node,*/ int nprocs)
4167 for (i = njobs, jp = jobtab; ; jp++) {
4174 if (jp->state != JOBDONE || !jp->waited)
4183 memset(jp, 0, sizeof(*jp));
4185 /* jp->jobctl is a bitfield.
4186 * "jp->jobctl |= jobctl" likely to give awful code */
4190 jp->prev_job = curjob;
4195 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4197 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4204 * Return a string identifying a command (to be printed by the
4207 static char *cmdnextc;
4210 cmdputs(const char *s)
4212 static const char vstype[VSTYPE + 1][3] = {
4213 "", "}", "-", "+", "?", "=",
4214 "%", "%%", "#", "##"
4215 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4218 const char *p, *str;
4222 unsigned char subtype = 0;
4226 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4228 while ((c = *p++) != '\0') {
4236 if ((subtype & VSTYPE) == VSLENGTH)
4240 if (!(subtype & VSQUOTE) == !(quoted & 1))
4246 str = "\"}" + !(quoted & 1);
4253 case CTLBACKQ+CTLQUOTE:
4256 #if ENABLE_SH_MATH_SUPPORT
4271 if ((subtype & VSTYPE) != VSNORMAL)
4273 str = vstype[subtype & VSTYPE];
4274 if (subtype & VSNUL)
4283 /* These can only happen inside quotes */
4296 while ((c = *str++) != '\0') {
4299 } /* while *p++ not NUL */
4302 USTPUTC('"', nextc);
4308 /* cmdtxt() and cmdlist() call each other */
4309 static void cmdtxt(union node *n);
4312 cmdlist(union node *np, int sep)
4314 for (; np; np = np->narg.next) {
4318 if (sep && np->narg.next)
4324 cmdtxt(union node *n)
4327 struct nodelist *lp;
4338 lp = n->npipe.cmdlist;
4356 cmdtxt(n->nbinary.ch1);
4372 cmdtxt(n->nif.test);
4374 if (n->nif.elsepart) {
4375 cmdtxt(n->nif.ifpart);
4377 n = n->nif.elsepart;
4395 cmdtxt(n->nbinary.ch1);
4405 cmdputs(n->nfor.var);
4407 cmdlist(n->nfor.args, 1);
4412 cmdputs(n->narg.text);
4416 cmdlist(n->ncmd.args, 1);
4417 cmdlist(n->ncmd.redirect, 0);
4430 cmdputs(n->ncase.expr->narg.text);
4432 for (np = n->ncase.cases; np; np = np->nclist.next) {
4433 cmdtxt(np->nclist.pattern);
4435 cmdtxt(np->nclist.body);
4449 #if ENABLE_ASH_BASH_COMPAT
4464 cmdputs(utoa(n->nfile.fd));
4466 if (n->type == NTOFD || n->type == NFROMFD) {
4467 cmdputs(utoa(n->ndup.dupfd));
4476 commandtext(union node *n)
4480 STARTSTACKSTR(cmdnextc);
4482 name = stackblock();
4483 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4484 name, cmdnextc, cmdnextc));
4485 return ckstrdup(name);
4490 * Fork off a subshell. If we are doing job control, give the subshell its
4491 * own process group. Jp is a job structure that the job is to be added to.
4492 * N is the command that will be evaluated by the child. Both jp and n may
4493 * be NULL. The mode parameter can be one of the following:
4494 * FORK_FG - Fork off a foreground process.
4495 * FORK_BG - Fork off a background process.
4496 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4497 * process group even if job control is on.
4499 * When job control is turned off, background processes have their standard
4500 * input redirected to /dev/null (except for the second and later processes
4503 * Called with interrupts off.
4506 * Clear traps on a fork.
4513 for (tp = trap; tp < &trap[NSIG]; tp++) {
4514 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4516 if (trap_ptr == trap)
4518 /* else: it "belongs" to trap_ptr vector, don't free */
4520 if ((tp - trap) != 0)
4521 setsignal(tp - trap);
4527 /* Lives far away from here, needed for forkchild */
4528 static void closescript(void);
4530 /* Called after fork(), in child */
4531 static NOINLINE void
4532 forkchild(struct job *jp, union node *n, int mode)
4536 TRACE(("Child shell %d\n", getpid()));
4540 /* man bash: "Non-builtin commands run by bash have signal handlers
4541 * set to the values inherited by the shell from its parent".
4542 * Do we do it correctly? */
4546 if (mode == FORK_NOJOB /* is it `xxx` ? */
4547 && n && n->type == NCMD /* is it single cmd? */
4548 /* && n->ncmd.args->type == NARG - always true? */
4549 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4550 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4551 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4553 TRACE(("Trap hack\n"));
4554 /* Awful hack for `trap` or $(trap).
4556 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4557 * contains an example where "trap" is executed in a subshell:
4559 * save_traps=$(trap)
4561 * eval "$save_traps"
4563 * Standard does not say that "trap" in subshell shall print
4564 * parent shell's traps. It only says that its output
4565 * must have suitable form, but then, in the above example
4566 * (which is not supposed to be normative), it implies that.
4568 * bash (and probably other shell) does implement it
4569 * (traps are reset to defaults, but "trap" still shows them),
4570 * but as a result, "trap" logic is hopelessly messed up:
4573 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4574 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4575 * # true | trap <--- trap is in subshell - no output (ditto)
4576 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4577 * trap -- 'echo Ho' SIGWINCH
4578 * # echo `(trap)` <--- in subshell in subshell - output
4579 * trap -- 'echo Ho' SIGWINCH
4580 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4581 * trap -- 'echo Ho' SIGWINCH
4583 * The rules when to forget and when to not forget traps
4584 * get really complex and nonsensical.
4586 * Our solution: ONLY bare $(trap) or `trap` is special.
4588 /* Save trap handler strings for trap builtin to print */
4589 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4590 /* Fall through into clearing traps */
4594 /* do job control only in root shell */
4596 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4599 if (jp->nprocs == 0)
4602 pgrp = jp->ps[0].ps_pid;
4603 /* this can fail because we are doing it in the parent also */
4605 if (mode == FORK_FG)
4606 xtcsetpgrp(ttyfd, pgrp);
4611 if (mode == FORK_BG) {
4612 /* man bash: "When job control is not in effect,
4613 * asynchronous commands ignore SIGINT and SIGQUIT" */
4616 if (jp->nprocs == 0) {
4618 if (open(bb_dev_null, O_RDONLY) != 0)
4619 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4623 if (iflag) { /* why if iflag only? */
4628 * "In all cases, bash ignores SIGQUIT. Non-builtin
4629 * commands run by bash have signal handlers
4630 * set to the values inherited by the shell
4632 * Take care of the second rule: */
4636 if (n && n->type == NCMD
4637 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4639 TRACE(("Job hack\n"));
4640 /* "jobs": we do not want to clear job list for it,
4641 * instead we remove only _its_ own_ job from job list.
4642 * This makes "jobs .... | cat" more useful.
4648 for (jp = curjob; jp; jp = jp->prev_job)
4653 /* Called after fork(), in parent */
4655 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4658 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4660 TRACE(("In parent shell: child = %d\n", pid));
4662 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4668 if (mode != FORK_NOJOB && jp->jobctl) {
4671 if (jp->nprocs == 0)
4674 pgrp = jp->ps[0].ps_pid;
4675 /* This can fail because we are doing it in the child also */
4679 if (mode == FORK_BG) {
4680 backgndpid = pid; /* set $! */
4681 set_curjob(jp, CUR_RUNNING);
4684 struct procstat *ps = &jp->ps[jp->nprocs++];
4687 ps->ps_cmd = nullstr;
4689 if (doing_jobctl && n)
4690 ps->ps_cmd = commandtext(n);
4696 forkshell(struct job *jp, union node *n, int mode)
4700 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4703 TRACE(("Fork failed, errno=%d", errno));
4706 ash_msg_and_raise_error("can't fork");
4709 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4710 forkchild(jp, n, mode);
4712 forkparent(jp, n, mode, pid);
4718 * Wait for job to finish.
4720 * Under job control we have the problem that while a child process
4721 * is running interrupts generated by the user are sent to the child
4722 * but not to the shell. This means that an infinite loop started by
4723 * an interactive user may be hard to kill. With job control turned off,
4724 * an interactive user may place an interactive program inside a loop.
4725 * If the interactive program catches interrupts, the user doesn't want
4726 * these interrupts to also abort the loop. The approach we take here
4727 * is to have the shell ignore interrupt signals while waiting for a
4728 * foreground process to terminate, and then send itself an interrupt
4729 * signal if the child process was terminated by an interrupt signal.
4730 * Unfortunately, some programs want to do a bit of cleanup and then
4731 * exit on interrupt; unless these processes terminate themselves by
4732 * sending a signal to themselves (instead of calling exit) they will
4733 * confuse this approach.
4735 * Called with interrupts off.
4738 waitforjob(struct job *jp)
4742 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4745 while (jp->state == JOBRUNNING) {
4746 /* In non-interactive shells, we _can_ get
4747 * a keyboard signal here and be EINTRed,
4748 * but we just loop back, waiting for command to complete.
4751 * "If bash is waiting for a command to complete and receives
4752 * a signal for which a trap has been set, the trap
4753 * will not be executed until the command completes."
4755 * Reality is that even if trap is not set, bash
4756 * will not act on the signal until command completes.
4757 * Try this. sleep5intoff.c:
4758 * #include <signal.h>
4759 * #include <unistd.h>
4762 * sigemptyset(&set);
4763 * sigaddset(&set, SIGINT);
4764 * sigaddset(&set, SIGQUIT);
4765 * sigprocmask(SIG_BLOCK, &set, NULL);
4769 * $ bash -c './sleep5intoff; echo hi'
4770 * ^C^C^C^C <--- pressing ^C once a second
4772 * $ bash -c './sleep5intoff; echo hi'
4773 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4776 dowait(DOWAIT_BLOCK, jp);
4783 xtcsetpgrp(ttyfd, rootpid);
4785 * This is truly gross.
4786 * If we're doing job control, then we did a TIOCSPGRP which
4787 * caused us (the shell) to no longer be in the controlling
4788 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4789 * intuit from the subprocess exit status whether a SIGINT
4790 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4792 if (jp->sigint) /* TODO: do the same with all signals */
4793 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4795 if (jp->state == JOBDONE)
4802 * return 1 if there are stopped jobs, otherwise 0
4814 if (jp && jp->state == JOBSTOPPED) {
4815 out2str("You have stopped jobs.\n");
4824 /* ============ redir.c
4826 * Code for dealing with input/output redirection.
4829 #define EMPTY -2 /* marks an unused slot in redirtab */
4830 #define CLOSED -3 /* marks a slot of previously-closed fd */
4833 * Open a file in noclobber mode.
4834 * The code was copied from bash.
4837 noclobberopen(const char *fname)
4840 struct stat finfo, finfo2;
4843 * If the file exists and is a regular file, return an error
4846 r = stat(fname, &finfo);
4847 if (r == 0 && S_ISREG(finfo.st_mode)) {
4853 * If the file was not present (r != 0), make sure we open it
4854 * exclusively so that if it is created before we open it, our open
4855 * will fail. Make sure that we do not truncate an existing file.
4856 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4857 * file was not a regular file, we leave O_EXCL off.
4860 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4861 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4863 /* If the open failed, return the file descriptor right away. */
4868 * OK, the open succeeded, but the file may have been changed from a
4869 * non-regular file to a regular file between the stat and the open.
4870 * We are assuming that the O_EXCL open handles the case where FILENAME
4871 * did not exist and is symlinked to an existing file between the stat
4876 * If we can open it and fstat the file descriptor, and neither check
4877 * revealed that it was a regular file, and the file has not been
4878 * replaced, return the file descriptor.
4880 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4881 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4884 /* The file has been replaced. badness. */
4891 * Handle here documents. Normally we fork off a process to write the
4892 * data to a pipe. If the document is short, we can stuff the data in
4893 * the pipe without forking.
4895 /* openhere needs this forward reference */
4896 static void expandhere(union node *arg, int fd);
4898 openhere(union node *redir)
4904 ash_msg_and_raise_error("pipe call failed");
4905 if (redir->type == NHERE) {
4906 len = strlen(redir->nhere.doc->narg.text);
4907 if (len <= PIPE_BUF) {
4908 full_write(pip[1], redir->nhere.doc->narg.text, len);
4912 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4915 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4916 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4917 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4918 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4919 signal(SIGPIPE, SIG_DFL);
4920 if (redir->type == NHERE)
4921 full_write(pip[1], redir->nhere.doc->narg.text, len);
4923 expandhere(redir->nhere.doc, pip[1]);
4924 _exit(EXIT_SUCCESS);
4932 openredirect(union node *redir)
4937 switch (redir->nfile.type) {
4939 fname = redir->nfile.expfname;
4940 f = open(fname, O_RDONLY);
4945 fname = redir->nfile.expfname;
4946 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4951 #if ENABLE_ASH_BASH_COMPAT
4954 /* Take care of noclobber mode. */
4956 fname = redir->nfile.expfname;
4957 f = noclobberopen(fname);
4964 fname = redir->nfile.expfname;
4965 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4970 fname = redir->nfile.expfname;
4971 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4979 /* Fall through to eliminate warning. */
4980 /* Our single caller does this itself */
4987 f = openhere(redir);
4993 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4995 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
4999 * Copy a file descriptor to be >= to. Returns -1
5000 * if the source file descriptor is closed, EMPTY if there are no unused
5001 * file descriptors left.
5003 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5004 * old code was doing close(to) prior to copyfd() to achieve the same */
5006 COPYFD_EXACT = (int)~(INT_MAX),
5007 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5010 copyfd(int from, int to)
5014 if (to & COPYFD_EXACT) {
5015 to &= ~COPYFD_EXACT;
5017 newfd = dup2(from, to);
5019 newfd = fcntl(from, F_DUPFD, to);
5022 if (errno == EMFILE)
5024 /* Happens when source fd is not open: try "echo >&99" */
5025 ash_msg_and_raise_error("%d: %m", from);
5030 /* Struct def and variable are moved down to the first usage site */
5035 struct redirtab *next;
5038 struct two_fd_t two_fd[];
5040 #define redirlist (G_var.redirlist)
5042 static int need_to_remember(struct redirtab *rp, int fd)
5046 if (!rp) /* remembering was not requested */
5049 for (i = 0; i < rp->pair_count; i++) {
5050 if (rp->two_fd[i].orig == fd) {
5051 /* already remembered */
5058 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5059 static int is_hidden_fd(struct redirtab *rp, int fd)
5062 struct parsefile *pf;
5075 fd |= COPYFD_RESTORE;
5076 for (i = 0; i < rp->pair_count; i++) {
5077 if (rp->two_fd[i].copy == fd) {
5085 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5086 * old file descriptors are stashed away so that the redirection can be
5087 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5088 * standard output, and the standard error if it becomes a duplicate of
5089 * stdout, is saved in memory.
5091 /* flags passed to redirect */
5092 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5093 #define REDIR_SAVEFD2 03 /* set preverrout */
5095 redirect(union node *redir, int flags)
5097 struct redirtab *sv;
5102 int copied_fd2 = -1;
5112 if (flags & REDIR_PUSH) {
5113 union node *tmp = redir;
5116 #if ENABLE_ASH_BASH_COMPAT
5117 if (tmp->nfile.type == NTO2)
5120 tmp = tmp->nfile.next;
5122 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5123 sv->next = redirlist;
5124 sv->pair_count = sv_pos;
5126 sv->nullredirs = g_nullredirs - 1;
5128 while (sv_pos > 0) {
5130 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5135 fd = redir->nfile.fd;
5136 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5137 int right_fd = redir->ndup.dupfd;
5138 /* redirect from/to same file descriptor? */
5141 /* echo >&10 and 10 is a fd opened to the sh script? */
5142 if (is_hidden_fd(sv, right_fd)) {
5143 errno = EBADF; /* as if it is closed */
5144 ash_msg_and_raise_error("%d: %m", right_fd);
5148 newfd = openredirect(redir); /* always >= 0 */
5150 /* Descriptor wasn't open before redirect.
5151 * Mark it for close in the future */
5152 if (need_to_remember(sv, fd)) {
5153 goto remember_to_close;
5158 #if ENABLE_ASH_BASH_COMPAT
5161 if (need_to_remember(sv, fd)) {
5162 /* Copy old descriptor */
5163 i = fcntl(fd, F_DUPFD, 10);
5164 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5165 * are closed in popredir() in the child, preventing them from leaking
5166 * into child. (popredir() also cleans up the mess in case of failures)
5171 /* Strange error (e.g. "too many files" EMFILE?) */
5175 ash_msg_and_raise_error("%d: %m", fd);
5178 /* EBADF: it is not open - good, remember to close it */
5181 } else { /* fd is open, save its copy */
5182 /* "exec fd>&-" should not close fds
5183 * which point to script file(s).
5184 * Force them to be restored afterwards */
5185 if (is_hidden_fd(sv, fd))
5186 i |= COPYFD_RESTORE;
5190 sv->two_fd[sv_pos].orig = fd;
5191 sv->two_fd[sv_pos].copy = i;
5195 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5196 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5197 /* Don't want to trigger debugging */
5201 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5203 } else if (fd != newfd) { /* move newfd to fd */
5204 copyfd(newfd, fd | COPYFD_EXACT);
5205 #if ENABLE_ASH_BASH_COMPAT
5206 if (!(redir->nfile.type == NTO2 && fd == 2))
5210 #if ENABLE_ASH_BASH_COMPAT
5211 if (redir->nfile.type == NTO2 && fd == 1) {
5212 /* We already redirected it to fd 1, now copy it to 2 */
5218 } while ((redir = redir->nfile.next) != NULL);
5221 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5222 preverrout_fd = copied_fd2;
5226 * Undo the effects of the last redirection.
5229 popredir(int drop, int restore)
5231 struct redirtab *rp;
5234 if (--g_nullredirs >= 0)
5238 for (i = 0; i < rp->pair_count; i++) {
5239 int fd = rp->two_fd[i].orig;
5240 int copy = rp->two_fd[i].copy;
5241 if (copy == CLOSED) {
5246 if (copy != EMPTY) {
5247 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5248 copy &= ~COPYFD_RESTORE;
5250 copyfd(copy, fd | COPYFD_EXACT);
5252 close(copy & ~COPYFD_RESTORE);
5255 redirlist = rp->next;
5256 g_nullredirs = rp->nullredirs;
5262 * Undo all redirections. Called on error or interrupt.
5266 * Discard all saved file descriptors.
5269 clearredir(int drop)
5275 popredir(drop, /*restore:*/ 0);
5280 redirectsafe(union node *redir, int flags)
5283 volatile int saveint;
5284 struct jmploc *volatile savehandler = exception_handler;
5285 struct jmploc jmploc;
5288 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5289 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5291 exception_handler = &jmploc;
5292 redirect(redir, flags);
5294 exception_handler = savehandler;
5295 if (err && exception_type != EXERROR)
5296 longjmp(exception_handler->loc, 1);
5297 RESTORE_INT(saveint);
5302 /* ============ Routines to expand arguments to commands
5304 * We have to deal with backquotes, shell variables, and file metacharacters.
5307 #if ENABLE_SH_MATH_SUPPORT
5309 ash_arith(const char *s)
5311 arith_eval_hooks_t math_hooks;
5315 math_hooks.lookupvar = lookupvar;
5316 math_hooks.setvar = setvar2;
5317 math_hooks.endofname = endofname;
5320 result = arith(s, &errcode, &math_hooks);
5323 ash_msg_and_raise_error("exponent less than 0");
5325 ash_msg_and_raise_error("divide by zero");
5327 ash_msg_and_raise_error("expression recursion loop detected");
5328 raise_error_syntax(s);
5339 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5340 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5341 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5342 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5343 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5344 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5345 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5346 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5347 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5351 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5352 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5353 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5354 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5355 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5358 * Structure specifying which parts of the string should be searched
5359 * for IFS characters.
5362 struct ifsregion *next; /* next region in list */
5363 int begoff; /* offset of start of region */
5364 int endoff; /* offset of end of region */
5365 int nulonly; /* search for nul bytes only */
5369 struct strlist *list;
5370 struct strlist **lastp;
5373 /* output of current string */
5374 static char *expdest;
5375 /* list of back quote expressions */
5376 static struct nodelist *argbackq;
5377 /* first struct in list of ifs regions */
5378 static struct ifsregion ifsfirst;
5379 /* last struct in list */
5380 static struct ifsregion *ifslastp;
5381 /* holds expanded arg list */
5382 static struct arglist exparg;
5392 expdest = makestrspace(32, expdest);
5393 len = fmtstr(expdest, 32, arith_t_fmt, num);
5394 STADJUST(len, expdest);
5399 esclen(const char *start, const char *p)
5403 while (p > start && (unsigned char)*--p == CTLESC) {
5410 * Remove any CTLESC characters from a string.
5413 rmescapes(char *str, int flag)
5415 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5419 unsigned protect_against_glob;
5422 p = strpbrk(str, qchars);
5428 if (flag & RMESCAPE_ALLOC) {
5429 size_t len = p - str;
5430 size_t fulllen = len + strlen(p) + 1;
5432 if (flag & RMESCAPE_GROW) {
5433 int strloc = str - (char *)stackblock();
5434 r = makestrspace(fulllen, expdest);
5435 /* p and str may be invalidated by makestrspace */
5436 str = (char *)stackblock() + strloc;
5438 } else if (flag & RMESCAPE_HEAP) {
5439 r = ckmalloc(fulllen);
5441 r = stalloc(fulllen);
5445 q = (char *)memcpy(q, str, len) + len;
5449 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5450 globbing = flag & RMESCAPE_GLOB;
5451 protect_against_glob = globbing;
5453 if ((unsigned char)*p == CTLQUOTEMARK) {
5454 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5455 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5456 // Note: both inquotes and protect_against_glob only affect whether
5457 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5458 inquotes = ~inquotes;
5460 protect_against_glob = globbing;
5464 /* naked back slash */
5465 protect_against_glob = 0;
5468 if ((unsigned char)*p == CTLESC) {
5470 if (protect_against_glob && inquotes && *p != '/') {
5474 protect_against_glob = globbing;
5479 if (flag & RMESCAPE_GROW) {
5481 STADJUST(q - r + 1, expdest);
5485 #define pmatch(a, b) !fnmatch((a), (b), 0)
5488 * Prepare a pattern for a expmeta (internal glob(3)) call.
5490 * Returns an stalloced string.
5493 preglob(const char *pattern, int quoted, int flag)
5495 flag |= RMESCAPE_GLOB;
5497 flag |= RMESCAPE_QUOTED;
5499 return rmescapes((char *)pattern, flag);
5503 * Put a string on the stack.
5506 memtodest(const char *p, size_t len, int syntax, int quotes)
5510 q = makestrspace(quotes ? len * 2 : len, q);
5513 unsigned char c = *p++;
5517 int n = SIT(c, syntax);
5518 if (n == CCTL || n == CBACK)
5528 strtodest(const char *p, int syntax, int quotes)
5530 memtodest(p, strlen(p), syntax, quotes);
5534 * Record the fact that we have to scan this region of the
5535 * string for IFS characters.
5538 recordregion(int start, int end, int nulonly)
5540 struct ifsregion *ifsp;
5542 if (ifslastp == NULL) {
5546 ifsp = ckzalloc(sizeof(*ifsp));
5547 /*ifsp->next = NULL; - ckzalloc did it */
5548 ifslastp->next = ifsp;
5552 ifslastp->begoff = start;
5553 ifslastp->endoff = end;
5554 ifslastp->nulonly = nulonly;
5558 removerecordregions(int endoff)
5560 if (ifslastp == NULL)
5563 if (ifsfirst.endoff > endoff) {
5564 while (ifsfirst.next != NULL) {
5565 struct ifsregion *ifsp;
5567 ifsp = ifsfirst.next->next;
5568 free(ifsfirst.next);
5569 ifsfirst.next = ifsp;
5572 if (ifsfirst.begoff > endoff)
5575 ifslastp = &ifsfirst;
5576 ifsfirst.endoff = endoff;
5581 ifslastp = &ifsfirst;
5582 while (ifslastp->next && ifslastp->next->begoff < endoff)
5583 ifslastp=ifslastp->next;
5584 while (ifslastp->next != NULL) {
5585 struct ifsregion *ifsp;
5587 ifsp = ifslastp->next->next;
5588 free(ifslastp->next);
5589 ifslastp->next = ifsp;
5592 if (ifslastp->endoff > endoff)
5593 ifslastp->endoff = endoff;
5597 exptilde(char *startp, char *p, int flags)
5603 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5608 while ((c = *++p) != '\0') {
5615 if (flags & EXP_VARTILDE)
5625 if (*name == '\0') {
5626 home = lookupvar(homestr);
5628 pw = getpwnam(name);
5633 if (!home || !*home)
5636 startloc = expdest - (char *)stackblock();
5637 strtodest(home, SQSYNTAX, quotes);
5638 recordregion(startloc, expdest - (char *)stackblock(), 0);
5646 * Execute a command inside back quotes. If it's a builtin command, we
5647 * want to save its output in a block obtained from malloc. Otherwise
5648 * we fork off a subprocess and get the output of the command via a pipe.
5649 * Should be called with interrupts off.
5651 struct backcmd { /* result of evalbackcmd */
5652 int fd; /* file descriptor to read from */
5653 int nleft; /* number of chars in buffer */
5654 char *buf; /* buffer */
5655 struct job *jp; /* job structure for command */
5658 /* These forward decls are needed to use "eval" code for backticks handling: */
5659 static uint8_t back_exitstatus; /* exit status of backquoted command */
5660 #define EV_EXIT 01 /* exit after evaluating tree */
5661 static void evaltree(union node *, int);
5663 static void FAST_FUNC
5664 evalbackcmd(union node *n, struct backcmd *result)
5675 saveherefd = herefd;
5683 ash_msg_and_raise_error("pipe call failed");
5684 jp = makejob(/*n,*/ 1);
5685 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5690 copyfd(pip[1], 1 | COPYFD_EXACT);
5694 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5698 result->fd = pip[0];
5701 herefd = saveherefd;
5703 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5704 result->fd, result->buf, result->nleft, result->jp));
5708 * Expand stuff in backwards quotes.
5711 expbackq(union node *cmd, int quoted, int quotes)
5719 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5720 struct stackmark smark;
5723 setstackmark(&smark);
5725 startloc = dest - (char *)stackblock();
5727 evalbackcmd(cmd, &in);
5728 popstackmark(&smark);
5735 memtodest(p, i, syntax, quotes);
5739 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5740 TRACE(("expbackq: read returns %d\n", i));
5749 back_exitstatus = waitforjob(in.jp);
5753 /* Eat all trailing newlines */
5755 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5760 recordregion(startloc, dest - (char *)stackblock(), 0);
5761 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5762 (dest - (char *)stackblock()) - startloc,
5763 (dest - (char *)stackblock()) - startloc,
5764 stackblock() + startloc));
5767 #if ENABLE_SH_MATH_SUPPORT
5769 * Expand arithmetic expression. Backup to start of expression,
5770 * evaluate, place result in (backed up) result, adjust string position.
5783 * This routine is slightly over-complicated for
5784 * efficiency. Next we scan backwards looking for the
5785 * start of arithmetic.
5787 start = stackblock();
5794 while ((unsigned char)*p != CTLARI) {
5798 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5803 esc = esclen(start, p);
5813 removerecordregions(begoff);
5820 rmescapes(p + 2, 0);
5822 len = cvtnum(ash_arith(p + 2));
5825 recordregion(begoff, begoff + len, 0);
5829 /* argstr needs it */
5830 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5833 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5834 * characters to allow for further processing. Otherwise treat
5835 * $@ like $* since no splitting will be performed.
5837 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5838 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5839 * for correct expansion of "B=$A" word.
5842 argstr(char *p, int flags, struct strlist *var_str_list)
5844 static const char spclchars[] ALIGN1 = {
5852 CTLBACKQ | CTLQUOTE,
5853 #if ENABLE_SH_MATH_SUPPORT
5858 const char *reject = spclchars;
5859 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5860 int breakall = flags & EXP_WORD;
5865 if (!(flags & EXP_VARTILDE)) {
5867 } else if (flags & EXP_VARTILDE2) {
5872 if (flags & EXP_TILDE) {
5875 flags &= ~EXP_TILDE;
5878 if (*q == CTLESC && (flags & EXP_QWORD))
5881 p = exptilde(p, q, flags);
5884 startloc = expdest - (char *)stackblock();
5888 length += strcspn(p + length, reject);
5892 #if ENABLE_SH_MATH_SUPPORT
5896 /* c == '=' || c == ':' || c == CTLENDARI */
5902 expdest = stack_nputstr(p, length, expdest);
5903 newloc = expdest - (char *)stackblock();
5904 if (breakall && !inquotes && newloc > startloc) {
5905 recordregion(startloc, newloc, 0);
5916 if (flags & EXP_VARTILDE2) {
5920 flags |= EXP_VARTILDE2;
5925 * sort of a hack - expand tildes in variable
5926 * assignments (after the first '=' and after ':'s).
5935 case CTLENDVAR: /* ??? */
5938 /* "$@" syntax adherence hack */
5940 && memcmp(p, dolatstr, 4) == 0
5941 && ( p[4] == CTLQUOTEMARK
5942 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5945 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
5948 inquotes = !inquotes;
5961 p = evalvar(p, flags, var_str_list);
5965 case CTLBACKQ|CTLQUOTE:
5966 expbackq(argbackq->n, c, quotes);
5967 argbackq = argbackq->next;
5969 #if ENABLE_SH_MATH_SUPPORT
5982 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
5985 // This commented out code was added by James Simmons <jsimmons@infradead.org>
5986 // as part of a larger change when he added support for ${var/a/b}.
5987 // However, it broke # and % operators:
5991 //echo ${var#ab} abcdcd abcdcd
5992 //echo ${var##ab} abcdcd abcdcd
5993 //echo ${var#a*b} abcdcd ababcdcd (!)
5994 //echo ${var##a*b} cdcd cdcd
5995 //echo ${var#?} babcdcd ababcdcd (!)
5996 //echo ${var##?} babcdcd babcdcd
5997 //echo ${var#*} ababcdcd babcdcd (!)
5999 //echo ${var%cd} ababcd ababcd
6000 //echo ${var%%cd} ababcd abab (!)
6001 //echo ${var%c*d} ababcd ababcd
6002 //echo ${var%%c*d} abab ababcdcd (!)
6003 //echo ${var%?} ababcdc ababcdc
6004 //echo ${var%%?} ababcdc ababcdcd (!)
6005 //echo ${var%*} ababcdcd ababcdcd
6008 // Commenting it back out helped. Remove it completely if it really
6011 char *loc, *loc2; //, *full;
6017 int match; // = strlen(str);
6018 const char *s = loc2;
6025 match = pmatch(str, s); // this line was deleted
6027 // // chop off end if its '*'
6028 // full = strrchr(str, '*');
6029 // if (full && full != str)
6032 // // If str starts with '*' replace with s.
6033 // if ((*str == '*') && strlen(s) >= match) {
6034 // full = xstrdup(s);
6035 // strncpy(full+strlen(s)-match+1, str+1, match-1);
6037 // full = xstrndup(str, match);
6038 // match = strncmp(s, full, strlen(full));
6042 if (match) // if (!match)
6044 if (quotes && (unsigned char)*loc == CTLESC)
6053 scanright(char *startp, char *rmesc, char *rmescend, char *pattern, int quotes, int match_at_start)
6055 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6056 int try2optimize = match_at_start;
6062 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6063 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6064 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6066 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6067 * and on each iteration they go back two/one char until they reach the beginning.
6068 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6070 /* TODO: document in what other circumstances we are called. */
6072 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6075 const char *s = loc2;
6076 if (match_at_start) {
6080 match = pmatch(pattern, s);
6081 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6085 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6087 /* Maybe we can optimize this:
6088 * if pattern ends with unescaped *, we can avoid checking
6089 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6090 * it wont match truncated "raw_value_of_" strings too.
6092 unsigned plen = strlen(pattern);
6093 /* Does it end with "*"? */
6094 if (plen != 0 && pattern[--plen] == '*') {
6095 /* "xxxx*" is not escaped */
6096 /* "xxx\*" is escaped */
6097 /* "xx\\*" is not escaped */
6098 /* "x\\\*" is escaped */
6100 while (plen != 0 && pattern[--plen] == '\\')
6103 break; /* ends with unescaped "*" */
6111 esc = esclen(startp, loc);
6122 static void varunset(const char *, const char *, const char *, int) NORETURN;
6124 varunset(const char *end, const char *var, const char *umsg, int varflags)
6130 msg = "parameter not set";
6132 if ((unsigned char)*end == CTLENDVAR) {
6133 if (varflags & VSNUL)
6139 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6142 #if ENABLE_ASH_BASH_COMPAT
6144 parse_sub_pattern(char *arg, int inquotes)
6146 char *idx, *repl = NULL;
6155 /* Only the first '/' seen is our separator */
6162 if (!inquotes && c == '\\' && arg[1] == '\\')
6163 arg++; /* skip both \\, not just first one */
6170 #endif /* ENABLE_ASH_BASH_COMPAT */
6173 subevalvar(char *p, char *str, int strloc, int subtype,
6174 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6176 struct nodelist *saveargbackq = argbackq;
6179 char *rmesc, *rmescend;
6180 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6181 IF_ASH_BASH_COMPAT(char null = '\0';)
6182 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6183 int saveherefd = herefd;
6184 int amount, workloc, resetloc;
6186 char *(*scan)(char*, char*, char*, char*, int, int);
6189 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6191 STPUTC('\0', expdest);
6192 herefd = saveherefd;
6193 argbackq = saveargbackq;
6194 startp = (char *)stackblock() + startloc;
6198 setvar(str, startp, 0);
6199 amount = startp - expdest;
6200 STADJUST(amount, expdest);
6203 #if ENABLE_ASH_BASH_COMPAT
6205 loc = str = stackblock() + strloc;
6206 /* Read POS in ${var:POS:LEN} */
6207 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6208 len = str - startp - 1;
6210 /* *loc != '\0', guaranteed by parser */
6214 /* Adjust the length by the number of escapes */
6215 for (ptr = startp; ptr < (str - 1); ptr++) {
6216 if ((unsigned char)*ptr == CTLESC) {
6224 if (*loc++ == ':') {
6228 /* Skip POS in ${var:POS:LEN} */
6230 while (*loc && *loc != ':') {
6232 * bash complains on: var=qwe; echo ${var:1a:123}
6234 ash_msg_and_raise_error(msg_illnum, str);
6238 if (*loc++ == ':') {
6242 if (pos >= orig_len) {
6246 if (len > (orig_len - pos))
6247 len = orig_len - pos;
6249 for (str = startp; pos; str++, pos--) {
6250 if (quotes && (unsigned char)*str == CTLESC)
6253 for (loc = startp; len; len--) {
6254 if (quotes && (unsigned char)*str == CTLESC)
6259 amount = loc - expdest;
6260 STADJUST(amount, expdest);
6265 varunset(p, str, startp, varflags);
6268 resetloc = expdest - (char *)stackblock();
6270 /* We'll comeback here if we grow the stack while handling
6271 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6272 * stack will need rebasing, and we'll need to remove our work
6275 IF_ASH_BASH_COMPAT(restart:)
6277 amount = expdest - ((char *)stackblock() + resetloc);
6278 STADJUST(-amount, expdest);
6279 startp = (char *)stackblock() + startloc;
6282 rmescend = (char *)stackblock() + strloc;
6284 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6285 if (rmesc != startp) {
6287 startp = (char *)stackblock() + startloc;
6291 str = (char *)stackblock() + strloc;
6292 preglob(str, varflags & VSQUOTE, 0);
6293 workloc = expdest - (char *)stackblock();
6295 #if ENABLE_ASH_BASH_COMPAT
6296 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6300 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6305 /* If there's no pattern to match, return the expansion unmolested */
6314 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6316 /* No match, advance */
6317 char *restart_detect = stackblock();
6319 STPUTC(*idx, expdest);
6320 if (quotes && (unsigned char)*idx == CTLESC) {
6323 STPUTC(*idx, expdest);
6325 if (stackblock() != restart_detect)
6330 /* continue; - prone to quadratic behavior, smarter code: */
6333 if (str[0] == '*') {
6334 /* Pattern is "*foo". If "*foo" does not match "long_string",
6335 * it would never match "ong_string" etc, no point in trying.
6342 if (subtype == VSREPLACEALL) {
6344 if (quotes && (unsigned char)*idx == CTLESC)
6353 for (loc = repl; *loc; loc++) {
6354 char *restart_detect = stackblock();
6355 STPUTC(*loc, expdest);
6356 if (stackblock() != restart_detect)
6361 if (subtype == VSREPLACE) {
6363 char *restart_detect = stackblock();
6364 STPUTC(*idx, expdest);
6365 if (stackblock() != restart_detect)
6374 /* We've put the replaced text into a buffer at workloc, now
6375 * move it to the right place and adjust the stack.
6377 startp = stackblock() + startloc;
6378 STPUTC('\0', expdest);
6379 memmove(startp, stackblock() + workloc, len);
6380 startp[len++] = '\0';
6381 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6382 STADJUST(-amount, expdest);
6385 #endif /* ENABLE_ASH_BASH_COMPAT */
6387 subtype -= VSTRIMRIGHT;
6389 if (subtype < 0 || subtype > 7)
6392 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6393 zero = subtype >> 1;
6394 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6395 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6397 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6400 memmove(startp, loc, str - loc);
6401 loc = startp + (str - loc) - 1;
6404 amount = loc - expdest;
6405 STADJUST(amount, expdest);
6411 * Add the value of a specialized variable to the stack string.
6412 * name parameter (examples):
6413 * ash -c 'echo $1' name:'1='
6414 * ash -c 'echo $qwe' name:'qwe='
6415 * ash -c 'echo $$' name:'$='
6416 * ash -c 'echo ${$}' name:'$='
6417 * ash -c 'echo ${$##q}' name:'$=q'
6418 * ash -c 'echo ${#$}' name:'$='
6419 * note: examples with bad shell syntax:
6420 * ash -c 'echo ${#$1}' name:'$=1'
6421 * ash -c 'echo ${#1#}' name:'1=#'
6423 static NOINLINE ssize_t
6424 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6431 int subtype = varflags & VSTYPE;
6432 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6433 int quoted = varflags & VSQUOTE;
6434 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6444 num = shellparam.nparam;
6452 goto check_1char_name;
6454 expdest = makestrspace(NOPTS, expdest);
6455 for (i = NOPTS - 1; i >= 0; i--) {
6457 USTPUTC(optletters(i), expdest);
6463 /* handles cases similar to ${#$1} */
6464 if (name[2] != '\0')
6465 raise_error_syntax("bad substitution");
6472 if (quoted && (flags & EXP_FULL)) {
6473 /* note: this is not meant as PEOF value */
6474 sep = 1 << CHAR_BIT;
6479 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6480 i = SIT(sep, syntax);
6481 if (quotes && (i == CCTL || i == CBACK))
6487 while ((p = *ap++) != NULL) {
6490 partlen = strlen(p);
6493 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6494 memtodest(p, partlen, syntax, quotes);
6500 if (subtype == VSPLUS || subtype == VSLENGTH) {
6506 /* note: may put NUL despite sep != 0
6507 * (see sep = 1 << CHAR_BIT above) */
6513 } /* case '@' and '*' */
6524 num = atoi(name); /* number(name) fails on ${N#str} etc */
6525 if (num < 0 || num > shellparam.nparam)
6527 p = num ? shellparam.p[num - 1] : arg0;
6530 /* NB: name has form "VAR=..." */
6532 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6533 * which should be considered before we check variables. */
6535 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6539 str = var_str_list->text;
6540 eq = strchr(str, '=');
6541 if (!eq) /* stop at first non-assignment */
6544 if (name_len == (unsigned)(eq - str)
6545 && strncmp(str, name, name_len) == 0
6548 /* goto value; - WRONG! */
6549 /* think "A=1 A=2 B=$A" */
6551 var_str_list = var_str_list->next;
6552 } while (var_str_list);
6556 p = lookupvar(name);
6562 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6563 memtodest(p, len, syntax, quotes);
6567 if (subtype == VSPLUS || subtype == VSLENGTH)
6568 STADJUST(-len, expdest);
6573 * Expand a variable, and return a pointer to the next character in the
6577 evalvar(char *p, int flags, struct strlist *var_str_list)
6588 varflags = (unsigned char) *p++;
6589 subtype = varflags & VSTYPE;
6590 quoted = varflags & VSQUOTE;
6592 easy = (!quoted || (*var == '@' && shellparam.nparam));
6593 startloc = expdest - (char *)stackblock();
6594 p = strchr(p, '=') + 1;
6597 varlen = varvalue(var, varflags, flags, var_str_list);
6598 if (varflags & VSNUL)
6601 if (subtype == VSPLUS) {
6602 varlen = -1 - varlen;
6606 if (subtype == VSMINUS) {
6610 p, flags | EXP_TILDE |
6611 (quoted ? EXP_QWORD : EXP_WORD),
6621 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6623 if (subevalvar(p, var, /* strloc: */ 0,
6624 subtype, startloc, varflags,
6630 * Remove any recorded regions beyond
6633 removerecordregions(startloc);
6643 if (varlen < 0 && uflag)
6644 varunset(p, var, 0, 0);
6646 if (subtype == VSLENGTH) {
6647 cvtnum(varlen > 0 ? varlen : 0);
6651 if (subtype == VSNORMAL) {
6662 case VSTRIMRIGHTMAX:
6663 #if ENABLE_ASH_BASH_COMPAT
6676 * Terminate the string and start recording the pattern
6679 STPUTC('\0', expdest);
6680 patloc = expdest - (char *)stackblock();
6681 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6683 //TODO: | EXP_REDIR too? All other such places do it too
6684 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6687 int amount = expdest - (
6688 (char *)stackblock() + patloc - 1
6690 STADJUST(-amount, expdest);
6692 /* Remove any recorded regions beyond start of variable */
6693 removerecordregions(startloc);
6695 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6699 if (subtype != VSNORMAL) { /* skip to end of alternative */
6702 unsigned char c = *p++;
6705 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6707 argbackq = argbackq->next;
6708 } else if (c == CTLVAR) {
6709 if ((*p++ & VSTYPE) != VSNORMAL)
6711 } else if (c == CTLENDVAR) {
6721 * Break the argument string into pieces based upon IFS and add the
6722 * strings to the argument list. The regions of the string to be
6723 * searched for IFS characters have been stored by recordregion.
6726 ifsbreakup(char *string, struct arglist *arglist)
6728 struct ifsregion *ifsp;
6733 const char *ifs, *realifs;
6738 if (ifslastp != NULL) {
6741 realifs = ifsset() ? ifsval() : defifs;
6744 p = string + ifsp->begoff;
6745 nulonly = ifsp->nulonly;
6746 ifs = nulonly ? nullstr : realifs;
6748 while (p < string + ifsp->endoff) {
6750 if ((unsigned char)*p == CTLESC)
6752 if (!strchr(ifs, *p)) {
6757 ifsspc = (strchr(defifs, *p) != NULL);
6758 /* Ignore IFS whitespace at start */
6759 if (q == start && ifsspc) {
6765 sp = stzalloc(sizeof(*sp));
6767 *arglist->lastp = sp;
6768 arglist->lastp = &sp->next;
6772 if (p >= string + ifsp->endoff) {
6776 if ((unsigned char)*p == CTLESC)
6778 if (strchr(ifs, *p) == NULL) {
6782 if (strchr(defifs, *p) == NULL) {
6797 } while (ifsp != NULL);
6806 sp = stzalloc(sizeof(*sp));
6808 *arglist->lastp = sp;
6809 arglist->lastp = &sp->next;
6815 struct ifsregion *p;
6820 struct ifsregion *ifsp;
6826 ifsfirst.next = NULL;
6831 * Add a file name to the list.
6834 addfname(const char *name)
6838 sp = stzalloc(sizeof(*sp));
6839 sp->text = ststrdup(name);
6841 exparg.lastp = &sp->next;
6844 static char *expdir;
6847 * Do metacharacter (i.e. *, ?, [...]) expansion.
6850 expmeta(char *enddir, char *name)
6865 for (p = name; *p; p++) {
6866 if (*p == '*' || *p == '?')
6868 else if (*p == '[') {
6875 if (*q == '/' || *q == '\0')
6882 } else if (*p == '\\')
6884 else if (*p == '/') {
6891 if (metaflag == 0) { /* we've reached the end of the file name */
6892 if (enddir != expdir)
6900 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6911 } while (p < start);
6913 if (enddir == expdir) {
6915 } else if (enddir == expdir + 1 && *expdir == '/') {
6924 if (enddir != expdir)
6926 if (*endname == 0) {
6938 while (!pending_int && (dp = readdir(dirp)) != NULL) {
6939 if (dp->d_name[0] == '.' && !matchdot)
6941 if (pmatch(start, dp->d_name)) {
6943 strcpy(enddir, dp->d_name);
6946 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6949 expmeta(p, endname);
6958 static struct strlist *
6959 msort(struct strlist *list, int len)
6961 struct strlist *p, *q = NULL;
6962 struct strlist **lpp;
6970 for (n = half; --n >= 0;) {
6974 q->next = NULL; /* terminate first half of list */
6975 q = msort(list, half); /* sort first half of list */
6976 p = msort(p, len - half); /* sort second half */
6979 #if ENABLE_LOCALE_SUPPORT
6980 if (strcoll(p->text, q->text) < 0)
6982 if (strcmp(p->text, q->text) < 0)
7006 * Sort the results of file name expansion. It calculates the number of
7007 * strings to sort and then calls msort (short for merge sort) to do the
7010 static struct strlist *
7011 expsort(struct strlist *str)
7017 for (sp = str; sp; sp = sp->next)
7019 return msort(str, len);
7023 expandmeta(struct strlist *str /*, int flag*/)
7025 static const char metachars[] ALIGN1 = {
7028 /* TODO - EXP_REDIR */
7031 struct strlist **savelastp;
7037 if (!strpbrk(str->text, metachars))
7039 savelastp = exparg.lastp;
7042 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7044 int i = strlen(str->text);
7045 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7053 if (exparg.lastp == savelastp) {
7058 *exparg.lastp = str;
7059 rmescapes(str->text, 0);
7060 exparg.lastp = &str->next;
7062 *exparg.lastp = NULL;
7063 *savelastp = sp = expsort(*savelastp);
7064 while (sp->next != NULL)
7066 exparg.lastp = &sp->next;
7073 * Perform variable substitution and command substitution on an argument,
7074 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7075 * perform splitting and file name expansion. When arglist is NULL, perform
7076 * here document expansion.
7079 expandarg(union node *arg, struct arglist *arglist, int flag)
7084 argbackq = arg->narg.backquote;
7085 STARTSTACKSTR(expdest);
7086 ifsfirst.next = NULL;
7088 argstr(arg->narg.text, flag,
7089 /* var_str_list: */ arglist ? arglist->list : NULL);
7090 p = _STPUTC('\0', expdest);
7092 if (arglist == NULL) {
7093 return; /* here document expanded */
7095 p = grabstackstr(p);
7096 exparg.lastp = &exparg.list;
7100 if (flag & EXP_FULL) {
7101 ifsbreakup(p, &exparg);
7102 *exparg.lastp = NULL;
7103 exparg.lastp = &exparg.list;
7104 expandmeta(exparg.list /*, flag*/);
7106 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7108 sp = stzalloc(sizeof(*sp));
7111 exparg.lastp = &sp->next;
7115 *exparg.lastp = NULL;
7117 *arglist->lastp = exparg.list;
7118 arglist->lastp = exparg.lastp;
7123 * Expand shell variables and backquotes inside a here document.
7126 expandhere(union node *arg, int fd)
7129 expandarg(arg, (struct arglist *)NULL, 0);
7130 full_write(fd, stackblock(), expdest - (char *)stackblock());
7134 * Returns true if the pattern matches the string.
7137 patmatch(char *pattern, const char *string)
7139 return pmatch(preglob(pattern, 0, 0), string);
7143 * See if a pattern matches in a case statement.
7146 casematch(union node *pattern, char *val)
7148 struct stackmark smark;
7151 setstackmark(&smark);
7152 argbackq = pattern->narg.backquote;
7153 STARTSTACKSTR(expdest);
7155 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7156 /* var_str_list: */ NULL);
7157 STACKSTRNUL(expdest);
7158 result = patmatch(stackblock(), val);
7159 popstackmark(&smark);
7164 /* ============ find_command */
7168 int (*builtin)(int, char **) FAST_FUNC;
7169 /* unsigned flags; */
7171 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7172 /* "regular" builtins always take precedence over commands,
7173 * regardless of PATH=....%builtin... position */
7174 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7175 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7178 smallint cmdtype; /* CMDxxx */
7181 /* index >= 0 for commands without path (slashes) */
7182 /* (TODO: what exactly does the value mean? PATH position?) */
7183 /* index == -1 for commands with slashes */
7184 /* index == (-2 - applet_no) for NOFORK applets */
7185 const struct builtincmd *cmd;
7186 struct funcnode *func;
7189 /* values of cmdtype */
7190 #define CMDUNKNOWN -1 /* no entry in table for command */
7191 #define CMDNORMAL 0 /* command is an executable program */
7192 #define CMDFUNCTION 1 /* command is a shell function */
7193 #define CMDBUILTIN 2 /* command is a shell builtin */
7195 /* action to find_command() */
7196 #define DO_ERR 0x01 /* prints errors */
7197 #define DO_ABS 0x02 /* checks absolute paths */
7198 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7199 #define DO_ALTPATH 0x08 /* using alternate path */
7200 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7202 static void find_command(char *, struct cmdentry *, int, const char *);
7205 /* ============ Hashing commands */
7208 * When commands are first encountered, they are entered in a hash table.
7209 * This ensures that a full path search will not have to be done for them
7210 * on each invocation.
7212 * We should investigate converting to a linear search, even though that
7213 * would make the command name "hash" a misnomer.
7217 struct tblentry *next; /* next entry in hash chain */
7218 union param param; /* definition of builtin function */
7219 smallint cmdtype; /* CMDxxx */
7220 char rehash; /* if set, cd done since entry created */
7221 char cmdname[1]; /* name of command */
7224 static struct tblentry **cmdtable;
7225 #define INIT_G_cmdtable() do { \
7226 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7229 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7233 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7237 #if ENABLE_FEATURE_SH_STANDALONE
7238 if (applet_no >= 0) {
7239 if (APPLET_IS_NOEXEC(applet_no)) {
7242 run_applet_no_and_exit(applet_no, argv);
7244 /* re-exec ourselves with the new arguments */
7245 execve(bb_busybox_exec_path, argv, envp);
7246 /* If they called chroot or otherwise made the binary no longer
7247 * executable, fall through */
7254 execve(cmd, argv, envp);
7255 } while (errno == EINTR);
7257 execve(cmd, argv, envp);
7263 if (errno == ENOEXEC) {
7267 for (ap = argv; *ap; ap++)
7269 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7271 ap[0] = cmd = (char *)DEFAULT_SHELL;
7274 while ((*ap++ = *argv++) != NULL)
7283 * Exec a program. Never returns. If you change this routine, you may
7284 * have to change the find_command routine as well.
7286 static void shellexec(char **, const char *, int) NORETURN;
7288 shellexec(char **argv, const char *path, int idx)
7294 #if ENABLE_FEATURE_SH_STANDALONE
7298 clearredir(/*drop:*/ 1);
7299 envp = listvars(VEXPORT, VUNSET, 0);
7300 if (strchr(argv[0], '/') != NULL
7301 #if ENABLE_FEATURE_SH_STANDALONE
7302 || (applet_no = find_applet_by_name(argv[0])) >= 0
7305 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7309 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7310 if (--idx < 0 && pathopt == NULL) {
7311 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7312 if (errno != ENOENT && errno != ENOTDIR)
7319 /* Map to POSIX errors */
7331 exitstatus = exerrno;
7332 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7333 argv[0], e, suppress_int));
7334 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7339 printentry(struct tblentry *cmdp)
7345 idx = cmdp->param.index;
7348 name = path_advance(&path, cmdp->cmdname);
7350 } while (--idx >= 0);
7351 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7355 * Clear out command entries. The argument specifies the first entry in
7356 * PATH which has changed.
7359 clearcmdentry(int firstchange)
7361 struct tblentry **tblp;
7362 struct tblentry **pp;
7363 struct tblentry *cmdp;
7366 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7368 while ((cmdp = *pp) != NULL) {
7369 if ((cmdp->cmdtype == CMDNORMAL &&
7370 cmdp->param.index >= firstchange)
7371 || (cmdp->cmdtype == CMDBUILTIN &&
7372 builtinloc >= firstchange)
7385 * Locate a command in the command hash table. If "add" is nonzero,
7386 * add the command to the table if it is not already present. The
7387 * variable "lastcmdentry" is set to point to the address of the link
7388 * pointing to the entry, so that delete_cmd_entry can delete the
7391 * Interrupts must be off if called with add != 0.
7393 static struct tblentry **lastcmdentry;
7395 static struct tblentry *
7396 cmdlookup(const char *name, int add)
7398 unsigned int hashval;
7400 struct tblentry *cmdp;
7401 struct tblentry **pp;
7404 hashval = (unsigned char)*p << 4;
7406 hashval += (unsigned char)*p++;
7408 pp = &cmdtable[hashval % CMDTABLESIZE];
7409 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7410 if (strcmp(cmdp->cmdname, name) == 0)
7414 if (add && cmdp == NULL) {
7415 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7417 /* + 1 - already done because
7418 * tblentry::cmdname is char[1] */);
7419 /*cmdp->next = NULL; - ckzalloc did it */
7420 cmdp->cmdtype = CMDUNKNOWN;
7421 strcpy(cmdp->cmdname, name);
7428 * Delete the command entry returned on the last lookup.
7431 delete_cmd_entry(void)
7433 struct tblentry *cmdp;
7436 cmdp = *lastcmdentry;
7437 *lastcmdentry = cmdp->next;
7438 if (cmdp->cmdtype == CMDFUNCTION)
7439 freefunc(cmdp->param.func);
7445 * Add a new command entry, replacing any existing command entry for
7446 * the same name - except special builtins.
7449 addcmdentry(char *name, struct cmdentry *entry)
7451 struct tblentry *cmdp;
7453 cmdp = cmdlookup(name, 1);
7454 if (cmdp->cmdtype == CMDFUNCTION) {
7455 freefunc(cmdp->param.func);
7457 cmdp->cmdtype = entry->cmdtype;
7458 cmdp->param = entry->u;
7462 static int FAST_FUNC
7463 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7465 struct tblentry **pp;
7466 struct tblentry *cmdp;
7468 struct cmdentry entry;
7471 if (nextopt("r") != '\0') {
7476 if (*argptr == NULL) {
7477 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7478 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7479 if (cmdp->cmdtype == CMDNORMAL)
7487 while ((name = *argptr) != NULL) {
7488 cmdp = cmdlookup(name, 0);
7490 && (cmdp->cmdtype == CMDNORMAL
7491 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7495 find_command(name, &entry, DO_ERR, pathval());
7496 if (entry.cmdtype == CMDUNKNOWN)
7504 * Called when a cd is done. Marks all commands so the next time they
7505 * are executed they will be rehashed.
7510 struct tblentry **pp;
7511 struct tblentry *cmdp;
7513 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7514 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7515 if (cmdp->cmdtype == CMDNORMAL
7516 || (cmdp->cmdtype == CMDBUILTIN
7517 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7527 * Fix command hash table when PATH changed.
7528 * Called before PATH is changed. The argument is the new value of PATH;
7529 * pathval() still returns the old value at this point.
7530 * Called with interrupts off.
7532 static void FAST_FUNC
7533 changepath(const char *new)
7541 firstchange = 9999; /* assume no change */
7547 if ((*old == '\0' && *new == ':')
7548 || (*old == ':' && *new == '\0'))
7550 old = new; /* ignore subsequent differences */
7554 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7560 if (builtinloc < 0 && idx_bltin >= 0)
7561 builtinloc = idx_bltin; /* zap builtins */
7562 if (builtinloc >= 0 && idx_bltin < 0)
7564 clearcmdentry(firstchange);
7565 builtinloc = idx_bltin;
7580 #define TENDBQUOTE 12
7597 typedef smallint token_id_t;
7599 /* first char is indicating which tokens mark the end of a list */
7600 static const char *const tokname_array[] = {
7614 #define KWDOFFSET 13
7615 /* the following are keywords */
7637 static char buf[16];
7640 //if (tok < TSEMI) return tokname_array[tok] + 1;
7641 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7646 sprintf(buf + (tok >= TSEMI), "%s%c",
7647 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7651 /* Wrapper around strcmp for qsort/bsearch/... */
7653 pstrcmp(const void *a, const void *b)
7655 return strcmp((char*) a, (*(char**) b) + 1);
7658 static const char *const *
7659 findkwd(const char *s)
7661 return bsearch(s, tokname_array + KWDOFFSET,
7662 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7663 sizeof(tokname_array[0]), pstrcmp);
7667 * Locate and print what a word is...
7670 describe_command(char *command, int describe_command_verbose)
7672 struct cmdentry entry;
7673 struct tblentry *cmdp;
7674 #if ENABLE_ASH_ALIAS
7675 const struct alias *ap;
7677 const char *path = pathval();
7679 if (describe_command_verbose) {
7683 /* First look at the keywords */
7684 if (findkwd(command)) {
7685 out1str(describe_command_verbose ? " is a shell keyword" : command);
7689 #if ENABLE_ASH_ALIAS
7690 /* Then look at the aliases */
7691 ap = lookupalias(command, 0);
7693 if (!describe_command_verbose) {
7698 out1fmt(" is an alias for %s", ap->val);
7702 /* Then check if it is a tracked alias */
7703 cmdp = cmdlookup(command, 0);
7705 entry.cmdtype = cmdp->cmdtype;
7706 entry.u = cmdp->param;
7708 /* Finally use brute force */
7709 find_command(command, &entry, DO_ABS, path);
7712 switch (entry.cmdtype) {
7714 int j = entry.u.index;
7720 p = path_advance(&path, command);
7724 if (describe_command_verbose) {
7726 (cmdp ? " a tracked alias for" : nullstr), p
7735 if (describe_command_verbose) {
7736 out1str(" is a shell function");
7743 if (describe_command_verbose) {
7744 out1fmt(" is a %sshell builtin",
7745 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7746 "special " : nullstr
7754 if (describe_command_verbose) {
7755 out1str(": not found\n");
7764 static int FAST_FUNC
7765 typecmd(int argc UNUSED_PARAM, char **argv)
7771 /* type -p ... ? (we don't bother checking for 'p') */
7772 if (argv[1] && argv[1][0] == '-') {
7777 err |= describe_command(argv[i++], verbose);
7782 #if ENABLE_ASH_CMDCMD
7783 static int FAST_FUNC
7784 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7792 while ((c = nextopt("pvV")) != '\0')
7794 verify |= VERIFY_VERBOSE;
7796 verify |= VERIFY_BRIEF;
7801 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7802 if (verify && (*argptr != NULL)) {
7803 return describe_command(*argptr, verify - VERIFY_BRIEF);
7811 /* ============ eval.c */
7813 static int funcblocksize; /* size of structures in function */
7814 static int funcstringsize; /* size of strings in node */
7815 static void *funcblock; /* block to allocate function from */
7816 static char *funcstring; /* block to allocate strings from */
7818 /* flags in argument to evaltree */
7819 #define EV_EXIT 01 /* exit after evaluating tree */
7820 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7821 #define EV_BACKCMD 04 /* command executing within back quotes */
7823 static const uint8_t nodesize[N_NUMBER] = {
7824 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7825 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7826 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7827 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7828 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7829 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7830 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7831 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7832 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7833 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7834 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7835 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7836 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7837 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7838 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7839 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7840 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7841 #if ENABLE_ASH_BASH_COMPAT
7842 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7844 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7845 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7846 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7847 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7848 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7849 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7850 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7851 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7852 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7855 static void calcsize(union node *n);
7858 sizenodelist(struct nodelist *lp)
7861 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7868 calcsize(union node *n)
7872 funcblocksize += nodesize[n->type];
7875 calcsize(n->ncmd.redirect);
7876 calcsize(n->ncmd.args);
7877 calcsize(n->ncmd.assign);
7880 sizenodelist(n->npipe.cmdlist);
7885 calcsize(n->nredir.redirect);
7886 calcsize(n->nredir.n);
7893 calcsize(n->nbinary.ch2);
7894 calcsize(n->nbinary.ch1);
7897 calcsize(n->nif.elsepart);
7898 calcsize(n->nif.ifpart);
7899 calcsize(n->nif.test);
7902 funcstringsize += strlen(n->nfor.var) + 1;
7903 calcsize(n->nfor.body);
7904 calcsize(n->nfor.args);
7907 calcsize(n->ncase.cases);
7908 calcsize(n->ncase.expr);
7911 calcsize(n->nclist.body);
7912 calcsize(n->nclist.pattern);
7913 calcsize(n->nclist.next);
7917 sizenodelist(n->narg.backquote);
7918 funcstringsize += strlen(n->narg.text) + 1;
7919 calcsize(n->narg.next);
7922 #if ENABLE_ASH_BASH_COMPAT
7929 calcsize(n->nfile.fname);
7930 calcsize(n->nfile.next);
7934 calcsize(n->ndup.vname);
7935 calcsize(n->ndup.next);
7939 calcsize(n->nhere.doc);
7940 calcsize(n->nhere.next);
7943 calcsize(n->nnot.com);
7949 nodeckstrdup(char *s)
7951 char *rtn = funcstring;
7953 strcpy(funcstring, s);
7954 funcstring += strlen(s) + 1;
7958 static union node *copynode(union node *);
7960 static struct nodelist *
7961 copynodelist(struct nodelist *lp)
7963 struct nodelist *start;
7964 struct nodelist **lpp;
7969 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7970 (*lpp)->n = copynode(lp->n);
7972 lpp = &(*lpp)->next;
7979 copynode(union node *n)
7986 funcblock = (char *) funcblock + nodesize[n->type];
7990 new->ncmd.redirect = copynode(n->ncmd.redirect);
7991 new->ncmd.args = copynode(n->ncmd.args);
7992 new->ncmd.assign = copynode(n->ncmd.assign);
7995 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7996 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8001 new->nredir.redirect = copynode(n->nredir.redirect);
8002 new->nredir.n = copynode(n->nredir.n);
8009 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8010 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8013 new->nif.elsepart = copynode(n->nif.elsepart);
8014 new->nif.ifpart = copynode(n->nif.ifpart);
8015 new->nif.test = copynode(n->nif.test);
8018 new->nfor.var = nodeckstrdup(n->nfor.var);
8019 new->nfor.body = copynode(n->nfor.body);
8020 new->nfor.args = copynode(n->nfor.args);
8023 new->ncase.cases = copynode(n->ncase.cases);
8024 new->ncase.expr = copynode(n->ncase.expr);
8027 new->nclist.body = copynode(n->nclist.body);
8028 new->nclist.pattern = copynode(n->nclist.pattern);
8029 new->nclist.next = copynode(n->nclist.next);
8033 new->narg.backquote = copynodelist(n->narg.backquote);
8034 new->narg.text = nodeckstrdup(n->narg.text);
8035 new->narg.next = copynode(n->narg.next);
8038 #if ENABLE_ASH_BASH_COMPAT
8045 new->nfile.fname = copynode(n->nfile.fname);
8046 new->nfile.fd = n->nfile.fd;
8047 new->nfile.next = copynode(n->nfile.next);
8051 new->ndup.vname = copynode(n->ndup.vname);
8052 new->ndup.dupfd = n->ndup.dupfd;
8053 new->ndup.fd = n->ndup.fd;
8054 new->ndup.next = copynode(n->ndup.next);
8058 new->nhere.doc = copynode(n->nhere.doc);
8059 new->nhere.fd = n->nhere.fd;
8060 new->nhere.next = copynode(n->nhere.next);
8063 new->nnot.com = copynode(n->nnot.com);
8066 new->type = n->type;
8071 * Make a copy of a parse tree.
8073 static struct funcnode *
8074 copyfunc(union node *n)
8079 funcblocksize = offsetof(struct funcnode, n);
8082 blocksize = funcblocksize;
8083 f = ckmalloc(blocksize + funcstringsize);
8084 funcblock = (char *) f + offsetof(struct funcnode, n);
8085 funcstring = (char *) f + blocksize;
8092 * Define a shell function.
8095 defun(char *name, union node *func)
8097 struct cmdentry entry;
8100 entry.cmdtype = CMDFUNCTION;
8101 entry.u.func = copyfunc(func);
8102 addcmdentry(name, &entry);
8106 /* Reasons for skipping commands (see comment on breakcmd routine) */
8107 #define SKIPBREAK (1 << 0)
8108 #define SKIPCONT (1 << 1)
8109 #define SKIPFUNC (1 << 2)
8110 #define SKIPFILE (1 << 3)
8111 #define SKIPEVAL (1 << 4)
8112 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8113 static int skipcount; /* number of levels to skip */
8114 static int funcnest; /* depth of function calls */
8115 static int loopnest; /* current loop nesting level */
8117 /* Forward decl way out to parsing code - dotrap needs it */
8118 static int evalstring(char *s, int mask);
8120 /* Called to execute a trap.
8121 * Single callsite - at the end of evaltree().
8122 * If we return non-zero, exaltree raises EXEXIT exception.
8124 * Perhaps we should avoid entering new trap handlers
8125 * while we are executing a trap handler. [is it a TODO?]
8134 savestatus = exitstatus;
8138 TRACE(("dotrap entered\n"));
8139 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8146 /* non-trapped SIGINT is handled separately by raise_interrupt,
8147 * don't upset it by resetting gotsig[SIGINT-1] */
8148 if (sig == SIGINT && !t)
8151 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8155 want_exexit = evalstring(t, SKIPEVAL);
8156 exitstatus = savestatus;
8158 TRACE(("dotrap returns %d\n", want_exexit));
8163 TRACE(("dotrap returns 0\n"));
8167 /* forward declarations - evaluation is fairly recursive business... */
8168 static void evalloop(union node *, int);
8169 static void evalfor(union node *, int);
8170 static void evalcase(union node *, int);
8171 static void evalsubshell(union node *, int);
8172 static void expredir(union node *);
8173 static void evalpipe(union node *, int);
8174 static void evalcommand(union node *, int);
8175 static int evalbltin(const struct builtincmd *, int, char **);
8176 static void prehash(union node *);
8179 * Evaluate a parse tree. The value is left in the global variable
8183 evaltree(union node *n, int flags)
8185 struct jmploc *volatile savehandler = exception_handler;
8186 struct jmploc jmploc;
8188 void (*evalfn)(union node *, int);
8192 SAVE_INT(int_level);
8195 TRACE(("evaltree(NULL) called\n"));
8198 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8200 exception_handler = &jmploc;
8202 int err = setjmp(jmploc.loc);
8204 /* if it was a signal, check for trap handlers */
8205 if (exception_type == EXSIG) {
8206 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8207 exception_type, err));
8210 /* continue on the way out */
8211 TRACE(("exception %d in evaltree, propagating err=%d\n",
8212 exception_type, err));
8213 exception_handler = savehandler;
8214 longjmp(exception_handler->loc, err);
8221 out1fmt("Node type = %d\n", n->type);
8226 evaltree(n->nnot.com, EV_TESTED);
8227 status = !exitstatus;
8230 expredir(n->nredir.redirect);
8231 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8233 evaltree(n->nredir.n, flags & EV_TESTED);
8234 status = exitstatus;
8236 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8239 evalfn = evalcommand;
8241 if (eflag && !(flags & EV_TESTED))
8253 evalfn = evalsubshell;
8266 #error NAND + 1 != NOR
8268 #if NOR + 1 != NSEMI
8269 #error NOR + 1 != NSEMI
8271 unsigned is_or = n->type - NAND;
8274 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8276 if (!exitstatus == is_or)
8289 evaltree(n->nif.test, EV_TESTED);
8292 if (exitstatus == 0) {
8296 if (n->nif.elsepart) {
8297 n = n->nif.elsepart;
8302 defun(n->narg.text, n->narg.next);
8306 exitstatus = status;
8311 exception_handler = savehandler;
8313 if (checkexit & exitstatus)
8314 evalskip |= SKIPEVAL;
8315 else if (pending_sig && dotrap())
8318 if (flags & EV_EXIT) {
8320 raise_exception(EXEXIT);
8323 RESTORE_INT(int_level);
8324 TRACE(("leaving evaltree (no interrupts)\n"));
8327 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8330 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8333 evalloop(union node *n, int flags)
8343 evaltree(n->nbinary.ch1, EV_TESTED);
8346 if (evalskip == SKIPCONT && --skipcount <= 0) {
8350 if (evalskip == SKIPBREAK && --skipcount <= 0)
8355 if (n->type != NWHILE)
8359 evaltree(n->nbinary.ch2, flags);
8360 status = exitstatus;
8365 exitstatus = status;
8369 evalfor(union node *n, int flags)
8371 struct arglist arglist;
8374 struct stackmark smark;
8376 setstackmark(&smark);
8377 arglist.list = NULL;
8378 arglist.lastp = &arglist.list;
8379 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8380 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8385 *arglist.lastp = NULL;
8390 for (sp = arglist.list; sp; sp = sp->next) {
8391 setvar(n->nfor.var, sp->text, 0);
8392 evaltree(n->nfor.body, flags);
8394 if (evalskip == SKIPCONT && --skipcount <= 0) {
8398 if (evalskip == SKIPBREAK && --skipcount <= 0)
8405 popstackmark(&smark);
8409 evalcase(union node *n, int flags)
8413 struct arglist arglist;
8414 struct stackmark smark;
8416 setstackmark(&smark);
8417 arglist.list = NULL;
8418 arglist.lastp = &arglist.list;
8419 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8421 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8422 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8423 if (casematch(patp, arglist.list->text)) {
8424 if (evalskip == 0) {
8425 evaltree(cp->nclist.body, flags);
8432 popstackmark(&smark);
8436 * Kick off a subshell to evaluate a tree.
8439 evalsubshell(union node *n, int flags)
8442 int backgnd = (n->type == NBACKGND);
8445 expredir(n->nredir.redirect);
8446 if (!backgnd && flags & EV_EXIT && !trap[0])
8449 jp = makejob(/*n,*/ 1);
8450 if (forkshell(jp, n, backgnd) == 0) {
8454 flags &=~ EV_TESTED;
8456 redirect(n->nredir.redirect, 0);
8457 evaltreenr(n->nredir.n, flags);
8462 status = waitforjob(jp);
8463 exitstatus = status;
8468 * Compute the names of the files in a redirection list.
8470 static void fixredir(union node *, const char *, int);
8472 expredir(union node *n)
8476 for (redir = n; redir; redir = redir->nfile.next) {
8480 fn.lastp = &fn.list;
8481 switch (redir->type) {
8485 #if ENABLE_ASH_BASH_COMPAT
8490 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8491 #if ENABLE_ASH_BASH_COMPAT
8494 redir->nfile.expfname = fn.list->text;
8497 case NTOFD: /* >& */
8498 if (redir->ndup.vname) {
8499 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8500 if (fn.list == NULL)
8501 ash_msg_and_raise_error("redir error");
8502 #if ENABLE_ASH_BASH_COMPAT
8503 //FIXME: we used expandarg with different args!
8504 if (!isdigit_str9(fn.list->text)) {
8505 /* >&file, not >&fd */
8506 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8507 ash_msg_and_raise_error("redir error");
8509 goto store_expfname;
8512 fixredir(redir, fn.list->text, 1);
8520 * Evaluate a pipeline. All the processes in the pipeline are children
8521 * of the process creating the pipeline. (This differs from some versions
8522 * of the shell, which make the last process in a pipeline the parent
8526 evalpipe(union node *n, int flags)
8529 struct nodelist *lp;
8534 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8536 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8540 jp = makejob(/*n,*/ pipelen);
8542 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8546 if (pipe(pip) < 0) {
8548 ash_msg_and_raise_error("pipe call failed");
8551 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8564 evaltreenr(lp->n, flags);
8570 /* Don't want to trigger debugging */
8574 if (n->npipe.pipe_backgnd == 0) {
8575 exitstatus = waitforjob(jp);
8576 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8582 * Controls whether the shell is interactive or not.
8585 setinteractive(int on)
8587 static smallint is_interactive;
8589 if (++on == is_interactive)
8591 is_interactive = on;
8595 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8596 if (is_interactive > 1) {
8597 /* Looks like they want an interactive shell */
8598 static smallint did_banner;
8601 /* note: ash and hush share this string */
8602 out1fmt("\n\n%s %s\n"
8603 "Enter 'help' for a list of built-in commands."
8606 "built-in shell (ash)"
8620 setinteractive(iflag);
8622 #if ENABLE_FEATURE_EDITING_VI
8624 line_input_state->flags |= VI_MODE;
8626 line_input_state->flags &= ~VI_MODE;
8628 viflag = 0; /* forcibly keep the option off */
8632 static struct localvar *localvars;
8635 * Called after a function returns.
8636 * Interrupts must be off.
8641 struct localvar *lvp;
8644 while ((lvp = localvars) != NULL) {
8645 localvars = lvp->next;
8647 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8648 if (vp == NULL) { /* $- saved */
8649 memcpy(optlist, lvp->text, sizeof(optlist));
8650 free((char*)lvp->text);
8652 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8656 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8657 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8658 free((char*)vp->text);
8659 vp->flags = lvp->flags;
8660 vp->text = lvp->text;
8667 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8669 volatile struct shparam saveparam;
8670 struct localvar *volatile savelocalvars;
8671 struct jmploc *volatile savehandler;
8672 struct jmploc jmploc;
8675 saveparam = shellparam;
8676 savelocalvars = localvars;
8677 e = setjmp(jmploc.loc);
8682 savehandler = exception_handler;
8683 exception_handler = &jmploc;
8685 shellparam.malloced = 0;
8689 shellparam.nparam = argc - 1;
8690 shellparam.p = argv + 1;
8691 #if ENABLE_ASH_GETOPTS
8692 shellparam.optind = 1;
8693 shellparam.optoff = -1;
8695 evaltree(&func->n, flags & EV_TESTED);
8701 localvars = savelocalvars;
8702 freeparam(&shellparam);
8703 shellparam = saveparam;
8704 exception_handler = savehandler;
8706 evalskip &= ~SKIPFUNC;
8710 #if ENABLE_ASH_CMDCMD
8712 parse_command_args(char **argv, const char **path)
8725 if (c == '-' && !*cp) {
8732 *path = bb_default_path;
8735 /* run 'typecmd' for other options */
8746 * Make a variable a local variable. When a variable is made local, it's
8747 * value and flags are saved in a localvar structure. The saved values
8748 * will be restored when the shell function returns. We handle the name
8749 * "-" as a special case.
8754 struct localvar *lvp;
8759 lvp = ckzalloc(sizeof(struct localvar));
8760 if (LONE_DASH(name)) {
8762 p = ckmalloc(sizeof(optlist));
8763 lvp->text = memcpy(p, optlist, sizeof(optlist));
8768 vpp = hashvar(name);
8769 vp = *findvar(vpp, name);
8770 eq = strchr(name, '=');
8773 setvareq(name, VSTRFIXED);
8775 setvar(name, NULL, VSTRFIXED);
8776 vp = *vpp; /* the new variable */
8777 lvp->flags = VUNSET;
8779 lvp->text = vp->text;
8780 lvp->flags = vp->flags;
8781 vp->flags |= VSTRFIXED|VTEXTFIXED;
8787 lvp->next = localvars;
8793 * The "local" command.
8795 static int FAST_FUNC
8796 localcmd(int argc UNUSED_PARAM, char **argv)
8801 while ((name = *argv++) != NULL) {
8807 static int FAST_FUNC
8808 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8813 static int FAST_FUNC
8814 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8819 static int FAST_FUNC
8820 execcmd(int argc UNUSED_PARAM, char **argv)
8823 iflag = 0; /* exit on error */
8826 shellexec(argv + 1, pathval(), 0);
8832 * The return command.
8834 static int FAST_FUNC
8835 returncmd(int argc UNUSED_PARAM, char **argv)
8838 * If called outside a function, do what ksh does;
8839 * skip the rest of the file.
8841 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8842 return argv[1] ? number(argv[1]) : exitstatus;
8845 /* Forward declarations for builtintab[] */
8846 static int breakcmd(int, char **) FAST_FUNC;
8847 static int dotcmd(int, char **) FAST_FUNC;
8848 static int evalcmd(int, char **) FAST_FUNC;
8849 static int exitcmd(int, char **) FAST_FUNC;
8850 static int exportcmd(int, char **) FAST_FUNC;
8851 #if ENABLE_ASH_GETOPTS
8852 static int getoptscmd(int, char **) FAST_FUNC;
8854 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8855 static int helpcmd(int, char **) FAST_FUNC;
8857 #if ENABLE_SH_MATH_SUPPORT
8858 static int letcmd(int, char **) FAST_FUNC;
8860 static int readcmd(int, char **) FAST_FUNC;
8861 static int setcmd(int, char **) FAST_FUNC;
8862 static int shiftcmd(int, char **) FAST_FUNC;
8863 static int timescmd(int, char **) FAST_FUNC;
8864 static int trapcmd(int, char **) FAST_FUNC;
8865 static int umaskcmd(int, char **) FAST_FUNC;
8866 static int unsetcmd(int, char **) FAST_FUNC;
8867 static int ulimitcmd(int, char **) FAST_FUNC;
8869 #define BUILTIN_NOSPEC "0"
8870 #define BUILTIN_SPECIAL "1"
8871 #define BUILTIN_REGULAR "2"
8872 #define BUILTIN_SPEC_REG "3"
8873 #define BUILTIN_ASSIGN "4"
8874 #define BUILTIN_SPEC_ASSG "5"
8875 #define BUILTIN_REG_ASSG "6"
8876 #define BUILTIN_SPEC_REG_ASSG "7"
8878 /* Stubs for calling non-FAST_FUNC's */
8879 #if ENABLE_ASH_BUILTIN_ECHO
8880 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8882 #if ENABLE_ASH_BUILTIN_PRINTF
8883 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8885 #if ENABLE_ASH_BUILTIN_TEST
8886 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8889 /* Keep these in proper order since it is searched via bsearch() */
8890 static const struct builtincmd builtintab[] = {
8891 { BUILTIN_SPEC_REG "." , dotcmd },
8892 { BUILTIN_SPEC_REG ":" , truecmd },
8893 #if ENABLE_ASH_BUILTIN_TEST
8894 { BUILTIN_REGULAR "[" , testcmd },
8895 #if ENABLE_ASH_BASH_COMPAT
8896 { BUILTIN_REGULAR "[[" , testcmd },
8899 #if ENABLE_ASH_ALIAS
8900 { BUILTIN_REG_ASSG "alias" , aliascmd },
8903 { BUILTIN_REGULAR "bg" , fg_bgcmd },
8905 { BUILTIN_SPEC_REG "break" , breakcmd },
8906 { BUILTIN_REGULAR "cd" , cdcmd },
8907 { BUILTIN_NOSPEC "chdir" , cdcmd },
8908 #if ENABLE_ASH_CMDCMD
8909 { BUILTIN_REGULAR "command" , commandcmd },
8911 { BUILTIN_SPEC_REG "continue", breakcmd },
8912 #if ENABLE_ASH_BUILTIN_ECHO
8913 { BUILTIN_REGULAR "echo" , echocmd },
8915 { BUILTIN_SPEC_REG "eval" , evalcmd },
8916 { BUILTIN_SPEC_REG "exec" , execcmd },
8917 { BUILTIN_SPEC_REG "exit" , exitcmd },
8918 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
8919 { BUILTIN_REGULAR "false" , falsecmd },
8921 { BUILTIN_REGULAR "fg" , fg_bgcmd },
8923 #if ENABLE_ASH_GETOPTS
8924 { BUILTIN_REGULAR "getopts" , getoptscmd },
8926 { BUILTIN_NOSPEC "hash" , hashcmd },
8927 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8928 { BUILTIN_NOSPEC "help" , helpcmd },
8931 { BUILTIN_REGULAR "jobs" , jobscmd },
8932 { BUILTIN_REGULAR "kill" , killcmd },
8934 #if ENABLE_SH_MATH_SUPPORT
8935 { BUILTIN_NOSPEC "let" , letcmd },
8937 { BUILTIN_ASSIGN "local" , localcmd },
8938 #if ENABLE_ASH_BUILTIN_PRINTF
8939 { BUILTIN_REGULAR "printf" , printfcmd },
8941 { BUILTIN_NOSPEC "pwd" , pwdcmd },
8942 { BUILTIN_REGULAR "read" , readcmd },
8943 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8944 { BUILTIN_SPEC_REG "return" , returncmd },
8945 { BUILTIN_SPEC_REG "set" , setcmd },
8946 { BUILTIN_SPEC_REG "shift" , shiftcmd },
8947 #if ENABLE_ASH_BASH_COMPAT
8948 { BUILTIN_SPEC_REG "source" , dotcmd },
8950 #if ENABLE_ASH_BUILTIN_TEST
8951 { BUILTIN_REGULAR "test" , testcmd },
8953 { BUILTIN_SPEC_REG "times" , timescmd },
8954 { BUILTIN_SPEC_REG "trap" , trapcmd },
8955 { BUILTIN_REGULAR "true" , truecmd },
8956 { BUILTIN_NOSPEC "type" , typecmd },
8957 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
8958 { BUILTIN_REGULAR "umask" , umaskcmd },
8959 #if ENABLE_ASH_ALIAS
8960 { BUILTIN_REGULAR "unalias" , unaliascmd },
8962 { BUILTIN_SPEC_REG "unset" , unsetcmd },
8963 { BUILTIN_REGULAR "wait" , waitcmd },
8966 /* Should match the above table! */
8967 #define COMMANDCMD (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 #define EXECCMD (builtintab + \
8976 1 * ENABLE_ASH_BUILTIN_TEST + \
8977 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8978 1 * ENABLE_ASH_ALIAS + \
8979 1 * ENABLE_ASH_JOB_CONTROL + \
8981 1 * ENABLE_ASH_CMDCMD + \
8983 ENABLE_ASH_BUILTIN_ECHO + \
8987 * Search the table of builtin commands.
8989 static struct builtincmd *
8990 find_builtin(const char *name)
8992 struct builtincmd *bp;
8995 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9002 * Execute a simple command.
9005 isassignment(const char *p)
9007 const char *q = endofname(p);
9012 static int FAST_FUNC
9013 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9015 /* Preserve exitstatus of a previous possible redirection
9016 * as POSIX mandates */
9017 return back_exitstatus;
9020 evalcommand(union node *cmd, int flags)
9022 static const struct builtincmd null_bltin = {
9023 "\0\0", bltincmd /* why three NULs? */
9025 struct stackmark smark;
9027 struct arglist arglist;
9028 struct arglist varlist;
9031 const struct strlist *sp;
9032 struct cmdentry cmdentry;
9039 struct builtincmd *bcmd;
9040 smallint cmd_is_exec;
9041 smallint pseudovarflag = 0;
9043 /* First expand the arguments. */
9044 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9045 setstackmark(&smark);
9046 back_exitstatus = 0;
9048 cmdentry.cmdtype = CMDBUILTIN;
9049 cmdentry.u.cmd = &null_bltin;
9050 varlist.lastp = &varlist.list;
9051 *varlist.lastp = NULL;
9052 arglist.lastp = &arglist.list;
9053 *arglist.lastp = NULL;
9056 if (cmd->ncmd.args) {
9057 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9058 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9061 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9062 struct strlist **spp;
9064 spp = arglist.lastp;
9065 if (pseudovarflag && isassignment(argp->narg.text))
9066 expandarg(argp, &arglist, EXP_VARTILDE);
9068 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9070 for (sp = *spp; sp; sp = sp->next)
9074 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9075 for (sp = arglist.list; sp; sp = sp->next) {
9076 TRACE(("evalcommand arg: %s\n", sp->text));
9077 *nargv++ = sp->text;
9082 if (iflag && funcnest == 0 && argc > 0)
9083 lastarg = nargv[-1];
9086 expredir(cmd->ncmd.redirect);
9087 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9090 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9091 struct strlist **spp;
9094 spp = varlist.lastp;
9095 expandarg(argp, &varlist, EXP_VARTILDE);
9098 * Modify the command lookup path, if a PATH= assignment
9102 if (varequal(p, path))
9106 /* Print the command if xflag is set. */
9109 const char *p = " %s";
9112 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9115 for (n = 0; n < 2; n++) {
9117 fdprintf(preverrout_fd, p, sp->text);
9125 safe_write(preverrout_fd, "\n", 1);
9131 /* Now locate the command. */
9133 const char *oldpath;
9134 int cmd_flag = DO_ERR;
9139 find_command(argv[0], &cmdentry, cmd_flag, path);
9140 if (cmdentry.cmdtype == CMDUNKNOWN) {
9141 flush_stdout_stderr();
9146 /* implement bltin and command here */
9147 if (cmdentry.cmdtype != CMDBUILTIN)
9150 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9151 if (cmdentry.u.cmd == EXECCMD)
9153 #if ENABLE_ASH_CMDCMD
9154 if (cmdentry.u.cmd == COMMANDCMD) {
9156 nargv = parse_command_args(argv, &path);
9159 argc -= nargv - argv;
9161 cmd_flag |= DO_NOFUNC;
9169 /* We have a redirection error. */
9171 raise_exception(EXERROR);
9173 exitstatus = status;
9177 /* Execute the command. */
9178 switch (cmdentry.cmdtype) {
9181 #if ENABLE_FEATURE_SH_NOFORK
9182 /* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9183 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
9185 /* find_command() encodes applet_no as (-2 - applet_no) */
9186 int applet_no = (- cmdentry.u.index - 2);
9187 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9188 listsetvar(varlist.list, VEXPORT|VSTACK);
9189 /* run <applet>_main() */
9190 exitstatus = run_nofork_applet(applet_no, argv);
9195 /* Fork off a child process if necessary. */
9196 if (!(flags & EV_EXIT) || trap[0]) {
9198 jp = makejob(/*cmd,*/ 1);
9199 if (forkshell(jp, cmd, FORK_FG) != 0) {
9200 exitstatus = waitforjob(jp);
9202 TRACE(("forked child exited with %d\n", exitstatus));
9207 listsetvar(varlist.list, VEXPORT|VSTACK);
9208 shellexec(argv, path, cmdentry.u.index);
9212 cmdenviron = varlist.list;
9214 struct strlist *list = cmdenviron;
9216 if (spclbltin > 0 || argc == 0) {
9218 if (cmd_is_exec && argc > 1)
9221 listsetvar(list, i);
9223 /* Tight loop with builtins only:
9224 * "while kill -0 $child; do true; done"
9225 * will never exit even if $child died, unless we do this
9226 * to reap the zombie and make kill detect that it's gone: */
9227 dowait(DOWAIT_NONBLOCK, NULL);
9229 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9231 int i = exception_type;
9236 exit_status = 128 + SIGINT;
9238 exit_status = 128 + pending_sig;
9239 exitstatus = exit_status;
9240 if (i == EXINT || spclbltin > 0) {
9242 longjmp(exception_handler->loc, 1);
9249 listsetvar(varlist.list, 0);
9250 /* See above for the rationale */
9251 dowait(DOWAIT_NONBLOCK, NULL);
9252 if (evalfun(cmdentry.u.func, argc, argv, flags))
9258 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9260 /* dsl: I think this is intended to be used to support
9261 * '_' in 'vi' command mode during line editing...
9262 * However I implemented that within libedit itself.
9264 setvar("_", lastarg, 0);
9266 popstackmark(&smark);
9270 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9272 char *volatile savecmdname;
9273 struct jmploc *volatile savehandler;
9274 struct jmploc jmploc;
9277 savecmdname = commandname;
9278 i = setjmp(jmploc.loc);
9281 savehandler = exception_handler;
9282 exception_handler = &jmploc;
9283 commandname = argv[0];
9285 optptr = NULL; /* initialize nextopt */
9286 exitstatus = (*cmd->builtin)(argc, argv);
9287 flush_stdout_stderr();
9289 exitstatus |= ferror(stdout);
9291 commandname = savecmdname;
9292 exception_handler = savehandler;
9298 goodname(const char *p)
9300 return !*endofname(p);
9305 * Search for a command. This is called before we fork so that the
9306 * location of the command will be available in the parent as well as
9307 * the child. The check for "goodname" is an overly conservative
9308 * check that the name will not be subject to expansion.
9311 prehash(union node *n)
9313 struct cmdentry entry;
9315 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9316 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9320 /* ============ Builtin commands
9322 * Builtin commands whose functions are closely tied to evaluation
9323 * are implemented here.
9327 * Handle break and continue commands. Break, continue, and return are
9328 * all handled by setting the evalskip flag. The evaluation routines
9329 * above all check this flag, and if it is set they start skipping
9330 * commands rather than executing them. The variable skipcount is
9331 * the number of loops to break/continue, or the number of function
9332 * levels to return. (The latter is always 1.) It should probably
9333 * be an error to break out of more loops than exist, but it isn't
9334 * in the standard shell so we don't make it one here.
9336 static int FAST_FUNC
9337 breakcmd(int argc UNUSED_PARAM, char **argv)
9339 int n = argv[1] ? number(argv[1]) : 1;
9342 ash_msg_and_raise_error(msg_illnum, argv[1]);
9346 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9353 /* ============ input.c
9355 * This implements the input routines used by the parser.
9359 INPUT_PUSH_FILE = 1,
9360 INPUT_NOFILE_OK = 2,
9363 static smallint checkkwd;
9364 /* values of checkkwd variable */
9365 #define CHKALIAS 0x1
9370 * Push a string back onto the input at this current parsefile level.
9371 * We handle aliases this way.
9373 #if !ENABLE_ASH_ALIAS
9374 #define pushstring(s, ap) pushstring(s)
9377 pushstring(char *s, struct alias *ap)
9384 if (g_parsefile->strpush) {
9385 sp = ckzalloc(sizeof(*sp));
9386 sp->prev = g_parsefile->strpush;
9388 sp = &(g_parsefile->basestrpush);
9390 g_parsefile->strpush = sp;
9391 sp->prev_string = g_parsefile->next_to_pgetc;
9392 sp->prev_left_in_line = g_parsefile->left_in_line;
9393 #if ENABLE_ASH_ALIAS
9396 ap->flag |= ALIASINUSE;
9400 g_parsefile->next_to_pgetc = s;
9401 g_parsefile->left_in_line = len;
9408 struct strpush *sp = g_parsefile->strpush;
9411 #if ENABLE_ASH_ALIAS
9413 if (g_parsefile->next_to_pgetc[-1] == ' '
9414 || g_parsefile->next_to_pgetc[-1] == '\t'
9416 checkkwd |= CHKALIAS;
9418 if (sp->string != sp->ap->val) {
9421 sp->ap->flag &= ~ALIASINUSE;
9422 if (sp->ap->flag & ALIASDEAD) {
9423 unalias(sp->ap->name);
9427 g_parsefile->next_to_pgetc = sp->prev_string;
9428 g_parsefile->left_in_line = sp->prev_left_in_line;
9429 g_parsefile->strpush = sp->prev;
9430 if (sp != &(g_parsefile->basestrpush))
9435 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9436 //it peeks whether it is &>, and then pushes back both chars.
9437 //This function needs to save last *next_to_pgetc to buf[0]
9438 //to make two pungetc() reliable. Currently,
9439 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9444 char *buf = g_parsefile->buf;
9446 g_parsefile->next_to_pgetc = buf;
9447 #if ENABLE_FEATURE_EDITING
9449 if (!iflag || g_parsefile->fd != STDIN_FILENO)
9450 nr = nonblock_safe_read(g_parsefile->fd, buf, IBUFSIZ - 1);
9452 #if ENABLE_FEATURE_TAB_COMPLETION
9453 line_input_state->path_lookup = pathval();
9455 nr = read_line_input(cmdedit_prompt, buf, IBUFSIZ, line_input_state);
9457 /* Ctrl+C pressed */
9466 if (nr < 0 && errno == 0) {
9467 /* Ctrl+D pressed */
9472 nr = nonblock_safe_read(g_parsefile->fd, buf, IBUFSIZ - 1);
9476 /* nonblock_safe_read() handles this problem */
9478 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9479 int flags = fcntl(0, F_GETFL);
9480 if (flags >= 0 && (flags & O_NONBLOCK)) {
9481 flags &= ~O_NONBLOCK;
9482 if (fcntl(0, F_SETFL, flags) >= 0) {
9483 out2str("sh: turning off NDELAY mode\n");
9494 * Refill the input buffer and return the next input character:
9496 * 1) If a string was pushed back on the input, pop it;
9497 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9498 * or we are reading from a string so we can't refill the buffer,
9500 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9501 * 4) Process input up to the next newline, deleting nul characters.
9503 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9504 #define pgetc_debug(...) ((void)0)
9511 while (g_parsefile->strpush) {
9512 #if ENABLE_ASH_ALIAS
9513 if (g_parsefile->left_in_line == -1
9514 && g_parsefile->strpush->ap
9515 && g_parsefile->next_to_pgetc[-1] != ' '
9516 && g_parsefile->next_to_pgetc[-1] != '\t'
9518 pgetc_debug("preadbuffer PEOA");
9523 /* try "pgetc" now: */
9524 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9525 g_parsefile->left_in_line,
9526 g_parsefile->next_to_pgetc,
9527 g_parsefile->next_to_pgetc);
9528 if (--g_parsefile->left_in_line >= 0)
9529 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9531 /* on both branches above g_parsefile->left_in_line < 0.
9532 * "pgetc" needs refilling.
9535 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9536 * pungetc() may increment it a few times.
9537 * Assuming it won't increment it to less than -90.
9539 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9540 pgetc_debug("preadbuffer PEOF1");
9541 /* even in failure keep left_in_line and next_to_pgetc
9542 * in lock step, for correct multi-layer pungetc.
9543 * left_in_line was decremented before preadbuffer(),
9544 * must inc next_to_pgetc: */
9545 g_parsefile->next_to_pgetc++;
9549 more = g_parsefile->left_in_buffer;
9551 flush_stdout_stderr();
9555 /* don't try reading again */
9556 g_parsefile->left_in_line = -99;
9557 pgetc_debug("preadbuffer PEOF2");
9558 g_parsefile->next_to_pgetc++;
9563 /* Find out where's the end of line.
9564 * Set g_parsefile->left_in_line
9565 * and g_parsefile->left_in_buffer acordingly.
9566 * NUL chars are deleted.
9568 q = g_parsefile->next_to_pgetc;
9576 memmove(q, q + 1, more);
9580 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9586 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9587 if (g_parsefile->left_in_line < 0)
9592 g_parsefile->left_in_buffer = more;
9597 out2str(g_parsefile->next_to_pgetc);
9601 pgetc_debug("preadbuffer at %d:%p'%s'",
9602 g_parsefile->left_in_line,
9603 g_parsefile->next_to_pgetc,
9604 g_parsefile->next_to_pgetc);
9605 return (unsigned char)*g_parsefile->next_to_pgetc++;
9608 #define pgetc_as_macro() \
9609 (--g_parsefile->left_in_line >= 0 \
9610 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9617 pgetc_debug("pgetc_fast at %d:%p'%s'",
9618 g_parsefile->left_in_line,
9619 g_parsefile->next_to_pgetc,
9620 g_parsefile->next_to_pgetc);
9621 return pgetc_as_macro();
9624 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9625 # define pgetc_fast() pgetc()
9627 # define pgetc_fast() pgetc_as_macro()
9630 #if ENABLE_ASH_ALIAS
9632 pgetc_without_PEOA(void)
9636 pgetc_debug("pgetc_fast at %d:%p'%s'",
9637 g_parsefile->left_in_line,
9638 g_parsefile->next_to_pgetc,
9639 g_parsefile->next_to_pgetc);
9641 } while (c == PEOA);
9645 # define pgetc_without_PEOA() pgetc()
9649 * Read a line from the script.
9652 pfgets(char *line, int len)
9658 while (--nleft > 0) {
9659 c = pgetc_without_PEOA();
9674 * Undo the last call to pgetc. Only one character may be pushed back.
9675 * PEOF may be pushed back.
9680 g_parsefile->left_in_line++;
9681 g_parsefile->next_to_pgetc--;
9682 pgetc_debug("pushed back to %d:%p'%s'",
9683 g_parsefile->left_in_line,
9684 g_parsefile->next_to_pgetc,
9685 g_parsefile->next_to_pgetc);
9689 * To handle the "." command, a stack of input files is used. Pushfile
9690 * adds a new entry to the stack and popfile restores the previous level.
9695 struct parsefile *pf;
9697 pf = ckzalloc(sizeof(*pf));
9698 pf->prev = g_parsefile;
9700 /*pf->strpush = NULL; - ckzalloc did it */
9701 /*pf->basestrpush.prev = NULL;*/
9708 struct parsefile *pf = g_parsefile;
9716 g_parsefile = pf->prev;
9722 * Return to top level.
9727 while (g_parsefile != &basepf)
9732 * Close the file(s) that the shell is reading commands from. Called
9733 * after a fork is done.
9739 if (g_parsefile->fd > 0) {
9740 close(g_parsefile->fd);
9741 g_parsefile->fd = 0;
9746 * Like setinputfile, but takes an open file descriptor. Call this with
9750 setinputfd(int fd, int push)
9752 close_on_exec_on(fd);
9755 g_parsefile->buf = NULL;
9757 g_parsefile->fd = fd;
9758 if (g_parsefile->buf == NULL)
9759 g_parsefile->buf = ckmalloc(IBUFSIZ);
9760 g_parsefile->left_in_buffer = 0;
9761 g_parsefile->left_in_line = 0;
9762 g_parsefile->linno = 1;
9766 * Set the input to take input from a file. If push is set, push the
9767 * old input onto the stack first.
9770 setinputfile(const char *fname, int flags)
9776 fd = open(fname, O_RDONLY);
9778 if (flags & INPUT_NOFILE_OK)
9780 ash_msg_and_raise_error("can't open '%s'", fname);
9783 fd2 = copyfd(fd, 10);
9786 ash_msg_and_raise_error("out of file descriptors");
9789 setinputfd(fd, flags & INPUT_PUSH_FILE);
9796 * Like setinputfile, but takes input from a string.
9799 setinputstring(char *string)
9803 g_parsefile->next_to_pgetc = string;
9804 g_parsefile->left_in_line = strlen(string);
9805 g_parsefile->buf = NULL;
9806 g_parsefile->linno = 1;
9811 /* ============ mail.c
9813 * Routines to check for mail.
9818 #define MAXMBOXES 10
9820 /* times of mailboxes */
9821 static time_t mailtime[MAXMBOXES];
9822 /* Set if MAIL or MAILPATH is changed. */
9823 static smallint mail_var_path_changed;
9826 * Print appropriate message(s) if mail has arrived.
9827 * If mail_var_path_changed is set,
9828 * then the value of MAIL has mail_var_path_changed,
9829 * so we just update the values.
9838 struct stackmark smark;
9841 setstackmark(&smark);
9842 mpath = mpathset() ? mpathval() : mailval();
9843 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9844 p = path_advance(&mpath, nullstr);
9849 for (q = p; *q; q++)
9855 q[-1] = '\0'; /* delete trailing '/' */
9856 if (stat(p, &statb) < 0) {
9860 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9863 pathopt ? pathopt : "you have mail"
9866 *mtp = statb.st_mtime;
9868 mail_var_path_changed = 0;
9869 popstackmark(&smark);
9872 static void FAST_FUNC
9873 changemail(const char *val UNUSED_PARAM)
9875 mail_var_path_changed = 1;
9878 #endif /* ASH_MAIL */
9881 /* ============ ??? */
9884 * Set the shell parameters.
9887 setparam(char **argv)
9893 for (nparam = 0; argv[nparam]; nparam++)
9895 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9897 *ap++ = ckstrdup(*argv++);
9900 freeparam(&shellparam);
9901 shellparam.malloced = 1;
9902 shellparam.nparam = nparam;
9903 shellparam.p = newparam;
9904 #if ENABLE_ASH_GETOPTS
9905 shellparam.optind = 1;
9906 shellparam.optoff = -1;
9911 * Process shell options. The global variable argptr contains a pointer
9912 * to the argument list; we advance it past the options.
9914 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9915 * For a non-interactive shell, an error condition encountered
9916 * by a special built-in ... shall cause the shell to write a diagnostic message
9917 * to standard error and exit as shown in the following table:
9918 * Error Special Built-In
9920 * Utility syntax error (option or operand error) Shall exit
9922 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9923 * we see that bash does not do that (set "finishes" with error code 1 instead,
9924 * and shell continues), and people rely on this behavior!
9926 * set -o barfoo 2>/dev/null
9929 * Oh well. Let's mimic that.
9932 plus_minus_o(char *name, int val)
9937 for (i = 0; i < NOPTS; i++) {
9938 if (strcmp(name, optnames(i)) == 0) {
9943 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9946 for (i = 0; i < NOPTS; i++) {
9948 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9950 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9956 setoption(int flag, int val)
9960 for (i = 0; i < NOPTS; i++) {
9961 if (optletters(i) == flag) {
9966 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9970 options(int cmdline)
9978 while ((p = *argptr) != NULL) {
9980 if (c != '-' && c != '+')
9983 val = 0; /* val = 0 if c == '+' */
9986 if (p[0] == '\0' || LONE_DASH(p)) {
9988 /* "-" means turn off -x and -v */
9991 /* "--" means reset params */
9992 else if (*argptr == NULL)
9995 break; /* "-" or "--" terminates options */
9998 /* first char was + or - */
9999 while ((c = *p++) != '\0') {
10000 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10001 if (c == 'c' && cmdline) {
10002 minusc = p; /* command is after shell args */
10003 } else if (c == 'o') {
10004 if (plus_minus_o(*argptr, val)) {
10005 /* it already printed err message */
10006 return 1; /* error */
10010 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10012 /* bash does not accept +-login, we also won't */
10013 } else if (cmdline && val && (c == '-')) { /* long options */
10014 if (strcmp(p, "login") == 0)
10026 * The shift builtin command.
10028 static int FAST_FUNC
10029 shiftcmd(int argc UNUSED_PARAM, char **argv)
10036 n = number(argv[1]);
10037 if (n > shellparam.nparam)
10038 n = 0; /* bash compat, was = shellparam.nparam; */
10040 shellparam.nparam -= n;
10041 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10042 if (shellparam.malloced)
10045 ap2 = shellparam.p;
10046 while ((*ap2++ = *ap1++) != NULL)
10048 #if ENABLE_ASH_GETOPTS
10049 shellparam.optind = 1;
10050 shellparam.optoff = -1;
10057 * POSIX requires that 'set' (but not export or readonly) output the
10058 * variables in lexicographic order - by the locale's collating order (sigh).
10059 * Maybe we could keep them in an ordered balanced binary tree
10060 * instead of hashed lists.
10061 * For now just roll 'em through qsort for printing...
10064 showvars(const char *sep_prefix, int on, int off)
10067 char **ep, **epend;
10069 ep = listvars(on, off, &epend);
10070 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10072 sep = *sep_prefix ? " " : sep_prefix;
10074 for (; ep < epend; ep++) {
10078 p = strchrnul(*ep, '=');
10081 q = single_quote(++p);
10082 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10088 * The set command builtin.
10090 static int FAST_FUNC
10091 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10096 return showvars(nullstr, 0, VUNSET);
10099 if (!options(0)) { /* if no parse error... */
10102 if (*argptr != NULL) {
10110 #if ENABLE_ASH_RANDOM_SUPPORT
10111 static void FAST_FUNC
10112 change_random(const char *value)
10116 if (value == NULL) {
10117 /* "get", generate */
10118 t = next_random(&random_gen);
10119 /* set without recursion */
10120 setvar(vrandom.text, utoa(t), VNOFUNC);
10121 vrandom.flags &= ~VNOFUNC;
10124 t = strtoul(value, NULL, 10);
10125 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10130 #if ENABLE_ASH_GETOPTS
10132 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10141 if (*param_optind < 1)
10143 optnext = optfirst + *param_optind - 1;
10145 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10148 p = optnext[-1] + *optoff;
10149 if (p == NULL || *p == '\0') {
10150 /* Current word is done, advance */
10152 if (p == NULL || *p != '-' || *++p == '\0') {
10159 if (LONE_DASH(p)) /* check for "--" */
10164 for (q = optstr; *q != c;) {
10166 if (optstr[0] == ':') {
10169 err |= setvarsafe("OPTARG", s, 0);
10171 fprintf(stderr, "Illegal option -%c\n", c);
10172 unsetvar("OPTARG");
10182 if (*p == '\0' && (p = *optnext) == NULL) {
10183 if (optstr[0] == ':') {
10186 err |= setvarsafe("OPTARG", s, 0);
10189 fprintf(stderr, "No arg for -%c option\n", c);
10190 unsetvar("OPTARG");
10198 err |= setvarsafe("OPTARG", p, 0);
10201 err |= setvarsafe("OPTARG", nullstr, 0);
10203 *optoff = p ? p - *(optnext - 1) : -1;
10204 *param_optind = optnext - optfirst + 1;
10205 fmtstr(s, sizeof(s), "%d", *param_optind);
10206 err |= setvarsafe("OPTIND", s, VNOFUNC);
10209 err |= setvarsafe(optvar, s, 0);
10213 flush_stdout_stderr();
10214 raise_exception(EXERROR);
10220 * The getopts builtin. Shellparam.optnext points to the next argument
10221 * to be processed. Shellparam.optptr points to the next character to
10222 * be processed in the current argument. If shellparam.optnext is NULL,
10223 * then it's the first time getopts has been called.
10225 static int FAST_FUNC
10226 getoptscmd(int argc, char **argv)
10231 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10233 optbase = shellparam.p;
10234 if (shellparam.optind > shellparam.nparam + 1) {
10235 shellparam.optind = 1;
10236 shellparam.optoff = -1;
10239 optbase = &argv[3];
10240 if (shellparam.optind > argc - 2) {
10241 shellparam.optind = 1;
10242 shellparam.optoff = -1;
10246 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10247 &shellparam.optoff);
10249 #endif /* ASH_GETOPTS */
10252 /* ============ Shell parser */
10255 struct heredoc *next; /* next here document in list */
10256 union node *here; /* redirection node */
10257 char *eofmark; /* string indicating end of input */
10258 smallint striptabs; /* if set, strip leading tabs */
10261 static smallint tokpushback; /* last token pushed back */
10262 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10263 static smallint quoteflag; /* set if (part of) last token was quoted */
10264 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10265 static struct heredoc *heredoclist; /* list of here documents to read */
10266 static char *wordtext; /* text of last word returned by readtoken */
10267 static struct nodelist *backquotelist;
10268 static union node *redirnode;
10269 static struct heredoc *heredoc;
10272 * Called when an unexpected token is read during the parse. The argument
10273 * is the token that is expected, or -1 if more than one type of token can
10274 * occur at this point.
10276 static void raise_error_unexpected_syntax(int) NORETURN;
10278 raise_error_unexpected_syntax(int token)
10283 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
10285 sprintf(msg + l, " (expecting %s)", tokname(token));
10286 raise_error_syntax(msg);
10290 #define EOFMARKLEN 79
10292 /* parsing is heavily cross-recursive, need these forward decls */
10293 static union node *andor(void);
10294 static union node *pipeline(void);
10295 static union node *parse_command(void);
10296 static void parseheredoc(void);
10297 static char peektoken(void);
10298 static int readtoken(void);
10300 static union node *
10303 union node *n1, *n2, *n3;
10306 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10307 if (nlflag == 2 && peektoken())
10313 if (tok == TBACKGND) {
10314 if (n2->type == NPIPE) {
10315 n2->npipe.pipe_backgnd = 1;
10317 if (n2->type != NREDIR) {
10318 n3 = stzalloc(sizeof(struct nredir));
10320 /*n3->nredir.redirect = NULL; - stzalloc did it */
10323 n2->type = NBACKGND;
10329 n3 = stzalloc(sizeof(struct nbinary));
10331 n3->nbinary.ch1 = n1;
10332 n3->nbinary.ch2 = n2;
10348 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10356 pungetc(); /* push back EOF on input */
10360 raise_error_unexpected_syntax(-1);
10367 static union node *
10370 union node *n1, *n2, *n3;
10378 } else if (t == TOR) {
10384 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10386 n3 = stzalloc(sizeof(struct nbinary));
10388 n3->nbinary.ch1 = n1;
10389 n3->nbinary.ch2 = n2;
10394 static union node *
10397 union node *n1, *n2, *pipenode;
10398 struct nodelist *lp, *prev;
10402 TRACE(("pipeline: entered\n"));
10403 if (readtoken() == TNOT) {
10405 checkkwd = CHKKWD | CHKALIAS;
10408 n1 = parse_command();
10409 if (readtoken() == TPIPE) {
10410 pipenode = stzalloc(sizeof(struct npipe));
10411 pipenode->type = NPIPE;
10412 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10413 lp = stzalloc(sizeof(struct nodelist));
10414 pipenode->npipe.cmdlist = lp;
10418 lp = stzalloc(sizeof(struct nodelist));
10419 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10420 lp->n = parse_command();
10422 } while (readtoken() == TPIPE);
10428 n2 = stzalloc(sizeof(struct nnot));
10436 static union node *
10441 n = stzalloc(sizeof(struct narg));
10443 /*n->narg.next = NULL; - stzalloc did it */
10444 n->narg.text = wordtext;
10445 n->narg.backquote = backquotelist;
10450 fixredir(union node *n, const char *text, int err)
10454 TRACE(("Fix redir %s %d\n", text, err));
10456 n->ndup.vname = NULL;
10458 fd = bb_strtou(text, NULL, 10);
10459 if (!errno && fd >= 0)
10460 n->ndup.dupfd = fd;
10461 else if (LONE_DASH(text))
10462 n->ndup.dupfd = -1;
10465 raise_error_syntax("bad fd number");
10466 n->ndup.vname = makename();
10471 * Returns true if the text contains nothing to expand (no dollar signs
10475 noexpand(const char *text)
10479 while ((c = *text++) != '\0') {
10480 if (c == CTLQUOTEMARK)
10484 else if (SIT(c, BASESYNTAX) == CCTL)
10493 union node *n = redirnode;
10495 if (readtoken() != TWORD)
10496 raise_error_unexpected_syntax(-1);
10497 if (n->type == NHERE) {
10498 struct heredoc *here = heredoc;
10502 if (quoteflag == 0)
10504 TRACE(("Here document %d\n", n->type));
10505 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10506 raise_error_syntax("illegal eof marker for << redirection");
10507 rmescapes(wordtext, 0);
10508 here->eofmark = wordtext;
10510 if (heredoclist == NULL)
10511 heredoclist = here;
10513 for (p = heredoclist; p->next; p = p->next)
10517 } else if (n->type == NTOFD || n->type == NFROMFD) {
10518 fixredir(n, wordtext, 0);
10520 n->nfile.fname = makename();
10524 static union node *
10527 union node *args, **app;
10528 union node *n = NULL;
10529 union node *vars, **vpp;
10530 union node **rpp, *redir;
10532 #if ENABLE_ASH_BASH_COMPAT
10533 smallint double_brackets_flag = 0;
10543 savecheckkwd = CHKALIAS;
10546 checkkwd = savecheckkwd;
10549 #if ENABLE_ASH_BASH_COMPAT
10550 case TAND: /* "&&" */
10551 case TOR: /* "||" */
10552 if (!double_brackets_flag) {
10556 wordtext = (char *) (t == TAND ? "-a" : "-o");
10559 n = stzalloc(sizeof(struct narg));
10561 /*n->narg.next = NULL; - stzalloc did it */
10562 n->narg.text = wordtext;
10563 #if ENABLE_ASH_BASH_COMPAT
10564 if (strcmp("[[", wordtext) == 0)
10565 double_brackets_flag = 1;
10566 else if (strcmp("]]", wordtext) == 0)
10567 double_brackets_flag = 0;
10569 n->narg.backquote = backquotelist;
10570 if (savecheckkwd && isassignment(wordtext)) {
10572 vpp = &n->narg.next;
10575 app = &n->narg.next;
10580 *rpp = n = redirnode;
10581 rpp = &n->nfile.next;
10582 parsefname(); /* read name of redirection file */
10585 if (args && app == &args->narg.next
10588 struct builtincmd *bcmd;
10591 /* We have a function */
10592 if (readtoken() != TRP)
10593 raise_error_unexpected_syntax(TRP);
10594 name = n->narg.text;
10595 if (!goodname(name)
10596 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10598 raise_error_syntax("bad function name");
10601 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10602 n->narg.next = parse_command();
10615 n = stzalloc(sizeof(struct ncmd));
10617 n->ncmd.args = args;
10618 n->ncmd.assign = vars;
10619 n->ncmd.redirect = redir;
10623 static union node *
10624 parse_command(void)
10626 union node *n1, *n2;
10627 union node *ap, **app;
10628 union node *cp, **cpp;
10629 union node *redir, **rpp;
10636 switch (readtoken()) {
10638 raise_error_unexpected_syntax(-1);
10641 n1 = stzalloc(sizeof(struct nif));
10643 n1->nif.test = list(0);
10644 if (readtoken() != TTHEN)
10645 raise_error_unexpected_syntax(TTHEN);
10646 n1->nif.ifpart = list(0);
10648 while (readtoken() == TELIF) {
10649 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10650 n2 = n2->nif.elsepart;
10652 n2->nif.test = list(0);
10653 if (readtoken() != TTHEN)
10654 raise_error_unexpected_syntax(TTHEN);
10655 n2->nif.ifpart = list(0);
10657 if (lasttoken == TELSE)
10658 n2->nif.elsepart = list(0);
10660 n2->nif.elsepart = NULL;
10668 n1 = stzalloc(sizeof(struct nbinary));
10669 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10670 n1->nbinary.ch1 = list(0);
10673 TRACE(("expecting DO got %s %s\n", tokname(got),
10674 got == TWORD ? wordtext : ""));
10675 raise_error_unexpected_syntax(TDO);
10677 n1->nbinary.ch2 = list(0);
10682 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10683 raise_error_syntax("bad for loop variable");
10684 n1 = stzalloc(sizeof(struct nfor));
10686 n1->nfor.var = wordtext;
10687 checkkwd = CHKKWD | CHKALIAS;
10688 if (readtoken() == TIN) {
10690 while (readtoken() == TWORD) {
10691 n2 = stzalloc(sizeof(struct narg));
10693 /*n2->narg.next = NULL; - stzalloc did it */
10694 n2->narg.text = wordtext;
10695 n2->narg.backquote = backquotelist;
10697 app = &n2->narg.next;
10700 n1->nfor.args = ap;
10701 if (lasttoken != TNL && lasttoken != TSEMI)
10702 raise_error_unexpected_syntax(-1);
10704 n2 = stzalloc(sizeof(struct narg));
10706 /*n2->narg.next = NULL; - stzalloc did it */
10707 n2->narg.text = (char *)dolatstr;
10708 /*n2->narg.backquote = NULL;*/
10709 n1->nfor.args = n2;
10711 * Newline or semicolon here is optional (but note
10712 * that the original Bourne shell only allowed NL).
10714 if (lasttoken != TNL && lasttoken != TSEMI)
10717 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10718 if (readtoken() != TDO)
10719 raise_error_unexpected_syntax(TDO);
10720 n1->nfor.body = list(0);
10724 n1 = stzalloc(sizeof(struct ncase));
10726 if (readtoken() != TWORD)
10727 raise_error_unexpected_syntax(TWORD);
10728 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10730 /*n2->narg.next = NULL; - stzalloc did it */
10731 n2->narg.text = wordtext;
10732 n2->narg.backquote = backquotelist;
10734 checkkwd = CHKKWD | CHKALIAS;
10735 } while (readtoken() == TNL);
10736 if (lasttoken != TIN)
10737 raise_error_unexpected_syntax(TIN);
10738 cpp = &n1->ncase.cases;
10740 checkkwd = CHKNL | CHKKWD;
10742 while (t != TESAC) {
10743 if (lasttoken == TLP)
10745 *cpp = cp = stzalloc(sizeof(struct nclist));
10747 app = &cp->nclist.pattern;
10749 *app = ap = stzalloc(sizeof(struct narg));
10751 /*ap->narg.next = NULL; - stzalloc did it */
10752 ap->narg.text = wordtext;
10753 ap->narg.backquote = backquotelist;
10754 if (readtoken() != TPIPE)
10756 app = &ap->narg.next;
10759 //ap->narg.next = NULL;
10760 if (lasttoken != TRP)
10761 raise_error_unexpected_syntax(TRP);
10762 cp->nclist.body = list(2);
10764 cpp = &cp->nclist.next;
10766 checkkwd = CHKNL | CHKKWD;
10770 raise_error_unexpected_syntax(TENDCASE);
10777 n1 = stzalloc(sizeof(struct nredir));
10778 n1->type = NSUBSHELL;
10779 n1->nredir.n = list(0);
10780 /*n1->nredir.redirect = NULL; - stzalloc did it */
10790 return simplecmd();
10793 if (readtoken() != t)
10794 raise_error_unexpected_syntax(t);
10797 /* Now check for redirection which may follow command */
10798 checkkwd = CHKKWD | CHKALIAS;
10800 while (readtoken() == TREDIR) {
10801 *rpp = n2 = redirnode;
10802 rpp = &n2->nfile.next;
10808 if (n1->type != NSUBSHELL) {
10809 n2 = stzalloc(sizeof(struct nredir));
10814 n1->nredir.redirect = redir;
10819 #if ENABLE_ASH_BASH_COMPAT
10820 static int decode_dollar_squote(void)
10822 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10828 p = strchr(C_escapes, c);
10833 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10837 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10839 } else if (c == 'x') { /* \xHH */
10843 } while (isxdigit(c) && --cnt);
10845 if (cnt == 3) { /* \x but next char is "bad" */
10849 } else { /* simple seq like \\ or \t */
10854 c = bb_process_escape_sequence((void*)&p);
10855 } else { /* unrecognized "\z": print both chars unless ' or " */
10856 if (c != '\'' && c != '"') {
10858 c |= 0x100; /* "please encode \, then me" */
10866 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10867 * is not NULL, read a here document. In the latter case, eofmark is the
10868 * word which marks the end of the document and striptabs is true if
10869 * leading tabs should be stripped from the document. The argument c
10870 * is the first character of the input token or document.
10872 * Because C does not have internal subroutines, I have simulated them
10873 * using goto's to implement the subroutine linkage. The following macros
10874 * will run code that appears at the end of readtoken1.
10876 #define CHECKEND() {goto checkend; checkend_return:;}
10877 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10878 #define PARSESUB() {goto parsesub; parsesub_return:;}
10879 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10880 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10881 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10883 readtoken1(int c, int syntax, char *eofmark, int striptabs)
10885 /* NB: syntax parameter fits into smallint */
10886 /* c parameter is an unsigned char or PEOF or PEOA */
10889 char line[EOFMARKLEN + 1];
10890 struct nodelist *bqlist;
10894 smallint prevsyntax; /* syntax before arithmetic */
10895 #if ENABLE_ASH_EXPAND_PRMT
10896 smallint pssyntax; /* we are expanding a prompt string */
10898 int varnest; /* levels of variables expansion */
10899 int arinest; /* levels of arithmetic expansion */
10900 int parenlevel; /* levels of parens in arithmetic */
10901 int dqvarnest; /* levels of variables expansion within double quotes */
10903 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10906 /* Avoid longjmp clobbering */
10912 (void) &parenlevel;
10915 (void) &prevsyntax;
10918 startlinno = g_parsefile->linno;
10923 #if ENABLE_ASH_EXPAND_PRMT
10924 pssyntax = (syntax == PSSYNTAX);
10928 dblquote = (syntax == DQSYNTAX);
10934 STARTSTACKSTR(out);
10936 /* For each line, until end of word */
10938 CHECKEND(); /* set c to PEOF if at end of here document */
10939 for (;;) { /* until end of line or end of word */
10940 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10941 switch (SIT(c, syntax)) {
10942 case CNL: /* '\n' */
10943 if (syntax == BASESYNTAX)
10944 goto endword; /* exit outer loop */
10946 g_parsefile->linno++;
10950 goto loop; /* continue outer loop */
10955 if (eofmark == NULL || dblquote)
10956 USTPUTC(CTLESC, out);
10957 #if ENABLE_ASH_BASH_COMPAT
10958 if (c == '\\' && bash_dollar_squote) {
10959 c = decode_dollar_squote();
10961 USTPUTC('\\', out);
10962 c = (unsigned char)c;
10968 case CBACK: /* backslash */
10969 c = pgetc_without_PEOA();
10971 USTPUTC(CTLESC, out);
10972 USTPUTC('\\', out);
10974 } else if (c == '\n') {
10978 #if ENABLE_ASH_EXPAND_PRMT
10979 if (c == '$' && pssyntax) {
10980 USTPUTC(CTLESC, out);
10981 USTPUTC('\\', out);
10984 if (dblquote && c != '\\'
10985 && c != '`' && c != '$'
10986 && (c != '"' || eofmark != NULL)
10988 USTPUTC(CTLESC, out);
10989 USTPUTC('\\', out);
10991 if (SIT(c, SQSYNTAX) == CCTL)
10992 USTPUTC(CTLESC, out);
11000 if (eofmark == NULL) {
11001 USTPUTC(CTLQUOTEMARK, out);
11009 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11010 if (eofmark != NULL && arinest == 0
11015 if (dqvarnest == 0) {
11016 syntax = BASESYNTAX;
11023 case CVAR: /* '$' */
11024 PARSESUB(); /* parse substitution */
11026 case CENDVAR: /* '}' */
11029 if (dqvarnest > 0) {
11032 USTPUTC(CTLENDVAR, out);
11037 #if ENABLE_SH_MATH_SUPPORT
11038 case CLP: /* '(' in arithmetic */
11042 case CRP: /* ')' in arithmetic */
11043 if (parenlevel > 0) {
11047 if (pgetc() == ')') {
11048 if (--arinest == 0) {
11049 USTPUTC(CTLENDARI, out);
11050 syntax = prevsyntax;
11051 dblquote = (syntax == DQSYNTAX);
11056 * unbalanced parens
11057 * (don't 2nd guess - no error)
11065 case CBQUOTE: /* '`' */
11069 goto endword; /* exit outer loop */
11073 if (varnest == 0) {
11074 #if ENABLE_ASH_BASH_COMPAT
11076 if (pgetc() == '>')
11077 c = 0x100 + '>'; /* flag &> */
11081 goto endword; /* exit outer loop */
11083 IF_ASH_ALIAS(if (c != PEOA))
11091 #if ENABLE_SH_MATH_SUPPORT
11092 if (syntax == ARISYNTAX)
11093 raise_error_syntax("missing '))'");
11095 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11096 raise_error_syntax("unterminated quoted string");
11097 if (varnest != 0) {
11098 startlinno = g_parsefile->linno;
11100 raise_error_syntax("missing '}'");
11102 USTPUTC('\0', out);
11103 len = out - (char *)stackblock();
11104 out = stackblock();
11105 if (eofmark == NULL) {
11106 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11109 if (isdigit_str9(out)) {
11110 PARSEREDIR(); /* passed as params: out, c */
11111 lasttoken = TREDIR;
11114 /* else: non-number X seen, interpret it
11115 * as "NNNX>file" = "NNNX >file" */
11119 quoteflag = quotef;
11120 backquotelist = bqlist;
11121 grabstackblock(len);
11125 /* end of readtoken routine */
11128 * Check to see whether we are at the end of the here document. When this
11129 * is called, c is set to the first character of the next input line. If
11130 * we are at the end of the here document, this routine sets the c to PEOF.
11134 #if ENABLE_ASH_ALIAS
11136 c = pgetc_without_PEOA();
11139 while (c == '\t') {
11140 c = pgetc_without_PEOA();
11143 if (c == *eofmark) {
11144 if (pfgets(line, sizeof(line)) != NULL) {
11148 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11150 if (*p == '\n' && *q == '\0') {
11152 g_parsefile->linno++;
11153 needprompt = doprompt;
11155 pushstring(line, NULL);
11160 goto checkend_return;
11164 * Parse a redirection operator. The variable "out" points to a string
11165 * specifying the fd to be redirected. The variable "c" contains the
11166 * first character of the redirection operator.
11169 /* out is already checked to be a valid number or "" */
11170 int fd = (*out == '\0' ? -1 : atoi(out));
11173 np = stzalloc(sizeof(struct nfile));
11178 np->type = NAPPEND;
11180 np->type = NCLOBBER;
11183 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11189 #if ENABLE_ASH_BASH_COMPAT
11190 else if (c == 0x100 + '>') { /* this flags &> redirection */
11192 pgetc(); /* this is '>', no need to check */
11196 else { /* c == '<' */
11197 /*np->nfile.fd = 0; - stzalloc did it */
11201 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11202 np = stzalloc(sizeof(struct nhere));
11203 /*np->nfile.fd = 0; - stzalloc did it */
11206 heredoc = stzalloc(sizeof(struct heredoc));
11207 heredoc->here = np;
11210 heredoc->striptabs = 1;
11212 /*heredoc->striptabs = 0; - stzalloc did it */
11218 np->type = NFROMFD;
11222 np->type = NFROMTO;
11234 goto parseredir_return;
11238 * Parse a substitution. At this point, we have read the dollar sign
11239 * and nothing else.
11242 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11243 * (assuming ascii char codes, as the original implementation did) */
11244 #define is_special(c) \
11245 (((unsigned)(c) - 33 < 32) \
11246 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11248 unsigned char subtype;
11252 static const char types[] ALIGN1 = "}-+?=";
11255 if (c > 255 /* PEOA or PEOF */
11256 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11258 #if ENABLE_ASH_BASH_COMPAT
11260 bash_dollar_squote = 1;
11265 } else if (c == '(') { /* $(command) or $((arith)) */
11266 if (pgetc() == '(') {
11267 #if ENABLE_SH_MATH_SUPPORT
11270 raise_error_syntax("you disabled math support for $((arith)) syntax");
11277 USTPUTC(CTLVAR, out);
11278 typeloc = out - (char *)stackblock();
11279 USTPUTC(VSNORMAL, out);
11280 subtype = VSNORMAL;
11288 subtype = VSLENGTH;
11292 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11296 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11297 } else if (isdigit(c)) {
11301 } while (isdigit(c));
11302 } else if (is_special(c)) {
11307 raise_error_syntax("bad substitution");
11309 if (c != '}' && subtype == VSLENGTH)
11314 if (subtype == 0) {
11318 #if ENABLE_ASH_BASH_COMPAT
11319 if (c == ':' || c == '$' || isdigit(c)) {
11321 subtype = VSSUBSTR;
11328 p = strchr(types, c);
11331 subtype = p - types + VSNORMAL;
11336 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11344 #if ENABLE_ASH_BASH_COMPAT
11346 subtype = VSREPLACE;
11349 subtype++; /* VSREPLACEALL */
11358 if (dblquote || arinest)
11360 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11361 if (subtype != VSNORMAL) {
11363 if (dblquote || arinest) {
11368 goto parsesub_return;
11372 * Called to parse command substitutions. Newstyle is set if the command
11373 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11374 * list of commands (passed by reference), and savelen is the number of
11375 * characters on the top of the stack which must be preserved.
11378 struct nodelist **nlpp;
11381 char *volatile str;
11382 struct jmploc jmploc;
11383 struct jmploc *volatile savehandler;
11385 smallint saveprompt = 0;
11388 (void) &saveprompt;
11390 savepbq = parsebackquote;
11391 if (setjmp(jmploc.loc)) {
11393 parsebackquote = 0;
11394 exception_handler = savehandler;
11395 longjmp(exception_handler->loc, 1);
11399 savelen = out - (char *)stackblock();
11401 str = ckmalloc(savelen);
11402 memcpy(str, stackblock(), savelen);
11404 savehandler = exception_handler;
11405 exception_handler = &jmploc;
11408 /* We must read until the closing backquote, giving special
11409 treatment to some slashes, and then push the string and
11410 reread it as input, interpreting it normally. */
11417 STARTSTACKSTR(pout);
11430 g_parsefile->linno++;
11434 * If eating a newline, avoid putting
11435 * the newline into the new character
11436 * stream (via the STPUTC after the
11441 if (pc != '\\' && pc != '`' && pc != '$'
11442 && (!dblquote || pc != '"')
11444 STPUTC('\\', pout);
11446 if (pc <= 255 /* not PEOA or PEOF */) {
11452 IF_ASH_ALIAS(case PEOA:)
11453 startlinno = g_parsefile->linno;
11454 raise_error_syntax("EOF in backquote substitution");
11457 g_parsefile->linno++;
11458 needprompt = doprompt;
11467 STPUTC('\0', pout);
11468 psavelen = pout - (char *)stackblock();
11469 if (psavelen > 0) {
11470 pstr = grabstackstr(pout);
11471 setinputstring(pstr);
11476 nlpp = &(*nlpp)->next;
11477 *nlpp = stzalloc(sizeof(**nlpp));
11478 /* (*nlpp)->next = NULL; - stzalloc did it */
11479 parsebackquote = oldstyle;
11482 saveprompt = doprompt;
11489 doprompt = saveprompt;
11490 else if (readtoken() != TRP)
11491 raise_error_unexpected_syntax(TRP);
11496 * Start reading from old file again, ignoring any pushed back
11497 * tokens left from the backquote parsing
11502 while (stackblocksize() <= savelen)
11504 STARTSTACKSTR(out);
11506 memcpy(out, str, savelen);
11507 STADJUST(savelen, out);
11513 parsebackquote = savepbq;
11514 exception_handler = savehandler;
11515 if (arinest || dblquote)
11516 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11518 USTPUTC(CTLBACKQ, out);
11520 goto parsebackq_oldreturn;
11521 goto parsebackq_newreturn;
11524 #if ENABLE_SH_MATH_SUPPORT
11526 * Parse an arithmetic expansion (indicate start of one and set state)
11529 if (++arinest == 1) {
11530 prevsyntax = syntax;
11531 syntax = ARISYNTAX;
11532 USTPUTC(CTLARI, out);
11539 * we collapse embedded arithmetic expansion to
11540 * parenthesis, which should be equivalent
11544 goto parsearith_return;
11548 } /* end of readtoken */
11551 * Read the next input token.
11552 * If the token is a word, we set backquotelist to the list of cmds in
11553 * backquotes. We set quoteflag to true if any part of the word was
11555 * If the token is TREDIR, then we set redirnode to a structure containing
11557 * In all cases, the variable startlinno is set to the number of the line
11558 * on which the token starts.
11560 * [Change comment: here documents and internal procedures]
11561 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11562 * word parsing code into a separate routine. In this case, readtoken
11563 * doesn't need to have any internal procedures, but parseword does.
11564 * We could also make parseoperator in essence the main routine, and
11565 * have parseword (readtoken1?) handle both words and redirection.]
11567 #define NEW_xxreadtoken
11568 #ifdef NEW_xxreadtoken
11569 /* singles must be first! */
11570 static const char xxreadtoken_chars[7] ALIGN1 = {
11571 '\n', '(', ')', /* singles */
11572 '&', '|', ';', /* doubles */
11576 #define xxreadtoken_singles 3
11577 #define xxreadtoken_doubles 3
11579 static const char xxreadtoken_tokens[] ALIGN1 = {
11580 TNL, TLP, TRP, /* only single occurrence allowed */
11581 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11582 TEOF, /* corresponds to trailing nul */
11583 TAND, TOR, TENDCASE /* if double occurrence */
11598 startlinno = g_parsefile->linno;
11599 for (;;) { /* until token or start of word found */
11601 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11605 while ((c = pgetc()) != '\n' && c != PEOF)
11608 } else if (c == '\\') {
11609 if (pgetc() != '\n') {
11611 break; /* return readtoken1(...) */
11613 startlinno = ++g_parsefile->linno;
11619 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11622 g_parsefile->linno++;
11623 needprompt = doprompt;
11626 p = strchr(xxreadtoken_chars, c);
11628 break; /* return readtoken1(...) */
11630 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11632 if (cc == c) { /* double occurrence? */
11633 p += xxreadtoken_doubles + 1;
11636 #if ENABLE_ASH_BASH_COMPAT
11637 if (c == '&' && cc == '>') /* &> */
11638 break; /* return readtoken1(...) */
11643 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11648 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11650 #else /* old xxreadtoken */
11651 #define RETURN(token) return lasttoken = token
11664 startlinno = g_parsefile->linno;
11665 for (;;) { /* until token or start of word found */
11668 case ' ': case '\t':
11669 IF_ASH_ALIAS(case PEOA:)
11672 while ((c = pgetc()) != '\n' && c != PEOF)
11677 if (pgetc() == '\n') {
11678 startlinno = ++g_parsefile->linno;
11686 g_parsefile->linno++;
11687 needprompt = doprompt;
11692 if (pgetc() == '&')
11697 if (pgetc() == '|')
11702 if (pgetc() == ';')
11715 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11718 #endif /* old xxreadtoken */
11725 smallint alreadyseen = tokpushback;
11728 #if ENABLE_ASH_ALIAS
11737 if (checkkwd & CHKNL) {
11744 if (t != TWORD || quoteflag) {
11749 * check for keywords
11751 if (checkkwd & CHKKWD) {
11752 const char *const *pp;
11754 pp = findkwd(wordtext);
11756 lasttoken = t = pp - tokname_array;
11757 TRACE(("keyword %s recognized\n", tokname(t)));
11762 if (checkkwd & CHKALIAS) {
11763 #if ENABLE_ASH_ALIAS
11765 ap = lookupalias(wordtext, 1);
11768 pushstring(ap->val, ap);
11778 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11780 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11792 return tokname_array[t][0];
11796 * Read and parse a command. Returns NODE_EOF on end of file.
11797 * (NULL is a valid parse tree indicating a blank line.)
11799 static union node *
11800 parsecmd(int interact)
11805 doprompt = interact;
11807 setprompt(doprompt);
11819 * Input any here documents.
11824 struct heredoc *here;
11827 here = heredoclist;
11828 heredoclist = NULL;
11834 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11835 here->eofmark, here->striptabs);
11836 n = stzalloc(sizeof(struct narg));
11837 n->narg.type = NARG;
11838 /*n->narg.next = NULL; - stzalloc did it */
11839 n->narg.text = wordtext;
11840 n->narg.backquote = backquotelist;
11841 here->here->nhere.doc = n;
11848 * called by editline -- any expansions to the prompt should be added here.
11850 #if ENABLE_ASH_EXPAND_PRMT
11851 static const char *
11852 expandstr(const char *ps)
11856 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11857 * and token processing _can_ alter it (delete NULs etc). */
11858 setinputstring((char *)ps);
11859 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11862 n.narg.type = NARG;
11863 n.narg.next = NULL;
11864 n.narg.text = wordtext;
11865 n.narg.backquote = backquotelist;
11867 expandarg(&n, NULL, 0);
11868 return stackblock();
11873 * Execute a command or commands contained in a string.
11876 evalstring(char *s, int mask)
11879 struct stackmark smark;
11883 setstackmark(&smark);
11886 while ((n = parsecmd(0)) != NODE_EOF) {
11888 popstackmark(&smark);
11901 * The eval command.
11903 static int FAST_FUNC
11904 evalcmd(int argc UNUSED_PARAM, char **argv)
11913 STARTSTACKSTR(concat);
11915 concat = stack_putstr(p, concat);
11919 STPUTC(' ', concat);
11921 STPUTC('\0', concat);
11922 p = grabstackstr(concat);
11924 evalstring(p, ~SKIPEVAL);
11931 * Read and execute commands.
11932 * "Top" is nonzero for the top level command loop;
11933 * it turns on prompting if the shell is interactive.
11939 struct stackmark smark;
11943 TRACE(("cmdloop(%d) called\n", top));
11947 setstackmark(&smark);
11950 showjobs(stderr, SHOW_CHANGED);
11953 if (iflag && top) {
11955 #if ENABLE_ASH_MAIL
11959 n = parsecmd(inter);
11961 if (DEBUG > 2 && debug && (n != NODE_EOF))
11964 if (n == NODE_EOF) {
11965 if (!top || numeof >= 50)
11967 if (!stoppedjobs()) {
11970 out2str("\nUse \"exit\" to leave shell.\n");
11973 } else if (nflag == 0) {
11974 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11979 popstackmark(&smark);
11984 return skip & SKIPEVAL;
11991 * Take commands from a file. To be compatible we should do a path
11992 * search for the file, which is necessary to find sub-commands.
11995 find_dot_file(char *name)
11998 const char *path = pathval();
12001 /* don't try this for absolute or relative paths */
12002 if (strchr(name, '/'))
12005 /* IIRC standards do not say whether . is to be searched.
12006 * And it is even smaller this way, making it unconditional for now:
12008 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12013 while ((fullname = path_advance(&path, name)) != NULL) {
12015 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12017 * Don't bother freeing here, since it will
12018 * be freed by the caller.
12022 if (fullname != name)
12023 stunalloc(fullname);
12026 /* not found in the PATH */
12027 ash_msg_and_raise_error("%s: not found", name);
12031 static int FAST_FUNC
12032 dotcmd(int argc, char **argv)
12034 struct strlist *sp;
12035 volatile struct shparam saveparam;
12037 for (sp = cmdenviron; sp; sp = sp->next)
12038 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12040 /* "false; . empty_file; echo $?" should print 0, not 1: */
12043 if (argv[1]) { /* That's what SVR2 does */
12044 char *fullname = find_dot_file(argv[1]);
12048 if (argc) { /* argc > 0, argv[0] != NULL */
12049 saveparam = shellparam;
12050 shellparam.malloced = 0;
12051 shellparam.nparam = argc;
12052 shellparam.p = argv;
12055 setinputfile(fullname, INPUT_PUSH_FILE);
12056 commandname = fullname;
12061 freeparam(&shellparam);
12062 shellparam = saveparam;
12068 static int FAST_FUNC
12069 exitcmd(int argc UNUSED_PARAM, char **argv)
12074 exitstatus = number(argv[1]);
12075 raise_exception(EXEXIT);
12080 * Read a file containing shell functions.
12083 readcmdfile(char *name)
12085 setinputfile(name, INPUT_PUSH_FILE);
12091 /* ============ find_command inplementation */
12094 * Resolve a command name. If you change this routine, you may have to
12095 * change the shellexec routine as well.
12098 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12100 struct tblentry *cmdp;
12107 struct builtincmd *bcmd;
12109 /* If name contains a slash, don't use PATH or hash table */
12110 if (strchr(name, '/') != NULL) {
12111 entry->u.index = -1;
12112 if (act & DO_ABS) {
12113 while (stat(name, &statb) < 0) {
12115 if (errno == EINTR)
12118 entry->cmdtype = CMDUNKNOWN;
12122 entry->cmdtype = CMDNORMAL;
12126 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12128 updatetbl = (path == pathval());
12131 if (strstr(path, "%builtin") != NULL)
12132 act |= DO_ALTBLTIN;
12135 /* If name is in the table, check answer will be ok */
12136 cmdp = cmdlookup(name, 0);
12137 if (cmdp != NULL) {
12140 switch (cmdp->cmdtype) {
12158 } else if (cmdp->rehash == 0)
12159 /* if not invalidated by cd, we're done */
12163 /* If %builtin not in path, check for builtin next */
12164 bcmd = find_builtin(name);
12166 if (IS_BUILTIN_REGULAR(bcmd))
12167 goto builtin_success;
12168 if (act & DO_ALTPATH) {
12169 if (!(act & DO_ALTBLTIN))
12170 goto builtin_success;
12171 } else if (builtinloc <= 0) {
12172 goto builtin_success;
12176 #if ENABLE_FEATURE_SH_STANDALONE
12178 int applet_no = find_applet_by_name(name);
12179 if (applet_no >= 0) {
12180 entry->cmdtype = CMDNORMAL;
12181 entry->u.index = -2 - applet_no;
12187 /* We have to search path. */
12188 prev = -1; /* where to start */
12189 if (cmdp && cmdp->rehash) { /* doing a rehash */
12190 if (cmdp->cmdtype == CMDBUILTIN)
12193 prev = cmdp->param.index;
12199 while ((fullname = path_advance(&path, name)) != NULL) {
12200 stunalloc(fullname);
12201 /* NB: code below will still use fullname
12202 * despite it being "unallocated" */
12205 if (prefix(pathopt, "builtin")) {
12207 goto builtin_success;
12210 if ((act & DO_NOFUNC)
12211 || !prefix(pathopt, "func")
12212 ) { /* ignore unimplemented options */
12216 /* if rehash, don't redo absolute path names */
12217 if (fullname[0] == '/' && idx <= prev) {
12220 TRACE(("searchexec \"%s\": no change\n", name));
12223 while (stat(fullname, &statb) < 0) {
12225 if (errno == EINTR)
12228 if (errno != ENOENT && errno != ENOTDIR)
12232 e = EACCES; /* if we fail, this will be the error */
12233 if (!S_ISREG(statb.st_mode))
12235 if (pathopt) { /* this is a %func directory */
12236 stalloc(strlen(fullname) + 1);
12237 /* NB: stalloc will return space pointed by fullname
12238 * (because we don't have any intervening allocations
12239 * between stunalloc above and this stalloc) */
12240 readcmdfile(fullname);
12241 cmdp = cmdlookup(name, 0);
12242 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12243 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12244 stunalloc(fullname);
12247 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12249 entry->cmdtype = CMDNORMAL;
12250 entry->u.index = idx;
12254 cmdp = cmdlookup(name, 1);
12255 cmdp->cmdtype = CMDNORMAL;
12256 cmdp->param.index = idx;
12261 /* We failed. If there was an entry for this command, delete it */
12262 if (cmdp && updatetbl)
12263 delete_cmd_entry();
12265 ash_msg("%s: %s", name, errmsg(e, "not found"));
12266 entry->cmdtype = CMDUNKNOWN;
12271 entry->cmdtype = CMDBUILTIN;
12272 entry->u.cmd = bcmd;
12276 cmdp = cmdlookup(name, 1);
12277 cmdp->cmdtype = CMDBUILTIN;
12278 cmdp->param.cmd = bcmd;
12282 entry->cmdtype = cmdp->cmdtype;
12283 entry->u = cmdp->param;
12287 /* ============ trap.c */
12290 * The trap builtin.
12292 static int FAST_FUNC
12293 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12297 int signo, exitcode;
12302 for (signo = 0; signo < NSIG; signo++) {
12303 char *tr = trap_ptr[signo];
12305 /* note: bash adds "SIG", but only if invoked
12306 * as "bash". If called as "sh", or if set -o posix,
12307 * then it prints short signal names.
12308 * We are printing short names: */
12309 out1fmt("trap -- %s %s\n",
12311 get_signame(signo));
12312 /* trap_ptr != trap only if we are in special-cased `trap` code.
12313 * In this case, we will exit very soon, no need to free(). */
12314 /* if (trap_ptr != trap && tp[0]) */
12319 if (trap_ptr != trap) {
12332 signo = get_signum(*ap);
12334 /* Mimic bash message exactly */
12335 ash_msg("%s: invalid signal specification", *ap);
12341 if (LONE_DASH(action))
12344 action = ckstrdup(action);
12347 trap[signo] = action;
12358 /* ============ Builtins */
12360 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12362 * Lists available builtins
12364 static int FAST_FUNC
12365 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12371 "Built-in commands:\n"
12372 "------------------\n");
12373 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12374 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12375 builtintab[i].name + 1);
12381 #if ENABLE_FEATURE_SH_STANDALONE
12383 const char *a = applet_names;
12385 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12390 a += strlen(a) + 1;
12395 return EXIT_SUCCESS;
12397 #endif /* FEATURE_SH_EXTRA_QUIET */
12400 * The export and readonly commands.
12402 static int FAST_FUNC
12403 exportcmd(int argc UNUSED_PARAM, char **argv)
12409 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12411 if (nextopt("p") != 'p') {
12416 p = strchr(name, '=');
12420 vp = *findvar(hashvar(name), name);
12426 setvar(name, p, flag);
12427 } while ((name = *++aptr) != NULL);
12431 showvars(argv[0], flag, 0);
12436 * Delete a function if it exists.
12439 unsetfunc(const char *name)
12441 struct tblentry *cmdp;
12443 cmdp = cmdlookup(name, 0);
12444 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12445 delete_cmd_entry();
12449 * The unset builtin command. We unset the function before we unset the
12450 * variable to allow a function to be unset when there is a readonly variable
12451 * with the same name.
12453 static int FAST_FUNC
12454 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12461 while ((i = nextopt("vf")) != '\0') {
12465 for (ap = argptr; *ap; ap++) {
12481 #include <sys/times.h>
12483 static const unsigned char timescmd_str[] ALIGN1 = {
12484 ' ', offsetof(struct tms, tms_utime),
12485 '\n', offsetof(struct tms, tms_stime),
12486 ' ', offsetof(struct tms, tms_cutime),
12487 '\n', offsetof(struct tms, tms_cstime),
12491 static int FAST_FUNC
12492 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12494 long clk_tck, s, t;
12495 const unsigned char *p;
12498 clk_tck = sysconf(_SC_CLK_TCK);
12503 t = *(clock_t *)(((char *) &buf) + p[1]);
12505 out1fmt("%ldm%ld.%.3lds%c",
12507 ((t - s * clk_tck) * 1000) / clk_tck,
12509 } while (*(p += 2));
12514 #if ENABLE_SH_MATH_SUPPORT
12516 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12517 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12519 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12521 static int FAST_FUNC
12522 letcmd(int argc UNUSED_PARAM, char **argv)
12528 ash_msg_and_raise_error("expression expected");
12530 i = ash_arith(*argv);
12535 #endif /* SH_MATH_SUPPORT */
12538 /* ============ miscbltin.c
12540 * Miscellaneous builtins.
12545 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
12546 typedef enum __rlimit_resource rlim_t;
12550 * The read builtin. Options:
12551 * -r Do not interpret '\' specially
12552 * -s Turn off echo (tty only)
12553 * -n NCHARS Read NCHARS max
12554 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12555 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12556 * -u FD Read from given FD instead of fd 0
12557 * This uses unbuffered input, which may be avoidable in some cases.
12558 * TODO: bash also has:
12559 * -a ARRAY Read into array[0],[1],etc
12560 * -d DELIM End on DELIM char, not newline
12561 * -e Use line editing (tty only)
12563 static int FAST_FUNC
12564 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12566 char *opt_n = NULL;
12567 char *opt_p = NULL;
12568 char *opt_t = NULL;
12569 char *opt_u = NULL;
12570 int read_flags = 0;
12574 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12583 read_flags |= BUILTIN_READ_SILENT;
12589 read_flags |= BUILTIN_READ_RAW;
12599 r = shell_builtin_read(setvar2,
12601 bltinlookup("IFS"), /* can be NULL */
12609 if ((uintptr_t)r > 1)
12610 ash_msg_and_raise_error(r);
12612 return (uintptr_t)r;
12615 static int FAST_FUNC
12616 umaskcmd(int argc UNUSED_PARAM, char **argv)
12618 static const char permuser[3] ALIGN1 = "ugo";
12619 static const char permmode[3] ALIGN1 = "rwx";
12620 static const short permmask[] ALIGN2 = {
12621 S_IRUSR, S_IWUSR, S_IXUSR,
12622 S_IRGRP, S_IWGRP, S_IXGRP,
12623 S_IROTH, S_IWOTH, S_IXOTH
12626 /* TODO: use bb_parse_mode() instead */
12631 int symbolic_mode = 0;
12633 while (nextopt("S") != '\0') {
12644 if (symbolic_mode) {
12648 for (i = 0; i < 3; i++) {
12651 *p++ = permuser[i];
12653 for (j = 0; j < 3; j++) {
12654 if ((mask & permmask[3 * i + j]) == 0) {
12655 *p++ = permmode[j];
12663 out1fmt("%.4o\n", mask);
12666 if (isdigit((unsigned char) *ap)) {
12669 if (*ap >= '8' || *ap < '0')
12670 ash_msg_and_raise_error(msg_illnum, argv[1]);
12671 mask = (mask << 3) + (*ap - '0');
12672 } while (*++ap != '\0');
12675 mask = ~mask & 0777;
12676 if (!bb_parse_mode(ap, &mask)) {
12677 ash_msg_and_raise_error("illegal mode: %s", ap);
12679 umask(~mask & 0777);
12685 static int FAST_FUNC
12686 ulimitcmd(int argc UNUSED_PARAM, char **argv)
12688 return shell_builtin_ulimit(argv);
12691 /* ============ main() and helpers */
12694 * Called to exit the shell.
12696 static void exitshell(void) NORETURN;
12704 status = exitstatus;
12705 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12706 if (setjmp(loc.loc)) {
12707 if (exception_type == EXEXIT)
12708 /* dash bug: it just does _exit(exitstatus) here
12709 * but we have to do setjobctl(0) first!
12710 * (bug is still not fixed in dash-0.5.3 - if you run dash
12711 * under Midnight Commander, on exit from dash MC is backgrounded) */
12712 status = exitstatus;
12715 exception_handler = &loc;
12722 flush_stdout_stderr();
12732 /* from input.c: */
12733 /* we will never free this */
12734 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
12737 signal(SIGCHLD, SIG_DFL);
12738 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12739 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12741 signal(SIGHUP, SIG_DFL);
12747 struct stat st1, st2;
12750 for (envp = environ; envp && *envp; envp++) {
12751 if (strchr(*envp, '=')) {
12752 setvareq(*envp, VEXPORT|VTEXTFIXED);
12756 setvar("PPID", utoa(getppid()), 0);
12758 p = lookupvar("PWD");
12760 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12761 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12768 * Process the shell command line arguments.
12771 procargs(char **argv)
12774 const char *xminusc;
12779 /* if (xargv[0]) - mmm, this is always true! */
12781 for (i = 0; i < NOPTS; i++)
12785 /* it already printed err message */
12786 raise_exception(EXERROR);
12790 if (*xargv == NULL) {
12792 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12795 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12799 for (i = 0; i < NOPTS; i++)
12800 if (optlist[i] == 2)
12805 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12810 } else if (!sflag) {
12811 setinputfile(*xargv, 0);
12814 commandname = arg0;
12817 shellparam.p = xargv;
12818 #if ENABLE_ASH_GETOPTS
12819 shellparam.optind = 1;
12820 shellparam.optoff = -1;
12822 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
12824 shellparam.nparam++;
12831 * Read /etc/profile or .profile.
12834 read_profile(const char *name)
12838 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12847 * This routine is called when an error or an interrupt occurs in an
12848 * interactive shell and control is returned to the main command loop.
12856 /* from input.c: */
12857 g_parsefile->left_in_buffer = 0;
12858 g_parsefile->left_in_line = 0; /* clear input buffer */
12860 /* from parser.c: */
12863 /* from redir.c: */
12864 clearredir(/*drop:*/ 0);
12868 static short profile_buf[16384];
12869 extern int etext();
12873 * Main routine. We initialize things, parse the arguments, execute
12874 * profiles if we're a login shell, and then call cmdloop to execute
12875 * commands. The setjmp call sets up the location to jump to when an
12876 * exception occurs. When an exception occurs the variable "state"
12877 * is used to figure out how far we had gotten.
12879 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
12880 int ash_main(int argc UNUSED_PARAM, char **argv)
12882 const char *shinit;
12883 volatile smallint state;
12884 struct jmploc jmploc;
12885 struct stackmark smark;
12887 /* Initialize global data */
12891 #if ENABLE_ASH_ALIAS
12897 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12900 #if ENABLE_FEATURE_EDITING
12901 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12904 if (setjmp(jmploc.loc)) {
12910 e = exception_type;
12914 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12917 outcslow('\n', stderr);
12919 popstackmark(&smark);
12920 FORCE_INT_ON; /* enable interrupts */
12929 exception_handler = &jmploc;
12932 TRACE(("Shell args: "));
12933 trace_puts_args(argv);
12935 rootpid = getpid();
12938 setstackmark(&smark);
12941 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
12943 const char *hp = lookupvar("HISTFILE");
12946 hp = lookupvar("HOME");
12948 char *defhp = concat_path_file(hp, ".ash_history");
12949 setvar("HISTFILE", defhp, 0);
12955 if (/* argv[0] && */ argv[0][0] == '-')
12959 read_profile("/etc/profile");
12962 read_profile(".profile");
12968 getuid() == geteuid() && getgid() == getegid() &&
12972 shinit = lookupvar("ENV");
12973 if (shinit != NULL && *shinit != '\0') {
12974 read_profile(shinit);
12980 /* evalstring pushes parsefile stack.
12981 * Ensure we don't falsely claim that 0 (stdin)
12982 * is one of stacked source fds.
12983 * Testcase: ash -c 'exec 1>&0' must not complain. */
12985 g_parsefile->fd = -1;
12986 evalstring(minusc, 0);
12989 if (sflag || minusc == NULL) {
12990 #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
12992 const char *hp = lookupvar("HISTFILE");
12994 line_input_state->hist_file = hp;
12997 state4: /* XXX ??? - why isn't this before the "if" statement */
13005 extern void _mcleanup(void);
13015 * Copyright (c) 1989, 1991, 1993, 1994
13016 * The Regents of the University of California. All rights reserved.
13018 * This code is derived from software contributed to Berkeley by
13019 * Kenneth Almquist.
13021 * Redistribution and use in source and binary forms, with or without
13022 * modification, are permitted provided that the following conditions
13024 * 1. Redistributions of source code must retain the above copyright
13025 * notice, this list of conditions and the following disclaimer.
13026 * 2. Redistributions in binary form must reproduce the above copyright
13027 * notice, this list of conditions and the following disclaimer in the
13028 * documentation and/or other materials provided with the distribution.
13029 * 3. Neither the name of the University nor the names of its contributors
13030 * may be used to endorse or promote products derived from this software
13031 * without specific prior written permission.
13033 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13034 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13035 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13036 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13037 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13038 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13039 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13040 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13041 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13042 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF