1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
20 * The following should be set to reflect the type of system you have:
21 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22 * define SYSV if you are running under System V.
23 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24 * define DEBUG=2 to compile in and turn on debugging.
26 * When debugging is on, debugging info will be written to ./trace and
27 * a quit signal will generate a core dump.
30 /* Tweak debug output verbosity here */
37 #define JOBS ENABLE_ASH_JOB_CONTROL
45 #include "busybox.h" /* for applet_names */
50 #include "shell_common.h"
51 #include "builtin_read.h"
52 #include "builtin_ulimit.h"
54 #if ENABLE_ASH_RANDOM_SUPPORT
57 # define CLEAR_RANDOM_T(rnd) ((void)0)
60 #define SKIP_definitions 1
61 #include "applet_tables.h"
62 #undef SKIP_definitions
64 /* STANDALONE does not make sense, and won't compile */
65 # undef CONFIG_FEATURE_SH_STANDALONE
66 # undef ENABLE_FEATURE_SH_STANDALONE
67 # undef IF_FEATURE_SH_STANDALONE
68 # undef IF_NOT_FEATURE_SH_STANDALONE
69 # define ENABLE_FEATURE_SH_STANDALONE 0
70 # define IF_FEATURE_SH_STANDALONE(...)
71 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
75 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
79 # error "Do not even bother, ash will not run on NOMMU machine"
83 /* ============ Hash table sizes. Configurable. */
87 #define CMDTABLESIZE 31 /* should be prime */
90 /* ============ Shell options */
92 static const char *const optletters_optnames[] = {
107 #if ENABLE_ASH_BASH_COMPAT
116 #define optletters(n) optletters_optnames[n][0]
117 #define optnames(n) (optletters_optnames[n] + 1)
119 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
122 /* ============ Misc data */
124 static const char homestr[] ALIGN1 = "HOME";
125 static const char snlfmt[] ALIGN1 = "%s\n";
126 static const char msg_illnum[] ALIGN1 = "Illegal number: %s";
129 * We enclose jmp_buf in a structure so that we can declare pointers to
130 * jump locations. The global variable handler contains the location to
131 * jump to when an exception occurs, and the global variable exception_type
132 * contains a code identifying the exception. To implement nested
133 * exception handlers, the user should save the value of handler on entry
134 * to an inner scope, set handler to point to a jmploc structure for the
135 * inner scope, and restore handler on exit from the scope.
141 struct globals_misc {
142 /* pid of main shell */
144 /* shell level: 0 for the main shell, 1 for its children, and so on */
146 #define rootshell (!shlvl)
147 char *minusc; /* argument to -c option */
149 char *curdir; // = nullstr; /* current working directory */
150 char *physdir; // = nullstr; /* physical working directory */
152 char *arg0; /* value of $0 */
154 struct jmploc *exception_handler;
156 volatile int suppress_int; /* counter */
157 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
158 /* last pending signal */
159 volatile /*sig_atomic_t*/ smallint pending_sig;
160 smallint exception_type; /* kind of exception (0..5) */
162 #define EXINT 0 /* SIGINT received */
163 #define EXERROR 1 /* a generic error */
164 #define EXSHELLPROC 2 /* execute a shell procedure */
165 #define EXEXEC 3 /* command execution failed */
166 #define EXEXIT 4 /* exit the shell */
167 #define EXSIG 5 /* trapped signal in wait(1) */
170 char nullstr[1]; /* zero length string */
173 #define eflag optlist[0]
174 #define fflag optlist[1]
175 #define Iflag optlist[2]
176 #define iflag optlist[3]
177 #define mflag optlist[4]
178 #define nflag optlist[5]
179 #define sflag optlist[6]
180 #define xflag optlist[7]
181 #define vflag optlist[8]
182 #define Cflag optlist[9]
183 #define aflag optlist[10]
184 #define bflag optlist[11]
185 #define uflag optlist[12]
186 #define viflag optlist[13]
187 #if ENABLE_ASH_BASH_COMPAT
188 # define pipefail optlist[14]
193 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
194 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
197 /* trap handler commands */
199 * Sigmode records the current value of the signal handlers for the various
200 * modes. A value of zero means that the current handler is not known.
201 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
203 char sigmode[NSIG - 1];
204 #define S_DFL 1 /* default signal handling (SIG_DFL) */
205 #define S_CATCH 2 /* signal is caught */
206 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
207 #define S_HARD_IGN 4 /* signal is ignored permenantly */
209 /* indicates specified signal received */
210 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
212 char **trap_ptr; /* used only by "trap hack" */
214 /* Rarely referenced stuff */
215 #if ENABLE_ASH_RANDOM_SUPPORT
218 pid_t backgndpid; /* pid of last background process */
219 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
221 extern struct globals_misc *const ash_ptr_to_globals_misc;
222 #define G_misc (*ash_ptr_to_globals_misc)
223 #define rootpid (G_misc.rootpid )
224 #define shlvl (G_misc.shlvl )
225 #define minusc (G_misc.minusc )
226 #define curdir (G_misc.curdir )
227 #define physdir (G_misc.physdir )
228 #define arg0 (G_misc.arg0 )
229 #define exception_handler (G_misc.exception_handler)
230 #define exception_type (G_misc.exception_type )
231 #define suppress_int (G_misc.suppress_int )
232 #define pending_int (G_misc.pending_int )
233 #define pending_sig (G_misc.pending_sig )
234 #define isloginsh (G_misc.isloginsh )
235 #define nullstr (G_misc.nullstr )
236 #define optlist (G_misc.optlist )
237 #define sigmode (G_misc.sigmode )
238 #define gotsig (G_misc.gotsig )
239 #define trap (G_misc.trap )
240 #define trap_ptr (G_misc.trap_ptr )
241 #define random_gen (G_misc.random_gen )
242 #define backgndpid (G_misc.backgndpid )
243 #define job_warning (G_misc.job_warning)
244 #define INIT_G_misc() do { \
245 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
253 /* ============ DEBUG */
255 static void trace_printf(const char *fmt, ...);
256 static void trace_vprintf(const char *fmt, va_list va);
257 # define TRACE(param) trace_printf param
258 # define TRACEV(param) trace_vprintf param
259 # define close(fd) do { \
261 if (close(dfd) < 0) \
262 bb_error_msg("bug on %d: closing %d(0x%x)", \
263 __LINE__, dfd, dfd); \
266 # define TRACE(param)
267 # define TRACEV(param)
271 /* ============ Utility functions */
272 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
274 static int isdigit_str9(const char *str)
276 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
277 while (--maxlen && isdigit(*str))
279 return (*str == '\0');
283 /* ============ Interrupts / exceptions */
285 * These macros allow the user to suspend the handling of interrupt signals
286 * over a period of time. This is similar to SIGHOLD or to sigblock, but
287 * much more efficient and portable. (But hacking the kernel is so much
288 * more fun than worrying about efficiency and portability. :-))
290 #define INT_OFF do { \
296 * Called to raise an exception. Since C doesn't include exceptions, we
297 * just do a longjmp to the exception handler. The type of exception is
298 * stored in the global variable "exception_type".
300 static void raise_exception(int) NORETURN;
302 raise_exception(int e)
305 if (exception_handler == NULL)
310 longjmp(exception_handler->loc, 1);
313 #define raise_exception(e) do { \
314 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
315 raise_exception(e); \
320 * Called from trap.c when a SIGINT is received. (If the user specifies
321 * that SIGINT is to be trapped or ignored using the trap builtin, then
322 * this routine is not called.) Suppressint is nonzero when interrupts
323 * are held using the INT_OFF macro. (The test for iflag is just
324 * defensive programming.)
326 static void raise_interrupt(void) NORETURN;
328 raise_interrupt(void)
333 /* Signal is not automatically unmasked after it is raised,
334 * do it ourself - unmask all signals */
335 sigprocmask_allsigs(SIG_UNBLOCK);
336 /* pending_sig = 0; - now done in onsig() */
339 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
340 if (!(rootshell && iflag)) {
341 /* Kill ourself with SIGINT */
342 signal(SIGINT, SIG_DFL);
347 raise_exception(ex_type);
351 #define raise_interrupt() do { \
352 TRACE(("raising interrupt on line %d\n", __LINE__)); \
357 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
361 if (--suppress_int == 0 && pending_int) {
365 #define INT_ON int_on()
366 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
374 #define FORCE_INT_ON force_int_on()
376 #define SAVE_INT(v) ((v) = suppress_int)
378 #define RESTORE_INT(v) do { \
380 suppress_int = (v); \
381 if (suppress_int == 0 && pending_int) \
386 /* ============ Stdout/stderr output */
389 outstr(const char *p, FILE *file)
397 flush_stdout_stderr(void)
405 outcslow(int c, FILE *dest)
413 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
415 out1fmt(const char *fmt, ...)
422 r = vprintf(fmt, ap);
428 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
430 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
437 ret = vsnprintf(outbuf, length, fmt, ap);
444 out1str(const char *p)
450 out2str(const char *p)
453 flush_stdout_stderr();
457 /* ============ Parser structures */
459 /* control characters in argument strings */
460 #define CTL_FIRST CTLESC
461 #define CTLESC ((unsigned char)'\201') /* escape next character */
462 #define CTLVAR ((unsigned char)'\202') /* variable defn */
463 #define CTLENDVAR ((unsigned char)'\203')
464 #define CTLBACKQ ((unsigned char)'\204')
465 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
466 /* CTLBACKQ | CTLQUOTE == '\205' */
467 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
468 #define CTLENDARI ((unsigned char)'\207')
469 #define CTLQUOTEMARK ((unsigned char)'\210')
470 #define CTL_LAST CTLQUOTEMARK
472 /* variable substitution byte (follows CTLVAR) */
473 #define VSTYPE 0x0f /* type of variable substitution */
474 #define VSNUL 0x10 /* colon--treat the empty string as unset */
475 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
477 /* values of VSTYPE field */
478 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
479 #define VSMINUS 0x2 /* ${var-text} */
480 #define VSPLUS 0x3 /* ${var+text} */
481 #define VSQUESTION 0x4 /* ${var?message} */
482 #define VSASSIGN 0x5 /* ${var=text} */
483 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
484 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
485 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
486 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
487 #define VSLENGTH 0xa /* ${#var} */
488 #if ENABLE_ASH_BASH_COMPAT
489 #define VSSUBSTR 0xc /* ${var:position:length} */
490 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
491 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
494 static const char dolatstr[] ALIGN1 = {
495 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
515 #if ENABLE_ASH_BASH_COMPAT
532 smallint type; /* Nxxxx */
535 union node *redirect;
540 smallint pipe_backgnd;
541 struct nodelist *cmdlist;
547 union node *redirect;
560 union node *elsepart;
587 struct nodelist *backquote;
590 /* nfile and ndup layout must match!
591 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
592 * that it is actually NTO2 (>&file), and change its type.
609 char *_unused_expfname;
628 struct nredir nredir;
629 struct nbinary nbinary;
633 struct nclist nclist;
642 * NODE_EOF is returned by parsecmd when it encounters an end of file.
643 * It must be distinct from NULL.
645 #define NODE_EOF ((union node *) -1L)
648 struct nodelist *next;
661 freefunc(struct funcnode *f)
663 if (f && --f->count < 0)
668 /* ============ Debugging output */
672 static FILE *tracefile;
675 trace_printf(const char *fmt, ...)
682 fprintf(tracefile, "%u ", (int) time(NULL));
684 fprintf(tracefile, "[%u] ", (int) getpid());
686 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
688 vfprintf(tracefile, fmt, va);
693 trace_vprintf(const char *fmt, va_list va)
698 fprintf(tracefile, "%u ", (int) time(NULL));
700 fprintf(tracefile, "[%u] ", (int) getpid());
702 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
703 vfprintf(tracefile, fmt, va);
707 trace_puts(const char *s)
715 trace_puts_quoted(char *s)
722 putc('"', tracefile);
723 for (p = s; *p; p++) {
724 switch ((unsigned char)*p) {
725 case '\n': c = 'n'; goto backslash;
726 case '\t': c = 't'; goto backslash;
727 case '\r': c = 'r'; goto backslash;
728 case '\"': c = '\"'; goto backslash;
729 case '\\': c = '\\'; goto backslash;
730 case CTLESC: c = 'e'; goto backslash;
731 case CTLVAR: c = 'v'; goto backslash;
732 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
733 case CTLBACKQ: c = 'q'; goto backslash;
734 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
736 putc('\\', tracefile);
740 if (*p >= ' ' && *p <= '~')
743 putc('\\', tracefile);
744 putc((*p >> 6) & 03, tracefile);
745 putc((*p >> 3) & 07, tracefile);
746 putc(*p & 07, tracefile);
751 putc('"', tracefile);
755 trace_puts_args(char **ap)
762 trace_puts_quoted(*ap);
764 putc('\n', tracefile);
767 putc(' ', tracefile);
782 /* leave open because libedit might be using it */
785 strcpy(s, "./trace");
787 if (!freopen(s, "a", tracefile)) {
788 fprintf(stderr, "Can't re-open %s\n", s);
793 tracefile = fopen(s, "a");
794 if (tracefile == NULL) {
795 fprintf(stderr, "Can't open %s\n", s);
801 flags = fcntl(fileno(tracefile), F_GETFL);
803 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
805 setlinebuf(tracefile);
806 fputs("\nTracing started.\n", tracefile);
810 indent(int amount, char *pfx, FILE *fp)
814 for (i = 0; i < amount; i++) {
815 if (pfx && i == amount - 1)
821 /* little circular references here... */
822 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
825 sharg(union node *arg, FILE *fp)
828 struct nodelist *bqlist;
829 unsigned char subtype;
831 if (arg->type != NARG) {
832 out1fmt("<node type %d>\n", arg->type);
835 bqlist = arg->narg.backquote;
836 for (p = arg->narg.text; *p; p++) {
837 switch ((unsigned char)*p) {
845 if (subtype == VSLENGTH)
854 switch (subtype & VSTYPE) {
887 out1fmt("<subtype %d>", subtype);
894 case CTLBACKQ|CTLQUOTE:
897 shtree(bqlist->n, -1, NULL, fp);
908 shcmd(union node *cmd, FILE *fp)
916 for (np = cmd->ncmd.args; np; np = np->narg.next) {
922 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
926 switch (np->nfile.type) {
927 case NTO: s = ">>"+1; dftfd = 1; break;
928 case NCLOBBER: s = ">|"; dftfd = 1; break;
929 case NAPPEND: s = ">>"; dftfd = 1; break;
930 #if ENABLE_ASH_BASH_COMPAT
933 case NTOFD: s = ">&"; dftfd = 1; break;
934 case NFROM: s = "<"; break;
935 case NFROMFD: s = "<&"; break;
936 case NFROMTO: s = "<>"; break;
937 default: s = "*error*"; break;
939 if (np->nfile.fd != dftfd)
940 fprintf(fp, "%d", np->nfile.fd);
942 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
943 fprintf(fp, "%d", np->ndup.dupfd);
945 sharg(np->nfile.fname, fp);
952 shtree(union node *n, int ind, char *pfx, FILE *fp)
960 indent(ind, pfx, fp);
977 shtree(n->nbinary.ch1, ind, NULL, fp);
980 shtree(n->nbinary.ch2, ind, NULL, fp);
988 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
989 shtree(lp->n, 0, NULL, fp);
993 if (n->npipe.pipe_backgnd)
999 fprintf(fp, "<node type %d>", n->type);
1007 showtree(union node *n)
1009 trace_puts("showtree called\n");
1010 shtree(n, 1, NULL, stderr);
1016 /* ============ Parser data */
1019 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1022 struct strlist *next;
1029 struct strpush *prev; /* preceding string on stack */
1031 int prev_left_in_line;
1032 #if ENABLE_ASH_ALIAS
1033 struct alias *ap; /* if push was associated with an alias */
1035 char *string; /* remember the string since it may change */
1039 struct parsefile *prev; /* preceding file on stack */
1040 int linno; /* current line */
1041 int fd; /* file descriptor (or -1 if string) */
1042 int left_in_line; /* number of chars left in this line */
1043 int left_in_buffer; /* number of chars left in this buffer past the line */
1044 char *next_to_pgetc; /* next char in buffer */
1045 char *buf; /* input buffer */
1046 struct strpush *strpush; /* for pushing strings at this level */
1047 struct strpush basestrpush; /* so pushing one is fast */
1050 static struct parsefile basepf; /* top level input file */
1051 static struct parsefile *g_parsefile = &basepf; /* current input file */
1052 static int startlinno; /* line # where last token started */
1053 static char *commandname; /* currently executing command */
1054 static struct strlist *cmdenviron; /* environment for builtin command */
1055 static uint8_t exitstatus; /* exit status of last command */
1058 /* ============ Message printing */
1061 ash_vmsg(const char *msg, va_list ap)
1063 fprintf(stderr, "%s: ", arg0);
1065 if (strcmp(arg0, commandname))
1066 fprintf(stderr, "%s: ", commandname);
1067 if (!iflag || g_parsefile->fd)
1068 fprintf(stderr, "line %d: ", startlinno);
1070 vfprintf(stderr, msg, ap);
1071 outcslow('\n', stderr);
1075 * Exverror is called to raise the error exception. If the second argument
1076 * is not NULL then error prints an error message using printf style
1077 * formatting. It then raises the error exception.
1079 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1081 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1085 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1087 TRACE(("\") pid=%d\n", getpid()));
1089 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1094 flush_stdout_stderr();
1095 raise_exception(cond);
1099 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1101 ash_msg_and_raise_error(const char *msg, ...)
1106 ash_vmsg_and_raise(EXERROR, msg, ap);
1111 static void raise_error_syntax(const char *) NORETURN;
1113 raise_error_syntax(const char *msg)
1115 ash_msg_and_raise_error("syntax error: %s", msg);
1119 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1121 ash_msg_and_raise(int cond, const char *msg, ...)
1126 ash_vmsg_and_raise(cond, msg, ap);
1132 * error/warning routines for external builtins
1135 ash_msg(const char *fmt, ...)
1145 * Return a string describing an error. The returned string may be a
1146 * pointer to a static buffer that will be overwritten on the next call.
1147 * Action describes the operation that got the error.
1150 errmsg(int e, const char *em)
1152 if (e == ENOENT || e == ENOTDIR) {
1159 /* ============ Memory allocation */
1162 /* I consider these wrappers nearly useless:
1163 * ok, they return you to nearest exception handler, but
1164 * how much memory do you leak in the process, making
1165 * memory starvation worse?
1168 ckrealloc(void * p, size_t nbytes)
1170 p = realloc(p, nbytes);
1172 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1177 ckmalloc(size_t nbytes)
1179 return ckrealloc(NULL, nbytes);
1183 ckzalloc(size_t nbytes)
1185 return memset(ckmalloc(nbytes), 0, nbytes);
1189 ckstrdup(const char *s)
1191 char *p = strdup(s);
1193 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1197 /* Using bbox equivalents. They exit if out of memory */
1198 # define ckrealloc xrealloc
1199 # define ckmalloc xmalloc
1200 # define ckzalloc xzalloc
1201 # define ckstrdup xstrdup
1205 * It appears that grabstackstr() will barf with such alignments
1206 * because stalloc() will return a string allocated in a new stackblock.
1208 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1210 /* Most machines require the value returned from malloc to be aligned
1211 * in some way. The following macro will get this right
1212 * on many machines. */
1213 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1214 /* Minimum size of a block */
1215 MINSIZE = SHELL_ALIGN(504),
1218 struct stack_block {
1219 struct stack_block *prev;
1220 char space[MINSIZE];
1224 struct stack_block *stackp;
1227 struct stackmark *marknext;
1231 struct globals_memstack {
1232 struct stack_block *g_stackp; // = &stackbase;
1233 struct stackmark *markp;
1234 char *g_stacknxt; // = stackbase.space;
1235 char *sstrend; // = stackbase.space + MINSIZE;
1236 size_t g_stacknleft; // = MINSIZE;
1237 int herefd; // = -1;
1238 struct stack_block stackbase;
1240 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1241 #define G_memstack (*ash_ptr_to_globals_memstack)
1242 #define g_stackp (G_memstack.g_stackp )
1243 #define markp (G_memstack.markp )
1244 #define g_stacknxt (G_memstack.g_stacknxt )
1245 #define sstrend (G_memstack.sstrend )
1246 #define g_stacknleft (G_memstack.g_stacknleft)
1247 #define herefd (G_memstack.herefd )
1248 #define stackbase (G_memstack.stackbase )
1249 #define INIT_G_memstack() do { \
1250 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1252 g_stackp = &stackbase; \
1253 g_stacknxt = stackbase.space; \
1254 g_stacknleft = MINSIZE; \
1255 sstrend = stackbase.space + MINSIZE; \
1260 #define stackblock() ((void *)g_stacknxt)
1261 #define stackblocksize() g_stacknleft
1264 * Parse trees for commands are allocated in lifo order, so we use a stack
1265 * to make this more efficient, and also to avoid all sorts of exception
1266 * handling code to handle interrupts in the middle of a parse.
1268 * The size 504 was chosen because the Ultrix malloc handles that size
1272 stalloc(size_t nbytes)
1277 aligned = SHELL_ALIGN(nbytes);
1278 if (aligned > g_stacknleft) {
1281 struct stack_block *sp;
1283 blocksize = aligned;
1284 if (blocksize < MINSIZE)
1285 blocksize = MINSIZE;
1286 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1287 if (len < blocksize)
1288 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1291 sp->prev = g_stackp;
1292 g_stacknxt = sp->space;
1293 g_stacknleft = blocksize;
1294 sstrend = g_stacknxt + blocksize;
1299 g_stacknxt += aligned;
1300 g_stacknleft -= aligned;
1305 stzalloc(size_t nbytes)
1307 return memset(stalloc(nbytes), 0, nbytes);
1314 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1315 write(STDERR_FILENO, "stunalloc\n", 10);
1319 g_stacknleft += g_stacknxt - (char *)p;
1324 * Like strdup but works with the ash stack.
1327 ststrdup(const char *p)
1329 size_t len = strlen(p) + 1;
1330 return memcpy(stalloc(len), p, len);
1334 setstackmark(struct stackmark *mark)
1336 mark->stackp = g_stackp;
1337 mark->stacknxt = g_stacknxt;
1338 mark->stacknleft = g_stacknleft;
1339 mark->marknext = markp;
1344 popstackmark(struct stackmark *mark)
1346 struct stack_block *sp;
1352 markp = mark->marknext;
1353 while (g_stackp != mark->stackp) {
1355 g_stackp = sp->prev;
1358 g_stacknxt = mark->stacknxt;
1359 g_stacknleft = mark->stacknleft;
1360 sstrend = mark->stacknxt + mark->stacknleft;
1365 * When the parser reads in a string, it wants to stick the string on the
1366 * stack and only adjust the stack pointer when it knows how big the
1367 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1368 * of space on top of the stack and stackblocklen returns the length of
1369 * this block. Growstackblock will grow this space by at least one byte,
1370 * possibly moving it (like realloc). Grabstackblock actually allocates the
1371 * part of the block that has been used.
1374 growstackblock(void)
1378 newlen = g_stacknleft * 2;
1379 if (newlen < g_stacknleft)
1380 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1384 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1385 struct stack_block *oldstackp;
1386 struct stackmark *xmark;
1387 struct stack_block *sp;
1388 struct stack_block *prevstackp;
1392 oldstackp = g_stackp;
1394 prevstackp = sp->prev;
1395 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1396 sp = ckrealloc(sp, grosslen);
1397 sp->prev = prevstackp;
1399 g_stacknxt = sp->space;
1400 g_stacknleft = newlen;
1401 sstrend = sp->space + newlen;
1404 * Stack marks pointing to the start of the old block
1405 * must be relocated to point to the new block
1408 while (xmark != NULL && xmark->stackp == oldstackp) {
1409 xmark->stackp = g_stackp;
1410 xmark->stacknxt = g_stacknxt;
1411 xmark->stacknleft = g_stacknleft;
1412 xmark = xmark->marknext;
1416 char *oldspace = g_stacknxt;
1417 size_t oldlen = g_stacknleft;
1418 char *p = stalloc(newlen);
1420 /* free the space we just allocated */
1421 g_stacknxt = memcpy(p, oldspace, oldlen);
1422 g_stacknleft += newlen;
1427 grabstackblock(size_t len)
1429 len = SHELL_ALIGN(len);
1431 g_stacknleft -= len;
1435 * The following routines are somewhat easier to use than the above.
1436 * The user declares a variable of type STACKSTR, which may be declared
1437 * to be a register. The macro STARTSTACKSTR initializes things. Then
1438 * the user uses the macro STPUTC to add characters to the string. In
1439 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1440 * grown as necessary. When the user is done, she can just leave the
1441 * string there and refer to it using stackblock(). Or she can allocate
1442 * the space for it using grabstackstr(). If it is necessary to allow
1443 * someone else to use the stack temporarily and then continue to grow
1444 * the string, the user should use grabstack to allocate the space, and
1445 * then call ungrabstr(p) to return to the previous mode of operation.
1447 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1448 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1449 * is space for at least one character.
1454 size_t len = stackblocksize();
1455 if (herefd >= 0 && len >= 1024) {
1456 full_write(herefd, stackblock(), len);
1457 return stackblock();
1460 return (char *)stackblock() + len;
1464 * Called from CHECKSTRSPACE.
1467 makestrspace(size_t newlen, char *p)
1469 size_t len = p - g_stacknxt;
1470 size_t size = stackblocksize();
1475 size = stackblocksize();
1477 if (nleft >= newlen)
1481 return (char *)stackblock() + len;
1485 stack_nputstr(const char *s, size_t n, char *p)
1487 p = makestrspace(n, p);
1488 p = (char *)memcpy(p, s, n) + n;
1493 stack_putstr(const char *s, char *p)
1495 return stack_nputstr(s, strlen(s), p);
1499 _STPUTC(int c, char *p)
1507 #define STARTSTACKSTR(p) ((p) = stackblock())
1508 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1509 #define CHECKSTRSPACE(n, p) do { \
1512 size_t m = sstrend - q; \
1514 (p) = makestrspace(l, q); \
1516 #define USTPUTC(c, p) (*(p)++ = (c))
1517 #define STACKSTRNUL(p) do { \
1518 if ((p) == sstrend) \
1519 (p) = growstackstr(); \
1522 #define STUNPUTC(p) (--(p))
1523 #define STTOPC(p) ((p)[-1])
1524 #define STADJUST(amount, p) ((p) += (amount))
1526 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1527 #define ungrabstackstr(s, p) stunalloc(s)
1528 #define stackstrend() ((void *)sstrend)
1531 /* ============ String helpers */
1534 * prefix -- see if pfx is a prefix of string.
1537 prefix(const char *string, const char *pfx)
1540 if (*pfx++ != *string++)
1543 return (char *) string;
1547 * Check for a valid number. This should be elsewhere.
1550 is_number(const char *p)
1555 } while (*++p != '\0');
1560 * Convert a string of digits to an integer, printing an error message on
1564 number(const char *s)
1567 ash_msg_and_raise_error(msg_illnum, s);
1572 * Produce a possibly single quoted string suitable as input to the shell.
1573 * The return string is allocated on the stack.
1576 single_quote(const char *s)
1586 len = strchrnul(s, '\'') - s;
1588 q = p = makestrspace(len + 3, p);
1591 q = (char *)memcpy(q, s, len) + len;
1600 do len++; while (*++s == '\'');
1602 q = p = makestrspace(len + 3, p);
1605 q = (char *)memcpy(q, s - len, len) + len;
1613 return stackblock();
1617 /* ============ nextopt */
1619 static char **argptr; /* argument list for builtin commands */
1620 static char *optionarg; /* set by nextopt (like getopt) */
1621 static char *optptr; /* used by nextopt */
1624 * XXX - should get rid of. Have all builtins use getopt(3).
1625 * The library getopt must have the BSD extension static variable
1626 * "optreset", otherwise it can't be used within the shell safely.
1628 * Standard option processing (a la getopt) for builtin routines.
1629 * The only argument that is passed to nextopt is the option string;
1630 * the other arguments are unnecessary. It returns the character,
1631 * or '\0' on end of input.
1634 nextopt(const char *optstring)
1641 if (p == NULL || *p == '\0') {
1642 /* We ate entire "-param", take next one */
1648 if (*++p == '\0') /* just "-" ? */
1651 if (LONE_DASH(p)) /* "--" ? */
1653 /* p => next "-param" */
1655 /* p => some option char in the middle of a "-param" */
1657 for (q = optstring; *q != c;) {
1659 ash_msg_and_raise_error("illegal option -%c", c);
1667 ash_msg_and_raise_error("no arg for -%c option", c);
1677 /* ============ Shell variables */
1680 * The parsefile structure pointed to by the global variable parsefile
1681 * contains information about the current file being read.
1684 int nparam; /* # of positional parameters (without $0) */
1685 #if ENABLE_ASH_GETOPTS
1686 int optind; /* next parameter to be processed by getopts */
1687 int optoff; /* used by getopts */
1689 unsigned char malloced; /* if parameter list dynamically allocated */
1690 char **p; /* parameter list */
1694 * Free the list of positional parameters.
1697 freeparam(volatile struct shparam *param)
1699 if (param->malloced) {
1701 ap = ap1 = param->p;
1708 #if ENABLE_ASH_GETOPTS
1709 static void FAST_FUNC getoptsreset(const char *value);
1713 struct var *next; /* next entry in hash list */
1714 int flags; /* flags are defined above */
1715 const char *text; /* name=value */
1716 void (*func)(const char *) FAST_FUNC; /* function to be called when */
1717 /* the variable gets set/unset */
1721 struct localvar *next; /* next local variable in list */
1722 struct var *vp; /* the variable that was made local */
1723 int flags; /* saved flags */
1724 const char *text; /* saved text */
1728 #define VEXPORT 0x01 /* variable is exported */
1729 #define VREADONLY 0x02 /* variable cannot be modified */
1730 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1731 #define VTEXTFIXED 0x08 /* text is statically allocated */
1732 #define VSTACK 0x10 /* text is allocated on the stack */
1733 #define VUNSET 0x20 /* the variable is not set */
1734 #define VNOFUNC 0x40 /* don't call the callback function */
1735 #define VNOSET 0x80 /* do not set variable - just readonly test */
1736 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1737 #if ENABLE_ASH_RANDOM_SUPPORT
1738 # define VDYNAMIC 0x200 /* dynamic variable */
1744 /* Need to be before varinit_data[] */
1745 #if ENABLE_LOCALE_SUPPORT
1746 static void FAST_FUNC
1747 change_lc_all(const char *value)
1749 if (value && *value != '\0')
1750 setlocale(LC_ALL, value);
1752 static void FAST_FUNC
1753 change_lc_ctype(const char *value)
1755 if (value && *value != '\0')
1756 setlocale(LC_CTYPE, value);
1760 static void chkmail(void);
1761 static void changemail(const char *) FAST_FUNC;
1763 static void changepath(const char *) FAST_FUNC;
1764 #if ENABLE_ASH_RANDOM_SUPPORT
1765 static void change_random(const char *) FAST_FUNC;
1768 static const struct {
1771 void (*func)(const char *) FAST_FUNC;
1772 } varinit_data[] = {
1773 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1775 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1776 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1778 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1779 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1780 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1781 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1782 #if ENABLE_ASH_GETOPTS
1783 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1785 #if ENABLE_ASH_RANDOM_SUPPORT
1786 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
1788 #if ENABLE_LOCALE_SUPPORT
1789 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1790 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
1792 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1793 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
1799 struct globals_var {
1800 struct shparam shellparam; /* $@ current positional parameters */
1801 struct redirtab *redirlist;
1803 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1804 struct var *vartab[VTABSIZE];
1805 struct var varinit[ARRAY_SIZE(varinit_data)];
1807 extern struct globals_var *const ash_ptr_to_globals_var;
1808 #define G_var (*ash_ptr_to_globals_var)
1809 #define shellparam (G_var.shellparam )
1810 //#define redirlist (G_var.redirlist )
1811 #define g_nullredirs (G_var.g_nullredirs )
1812 #define preverrout_fd (G_var.preverrout_fd)
1813 #define vartab (G_var.vartab )
1814 #define varinit (G_var.varinit )
1815 #define INIT_G_var() do { \
1817 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1819 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1820 varinit[i].flags = varinit_data[i].flags; \
1821 varinit[i].text = varinit_data[i].text; \
1822 varinit[i].func = varinit_data[i].func; \
1826 #define vifs varinit[0]
1828 # define vmail (&vifs)[1]
1829 # define vmpath (&vmail)[1]
1830 # define vpath (&vmpath)[1]
1832 # define vpath (&vifs)[1]
1834 #define vps1 (&vpath)[1]
1835 #define vps2 (&vps1)[1]
1836 #define vps4 (&vps2)[1]
1837 #if ENABLE_ASH_GETOPTS
1838 # define voptind (&vps4)[1]
1839 # if ENABLE_ASH_RANDOM_SUPPORT
1840 # define vrandom (&voptind)[1]
1843 # if ENABLE_ASH_RANDOM_SUPPORT
1844 # define vrandom (&vps4)[1]
1849 * The following macros access the values of the above variables.
1850 * They have to skip over the name. They return the null string
1851 * for unset variables.
1853 #define ifsval() (vifs.text + 4)
1854 #define ifsset() ((vifs.flags & VUNSET) == 0)
1856 # define mailval() (vmail.text + 5)
1857 # define mpathval() (vmpath.text + 9)
1858 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1860 #define pathval() (vpath.text + 5)
1861 #define ps1val() (vps1.text + 4)
1862 #define ps2val() (vps2.text + 4)
1863 #define ps4val() (vps4.text + 4)
1864 #if ENABLE_ASH_GETOPTS
1865 # define optindval() (voptind.text + 7)
1869 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1870 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1872 #if ENABLE_ASH_GETOPTS
1873 static void FAST_FUNC
1874 getoptsreset(const char *value)
1876 shellparam.optind = number(value);
1877 shellparam.optoff = -1;
1882 * Return of a legal variable name (a letter or underscore followed by zero or
1883 * more letters, underscores, and digits).
1885 static char* FAST_FUNC
1886 endofname(const char *name)
1894 if (!is_in_name(*p))
1901 * Compares two strings up to the first = or '\0'. The first
1902 * string must be terminated by '='; the second may be terminated by
1903 * either '=' or '\0'.
1906 varcmp(const char *p, const char *q)
1910 while ((c = *p) == (d = *q)) {
1925 varequal(const char *a, const char *b)
1927 return !varcmp(a, b);
1931 * Find the appropriate entry in the hash table from the name.
1933 static struct var **
1934 hashvar(const char *p)
1938 hashval = ((unsigned char) *p) << 4;
1939 while (*p && *p != '=')
1940 hashval += (unsigned char) *p++;
1941 return &vartab[hashval % VTABSIZE];
1945 vpcmp(const void *a, const void *b)
1947 return varcmp(*(const char **)a, *(const char **)b);
1951 * This routine initializes the builtin variables.
1961 * PS1 depends on uid
1963 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1964 vps1.text = "PS1=\\w \\$ ";
1967 vps1.text = "PS1=# ";
1970 end = vp + ARRAY_SIZE(varinit);
1972 vpp = hashvar(vp->text);
1975 } while (++vp < end);
1978 static struct var **
1979 findvar(struct var **vpp, const char *name)
1981 for (; *vpp; vpp = &(*vpp)->next) {
1982 if (varequal((*vpp)->text, name)) {
1990 * Find the value of a variable. Returns NULL if not set.
1992 static const char* FAST_FUNC
1993 lookupvar(const char *name)
1997 v = *findvar(hashvar(name), name);
1999 #if ENABLE_ASH_RANDOM_SUPPORT
2001 * Dynamic variables are implemented roughly the same way they are
2002 * in bash. Namely, they're "special" so long as they aren't unset.
2003 * As soon as they're unset, they're no longer dynamic, and dynamic
2004 * lookup will no longer happen at that point. -- PFM.
2006 if ((v->flags & VDYNAMIC))
2009 if (!(v->flags & VUNSET))
2010 return strchrnul(v->text, '=') + 1;
2016 * Search the environment of a builtin command.
2019 bltinlookup(const char *name)
2023 for (sp = cmdenviron; sp; sp = sp->next) {
2024 if (varequal(sp->text, name))
2025 return strchrnul(sp->text, '=') + 1;
2027 return lookupvar(name);
2031 * Same as setvar except that the variable and value are passed in
2032 * the first argument as name=value. Since the first argument will
2033 * be actually stored in the table, it should not be a string that
2035 * Called with interrupts off.
2038 setvareq(char *s, int flags)
2040 struct var *vp, **vpp;
2043 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2044 vp = *findvar(vpp, s);
2046 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2049 if (flags & VNOSAVE)
2052 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2058 if (vp->func && (flags & VNOFUNC) == 0)
2059 (*vp->func)(strchrnul(s, '=') + 1);
2061 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2062 free((char*)vp->text);
2064 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2069 vp = ckzalloc(sizeof(*vp));
2071 /*vp->func = NULL; - ckzalloc did it */
2074 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2081 * Set the value of a variable. The flags argument is ored with the
2082 * flags of the variable. If val is NULL, the variable is unset.
2085 setvar(const char *name, const char *val, int flags)
2092 q = endofname(name);
2093 p = strchrnul(q, '=');
2095 if (!namelen || p != q)
2096 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2101 vallen = strlen(val);
2104 nameeq = ckmalloc(namelen + vallen + 2);
2105 p = (char *)memcpy(nameeq, name, namelen) + namelen;
2108 p = (char *)memcpy(p, val, vallen) + vallen;
2111 setvareq(nameeq, flags | VNOSAVE);
2115 static void FAST_FUNC
2116 setvar2(const char *name, const char *val)
2118 setvar(name, val, 0);
2121 #if ENABLE_ASH_GETOPTS
2123 * Safe version of setvar, returns 1 on success 0 on failure.
2126 setvarsafe(const char *name, const char *val, int flags)
2129 volatile int saveint;
2130 struct jmploc *volatile savehandler = exception_handler;
2131 struct jmploc jmploc;
2134 if (setjmp(jmploc.loc))
2137 exception_handler = &jmploc;
2138 setvar(name, val, flags);
2141 exception_handler = savehandler;
2142 RESTORE_INT(saveint);
2148 * Unset the specified variable.
2151 unsetvar(const char *s)
2157 vpp = findvar(hashvar(s), s);
2161 int flags = vp->flags;
2164 if (flags & VREADONLY)
2166 #if ENABLE_ASH_RANDOM_SUPPORT
2167 vp->flags &= ~VDYNAMIC;
2171 if ((flags & VSTRFIXED) == 0) {
2173 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2174 free((char*)vp->text);
2180 vp->flags &= ~VEXPORT;
2190 * Process a linked list of variable assignments.
2193 listsetvar(struct strlist *list_set_var, int flags)
2195 struct strlist *lp = list_set_var;
2201 setvareq(lp->text, flags);
2208 * Generate a list of variables satisfying the given conditions.
2211 listvars(int on, int off, char ***end)
2222 for (vp = *vpp; vp; vp = vp->next) {
2223 if ((vp->flags & mask) == on) {
2224 if (ep == stackstrend())
2225 ep = growstackstr();
2226 *ep++ = (char *) vp->text;
2229 } while (++vpp < vartab + VTABSIZE);
2230 if (ep == stackstrend())
2231 ep = growstackstr();
2235 return grabstackstr(ep);
2239 /* ============ Path search helper
2241 * The variable path (passed by reference) should be set to the start
2242 * of the path before the first call; path_advance will update
2243 * this value as it proceeds. Successive calls to path_advance will return
2244 * the possible path expansions in sequence. If an option (indicated by
2245 * a percent sign) appears in the path entry then the global variable
2246 * pathopt will be set to point to it; otherwise pathopt will be set to
2249 static const char *pathopt; /* set by path_advance */
2252 path_advance(const char **path, const char *name)
2262 for (p = start; *p && *p != ':' && *p != '%'; p++)
2264 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2265 while (stackblocksize() < len)
2269 memcpy(q, start, p - start);
2277 while (*p && *p != ':')
2284 return stalloc(len);
2288 /* ============ Prompt */
2290 static smallint doprompt; /* if set, prompt the user */
2291 static smallint needprompt; /* true if interactive and at start of line */
2293 #if ENABLE_FEATURE_EDITING
2294 static line_input_t *line_input_state;
2295 static const char *cmdedit_prompt;
2297 putprompt(const char *s)
2299 if (ENABLE_ASH_EXPAND_PRMT) {
2300 free((char*)cmdedit_prompt);
2301 cmdedit_prompt = ckstrdup(s);
2308 putprompt(const char *s)
2314 #if ENABLE_ASH_EXPAND_PRMT
2315 /* expandstr() needs parsing machinery, so it is far away ahead... */
2316 static const char *expandstr(const char *ps);
2318 #define expandstr(s) s
2322 setprompt(int whichprompt)
2325 #if ENABLE_ASH_EXPAND_PRMT
2326 struct stackmark smark;
2331 switch (whichprompt) {
2341 #if ENABLE_ASH_EXPAND_PRMT
2342 setstackmark(&smark);
2343 stalloc(stackblocksize());
2345 putprompt(expandstr(prompt));
2346 #if ENABLE_ASH_EXPAND_PRMT
2347 popstackmark(&smark);
2352 /* ============ The cd and pwd commands */
2354 #define CD_PHYSICAL 1
2364 while ((i = nextopt("LP")) != '\0') {
2366 flags ^= CD_PHYSICAL;
2375 * Update curdir (the name of the current directory) in response to a
2379 updatepwd(const char *dir)
2386 cdcomppath = ststrdup(dir);
2389 if (curdir == nullstr)
2391 new = stack_putstr(curdir, new);
2393 new = makestrspace(strlen(dir) + 2, new);
2394 lim = (char *)stackblock() + 1;
2398 if (new > lim && *lim == '/')
2403 if (dir[1] == '/' && dir[2] != '/') {
2409 p = strtok(cdcomppath, "/");
2413 if (p[1] == '.' && p[2] == '\0') {
2425 new = stack_putstr(p, new);
2433 return stackblock();
2437 * Find out what the current directory is. If we already know the current
2438 * directory, this routine returns immediately.
2443 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2444 return dir ? dir : nullstr;
2448 setpwd(const char *val, int setold)
2452 oldcur = dir = curdir;
2455 setvar("OLDPWD", oldcur, VEXPORT);
2458 if (physdir != nullstr) {
2459 if (physdir != oldcur)
2463 if (oldcur == val || !val) {
2469 dir = ckstrdup(val);
2470 if (oldcur != dir && oldcur != nullstr) {
2475 setvar("PWD", dir, VEXPORT);
2478 static void hashcd(void);
2481 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2482 * know that the current directory has changed.
2485 docd(const char *dest, int flags)
2487 const char *dir = NULL;
2490 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2493 if (!(flags & CD_PHYSICAL)) {
2494 dir = updatepwd(dest);
2508 static int FAST_FUNC
2509 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2521 dest = bltinlookup(homestr);
2522 else if (LONE_DASH(dest)) {
2523 dest = bltinlookup("OLDPWD");
2545 path = bltinlookup("CDPATH");
2554 p = path_advance(&path, dest);
2555 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2559 if (!docd(p, flags))
2564 ash_msg_and_raise_error("can't cd to %s", dest);
2567 if (flags & CD_PRINT)
2568 out1fmt(snlfmt, curdir);
2572 static int FAST_FUNC
2573 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2576 const char *dir = curdir;
2580 if (physdir == nullstr)
2584 out1fmt(snlfmt, dir);
2589 /* ============ ... */
2592 #define IBUFSIZ COMMON_BUFSIZE
2593 /* buffer for top level input file */
2594 #define basebuf bb_common_bufsiz1
2596 /* Syntax classes */
2597 #define CWORD 0 /* character is nothing special */
2598 #define CNL 1 /* newline character */
2599 #define CBACK 2 /* a backslash character */
2600 #define CSQUOTE 3 /* single quote */
2601 #define CDQUOTE 4 /* double quote */
2602 #define CENDQUOTE 5 /* a terminating quote */
2603 #define CBQUOTE 6 /* backwards single quote */
2604 #define CVAR 7 /* a dollar sign */
2605 #define CENDVAR 8 /* a '}' character */
2606 #define CLP 9 /* a left paren in arithmetic */
2607 #define CRP 10 /* a right paren in arithmetic */
2608 #define CENDFILE 11 /* end of file */
2609 #define CCTL 12 /* like CWORD, except it must be escaped */
2610 #define CSPCL 13 /* these terminate a word */
2611 #define CIGN 14 /* character should be ignored */
2614 #if ENABLE_ASH_ALIAS
2618 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2620 #if ENABLE_SH_MATH_SUPPORT
2621 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2623 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2625 static const uint16_t S_I_T[] = {
2626 #if ENABLE_ASH_ALIAS
2627 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2629 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2630 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2631 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2632 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2633 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2634 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2635 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2636 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2637 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2638 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2639 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2640 #if !USE_SIT_FUNCTION
2641 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2642 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2643 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2647 /* Constants below must match table above */
2649 #if ENABLE_ASH_ALIAS
2650 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2652 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2653 CNL_CNL_CNL_CNL , /* 2 */
2654 CWORD_CCTL_CCTL_CWORD , /* 3 */
2655 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2656 CVAR_CVAR_CWORD_CVAR , /* 5 */
2657 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2658 CSPCL_CWORD_CWORD_CLP , /* 7 */
2659 CSPCL_CWORD_CWORD_CRP , /* 8 */
2660 CBACK_CBACK_CCTL_CBACK , /* 9 */
2661 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2662 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2663 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2664 CWORD_CWORD_CWORD_CWORD , /* 13 */
2665 CCTL_CCTL_CCTL_CCTL , /* 14 */
2668 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2669 * caller must ensure proper cast on it if c is *char_ptr!
2671 /* Values for syntax param */
2672 #define BASESYNTAX 0 /* not in quotes */
2673 #define DQSYNTAX 1 /* in double quotes */
2674 #define SQSYNTAX 2 /* in single quotes */
2675 #define ARISYNTAX 3 /* in arithmetic */
2676 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2678 #if USE_SIT_FUNCTION
2681 SIT(int c, int syntax)
2683 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2684 # if ENABLE_ASH_ALIAS
2685 static const uint8_t syntax_index_table[] ALIGN1 = {
2686 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2687 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2688 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2692 static const uint8_t syntax_index_table[] ALIGN1 = {
2693 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2694 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2695 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2704 # if ENABLE_ASH_ALIAS
2710 /* Cast is purely for paranoia here,
2711 * just in case someone passed signed char to us */
2712 if ((unsigned char)c >= CTL_FIRST
2713 && (unsigned char)c <= CTL_LAST
2717 s = strchrnul(spec_symbls, c);
2720 indx = syntax_index_table[s - spec_symbls];
2722 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2725 #else /* !USE_SIT_FUNCTION */
2727 static const uint8_t syntax_index_table[] = {
2728 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2729 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2738 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2739 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2740 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2760 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2761 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2762 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2763 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2764 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2765 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2766 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2767 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2768 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2769 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2770 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2771 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2772 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2773 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2774 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2775 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2776 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2777 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2778 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2779 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2780 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2781 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2782 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2783 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2784 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2785 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2786 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2787 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2788 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2789 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2790 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2791 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2792 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2793 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2794 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2795 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2796 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2797 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2800 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2802 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2803 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2814 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2815 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2816 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2817 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2819 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2820 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2821 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2822 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2823 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2824 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2825 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2826 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2848 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2849 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2850 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2851 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2852 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2853 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2854 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2855 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2856 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2857 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2859 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2860 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2861 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2862 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2863 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2864 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2865 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2866 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 162 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 163 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 164 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 165 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 166 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 167 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 168 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 169 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 170 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 171 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 172 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 173 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 174 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 175 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 176 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 177 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 178 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 179 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 180 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 181 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 182 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 183 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 184 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 185 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 186 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 187 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 188 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 189 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 190 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 191 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 192 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 193 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 194 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 195 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 196 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 197 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 198 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 199 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 200 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 201 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 202 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 203 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 204 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 205 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 206 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 207 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 208 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 209 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 210 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 211 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 212 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 213 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 214 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 215 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 216 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 217 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 218 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 219 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 220 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 221 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 222 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 223 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 224 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 225 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 226 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 227 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 228 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 229 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 231 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 232 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 233 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 234 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 235 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 236 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 237 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 238 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 239 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 241 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 242 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 243 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 244 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 245 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 246 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 247 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 248 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 249 */ CWORD_CWORD_CWORD_CWORD,
2979 /* 250 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 251 */ CWORD_CWORD_CWORD_CWORD,
2981 /* 252 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 253 */ CWORD_CWORD_CWORD_CWORD,
2983 /* 254 */ CWORD_CWORD_CWORD_CWORD,
2984 /* 255 */ CWORD_CWORD_CWORD_CWORD,
2985 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2986 # if ENABLE_ASH_ALIAS
2987 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
2991 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
2993 #endif /* !USE_SIT_FUNCTION */
2996 /* ============ Alias handling */
2998 #if ENABLE_ASH_ALIAS
3000 #define ALIASINUSE 1
3011 static struct alias **atab; // [ATABSIZE];
3012 #define INIT_G_alias() do { \
3013 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3017 static struct alias **
3018 __lookupalias(const char *name) {
3019 unsigned int hashval;
3026 ch = (unsigned char)*p;
3030 ch = (unsigned char)*++p;
3032 app = &atab[hashval % ATABSIZE];
3034 for (; *app; app = &(*app)->next) {
3035 if (strcmp(name, (*app)->name) == 0) {
3043 static struct alias *
3044 lookupalias(const char *name, int check)
3046 struct alias *ap = *__lookupalias(name);
3048 if (check && ap && (ap->flag & ALIASINUSE))
3053 static struct alias *
3054 freealias(struct alias *ap)
3058 if (ap->flag & ALIASINUSE) {
3059 ap->flag |= ALIASDEAD;
3071 setalias(const char *name, const char *val)
3073 struct alias *ap, **app;
3075 app = __lookupalias(name);
3079 if (!(ap->flag & ALIASINUSE)) {
3082 ap->val = ckstrdup(val);
3083 ap->flag &= ~ALIASDEAD;
3086 ap = ckzalloc(sizeof(struct alias));
3087 ap->name = ckstrdup(name);
3088 ap->val = ckstrdup(val);
3089 /*ap->flag = 0; - ckzalloc did it */
3090 /*ap->next = NULL;*/
3097 unalias(const char *name)
3101 app = __lookupalias(name);
3105 *app = freealias(*app);
3116 struct alias *ap, **app;
3120 for (i = 0; i < ATABSIZE; i++) {
3122 for (ap = *app; ap; ap = *app) {
3123 *app = freealias(*app);
3133 printalias(const struct alias *ap)
3135 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3139 * TODO - sort output
3141 static int FAST_FUNC
3142 aliascmd(int argc UNUSED_PARAM, char **argv)
3151 for (i = 0; i < ATABSIZE; i++) {
3152 for (ap = atab[i]; ap; ap = ap->next) {
3158 while ((n = *++argv) != NULL) {
3159 v = strchr(n+1, '=');
3160 if (v == NULL) { /* n+1: funny ksh stuff */
3161 ap = *__lookupalias(n);
3163 fprintf(stderr, "%s: %s not found\n", "alias", n);
3176 static int FAST_FUNC
3177 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3181 while ((i = nextopt("a")) != '\0') {
3187 for (i = 0; *argptr; argptr++) {
3188 if (unalias(*argptr)) {
3189 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3197 #endif /* ASH_ALIAS */
3200 /* ============ jobs.c */
3202 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3205 #define FORK_NOJOB 2
3207 /* mode flags for showjob(s) */
3208 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3209 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3210 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3213 * A job structure contains information about a job. A job is either a
3214 * single process or a set of processes contained in a pipeline. In the
3215 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3219 pid_t ps_pid; /* process id */
3220 int ps_status; /* last process status from wait() */
3221 char *ps_cmd; /* text of command being run */
3225 struct procstat ps0; /* status of process */
3226 struct procstat *ps; /* status or processes when more than one */
3228 int stopstatus; /* status of a stopped job */
3231 nprocs: 16, /* number of processes */
3233 #define JOBRUNNING 0 /* at least one proc running */
3234 #define JOBSTOPPED 1 /* all procs are stopped */
3235 #define JOBDONE 2 /* all procs are completed */
3237 sigint: 1, /* job was killed by SIGINT */
3238 jobctl: 1, /* job running under job control */
3240 waited: 1, /* true if this entry has been waited for */
3241 used: 1, /* true if this entry is in used */
3242 changed: 1; /* true if status has changed */
3243 struct job *prev_job; /* previous job */
3246 static struct job *makejob(/*union node *,*/ int);
3247 static int forkshell(struct job *, union node *, int);
3248 static int waitforjob(struct job *);
3251 enum { doing_jobctl = 0 };
3252 #define setjobctl(on) do {} while (0)
3254 static smallint doing_jobctl; //references:8
3255 static void setjobctl(int);
3262 ignoresig(int signo)
3264 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3265 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3266 /* No, need to do it */
3267 signal(signo, SIG_IGN);
3269 sigmode[signo - 1] = S_HARD_IGN;
3273 * Signal handler. Only one usage site - in setsignal()
3278 gotsig[signo - 1] = 1;
3280 if (signo == SIGINT && !trap[SIGINT]) {
3281 if (!suppress_int) {
3283 raise_interrupt(); /* does not return */
3287 pending_sig = signo;
3292 * Set the signal handler for the specified signal. The routine figures
3293 * out what it should be set to.
3296 setsignal(int signo)
3299 char cur_act, new_act;
3300 struct sigaction act;
3304 if (t != NULL) { /* trap for this sig is set */
3306 if (t[0] == '\0') /* trap is "": ignore this sig */
3310 if (rootshell && new_act == S_DFL) {
3313 if (iflag || minusc || sflag == 0)
3322 * "In all cases, bash ignores SIGQUIT. Non-builtin
3323 * commands run by bash have signal handlers
3324 * set to the values inherited by the shell
3325 * from its parent". */
3341 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3342 //whereas we have to restore it to what shell got on entry
3343 //from the parent. See comment above
3345 t = &sigmode[signo - 1];
3348 /* current setting is not yet known */
3349 if (sigaction(signo, NULL, &act)) {
3350 /* pretend it worked; maybe we should give a warning,
3351 * but other shells don't. We don't alter sigmode,
3352 * so we retry every time.
3353 * btw, in Linux it never fails. --vda */
3356 if (act.sa_handler == SIG_IGN) {
3357 cur_act = S_HARD_IGN;
3359 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3361 cur_act = S_IGN; /* don't hard ignore these */
3365 if (cur_act == S_HARD_IGN || cur_act == new_act)
3368 act.sa_handler = SIG_DFL;
3371 act.sa_handler = onsig;
3372 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3373 sigfillset(&act.sa_mask); /* ditto */
3376 act.sa_handler = SIG_IGN;
3379 sigaction_set(signo, &act);
3384 /* mode flags for set_curjob */
3385 #define CUR_DELETE 2
3386 #define CUR_RUNNING 1
3387 #define CUR_STOPPED 0
3389 /* mode flags for dowait */
3390 #define DOWAIT_NONBLOCK WNOHANG
3391 #define DOWAIT_BLOCK 0
3394 /* pgrp of shell on invocation */
3395 static int initialpgrp; //references:2
3396 static int ttyfd = -1; //5
3399 static struct job *jobtab; //5
3401 static unsigned njobs; //4
3403 static struct job *curjob; //lots
3404 /* number of presumed living untracked jobs */
3405 static int jobless; //4
3408 set_curjob(struct job *jp, unsigned mode)
3411 struct job **jpp, **curp;
3413 /* first remove from list */
3414 jpp = curp = &curjob;
3419 jpp = &jp1->prev_job;
3421 *jpp = jp1->prev_job;
3423 /* Then re-insert in correct position */
3431 /* job being deleted */
3434 /* newly created job or backgrounded job,
3435 put after all stopped jobs. */
3439 if (!jp1 || jp1->state != JOBSTOPPED)
3442 jpp = &jp1->prev_job;
3448 /* newly stopped job - becomes curjob */
3449 jp->prev_job = *jpp;
3457 jobno(const struct job *jp)
3459 return jp - jobtab + 1;
3464 * Convert a job name to a job structure.
3467 #define getjob(name, getctl) getjob(name)
3470 getjob(const char *name, int getctl)
3474 const char *err_msg = "%s: no such job";
3478 char *(*match)(const char *, const char *);
3493 if (c == '+' || c == '%') {
3495 err_msg = "No current job";
3501 err_msg = "No previous job";
3512 jp = jobtab + num - 1;
3527 if (match(jp->ps[0].ps_cmd, p)) {
3531 err_msg = "%s: ambiguous";
3541 err_msg = "job %s not created under job control";
3542 if (getctl && jp->jobctl == 0)
3547 ash_msg_and_raise_error(err_msg, name);
3551 * Mark a job structure as unused.
3554 freejob(struct job *jp)
3556 struct procstat *ps;
3560 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3561 if (ps->ps_cmd != nullstr)
3564 if (jp->ps != &jp->ps0)
3567 set_curjob(jp, CUR_DELETE);
3573 xtcsetpgrp(int fd, pid_t pgrp)
3575 if (tcsetpgrp(fd, pgrp))
3576 ash_msg_and_raise_error("can't set tty process group (%m)");
3580 * Turn job control on and off.
3582 * Note: This code assumes that the third arg to ioctl is a character
3583 * pointer, which is true on Berkeley systems but not System V. Since
3584 * System V doesn't have job control yet, this isn't a problem now.
3586 * Called with interrupts off.
3594 if (on == doing_jobctl || rootshell == 0)
3598 ofd = fd = open(_PATH_TTY, O_RDWR);
3600 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3601 * That sometimes helps to acquire controlling tty.
3602 * Obviously, a workaround for bugs when someone
3603 * failed to provide a controlling tty to bash! :) */
3609 fd = fcntl(fd, F_DUPFD, 10);
3614 /* fd is a tty at this point */
3615 close_on_exec_on(fd);
3616 do { /* while we are in the background */
3617 pgrp = tcgetpgrp(fd);
3620 ash_msg("can't access tty; job control turned off");
3624 if (pgrp == getpgrp())
3635 xtcsetpgrp(fd, pgrp);
3637 /* turning job control off */
3640 /* was xtcsetpgrp, but this can make exiting ash
3641 * loop forever if pty is already deleted */
3642 tcsetpgrp(fd, pgrp);
3656 static int FAST_FUNC
3657 killcmd(int argc, char **argv)
3660 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3662 if (argv[i][0] == '%') {
3663 struct job *jp = getjob(argv[i], 0);
3664 unsigned pid = jp->ps[0].ps_pid;
3665 /* Enough space for ' -NNN<nul>' */
3666 argv[i] = alloca(sizeof(int)*3 + 3);
3667 /* kill_main has matching code to expect
3668 * leading space. Needed to not confuse
3669 * negative pids with "kill -SIGNAL_NO" syntax */
3670 sprintf(argv[i], " -%u", pid);
3672 } while (argv[++i]);
3674 return kill_main(argc, argv);
3678 showpipe(struct job *jp /*, FILE *out*/)
3680 struct procstat *ps;
3681 struct procstat *psend;
3683 psend = jp->ps + jp->nprocs;
3684 for (ps = jp->ps + 1; ps < psend; ps++)
3685 printf(" | %s", ps->ps_cmd);
3686 outcslow('\n', stdout);
3687 flush_stdout_stderr();
3692 restartjob(struct job *jp, int mode)
3694 struct procstat *ps;
3700 if (jp->state == JOBDONE)
3702 jp->state = JOBRUNNING;
3703 pgid = jp->ps[0].ps_pid;
3704 if (mode == FORK_FG)
3705 xtcsetpgrp(ttyfd, pgid);
3706 killpg(pgid, SIGCONT);
3710 if (WIFSTOPPED(ps->ps_status)) {
3716 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3721 static int FAST_FUNC
3722 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3728 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3732 jp = getjob(*argv, 1);
3733 if (mode == FORK_BG) {
3734 set_curjob(jp, CUR_RUNNING);
3735 printf("[%d] ", jobno(jp));
3737 out1str(jp->ps[0].ps_cmd);
3738 showpipe(jp /*, stdout*/);
3739 retval = restartjob(jp, mode);
3740 } while (*argv && *++argv);
3746 sprint_status(char *s, int status, int sigonly)
3752 if (!WIFEXITED(status)) {
3754 if (WIFSTOPPED(status))
3755 st = WSTOPSIG(status);
3758 st = WTERMSIG(status);
3760 if (st == SIGINT || st == SIGPIPE)
3763 if (WIFSTOPPED(status))
3768 col = fmtstr(s, 32, strsignal(st));
3769 if (WCOREDUMP(status)) {
3770 col += fmtstr(s + col, 16, " (core dumped)");
3772 } else if (!sigonly) {
3773 st = WEXITSTATUS(status);
3775 col = fmtstr(s, 16, "Done(%d)", st);
3777 col = fmtstr(s, 16, "Done");
3784 dowait(int wait_flags, struct job *job)
3789 struct job *thisjob;
3792 TRACE(("dowait(0x%x) called\n", wait_flags));
3794 /* Do a wait system call. If job control is compiled in, we accept
3795 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3796 * NB: _not_ safe_waitpid, we need to detect EINTR */
3798 wait_flags |= WUNTRACED;
3799 pid = waitpid(-1, &status, wait_flags);
3800 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3801 pid, status, errno, strerror(errno)));
3807 for (jp = curjob; jp; jp = jp->prev_job) {
3808 struct procstat *ps;
3809 struct procstat *psend;
3810 if (jp->state == JOBDONE)
3814 psend = ps + jp->nprocs;
3816 if (ps->ps_pid == pid) {
3817 TRACE(("Job %d: changing status of proc %d "
3818 "from 0x%x to 0x%x\n",
3819 jobno(jp), pid, ps->ps_status, status));
3820 ps->ps_status = status;
3823 if (ps->ps_status == -1)
3826 if (state == JOBRUNNING)
3828 if (WIFSTOPPED(ps->ps_status)) {
3829 jp->stopstatus = ps->ps_status;
3833 } while (++ps < psend);
3838 if (!WIFSTOPPED(status))
3844 if (state != JOBRUNNING) {
3845 thisjob->changed = 1;
3847 if (thisjob->state != state) {
3848 TRACE(("Job %d: changing state from %d to %d\n",
3849 jobno(thisjob), thisjob->state, state));
3850 thisjob->state = state;
3852 if (state == JOBSTOPPED) {
3853 set_curjob(thisjob, CUR_STOPPED);
3862 if (thisjob && thisjob == job) {
3866 len = sprint_status(s, status, 1);
3877 blocking_wait_with_raise_on_sig(struct job *job)
3879 pid_t pid = dowait(DOWAIT_BLOCK, job);
3880 if (pid <= 0 && pending_sig)
3881 raise_exception(EXSIG);
3887 showjob(FILE *out, struct job *jp, int mode)
3889 struct procstat *ps;
3890 struct procstat *psend;
3897 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
3898 /* just output process (group) id of pipeline */
3899 fprintf(out, "%d\n", ps->ps_pid);
3903 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3908 else if (curjob && jp == curjob->prev_job)
3911 if (mode & SHOW_PIDS)
3912 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
3914 psend = ps + jp->nprocs;
3916 if (jp->state == JOBRUNNING) {
3917 strcpy(s + col, "Running");
3918 col += sizeof("Running") - 1;
3920 int status = psend[-1].ps_status;
3921 if (jp->state == JOBSTOPPED)
3922 status = jp->stopstatus;
3923 col += sprint_status(s + col, status, 0);
3925 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
3927 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3928 * or prints several "PID | <cmdN>" lines,
3929 * depending on SHOW_PIDS bit.
3930 * We do not print status of individual processes
3931 * between PID and <cmdN>. bash does it, but not very well:
3932 * first line shows overall job status, not process status,
3933 * making it impossible to know 1st process status.
3937 /* for each process */
3940 if (mode & SHOW_PIDS)
3941 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
3943 fprintf(out, "%s%*c%s%s",
3945 33 - col >= 0 ? 33 - col : 0, ' ',
3946 ps == jp->ps ? "" : "| ",
3949 } while (++ps != psend);
3950 outcslow('\n', out);
3954 if (jp->state == JOBDONE) {
3955 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3961 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3962 * statuses have changed since the last call to showjobs.
3965 showjobs(FILE *out, int mode)
3969 TRACE(("showjobs(0x%x) called\n", mode));
3971 /* Handle all finished jobs */
3972 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
3975 for (jp = curjob; jp; jp = jp->prev_job) {
3976 if (!(mode & SHOW_CHANGED) || jp->changed) {
3977 showjob(out, jp, mode);
3982 static int FAST_FUNC
3983 jobscmd(int argc UNUSED_PARAM, char **argv)
3988 while ((m = nextopt("lp")) != '\0') {
3992 mode |= SHOW_ONLY_PGID;
3998 showjob(stdout, getjob(*argv, 0), mode);
4001 showjobs(stdout, mode);
4008 /* Called only on finished or stopped jobs (no members are running) */
4010 getstatus(struct job *job)
4014 struct procstat *ps;
4016 /* Fetch last member's status */
4017 ps = job->ps + job->nprocs - 1;
4018 status = ps->ps_status;
4020 /* "set -o pipefail" mode: use last _nonzero_ status */
4021 while (status == 0 && --ps >= job->ps)
4022 status = ps->ps_status;
4025 retval = WEXITSTATUS(status);
4026 if (!WIFEXITED(status)) {
4028 retval = WSTOPSIG(status);
4029 if (!WIFSTOPPED(status))
4032 /* XXX: limits number of signals */
4033 retval = WTERMSIG(status);
4035 if (retval == SIGINT)
4041 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4042 jobno(job), job->nprocs, status, retval));
4046 static int FAST_FUNC
4047 waitcmd(int argc UNUSED_PARAM, char **argv)
4054 raise_exception(EXSIG);
4061 /* wait for all jobs */
4065 if (!jp) /* no running procs */
4067 if (jp->state == JOBRUNNING)
4073 * "When bash is waiting for an asynchronous command via
4074 * the wait builtin, the reception of a signal for which a trap
4075 * has been set will cause the wait builtin to return immediately
4076 * with an exit status greater than 128, immediately after which
4077 * the trap is executed."
4078 * Do we do it that way? */
4079 blocking_wait_with_raise_on_sig(NULL);
4085 if (**argv != '%') {
4086 pid_t pid = number(*argv);
4091 if (job->ps[job->nprocs - 1].ps_pid == pid)
4093 job = job->prev_job;
4096 job = getjob(*argv, 0);
4097 /* loop until process terminated or stopped */
4098 while (job->state == JOBRUNNING)
4099 blocking_wait_with_raise_on_sig(NULL);
4101 retval = getstatus(job);
4114 struct job *jp, *jq;
4116 len = njobs * sizeof(*jp);
4118 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4120 offset = (char *)jp - (char *)jq;
4122 /* Relocate pointers */
4125 jq = (struct job *)((char *)jq + l);
4129 #define joff(p) ((struct job *)((char *)(p) + l))
4130 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4131 if (joff(jp)->ps == &jq->ps0)
4132 jmove(joff(jp)->ps);
4133 if (joff(jp)->prev_job)
4134 jmove(joff(jp)->prev_job);
4144 jp = (struct job *)((char *)jp + len);
4148 } while (--jq >= jp);
4153 * Return a new job structure.
4154 * Called with interrupts off.
4157 makejob(/*union node *node,*/ int nprocs)
4162 for (i = njobs, jp = jobtab; ; jp++) {
4169 if (jp->state != JOBDONE || !jp->waited)
4178 memset(jp, 0, sizeof(*jp));
4180 /* jp->jobctl is a bitfield.
4181 * "jp->jobctl |= jobctl" likely to give awful code */
4185 jp->prev_job = curjob;
4190 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4192 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4199 * Return a string identifying a command (to be printed by the
4202 static char *cmdnextc;
4205 cmdputs(const char *s)
4207 static const char vstype[VSTYPE + 1][3] = {
4208 "", "}", "-", "+", "?", "=",
4209 "%", "%%", "#", "##"
4210 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4213 const char *p, *str;
4217 unsigned char subtype = 0;
4221 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4223 while ((c = *p++) != '\0') {
4231 if ((subtype & VSTYPE) == VSLENGTH)
4235 if (!(subtype & VSQUOTE) == !(quoted & 1))
4241 str = "\"}" + !(quoted & 1);
4248 case CTLBACKQ+CTLQUOTE:
4251 #if ENABLE_SH_MATH_SUPPORT
4266 if ((subtype & VSTYPE) != VSNORMAL)
4268 str = vstype[subtype & VSTYPE];
4269 if (subtype & VSNUL)
4278 /* These can only happen inside quotes */
4291 while ((c = *str++) != '\0') {
4294 } /* while *p++ not NUL */
4297 USTPUTC('"', nextc);
4303 /* cmdtxt() and cmdlist() call each other */
4304 static void cmdtxt(union node *n);
4307 cmdlist(union node *np, int sep)
4309 for (; np; np = np->narg.next) {
4313 if (sep && np->narg.next)
4319 cmdtxt(union node *n)
4322 struct nodelist *lp;
4333 lp = n->npipe.cmdlist;
4351 cmdtxt(n->nbinary.ch1);
4367 cmdtxt(n->nif.test);
4369 if (n->nif.elsepart) {
4370 cmdtxt(n->nif.ifpart);
4372 n = n->nif.elsepart;
4390 cmdtxt(n->nbinary.ch1);
4400 cmdputs(n->nfor.var);
4402 cmdlist(n->nfor.args, 1);
4407 cmdputs(n->narg.text);
4411 cmdlist(n->ncmd.args, 1);
4412 cmdlist(n->ncmd.redirect, 0);
4425 cmdputs(n->ncase.expr->narg.text);
4427 for (np = n->ncase.cases; np; np = np->nclist.next) {
4428 cmdtxt(np->nclist.pattern);
4430 cmdtxt(np->nclist.body);
4444 #if ENABLE_ASH_BASH_COMPAT
4459 cmdputs(utoa(n->nfile.fd));
4461 if (n->type == NTOFD || n->type == NFROMFD) {
4462 cmdputs(utoa(n->ndup.dupfd));
4471 commandtext(union node *n)
4475 STARTSTACKSTR(cmdnextc);
4477 name = stackblock();
4478 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4479 name, cmdnextc, cmdnextc));
4480 return ckstrdup(name);
4485 * Fork off a subshell. If we are doing job control, give the subshell its
4486 * own process group. Jp is a job structure that the job is to be added to.
4487 * N is the command that will be evaluated by the child. Both jp and n may
4488 * be NULL. The mode parameter can be one of the following:
4489 * FORK_FG - Fork off a foreground process.
4490 * FORK_BG - Fork off a background process.
4491 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4492 * process group even if job control is on.
4494 * When job control is turned off, background processes have their standard
4495 * input redirected to /dev/null (except for the second and later processes
4498 * Called with interrupts off.
4501 * Clear traps on a fork.
4508 for (tp = trap; tp < &trap[NSIG]; tp++) {
4509 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4511 if (trap_ptr == trap)
4513 /* else: it "belongs" to trap_ptr vector, don't free */
4515 if ((tp - trap) != 0)
4516 setsignal(tp - trap);
4522 /* Lives far away from here, needed for forkchild */
4523 static void closescript(void);
4525 /* Called after fork(), in child */
4526 static NOINLINE void
4527 forkchild(struct job *jp, union node *n, int mode)
4531 TRACE(("Child shell %d\n", getpid()));
4535 /* man bash: "Non-builtin commands run by bash have signal handlers
4536 * set to the values inherited by the shell from its parent".
4537 * Do we do it correctly? */
4541 if (mode == FORK_NOJOB /* is it `xxx` ? */
4542 && n && n->type == NCMD /* is it single cmd? */
4543 /* && n->ncmd.args->type == NARG - always true? */
4544 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4545 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4546 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4548 TRACE(("Trap hack\n"));
4549 /* Awful hack for `trap` or $(trap).
4551 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4552 * contains an example where "trap" is executed in a subshell:
4554 * save_traps=$(trap)
4556 * eval "$save_traps"
4558 * Standard does not say that "trap" in subshell shall print
4559 * parent shell's traps. It only says that its output
4560 * must have suitable form, but then, in the above example
4561 * (which is not supposed to be normative), it implies that.
4563 * bash (and probably other shell) does implement it
4564 * (traps are reset to defaults, but "trap" still shows them),
4565 * but as a result, "trap" logic is hopelessly messed up:
4568 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4569 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4570 * # true | trap <--- trap is in subshell - no output (ditto)
4571 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4572 * trap -- 'echo Ho' SIGWINCH
4573 * # echo `(trap)` <--- in subshell in subshell - output
4574 * trap -- 'echo Ho' SIGWINCH
4575 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4576 * trap -- 'echo Ho' SIGWINCH
4578 * The rules when to forget and when to not forget traps
4579 * get really complex and nonsensical.
4581 * Our solution: ONLY bare $(trap) or `trap` is special.
4583 /* Save trap handler strings for trap builtin to print */
4584 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4585 /* Fall through into clearing traps */
4589 /* do job control only in root shell */
4591 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4594 if (jp->nprocs == 0)
4597 pgrp = jp->ps[0].ps_pid;
4598 /* this can fail because we are doing it in the parent also */
4600 if (mode == FORK_FG)
4601 xtcsetpgrp(ttyfd, pgrp);
4606 if (mode == FORK_BG) {
4607 /* man bash: "When job control is not in effect,
4608 * asynchronous commands ignore SIGINT and SIGQUIT" */
4611 if (jp->nprocs == 0) {
4613 if (open(bb_dev_null, O_RDONLY) != 0)
4614 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4618 if (iflag) { /* why if iflag only? */
4623 * "In all cases, bash ignores SIGQUIT. Non-builtin
4624 * commands run by bash have signal handlers
4625 * set to the values inherited by the shell
4627 * Take care of the second rule: */
4631 if (n && n->type == NCMD
4632 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4634 TRACE(("Job hack\n"));
4635 /* "jobs": we do not want to clear job list for it,
4636 * instead we remove only _its_ own_ job from job list.
4637 * This makes "jobs .... | cat" more useful.
4643 for (jp = curjob; jp; jp = jp->prev_job)
4648 /* Called after fork(), in parent */
4650 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4653 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4655 TRACE(("In parent shell: child = %d\n", pid));
4657 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4663 if (mode != FORK_NOJOB && jp->jobctl) {
4666 if (jp->nprocs == 0)
4669 pgrp = jp->ps[0].ps_pid;
4670 /* This can fail because we are doing it in the child also */
4674 if (mode == FORK_BG) {
4675 backgndpid = pid; /* set $! */
4676 set_curjob(jp, CUR_RUNNING);
4679 struct procstat *ps = &jp->ps[jp->nprocs++];
4682 ps->ps_cmd = nullstr;
4684 if (doing_jobctl && n)
4685 ps->ps_cmd = commandtext(n);
4691 forkshell(struct job *jp, union node *n, int mode)
4695 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4698 TRACE(("Fork failed, errno=%d", errno));
4701 ash_msg_and_raise_error("can't fork");
4704 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4705 forkchild(jp, n, mode);
4707 forkparent(jp, n, mode, pid);
4713 * Wait for job to finish.
4715 * Under job control we have the problem that while a child process
4716 * is running interrupts generated by the user are sent to the child
4717 * but not to the shell. This means that an infinite loop started by
4718 * an interactive user may be hard to kill. With job control turned off,
4719 * an interactive user may place an interactive program inside a loop.
4720 * If the interactive program catches interrupts, the user doesn't want
4721 * these interrupts to also abort the loop. The approach we take here
4722 * is to have the shell ignore interrupt signals while waiting for a
4723 * foreground process to terminate, and then send itself an interrupt
4724 * signal if the child process was terminated by an interrupt signal.
4725 * Unfortunately, some programs want to do a bit of cleanup and then
4726 * exit on interrupt; unless these processes terminate themselves by
4727 * sending a signal to themselves (instead of calling exit) they will
4728 * confuse this approach.
4730 * Called with interrupts off.
4733 waitforjob(struct job *jp)
4737 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4740 while (jp->state == JOBRUNNING) {
4741 /* In non-interactive shells, we _can_ get
4742 * a keyboard signal here and be EINTRed,
4743 * but we just loop back, waiting for command to complete.
4746 * "If bash is waiting for a command to complete and receives
4747 * a signal for which a trap has been set, the trap
4748 * will not be executed until the command completes."
4750 * Reality is that even if trap is not set, bash
4751 * will not act on the signal until command completes.
4752 * Try this. sleep5intoff.c:
4753 * #include <signal.h>
4754 * #include <unistd.h>
4757 * sigemptyset(&set);
4758 * sigaddset(&set, SIGINT);
4759 * sigaddset(&set, SIGQUIT);
4760 * sigprocmask(SIG_BLOCK, &set, NULL);
4764 * $ bash -c './sleep5intoff; echo hi'
4765 * ^C^C^C^C <--- pressing ^C once a second
4767 * $ bash -c './sleep5intoff; echo hi'
4768 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4771 dowait(DOWAIT_BLOCK, jp);
4778 xtcsetpgrp(ttyfd, rootpid);
4780 * This is truly gross.
4781 * If we're doing job control, then we did a TIOCSPGRP which
4782 * caused us (the shell) to no longer be in the controlling
4783 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4784 * intuit from the subprocess exit status whether a SIGINT
4785 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4787 if (jp->sigint) /* TODO: do the same with all signals */
4788 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4790 if (jp->state == JOBDONE)
4797 * return 1 if there are stopped jobs, otherwise 0
4809 if (jp && jp->state == JOBSTOPPED) {
4810 out2str("You have stopped jobs.\n");
4819 /* ============ redir.c
4821 * Code for dealing with input/output redirection.
4824 #define EMPTY -2 /* marks an unused slot in redirtab */
4825 #define CLOSED -3 /* marks a slot of previously-closed fd */
4828 * Open a file in noclobber mode.
4829 * The code was copied from bash.
4832 noclobberopen(const char *fname)
4835 struct stat finfo, finfo2;
4838 * If the file exists and is a regular file, return an error
4841 r = stat(fname, &finfo);
4842 if (r == 0 && S_ISREG(finfo.st_mode)) {
4848 * If the file was not present (r != 0), make sure we open it
4849 * exclusively so that if it is created before we open it, our open
4850 * will fail. Make sure that we do not truncate an existing file.
4851 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4852 * file was not a regular file, we leave O_EXCL off.
4855 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4856 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4858 /* If the open failed, return the file descriptor right away. */
4863 * OK, the open succeeded, but the file may have been changed from a
4864 * non-regular file to a regular file between the stat and the open.
4865 * We are assuming that the O_EXCL open handles the case where FILENAME
4866 * did not exist and is symlinked to an existing file between the stat
4871 * If we can open it and fstat the file descriptor, and neither check
4872 * revealed that it was a regular file, and the file has not been
4873 * replaced, return the file descriptor.
4875 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4876 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4879 /* The file has been replaced. badness. */
4886 * Handle here documents. Normally we fork off a process to write the
4887 * data to a pipe. If the document is short, we can stuff the data in
4888 * the pipe without forking.
4890 /* openhere needs this forward reference */
4891 static void expandhere(union node *arg, int fd);
4893 openhere(union node *redir)
4899 ash_msg_and_raise_error("pipe call failed");
4900 if (redir->type == NHERE) {
4901 len = strlen(redir->nhere.doc->narg.text);
4902 if (len <= PIPE_BUF) {
4903 full_write(pip[1], redir->nhere.doc->narg.text, len);
4907 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4910 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4911 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4912 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4913 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4914 signal(SIGPIPE, SIG_DFL);
4915 if (redir->type == NHERE)
4916 full_write(pip[1], redir->nhere.doc->narg.text, len);
4918 expandhere(redir->nhere.doc, pip[1]);
4919 _exit(EXIT_SUCCESS);
4927 openredirect(union node *redir)
4932 switch (redir->nfile.type) {
4934 fname = redir->nfile.expfname;
4935 f = open(fname, O_RDONLY);
4940 fname = redir->nfile.expfname;
4941 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4946 #if ENABLE_ASH_BASH_COMPAT
4949 /* Take care of noclobber mode. */
4951 fname = redir->nfile.expfname;
4952 f = noclobberopen(fname);
4959 fname = redir->nfile.expfname;
4960 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4965 fname = redir->nfile.expfname;
4966 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4974 /* Fall through to eliminate warning. */
4975 /* Our single caller does this itself */
4982 f = openhere(redir);
4988 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4990 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
4994 * Copy a file descriptor to be >= to. Returns -1
4995 * if the source file descriptor is closed, EMPTY if there are no unused
4996 * file descriptors left.
4998 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
4999 * old code was doing close(to) prior to copyfd() to achieve the same */
5001 COPYFD_EXACT = (int)~(INT_MAX),
5002 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5005 copyfd(int from, int to)
5009 if (to & COPYFD_EXACT) {
5010 to &= ~COPYFD_EXACT;
5012 newfd = dup2(from, to);
5014 newfd = fcntl(from, F_DUPFD, to);
5017 if (errno == EMFILE)
5019 /* Happens when source fd is not open: try "echo >&99" */
5020 ash_msg_and_raise_error("%d: %m", from);
5025 /* Struct def and variable are moved down to the first usage site */
5030 struct redirtab *next;
5033 struct two_fd_t two_fd[];
5035 #define redirlist (G_var.redirlist)
5037 static int need_to_remember(struct redirtab *rp, int fd)
5041 if (!rp) /* remembering was not requested */
5044 for (i = 0; i < rp->pair_count; i++) {
5045 if (rp->two_fd[i].orig == fd) {
5046 /* already remembered */
5053 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5054 static int is_hidden_fd(struct redirtab *rp, int fd)
5057 struct parsefile *pf;
5070 fd |= COPYFD_RESTORE;
5071 for (i = 0; i < rp->pair_count; i++) {
5072 if (rp->two_fd[i].copy == fd) {
5080 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5081 * old file descriptors are stashed away so that the redirection can be
5082 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5083 * standard output, and the standard error if it becomes a duplicate of
5084 * stdout, is saved in memory.
5086 /* flags passed to redirect */
5087 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5088 #define REDIR_SAVEFD2 03 /* set preverrout */
5090 redirect(union node *redir, int flags)
5092 struct redirtab *sv;
5097 int copied_fd2 = -1;
5107 if (flags & REDIR_PUSH) {
5108 union node *tmp = redir;
5111 #if ENABLE_ASH_BASH_COMPAT
5112 if (tmp->nfile.type == NTO2)
5115 tmp = tmp->nfile.next;
5117 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5118 sv->next = redirlist;
5119 sv->pair_count = sv_pos;
5121 sv->nullredirs = g_nullredirs - 1;
5123 while (sv_pos > 0) {
5125 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5130 fd = redir->nfile.fd;
5131 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5132 int right_fd = redir->ndup.dupfd;
5133 /* redirect from/to same file descriptor? */
5136 /* echo >&10 and 10 is a fd opened to the sh script? */
5137 if (is_hidden_fd(sv, right_fd)) {
5138 errno = EBADF; /* as if it is closed */
5139 ash_msg_and_raise_error("%d: %m", right_fd);
5143 newfd = openredirect(redir); /* always >= 0 */
5145 /* Descriptor wasn't open before redirect.
5146 * Mark it for close in the future */
5147 if (need_to_remember(sv, fd)) {
5148 goto remember_to_close;
5153 #if ENABLE_ASH_BASH_COMPAT
5156 if (need_to_remember(sv, fd)) {
5157 /* Copy old descriptor */
5158 i = fcntl(fd, F_DUPFD, 10);
5159 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5160 * are closed in popredir() in the child, preventing them from leaking
5161 * into child. (popredir() also cleans up the mess in case of failures)
5166 /* Strange error (e.g. "too many files" EMFILE?) */
5170 ash_msg_and_raise_error("%d: %m", fd);
5173 /* EBADF: it is not open - good, remember to close it */
5176 } else { /* fd is open, save its copy */
5177 /* "exec fd>&-" should not close fds
5178 * which point to script file(s).
5179 * Force them to be restored afterwards */
5180 if (is_hidden_fd(sv, fd))
5181 i |= COPYFD_RESTORE;
5185 sv->two_fd[sv_pos].orig = fd;
5186 sv->two_fd[sv_pos].copy = i;
5190 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5191 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5192 /* Don't want to trigger debugging */
5196 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5198 } else if (fd != newfd) { /* move newfd to fd */
5199 copyfd(newfd, fd | COPYFD_EXACT);
5200 #if ENABLE_ASH_BASH_COMPAT
5201 if (!(redir->nfile.type == NTO2 && fd == 2))
5205 #if ENABLE_ASH_BASH_COMPAT
5206 if (redir->nfile.type == NTO2 && fd == 1) {
5207 /* We already redirected it to fd 1, now copy it to 2 */
5213 } while ((redir = redir->nfile.next) != NULL);
5216 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5217 preverrout_fd = copied_fd2;
5221 * Undo the effects of the last redirection.
5224 popredir(int drop, int restore)
5226 struct redirtab *rp;
5229 if (--g_nullredirs >= 0)
5233 for (i = 0; i < rp->pair_count; i++) {
5234 int fd = rp->two_fd[i].orig;
5235 int copy = rp->two_fd[i].copy;
5236 if (copy == CLOSED) {
5241 if (copy != EMPTY) {
5242 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5243 copy &= ~COPYFD_RESTORE;
5245 copyfd(copy, fd | COPYFD_EXACT);
5247 close(copy & ~COPYFD_RESTORE);
5250 redirlist = rp->next;
5251 g_nullredirs = rp->nullredirs;
5257 * Undo all redirections. Called on error or interrupt.
5261 * Discard all saved file descriptors.
5264 clearredir(int drop)
5270 popredir(drop, /*restore:*/ 0);
5275 redirectsafe(union node *redir, int flags)
5278 volatile int saveint;
5279 struct jmploc *volatile savehandler = exception_handler;
5280 struct jmploc jmploc;
5283 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5284 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5286 exception_handler = &jmploc;
5287 redirect(redir, flags);
5289 exception_handler = savehandler;
5290 if (err && exception_type != EXERROR)
5291 longjmp(exception_handler->loc, 1);
5292 RESTORE_INT(saveint);
5297 /* ============ Routines to expand arguments to commands
5299 * We have to deal with backquotes, shell variables, and file metacharacters.
5302 #if ENABLE_SH_MATH_SUPPORT
5304 ash_arith(const char *s)
5306 arith_eval_hooks_t math_hooks;
5310 math_hooks.lookupvar = lookupvar;
5311 math_hooks.setvar = setvar2;
5312 math_hooks.endofname = endofname;
5315 result = arith(s, &errcode, &math_hooks);
5318 ash_msg_and_raise_error("exponent less than 0");
5320 ash_msg_and_raise_error("divide by zero");
5322 ash_msg_and_raise_error("expression recursion loop detected");
5323 raise_error_syntax(s);
5334 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5335 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5336 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5337 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5338 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5339 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5340 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5341 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5342 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5346 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5347 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5348 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5349 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5350 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5353 * Structure specifying which parts of the string should be searched
5354 * for IFS characters.
5357 struct ifsregion *next; /* next region in list */
5358 int begoff; /* offset of start of region */
5359 int endoff; /* offset of end of region */
5360 int nulonly; /* search for nul bytes only */
5364 struct strlist *list;
5365 struct strlist **lastp;
5368 /* output of current string */
5369 static char *expdest;
5370 /* list of back quote expressions */
5371 static struct nodelist *argbackq;
5372 /* first struct in list of ifs regions */
5373 static struct ifsregion ifsfirst;
5374 /* last struct in list */
5375 static struct ifsregion *ifslastp;
5376 /* holds expanded arg list */
5377 static struct arglist exparg;
5387 expdest = makestrspace(32, expdest);
5388 len = fmtstr(expdest, 32, arith_t_fmt, num);
5389 STADJUST(len, expdest);
5394 esclen(const char *start, const char *p)
5398 while (p > start && (unsigned char)*--p == CTLESC) {
5405 * Remove any CTLESC characters from a string.
5408 rmescapes(char *str, int flag)
5410 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5414 unsigned protect_against_glob;
5417 p = strpbrk(str, qchars);
5423 if (flag & RMESCAPE_ALLOC) {
5424 size_t len = p - str;
5425 size_t fulllen = len + strlen(p) + 1;
5427 if (flag & RMESCAPE_GROW) {
5428 r = makestrspace(fulllen, expdest);
5429 } else if (flag & RMESCAPE_HEAP) {
5430 r = ckmalloc(fulllen);
5432 r = stalloc(fulllen);
5436 q = (char *)memcpy(q, str, len) + len;
5440 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5441 globbing = flag & RMESCAPE_GLOB;
5442 protect_against_glob = globbing;
5444 if ((unsigned char)*p == CTLQUOTEMARK) {
5445 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5446 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5447 // Note: both inquotes and protect_against_glob only affect whether
5448 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5449 inquotes = ~inquotes;
5451 protect_against_glob = globbing;
5455 /* naked back slash */
5456 protect_against_glob = 0;
5459 if ((unsigned char)*p == CTLESC) {
5461 if (protect_against_glob && inquotes && *p != '/') {
5465 protect_against_glob = globbing;
5470 if (flag & RMESCAPE_GROW) {
5472 STADJUST(q - r + 1, expdest);
5476 #define pmatch(a, b) !fnmatch((a), (b), 0)
5479 * Prepare a pattern for a expmeta (internal glob(3)) call.
5481 * Returns an stalloced string.
5484 preglob(const char *pattern, int quoted, int flag)
5486 flag |= RMESCAPE_GLOB;
5488 flag |= RMESCAPE_QUOTED;
5490 return rmescapes((char *)pattern, flag);
5494 * Put a string on the stack.
5497 memtodest(const char *p, size_t len, int syntax, int quotes)
5501 q = makestrspace(quotes ? len * 2 : len, q);
5504 unsigned char c = *p++;
5508 int n = SIT(c, syntax);
5509 if (n == CCTL || n == CBACK)
5519 strtodest(const char *p, int syntax, int quotes)
5521 memtodest(p, strlen(p), syntax, quotes);
5525 * Record the fact that we have to scan this region of the
5526 * string for IFS characters.
5529 recordregion(int start, int end, int nulonly)
5531 struct ifsregion *ifsp;
5533 if (ifslastp == NULL) {
5537 ifsp = ckzalloc(sizeof(*ifsp));
5538 /*ifsp->next = NULL; - ckzalloc did it */
5539 ifslastp->next = ifsp;
5543 ifslastp->begoff = start;
5544 ifslastp->endoff = end;
5545 ifslastp->nulonly = nulonly;
5549 removerecordregions(int endoff)
5551 if (ifslastp == NULL)
5554 if (ifsfirst.endoff > endoff) {
5555 while (ifsfirst.next != NULL) {
5556 struct ifsregion *ifsp;
5558 ifsp = ifsfirst.next->next;
5559 free(ifsfirst.next);
5560 ifsfirst.next = ifsp;
5563 if (ifsfirst.begoff > endoff)
5566 ifslastp = &ifsfirst;
5567 ifsfirst.endoff = endoff;
5572 ifslastp = &ifsfirst;
5573 while (ifslastp->next && ifslastp->next->begoff < endoff)
5574 ifslastp=ifslastp->next;
5575 while (ifslastp->next != NULL) {
5576 struct ifsregion *ifsp;
5578 ifsp = ifslastp->next->next;
5579 free(ifslastp->next);
5580 ifslastp->next = ifsp;
5583 if (ifslastp->endoff > endoff)
5584 ifslastp->endoff = endoff;
5588 exptilde(char *startp, char *p, int flags)
5594 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5599 while ((c = *++p) != '\0') {
5606 if (flags & EXP_VARTILDE)
5616 if (*name == '\0') {
5617 home = lookupvar(homestr);
5619 pw = getpwnam(name);
5624 if (!home || !*home)
5627 startloc = expdest - (char *)stackblock();
5628 strtodest(home, SQSYNTAX, quotes);
5629 recordregion(startloc, expdest - (char *)stackblock(), 0);
5637 * Execute a command inside back quotes. If it's a builtin command, we
5638 * want to save its output in a block obtained from malloc. Otherwise
5639 * we fork off a subprocess and get the output of the command via a pipe.
5640 * Should be called with interrupts off.
5642 struct backcmd { /* result of evalbackcmd */
5643 int fd; /* file descriptor to read from */
5644 int nleft; /* number of chars in buffer */
5645 char *buf; /* buffer */
5646 struct job *jp; /* job structure for command */
5649 /* These forward decls are needed to use "eval" code for backticks handling: */
5650 static uint8_t back_exitstatus; /* exit status of backquoted command */
5651 #define EV_EXIT 01 /* exit after evaluating tree */
5652 static void evaltree(union node *, int);
5654 static void FAST_FUNC
5655 evalbackcmd(union node *n, struct backcmd *result)
5666 saveherefd = herefd;
5674 ash_msg_and_raise_error("pipe call failed");
5675 jp = makejob(/*n,*/ 1);
5676 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5681 copyfd(pip[1], 1 | COPYFD_EXACT);
5685 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5689 result->fd = pip[0];
5692 herefd = saveherefd;
5694 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5695 result->fd, result->buf, result->nleft, result->jp));
5699 * Expand stuff in backwards quotes.
5702 expbackq(union node *cmd, int quoted, int quotes)
5710 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5711 struct stackmark smark;
5714 setstackmark(&smark);
5716 startloc = dest - (char *)stackblock();
5718 evalbackcmd(cmd, &in);
5719 popstackmark(&smark);
5726 memtodest(p, i, syntax, quotes);
5730 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5731 TRACE(("expbackq: read returns %d\n", i));
5740 back_exitstatus = waitforjob(in.jp);
5744 /* Eat all trailing newlines */
5746 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5751 recordregion(startloc, dest - (char *)stackblock(), 0);
5752 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5753 (dest - (char *)stackblock()) - startloc,
5754 (dest - (char *)stackblock()) - startloc,
5755 stackblock() + startloc));
5758 #if ENABLE_SH_MATH_SUPPORT
5760 * Expand arithmetic expression. Backup to start of expression,
5761 * evaluate, place result in (backed up) result, adjust string position.
5774 * This routine is slightly over-complicated for
5775 * efficiency. Next we scan backwards looking for the
5776 * start of arithmetic.
5778 start = stackblock();
5785 while ((unsigned char)*p != CTLARI) {
5789 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5794 esc = esclen(start, p);
5804 removerecordregions(begoff);
5811 rmescapes(p + 2, 0);
5813 len = cvtnum(ash_arith(p + 2));
5816 recordregion(begoff, begoff + len, 0);
5820 /* argstr needs it */
5821 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5824 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5825 * characters to allow for further processing. Otherwise treat
5826 * $@ like $* since no splitting will be performed.
5828 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5829 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5830 * for correct expansion of "B=$A" word.
5833 argstr(char *p, int flags, struct strlist *var_str_list)
5835 static const char spclchars[] ALIGN1 = {
5843 CTLBACKQ | CTLQUOTE,
5844 #if ENABLE_SH_MATH_SUPPORT
5849 const char *reject = spclchars;
5850 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5851 int breakall = flags & EXP_WORD;
5856 if (!(flags & EXP_VARTILDE)) {
5858 } else if (flags & EXP_VARTILDE2) {
5863 if (flags & EXP_TILDE) {
5866 flags &= ~EXP_TILDE;
5869 if (*q == CTLESC && (flags & EXP_QWORD))
5872 p = exptilde(p, q, flags);
5875 startloc = expdest - (char *)stackblock();
5879 length += strcspn(p + length, reject);
5883 #if ENABLE_SH_MATH_SUPPORT
5887 /* c == '=' || c == ':' || c == CTLENDARI */
5893 expdest = stack_nputstr(p, length, expdest);
5894 newloc = expdest - (char *)stackblock();
5895 if (breakall && !inquotes && newloc > startloc) {
5896 recordregion(startloc, newloc, 0);
5907 if (flags & EXP_VARTILDE2) {
5911 flags |= EXP_VARTILDE2;
5916 * sort of a hack - expand tildes in variable
5917 * assignments (after the first '=' and after ':'s).
5926 case CTLENDVAR: /* ??? */
5929 /* "$@" syntax adherence hack */
5931 && memcmp(p, dolatstr, 4) == 0
5932 && ( p[4] == CTLQUOTEMARK
5933 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5936 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
5939 inquotes = !inquotes;
5952 p = evalvar(p, flags, var_str_list);
5956 case CTLBACKQ|CTLQUOTE:
5957 expbackq(argbackq->n, c, quotes);
5958 argbackq = argbackq->next;
5960 #if ENABLE_SH_MATH_SUPPORT
5973 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
5976 // This commented out code was added by James Simmons <jsimmons@infradead.org>
5977 // as part of a larger change when he added support for ${var/a/b}.
5978 // However, it broke # and % operators:
5982 //echo ${var#ab} abcdcd abcdcd
5983 //echo ${var##ab} abcdcd abcdcd
5984 //echo ${var#a*b} abcdcd ababcdcd (!)
5985 //echo ${var##a*b} cdcd cdcd
5986 //echo ${var#?} babcdcd ababcdcd (!)
5987 //echo ${var##?} babcdcd babcdcd
5988 //echo ${var#*} ababcdcd babcdcd (!)
5990 //echo ${var%cd} ababcd ababcd
5991 //echo ${var%%cd} ababcd abab (!)
5992 //echo ${var%c*d} ababcd ababcd
5993 //echo ${var%%c*d} abab ababcdcd (!)
5994 //echo ${var%?} ababcdc ababcdc
5995 //echo ${var%%?} ababcdc ababcdcd (!)
5996 //echo ${var%*} ababcdcd ababcdcd
5999 // Commenting it back out helped. Remove it completely if it really
6002 char *loc, *loc2; //, *full;
6008 int match; // = strlen(str);
6009 const char *s = loc2;
6016 match = pmatch(str, s); // this line was deleted
6018 // // chop off end if its '*'
6019 // full = strrchr(str, '*');
6020 // if (full && full != str)
6023 // // If str starts with '*' replace with s.
6024 // if ((*str == '*') && strlen(s) >= match) {
6025 // full = xstrdup(s);
6026 // strncpy(full+strlen(s)-match+1, str+1, match-1);
6028 // full = xstrndup(str, match);
6029 // match = strncmp(s, full, strlen(full));
6033 if (match) // if (!match)
6035 if (quotes && (unsigned char)*loc == CTLESC)
6044 scanright(char *startp, char *rmesc, char *rmescend, char *pattern, int quotes, int match_at_start)
6046 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6047 int try2optimize = match_at_start;
6053 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6054 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6055 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6057 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6058 * and on each iteration they go back two/one char until they reach the beginning.
6059 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6061 /* TODO: document in what other circumstances we are called. */
6063 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6066 const char *s = loc2;
6067 if (match_at_start) {
6071 match = pmatch(pattern, s);
6072 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6076 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6078 /* Maybe we can optimize this:
6079 * if pattern ends with unescaped *, we can avoid checking
6080 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6081 * it wont match truncated "raw_value_of_" strings too.
6083 unsigned plen = strlen(pattern);
6084 /* Does it end with "*"? */
6085 if (plen != 0 && pattern[--plen] == '*') {
6086 /* "xxxx*" is not escaped */
6087 /* "xxx\*" is escaped */
6088 /* "xx\\*" is not escaped */
6089 /* "x\\\*" is escaped */
6091 while (plen != 0 && pattern[--plen] == '\\')
6094 break; /* ends with unescaped "*" */
6102 esc = esclen(startp, loc);
6113 static void varunset(const char *, const char *, const char *, int) NORETURN;
6115 varunset(const char *end, const char *var, const char *umsg, int varflags)
6121 msg = "parameter not set";
6123 if ((unsigned char)*end == CTLENDVAR) {
6124 if (varflags & VSNUL)
6130 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6133 #if ENABLE_ASH_BASH_COMPAT
6135 parse_sub_pattern(char *arg, int inquotes)
6137 char *idx, *repl = NULL;
6146 /* Only the first '/' seen is our separator */
6153 if (!inquotes && c == '\\' && arg[1] == '\\')
6154 arg++; /* skip both \\, not just first one */
6161 #endif /* ENABLE_ASH_BASH_COMPAT */
6164 subevalvar(char *p, char *str, int strloc, int subtype,
6165 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6167 struct nodelist *saveargbackq = argbackq;
6170 char *rmesc, *rmescend;
6171 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6172 IF_ASH_BASH_COMPAT(char null = '\0';)
6173 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6174 int saveherefd = herefd;
6175 int amount, workloc, resetloc;
6177 char *(*scan)(char*, char*, char*, char*, int, int);
6180 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6182 STPUTC('\0', expdest);
6183 herefd = saveherefd;
6184 argbackq = saveargbackq;
6185 startp = (char *)stackblock() + startloc;
6189 setvar(str, startp, 0);
6190 amount = startp - expdest;
6191 STADJUST(amount, expdest);
6194 #if ENABLE_ASH_BASH_COMPAT
6196 loc = str = stackblock() + strloc;
6197 /* Read POS in ${var:POS:LEN} */
6198 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6199 len = str - startp - 1;
6201 /* *loc != '\0', guaranteed by parser */
6205 /* Adjust the length by the number of escapes */
6206 for (ptr = startp; ptr < (str - 1); ptr++) {
6207 if ((unsigned char)*ptr == CTLESC) {
6215 if (*loc++ == ':') {
6219 /* Skip POS in ${var:POS:LEN} */
6221 while (*loc && *loc != ':') {
6223 * bash complains on: var=qwe; echo ${var:1a:123}
6225 ash_msg_and_raise_error(msg_illnum, str);
6229 if (*loc++ == ':') {
6233 if (pos >= orig_len) {
6237 if (len > (orig_len - pos))
6238 len = orig_len - pos;
6240 for (str = startp; pos; str++, pos--) {
6241 if (quotes && (unsigned char)*str == CTLESC)
6244 for (loc = startp; len; len--) {
6245 if (quotes && (unsigned char)*str == CTLESC)
6250 amount = loc - expdest;
6251 STADJUST(amount, expdest);
6256 varunset(p, str, startp, varflags);
6259 resetloc = expdest - (char *)stackblock();
6261 /* We'll comeback here if we grow the stack while handling
6262 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6263 * stack will need rebasing, and we'll need to remove our work
6266 IF_ASH_BASH_COMPAT(restart:)
6268 amount = expdest - ((char *)stackblock() + resetloc);
6269 STADJUST(-amount, expdest);
6270 startp = (char *)stackblock() + startloc;
6273 rmescend = (char *)stackblock() + strloc;
6275 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6276 if (rmesc != startp) {
6278 startp = (char *)stackblock() + startloc;
6282 str = (char *)stackblock() + strloc;
6283 preglob(str, varflags & VSQUOTE, 0);
6284 workloc = expdest - (char *)stackblock();
6286 #if ENABLE_ASH_BASH_COMPAT
6287 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6291 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6296 /* If there's no pattern to match, return the expansion unmolested */
6305 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6307 /* No match, advance */
6308 char *restart_detect = stackblock();
6310 STPUTC(*idx, expdest);
6311 if (quotes && (unsigned char)*idx == CTLESC) {
6314 STPUTC(*idx, expdest);
6316 if (stackblock() != restart_detect)
6321 /* continue; - prone to quadratic behavior, smarter code: */
6324 if (str[0] == '*') {
6325 /* Pattern is "*foo". If "*foo" does not match "long_string",
6326 * it would never match "ong_string" etc, no point in trying.
6333 if (subtype == VSREPLACEALL) {
6335 if (quotes && (unsigned char)*idx == CTLESC)
6344 for (loc = repl; *loc; loc++) {
6345 char *restart_detect = stackblock();
6346 STPUTC(*loc, expdest);
6347 if (stackblock() != restart_detect)
6352 if (subtype == VSREPLACE) {
6354 char *restart_detect = stackblock();
6355 STPUTC(*idx, expdest);
6356 if (stackblock() != restart_detect)
6365 /* We've put the replaced text into a buffer at workloc, now
6366 * move it to the right place and adjust the stack.
6368 startp = stackblock() + startloc;
6369 STPUTC('\0', expdest);
6370 memmove(startp, stackblock() + workloc, len);
6371 startp[len++] = '\0';
6372 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6373 STADJUST(-amount, expdest);
6376 #endif /* ENABLE_ASH_BASH_COMPAT */
6378 subtype -= VSTRIMRIGHT;
6380 if (subtype < 0 || subtype > 7)
6383 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6384 zero = subtype >> 1;
6385 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6386 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6388 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6391 memmove(startp, loc, str - loc);
6392 loc = startp + (str - loc) - 1;
6395 amount = loc - expdest;
6396 STADJUST(amount, expdest);
6402 * Add the value of a specialized variable to the stack string.
6403 * name parameter (examples):
6404 * ash -c 'echo $1' name:'1='
6405 * ash -c 'echo $qwe' name:'qwe='
6406 * ash -c 'echo $$' name:'$='
6407 * ash -c 'echo ${$}' name:'$='
6408 * ash -c 'echo ${$##q}' name:'$=q'
6409 * ash -c 'echo ${#$}' name:'$='
6410 * note: examples with bad shell syntax:
6411 * ash -c 'echo ${#$1}' name:'$=1'
6412 * ash -c 'echo ${#1#}' name:'1=#'
6414 static NOINLINE ssize_t
6415 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6422 int subtype = varflags & VSTYPE;
6423 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6424 int quoted = varflags & VSQUOTE;
6425 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6435 num = shellparam.nparam;
6443 goto check_1char_name;
6445 expdest = makestrspace(NOPTS, expdest);
6446 for (i = NOPTS - 1; i >= 0; i--) {
6448 USTPUTC(optletters(i), expdest);
6454 /* handles cases similar to ${#$1} */
6455 if (name[2] != '\0')
6456 raise_error_syntax("bad substitution");
6463 if (quoted && (flags & EXP_FULL)) {
6464 /* note: this is not meant as PEOF value */
6465 sep = 1 << CHAR_BIT;
6470 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6471 i = SIT(sep, syntax);
6472 if (quotes && (i == CCTL || i == CBACK))
6478 while ((p = *ap++) != NULL) {
6481 partlen = strlen(p);
6484 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6485 memtodest(p, partlen, syntax, quotes);
6491 if (subtype == VSPLUS || subtype == VSLENGTH) {
6497 /* note: may put NUL despite sep != 0
6498 * (see sep = 1 << CHAR_BIT above) */
6504 } /* case '@' and '*' */
6515 num = atoi(name); /* number(name) fails on ${N#str} etc */
6516 if (num < 0 || num > shellparam.nparam)
6518 p = num ? shellparam.p[num - 1] : arg0;
6521 /* NB: name has form "VAR=..." */
6523 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6524 * which should be considered before we check variables. */
6526 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6530 str = var_str_list->text;
6531 eq = strchr(str, '=');
6532 if (!eq) /* stop at first non-assignment */
6535 if (name_len == (unsigned)(eq - str)
6536 && strncmp(str, name, name_len) == 0
6539 /* goto value; - WRONG! */
6540 /* think "A=1 A=2 B=$A" */
6542 var_str_list = var_str_list->next;
6543 } while (var_str_list);
6547 p = lookupvar(name);
6553 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6554 memtodest(p, len, syntax, quotes);
6558 if (subtype == VSPLUS || subtype == VSLENGTH)
6559 STADJUST(-len, expdest);
6564 * Expand a variable, and return a pointer to the next character in the
6568 evalvar(char *p, int flags, struct strlist *var_str_list)
6579 varflags = (unsigned char) *p++;
6580 subtype = varflags & VSTYPE;
6581 quoted = varflags & VSQUOTE;
6583 easy = (!quoted || (*var == '@' && shellparam.nparam));
6584 startloc = expdest - (char *)stackblock();
6585 p = strchr(p, '=') + 1;
6588 varlen = varvalue(var, varflags, flags, var_str_list);
6589 if (varflags & VSNUL)
6592 if (subtype == VSPLUS) {
6593 varlen = -1 - varlen;
6597 if (subtype == VSMINUS) {
6601 p, flags | EXP_TILDE |
6602 (quoted ? EXP_QWORD : EXP_WORD),
6612 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6614 if (subevalvar(p, var, /* strloc: */ 0,
6615 subtype, startloc, varflags,
6621 * Remove any recorded regions beyond
6624 removerecordregions(startloc);
6634 if (varlen < 0 && uflag)
6635 varunset(p, var, 0, 0);
6637 if (subtype == VSLENGTH) {
6638 cvtnum(varlen > 0 ? varlen : 0);
6642 if (subtype == VSNORMAL) {
6653 case VSTRIMRIGHTMAX:
6654 #if ENABLE_ASH_BASH_COMPAT
6667 * Terminate the string and start recording the pattern
6670 STPUTC('\0', expdest);
6671 patloc = expdest - (char *)stackblock();
6672 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6674 //TODO: | EXP_REDIR too? All other such places do it too
6675 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6678 int amount = expdest - (
6679 (char *)stackblock() + patloc - 1
6681 STADJUST(-amount, expdest);
6683 /* Remove any recorded regions beyond start of variable */
6684 removerecordregions(startloc);
6686 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6690 if (subtype != VSNORMAL) { /* skip to end of alternative */
6693 unsigned char c = *p++;
6696 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6698 argbackq = argbackq->next;
6699 } else if (c == CTLVAR) {
6700 if ((*p++ & VSTYPE) != VSNORMAL)
6702 } else if (c == CTLENDVAR) {
6712 * Break the argument string into pieces based upon IFS and add the
6713 * strings to the argument list. The regions of the string to be
6714 * searched for IFS characters have been stored by recordregion.
6717 ifsbreakup(char *string, struct arglist *arglist)
6719 struct ifsregion *ifsp;
6724 const char *ifs, *realifs;
6729 if (ifslastp != NULL) {
6732 realifs = ifsset() ? ifsval() : defifs;
6735 p = string + ifsp->begoff;
6736 nulonly = ifsp->nulonly;
6737 ifs = nulonly ? nullstr : realifs;
6739 while (p < string + ifsp->endoff) {
6741 if ((unsigned char)*p == CTLESC)
6743 if (!strchr(ifs, *p)) {
6748 ifsspc = (strchr(defifs, *p) != NULL);
6749 /* Ignore IFS whitespace at start */
6750 if (q == start && ifsspc) {
6756 sp = stzalloc(sizeof(*sp));
6758 *arglist->lastp = sp;
6759 arglist->lastp = &sp->next;
6763 if (p >= string + ifsp->endoff) {
6767 if ((unsigned char)*p == CTLESC)
6769 if (strchr(ifs, *p) == NULL) {
6773 if (strchr(defifs, *p) == NULL) {
6788 } while (ifsp != NULL);
6797 sp = stzalloc(sizeof(*sp));
6799 *arglist->lastp = sp;
6800 arglist->lastp = &sp->next;
6806 struct ifsregion *p;
6811 struct ifsregion *ifsp;
6817 ifsfirst.next = NULL;
6822 * Add a file name to the list.
6825 addfname(const char *name)
6829 sp = stzalloc(sizeof(*sp));
6830 sp->text = ststrdup(name);
6832 exparg.lastp = &sp->next;
6835 static char *expdir;
6838 * Do metacharacter (i.e. *, ?, [...]) expansion.
6841 expmeta(char *enddir, char *name)
6856 for (p = name; *p; p++) {
6857 if (*p == '*' || *p == '?')
6859 else if (*p == '[') {
6866 if (*q == '/' || *q == '\0')
6873 } else if (*p == '\\')
6875 else if (*p == '/') {
6882 if (metaflag == 0) { /* we've reached the end of the file name */
6883 if (enddir != expdir)
6891 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6902 } while (p < start);
6904 if (enddir == expdir) {
6906 } else if (enddir == expdir + 1 && *expdir == '/') {
6915 if (enddir != expdir)
6917 if (*endname == 0) {
6929 while (!pending_int && (dp = readdir(dirp)) != NULL) {
6930 if (dp->d_name[0] == '.' && !matchdot)
6932 if (pmatch(start, dp->d_name)) {
6934 strcpy(enddir, dp->d_name);
6937 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6940 expmeta(p, endname);
6949 static struct strlist *
6950 msort(struct strlist *list, int len)
6952 struct strlist *p, *q = NULL;
6953 struct strlist **lpp;
6961 for (n = half; --n >= 0;) {
6965 q->next = NULL; /* terminate first half of list */
6966 q = msort(list, half); /* sort first half of list */
6967 p = msort(p, len - half); /* sort second half */
6970 #if ENABLE_LOCALE_SUPPORT
6971 if (strcoll(p->text, q->text) < 0)
6973 if (strcmp(p->text, q->text) < 0)
6997 * Sort the results of file name expansion. It calculates the number of
6998 * strings to sort and then calls msort (short for merge sort) to do the
7001 static struct strlist *
7002 expsort(struct strlist *str)
7008 for (sp = str; sp; sp = sp->next)
7010 return msort(str, len);
7014 expandmeta(struct strlist *str /*, int flag*/)
7016 static const char metachars[] ALIGN1 = {
7019 /* TODO - EXP_REDIR */
7022 struct strlist **savelastp;
7028 if (!strpbrk(str->text, metachars))
7030 savelastp = exparg.lastp;
7033 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7035 int i = strlen(str->text);
7036 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7044 if (exparg.lastp == savelastp) {
7049 *exparg.lastp = str;
7050 rmescapes(str->text, 0);
7051 exparg.lastp = &str->next;
7053 *exparg.lastp = NULL;
7054 *savelastp = sp = expsort(*savelastp);
7055 while (sp->next != NULL)
7057 exparg.lastp = &sp->next;
7064 * Perform variable substitution and command substitution on an argument,
7065 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7066 * perform splitting and file name expansion. When arglist is NULL, perform
7067 * here document expansion.
7070 expandarg(union node *arg, struct arglist *arglist, int flag)
7075 argbackq = arg->narg.backquote;
7076 STARTSTACKSTR(expdest);
7077 ifsfirst.next = NULL;
7079 argstr(arg->narg.text, flag,
7080 /* var_str_list: */ arglist ? arglist->list : NULL);
7081 p = _STPUTC('\0', expdest);
7083 if (arglist == NULL) {
7084 return; /* here document expanded */
7086 p = grabstackstr(p);
7087 exparg.lastp = &exparg.list;
7091 if (flag & EXP_FULL) {
7092 ifsbreakup(p, &exparg);
7093 *exparg.lastp = NULL;
7094 exparg.lastp = &exparg.list;
7095 expandmeta(exparg.list /*, flag*/);
7097 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7099 sp = stzalloc(sizeof(*sp));
7102 exparg.lastp = &sp->next;
7106 *exparg.lastp = NULL;
7108 *arglist->lastp = exparg.list;
7109 arglist->lastp = exparg.lastp;
7114 * Expand shell variables and backquotes inside a here document.
7117 expandhere(union node *arg, int fd)
7120 expandarg(arg, (struct arglist *)NULL, 0);
7121 full_write(fd, stackblock(), expdest - (char *)stackblock());
7125 * Returns true if the pattern matches the string.
7128 patmatch(char *pattern, const char *string)
7130 return pmatch(preglob(pattern, 0, 0), string);
7134 * See if a pattern matches in a case statement.
7137 casematch(union node *pattern, char *val)
7139 struct stackmark smark;
7142 setstackmark(&smark);
7143 argbackq = pattern->narg.backquote;
7144 STARTSTACKSTR(expdest);
7146 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7147 /* var_str_list: */ NULL);
7148 STACKSTRNUL(expdest);
7149 result = patmatch(stackblock(), val);
7150 popstackmark(&smark);
7155 /* ============ find_command */
7159 int (*builtin)(int, char **) FAST_FUNC;
7160 /* unsigned flags; */
7162 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7163 /* "regular" builtins always take precedence over commands,
7164 * regardless of PATH=....%builtin... position */
7165 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7166 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7169 smallint cmdtype; /* CMDxxx */
7172 /* index >= 0 for commands without path (slashes) */
7173 /* (TODO: what exactly does the value mean? PATH position?) */
7174 /* index == -1 for commands with slashes */
7175 /* index == (-2 - applet_no) for NOFORK applets */
7176 const struct builtincmd *cmd;
7177 struct funcnode *func;
7180 /* values of cmdtype */
7181 #define CMDUNKNOWN -1 /* no entry in table for command */
7182 #define CMDNORMAL 0 /* command is an executable program */
7183 #define CMDFUNCTION 1 /* command is a shell function */
7184 #define CMDBUILTIN 2 /* command is a shell builtin */
7186 /* action to find_command() */
7187 #define DO_ERR 0x01 /* prints errors */
7188 #define DO_ABS 0x02 /* checks absolute paths */
7189 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7190 #define DO_ALTPATH 0x08 /* using alternate path */
7191 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7193 static void find_command(char *, struct cmdentry *, int, const char *);
7196 /* ============ Hashing commands */
7199 * When commands are first encountered, they are entered in a hash table.
7200 * This ensures that a full path search will not have to be done for them
7201 * on each invocation.
7203 * We should investigate converting to a linear search, even though that
7204 * would make the command name "hash" a misnomer.
7208 struct tblentry *next; /* next entry in hash chain */
7209 union param param; /* definition of builtin function */
7210 smallint cmdtype; /* CMDxxx */
7211 char rehash; /* if set, cd done since entry created */
7212 char cmdname[1]; /* name of command */
7215 static struct tblentry **cmdtable;
7216 #define INIT_G_cmdtable() do { \
7217 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7220 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7224 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7228 #if ENABLE_FEATURE_SH_STANDALONE
7229 if (applet_no >= 0) {
7230 if (APPLET_IS_NOEXEC(applet_no)) {
7233 run_applet_no_and_exit(applet_no, argv);
7235 /* re-exec ourselves with the new arguments */
7236 execve(bb_busybox_exec_path, argv, envp);
7237 /* If they called chroot or otherwise made the binary no longer
7238 * executable, fall through */
7245 execve(cmd, argv, envp);
7246 } while (errno == EINTR);
7248 execve(cmd, argv, envp);
7254 if (errno == ENOEXEC) {
7258 for (ap = argv; *ap; ap++)
7260 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7262 ap[0] = cmd = (char *)DEFAULT_SHELL;
7265 while ((*ap++ = *argv++) != NULL)
7274 * Exec a program. Never returns. If you change this routine, you may
7275 * have to change the find_command routine as well.
7277 static void shellexec(char **, const char *, int) NORETURN;
7279 shellexec(char **argv, const char *path, int idx)
7285 #if ENABLE_FEATURE_SH_STANDALONE
7289 clearredir(/*drop:*/ 1);
7290 envp = listvars(VEXPORT, VUNSET, 0);
7291 if (strchr(argv[0], '/') != NULL
7292 #if ENABLE_FEATURE_SH_STANDALONE
7293 || (applet_no = find_applet_by_name(argv[0])) >= 0
7296 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7300 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7301 if (--idx < 0 && pathopt == NULL) {
7302 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7303 if (errno != ENOENT && errno != ENOTDIR)
7310 /* Map to POSIX errors */
7322 exitstatus = exerrno;
7323 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7324 argv[0], e, suppress_int));
7325 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7330 printentry(struct tblentry *cmdp)
7336 idx = cmdp->param.index;
7339 name = path_advance(&path, cmdp->cmdname);
7341 } while (--idx >= 0);
7342 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7346 * Clear out command entries. The argument specifies the first entry in
7347 * PATH which has changed.
7350 clearcmdentry(int firstchange)
7352 struct tblentry **tblp;
7353 struct tblentry **pp;
7354 struct tblentry *cmdp;
7357 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7359 while ((cmdp = *pp) != NULL) {
7360 if ((cmdp->cmdtype == CMDNORMAL &&
7361 cmdp->param.index >= firstchange)
7362 || (cmdp->cmdtype == CMDBUILTIN &&
7363 builtinloc >= firstchange)
7376 * Locate a command in the command hash table. If "add" is nonzero,
7377 * add the command to the table if it is not already present. The
7378 * variable "lastcmdentry" is set to point to the address of the link
7379 * pointing to the entry, so that delete_cmd_entry can delete the
7382 * Interrupts must be off if called with add != 0.
7384 static struct tblentry **lastcmdentry;
7386 static struct tblentry *
7387 cmdlookup(const char *name, int add)
7389 unsigned int hashval;
7391 struct tblentry *cmdp;
7392 struct tblentry **pp;
7395 hashval = (unsigned char)*p << 4;
7397 hashval += (unsigned char)*p++;
7399 pp = &cmdtable[hashval % CMDTABLESIZE];
7400 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7401 if (strcmp(cmdp->cmdname, name) == 0)
7405 if (add && cmdp == NULL) {
7406 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7408 /* + 1 - already done because
7409 * tblentry::cmdname is char[1] */);
7410 /*cmdp->next = NULL; - ckzalloc did it */
7411 cmdp->cmdtype = CMDUNKNOWN;
7412 strcpy(cmdp->cmdname, name);
7419 * Delete the command entry returned on the last lookup.
7422 delete_cmd_entry(void)
7424 struct tblentry *cmdp;
7427 cmdp = *lastcmdentry;
7428 *lastcmdentry = cmdp->next;
7429 if (cmdp->cmdtype == CMDFUNCTION)
7430 freefunc(cmdp->param.func);
7436 * Add a new command entry, replacing any existing command entry for
7437 * the same name - except special builtins.
7440 addcmdentry(char *name, struct cmdentry *entry)
7442 struct tblentry *cmdp;
7444 cmdp = cmdlookup(name, 1);
7445 if (cmdp->cmdtype == CMDFUNCTION) {
7446 freefunc(cmdp->param.func);
7448 cmdp->cmdtype = entry->cmdtype;
7449 cmdp->param = entry->u;
7453 static int FAST_FUNC
7454 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7456 struct tblentry **pp;
7457 struct tblentry *cmdp;
7459 struct cmdentry entry;
7462 if (nextopt("r") != '\0') {
7467 if (*argptr == NULL) {
7468 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7469 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7470 if (cmdp->cmdtype == CMDNORMAL)
7478 while ((name = *argptr) != NULL) {
7479 cmdp = cmdlookup(name, 0);
7481 && (cmdp->cmdtype == CMDNORMAL
7482 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7486 find_command(name, &entry, DO_ERR, pathval());
7487 if (entry.cmdtype == CMDUNKNOWN)
7495 * Called when a cd is done. Marks all commands so the next time they
7496 * are executed they will be rehashed.
7501 struct tblentry **pp;
7502 struct tblentry *cmdp;
7504 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7505 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7506 if (cmdp->cmdtype == CMDNORMAL
7507 || (cmdp->cmdtype == CMDBUILTIN
7508 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7518 * Fix command hash table when PATH changed.
7519 * Called before PATH is changed. The argument is the new value of PATH;
7520 * pathval() still returns the old value at this point.
7521 * Called with interrupts off.
7523 static void FAST_FUNC
7524 changepath(const char *new)
7532 firstchange = 9999; /* assume no change */
7538 if ((*old == '\0' && *new == ':')
7539 || (*old == ':' && *new == '\0'))
7541 old = new; /* ignore subsequent differences */
7545 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7551 if (builtinloc < 0 && idx_bltin >= 0)
7552 builtinloc = idx_bltin; /* zap builtins */
7553 if (builtinloc >= 0 && idx_bltin < 0)
7555 clearcmdentry(firstchange);
7556 builtinloc = idx_bltin;
7571 #define TENDBQUOTE 12
7588 typedef smallint token_id_t;
7590 /* first char is indicating which tokens mark the end of a list */
7591 static const char *const tokname_array[] = {
7605 #define KWDOFFSET 13
7606 /* the following are keywords */
7628 static char buf[16];
7631 //if (tok < TSEMI) return tokname_array[tok] + 1;
7632 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7637 sprintf(buf + (tok >= TSEMI), "%s%c",
7638 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7642 /* Wrapper around strcmp for qsort/bsearch/... */
7644 pstrcmp(const void *a, const void *b)
7646 return strcmp((char*) a, (*(char**) b) + 1);
7649 static const char *const *
7650 findkwd(const char *s)
7652 return bsearch(s, tokname_array + KWDOFFSET,
7653 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7654 sizeof(tokname_array[0]), pstrcmp);
7658 * Locate and print what a word is...
7661 describe_command(char *command, int describe_command_verbose)
7663 struct cmdentry entry;
7664 struct tblentry *cmdp;
7665 #if ENABLE_ASH_ALIAS
7666 const struct alias *ap;
7668 const char *path = pathval();
7670 if (describe_command_verbose) {
7674 /* First look at the keywords */
7675 if (findkwd(command)) {
7676 out1str(describe_command_verbose ? " is a shell keyword" : command);
7680 #if ENABLE_ASH_ALIAS
7681 /* Then look at the aliases */
7682 ap = lookupalias(command, 0);
7684 if (!describe_command_verbose) {
7689 out1fmt(" is an alias for %s", ap->val);
7693 /* Then check if it is a tracked alias */
7694 cmdp = cmdlookup(command, 0);
7696 entry.cmdtype = cmdp->cmdtype;
7697 entry.u = cmdp->param;
7699 /* Finally use brute force */
7700 find_command(command, &entry, DO_ABS, path);
7703 switch (entry.cmdtype) {
7705 int j = entry.u.index;
7711 p = path_advance(&path, command);
7715 if (describe_command_verbose) {
7717 (cmdp ? " a tracked alias for" : nullstr), p
7726 if (describe_command_verbose) {
7727 out1str(" is a shell function");
7734 if (describe_command_verbose) {
7735 out1fmt(" is a %sshell builtin",
7736 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7737 "special " : nullstr
7745 if (describe_command_verbose) {
7746 out1str(": not found\n");
7755 static int FAST_FUNC
7756 typecmd(int argc UNUSED_PARAM, char **argv)
7762 /* type -p ... ? (we don't bother checking for 'p') */
7763 if (argv[1] && argv[1][0] == '-') {
7768 err |= describe_command(argv[i++], verbose);
7773 #if ENABLE_ASH_CMDCMD
7774 static int FAST_FUNC
7775 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7783 while ((c = nextopt("pvV")) != '\0')
7785 verify |= VERIFY_VERBOSE;
7787 verify |= VERIFY_BRIEF;
7792 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7793 if (verify && (*argptr != NULL)) {
7794 return describe_command(*argptr, verify - VERIFY_BRIEF);
7802 /* ============ eval.c */
7804 static int funcblocksize; /* size of structures in function */
7805 static int funcstringsize; /* size of strings in node */
7806 static void *funcblock; /* block to allocate function from */
7807 static char *funcstring; /* block to allocate strings from */
7809 /* flags in argument to evaltree */
7810 #define EV_EXIT 01 /* exit after evaluating tree */
7811 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7812 #define EV_BACKCMD 04 /* command executing within back quotes */
7814 static const uint8_t nodesize[N_NUMBER] = {
7815 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7816 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7817 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7818 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7819 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7820 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7821 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7822 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7823 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7824 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7825 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7826 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7827 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7828 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7829 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7830 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7831 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7832 #if ENABLE_ASH_BASH_COMPAT
7833 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7835 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7836 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7837 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7838 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7839 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7840 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7841 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7842 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7843 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7846 static void calcsize(union node *n);
7849 sizenodelist(struct nodelist *lp)
7852 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7859 calcsize(union node *n)
7863 funcblocksize += nodesize[n->type];
7866 calcsize(n->ncmd.redirect);
7867 calcsize(n->ncmd.args);
7868 calcsize(n->ncmd.assign);
7871 sizenodelist(n->npipe.cmdlist);
7876 calcsize(n->nredir.redirect);
7877 calcsize(n->nredir.n);
7884 calcsize(n->nbinary.ch2);
7885 calcsize(n->nbinary.ch1);
7888 calcsize(n->nif.elsepart);
7889 calcsize(n->nif.ifpart);
7890 calcsize(n->nif.test);
7893 funcstringsize += strlen(n->nfor.var) + 1;
7894 calcsize(n->nfor.body);
7895 calcsize(n->nfor.args);
7898 calcsize(n->ncase.cases);
7899 calcsize(n->ncase.expr);
7902 calcsize(n->nclist.body);
7903 calcsize(n->nclist.pattern);
7904 calcsize(n->nclist.next);
7908 sizenodelist(n->narg.backquote);
7909 funcstringsize += strlen(n->narg.text) + 1;
7910 calcsize(n->narg.next);
7913 #if ENABLE_ASH_BASH_COMPAT
7920 calcsize(n->nfile.fname);
7921 calcsize(n->nfile.next);
7925 calcsize(n->ndup.vname);
7926 calcsize(n->ndup.next);
7930 calcsize(n->nhere.doc);
7931 calcsize(n->nhere.next);
7934 calcsize(n->nnot.com);
7940 nodeckstrdup(char *s)
7942 char *rtn = funcstring;
7944 strcpy(funcstring, s);
7945 funcstring += strlen(s) + 1;
7949 static union node *copynode(union node *);
7951 static struct nodelist *
7952 copynodelist(struct nodelist *lp)
7954 struct nodelist *start;
7955 struct nodelist **lpp;
7960 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7961 (*lpp)->n = copynode(lp->n);
7963 lpp = &(*lpp)->next;
7970 copynode(union node *n)
7977 funcblock = (char *) funcblock + nodesize[n->type];
7981 new->ncmd.redirect = copynode(n->ncmd.redirect);
7982 new->ncmd.args = copynode(n->ncmd.args);
7983 new->ncmd.assign = copynode(n->ncmd.assign);
7986 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7987 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
7992 new->nredir.redirect = copynode(n->nredir.redirect);
7993 new->nredir.n = copynode(n->nredir.n);
8000 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8001 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8004 new->nif.elsepart = copynode(n->nif.elsepart);
8005 new->nif.ifpart = copynode(n->nif.ifpart);
8006 new->nif.test = copynode(n->nif.test);
8009 new->nfor.var = nodeckstrdup(n->nfor.var);
8010 new->nfor.body = copynode(n->nfor.body);
8011 new->nfor.args = copynode(n->nfor.args);
8014 new->ncase.cases = copynode(n->ncase.cases);
8015 new->ncase.expr = copynode(n->ncase.expr);
8018 new->nclist.body = copynode(n->nclist.body);
8019 new->nclist.pattern = copynode(n->nclist.pattern);
8020 new->nclist.next = copynode(n->nclist.next);
8024 new->narg.backquote = copynodelist(n->narg.backquote);
8025 new->narg.text = nodeckstrdup(n->narg.text);
8026 new->narg.next = copynode(n->narg.next);
8029 #if ENABLE_ASH_BASH_COMPAT
8036 new->nfile.fname = copynode(n->nfile.fname);
8037 new->nfile.fd = n->nfile.fd;
8038 new->nfile.next = copynode(n->nfile.next);
8042 new->ndup.vname = copynode(n->ndup.vname);
8043 new->ndup.dupfd = n->ndup.dupfd;
8044 new->ndup.fd = n->ndup.fd;
8045 new->ndup.next = copynode(n->ndup.next);
8049 new->nhere.doc = copynode(n->nhere.doc);
8050 new->nhere.fd = n->nhere.fd;
8051 new->nhere.next = copynode(n->nhere.next);
8054 new->nnot.com = copynode(n->nnot.com);
8057 new->type = n->type;
8062 * Make a copy of a parse tree.
8064 static struct funcnode *
8065 copyfunc(union node *n)
8070 funcblocksize = offsetof(struct funcnode, n);
8073 blocksize = funcblocksize;
8074 f = ckmalloc(blocksize + funcstringsize);
8075 funcblock = (char *) f + offsetof(struct funcnode, n);
8076 funcstring = (char *) f + blocksize;
8083 * Define a shell function.
8086 defun(char *name, union node *func)
8088 struct cmdentry entry;
8091 entry.cmdtype = CMDFUNCTION;
8092 entry.u.func = copyfunc(func);
8093 addcmdentry(name, &entry);
8097 /* Reasons for skipping commands (see comment on breakcmd routine) */
8098 #define SKIPBREAK (1 << 0)
8099 #define SKIPCONT (1 << 1)
8100 #define SKIPFUNC (1 << 2)
8101 #define SKIPFILE (1 << 3)
8102 #define SKIPEVAL (1 << 4)
8103 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8104 static int skipcount; /* number of levels to skip */
8105 static int funcnest; /* depth of function calls */
8106 static int loopnest; /* current loop nesting level */
8108 /* Forward decl way out to parsing code - dotrap needs it */
8109 static int evalstring(char *s, int mask);
8111 /* Called to execute a trap.
8112 * Single callsite - at the end of evaltree().
8113 * If we return non-zero, exaltree raises EXEXIT exception.
8115 * Perhaps we should avoid entering new trap handlers
8116 * while we are executing a trap handler. [is it a TODO?]
8125 savestatus = exitstatus;
8129 TRACE(("dotrap entered\n"));
8130 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8137 /* non-trapped SIGINT is handled separately by raise_interrupt,
8138 * don't upset it by resetting gotsig[SIGINT-1] */
8139 if (sig == SIGINT && !t)
8142 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8146 want_exexit = evalstring(t, SKIPEVAL);
8147 exitstatus = savestatus;
8149 TRACE(("dotrap returns %d\n", want_exexit));
8154 TRACE(("dotrap returns 0\n"));
8158 /* forward declarations - evaluation is fairly recursive business... */
8159 static void evalloop(union node *, int);
8160 static void evalfor(union node *, int);
8161 static void evalcase(union node *, int);
8162 static void evalsubshell(union node *, int);
8163 static void expredir(union node *);
8164 static void evalpipe(union node *, int);
8165 static void evalcommand(union node *, int);
8166 static int evalbltin(const struct builtincmd *, int, char **);
8167 static void prehash(union node *);
8170 * Evaluate a parse tree. The value is left in the global variable
8174 evaltree(union node *n, int flags)
8176 struct jmploc *volatile savehandler = exception_handler;
8177 struct jmploc jmploc;
8179 void (*evalfn)(union node *, int);
8183 SAVE_INT(int_level);
8186 TRACE(("evaltree(NULL) called\n"));
8189 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8191 exception_handler = &jmploc;
8193 int err = setjmp(jmploc.loc);
8195 /* if it was a signal, check for trap handlers */
8196 if (exception_type == EXSIG) {
8197 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8198 exception_type, err));
8201 /* continue on the way out */
8202 TRACE(("exception %d in evaltree, propagating err=%d\n",
8203 exception_type, err));
8204 exception_handler = savehandler;
8205 longjmp(exception_handler->loc, err);
8212 out1fmt("Node type = %d\n", n->type);
8217 evaltree(n->nnot.com, EV_TESTED);
8218 status = !exitstatus;
8221 expredir(n->nredir.redirect);
8222 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8224 evaltree(n->nredir.n, flags & EV_TESTED);
8225 status = exitstatus;
8227 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8230 evalfn = evalcommand;
8232 if (eflag && !(flags & EV_TESTED))
8244 evalfn = evalsubshell;
8257 #error NAND + 1 != NOR
8259 #if NOR + 1 != NSEMI
8260 #error NOR + 1 != NSEMI
8262 unsigned is_or = n->type - NAND;
8265 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8267 if (!exitstatus == is_or)
8280 evaltree(n->nif.test, EV_TESTED);
8283 if (exitstatus == 0) {
8287 if (n->nif.elsepart) {
8288 n = n->nif.elsepart;
8293 defun(n->narg.text, n->narg.next);
8297 exitstatus = status;
8302 exception_handler = savehandler;
8304 if (checkexit & exitstatus)
8305 evalskip |= SKIPEVAL;
8306 else if (pending_sig && dotrap())
8309 if (flags & EV_EXIT) {
8311 raise_exception(EXEXIT);
8314 RESTORE_INT(int_level);
8315 TRACE(("leaving evaltree (no interrupts)\n"));
8318 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8321 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8324 evalloop(union node *n, int flags)
8334 evaltree(n->nbinary.ch1, EV_TESTED);
8337 if (evalskip == SKIPCONT && --skipcount <= 0) {
8341 if (evalskip == SKIPBREAK && --skipcount <= 0)
8346 if (n->type != NWHILE)
8350 evaltree(n->nbinary.ch2, flags);
8351 status = exitstatus;
8356 exitstatus = status;
8360 evalfor(union node *n, int flags)
8362 struct arglist arglist;
8365 struct stackmark smark;
8367 setstackmark(&smark);
8368 arglist.list = NULL;
8369 arglist.lastp = &arglist.list;
8370 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8371 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8376 *arglist.lastp = NULL;
8381 for (sp = arglist.list; sp; sp = sp->next) {
8382 setvar(n->nfor.var, sp->text, 0);
8383 evaltree(n->nfor.body, flags);
8385 if (evalskip == SKIPCONT && --skipcount <= 0) {
8389 if (evalskip == SKIPBREAK && --skipcount <= 0)
8396 popstackmark(&smark);
8400 evalcase(union node *n, int flags)
8404 struct arglist arglist;
8405 struct stackmark smark;
8407 setstackmark(&smark);
8408 arglist.list = NULL;
8409 arglist.lastp = &arglist.list;
8410 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8412 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8413 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8414 if (casematch(patp, arglist.list->text)) {
8415 if (evalskip == 0) {
8416 evaltree(cp->nclist.body, flags);
8423 popstackmark(&smark);
8427 * Kick off a subshell to evaluate a tree.
8430 evalsubshell(union node *n, int flags)
8433 int backgnd = (n->type == NBACKGND);
8436 expredir(n->nredir.redirect);
8437 if (!backgnd && flags & EV_EXIT && !trap[0])
8440 jp = makejob(/*n,*/ 1);
8441 if (forkshell(jp, n, backgnd) == 0) {
8445 flags &=~ EV_TESTED;
8447 redirect(n->nredir.redirect, 0);
8448 evaltreenr(n->nredir.n, flags);
8453 status = waitforjob(jp);
8454 exitstatus = status;
8459 * Compute the names of the files in a redirection list.
8461 static void fixredir(union node *, const char *, int);
8463 expredir(union node *n)
8467 for (redir = n; redir; redir = redir->nfile.next) {
8471 fn.lastp = &fn.list;
8472 switch (redir->type) {
8476 #if ENABLE_ASH_BASH_COMPAT
8481 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8482 #if ENABLE_ASH_BASH_COMPAT
8485 redir->nfile.expfname = fn.list->text;
8488 case NTOFD: /* >& */
8489 if (redir->ndup.vname) {
8490 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8491 if (fn.list == NULL)
8492 ash_msg_and_raise_error("redir error");
8493 #if ENABLE_ASH_BASH_COMPAT
8494 //FIXME: we used expandarg with different args!
8495 if (!isdigit_str9(fn.list->text)) {
8496 /* >&file, not >&fd */
8497 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8498 ash_msg_and_raise_error("redir error");
8500 goto store_expfname;
8503 fixredir(redir, fn.list->text, 1);
8511 * Evaluate a pipeline. All the processes in the pipeline are children
8512 * of the process creating the pipeline. (This differs from some versions
8513 * of the shell, which make the last process in a pipeline the parent
8517 evalpipe(union node *n, int flags)
8520 struct nodelist *lp;
8525 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8527 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8531 jp = makejob(/*n,*/ pipelen);
8533 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8537 if (pipe(pip) < 0) {
8539 ash_msg_and_raise_error("pipe call failed");
8542 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8555 evaltreenr(lp->n, flags);
8561 /* Don't want to trigger debugging */
8565 if (n->npipe.pipe_backgnd == 0) {
8566 exitstatus = waitforjob(jp);
8567 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8573 * Controls whether the shell is interactive or not.
8576 setinteractive(int on)
8578 static smallint is_interactive;
8580 if (++on == is_interactive)
8582 is_interactive = on;
8586 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8587 if (is_interactive > 1) {
8588 /* Looks like they want an interactive shell */
8589 static smallint did_banner;
8592 /* note: ash and hush share this string */
8593 out1fmt("\n\n%s %s\n"
8594 "Enter 'help' for a list of built-in commands."
8597 "built-in shell (ash)"
8611 setinteractive(iflag);
8613 #if ENABLE_FEATURE_EDITING_VI
8615 line_input_state->flags |= VI_MODE;
8617 line_input_state->flags &= ~VI_MODE;
8619 viflag = 0; /* forcibly keep the option off */
8623 static struct localvar *localvars;
8626 * Called after a function returns.
8627 * Interrupts must be off.
8632 struct localvar *lvp;
8635 while ((lvp = localvars) != NULL) {
8636 localvars = lvp->next;
8638 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8639 if (vp == NULL) { /* $- saved */
8640 memcpy(optlist, lvp->text, sizeof(optlist));
8641 free((char*)lvp->text);
8643 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8647 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8648 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8649 free((char*)vp->text);
8650 vp->flags = lvp->flags;
8651 vp->text = lvp->text;
8658 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8660 volatile struct shparam saveparam;
8661 struct localvar *volatile savelocalvars;
8662 struct jmploc *volatile savehandler;
8663 struct jmploc jmploc;
8666 saveparam = shellparam;
8667 savelocalvars = localvars;
8668 e = setjmp(jmploc.loc);
8673 savehandler = exception_handler;
8674 exception_handler = &jmploc;
8676 shellparam.malloced = 0;
8680 shellparam.nparam = argc - 1;
8681 shellparam.p = argv + 1;
8682 #if ENABLE_ASH_GETOPTS
8683 shellparam.optind = 1;
8684 shellparam.optoff = -1;
8686 evaltree(&func->n, flags & EV_TESTED);
8692 localvars = savelocalvars;
8693 freeparam(&shellparam);
8694 shellparam = saveparam;
8695 exception_handler = savehandler;
8697 evalskip &= ~SKIPFUNC;
8701 #if ENABLE_ASH_CMDCMD
8703 parse_command_args(char **argv, const char **path)
8716 if (c == '-' && !*cp) {
8723 *path = bb_default_path;
8726 /* run 'typecmd' for other options */
8737 * Make a variable a local variable. When a variable is made local, it's
8738 * value and flags are saved in a localvar structure. The saved values
8739 * will be restored when the shell function returns. We handle the name
8740 * "-" as a special case.
8745 struct localvar *lvp;
8750 lvp = ckzalloc(sizeof(struct localvar));
8751 if (LONE_DASH(name)) {
8753 p = ckmalloc(sizeof(optlist));
8754 lvp->text = memcpy(p, optlist, sizeof(optlist));
8759 vpp = hashvar(name);
8760 vp = *findvar(vpp, name);
8761 eq = strchr(name, '=');
8764 setvareq(name, VSTRFIXED);
8766 setvar(name, NULL, VSTRFIXED);
8767 vp = *vpp; /* the new variable */
8768 lvp->flags = VUNSET;
8770 lvp->text = vp->text;
8771 lvp->flags = vp->flags;
8772 vp->flags |= VSTRFIXED|VTEXTFIXED;
8778 lvp->next = localvars;
8784 * The "local" command.
8786 static int FAST_FUNC
8787 localcmd(int argc UNUSED_PARAM, char **argv)
8792 while ((name = *argv++) != NULL) {
8798 static int FAST_FUNC
8799 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8804 static int FAST_FUNC
8805 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8810 static int FAST_FUNC
8811 execcmd(int argc UNUSED_PARAM, char **argv)
8814 iflag = 0; /* exit on error */
8817 shellexec(argv + 1, pathval(), 0);
8823 * The return command.
8825 static int FAST_FUNC
8826 returncmd(int argc UNUSED_PARAM, char **argv)
8829 * If called outside a function, do what ksh does;
8830 * skip the rest of the file.
8832 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8833 return argv[1] ? number(argv[1]) : exitstatus;
8836 /* Forward declarations for builtintab[] */
8837 static int breakcmd(int, char **) FAST_FUNC;
8838 static int dotcmd(int, char **) FAST_FUNC;
8839 static int evalcmd(int, char **) FAST_FUNC;
8840 static int exitcmd(int, char **) FAST_FUNC;
8841 static int exportcmd(int, char **) FAST_FUNC;
8842 #if ENABLE_ASH_GETOPTS
8843 static int getoptscmd(int, char **) FAST_FUNC;
8845 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8846 static int helpcmd(int, char **) FAST_FUNC;
8848 #if ENABLE_SH_MATH_SUPPORT
8849 static int letcmd(int, char **) FAST_FUNC;
8851 static int readcmd(int, char **) FAST_FUNC;
8852 static int setcmd(int, char **) FAST_FUNC;
8853 static int shiftcmd(int, char **) FAST_FUNC;
8854 static int timescmd(int, char **) FAST_FUNC;
8855 static int trapcmd(int, char **) FAST_FUNC;
8856 static int umaskcmd(int, char **) FAST_FUNC;
8857 static int unsetcmd(int, char **) FAST_FUNC;
8858 static int ulimitcmd(int, char **) FAST_FUNC;
8860 #define BUILTIN_NOSPEC "0"
8861 #define BUILTIN_SPECIAL "1"
8862 #define BUILTIN_REGULAR "2"
8863 #define BUILTIN_SPEC_REG "3"
8864 #define BUILTIN_ASSIGN "4"
8865 #define BUILTIN_SPEC_ASSG "5"
8866 #define BUILTIN_REG_ASSG "6"
8867 #define BUILTIN_SPEC_REG_ASSG "7"
8869 /* Stubs for calling non-FAST_FUNC's */
8870 #if ENABLE_ASH_BUILTIN_ECHO
8871 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8873 #if ENABLE_ASH_BUILTIN_PRINTF
8874 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8876 #if ENABLE_ASH_BUILTIN_TEST
8877 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8880 /* Keep these in proper order since it is searched via bsearch() */
8881 static const struct builtincmd builtintab[] = {
8882 { BUILTIN_SPEC_REG ".", dotcmd },
8883 { BUILTIN_SPEC_REG ":", truecmd },
8884 #if ENABLE_ASH_BUILTIN_TEST
8885 { BUILTIN_REGULAR "[", testcmd },
8886 #if ENABLE_ASH_BASH_COMPAT
8887 { BUILTIN_REGULAR "[[", testcmd },
8890 #if ENABLE_ASH_ALIAS
8891 { BUILTIN_REG_ASSG "alias", aliascmd },
8894 { BUILTIN_REGULAR "bg", fg_bgcmd },
8896 { BUILTIN_SPEC_REG "break", breakcmd },
8897 { BUILTIN_REGULAR "cd", cdcmd },
8898 { BUILTIN_NOSPEC "chdir", cdcmd },
8899 #if ENABLE_ASH_CMDCMD
8900 { BUILTIN_REGULAR "command", commandcmd },
8902 { BUILTIN_SPEC_REG "continue", breakcmd },
8903 #if ENABLE_ASH_BUILTIN_ECHO
8904 { BUILTIN_REGULAR "echo", echocmd },
8906 { BUILTIN_SPEC_REG "eval", evalcmd },
8907 { BUILTIN_SPEC_REG "exec", execcmd },
8908 { BUILTIN_SPEC_REG "exit", exitcmd },
8909 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8910 { BUILTIN_REGULAR "false", falsecmd },
8912 { BUILTIN_REGULAR "fg", fg_bgcmd },
8914 #if ENABLE_ASH_GETOPTS
8915 { BUILTIN_REGULAR "getopts", getoptscmd },
8917 { BUILTIN_NOSPEC "hash", hashcmd },
8918 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8919 { BUILTIN_NOSPEC "help", helpcmd },
8922 { BUILTIN_REGULAR "jobs", jobscmd },
8923 { BUILTIN_REGULAR "kill", killcmd },
8925 #if ENABLE_SH_MATH_SUPPORT
8926 { BUILTIN_NOSPEC "let", letcmd },
8928 { BUILTIN_ASSIGN "local", localcmd },
8929 #if ENABLE_ASH_BUILTIN_PRINTF
8930 { BUILTIN_REGULAR "printf", printfcmd },
8932 { BUILTIN_NOSPEC "pwd", pwdcmd },
8933 { BUILTIN_REGULAR "read", readcmd },
8934 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8935 { BUILTIN_SPEC_REG "return", returncmd },
8936 { BUILTIN_SPEC_REG "set", setcmd },
8937 { BUILTIN_SPEC_REG "shift", shiftcmd },
8938 { BUILTIN_SPEC_REG "source", dotcmd },
8939 #if ENABLE_ASH_BUILTIN_TEST
8940 { BUILTIN_REGULAR "test", testcmd },
8942 { BUILTIN_SPEC_REG "times", timescmd },
8943 { BUILTIN_SPEC_REG "trap", trapcmd },
8944 { BUILTIN_REGULAR "true", truecmd },
8945 { BUILTIN_NOSPEC "type", typecmd },
8946 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8947 { BUILTIN_REGULAR "umask", umaskcmd },
8948 #if ENABLE_ASH_ALIAS
8949 { BUILTIN_REGULAR "unalias", unaliascmd },
8951 { BUILTIN_SPEC_REG "unset", unsetcmd },
8952 { BUILTIN_REGULAR "wait", waitcmd },
8955 /* Should match the above table! */
8956 #define COMMANDCMD (builtintab + \
8958 1 * ENABLE_ASH_BUILTIN_TEST + \
8959 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8960 1 * ENABLE_ASH_ALIAS + \
8961 1 * ENABLE_ASH_JOB_CONTROL + \
8963 #define EXECCMD (builtintab + \
8965 1 * ENABLE_ASH_BUILTIN_TEST + \
8966 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8967 1 * ENABLE_ASH_ALIAS + \
8968 1 * ENABLE_ASH_JOB_CONTROL + \
8970 1 * ENABLE_ASH_CMDCMD + \
8972 ENABLE_ASH_BUILTIN_ECHO + \
8976 * Search the table of builtin commands.
8978 static struct builtincmd *
8979 find_builtin(const char *name)
8981 struct builtincmd *bp;
8984 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8991 * Execute a simple command.
8994 isassignment(const char *p)
8996 const char *q = endofname(p);
9001 static int FAST_FUNC
9002 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9004 /* Preserve exitstatus of a previous possible redirection
9005 * as POSIX mandates */
9006 return back_exitstatus;
9009 evalcommand(union node *cmd, int flags)
9011 static const struct builtincmd null_bltin = {
9012 "\0\0", bltincmd /* why three NULs? */
9014 struct stackmark smark;
9016 struct arglist arglist;
9017 struct arglist varlist;
9020 const struct strlist *sp;
9021 struct cmdentry cmdentry;
9028 struct builtincmd *bcmd;
9029 smallint cmd_is_exec;
9030 smallint pseudovarflag = 0;
9032 /* First expand the arguments. */
9033 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9034 setstackmark(&smark);
9035 back_exitstatus = 0;
9037 cmdentry.cmdtype = CMDBUILTIN;
9038 cmdentry.u.cmd = &null_bltin;
9039 varlist.lastp = &varlist.list;
9040 *varlist.lastp = NULL;
9041 arglist.lastp = &arglist.list;
9042 *arglist.lastp = NULL;
9045 if (cmd->ncmd.args) {
9046 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9047 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9050 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9051 struct strlist **spp;
9053 spp = arglist.lastp;
9054 if (pseudovarflag && isassignment(argp->narg.text))
9055 expandarg(argp, &arglist, EXP_VARTILDE);
9057 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9059 for (sp = *spp; sp; sp = sp->next)
9063 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9064 for (sp = arglist.list; sp; sp = sp->next) {
9065 TRACE(("evalcommand arg: %s\n", sp->text));
9066 *nargv++ = sp->text;
9071 if (iflag && funcnest == 0 && argc > 0)
9072 lastarg = nargv[-1];
9075 expredir(cmd->ncmd.redirect);
9076 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9079 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9080 struct strlist **spp;
9083 spp = varlist.lastp;
9084 expandarg(argp, &varlist, EXP_VARTILDE);
9087 * Modify the command lookup path, if a PATH= assignment
9091 if (varequal(p, path))
9095 /* Print the command if xflag is set. */
9098 const char *p = " %s";
9101 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9104 for (n = 0; n < 2; n++) {
9106 fdprintf(preverrout_fd, p, sp->text);
9114 safe_write(preverrout_fd, "\n", 1);
9120 /* Now locate the command. */
9122 const char *oldpath;
9123 int cmd_flag = DO_ERR;
9128 find_command(argv[0], &cmdentry, cmd_flag, path);
9129 if (cmdentry.cmdtype == CMDUNKNOWN) {
9130 flush_stdout_stderr();
9135 /* implement bltin and command here */
9136 if (cmdentry.cmdtype != CMDBUILTIN)
9139 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9140 if (cmdentry.u.cmd == EXECCMD)
9142 #if ENABLE_ASH_CMDCMD
9143 if (cmdentry.u.cmd == COMMANDCMD) {
9145 nargv = parse_command_args(argv, &path);
9148 argc -= nargv - argv;
9150 cmd_flag |= DO_NOFUNC;
9158 /* We have a redirection error. */
9160 raise_exception(EXERROR);
9162 exitstatus = status;
9166 /* Execute the command. */
9167 switch (cmdentry.cmdtype) {
9170 #if ENABLE_FEATURE_SH_NOFORK
9171 /* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9172 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
9174 /* find_command() encodes applet_no as (-2 - applet_no) */
9175 int applet_no = (- cmdentry.u.index - 2);
9176 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9177 listsetvar(varlist.list, VEXPORT|VSTACK);
9178 /* run <applet>_main() */
9179 exitstatus = run_nofork_applet(applet_no, argv);
9184 /* Fork off a child process if necessary. */
9185 if (!(flags & EV_EXIT) || trap[0]) {
9187 jp = makejob(/*cmd,*/ 1);
9188 if (forkshell(jp, cmd, FORK_FG) != 0) {
9189 exitstatus = waitforjob(jp);
9191 TRACE(("forked child exited with %d\n", exitstatus));
9196 listsetvar(varlist.list, VEXPORT|VSTACK);
9197 shellexec(argv, path, cmdentry.u.index);
9201 cmdenviron = varlist.list;
9203 struct strlist *list = cmdenviron;
9205 if (spclbltin > 0 || argc == 0) {
9207 if (cmd_is_exec && argc > 1)
9210 listsetvar(list, i);
9212 /* Tight loop with builtins only:
9213 * "while kill -0 $child; do true; done"
9214 * will never exit even if $child died, unless we do this
9215 * to reap the zombie and make kill detect that it's gone: */
9216 dowait(DOWAIT_NONBLOCK, NULL);
9218 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9220 int i = exception_type;
9225 exit_status = 128 + SIGINT;
9227 exit_status = 128 + pending_sig;
9228 exitstatus = exit_status;
9229 if (i == EXINT || spclbltin > 0) {
9231 longjmp(exception_handler->loc, 1);
9238 listsetvar(varlist.list, 0);
9239 /* See above for the rationale */
9240 dowait(DOWAIT_NONBLOCK, NULL);
9241 if (evalfun(cmdentry.u.func, argc, argv, flags))
9247 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9249 /* dsl: I think this is intended to be used to support
9250 * '_' in 'vi' command mode during line editing...
9251 * However I implemented that within libedit itself.
9253 setvar("_", lastarg, 0);
9255 popstackmark(&smark);
9259 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9261 char *volatile savecmdname;
9262 struct jmploc *volatile savehandler;
9263 struct jmploc jmploc;
9266 savecmdname = commandname;
9267 i = setjmp(jmploc.loc);
9270 savehandler = exception_handler;
9271 exception_handler = &jmploc;
9272 commandname = argv[0];
9274 optptr = NULL; /* initialize nextopt */
9275 exitstatus = (*cmd->builtin)(argc, argv);
9276 flush_stdout_stderr();
9278 exitstatus |= ferror(stdout);
9280 commandname = savecmdname;
9281 exception_handler = savehandler;
9287 goodname(const char *p)
9289 return !*endofname(p);
9294 * Search for a command. This is called before we fork so that the
9295 * location of the command will be available in the parent as well as
9296 * the child. The check for "goodname" is an overly conservative
9297 * check that the name will not be subject to expansion.
9300 prehash(union node *n)
9302 struct cmdentry entry;
9304 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9305 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9309 /* ============ Builtin commands
9311 * Builtin commands whose functions are closely tied to evaluation
9312 * are implemented here.
9316 * Handle break and continue commands. Break, continue, and return are
9317 * all handled by setting the evalskip flag. The evaluation routines
9318 * above all check this flag, and if it is set they start skipping
9319 * commands rather than executing them. The variable skipcount is
9320 * the number of loops to break/continue, or the number of function
9321 * levels to return. (The latter is always 1.) It should probably
9322 * be an error to break out of more loops than exist, but it isn't
9323 * in the standard shell so we don't make it one here.
9325 static int FAST_FUNC
9326 breakcmd(int argc UNUSED_PARAM, char **argv)
9328 int n = argv[1] ? number(argv[1]) : 1;
9331 ash_msg_and_raise_error(msg_illnum, argv[1]);
9335 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9342 /* ============ input.c
9344 * This implements the input routines used by the parser.
9348 INPUT_PUSH_FILE = 1,
9349 INPUT_NOFILE_OK = 2,
9352 static smallint checkkwd;
9353 /* values of checkkwd variable */
9354 #define CHKALIAS 0x1
9359 * Push a string back onto the input at this current parsefile level.
9360 * We handle aliases this way.
9362 #if !ENABLE_ASH_ALIAS
9363 #define pushstring(s, ap) pushstring(s)
9366 pushstring(char *s, struct alias *ap)
9373 if (g_parsefile->strpush) {
9374 sp = ckzalloc(sizeof(*sp));
9375 sp->prev = g_parsefile->strpush;
9377 sp = &(g_parsefile->basestrpush);
9379 g_parsefile->strpush = sp;
9380 sp->prev_string = g_parsefile->next_to_pgetc;
9381 sp->prev_left_in_line = g_parsefile->left_in_line;
9382 #if ENABLE_ASH_ALIAS
9385 ap->flag |= ALIASINUSE;
9389 g_parsefile->next_to_pgetc = s;
9390 g_parsefile->left_in_line = len;
9397 struct strpush *sp = g_parsefile->strpush;
9400 #if ENABLE_ASH_ALIAS
9402 if (g_parsefile->next_to_pgetc[-1] == ' '
9403 || g_parsefile->next_to_pgetc[-1] == '\t'
9405 checkkwd |= CHKALIAS;
9407 if (sp->string != sp->ap->val) {
9410 sp->ap->flag &= ~ALIASINUSE;
9411 if (sp->ap->flag & ALIASDEAD) {
9412 unalias(sp->ap->name);
9416 g_parsefile->next_to_pgetc = sp->prev_string;
9417 g_parsefile->left_in_line = sp->prev_left_in_line;
9418 g_parsefile->strpush = sp->prev;
9419 if (sp != &(g_parsefile->basestrpush))
9424 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9425 //it peeks whether it is &>, and then pushes back both chars.
9426 //This function needs to save last *next_to_pgetc to buf[0]
9427 //to make two pungetc() reliable. Currently,
9428 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9433 char *buf = g_parsefile->buf;
9435 g_parsefile->next_to_pgetc = buf;
9436 #if ENABLE_FEATURE_EDITING
9438 if (!iflag || g_parsefile->fd != STDIN_FILENO)
9439 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9441 #if ENABLE_FEATURE_TAB_COMPLETION
9442 line_input_state->path_lookup = pathval();
9444 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9446 /* Ctrl+C pressed */
9455 if (nr < 0 && errno == 0) {
9456 /* Ctrl+D pressed */
9461 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9465 /* nonblock_safe_read() handles this problem */
9467 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9468 int flags = fcntl(0, F_GETFL);
9469 if (flags >= 0 && (flags & O_NONBLOCK)) {
9470 flags &= ~O_NONBLOCK;
9471 if (fcntl(0, F_SETFL, flags) >= 0) {
9472 out2str("sh: turning off NDELAY mode\n");
9483 * Refill the input buffer and return the next input character:
9485 * 1) If a string was pushed back on the input, pop it;
9486 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9487 * or we are reading from a string so we can't refill the buffer,
9489 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9490 * 4) Process input up to the next newline, deleting nul characters.
9492 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9493 #define pgetc_debug(...) ((void)0)
9500 while (g_parsefile->strpush) {
9501 #if ENABLE_ASH_ALIAS
9502 if (g_parsefile->left_in_line == -1
9503 && g_parsefile->strpush->ap
9504 && g_parsefile->next_to_pgetc[-1] != ' '
9505 && g_parsefile->next_to_pgetc[-1] != '\t'
9507 pgetc_debug("preadbuffer PEOA");
9512 /* try "pgetc" now: */
9513 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9514 g_parsefile->left_in_line,
9515 g_parsefile->next_to_pgetc,
9516 g_parsefile->next_to_pgetc);
9517 if (--g_parsefile->left_in_line >= 0)
9518 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9520 /* on both branches above g_parsefile->left_in_line < 0.
9521 * "pgetc" needs refilling.
9524 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9525 * pungetc() may increment it a few times.
9526 * Assuming it won't increment it to less than -90.
9528 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9529 pgetc_debug("preadbuffer PEOF1");
9530 /* even in failure keep left_in_line and next_to_pgetc
9531 * in lock step, for correct multi-layer pungetc.
9532 * left_in_line was decremented before preadbuffer(),
9533 * must inc next_to_pgetc: */
9534 g_parsefile->next_to_pgetc++;
9538 more = g_parsefile->left_in_buffer;
9540 flush_stdout_stderr();
9544 /* don't try reading again */
9545 g_parsefile->left_in_line = -99;
9546 pgetc_debug("preadbuffer PEOF2");
9547 g_parsefile->next_to_pgetc++;
9552 /* Find out where's the end of line.
9553 * Set g_parsefile->left_in_line
9554 * and g_parsefile->left_in_buffer acordingly.
9555 * NUL chars are deleted.
9557 q = g_parsefile->next_to_pgetc;
9565 memmove(q, q + 1, more);
9569 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9575 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9576 if (g_parsefile->left_in_line < 0)
9581 g_parsefile->left_in_buffer = more;
9586 out2str(g_parsefile->next_to_pgetc);
9590 pgetc_debug("preadbuffer at %d:%p'%s'",
9591 g_parsefile->left_in_line,
9592 g_parsefile->next_to_pgetc,
9593 g_parsefile->next_to_pgetc);
9594 return (unsigned char)*g_parsefile->next_to_pgetc++;
9597 #define pgetc_as_macro() \
9598 (--g_parsefile->left_in_line >= 0 \
9599 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9606 pgetc_debug("pgetc_fast at %d:%p'%s'",
9607 g_parsefile->left_in_line,
9608 g_parsefile->next_to_pgetc,
9609 g_parsefile->next_to_pgetc);
9610 return pgetc_as_macro();
9613 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9614 # define pgetc_fast() pgetc()
9616 # define pgetc_fast() pgetc_as_macro()
9619 #if ENABLE_ASH_ALIAS
9621 pgetc_without_PEOA(void)
9625 pgetc_debug("pgetc_fast at %d:%p'%s'",
9626 g_parsefile->left_in_line,
9627 g_parsefile->next_to_pgetc,
9628 g_parsefile->next_to_pgetc);
9630 } while (c == PEOA);
9634 # define pgetc_without_PEOA() pgetc()
9638 * Read a line from the script.
9641 pfgets(char *line, int len)
9647 while (--nleft > 0) {
9648 c = pgetc_without_PEOA();
9663 * Undo the last call to pgetc. Only one character may be pushed back.
9664 * PEOF may be pushed back.
9669 g_parsefile->left_in_line++;
9670 g_parsefile->next_to_pgetc--;
9671 pgetc_debug("pushed back to %d:%p'%s'",
9672 g_parsefile->left_in_line,
9673 g_parsefile->next_to_pgetc,
9674 g_parsefile->next_to_pgetc);
9678 * To handle the "." command, a stack of input files is used. Pushfile
9679 * adds a new entry to the stack and popfile restores the previous level.
9684 struct parsefile *pf;
9686 pf = ckzalloc(sizeof(*pf));
9687 pf->prev = g_parsefile;
9689 /*pf->strpush = NULL; - ckzalloc did it */
9690 /*pf->basestrpush.prev = NULL;*/
9697 struct parsefile *pf = g_parsefile;
9705 g_parsefile = pf->prev;
9711 * Return to top level.
9716 while (g_parsefile != &basepf)
9721 * Close the file(s) that the shell is reading commands from. Called
9722 * after a fork is done.
9728 if (g_parsefile->fd > 0) {
9729 close(g_parsefile->fd);
9730 g_parsefile->fd = 0;
9735 * Like setinputfile, but takes an open file descriptor. Call this with
9739 setinputfd(int fd, int push)
9741 close_on_exec_on(fd);
9744 g_parsefile->buf = NULL;
9746 g_parsefile->fd = fd;
9747 if (g_parsefile->buf == NULL)
9748 g_parsefile->buf = ckmalloc(IBUFSIZ);
9749 g_parsefile->left_in_buffer = 0;
9750 g_parsefile->left_in_line = 0;
9751 g_parsefile->linno = 1;
9755 * Set the input to take input from a file. If push is set, push the
9756 * old input onto the stack first.
9759 setinputfile(const char *fname, int flags)
9765 fd = open(fname, O_RDONLY);
9767 if (flags & INPUT_NOFILE_OK)
9769 ash_msg_and_raise_error("can't open '%s'", fname);
9772 fd2 = copyfd(fd, 10);
9775 ash_msg_and_raise_error("out of file descriptors");
9778 setinputfd(fd, flags & INPUT_PUSH_FILE);
9785 * Like setinputfile, but takes input from a string.
9788 setinputstring(char *string)
9792 g_parsefile->next_to_pgetc = string;
9793 g_parsefile->left_in_line = strlen(string);
9794 g_parsefile->buf = NULL;
9795 g_parsefile->linno = 1;
9800 /* ============ mail.c
9802 * Routines to check for mail.
9807 #define MAXMBOXES 10
9809 /* times of mailboxes */
9810 static time_t mailtime[MAXMBOXES];
9811 /* Set if MAIL or MAILPATH is changed. */
9812 static smallint mail_var_path_changed;
9815 * Print appropriate message(s) if mail has arrived.
9816 * If mail_var_path_changed is set,
9817 * then the value of MAIL has mail_var_path_changed,
9818 * so we just update the values.
9827 struct stackmark smark;
9830 setstackmark(&smark);
9831 mpath = mpathset() ? mpathval() : mailval();
9832 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9833 p = path_advance(&mpath, nullstr);
9838 for (q = p; *q; q++)
9844 q[-1] = '\0'; /* delete trailing '/' */
9845 if (stat(p, &statb) < 0) {
9849 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9852 pathopt ? pathopt : "you have mail"
9855 *mtp = statb.st_mtime;
9857 mail_var_path_changed = 0;
9858 popstackmark(&smark);
9861 static void FAST_FUNC
9862 changemail(const char *val UNUSED_PARAM)
9864 mail_var_path_changed = 1;
9867 #endif /* ASH_MAIL */
9870 /* ============ ??? */
9873 * Set the shell parameters.
9876 setparam(char **argv)
9882 for (nparam = 0; argv[nparam]; nparam++)
9884 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9886 *ap++ = ckstrdup(*argv++);
9889 freeparam(&shellparam);
9890 shellparam.malloced = 1;
9891 shellparam.nparam = nparam;
9892 shellparam.p = newparam;
9893 #if ENABLE_ASH_GETOPTS
9894 shellparam.optind = 1;
9895 shellparam.optoff = -1;
9900 * Process shell options. The global variable argptr contains a pointer
9901 * to the argument list; we advance it past the options.
9903 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9904 * For a non-interactive shell, an error condition encountered
9905 * by a special built-in ... shall cause the shell to write a diagnostic message
9906 * to standard error and exit as shown in the following table:
9907 * Error Special Built-In
9909 * Utility syntax error (option or operand error) Shall exit
9911 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9912 * we see that bash does not do that (set "finishes" with error code 1 instead,
9913 * and shell continues), and people rely on this behavior!
9915 * set -o barfoo 2>/dev/null
9918 * Oh well. Let's mimic that.
9921 plus_minus_o(char *name, int val)
9926 for (i = 0; i < NOPTS; i++) {
9927 if (strcmp(name, optnames(i)) == 0) {
9932 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9935 for (i = 0; i < NOPTS; i++) {
9937 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9939 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9945 setoption(int flag, int val)
9949 for (i = 0; i < NOPTS; i++) {
9950 if (optletters(i) == flag) {
9955 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9959 options(int cmdline)
9967 while ((p = *argptr) != NULL) {
9969 if (c != '-' && c != '+')
9972 val = 0; /* val = 0 if c == '+' */
9975 if (p[0] == '\0' || LONE_DASH(p)) {
9977 /* "-" means turn off -x and -v */
9980 /* "--" means reset params */
9981 else if (*argptr == NULL)
9984 break; /* "-" or "--" terminates options */
9987 /* first char was + or - */
9988 while ((c = *p++) != '\0') {
9989 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9990 if (c == 'c' && cmdline) {
9991 minusc = p; /* command is after shell args */
9992 } else if (c == 'o') {
9993 if (plus_minus_o(*argptr, val)) {
9994 /* it already printed err message */
9995 return 1; /* error */
9999 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10001 /* bash does not accept +-login, we also won't */
10002 } else if (cmdline && val && (c == '-')) { /* long options */
10003 if (strcmp(p, "login") == 0)
10015 * The shift builtin command.
10017 static int FAST_FUNC
10018 shiftcmd(int argc UNUSED_PARAM, char **argv)
10025 n = number(argv[1]);
10026 if (n > shellparam.nparam)
10027 n = 0; /* bash compat, was = shellparam.nparam; */
10029 shellparam.nparam -= n;
10030 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10031 if (shellparam.malloced)
10034 ap2 = shellparam.p;
10035 while ((*ap2++ = *ap1++) != NULL)
10037 #if ENABLE_ASH_GETOPTS
10038 shellparam.optind = 1;
10039 shellparam.optoff = -1;
10046 * POSIX requires that 'set' (but not export or readonly) output the
10047 * variables in lexicographic order - by the locale's collating order (sigh).
10048 * Maybe we could keep them in an ordered balanced binary tree
10049 * instead of hashed lists.
10050 * For now just roll 'em through qsort for printing...
10053 showvars(const char *sep_prefix, int on, int off)
10056 char **ep, **epend;
10058 ep = listvars(on, off, &epend);
10059 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10061 sep = *sep_prefix ? " " : sep_prefix;
10063 for (; ep < epend; ep++) {
10067 p = strchrnul(*ep, '=');
10070 q = single_quote(++p);
10071 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10077 * The set command builtin.
10079 static int FAST_FUNC
10080 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10085 return showvars(nullstr, 0, VUNSET);
10088 if (!options(0)) { /* if no parse error... */
10091 if (*argptr != NULL) {
10099 #if ENABLE_ASH_RANDOM_SUPPORT
10100 static void FAST_FUNC
10101 change_random(const char *value)
10105 if (value == NULL) {
10106 /* "get", generate */
10107 t = next_random(&random_gen);
10108 /* set without recursion */
10109 setvar(vrandom.text, utoa(t), VNOFUNC);
10110 vrandom.flags &= ~VNOFUNC;
10113 t = strtoul(value, NULL, 10);
10114 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10119 #if ENABLE_ASH_GETOPTS
10121 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10130 if (*param_optind < 1)
10132 optnext = optfirst + *param_optind - 1;
10134 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10137 p = optnext[-1] + *optoff;
10138 if (p == NULL || *p == '\0') {
10139 /* Current word is done, advance */
10141 if (p == NULL || *p != '-' || *++p == '\0') {
10148 if (LONE_DASH(p)) /* check for "--" */
10153 for (q = optstr; *q != c;) {
10155 if (optstr[0] == ':') {
10158 err |= setvarsafe("OPTARG", s, 0);
10160 fprintf(stderr, "Illegal option -%c\n", c);
10161 unsetvar("OPTARG");
10171 if (*p == '\0' && (p = *optnext) == NULL) {
10172 if (optstr[0] == ':') {
10175 err |= setvarsafe("OPTARG", s, 0);
10178 fprintf(stderr, "No arg for -%c option\n", c);
10179 unsetvar("OPTARG");
10187 err |= setvarsafe("OPTARG", p, 0);
10190 err |= setvarsafe("OPTARG", nullstr, 0);
10192 *optoff = p ? p - *(optnext - 1) : -1;
10193 *param_optind = optnext - optfirst + 1;
10194 fmtstr(s, sizeof(s), "%d", *param_optind);
10195 err |= setvarsafe("OPTIND", s, VNOFUNC);
10198 err |= setvarsafe(optvar, s, 0);
10202 flush_stdout_stderr();
10203 raise_exception(EXERROR);
10209 * The getopts builtin. Shellparam.optnext points to the next argument
10210 * to be processed. Shellparam.optptr points to the next character to
10211 * be processed in the current argument. If shellparam.optnext is NULL,
10212 * then it's the first time getopts has been called.
10214 static int FAST_FUNC
10215 getoptscmd(int argc, char **argv)
10220 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10222 optbase = shellparam.p;
10223 if (shellparam.optind > shellparam.nparam + 1) {
10224 shellparam.optind = 1;
10225 shellparam.optoff = -1;
10228 optbase = &argv[3];
10229 if (shellparam.optind > argc - 2) {
10230 shellparam.optind = 1;
10231 shellparam.optoff = -1;
10235 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10236 &shellparam.optoff);
10238 #endif /* ASH_GETOPTS */
10241 /* ============ Shell parser */
10244 struct heredoc *next; /* next here document in list */
10245 union node *here; /* redirection node */
10246 char *eofmark; /* string indicating end of input */
10247 smallint striptabs; /* if set, strip leading tabs */
10250 static smallint tokpushback; /* last token pushed back */
10251 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10252 static smallint quoteflag; /* set if (part of) last token was quoted */
10253 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10254 static struct heredoc *heredoclist; /* list of here documents to read */
10255 static char *wordtext; /* text of last word returned by readtoken */
10256 static struct nodelist *backquotelist;
10257 static union node *redirnode;
10258 static struct heredoc *heredoc;
10261 * Called when an unexpected token is read during the parse. The argument
10262 * is the token that is expected, or -1 if more than one type of token can
10263 * occur at this point.
10265 static void raise_error_unexpected_syntax(int) NORETURN;
10267 raise_error_unexpected_syntax(int token)
10272 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
10274 sprintf(msg + l, " (expecting %s)", tokname(token));
10275 raise_error_syntax(msg);
10279 #define EOFMARKLEN 79
10281 /* parsing is heavily cross-recursive, need these forward decls */
10282 static union node *andor(void);
10283 static union node *pipeline(void);
10284 static union node *parse_command(void);
10285 static void parseheredoc(void);
10286 static char peektoken(void);
10287 static int readtoken(void);
10289 static union node *
10292 union node *n1, *n2, *n3;
10295 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10296 if (nlflag == 2 && peektoken())
10302 if (tok == TBACKGND) {
10303 if (n2->type == NPIPE) {
10304 n2->npipe.pipe_backgnd = 1;
10306 if (n2->type != NREDIR) {
10307 n3 = stzalloc(sizeof(struct nredir));
10309 /*n3->nredir.redirect = NULL; - stzalloc did it */
10312 n2->type = NBACKGND;
10318 n3 = stzalloc(sizeof(struct nbinary));
10320 n3->nbinary.ch1 = n1;
10321 n3->nbinary.ch2 = n2;
10337 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10345 pungetc(); /* push back EOF on input */
10349 raise_error_unexpected_syntax(-1);
10356 static union node *
10359 union node *n1, *n2, *n3;
10367 } else if (t == TOR) {
10373 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10375 n3 = stzalloc(sizeof(struct nbinary));
10377 n3->nbinary.ch1 = n1;
10378 n3->nbinary.ch2 = n2;
10383 static union node *
10386 union node *n1, *n2, *pipenode;
10387 struct nodelist *lp, *prev;
10391 TRACE(("pipeline: entered\n"));
10392 if (readtoken() == TNOT) {
10394 checkkwd = CHKKWD | CHKALIAS;
10397 n1 = parse_command();
10398 if (readtoken() == TPIPE) {
10399 pipenode = stzalloc(sizeof(struct npipe));
10400 pipenode->type = NPIPE;
10401 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10402 lp = stzalloc(sizeof(struct nodelist));
10403 pipenode->npipe.cmdlist = lp;
10407 lp = stzalloc(sizeof(struct nodelist));
10408 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10409 lp->n = parse_command();
10411 } while (readtoken() == TPIPE);
10417 n2 = stzalloc(sizeof(struct nnot));
10425 static union node *
10430 n = stzalloc(sizeof(struct narg));
10432 /*n->narg.next = NULL; - stzalloc did it */
10433 n->narg.text = wordtext;
10434 n->narg.backquote = backquotelist;
10439 fixredir(union node *n, const char *text, int err)
10443 TRACE(("Fix redir %s %d\n", text, err));
10445 n->ndup.vname = NULL;
10447 fd = bb_strtou(text, NULL, 10);
10448 if (!errno && fd >= 0)
10449 n->ndup.dupfd = fd;
10450 else if (LONE_DASH(text))
10451 n->ndup.dupfd = -1;
10454 raise_error_syntax("bad fd number");
10455 n->ndup.vname = makename();
10460 * Returns true if the text contains nothing to expand (no dollar signs
10464 noexpand(const char *text)
10468 while ((c = *text++) != '\0') {
10469 if (c == CTLQUOTEMARK)
10473 else if (SIT(c, BASESYNTAX) == CCTL)
10482 union node *n = redirnode;
10484 if (readtoken() != TWORD)
10485 raise_error_unexpected_syntax(-1);
10486 if (n->type == NHERE) {
10487 struct heredoc *here = heredoc;
10491 if (quoteflag == 0)
10493 TRACE(("Here document %d\n", n->type));
10494 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10495 raise_error_syntax("illegal eof marker for << redirection");
10496 rmescapes(wordtext, 0);
10497 here->eofmark = wordtext;
10499 if (heredoclist == NULL)
10500 heredoclist = here;
10502 for (p = heredoclist; p->next; p = p->next)
10506 } else if (n->type == NTOFD || n->type == NFROMFD) {
10507 fixredir(n, wordtext, 0);
10509 n->nfile.fname = makename();
10513 static union node *
10516 union node *args, **app;
10517 union node *n = NULL;
10518 union node *vars, **vpp;
10519 union node **rpp, *redir;
10521 #if ENABLE_ASH_BASH_COMPAT
10522 smallint double_brackets_flag = 0;
10532 savecheckkwd = CHKALIAS;
10535 checkkwd = savecheckkwd;
10538 #if ENABLE_ASH_BASH_COMPAT
10539 case TAND: /* "&&" */
10540 case TOR: /* "||" */
10541 if (!double_brackets_flag) {
10545 wordtext = (char *) (t == TAND ? "-a" : "-o");
10548 n = stzalloc(sizeof(struct narg));
10550 /*n->narg.next = NULL; - stzalloc did it */
10551 n->narg.text = wordtext;
10552 #if ENABLE_ASH_BASH_COMPAT
10553 if (strcmp("[[", wordtext) == 0)
10554 double_brackets_flag = 1;
10555 else if (strcmp("]]", wordtext) == 0)
10556 double_brackets_flag = 0;
10558 n->narg.backquote = backquotelist;
10559 if (savecheckkwd && isassignment(wordtext)) {
10561 vpp = &n->narg.next;
10564 app = &n->narg.next;
10569 *rpp = n = redirnode;
10570 rpp = &n->nfile.next;
10571 parsefname(); /* read name of redirection file */
10574 if (args && app == &args->narg.next
10577 struct builtincmd *bcmd;
10580 /* We have a function */
10581 if (readtoken() != TRP)
10582 raise_error_unexpected_syntax(TRP);
10583 name = n->narg.text;
10584 if (!goodname(name)
10585 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10587 raise_error_syntax("bad function name");
10590 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10591 n->narg.next = parse_command();
10604 n = stzalloc(sizeof(struct ncmd));
10606 n->ncmd.args = args;
10607 n->ncmd.assign = vars;
10608 n->ncmd.redirect = redir;
10612 static union node *
10613 parse_command(void)
10615 union node *n1, *n2;
10616 union node *ap, **app;
10617 union node *cp, **cpp;
10618 union node *redir, **rpp;
10625 switch (readtoken()) {
10627 raise_error_unexpected_syntax(-1);
10630 n1 = stzalloc(sizeof(struct nif));
10632 n1->nif.test = list(0);
10633 if (readtoken() != TTHEN)
10634 raise_error_unexpected_syntax(TTHEN);
10635 n1->nif.ifpart = list(0);
10637 while (readtoken() == TELIF) {
10638 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10639 n2 = n2->nif.elsepart;
10641 n2->nif.test = list(0);
10642 if (readtoken() != TTHEN)
10643 raise_error_unexpected_syntax(TTHEN);
10644 n2->nif.ifpart = list(0);
10646 if (lasttoken == TELSE)
10647 n2->nif.elsepart = list(0);
10649 n2->nif.elsepart = NULL;
10657 n1 = stzalloc(sizeof(struct nbinary));
10658 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10659 n1->nbinary.ch1 = list(0);
10662 TRACE(("expecting DO got %s %s\n", tokname(got),
10663 got == TWORD ? wordtext : ""));
10664 raise_error_unexpected_syntax(TDO);
10666 n1->nbinary.ch2 = list(0);
10671 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10672 raise_error_syntax("bad for loop variable");
10673 n1 = stzalloc(sizeof(struct nfor));
10675 n1->nfor.var = wordtext;
10676 checkkwd = CHKKWD | CHKALIAS;
10677 if (readtoken() == TIN) {
10679 while (readtoken() == TWORD) {
10680 n2 = stzalloc(sizeof(struct narg));
10682 /*n2->narg.next = NULL; - stzalloc did it */
10683 n2->narg.text = wordtext;
10684 n2->narg.backquote = backquotelist;
10686 app = &n2->narg.next;
10689 n1->nfor.args = ap;
10690 if (lasttoken != TNL && lasttoken != TSEMI)
10691 raise_error_unexpected_syntax(-1);
10693 n2 = stzalloc(sizeof(struct narg));
10695 /*n2->narg.next = NULL; - stzalloc did it */
10696 n2->narg.text = (char *)dolatstr;
10697 /*n2->narg.backquote = NULL;*/
10698 n1->nfor.args = n2;
10700 * Newline or semicolon here is optional (but note
10701 * that the original Bourne shell only allowed NL).
10703 if (lasttoken != TNL && lasttoken != TSEMI)
10706 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10707 if (readtoken() != TDO)
10708 raise_error_unexpected_syntax(TDO);
10709 n1->nfor.body = list(0);
10713 n1 = stzalloc(sizeof(struct ncase));
10715 if (readtoken() != TWORD)
10716 raise_error_unexpected_syntax(TWORD);
10717 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10719 /*n2->narg.next = NULL; - stzalloc did it */
10720 n2->narg.text = wordtext;
10721 n2->narg.backquote = backquotelist;
10723 checkkwd = CHKKWD | CHKALIAS;
10724 } while (readtoken() == TNL);
10725 if (lasttoken != TIN)
10726 raise_error_unexpected_syntax(TIN);
10727 cpp = &n1->ncase.cases;
10729 checkkwd = CHKNL | CHKKWD;
10731 while (t != TESAC) {
10732 if (lasttoken == TLP)
10734 *cpp = cp = stzalloc(sizeof(struct nclist));
10736 app = &cp->nclist.pattern;
10738 *app = ap = stzalloc(sizeof(struct narg));
10740 /*ap->narg.next = NULL; - stzalloc did it */
10741 ap->narg.text = wordtext;
10742 ap->narg.backquote = backquotelist;
10743 if (readtoken() != TPIPE)
10745 app = &ap->narg.next;
10748 //ap->narg.next = NULL;
10749 if (lasttoken != TRP)
10750 raise_error_unexpected_syntax(TRP);
10751 cp->nclist.body = list(2);
10753 cpp = &cp->nclist.next;
10755 checkkwd = CHKNL | CHKKWD;
10759 raise_error_unexpected_syntax(TENDCASE);
10766 n1 = stzalloc(sizeof(struct nredir));
10767 n1->type = NSUBSHELL;
10768 n1->nredir.n = list(0);
10769 /*n1->nredir.redirect = NULL; - stzalloc did it */
10779 return simplecmd();
10782 if (readtoken() != t)
10783 raise_error_unexpected_syntax(t);
10786 /* Now check for redirection which may follow command */
10787 checkkwd = CHKKWD | CHKALIAS;
10789 while (readtoken() == TREDIR) {
10790 *rpp = n2 = redirnode;
10791 rpp = &n2->nfile.next;
10797 if (n1->type != NSUBSHELL) {
10798 n2 = stzalloc(sizeof(struct nredir));
10803 n1->nredir.redirect = redir;
10808 #if ENABLE_ASH_BASH_COMPAT
10809 static int decode_dollar_squote(void)
10811 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10817 p = strchr(C_escapes, c);
10822 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10826 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10828 } else if (c == 'x') { /* \xHH */
10832 } while (isxdigit(c) && --cnt);
10834 if (cnt == 3) { /* \x but next char is "bad" */
10838 } else { /* simple seq like \\ or \t */
10843 c = bb_process_escape_sequence((void*)&p);
10844 } else { /* unrecognized "\z": print both chars unless ' or " */
10845 if (c != '\'' && c != '"') {
10847 c |= 0x100; /* "please encode \, then me" */
10855 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10856 * is not NULL, read a here document. In the latter case, eofmark is the
10857 * word which marks the end of the document and striptabs is true if
10858 * leading tabs should be stripped from the document. The argument c
10859 * is the first character of the input token or document.
10861 * Because C does not have internal subroutines, I have simulated them
10862 * using goto's to implement the subroutine linkage. The following macros
10863 * will run code that appears at the end of readtoken1.
10865 #define CHECKEND() {goto checkend; checkend_return:;}
10866 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10867 #define PARSESUB() {goto parsesub; parsesub_return:;}
10868 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10869 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10870 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10872 readtoken1(int c, int syntax, char *eofmark, int striptabs)
10874 /* NB: syntax parameter fits into smallint */
10875 /* c parameter is an unsigned char or PEOF or PEOA */
10878 char line[EOFMARKLEN + 1];
10879 struct nodelist *bqlist;
10883 smallint prevsyntax; /* syntax before arithmetic */
10884 #if ENABLE_ASH_EXPAND_PRMT
10885 smallint pssyntax; /* we are expanding a prompt string */
10887 int varnest; /* levels of variables expansion */
10888 int arinest; /* levels of arithmetic expansion */
10889 int parenlevel; /* levels of parens in arithmetic */
10890 int dqvarnest; /* levels of variables expansion within double quotes */
10892 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10895 /* Avoid longjmp clobbering */
10901 (void) &parenlevel;
10904 (void) &prevsyntax;
10907 startlinno = g_parsefile->linno;
10912 #if ENABLE_ASH_EXPAND_PRMT
10913 pssyntax = (syntax == PSSYNTAX);
10917 dblquote = (syntax == DQSYNTAX);
10923 STARTSTACKSTR(out);
10925 /* For each line, until end of word */
10927 CHECKEND(); /* set c to PEOF if at end of here document */
10928 for (;;) { /* until end of line or end of word */
10929 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10930 switch (SIT(c, syntax)) {
10931 case CNL: /* '\n' */
10932 if (syntax == BASESYNTAX)
10933 goto endword; /* exit outer loop */
10935 g_parsefile->linno++;
10939 goto loop; /* continue outer loop */
10944 if (eofmark == NULL || dblquote)
10945 USTPUTC(CTLESC, out);
10946 #if ENABLE_ASH_BASH_COMPAT
10947 if (c == '\\' && bash_dollar_squote) {
10948 c = decode_dollar_squote();
10950 USTPUTC('\\', out);
10951 c = (unsigned char)c;
10957 case CBACK: /* backslash */
10958 c = pgetc_without_PEOA();
10960 USTPUTC(CTLESC, out);
10961 USTPUTC('\\', out);
10963 } else if (c == '\n') {
10967 #if ENABLE_ASH_EXPAND_PRMT
10968 if (c == '$' && pssyntax) {
10969 USTPUTC(CTLESC, out);
10970 USTPUTC('\\', out);
10973 if (dblquote && c != '\\'
10974 && c != '`' && c != '$'
10975 && (c != '"' || eofmark != NULL)
10977 USTPUTC(CTLESC, out);
10978 USTPUTC('\\', out);
10980 if (SIT(c, SQSYNTAX) == CCTL)
10981 USTPUTC(CTLESC, out);
10989 if (eofmark == NULL) {
10990 USTPUTC(CTLQUOTEMARK, out);
10998 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
10999 if (eofmark != NULL && arinest == 0
11004 if (dqvarnest == 0) {
11005 syntax = BASESYNTAX;
11012 case CVAR: /* '$' */
11013 PARSESUB(); /* parse substitution */
11015 case CENDVAR: /* '}' */
11018 if (dqvarnest > 0) {
11021 USTPUTC(CTLENDVAR, out);
11026 #if ENABLE_SH_MATH_SUPPORT
11027 case CLP: /* '(' in arithmetic */
11031 case CRP: /* ')' in arithmetic */
11032 if (parenlevel > 0) {
11036 if (pgetc() == ')') {
11037 if (--arinest == 0) {
11038 USTPUTC(CTLENDARI, out);
11039 syntax = prevsyntax;
11040 dblquote = (syntax == DQSYNTAX);
11045 * unbalanced parens
11046 * (don't 2nd guess - no error)
11054 case CBQUOTE: /* '`' */
11058 goto endword; /* exit outer loop */
11062 if (varnest == 0) {
11063 #if ENABLE_ASH_BASH_COMPAT
11065 if (pgetc() == '>')
11066 c = 0x100 + '>'; /* flag &> */
11070 goto endword; /* exit outer loop */
11072 IF_ASH_ALIAS(if (c != PEOA))
11080 #if ENABLE_SH_MATH_SUPPORT
11081 if (syntax == ARISYNTAX)
11082 raise_error_syntax("missing '))'");
11084 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11085 raise_error_syntax("unterminated quoted string");
11086 if (varnest != 0) {
11087 startlinno = g_parsefile->linno;
11089 raise_error_syntax("missing '}'");
11091 USTPUTC('\0', out);
11092 len = out - (char *)stackblock();
11093 out = stackblock();
11094 if (eofmark == NULL) {
11095 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11098 if (isdigit_str9(out)) {
11099 PARSEREDIR(); /* passed as params: out, c */
11100 lasttoken = TREDIR;
11103 /* else: non-number X seen, interpret it
11104 * as "NNNX>file" = "NNNX >file" */
11108 quoteflag = quotef;
11109 backquotelist = bqlist;
11110 grabstackblock(len);
11114 /* end of readtoken routine */
11117 * Check to see whether we are at the end of the here document. When this
11118 * is called, c is set to the first character of the next input line. If
11119 * we are at the end of the here document, this routine sets the c to PEOF.
11123 #if ENABLE_ASH_ALIAS
11125 c = pgetc_without_PEOA();
11128 while (c == '\t') {
11129 c = pgetc_without_PEOA();
11132 if (c == *eofmark) {
11133 if (pfgets(line, sizeof(line)) != NULL) {
11137 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11139 if (*p == '\n' && *q == '\0') {
11141 g_parsefile->linno++;
11142 needprompt = doprompt;
11144 pushstring(line, NULL);
11149 goto checkend_return;
11153 * Parse a redirection operator. The variable "out" points to a string
11154 * specifying the fd to be redirected. The variable "c" contains the
11155 * first character of the redirection operator.
11158 /* out is already checked to be a valid number or "" */
11159 int fd = (*out == '\0' ? -1 : atoi(out));
11162 np = stzalloc(sizeof(struct nfile));
11167 np->type = NAPPEND;
11169 np->type = NCLOBBER;
11172 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11178 #if ENABLE_ASH_BASH_COMPAT
11179 else if (c == 0x100 + '>') { /* this flags &> redirection */
11181 pgetc(); /* this is '>', no need to check */
11185 else { /* c == '<' */
11186 /*np->nfile.fd = 0; - stzalloc did it */
11190 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11191 np = stzalloc(sizeof(struct nhere));
11192 /*np->nfile.fd = 0; - stzalloc did it */
11195 heredoc = stzalloc(sizeof(struct heredoc));
11196 heredoc->here = np;
11199 heredoc->striptabs = 1;
11201 /*heredoc->striptabs = 0; - stzalloc did it */
11207 np->type = NFROMFD;
11211 np->type = NFROMTO;
11223 goto parseredir_return;
11227 * Parse a substitution. At this point, we have read the dollar sign
11228 * and nothing else.
11231 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11232 * (assuming ascii char codes, as the original implementation did) */
11233 #define is_special(c) \
11234 (((unsigned)(c) - 33 < 32) \
11235 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11237 unsigned char subtype;
11241 static const char types[] ALIGN1 = "}-+?=";
11244 if (c > 255 /* PEOA or PEOF */
11245 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11247 #if ENABLE_ASH_BASH_COMPAT
11249 bash_dollar_squote = 1;
11254 } else if (c == '(') { /* $(command) or $((arith)) */
11255 if (pgetc() == '(') {
11256 #if ENABLE_SH_MATH_SUPPORT
11259 raise_error_syntax("you disabled math support for $((arith)) syntax");
11266 USTPUTC(CTLVAR, out);
11267 typeloc = out - (char *)stackblock();
11268 USTPUTC(VSNORMAL, out);
11269 subtype = VSNORMAL;
11277 subtype = VSLENGTH;
11281 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11285 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11286 } else if (isdigit(c)) {
11290 } while (isdigit(c));
11291 } else if (is_special(c)) {
11296 raise_error_syntax("bad substitution");
11298 if (c != '}' && subtype == VSLENGTH)
11303 if (subtype == 0) {
11307 #if ENABLE_ASH_BASH_COMPAT
11308 if (c == ':' || c == '$' || isdigit(c)) {
11310 subtype = VSSUBSTR;
11317 p = strchr(types, c);
11320 subtype = p - types + VSNORMAL;
11325 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11333 #if ENABLE_ASH_BASH_COMPAT
11335 subtype = VSREPLACE;
11338 subtype++; /* VSREPLACEALL */
11347 if (dblquote || arinest)
11349 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11350 if (subtype != VSNORMAL) {
11352 if (dblquote || arinest) {
11357 goto parsesub_return;
11361 * Called to parse command substitutions. Newstyle is set if the command
11362 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11363 * list of commands (passed by reference), and savelen is the number of
11364 * characters on the top of the stack which must be preserved.
11367 struct nodelist **nlpp;
11370 char *volatile str;
11371 struct jmploc jmploc;
11372 struct jmploc *volatile savehandler;
11374 smallint saveprompt = 0;
11377 (void) &saveprompt;
11379 savepbq = parsebackquote;
11380 if (setjmp(jmploc.loc)) {
11382 parsebackquote = 0;
11383 exception_handler = savehandler;
11384 longjmp(exception_handler->loc, 1);
11388 savelen = out - (char *)stackblock();
11390 str = ckmalloc(savelen);
11391 memcpy(str, stackblock(), savelen);
11393 savehandler = exception_handler;
11394 exception_handler = &jmploc;
11397 /* We must read until the closing backquote, giving special
11398 treatment to some slashes, and then push the string and
11399 reread it as input, interpreting it normally. */
11406 STARTSTACKSTR(pout);
11419 g_parsefile->linno++;
11423 * If eating a newline, avoid putting
11424 * the newline into the new character
11425 * stream (via the STPUTC after the
11430 if (pc != '\\' && pc != '`' && pc != '$'
11431 && (!dblquote || pc != '"')
11433 STPUTC('\\', pout);
11435 if (pc <= 255 /* not PEOA or PEOF */) {
11441 IF_ASH_ALIAS(case PEOA:)
11442 startlinno = g_parsefile->linno;
11443 raise_error_syntax("EOF in backquote substitution");
11446 g_parsefile->linno++;
11447 needprompt = doprompt;
11456 STPUTC('\0', pout);
11457 psavelen = pout - (char *)stackblock();
11458 if (psavelen > 0) {
11459 pstr = grabstackstr(pout);
11460 setinputstring(pstr);
11465 nlpp = &(*nlpp)->next;
11466 *nlpp = stzalloc(sizeof(**nlpp));
11467 /* (*nlpp)->next = NULL; - stzalloc did it */
11468 parsebackquote = oldstyle;
11471 saveprompt = doprompt;
11478 doprompt = saveprompt;
11479 else if (readtoken() != TRP)
11480 raise_error_unexpected_syntax(TRP);
11485 * Start reading from old file again, ignoring any pushed back
11486 * tokens left from the backquote parsing
11491 while (stackblocksize() <= savelen)
11493 STARTSTACKSTR(out);
11495 memcpy(out, str, savelen);
11496 STADJUST(savelen, out);
11502 parsebackquote = savepbq;
11503 exception_handler = savehandler;
11504 if (arinest || dblquote)
11505 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11507 USTPUTC(CTLBACKQ, out);
11509 goto parsebackq_oldreturn;
11510 goto parsebackq_newreturn;
11513 #if ENABLE_SH_MATH_SUPPORT
11515 * Parse an arithmetic expansion (indicate start of one and set state)
11518 if (++arinest == 1) {
11519 prevsyntax = syntax;
11520 syntax = ARISYNTAX;
11521 USTPUTC(CTLARI, out);
11528 * we collapse embedded arithmetic expansion to
11529 * parenthesis, which should be equivalent
11533 goto parsearith_return;
11537 } /* end of readtoken */
11540 * Read the next input token.
11541 * If the token is a word, we set backquotelist to the list of cmds in
11542 * backquotes. We set quoteflag to true if any part of the word was
11544 * If the token is TREDIR, then we set redirnode to a structure containing
11546 * In all cases, the variable startlinno is set to the number of the line
11547 * on which the token starts.
11549 * [Change comment: here documents and internal procedures]
11550 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11551 * word parsing code into a separate routine. In this case, readtoken
11552 * doesn't need to have any internal procedures, but parseword does.
11553 * We could also make parseoperator in essence the main routine, and
11554 * have parseword (readtoken1?) handle both words and redirection.]
11556 #define NEW_xxreadtoken
11557 #ifdef NEW_xxreadtoken
11558 /* singles must be first! */
11559 static const char xxreadtoken_chars[7] ALIGN1 = {
11560 '\n', '(', ')', /* singles */
11561 '&', '|', ';', /* doubles */
11565 #define xxreadtoken_singles 3
11566 #define xxreadtoken_doubles 3
11568 static const char xxreadtoken_tokens[] ALIGN1 = {
11569 TNL, TLP, TRP, /* only single occurrence allowed */
11570 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11571 TEOF, /* corresponds to trailing nul */
11572 TAND, TOR, TENDCASE /* if double occurrence */
11587 startlinno = g_parsefile->linno;
11588 for (;;) { /* until token or start of word found */
11590 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11594 while ((c = pgetc()) != '\n' && c != PEOF)
11597 } else if (c == '\\') {
11598 if (pgetc() != '\n') {
11600 break; /* return readtoken1(...) */
11602 startlinno = ++g_parsefile->linno;
11608 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11611 g_parsefile->linno++;
11612 needprompt = doprompt;
11615 p = strchr(xxreadtoken_chars, c);
11617 break; /* return readtoken1(...) */
11619 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11621 if (cc == c) { /* double occurrence? */
11622 p += xxreadtoken_doubles + 1;
11625 #if ENABLE_ASH_BASH_COMPAT
11626 if (c == '&' && cc == '>') /* &> */
11627 break; /* return readtoken1(...) */
11632 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11637 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11639 #else /* old xxreadtoken */
11640 #define RETURN(token) return lasttoken = token
11653 startlinno = g_parsefile->linno;
11654 for (;;) { /* until token or start of word found */
11657 case ' ': case '\t':
11658 IF_ASH_ALIAS(case PEOA:)
11661 while ((c = pgetc()) != '\n' && c != PEOF)
11666 if (pgetc() == '\n') {
11667 startlinno = ++g_parsefile->linno;
11675 g_parsefile->linno++;
11676 needprompt = doprompt;
11681 if (pgetc() == '&')
11686 if (pgetc() == '|')
11691 if (pgetc() == ';')
11704 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11707 #endif /* old xxreadtoken */
11714 smallint alreadyseen = tokpushback;
11717 #if ENABLE_ASH_ALIAS
11726 if (checkkwd & CHKNL) {
11733 if (t != TWORD || quoteflag) {
11738 * check for keywords
11740 if (checkkwd & CHKKWD) {
11741 const char *const *pp;
11743 pp = findkwd(wordtext);
11745 lasttoken = t = pp - tokname_array;
11746 TRACE(("keyword %s recognized\n", tokname(t)));
11751 if (checkkwd & CHKALIAS) {
11752 #if ENABLE_ASH_ALIAS
11754 ap = lookupalias(wordtext, 1);
11757 pushstring(ap->val, ap);
11767 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11769 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11781 return tokname_array[t][0];
11785 * Read and parse a command. Returns NODE_EOF on end of file.
11786 * (NULL is a valid parse tree indicating a blank line.)
11788 static union node *
11789 parsecmd(int interact)
11794 doprompt = interact;
11796 setprompt(doprompt);
11808 * Input any here documents.
11813 struct heredoc *here;
11816 here = heredoclist;
11817 heredoclist = NULL;
11823 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11824 here->eofmark, here->striptabs);
11825 n = stzalloc(sizeof(struct narg));
11826 n->narg.type = NARG;
11827 /*n->narg.next = NULL; - stzalloc did it */
11828 n->narg.text = wordtext;
11829 n->narg.backquote = backquotelist;
11830 here->here->nhere.doc = n;
11837 * called by editline -- any expansions to the prompt should be added here.
11839 #if ENABLE_ASH_EXPAND_PRMT
11840 static const char *
11841 expandstr(const char *ps)
11845 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11846 * and token processing _can_ alter it (delete NULs etc). */
11847 setinputstring((char *)ps);
11848 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11851 n.narg.type = NARG;
11852 n.narg.next = NULL;
11853 n.narg.text = wordtext;
11854 n.narg.backquote = backquotelist;
11856 expandarg(&n, NULL, 0);
11857 return stackblock();
11862 * Execute a command or commands contained in a string.
11865 evalstring(char *s, int mask)
11868 struct stackmark smark;
11872 setstackmark(&smark);
11875 while ((n = parsecmd(0)) != NODE_EOF) {
11877 popstackmark(&smark);
11890 * The eval command.
11892 static int FAST_FUNC
11893 evalcmd(int argc UNUSED_PARAM, char **argv)
11902 STARTSTACKSTR(concat);
11904 concat = stack_putstr(p, concat);
11908 STPUTC(' ', concat);
11910 STPUTC('\0', concat);
11911 p = grabstackstr(concat);
11913 evalstring(p, ~SKIPEVAL);
11920 * Read and execute commands.
11921 * "Top" is nonzero for the top level command loop;
11922 * it turns on prompting if the shell is interactive.
11928 struct stackmark smark;
11932 TRACE(("cmdloop(%d) called\n", top));
11936 setstackmark(&smark);
11939 showjobs(stderr, SHOW_CHANGED);
11942 if (iflag && top) {
11944 #if ENABLE_ASH_MAIL
11948 n = parsecmd(inter);
11950 if (DEBUG > 2 && debug && (n != NODE_EOF))
11953 if (n == NODE_EOF) {
11954 if (!top || numeof >= 50)
11956 if (!stoppedjobs()) {
11959 out2str("\nUse \"exit\" to leave shell.\n");
11962 } else if (nflag == 0) {
11963 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11968 popstackmark(&smark);
11973 return skip & SKIPEVAL;
11980 * Take commands from a file. To be compatible we should do a path
11981 * search for the file, which is necessary to find sub-commands.
11984 find_dot_file(char *name)
11987 const char *path = pathval();
11990 /* don't try this for absolute or relative paths */
11991 if (strchr(name, '/'))
11994 /* IIRC standards do not say whether . is to be searched.
11995 * And it is even smaller this way, making it unconditional for now:
11997 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12002 while ((fullname = path_advance(&path, name)) != NULL) {
12004 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12006 * Don't bother freeing here, since it will
12007 * be freed by the caller.
12011 if (fullname != name)
12012 stunalloc(fullname);
12015 /* not found in the PATH */
12016 ash_msg_and_raise_error("%s: not found", name);
12020 static int FAST_FUNC
12021 dotcmd(int argc, char **argv)
12023 struct strlist *sp;
12024 volatile struct shparam saveparam;
12027 for (sp = cmdenviron; sp; sp = sp->next)
12028 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12030 if (argv[1]) { /* That's what SVR2 does */
12031 char *fullname = find_dot_file(argv[1]);
12034 if (argc) { /* argc > 0, argv[0] != NULL */
12035 saveparam = shellparam;
12036 shellparam.malloced = 0;
12037 shellparam.nparam = argc;
12038 shellparam.p = argv;
12041 setinputfile(fullname, INPUT_PUSH_FILE);
12042 commandname = fullname;
12047 freeparam(&shellparam);
12048 shellparam = saveparam;
12050 status = exitstatus;
12055 static int FAST_FUNC
12056 exitcmd(int argc UNUSED_PARAM, char **argv)
12061 exitstatus = number(argv[1]);
12062 raise_exception(EXEXIT);
12067 * Read a file containing shell functions.
12070 readcmdfile(char *name)
12072 setinputfile(name, INPUT_PUSH_FILE);
12078 /* ============ find_command inplementation */
12081 * Resolve a command name. If you change this routine, you may have to
12082 * change the shellexec routine as well.
12085 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12087 struct tblentry *cmdp;
12094 struct builtincmd *bcmd;
12096 /* If name contains a slash, don't use PATH or hash table */
12097 if (strchr(name, '/') != NULL) {
12098 entry->u.index = -1;
12099 if (act & DO_ABS) {
12100 while (stat(name, &statb) < 0) {
12102 if (errno == EINTR)
12105 entry->cmdtype = CMDUNKNOWN;
12109 entry->cmdtype = CMDNORMAL;
12113 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12115 updatetbl = (path == pathval());
12118 if (strstr(path, "%builtin") != NULL)
12119 act |= DO_ALTBLTIN;
12122 /* If name is in the table, check answer will be ok */
12123 cmdp = cmdlookup(name, 0);
12124 if (cmdp != NULL) {
12127 switch (cmdp->cmdtype) {
12145 } else if (cmdp->rehash == 0)
12146 /* if not invalidated by cd, we're done */
12150 /* If %builtin not in path, check for builtin next */
12151 bcmd = find_builtin(name);
12153 if (IS_BUILTIN_REGULAR(bcmd))
12154 goto builtin_success;
12155 if (act & DO_ALTPATH) {
12156 if (!(act & DO_ALTBLTIN))
12157 goto builtin_success;
12158 } else if (builtinloc <= 0) {
12159 goto builtin_success;
12163 #if ENABLE_FEATURE_SH_STANDALONE
12165 int applet_no = find_applet_by_name(name);
12166 if (applet_no >= 0) {
12167 entry->cmdtype = CMDNORMAL;
12168 entry->u.index = -2 - applet_no;
12174 /* We have to search path. */
12175 prev = -1; /* where to start */
12176 if (cmdp && cmdp->rehash) { /* doing a rehash */
12177 if (cmdp->cmdtype == CMDBUILTIN)
12180 prev = cmdp->param.index;
12186 while ((fullname = path_advance(&path, name)) != NULL) {
12187 stunalloc(fullname);
12188 /* NB: code below will still use fullname
12189 * despite it being "unallocated" */
12192 if (prefix(pathopt, "builtin")) {
12194 goto builtin_success;
12197 if ((act & DO_NOFUNC)
12198 || !prefix(pathopt, "func")
12199 ) { /* ignore unimplemented options */
12203 /* if rehash, don't redo absolute path names */
12204 if (fullname[0] == '/' && idx <= prev) {
12207 TRACE(("searchexec \"%s\": no change\n", name));
12210 while (stat(fullname, &statb) < 0) {
12212 if (errno == EINTR)
12215 if (errno != ENOENT && errno != ENOTDIR)
12219 e = EACCES; /* if we fail, this will be the error */
12220 if (!S_ISREG(statb.st_mode))
12222 if (pathopt) { /* this is a %func directory */
12223 stalloc(strlen(fullname) + 1);
12224 /* NB: stalloc will return space pointed by fullname
12225 * (because we don't have any intervening allocations
12226 * between stunalloc above and this stalloc) */
12227 readcmdfile(fullname);
12228 cmdp = cmdlookup(name, 0);
12229 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12230 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12231 stunalloc(fullname);
12234 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12236 entry->cmdtype = CMDNORMAL;
12237 entry->u.index = idx;
12241 cmdp = cmdlookup(name, 1);
12242 cmdp->cmdtype = CMDNORMAL;
12243 cmdp->param.index = idx;
12248 /* We failed. If there was an entry for this command, delete it */
12249 if (cmdp && updatetbl)
12250 delete_cmd_entry();
12252 ash_msg("%s: %s", name, errmsg(e, "not found"));
12253 entry->cmdtype = CMDUNKNOWN;
12258 entry->cmdtype = CMDBUILTIN;
12259 entry->u.cmd = bcmd;
12263 cmdp = cmdlookup(name, 1);
12264 cmdp->cmdtype = CMDBUILTIN;
12265 cmdp->param.cmd = bcmd;
12269 entry->cmdtype = cmdp->cmdtype;
12270 entry->u = cmdp->param;
12274 /* ============ trap.c */
12277 * The trap builtin.
12279 static int FAST_FUNC
12280 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12289 for (signo = 0; signo < NSIG; signo++) {
12290 char *tr = trap_ptr[signo];
12292 /* note: bash adds "SIG", but only if invoked
12293 * as "bash". If called as "sh", or if set -o posix,
12294 * then it prints short signal names.
12295 * We are printing short names: */
12296 out1fmt("trap -- %s %s\n",
12298 get_signame(signo));
12299 /* trap_ptr != trap only if we are in special-cased `trap` code.
12300 * In this case, we will exit very soon, no need to free(). */
12301 /* if (trap_ptr != trap && tp[0]) */
12306 if (trap_ptr != trap) {
12318 signo = get_signum(*ap);
12320 ash_msg_and_raise_error("%s: bad trap", *ap);
12323 if (LONE_DASH(action))
12326 action = ckstrdup(action);
12329 trap[signo] = action;
12339 /* ============ Builtins */
12341 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12343 * Lists available builtins
12345 static int FAST_FUNC
12346 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12352 "Built-in commands:\n"
12353 "------------------\n");
12354 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12355 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12356 builtintab[i].name + 1);
12362 #if ENABLE_FEATURE_SH_STANDALONE
12364 const char *a = applet_names;
12366 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12371 a += strlen(a) + 1;
12376 return EXIT_SUCCESS;
12378 #endif /* FEATURE_SH_EXTRA_QUIET */
12381 * The export and readonly commands.
12383 static int FAST_FUNC
12384 exportcmd(int argc UNUSED_PARAM, char **argv)
12390 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12392 if (nextopt("p") != 'p') {
12397 p = strchr(name, '=');
12401 vp = *findvar(hashvar(name), name);
12407 setvar(name, p, flag);
12408 } while ((name = *++aptr) != NULL);
12412 showvars(argv[0], flag, 0);
12417 * Delete a function if it exists.
12420 unsetfunc(const char *name)
12422 struct tblentry *cmdp;
12424 cmdp = cmdlookup(name, 0);
12425 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12426 delete_cmd_entry();
12430 * The unset builtin command. We unset the function before we unset the
12431 * variable to allow a function to be unset when there is a readonly variable
12432 * with the same name.
12434 static int FAST_FUNC
12435 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12442 while ((i = nextopt("vf")) != '\0') {
12446 for (ap = argptr; *ap; ap++) {
12462 #include <sys/times.h>
12464 static const unsigned char timescmd_str[] ALIGN1 = {
12465 ' ', offsetof(struct tms, tms_utime),
12466 '\n', offsetof(struct tms, tms_stime),
12467 ' ', offsetof(struct tms, tms_cutime),
12468 '\n', offsetof(struct tms, tms_cstime),
12472 static int FAST_FUNC
12473 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12475 long clk_tck, s, t;
12476 const unsigned char *p;
12479 clk_tck = sysconf(_SC_CLK_TCK);
12484 t = *(clock_t *)(((char *) &buf) + p[1]);
12486 out1fmt("%ldm%ld.%.3lds%c",
12488 ((t - s * clk_tck) * 1000) / clk_tck,
12490 } while (*(p += 2));
12495 #if ENABLE_SH_MATH_SUPPORT
12497 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12498 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12500 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12502 static int FAST_FUNC
12503 letcmd(int argc UNUSED_PARAM, char **argv)
12509 ash_msg_and_raise_error("expression expected");
12511 i = ash_arith(*argv);
12516 #endif /* SH_MATH_SUPPORT */
12519 /* ============ miscbltin.c
12521 * Miscellaneous builtins.
12526 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
12527 typedef enum __rlimit_resource rlim_t;
12531 * The read builtin. Options:
12532 * -r Do not interpret '\' specially
12533 * -s Turn off echo (tty only)
12534 * -n NCHARS Read NCHARS max
12535 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12536 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12537 * -u FD Read from given FD instead of fd 0
12538 * This uses unbuffered input, which may be avoidable in some cases.
12539 * TODO: bash also has:
12540 * -a ARRAY Read into array[0],[1],etc
12541 * -d DELIM End on DELIM char, not newline
12542 * -e Use line editing (tty only)
12544 static int FAST_FUNC
12545 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12547 char *opt_n = NULL;
12548 char *opt_p = NULL;
12549 char *opt_t = NULL;
12550 char *opt_u = NULL;
12551 int read_flags = 0;
12555 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12564 read_flags |= BUILTIN_READ_SILENT;
12570 read_flags |= BUILTIN_READ_RAW;
12580 r = shell_builtin_read(setvar2,
12582 bltinlookup("IFS"), /* can be NULL */
12590 if ((uintptr_t)r > 1)
12591 ash_msg_and_raise_error(r);
12593 return (uintptr_t)r;
12596 static int FAST_FUNC
12597 umaskcmd(int argc UNUSED_PARAM, char **argv)
12599 static const char permuser[3] ALIGN1 = "ugo";
12600 static const char permmode[3] ALIGN1 = "rwx";
12601 static const short permmask[] ALIGN2 = {
12602 S_IRUSR, S_IWUSR, S_IXUSR,
12603 S_IRGRP, S_IWGRP, S_IXGRP,
12604 S_IROTH, S_IWOTH, S_IXOTH
12607 /* TODO: use bb_parse_mode() instead */
12612 int symbolic_mode = 0;
12614 while (nextopt("S") != '\0') {
12625 if (symbolic_mode) {
12629 for (i = 0; i < 3; i++) {
12632 *p++ = permuser[i];
12634 for (j = 0; j < 3; j++) {
12635 if ((mask & permmask[3 * i + j]) == 0) {
12636 *p++ = permmode[j];
12644 out1fmt("%.4o\n", mask);
12647 if (isdigit((unsigned char) *ap)) {
12650 if (*ap >= '8' || *ap < '0')
12651 ash_msg_and_raise_error(msg_illnum, argv[1]);
12652 mask = (mask << 3) + (*ap - '0');
12653 } while (*++ap != '\0');
12656 mask = ~mask & 0777;
12657 if (!bb_parse_mode(ap, &mask)) {
12658 ash_msg_and_raise_error("illegal mode: %s", ap);
12660 umask(~mask & 0777);
12666 static int FAST_FUNC
12667 ulimitcmd(int argc UNUSED_PARAM, char **argv)
12669 return shell_builtin_ulimit(argv);
12672 /* ============ main() and helpers */
12675 * Called to exit the shell.
12677 static void exitshell(void) NORETURN;
12685 status = exitstatus;
12686 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12687 if (setjmp(loc.loc)) {
12688 if (exception_type == EXEXIT)
12689 /* dash bug: it just does _exit(exitstatus) here
12690 * but we have to do setjobctl(0) first!
12691 * (bug is still not fixed in dash-0.5.3 - if you run dash
12692 * under Midnight Commander, on exit from dash MC is backgrounded) */
12693 status = exitstatus;
12696 exception_handler = &loc;
12703 flush_stdout_stderr();
12713 /* from input.c: */
12714 basepf.next_to_pgetc = basepf.buf = basebuf;
12717 signal(SIGCHLD, SIG_DFL);
12718 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12719 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12721 signal(SIGHUP, SIG_DFL);
12727 struct stat st1, st2;
12730 for (envp = environ; envp && *envp; envp++) {
12731 if (strchr(*envp, '=')) {
12732 setvareq(*envp, VEXPORT|VTEXTFIXED);
12736 setvar("PPID", utoa(getppid()), 0);
12738 p = lookupvar("PWD");
12740 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12741 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12748 * Process the shell command line arguments.
12751 procargs(char **argv)
12754 const char *xminusc;
12759 /* if (xargv[0]) - mmm, this is always true! */
12761 for (i = 0; i < NOPTS; i++)
12765 /* it already printed err message */
12766 raise_exception(EXERROR);
12770 if (*xargv == NULL) {
12772 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12775 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12779 for (i = 0; i < NOPTS; i++)
12780 if (optlist[i] == 2)
12785 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12790 } else if (!sflag) {
12791 setinputfile(*xargv, 0);
12794 commandname = arg0;
12797 shellparam.p = xargv;
12798 #if ENABLE_ASH_GETOPTS
12799 shellparam.optind = 1;
12800 shellparam.optoff = -1;
12802 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
12804 shellparam.nparam++;
12811 * Read /etc/profile or .profile.
12814 read_profile(const char *name)
12818 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12827 * This routine is called when an error or an interrupt occurs in an
12828 * interactive shell and control is returned to the main command loop.
12836 /* from input.c: */
12837 g_parsefile->left_in_buffer = 0;
12838 g_parsefile->left_in_line = 0; /* clear input buffer */
12840 /* from parser.c: */
12843 /* from redir.c: */
12844 clearredir(/*drop:*/ 0);
12848 static short profile_buf[16384];
12849 extern int etext();
12853 * Main routine. We initialize things, parse the arguments, execute
12854 * profiles if we're a login shell, and then call cmdloop to execute
12855 * commands. The setjmp call sets up the location to jump to when an
12856 * exception occurs. When an exception occurs the variable "state"
12857 * is used to figure out how far we had gotten.
12859 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
12860 int ash_main(int argc UNUSED_PARAM, char **argv)
12862 const char *shinit;
12863 volatile smallint state;
12864 struct jmploc jmploc;
12865 struct stackmark smark;
12867 /* Initialize global data */
12871 #if ENABLE_ASH_ALIAS
12877 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12880 #if ENABLE_FEATURE_EDITING
12881 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12884 if (setjmp(jmploc.loc)) {
12890 e = exception_type;
12894 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12897 outcslow('\n', stderr);
12899 popstackmark(&smark);
12900 FORCE_INT_ON; /* enable interrupts */
12909 exception_handler = &jmploc;
12912 TRACE(("Shell args: "));
12913 trace_puts_args(argv);
12915 rootpid = getpid();
12918 setstackmark(&smark);
12921 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
12923 const char *hp = lookupvar("HISTFILE");
12926 hp = lookupvar("HOME");
12928 char *defhp = concat_path_file(hp, ".ash_history");
12929 setvar("HISTFILE", defhp, 0);
12935 if (/* argv[0] && */ argv[0][0] == '-')
12939 read_profile("/etc/profile");
12942 read_profile(".profile");
12948 getuid() == geteuid() && getgid() == getegid() &&
12952 shinit = lookupvar("ENV");
12953 if (shinit != NULL && *shinit != '\0') {
12954 read_profile(shinit);
12960 /* evalstring pushes parsefile stack.
12961 * Ensure we don't falsely claim that 0 (stdin)
12962 * is one of stacked source fds.
12963 * Testcase: ash -c 'exec 1>&0' must not complain. */
12965 g_parsefile->fd = -1;
12966 evalstring(minusc, 0);
12969 if (sflag || minusc == NULL) {
12970 #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
12972 const char *hp = lookupvar("HISTFILE");
12974 line_input_state->hist_file = hp;
12977 state4: /* XXX ??? - why isn't this before the "if" statement */
12985 extern void _mcleanup(void);
12995 * Copyright (c) 1989, 1991, 1993, 1994
12996 * The Regents of the University of California. All rights reserved.
12998 * This code is derived from software contributed to Berkeley by
12999 * Kenneth Almquist.
13001 * Redistribution and use in source and binary forms, with or without
13002 * modification, are permitted provided that the following conditions
13004 * 1. Redistributions of source code must retain the above copyright
13005 * notice, this list of conditions and the following disclaimer.
13006 * 2. Redistributions in binary form must reproduce the above copyright
13007 * notice, this list of conditions and the following disclaimer in the
13008 * documentation and/or other materials provided with the distribution.
13009 * 3. Neither the name of the University nor the names of its contributors
13010 * may be used to endorse or promote products derived from this software
13011 * without specific prior written permission.
13013 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13014 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13015 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13016 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13017 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13018 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13019 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13020 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13021 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13022 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF