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 */
49 #include <sys/times.h>
51 #include "shell_common.h"
53 #if ENABLE_ASH_RANDOM_SUPPORT
56 # define CLEAR_RANDOM_T(rnd) ((void)0)
59 #define SKIP_definitions 1
60 #include "applet_tables.h"
61 #undef SKIP_definitions
63 /* STANDALONE does not make sense, and won't compile */
64 # undef CONFIG_FEATURE_SH_STANDALONE
65 # undef ENABLE_FEATURE_SH_STANDALONE
66 # undef IF_FEATURE_SH_STANDALONE
67 # undef IF_NOT_FEATURE_SH_STANDALONE
68 # define ENABLE_FEATURE_SH_STANDALONE 0
69 # define IF_FEATURE_SH_STANDALONE(...)
70 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
74 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
78 # error "Do not even bother, ash will not run on NOMMU machine"
82 /* ============ Hash table sizes. Configurable. */
86 #define CMDTABLESIZE 31 /* should be prime */
89 /* ============ Shell options */
91 static const char *const optletters_optnames[] = {
106 #if ENABLE_ASH_BASH_COMPAT
115 #define optletters(n) optletters_optnames[n][0]
116 #define optnames(n) (optletters_optnames[n] + 1)
118 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
121 /* ============ Misc data */
123 #define msg_illnum "Illegal number: %s"
126 * We enclose jmp_buf in a structure so that we can declare pointers to
127 * jump locations. The global variable handler contains the location to
128 * jump to when an exception occurs, and the global variable exception_type
129 * contains a code identifying the exception. To implement nested
130 * exception handlers, the user should save the value of handler on entry
131 * to an inner scope, set handler to point to a jmploc structure for the
132 * inner scope, and restore handler on exit from the scope.
138 struct globals_misc {
139 /* pid of main shell */
141 /* shell level: 0 for the main shell, 1 for its children, and so on */
143 #define rootshell (!shlvl)
144 char *minusc; /* argument to -c option */
146 char *curdir; // = nullstr; /* current working directory */
147 char *physdir; // = nullstr; /* physical working directory */
149 char *arg0; /* value of $0 */
151 struct jmploc *exception_handler;
153 volatile int suppress_int; /* counter */
154 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
155 /* last pending signal */
156 volatile /*sig_atomic_t*/ smallint pending_sig;
157 smallint exception_type; /* kind of exception (0..5) */
159 #define EXINT 0 /* SIGINT received */
160 #define EXERROR 1 /* a generic error */
161 #define EXSHELLPROC 2 /* execute a shell procedure */
162 #define EXEXEC 3 /* command execution failed */
163 #define EXEXIT 4 /* exit the shell */
164 #define EXSIG 5 /* trapped signal in wait(1) */
167 char nullstr[1]; /* zero length string */
170 #define eflag optlist[0]
171 #define fflag optlist[1]
172 #define Iflag optlist[2]
173 #define iflag optlist[3]
174 #define mflag optlist[4]
175 #define nflag optlist[5]
176 #define sflag optlist[6]
177 #define xflag optlist[7]
178 #define vflag optlist[8]
179 #define Cflag optlist[9]
180 #define aflag optlist[10]
181 #define bflag optlist[11]
182 #define uflag optlist[12]
183 #define viflag optlist[13]
184 #if ENABLE_ASH_BASH_COMPAT
185 # define pipefail optlist[14]
190 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
191 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
194 /* trap handler commands */
196 * Sigmode records the current value of the signal handlers for the various
197 * modes. A value of zero means that the current handler is not known.
198 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
200 char sigmode[NSIG - 1];
201 #define S_DFL 1 /* default signal handling (SIG_DFL) */
202 #define S_CATCH 2 /* signal is caught */
203 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
204 #define S_HARD_IGN 4 /* signal is ignored permenantly */
206 /* indicates specified signal received */
207 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
208 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
210 char **trap_ptr; /* used only by "trap hack" */
212 /* Rarely referenced stuff */
213 #if ENABLE_ASH_RANDOM_SUPPORT
216 pid_t backgndpid; /* pid of last background process */
217 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
219 extern struct globals_misc *const ash_ptr_to_globals_misc;
220 #define G_misc (*ash_ptr_to_globals_misc)
221 #define rootpid (G_misc.rootpid )
222 #define shlvl (G_misc.shlvl )
223 #define minusc (G_misc.minusc )
224 #define curdir (G_misc.curdir )
225 #define physdir (G_misc.physdir )
226 #define arg0 (G_misc.arg0 )
227 #define exception_handler (G_misc.exception_handler)
228 #define exception_type (G_misc.exception_type )
229 #define suppress_int (G_misc.suppress_int )
230 #define pending_int (G_misc.pending_int )
231 #define pending_sig (G_misc.pending_sig )
232 #define isloginsh (G_misc.isloginsh )
233 #define nullstr (G_misc.nullstr )
234 #define optlist (G_misc.optlist )
235 #define sigmode (G_misc.sigmode )
236 #define gotsig (G_misc.gotsig )
237 #define may_have_traps (G_misc.may_have_traps )
238 #define trap (G_misc.trap )
239 #define trap_ptr (G_misc.trap_ptr )
240 #define random_gen (G_misc.random_gen )
241 #define backgndpid (G_misc.backgndpid )
242 #define job_warning (G_misc.job_warning)
243 #define INIT_G_misc() do { \
244 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
252 /* ============ DEBUG */
254 static void trace_printf(const char *fmt, ...);
255 static void trace_vprintf(const char *fmt, va_list va);
256 # define TRACE(param) trace_printf param
257 # define TRACEV(param) trace_vprintf param
258 # define close(fd) do { \
260 if (close(dfd) < 0) \
261 bb_error_msg("bug on %d: closing %d(0x%x)", \
262 __LINE__, dfd, dfd); \
265 # define TRACE(param)
266 # define TRACEV(param)
270 /* ============ Utility functions */
271 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
273 static int isdigit_str9(const char *str)
275 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
276 while (--maxlen && isdigit(*str))
278 return (*str == '\0');
281 static const char *var_end(const char *var)
290 /* ============ Interrupts / exceptions */
292 * These macros allow the user to suspend the handling of interrupt signals
293 * over a period of time. This is similar to SIGHOLD or to sigblock, but
294 * much more efficient and portable. (But hacking the kernel is so much
295 * more fun than worrying about efficiency and portability. :-))
297 #define INT_OFF do { \
303 * Called to raise an exception. Since C doesn't include exceptions, we
304 * just do a longjmp to the exception handler. The type of exception is
305 * stored in the global variable "exception_type".
307 static void raise_exception(int) NORETURN;
309 raise_exception(int e)
312 if (exception_handler == NULL)
317 longjmp(exception_handler->loc, 1);
320 #define raise_exception(e) do { \
321 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
322 raise_exception(e); \
327 * Called from trap.c when a SIGINT is received. (If the user specifies
328 * that SIGINT is to be trapped or ignored using the trap builtin, then
329 * this routine is not called.) Suppressint is nonzero when interrupts
330 * are held using the INT_OFF macro. (The test for iflag is just
331 * defensive programming.)
333 static void raise_interrupt(void) NORETURN;
335 raise_interrupt(void)
340 /* Signal is not automatically unmasked after it is raised,
341 * do it ourself - unmask all signals */
342 sigprocmask_allsigs(SIG_UNBLOCK);
343 /* pending_sig = 0; - now done in signal_handler() */
346 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
347 if (!(rootshell && iflag)) {
348 /* Kill ourself with SIGINT */
349 signal(SIGINT, SIG_DFL);
354 raise_exception(ex_type);
358 #define raise_interrupt() do { \
359 TRACE(("raising interrupt on line %d\n", __LINE__)); \
364 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
368 if (--suppress_int == 0 && pending_int) {
372 #define INT_ON int_on()
373 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
381 #define FORCE_INT_ON force_int_on()
383 #define SAVE_INT(v) ((v) = suppress_int)
385 #define RESTORE_INT(v) do { \
387 suppress_int = (v); \
388 if (suppress_int == 0 && pending_int) \
393 /* ============ Stdout/stderr output */
396 outstr(const char *p, FILE *file)
404 flush_stdout_stderr(void)
412 outcslow(int c, FILE *dest)
420 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
422 out1fmt(const char *fmt, ...)
429 r = vprintf(fmt, ap);
435 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
437 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
444 ret = vsnprintf(outbuf, length, fmt, ap);
451 out1str(const char *p)
457 out2str(const char *p)
460 flush_stdout_stderr();
464 /* ============ Parser structures */
466 /* control characters in argument strings */
467 #define CTL_FIRST CTLESC
468 #define CTLESC ((unsigned char)'\201') /* escape next character */
469 #define CTLVAR ((unsigned char)'\202') /* variable defn */
470 #define CTLENDVAR ((unsigned char)'\203')
471 #define CTLBACKQ ((unsigned char)'\204')
472 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
473 /* CTLBACKQ | CTLQUOTE == '\205' */
474 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
475 #define CTLENDARI ((unsigned char)'\207')
476 #define CTLQUOTEMARK ((unsigned char)'\210')
477 #define CTL_LAST CTLQUOTEMARK
479 /* variable substitution byte (follows CTLVAR) */
480 #define VSTYPE 0x0f /* type of variable substitution */
481 #define VSNUL 0x10 /* colon--treat the empty string as unset */
482 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
484 /* values of VSTYPE field */
485 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
486 #define VSMINUS 0x2 /* ${var-text} */
487 #define VSPLUS 0x3 /* ${var+text} */
488 #define VSQUESTION 0x4 /* ${var?message} */
489 #define VSASSIGN 0x5 /* ${var=text} */
490 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
491 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
492 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
493 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
494 #define VSLENGTH 0xa /* ${#var} */
495 #if ENABLE_ASH_BASH_COMPAT
496 #define VSSUBSTR 0xc /* ${var:position:length} */
497 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
498 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
501 static const char dolatstr[] ALIGN1 = {
502 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
522 #if ENABLE_ASH_BASH_COMPAT
539 smallint type; /* Nxxxx */
542 union node *redirect;
547 smallint pipe_backgnd;
548 struct nodelist *cmdlist;
554 union node *redirect;
567 union node *elsepart;
594 struct nodelist *backquote;
597 /* nfile and ndup layout must match!
598 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
599 * that it is actually NTO2 (>&file), and change its type.
616 char *_unused_expfname;
635 struct nredir nredir;
636 struct nbinary nbinary;
640 struct nclist nclist;
649 * NODE_EOF is returned by parsecmd when it encounters an end of file.
650 * It must be distinct from NULL.
652 #define NODE_EOF ((union node *) -1L)
655 struct nodelist *next;
668 freefunc(struct funcnode *f)
670 if (f && --f->count < 0)
675 /* ============ Debugging output */
679 static FILE *tracefile;
682 trace_printf(const char *fmt, ...)
689 fprintf(tracefile, "%u ", (int) time(NULL));
691 fprintf(tracefile, "[%u] ", (int) getpid());
693 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
695 vfprintf(tracefile, fmt, va);
700 trace_vprintf(const char *fmt, va_list va)
705 fprintf(tracefile, "%u ", (int) time(NULL));
707 fprintf(tracefile, "[%u] ", (int) getpid());
709 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
710 vfprintf(tracefile, fmt, va);
714 trace_puts(const char *s)
722 trace_puts_quoted(char *s)
729 putc('"', tracefile);
730 for (p = s; *p; p++) {
731 switch ((unsigned char)*p) {
732 case '\n': c = 'n'; goto backslash;
733 case '\t': c = 't'; goto backslash;
734 case '\r': c = 'r'; goto backslash;
735 case '\"': c = '\"'; goto backslash;
736 case '\\': c = '\\'; goto backslash;
737 case CTLESC: c = 'e'; goto backslash;
738 case CTLVAR: c = 'v'; goto backslash;
739 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
740 case CTLBACKQ: c = 'q'; goto backslash;
741 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
743 putc('\\', tracefile);
747 if (*p >= ' ' && *p <= '~')
750 putc('\\', tracefile);
751 putc((*p >> 6) & 03, tracefile);
752 putc((*p >> 3) & 07, tracefile);
753 putc(*p & 07, tracefile);
758 putc('"', tracefile);
762 trace_puts_args(char **ap)
769 trace_puts_quoted(*ap);
771 putc('\n', tracefile);
774 putc(' ', tracefile);
789 /* leave open because libedit might be using it */
792 strcpy(s, "./trace");
794 if (!freopen(s, "a", tracefile)) {
795 fprintf(stderr, "Can't re-open %s\n", s);
800 tracefile = fopen(s, "a");
801 if (tracefile == NULL) {
802 fprintf(stderr, "Can't open %s\n", s);
808 flags = fcntl(fileno(tracefile), F_GETFL);
810 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
812 setlinebuf(tracefile);
813 fputs("\nTracing started.\n", tracefile);
817 indent(int amount, char *pfx, FILE *fp)
821 for (i = 0; i < amount; i++) {
822 if (pfx && i == amount - 1)
828 /* little circular references here... */
829 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
832 sharg(union node *arg, FILE *fp)
835 struct nodelist *bqlist;
836 unsigned char subtype;
838 if (arg->type != NARG) {
839 out1fmt("<node type %d>\n", arg->type);
842 bqlist = arg->narg.backquote;
843 for (p = arg->narg.text; *p; p++) {
844 switch ((unsigned char)*p) {
852 if (subtype == VSLENGTH)
861 switch (subtype & VSTYPE) {
894 out1fmt("<subtype %d>", subtype);
901 case CTLBACKQ|CTLQUOTE:
904 shtree(bqlist->n, -1, NULL, fp);
915 shcmd(union node *cmd, FILE *fp)
923 for (np = cmd->ncmd.args; np; np = np->narg.next) {
929 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
933 switch (np->nfile.type) {
934 case NTO: s = ">>"+1; dftfd = 1; break;
935 case NCLOBBER: s = ">|"; dftfd = 1; break;
936 case NAPPEND: s = ">>"; dftfd = 1; break;
937 #if ENABLE_ASH_BASH_COMPAT
940 case NTOFD: s = ">&"; dftfd = 1; break;
941 case NFROM: s = "<"; break;
942 case NFROMFD: s = "<&"; break;
943 case NFROMTO: s = "<>"; break;
944 default: s = "*error*"; break;
946 if (np->nfile.fd != dftfd)
947 fprintf(fp, "%d", np->nfile.fd);
949 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
950 fprintf(fp, "%d", np->ndup.dupfd);
952 sharg(np->nfile.fname, fp);
959 shtree(union node *n, int ind, char *pfx, FILE *fp)
967 indent(ind, pfx, fp);
984 shtree(n->nbinary.ch1, ind, NULL, fp);
987 shtree(n->nbinary.ch2, ind, NULL, fp);
995 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
996 shtree(lp->n, 0, NULL, fp);
1000 if (n->npipe.pipe_backgnd)
1006 fprintf(fp, "<node type %d>", n->type);
1014 showtree(union node *n)
1016 trace_puts("showtree called\n");
1017 shtree(n, 1, NULL, stderr);
1023 /* ============ Parser data */
1026 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1029 struct strlist *next;
1036 struct strpush *prev; /* preceding string on stack */
1038 int prev_left_in_line;
1039 #if ENABLE_ASH_ALIAS
1040 struct alias *ap; /* if push was associated with an alias */
1042 char *string; /* remember the string since it may change */
1046 struct parsefile *prev; /* preceding file on stack */
1047 int linno; /* current line */
1048 int pf_fd; /* file descriptor (or -1 if string) */
1049 int left_in_line; /* number of chars left in this line */
1050 int left_in_buffer; /* number of chars left in this buffer past the line */
1051 char *next_to_pgetc; /* next char in buffer */
1052 char *buf; /* input buffer */
1053 struct strpush *strpush; /* for pushing strings at this level */
1054 struct strpush basestrpush; /* so pushing one is fast */
1057 static struct parsefile basepf; /* top level input file */
1058 static struct parsefile *g_parsefile = &basepf; /* current input file */
1059 static int startlinno; /* line # where last token started */
1060 static char *commandname; /* currently executing command */
1061 static struct strlist *cmdenviron; /* environment for builtin command */
1062 static uint8_t exitstatus; /* exit status of last command */
1065 /* ============ Message printing */
1068 ash_vmsg(const char *msg, va_list ap)
1070 fprintf(stderr, "%s: ", arg0);
1072 if (strcmp(arg0, commandname))
1073 fprintf(stderr, "%s: ", commandname);
1074 if (!iflag || g_parsefile->pf_fd > 0)
1075 fprintf(stderr, "line %d: ", startlinno);
1077 vfprintf(stderr, msg, ap);
1078 outcslow('\n', stderr);
1082 * Exverror is called to raise the error exception. If the second argument
1083 * is not NULL then error prints an error message using printf style
1084 * formatting. It then raises the error exception.
1086 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1088 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1092 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1094 TRACE(("\") pid=%d\n", getpid()));
1096 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1101 flush_stdout_stderr();
1102 raise_exception(cond);
1106 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1108 ash_msg_and_raise_error(const char *msg, ...)
1113 ash_vmsg_and_raise(EXERROR, msg, ap);
1118 static void raise_error_syntax(const char *) NORETURN;
1120 raise_error_syntax(const char *msg)
1122 ash_msg_and_raise_error("syntax error: %s", msg);
1126 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1128 ash_msg_and_raise(int cond, const char *msg, ...)
1133 ash_vmsg_and_raise(cond, msg, ap);
1139 * error/warning routines for external builtins
1142 ash_msg(const char *fmt, ...)
1152 * Return a string describing an error. The returned string may be a
1153 * pointer to a static buffer that will be overwritten on the next call.
1154 * Action describes the operation that got the error.
1157 errmsg(int e, const char *em)
1159 if (e == ENOENT || e == ENOTDIR) {
1166 /* ============ Memory allocation */
1169 /* I consider these wrappers nearly useless:
1170 * ok, they return you to nearest exception handler, but
1171 * how much memory do you leak in the process, making
1172 * memory starvation worse?
1175 ckrealloc(void * p, size_t nbytes)
1177 p = realloc(p, nbytes);
1179 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1184 ckmalloc(size_t nbytes)
1186 return ckrealloc(NULL, nbytes);
1190 ckzalloc(size_t nbytes)
1192 return memset(ckmalloc(nbytes), 0, nbytes);
1196 ckstrdup(const char *s)
1198 char *p = strdup(s);
1200 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1204 /* Using bbox equivalents. They exit if out of memory */
1205 # define ckrealloc xrealloc
1206 # define ckmalloc xmalloc
1207 # define ckzalloc xzalloc
1208 # define ckstrdup xstrdup
1212 * It appears that grabstackstr() will barf with such alignments
1213 * because stalloc() will return a string allocated in a new stackblock.
1215 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1217 /* Most machines require the value returned from malloc to be aligned
1218 * in some way. The following macro will get this right
1219 * on many machines. */
1220 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1221 /* Minimum size of a block */
1222 MINSIZE = SHELL_ALIGN(504),
1225 struct stack_block {
1226 struct stack_block *prev;
1227 char space[MINSIZE];
1231 struct stack_block *stackp;
1234 struct stackmark *marknext;
1238 struct globals_memstack {
1239 struct stack_block *g_stackp; // = &stackbase;
1240 struct stackmark *markp;
1241 char *g_stacknxt; // = stackbase.space;
1242 char *sstrend; // = stackbase.space + MINSIZE;
1243 size_t g_stacknleft; // = MINSIZE;
1244 int herefd; // = -1;
1245 struct stack_block stackbase;
1247 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1248 #define G_memstack (*ash_ptr_to_globals_memstack)
1249 #define g_stackp (G_memstack.g_stackp )
1250 #define markp (G_memstack.markp )
1251 #define g_stacknxt (G_memstack.g_stacknxt )
1252 #define sstrend (G_memstack.sstrend )
1253 #define g_stacknleft (G_memstack.g_stacknleft)
1254 #define herefd (G_memstack.herefd )
1255 #define stackbase (G_memstack.stackbase )
1256 #define INIT_G_memstack() do { \
1257 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1259 g_stackp = &stackbase; \
1260 g_stacknxt = stackbase.space; \
1261 g_stacknleft = MINSIZE; \
1262 sstrend = stackbase.space + MINSIZE; \
1267 #define stackblock() ((void *)g_stacknxt)
1268 #define stackblocksize() g_stacknleft
1271 * Parse trees for commands are allocated in lifo order, so we use a stack
1272 * to make this more efficient, and also to avoid all sorts of exception
1273 * handling code to handle interrupts in the middle of a parse.
1275 * The size 504 was chosen because the Ultrix malloc handles that size
1279 stalloc(size_t nbytes)
1284 aligned = SHELL_ALIGN(nbytes);
1285 if (aligned > g_stacknleft) {
1288 struct stack_block *sp;
1290 blocksize = aligned;
1291 if (blocksize < MINSIZE)
1292 blocksize = MINSIZE;
1293 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1294 if (len < blocksize)
1295 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1298 sp->prev = g_stackp;
1299 g_stacknxt = sp->space;
1300 g_stacknleft = blocksize;
1301 sstrend = g_stacknxt + blocksize;
1306 g_stacknxt += aligned;
1307 g_stacknleft -= aligned;
1312 stzalloc(size_t nbytes)
1314 return memset(stalloc(nbytes), 0, nbytes);
1321 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1322 write(STDERR_FILENO, "stunalloc\n", 10);
1326 g_stacknleft += g_stacknxt - (char *)p;
1331 * Like strdup but works with the ash stack.
1334 ststrdup(const char *p)
1336 size_t len = strlen(p) + 1;
1337 return memcpy(stalloc(len), p, len);
1341 setstackmark(struct stackmark *mark)
1343 mark->stackp = g_stackp;
1344 mark->stacknxt = g_stacknxt;
1345 mark->stacknleft = g_stacknleft;
1346 mark->marknext = markp;
1351 popstackmark(struct stackmark *mark)
1353 struct stack_block *sp;
1359 markp = mark->marknext;
1360 while (g_stackp != mark->stackp) {
1362 g_stackp = sp->prev;
1365 g_stacknxt = mark->stacknxt;
1366 g_stacknleft = mark->stacknleft;
1367 sstrend = mark->stacknxt + mark->stacknleft;
1372 * When the parser reads in a string, it wants to stick the string on the
1373 * stack and only adjust the stack pointer when it knows how big the
1374 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1375 * of space on top of the stack and stackblocklen returns the length of
1376 * this block. Growstackblock will grow this space by at least one byte,
1377 * possibly moving it (like realloc). Grabstackblock actually allocates the
1378 * part of the block that has been used.
1381 growstackblock(void)
1385 newlen = g_stacknleft * 2;
1386 if (newlen < g_stacknleft)
1387 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1391 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1392 struct stack_block *oldstackp;
1393 struct stackmark *xmark;
1394 struct stack_block *sp;
1395 struct stack_block *prevstackp;
1399 oldstackp = g_stackp;
1401 prevstackp = sp->prev;
1402 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1403 sp = ckrealloc(sp, grosslen);
1404 sp->prev = prevstackp;
1406 g_stacknxt = sp->space;
1407 g_stacknleft = newlen;
1408 sstrend = sp->space + newlen;
1411 * Stack marks pointing to the start of the old block
1412 * must be relocated to point to the new block
1415 while (xmark != NULL && xmark->stackp == oldstackp) {
1416 xmark->stackp = g_stackp;
1417 xmark->stacknxt = g_stacknxt;
1418 xmark->stacknleft = g_stacknleft;
1419 xmark = xmark->marknext;
1423 char *oldspace = g_stacknxt;
1424 size_t oldlen = g_stacknleft;
1425 char *p = stalloc(newlen);
1427 /* free the space we just allocated */
1428 g_stacknxt = memcpy(p, oldspace, oldlen);
1429 g_stacknleft += newlen;
1434 grabstackblock(size_t len)
1436 len = SHELL_ALIGN(len);
1438 g_stacknleft -= len;
1442 * The following routines are somewhat easier to use than the above.
1443 * The user declares a variable of type STACKSTR, which may be declared
1444 * to be a register. The macro STARTSTACKSTR initializes things. Then
1445 * the user uses the macro STPUTC to add characters to the string. In
1446 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1447 * grown as necessary. When the user is done, she can just leave the
1448 * string there and refer to it using stackblock(). Or she can allocate
1449 * the space for it using grabstackstr(). If it is necessary to allow
1450 * someone else to use the stack temporarily and then continue to grow
1451 * the string, the user should use grabstack to allocate the space, and
1452 * then call ungrabstr(p) to return to the previous mode of operation.
1454 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1455 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1456 * is space for at least one character.
1461 size_t len = stackblocksize();
1462 if (herefd >= 0 && len >= 1024) {
1463 full_write(herefd, stackblock(), len);
1464 return stackblock();
1467 return (char *)stackblock() + len;
1471 * Called from CHECKSTRSPACE.
1474 makestrspace(size_t newlen, char *p)
1476 size_t len = p - g_stacknxt;
1477 size_t size = stackblocksize();
1482 size = stackblocksize();
1484 if (nleft >= newlen)
1488 return (char *)stackblock() + len;
1492 stack_nputstr(const char *s, size_t n, char *p)
1494 p = makestrspace(n, p);
1495 p = (char *)memcpy(p, s, n) + n;
1500 stack_putstr(const char *s, char *p)
1502 return stack_nputstr(s, strlen(s), p);
1506 _STPUTC(int c, char *p)
1514 #define STARTSTACKSTR(p) ((p) = stackblock())
1515 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1516 #define CHECKSTRSPACE(n, p) do { \
1519 size_t m = sstrend - q; \
1521 (p) = makestrspace(l, q); \
1523 #define USTPUTC(c, p) (*(p)++ = (c))
1524 #define STACKSTRNUL(p) do { \
1525 if ((p) == sstrend) \
1526 (p) = growstackstr(); \
1529 #define STUNPUTC(p) (--(p))
1530 #define STTOPC(p) ((p)[-1])
1531 #define STADJUST(amount, p) ((p) += (amount))
1533 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1534 #define ungrabstackstr(s, p) stunalloc(s)
1535 #define stackstrend() ((void *)sstrend)
1538 /* ============ String helpers */
1541 * prefix -- see if pfx is a prefix of string.
1544 prefix(const char *string, const char *pfx)
1547 if (*pfx++ != *string++)
1550 return (char *) string;
1554 * Check for a valid number. This should be elsewhere.
1557 is_number(const char *p)
1562 } while (*++p != '\0');
1567 * Convert a string of digits to an integer, printing an error message on
1571 number(const char *s)
1574 ash_msg_and_raise_error(msg_illnum, s);
1579 * Produce a possibly single quoted string suitable as input to the shell.
1580 * The return string is allocated on the stack.
1583 single_quote(const char *s)
1593 len = strchrnul(s, '\'') - s;
1595 q = p = makestrspace(len + 3, p);
1598 q = (char *)memcpy(q, s, len) + len;
1607 do len++; while (*++s == '\'');
1609 q = p = makestrspace(len + 3, p);
1612 q = (char *)memcpy(q, s - len, len) + len;
1620 return stackblock();
1624 /* ============ nextopt */
1626 static char **argptr; /* argument list for builtin commands */
1627 static char *optionarg; /* set by nextopt (like getopt) */
1628 static char *optptr; /* used by nextopt */
1631 * XXX - should get rid of. Have all builtins use getopt(3).
1632 * The library getopt must have the BSD extension static variable
1633 * "optreset", otherwise it can't be used within the shell safely.
1635 * Standard option processing (a la getopt) for builtin routines.
1636 * The only argument that is passed to nextopt is the option string;
1637 * the other arguments are unnecessary. It returns the character,
1638 * or '\0' on end of input.
1641 nextopt(const char *optstring)
1648 if (p == NULL || *p == '\0') {
1649 /* We ate entire "-param", take next one */
1655 if (*++p == '\0') /* just "-" ? */
1658 if (LONE_DASH(p)) /* "--" ? */
1660 /* p => next "-param" */
1662 /* p => some option char in the middle of a "-param" */
1664 for (q = optstring; *q != c;) {
1666 ash_msg_and_raise_error("illegal option -%c", c);
1674 ash_msg_and_raise_error("no arg for -%c option", c);
1684 /* ============ Shell variables */
1687 * The parsefile structure pointed to by the global variable parsefile
1688 * contains information about the current file being read.
1691 int nparam; /* # of positional parameters (without $0) */
1692 #if ENABLE_ASH_GETOPTS
1693 int optind; /* next parameter to be processed by getopts */
1694 int optoff; /* used by getopts */
1696 unsigned char malloced; /* if parameter list dynamically allocated */
1697 char **p; /* parameter list */
1701 * Free the list of positional parameters.
1704 freeparam(volatile struct shparam *param)
1706 if (param->malloced) {
1708 ap = ap1 = param->p;
1715 #if ENABLE_ASH_GETOPTS
1716 static void FAST_FUNC getoptsreset(const char *value);
1720 struct var *next; /* next entry in hash list */
1721 int flags; /* flags are defined above */
1722 const char *var_text; /* name=value */
1723 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1724 /* the variable gets set/unset */
1728 struct localvar *next; /* next local variable in list */
1729 struct var *vp; /* the variable that was made local */
1730 int flags; /* saved flags */
1731 const char *text; /* saved text */
1735 #define VEXPORT 0x01 /* variable is exported */
1736 #define VREADONLY 0x02 /* variable cannot be modified */
1737 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1738 #define VTEXTFIXED 0x08 /* text is statically allocated */
1739 #define VSTACK 0x10 /* text is allocated on the stack */
1740 #define VUNSET 0x20 /* the variable is not set */
1741 #define VNOFUNC 0x40 /* don't call the callback function */
1742 #define VNOSET 0x80 /* do not set variable - just readonly test */
1743 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1744 #if ENABLE_ASH_RANDOM_SUPPORT
1745 # define VDYNAMIC 0x200 /* dynamic variable */
1751 /* Need to be before varinit_data[] */
1752 #if ENABLE_LOCALE_SUPPORT
1753 static void FAST_FUNC
1754 change_lc_all(const char *value)
1756 if (value && *value != '\0')
1757 setlocale(LC_ALL, value);
1759 static void FAST_FUNC
1760 change_lc_ctype(const char *value)
1762 if (value && *value != '\0')
1763 setlocale(LC_CTYPE, value);
1767 static void chkmail(void);
1768 static void changemail(const char *) FAST_FUNC;
1770 static void changepath(const char *) FAST_FUNC;
1771 #if ENABLE_ASH_RANDOM_SUPPORT
1772 static void change_random(const char *) FAST_FUNC;
1775 static const struct {
1777 const char *var_text;
1778 void (*var_func)(const char *) FAST_FUNC;
1779 } varinit_data[] = {
1780 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1782 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1783 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1785 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1786 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1787 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1788 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1789 #if ENABLE_ASH_GETOPTS
1790 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1792 #if ENABLE_ASH_RANDOM_SUPPORT
1793 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1795 #if ENABLE_LOCALE_SUPPORT
1796 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1797 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1799 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1800 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1806 struct globals_var {
1807 struct shparam shellparam; /* $@ current positional parameters */
1808 struct redirtab *redirlist;
1810 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1811 struct var *vartab[VTABSIZE];
1812 struct var varinit[ARRAY_SIZE(varinit_data)];
1814 extern struct globals_var *const ash_ptr_to_globals_var;
1815 #define G_var (*ash_ptr_to_globals_var)
1816 #define shellparam (G_var.shellparam )
1817 //#define redirlist (G_var.redirlist )
1818 #define g_nullredirs (G_var.g_nullredirs )
1819 #define preverrout_fd (G_var.preverrout_fd)
1820 #define vartab (G_var.vartab )
1821 #define varinit (G_var.varinit )
1822 #define INIT_G_var() do { \
1824 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1826 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1827 varinit[i].flags = varinit_data[i].flags; \
1828 varinit[i].var_text = varinit_data[i].var_text; \
1829 varinit[i].var_func = varinit_data[i].var_func; \
1833 #define vifs varinit[0]
1835 # define vmail (&vifs)[1]
1836 # define vmpath (&vmail)[1]
1837 # define vpath (&vmpath)[1]
1839 # define vpath (&vifs)[1]
1841 #define vps1 (&vpath)[1]
1842 #define vps2 (&vps1)[1]
1843 #define vps4 (&vps2)[1]
1844 #if ENABLE_ASH_GETOPTS
1845 # define voptind (&vps4)[1]
1846 # if ENABLE_ASH_RANDOM_SUPPORT
1847 # define vrandom (&voptind)[1]
1850 # if ENABLE_ASH_RANDOM_SUPPORT
1851 # define vrandom (&vps4)[1]
1856 * The following macros access the values of the above variables.
1857 * They have to skip over the name. They return the null string
1858 * for unset variables.
1860 #define ifsval() (vifs.var_text + 4)
1861 #define ifsset() ((vifs.flags & VUNSET) == 0)
1863 # define mailval() (vmail.var_text + 5)
1864 # define mpathval() (vmpath.var_text + 9)
1865 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1867 #define pathval() (vpath.var_text + 5)
1868 #define ps1val() (vps1.var_text + 4)
1869 #define ps2val() (vps2.var_text + 4)
1870 #define ps4val() (vps4.var_text + 4)
1871 #if ENABLE_ASH_GETOPTS
1872 # define optindval() (voptind.var_text + 7)
1876 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1877 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1879 #if ENABLE_ASH_GETOPTS
1880 static void FAST_FUNC
1881 getoptsreset(const char *value)
1883 shellparam.optind = number(value);
1884 shellparam.optoff = -1;
1889 * Return of a legal variable name (a letter or underscore followed by zero or
1890 * more letters, underscores, and digits).
1892 static char* FAST_FUNC
1893 endofname(const char *name)
1901 if (!is_in_name(*p))
1908 * Compares two strings up to the first = or '\0'. The first
1909 * string must be terminated by '='; the second may be terminated by
1910 * either '=' or '\0'.
1913 varcmp(const char *p, const char *q)
1917 while ((c = *p) == (d = *q)) {
1932 * Find the appropriate entry in the hash table from the name.
1934 static struct var **
1935 hashvar(const char *p)
1939 hashval = ((unsigned char) *p) << 4;
1940 while (*p && *p != '=')
1941 hashval += (unsigned char) *p++;
1942 return &vartab[hashval % VTABSIZE];
1946 vpcmp(const void *a, const void *b)
1948 return varcmp(*(const char **)a, *(const char **)b);
1952 * This routine initializes the builtin variables.
1962 * PS1 depends on uid
1964 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1965 vps1.var_text = "PS1=\\w \\$ ";
1968 vps1.var_text = "PS1=# ";
1971 end = vp + ARRAY_SIZE(varinit);
1973 vpp = hashvar(vp->var_text);
1976 } while (++vp < end);
1979 static struct var **
1980 findvar(struct var **vpp, const char *name)
1982 for (; *vpp; vpp = &(*vpp)->next) {
1983 if (varcmp((*vpp)->var_text, name) == 0) {
1991 * Find the value of a variable. Returns NULL if not set.
1993 static const char* FAST_FUNC
1994 lookupvar(const char *name)
1998 v = *findvar(hashvar(name), name);
2000 #if ENABLE_ASH_RANDOM_SUPPORT
2002 * Dynamic variables are implemented roughly the same way they are
2003 * in bash. Namely, they're "special" so long as they aren't unset.
2004 * As soon as they're unset, they're no longer dynamic, and dynamic
2005 * lookup will no longer happen at that point. -- PFM.
2007 if (v->flags & VDYNAMIC)
2010 if (!(v->flags & VUNSET))
2011 return var_end(v->var_text);
2017 * Search the environment of a builtin command.
2020 bltinlookup(const char *name)
2024 for (sp = cmdenviron; sp; sp = sp->next) {
2025 if (varcmp(sp->text, name) == 0)
2026 return var_end(sp->text);
2028 return lookupvar(name);
2032 * Same as setvar except that the variable and value are passed in
2033 * the first argument as name=value. Since the first argument will
2034 * be actually stored in the table, it should not be a string that
2036 * Called with interrupts off.
2039 setvareq(char *s, int flags)
2041 struct var *vp, **vpp;
2044 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2045 vp = *findvar(vpp, s);
2047 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2050 if (flags & VNOSAVE)
2053 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2059 if (vp->var_func && !(flags & VNOFUNC))
2060 vp->var_func(var_end(s));
2062 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2063 free((char*)vp->var_text);
2065 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2067 /* variable s is not found */
2070 vp = ckzalloc(sizeof(*vp));
2072 /*vp->func = NULL; - ckzalloc did it */
2075 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2082 * Set the value of a variable. The flags argument is ored with the
2083 * flags of the variable. If val is NULL, the variable is unset.
2086 setvar(const char *name, const char *val, int flags)
2093 q = endofname(name);
2094 p = strchrnul(q, '=');
2096 if (!namelen || p != q)
2097 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2102 vallen = strlen(val);
2105 nameeq = ckmalloc(namelen + vallen + 2);
2106 p = (char *)memcpy(nameeq, name, namelen) + namelen;
2109 p = (char *)memcpy(p, val, vallen) + vallen;
2112 setvareq(nameeq, flags | VNOSAVE);
2116 static void FAST_FUNC
2117 setvar2(const char *name, const char *val)
2119 setvar(name, val, 0);
2122 #if ENABLE_ASH_GETOPTS
2124 * Safe version of setvar, returns 1 on success 0 on failure.
2127 setvarsafe(const char *name, const char *val, int flags)
2130 volatile int saveint;
2131 struct jmploc *volatile savehandler = exception_handler;
2132 struct jmploc jmploc;
2135 if (setjmp(jmploc.loc))
2138 exception_handler = &jmploc;
2139 setvar(name, val, flags);
2142 exception_handler = savehandler;
2143 RESTORE_INT(saveint);
2149 * Unset the specified variable.
2152 unsetvar(const char *s)
2158 vpp = findvar(hashvar(s), s);
2162 int flags = vp->flags;
2165 if (flags & VREADONLY)
2167 #if ENABLE_ASH_RANDOM_SUPPORT
2168 vp->flags &= ~VDYNAMIC;
2172 if ((flags & VSTRFIXED) == 0) {
2174 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2175 free((char*)vp->var_text);
2181 vp->flags &= ~VEXPORT;
2191 * Process a linked list of variable assignments.
2194 listsetvar(struct strlist *list_set_var, int flags)
2196 struct strlist *lp = list_set_var;
2202 setvareq(lp->text, flags);
2209 * Generate a list of variables satisfying the given conditions.
2212 listvars(int on, int off, char ***end)
2223 for (vp = *vpp; vp; vp = vp->next) {
2224 if ((vp->flags & mask) == on) {
2225 if (ep == stackstrend())
2226 ep = growstackstr();
2227 *ep++ = (char*)vp->var_text;
2230 } while (++vpp < vartab + VTABSIZE);
2231 if (ep == stackstrend())
2232 ep = growstackstr();
2236 return grabstackstr(ep);
2240 /* ============ Path search helper
2242 * The variable path (passed by reference) should be set to the start
2243 * of the path before the first call; path_advance will update
2244 * this value as it proceeds. Successive calls to path_advance will return
2245 * the possible path expansions in sequence. If an option (indicated by
2246 * a percent sign) appears in the path entry then the global variable
2247 * pathopt will be set to point to it; otherwise pathopt will be set to
2250 static const char *pathopt; /* set by path_advance */
2253 path_advance(const char **path, const char *name)
2263 for (p = start; *p && *p != ':' && *p != '%'; p++)
2265 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2266 while (stackblocksize() < len)
2270 memcpy(q, start, p - start);
2278 while (*p && *p != ':')
2285 return stalloc(len);
2289 /* ============ Prompt */
2291 static smallint doprompt; /* if set, prompt the user */
2292 static smallint needprompt; /* true if interactive and at start of line */
2294 #if ENABLE_FEATURE_EDITING
2295 static line_input_t *line_input_state;
2296 static const char *cmdedit_prompt;
2298 putprompt(const char *s)
2300 if (ENABLE_ASH_EXPAND_PRMT) {
2301 free((char*)cmdedit_prompt);
2302 cmdedit_prompt = ckstrdup(s);
2309 putprompt(const char *s)
2315 #if ENABLE_ASH_EXPAND_PRMT
2316 /* expandstr() needs parsing machinery, so it is far away ahead... */
2317 static const char *expandstr(const char *ps);
2319 #define expandstr(s) s
2323 setprompt(int whichprompt)
2326 #if ENABLE_ASH_EXPAND_PRMT
2327 struct stackmark smark;
2332 switch (whichprompt) {
2342 #if ENABLE_ASH_EXPAND_PRMT
2343 setstackmark(&smark);
2344 stalloc(stackblocksize());
2346 putprompt(expandstr(prompt));
2347 #if ENABLE_ASH_EXPAND_PRMT
2348 popstackmark(&smark);
2353 /* ============ The cd and pwd commands */
2355 #define CD_PHYSICAL 1
2365 while ((i = nextopt("LP")) != '\0') {
2367 flags ^= CD_PHYSICAL;
2376 * Update curdir (the name of the current directory) in response to a
2380 updatepwd(const char *dir)
2387 cdcomppath = ststrdup(dir);
2390 if (curdir == nullstr)
2392 new = stack_putstr(curdir, new);
2394 new = makestrspace(strlen(dir) + 2, new);
2395 lim = (char *)stackblock() + 1;
2399 if (new > lim && *lim == '/')
2404 if (dir[1] == '/' && dir[2] != '/') {
2410 p = strtok(cdcomppath, "/");
2414 if (p[1] == '.' && p[2] == '\0') {
2426 new = stack_putstr(p, new);
2434 return stackblock();
2438 * Find out what the current directory is. If we already know the current
2439 * directory, this routine returns immediately.
2444 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2445 return dir ? dir : nullstr;
2449 setpwd(const char *val, int setold)
2453 oldcur = dir = curdir;
2456 setvar("OLDPWD", oldcur, VEXPORT);
2459 if (physdir != nullstr) {
2460 if (physdir != oldcur)
2464 if (oldcur == val || !val) {
2470 dir = ckstrdup(val);
2471 if (oldcur != dir && oldcur != nullstr) {
2476 setvar("PWD", dir, VEXPORT);
2479 static void hashcd(void);
2482 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2483 * know that the current directory has changed.
2486 docd(const char *dest, int flags)
2488 const char *dir = NULL;
2491 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2494 if (!(flags & CD_PHYSICAL)) {
2495 dir = updatepwd(dest);
2509 static int FAST_FUNC
2510 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2522 dest = bltinlookup("HOME");
2523 else if (LONE_DASH(dest)) {
2524 dest = bltinlookup("OLDPWD");
2546 path = bltinlookup("CDPATH");
2555 p = path_advance(&path, dest);
2556 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2560 if (!docd(p, flags))
2565 ash_msg_and_raise_error("can't cd to %s", dest);
2568 if (flags & CD_PRINT)
2569 out1fmt("%s\n", curdir);
2573 static int FAST_FUNC
2574 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2577 const char *dir = curdir;
2581 if (physdir == nullstr)
2585 out1fmt("%s\n", dir);
2590 /* ============ ... */
2593 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2595 /* Syntax classes */
2596 #define CWORD 0 /* character is nothing special */
2597 #define CNL 1 /* newline character */
2598 #define CBACK 2 /* a backslash character */
2599 #define CSQUOTE 3 /* single quote */
2600 #define CDQUOTE 4 /* double quote */
2601 #define CENDQUOTE 5 /* a terminating quote */
2602 #define CBQUOTE 6 /* backwards single quote */
2603 #define CVAR 7 /* a dollar sign */
2604 #define CENDVAR 8 /* a '}' character */
2605 #define CLP 9 /* a left paren in arithmetic */
2606 #define CRP 10 /* a right paren in arithmetic */
2607 #define CENDFILE 11 /* end of file */
2608 #define CCTL 12 /* like CWORD, except it must be escaped */
2609 #define CSPCL 13 /* these terminate a word */
2610 #define CIGN 14 /* character should be ignored */
2613 #if ENABLE_ASH_ALIAS
2617 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2619 #if ENABLE_SH_MATH_SUPPORT
2620 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2622 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2624 static const uint16_t S_I_T[] = {
2625 #if ENABLE_ASH_ALIAS
2626 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2628 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2629 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2630 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2631 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2632 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2633 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2634 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2635 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2636 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2637 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2638 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2639 #if !USE_SIT_FUNCTION
2640 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2641 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2642 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2646 /* Constants below must match table above */
2648 #if ENABLE_ASH_ALIAS
2649 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2651 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2652 CNL_CNL_CNL_CNL , /* 2 */
2653 CWORD_CCTL_CCTL_CWORD , /* 3 */
2654 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2655 CVAR_CVAR_CWORD_CVAR , /* 5 */
2656 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2657 CSPCL_CWORD_CWORD_CLP , /* 7 */
2658 CSPCL_CWORD_CWORD_CRP , /* 8 */
2659 CBACK_CBACK_CCTL_CBACK , /* 9 */
2660 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2661 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2662 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2663 CWORD_CWORD_CWORD_CWORD , /* 13 */
2664 CCTL_CCTL_CCTL_CCTL , /* 14 */
2667 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2668 * caller must ensure proper cast on it if c is *char_ptr!
2670 /* Values for syntax param */
2671 #define BASESYNTAX 0 /* not in quotes */
2672 #define DQSYNTAX 1 /* in double quotes */
2673 #define SQSYNTAX 2 /* in single quotes */
2674 #define ARISYNTAX 3 /* in arithmetic */
2675 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2677 #if USE_SIT_FUNCTION
2680 SIT(int c, int syntax)
2682 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2683 # if ENABLE_ASH_ALIAS
2684 static const uint8_t syntax_index_table[] ALIGN1 = {
2685 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2686 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2687 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2691 static const uint8_t syntax_index_table[] ALIGN1 = {
2692 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2693 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2694 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2703 # if ENABLE_ASH_ALIAS
2709 /* Cast is purely for paranoia here,
2710 * just in case someone passed signed char to us */
2711 if ((unsigned char)c >= CTL_FIRST
2712 && (unsigned char)c <= CTL_LAST
2716 s = strchrnul(spec_symbls, c);
2719 indx = syntax_index_table[s - spec_symbls];
2721 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2724 #else /* !USE_SIT_FUNCTION */
2726 static const uint8_t syntax_index_table[] = {
2727 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2728 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2738 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2739 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2760 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2761 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2762 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2763 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2764 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2765 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2766 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2767 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2768 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2769 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2770 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2771 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2772 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2773 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2774 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2775 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2776 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2777 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2778 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2779 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2780 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2781 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2782 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2783 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2784 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2785 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2786 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2787 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2788 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2789 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2790 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2791 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2792 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2793 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2794 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2795 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2796 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2797 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2800 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2802 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2803 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2814 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2815 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2816 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2817 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2819 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2820 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2821 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2822 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2823 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2824 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2825 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2848 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2849 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2850 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2851 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2852 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2853 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2854 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2855 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2856 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2858 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2859 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2860 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2861 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2862 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2863 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2864 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2865 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 162 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 163 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 164 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 165 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 166 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 167 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 168 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 169 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 170 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 171 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 172 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 173 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 174 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 175 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 176 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 177 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 178 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 179 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 180 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 181 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 182 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 183 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 184 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 185 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 186 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 187 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 188 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 189 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 190 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 191 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 192 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 193 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 194 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 195 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 196 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 197 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 198 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 199 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 200 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 201 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 202 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 203 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 204 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 205 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 206 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 207 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 208 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 209 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 210 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 211 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 212 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 213 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 214 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 215 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 216 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 217 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 218 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 219 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 220 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 221 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 222 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 223 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 224 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 225 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 226 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 227 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 228 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 229 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 231 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 232 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 233 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 234 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 235 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 236 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 237 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 238 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 239 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 241 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 242 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 243 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 244 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 245 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 246 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 247 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 248 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 249 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 250 */ CWORD_CWORD_CWORD_CWORD,
2979 /* 251 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 252 */ CWORD_CWORD_CWORD_CWORD,
2981 /* 253 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 254 */ CWORD_CWORD_CWORD_CWORD,
2983 /* 255 */ CWORD_CWORD_CWORD_CWORD,
2984 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2985 # if ENABLE_ASH_ALIAS
2986 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
2990 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
2992 #endif /* !USE_SIT_FUNCTION */
2995 /* ============ Alias handling */
2997 #if ENABLE_ASH_ALIAS
2999 #define ALIASINUSE 1
3010 static struct alias **atab; // [ATABSIZE];
3011 #define INIT_G_alias() do { \
3012 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3016 static struct alias **
3017 __lookupalias(const char *name) {
3018 unsigned int hashval;
3025 ch = (unsigned char)*p;
3029 ch = (unsigned char)*++p;
3031 app = &atab[hashval % ATABSIZE];
3033 for (; *app; app = &(*app)->next) {
3034 if (strcmp(name, (*app)->name) == 0) {
3042 static struct alias *
3043 lookupalias(const char *name, int check)
3045 struct alias *ap = *__lookupalias(name);
3047 if (check && ap && (ap->flag & ALIASINUSE))
3052 static struct alias *
3053 freealias(struct alias *ap)
3057 if (ap->flag & ALIASINUSE) {
3058 ap->flag |= ALIASDEAD;
3070 setalias(const char *name, const char *val)
3072 struct alias *ap, **app;
3074 app = __lookupalias(name);
3078 if (!(ap->flag & ALIASINUSE)) {
3081 ap->val = ckstrdup(val);
3082 ap->flag &= ~ALIASDEAD;
3085 ap = ckzalloc(sizeof(struct alias));
3086 ap->name = ckstrdup(name);
3087 ap->val = ckstrdup(val);
3088 /*ap->flag = 0; - ckzalloc did it */
3089 /*ap->next = NULL;*/
3096 unalias(const char *name)
3100 app = __lookupalias(name);
3104 *app = freealias(*app);
3115 struct alias *ap, **app;
3119 for (i = 0; i < ATABSIZE; i++) {
3121 for (ap = *app; ap; ap = *app) {
3122 *app = freealias(*app);
3132 printalias(const struct alias *ap)
3134 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3138 * TODO - sort output
3140 static int FAST_FUNC
3141 aliascmd(int argc UNUSED_PARAM, char **argv)
3150 for (i = 0; i < ATABSIZE; i++) {
3151 for (ap = atab[i]; ap; ap = ap->next) {
3157 while ((n = *++argv) != NULL) {
3158 v = strchr(n+1, '=');
3159 if (v == NULL) { /* n+1: funny ksh stuff */
3160 ap = *__lookupalias(n);
3162 fprintf(stderr, "%s: %s not found\n", "alias", n);
3175 static int FAST_FUNC
3176 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3180 while ((i = nextopt("a")) != '\0') {
3186 for (i = 0; *argptr; argptr++) {
3187 if (unalias(*argptr)) {
3188 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3196 #endif /* ASH_ALIAS */
3199 /* ============ jobs.c */
3201 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3204 #define FORK_NOJOB 2
3206 /* mode flags for showjob(s) */
3207 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3208 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3209 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3212 * A job structure contains information about a job. A job is either a
3213 * single process or a set of processes contained in a pipeline. In the
3214 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3218 pid_t ps_pid; /* process id */
3219 int ps_status; /* last process status from wait() */
3220 char *ps_cmd; /* text of command being run */
3224 struct procstat ps0; /* status of process */
3225 struct procstat *ps; /* status or processes when more than one */
3227 int stopstatus; /* status of a stopped job */
3230 nprocs: 16, /* number of processes */
3232 #define JOBRUNNING 0 /* at least one proc running */
3233 #define JOBSTOPPED 1 /* all procs are stopped */
3234 #define JOBDONE 2 /* all procs are completed */
3236 sigint: 1, /* job was killed by SIGINT */
3237 jobctl: 1, /* job running under job control */
3239 waited: 1, /* true if this entry has been waited for */
3240 used: 1, /* true if this entry is in used */
3241 changed: 1; /* true if status has changed */
3242 struct job *prev_job; /* previous job */
3245 static struct job *makejob(/*union node *,*/ int);
3246 static int forkshell(struct job *, union node *, int);
3247 static int waitforjob(struct job *);
3250 enum { doing_jobctl = 0 };
3251 #define setjobctl(on) do {} while (0)
3253 static smallint doing_jobctl; //references:8
3254 static void setjobctl(int);
3261 ignoresig(int signo)
3263 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3264 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3265 /* No, need to do it */
3266 signal(signo, SIG_IGN);
3268 sigmode[signo - 1] = S_HARD_IGN;
3272 * Only one usage site - in setsignal()
3275 signal_handler(int signo)
3277 gotsig[signo - 1] = 1;
3279 if (signo == SIGINT && !trap[SIGINT]) {
3280 if (!suppress_int) {
3282 raise_interrupt(); /* does not return */
3286 pending_sig = signo;
3291 * Set the signal handler for the specified signal. The routine figures
3292 * out what it should be set to.
3295 setsignal(int signo)
3298 char cur_act, new_act;
3299 struct sigaction act;
3303 if (t != NULL) { /* trap for this sig is set */
3305 if (t[0] == '\0') /* trap is "": ignore this sig */
3309 if (rootshell && new_act == S_DFL) {
3312 if (iflag || minusc || sflag == 0)
3321 * "In all cases, bash ignores SIGQUIT. Non-builtin
3322 * commands run by bash have signal handlers
3323 * set to the values inherited by the shell
3324 * from its parent". */
3340 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3341 //whereas we have to restore it to what shell got on entry
3342 //from the parent. See comment above
3344 t = &sigmode[signo - 1];
3347 /* current setting is not yet known */
3348 if (sigaction(signo, NULL, &act)) {
3349 /* pretend it worked; maybe we should give a warning,
3350 * but other shells don't. We don't alter sigmode,
3351 * so we retry every time.
3352 * btw, in Linux it never fails. --vda */
3355 if (act.sa_handler == SIG_IGN) {
3356 cur_act = S_HARD_IGN;
3358 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3360 cur_act = S_IGN; /* don't hard ignore these */
3364 if (cur_act == S_HARD_IGN || cur_act == new_act)
3367 act.sa_handler = SIG_DFL;
3370 act.sa_handler = signal_handler;
3371 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3372 sigfillset(&act.sa_mask); /* ditto */
3375 act.sa_handler = SIG_IGN;
3378 sigaction_set(signo, &act);
3383 /* mode flags for set_curjob */
3384 #define CUR_DELETE 2
3385 #define CUR_RUNNING 1
3386 #define CUR_STOPPED 0
3388 /* mode flags for dowait */
3389 #define DOWAIT_NONBLOCK WNOHANG
3390 #define DOWAIT_BLOCK 0
3393 /* pgrp of shell on invocation */
3394 static int initialpgrp; //references:2
3395 static int ttyfd = -1; //5
3398 static struct job *jobtab; //5
3400 static unsigned njobs; //4
3402 static struct job *curjob; //lots
3403 /* number of presumed living untracked jobs */
3404 static int jobless; //4
3407 set_curjob(struct job *jp, unsigned mode)
3410 struct job **jpp, **curp;
3412 /* first remove from list */
3413 jpp = curp = &curjob;
3418 jpp = &jp1->prev_job;
3420 *jpp = jp1->prev_job;
3422 /* Then re-insert in correct position */
3430 /* job being deleted */
3433 /* newly created job or backgrounded job,
3434 put after all stopped jobs. */
3438 if (!jp1 || jp1->state != JOBSTOPPED)
3441 jpp = &jp1->prev_job;
3447 /* newly stopped job - becomes curjob */
3448 jp->prev_job = *jpp;
3456 jobno(const struct job *jp)
3458 return jp - jobtab + 1;
3463 * Convert a job name to a job structure.
3466 #define getjob(name, getctl) getjob(name)
3469 getjob(const char *name, int getctl)
3473 const char *err_msg = "%s: no such job";
3477 char *(*match)(const char *, const char *);
3492 if (c == '+' || c == '%') {
3494 err_msg = "No current job";
3500 err_msg = "No previous job";
3511 jp = jobtab + num - 1;
3526 if (match(jp->ps[0].ps_cmd, p)) {
3530 err_msg = "%s: ambiguous";
3540 err_msg = "job %s not created under job control";
3541 if (getctl && jp->jobctl == 0)
3546 ash_msg_and_raise_error(err_msg, name);
3550 * Mark a job structure as unused.
3553 freejob(struct job *jp)
3555 struct procstat *ps;
3559 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3560 if (ps->ps_cmd != nullstr)
3563 if (jp->ps != &jp->ps0)
3566 set_curjob(jp, CUR_DELETE);
3572 xtcsetpgrp(int fd, pid_t pgrp)
3574 if (tcsetpgrp(fd, pgrp))
3575 ash_msg_and_raise_error("can't set tty process group (%m)");
3579 * Turn job control on and off.
3581 * Note: This code assumes that the third arg to ioctl is a character
3582 * pointer, which is true on Berkeley systems but not System V. Since
3583 * System V doesn't have job control yet, this isn't a problem now.
3585 * Called with interrupts off.
3593 if (on == doing_jobctl || rootshell == 0)
3597 ofd = fd = open(_PATH_TTY, O_RDWR);
3599 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3600 * That sometimes helps to acquire controlling tty.
3601 * Obviously, a workaround for bugs when someone
3602 * failed to provide a controlling tty to bash! :) */
3608 fd = fcntl(fd, F_DUPFD, 10);
3613 /* fd is a tty at this point */
3614 close_on_exec_on(fd);
3615 do { /* while we are in the background */
3616 pgrp = tcgetpgrp(fd);
3619 ash_msg("can't access tty; job control turned off");
3623 if (pgrp == getpgrp())
3634 xtcsetpgrp(fd, pgrp);
3636 /* turning job control off */
3639 /* was xtcsetpgrp, but this can make exiting ash
3640 * loop forever if pty is already deleted */
3641 tcsetpgrp(fd, pgrp);
3655 static int FAST_FUNC
3656 killcmd(int argc, char **argv)
3659 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3661 if (argv[i][0] == '%') {
3662 struct job *jp = getjob(argv[i], 0);
3663 unsigned pid = jp->ps[0].ps_pid;
3664 /* Enough space for ' -NNN<nul>' */
3665 argv[i] = alloca(sizeof(int)*3 + 3);
3666 /* kill_main has matching code to expect
3667 * leading space. Needed to not confuse
3668 * negative pids with "kill -SIGNAL_NO" syntax */
3669 sprintf(argv[i], " -%u", pid);
3671 } while (argv[++i]);
3673 return kill_main(argc, argv);
3677 showpipe(struct job *jp /*, FILE *out*/)
3679 struct procstat *ps;
3680 struct procstat *psend;
3682 psend = jp->ps + jp->nprocs;
3683 for (ps = jp->ps + 1; ps < psend; ps++)
3684 printf(" | %s", ps->ps_cmd);
3685 outcslow('\n', stdout);
3686 flush_stdout_stderr();
3691 restartjob(struct job *jp, int mode)
3693 struct procstat *ps;
3699 if (jp->state == JOBDONE)
3701 jp->state = JOBRUNNING;
3702 pgid = jp->ps[0].ps_pid;
3703 if (mode == FORK_FG)
3704 xtcsetpgrp(ttyfd, pgid);
3705 killpg(pgid, SIGCONT);
3709 if (WIFSTOPPED(ps->ps_status)) {
3715 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3720 static int FAST_FUNC
3721 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3727 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3731 jp = getjob(*argv, 1);
3732 if (mode == FORK_BG) {
3733 set_curjob(jp, CUR_RUNNING);
3734 printf("[%d] ", jobno(jp));
3736 out1str(jp->ps[0].ps_cmd);
3737 showpipe(jp /*, stdout*/);
3738 retval = restartjob(jp, mode);
3739 } while (*argv && *++argv);
3745 sprint_status(char *s, int status, int sigonly)
3751 if (!WIFEXITED(status)) {
3753 if (WIFSTOPPED(status))
3754 st = WSTOPSIG(status);
3757 st = WTERMSIG(status);
3759 if (st == SIGINT || st == SIGPIPE)
3762 if (WIFSTOPPED(status))
3767 col = fmtstr(s, 32, strsignal(st));
3768 if (WCOREDUMP(status)) {
3769 col += fmtstr(s + col, 16, " (core dumped)");
3771 } else if (!sigonly) {
3772 st = WEXITSTATUS(status);
3774 col = fmtstr(s, 16, "Done(%d)", st);
3776 col = fmtstr(s, 16, "Done");
3783 dowait(int wait_flags, struct job *job)
3788 struct job *thisjob;
3791 TRACE(("dowait(0x%x) called\n", wait_flags));
3793 /* Do a wait system call. If job control is compiled in, we accept
3794 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3795 * NB: _not_ safe_waitpid, we need to detect EINTR */
3797 wait_flags |= WUNTRACED;
3798 pid = waitpid(-1, &status, wait_flags);
3799 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3800 pid, status, errno, strerror(errno)));
3806 for (jp = curjob; jp; jp = jp->prev_job) {
3807 struct procstat *ps;
3808 struct procstat *psend;
3809 if (jp->state == JOBDONE)
3813 psend = ps + jp->nprocs;
3815 if (ps->ps_pid == pid) {
3816 TRACE(("Job %d: changing status of proc %d "
3817 "from 0x%x to 0x%x\n",
3818 jobno(jp), pid, ps->ps_status, status));
3819 ps->ps_status = status;
3822 if (ps->ps_status == -1)
3825 if (state == JOBRUNNING)
3827 if (WIFSTOPPED(ps->ps_status)) {
3828 jp->stopstatus = ps->ps_status;
3832 } while (++ps < psend);
3837 if (!WIFSTOPPED(status))
3843 if (state != JOBRUNNING) {
3844 thisjob->changed = 1;
3846 if (thisjob->state != state) {
3847 TRACE(("Job %d: changing state from %d to %d\n",
3848 jobno(thisjob), thisjob->state, state));
3849 thisjob->state = state;
3851 if (state == JOBSTOPPED) {
3852 set_curjob(thisjob, CUR_STOPPED);
3861 if (thisjob && thisjob == job) {
3865 len = sprint_status(s, status, 1);
3876 blocking_wait_with_raise_on_sig(void)
3878 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
3879 if (pid <= 0 && pending_sig)
3880 raise_exception(EXSIG);
3886 showjob(FILE *out, struct job *jp, int mode)
3888 struct procstat *ps;
3889 struct procstat *psend;
3896 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
3897 /* just output process (group) id of pipeline */
3898 fprintf(out, "%d\n", ps->ps_pid);
3902 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3907 else if (curjob && jp == curjob->prev_job)
3910 if (mode & SHOW_PIDS)
3911 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
3913 psend = ps + jp->nprocs;
3915 if (jp->state == JOBRUNNING) {
3916 strcpy(s + col, "Running");
3917 col += sizeof("Running") - 1;
3919 int status = psend[-1].ps_status;
3920 if (jp->state == JOBSTOPPED)
3921 status = jp->stopstatus;
3922 col += sprint_status(s + col, status, 0);
3924 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
3926 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3927 * or prints several "PID | <cmdN>" lines,
3928 * depending on SHOW_PIDS bit.
3929 * We do not print status of individual processes
3930 * between PID and <cmdN>. bash does it, but not very well:
3931 * first line shows overall job status, not process status,
3932 * making it impossible to know 1st process status.
3936 /* for each process */
3939 if (mode & SHOW_PIDS)
3940 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
3942 fprintf(out, "%s%*c%s%s",
3944 33 - col >= 0 ? 33 - col : 0, ' ',
3945 ps == jp->ps ? "" : "| ",
3948 } while (++ps != psend);
3949 outcslow('\n', out);
3953 if (jp->state == JOBDONE) {
3954 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3960 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3961 * statuses have changed since the last call to showjobs.
3964 showjobs(FILE *out, int mode)
3968 TRACE(("showjobs(0x%x) called\n", mode));
3970 /* Handle all finished jobs */
3971 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
3974 for (jp = curjob; jp; jp = jp->prev_job) {
3975 if (!(mode & SHOW_CHANGED) || jp->changed) {
3976 showjob(out, jp, mode);
3981 static int FAST_FUNC
3982 jobscmd(int argc UNUSED_PARAM, char **argv)
3987 while ((m = nextopt("lp")) != '\0') {
3991 mode |= SHOW_ONLY_PGID;
3997 showjob(stdout, getjob(*argv, 0), mode);
4000 showjobs(stdout, mode);
4007 /* Called only on finished or stopped jobs (no members are running) */
4009 getstatus(struct job *job)
4013 struct procstat *ps;
4015 /* Fetch last member's status */
4016 ps = job->ps + job->nprocs - 1;
4017 status = ps->ps_status;
4019 /* "set -o pipefail" mode: use last _nonzero_ status */
4020 while (status == 0 && --ps >= job->ps)
4021 status = ps->ps_status;
4024 retval = WEXITSTATUS(status);
4025 if (!WIFEXITED(status)) {
4027 retval = WSTOPSIG(status);
4028 if (!WIFSTOPPED(status))
4031 /* XXX: limits number of signals */
4032 retval = WTERMSIG(status);
4034 if (retval == SIGINT)
4040 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4041 jobno(job), job->nprocs, status, retval));
4045 static int FAST_FUNC
4046 waitcmd(int argc UNUSED_PARAM, char **argv)
4053 raise_exception(EXSIG);
4060 /* wait for all jobs */
4064 if (!jp) /* no running procs */
4066 if (jp->state == JOBRUNNING)
4071 blocking_wait_with_raise_on_sig();
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."
4079 * blocking_wait_with_raise_on_sig raises signal handlers
4080 * if it gets no pid (pid < 0). However,
4081 * if child sends us a signal *and immediately exits*,
4082 * blocking_wait_with_raise_on_sig gets pid > 0
4083 * and does not handle pending_sig. Check this case: */
4085 raise_exception(EXSIG);
4091 if (**argv != '%') {
4092 pid_t pid = number(*argv);
4097 if (job->ps[job->nprocs - 1].ps_pid == pid)
4099 job = job->prev_job;
4102 job = getjob(*argv, 0);
4103 /* loop until process terminated or stopped */
4104 while (job->state == JOBRUNNING)
4105 blocking_wait_with_raise_on_sig();
4107 retval = getstatus(job);
4120 struct job *jp, *jq;
4122 len = njobs * sizeof(*jp);
4124 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4126 offset = (char *)jp - (char *)jq;
4128 /* Relocate pointers */
4131 jq = (struct job *)((char *)jq + l);
4135 #define joff(p) ((struct job *)((char *)(p) + l))
4136 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4137 if (joff(jp)->ps == &jq->ps0)
4138 jmove(joff(jp)->ps);
4139 if (joff(jp)->prev_job)
4140 jmove(joff(jp)->prev_job);
4150 jp = (struct job *)((char *)jp + len);
4154 } while (--jq >= jp);
4159 * Return a new job structure.
4160 * Called with interrupts off.
4163 makejob(/*union node *node,*/ int nprocs)
4168 for (i = njobs, jp = jobtab; ; jp++) {
4175 if (jp->state != JOBDONE || !jp->waited)
4184 memset(jp, 0, sizeof(*jp));
4186 /* jp->jobctl is a bitfield.
4187 * "jp->jobctl |= jobctl" likely to give awful code */
4191 jp->prev_job = curjob;
4196 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4198 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4205 * Return a string identifying a command (to be printed by the
4208 static char *cmdnextc;
4211 cmdputs(const char *s)
4213 static const char vstype[VSTYPE + 1][3] = {
4214 "", "}", "-", "+", "?", "=",
4215 "%", "%%", "#", "##"
4216 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4219 const char *p, *str;
4223 unsigned char subtype = 0;
4227 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4229 while ((c = *p++) != '\0') {
4237 if ((subtype & VSTYPE) == VSLENGTH)
4241 if (!(subtype & VSQUOTE) == !(quoted & 1))
4247 str = "\"}" + !(quoted & 1);
4254 case CTLBACKQ+CTLQUOTE:
4257 #if ENABLE_SH_MATH_SUPPORT
4272 if ((subtype & VSTYPE) != VSNORMAL)
4274 str = vstype[subtype & VSTYPE];
4275 if (subtype & VSNUL)
4284 /* These can only happen inside quotes */
4297 while ((c = *str++) != '\0') {
4300 } /* while *p++ not NUL */
4303 USTPUTC('"', nextc);
4309 /* cmdtxt() and cmdlist() call each other */
4310 static void cmdtxt(union node *n);
4313 cmdlist(union node *np, int sep)
4315 for (; np; np = np->narg.next) {
4319 if (sep && np->narg.next)
4325 cmdtxt(union node *n)
4328 struct nodelist *lp;
4339 lp = n->npipe.cmdlist;
4357 cmdtxt(n->nbinary.ch1);
4373 cmdtxt(n->nif.test);
4375 if (n->nif.elsepart) {
4376 cmdtxt(n->nif.ifpart);
4378 n = n->nif.elsepart;
4396 cmdtxt(n->nbinary.ch1);
4406 cmdputs(n->nfor.var);
4408 cmdlist(n->nfor.args, 1);
4413 cmdputs(n->narg.text);
4417 cmdlist(n->ncmd.args, 1);
4418 cmdlist(n->ncmd.redirect, 0);
4431 cmdputs(n->ncase.expr->narg.text);
4433 for (np = n->ncase.cases; np; np = np->nclist.next) {
4434 cmdtxt(np->nclist.pattern);
4436 cmdtxt(np->nclist.body);
4450 #if ENABLE_ASH_BASH_COMPAT
4465 cmdputs(utoa(n->nfile.fd));
4467 if (n->type == NTOFD || n->type == NFROMFD) {
4468 cmdputs(utoa(n->ndup.dupfd));
4477 commandtext(union node *n)
4481 STARTSTACKSTR(cmdnextc);
4483 name = stackblock();
4484 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4485 name, cmdnextc, cmdnextc));
4486 return ckstrdup(name);
4491 * Fork off a subshell. If we are doing job control, give the subshell its
4492 * own process group. Jp is a job structure that the job is to be added to.
4493 * N is the command that will be evaluated by the child. Both jp and n may
4494 * be NULL. The mode parameter can be one of the following:
4495 * FORK_FG - Fork off a foreground process.
4496 * FORK_BG - Fork off a background process.
4497 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4498 * process group even if job control is on.
4500 * When job control is turned off, background processes have their standard
4501 * input redirected to /dev/null (except for the second and later processes
4504 * Called with interrupts off.
4507 * Clear traps on a fork.
4514 for (tp = trap; tp < &trap[NSIG]; tp++) {
4515 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4517 if (trap_ptr == trap)
4519 /* else: it "belongs" to trap_ptr vector, don't free */
4521 if ((tp - trap) != 0)
4522 setsignal(tp - trap);
4528 /* Lives far away from here, needed for forkchild */
4529 static void closescript(void);
4531 /* Called after fork(), in child */
4532 static NOINLINE void
4533 forkchild(struct job *jp, union node *n, int mode)
4537 TRACE(("Child shell %d\n", getpid()));
4541 /* man bash: "Non-builtin commands run by bash have signal handlers
4542 * set to the values inherited by the shell from its parent".
4543 * Do we do it correctly? */
4547 if (mode == FORK_NOJOB /* is it `xxx` ? */
4548 && n && n->type == NCMD /* is it single cmd? */
4549 /* && n->ncmd.args->type == NARG - always true? */
4550 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4551 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4552 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4554 TRACE(("Trap hack\n"));
4555 /* Awful hack for `trap` or $(trap).
4557 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4558 * contains an example where "trap" is executed in a subshell:
4560 * save_traps=$(trap)
4562 * eval "$save_traps"
4564 * Standard does not say that "trap" in subshell shall print
4565 * parent shell's traps. It only says that its output
4566 * must have suitable form, but then, in the above example
4567 * (which is not supposed to be normative), it implies that.
4569 * bash (and probably other shell) does implement it
4570 * (traps are reset to defaults, but "trap" still shows them),
4571 * but as a result, "trap" logic is hopelessly messed up:
4574 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4575 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4576 * # true | trap <--- trap is in subshell - no output (ditto)
4577 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4578 * trap -- 'echo Ho' SIGWINCH
4579 * # echo `(trap)` <--- in subshell in subshell - output
4580 * trap -- 'echo Ho' SIGWINCH
4581 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4582 * trap -- 'echo Ho' SIGWINCH
4584 * The rules when to forget and when to not forget traps
4585 * get really complex and nonsensical.
4587 * Our solution: ONLY bare $(trap) or `trap` is special.
4589 /* Save trap handler strings for trap builtin to print */
4590 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4591 /* Fall through into clearing traps */
4595 /* do job control only in root shell */
4597 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4600 if (jp->nprocs == 0)
4603 pgrp = jp->ps[0].ps_pid;
4604 /* this can fail because we are doing it in the parent also */
4606 if (mode == FORK_FG)
4607 xtcsetpgrp(ttyfd, pgrp);
4612 if (mode == FORK_BG) {
4613 /* man bash: "When job control is not in effect,
4614 * asynchronous commands ignore SIGINT and SIGQUIT" */
4617 if (jp->nprocs == 0) {
4619 if (open(bb_dev_null, O_RDONLY) != 0)
4620 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4624 if (iflag) { /* why if iflag only? */
4629 * "In all cases, bash ignores SIGQUIT. Non-builtin
4630 * commands run by bash have signal handlers
4631 * set to the values inherited by the shell
4633 * Take care of the second rule: */
4637 if (n && n->type == NCMD
4638 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4640 TRACE(("Job hack\n"));
4641 /* "jobs": we do not want to clear job list for it,
4642 * instead we remove only _its_ own_ job from job list.
4643 * This makes "jobs .... | cat" more useful.
4649 for (jp = curjob; jp; jp = jp->prev_job)
4654 /* Called after fork(), in parent */
4656 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4659 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4661 TRACE(("In parent shell: child = %d\n", pid));
4663 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4669 if (mode != FORK_NOJOB && jp->jobctl) {
4672 if (jp->nprocs == 0)
4675 pgrp = jp->ps[0].ps_pid;
4676 /* This can fail because we are doing it in the child also */
4680 if (mode == FORK_BG) {
4681 backgndpid = pid; /* set $! */
4682 set_curjob(jp, CUR_RUNNING);
4685 struct procstat *ps = &jp->ps[jp->nprocs++];
4688 ps->ps_cmd = nullstr;
4690 if (doing_jobctl && n)
4691 ps->ps_cmd = commandtext(n);
4697 forkshell(struct job *jp, union node *n, int mode)
4701 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4704 TRACE(("Fork failed, errno=%d", errno));
4707 ash_msg_and_raise_error("can't fork");
4710 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4711 forkchild(jp, n, mode);
4713 forkparent(jp, n, mode, pid);
4719 * Wait for job to finish.
4721 * Under job control we have the problem that while a child process
4722 * is running interrupts generated by the user are sent to the child
4723 * but not to the shell. This means that an infinite loop started by
4724 * an interactive user may be hard to kill. With job control turned off,
4725 * an interactive user may place an interactive program inside a loop.
4726 * If the interactive program catches interrupts, the user doesn't want
4727 * these interrupts to also abort the loop. The approach we take here
4728 * is to have the shell ignore interrupt signals while waiting for a
4729 * foreground process to terminate, and then send itself an interrupt
4730 * signal if the child process was terminated by an interrupt signal.
4731 * Unfortunately, some programs want to do a bit of cleanup and then
4732 * exit on interrupt; unless these processes terminate themselves by
4733 * sending a signal to themselves (instead of calling exit) they will
4734 * confuse this approach.
4736 * Called with interrupts off.
4739 waitforjob(struct job *jp)
4743 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4746 while (jp->state == JOBRUNNING) {
4747 /* In non-interactive shells, we _can_ get
4748 * a keyboard signal here and be EINTRed,
4749 * but we just loop back, waiting for command to complete.
4752 * "If bash is waiting for a command to complete and receives
4753 * a signal for which a trap has been set, the trap
4754 * will not be executed until the command completes."
4756 * Reality is that even if trap is not set, bash
4757 * will not act on the signal until command completes.
4758 * Try this. sleep5intoff.c:
4759 * #include <signal.h>
4760 * #include <unistd.h>
4763 * sigemptyset(&set);
4764 * sigaddset(&set, SIGINT);
4765 * sigaddset(&set, SIGQUIT);
4766 * sigprocmask(SIG_BLOCK, &set, NULL);
4770 * $ bash -c './sleep5intoff; echo hi'
4771 * ^C^C^C^C <--- pressing ^C once a second
4773 * $ bash -c './sleep5intoff; echo hi'
4774 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4777 dowait(DOWAIT_BLOCK, jp);
4784 xtcsetpgrp(ttyfd, rootpid);
4786 * This is truly gross.
4787 * If we're doing job control, then we did a TIOCSPGRP which
4788 * caused us (the shell) to no longer be in the controlling
4789 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4790 * intuit from the subprocess exit status whether a SIGINT
4791 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4793 if (jp->sigint) /* TODO: do the same with all signals */
4794 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4796 if (jp->state == JOBDONE)
4803 * return 1 if there are stopped jobs, otherwise 0
4815 if (jp && jp->state == JOBSTOPPED) {
4816 out2str("You have stopped jobs.\n");
4825 /* ============ redir.c
4827 * Code for dealing with input/output redirection.
4830 #define EMPTY -2 /* marks an unused slot in redirtab */
4831 #define CLOSED -3 /* marks a slot of previously-closed fd */
4834 * Open a file in noclobber mode.
4835 * The code was copied from bash.
4838 noclobberopen(const char *fname)
4841 struct stat finfo, finfo2;
4844 * If the file exists and is a regular file, return an error
4847 r = stat(fname, &finfo);
4848 if (r == 0 && S_ISREG(finfo.st_mode)) {
4854 * If the file was not present (r != 0), make sure we open it
4855 * exclusively so that if it is created before we open it, our open
4856 * will fail. Make sure that we do not truncate an existing file.
4857 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4858 * file was not a regular file, we leave O_EXCL off.
4861 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4862 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4864 /* If the open failed, return the file descriptor right away. */
4869 * OK, the open succeeded, but the file may have been changed from a
4870 * non-regular file to a regular file between the stat and the open.
4871 * We are assuming that the O_EXCL open handles the case where FILENAME
4872 * did not exist and is symlinked to an existing file between the stat
4877 * If we can open it and fstat the file descriptor, and neither check
4878 * revealed that it was a regular file, and the file has not been
4879 * replaced, return the file descriptor.
4881 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4882 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4885 /* The file has been replaced. badness. */
4892 * Handle here documents. Normally we fork off a process to write the
4893 * data to a pipe. If the document is short, we can stuff the data in
4894 * the pipe without forking.
4896 /* openhere needs this forward reference */
4897 static void expandhere(union node *arg, int fd);
4899 openhere(union node *redir)
4905 ash_msg_and_raise_error("pipe call failed");
4906 if (redir->type == NHERE) {
4907 len = strlen(redir->nhere.doc->narg.text);
4908 if (len <= PIPE_BUF) {
4909 full_write(pip[1], redir->nhere.doc->narg.text, len);
4913 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4916 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4917 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4918 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4919 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4920 signal(SIGPIPE, SIG_DFL);
4921 if (redir->type == NHERE)
4922 full_write(pip[1], redir->nhere.doc->narg.text, len);
4924 expandhere(redir->nhere.doc, pip[1]);
4925 _exit(EXIT_SUCCESS);
4933 openredirect(union node *redir)
4938 switch (redir->nfile.type) {
4940 fname = redir->nfile.expfname;
4941 f = open(fname, O_RDONLY);
4946 fname = redir->nfile.expfname;
4947 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4952 #if ENABLE_ASH_BASH_COMPAT
4955 /* Take care of noclobber mode. */
4957 fname = redir->nfile.expfname;
4958 f = noclobberopen(fname);
4965 fname = redir->nfile.expfname;
4966 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4971 fname = redir->nfile.expfname;
4972 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4980 /* Fall through to eliminate warning. */
4981 /* Our single caller does this itself */
4988 f = openhere(redir);
4994 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4996 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5000 * Copy a file descriptor to be >= to. Returns -1
5001 * if the source file descriptor is closed, EMPTY if there are no unused
5002 * file descriptors left.
5004 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5005 * old code was doing close(to) prior to copyfd() to achieve the same */
5007 COPYFD_EXACT = (int)~(INT_MAX),
5008 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5011 copyfd(int from, int to)
5015 if (to & COPYFD_EXACT) {
5016 to &= ~COPYFD_EXACT;
5018 newfd = dup2(from, to);
5020 newfd = fcntl(from, F_DUPFD, to);
5023 if (errno == EMFILE)
5025 /* Happens when source fd is not open: try "echo >&99" */
5026 ash_msg_and_raise_error("%d: %m", from);
5031 /* Struct def and variable are moved down to the first usage site */
5036 struct redirtab *next;
5039 struct two_fd_t two_fd[];
5041 #define redirlist (G_var.redirlist)
5043 static int need_to_remember(struct redirtab *rp, int fd)
5047 if (!rp) /* remembering was not requested */
5050 for (i = 0; i < rp->pair_count; i++) {
5051 if (rp->two_fd[i].orig == fd) {
5052 /* already remembered */
5059 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5060 static int is_hidden_fd(struct redirtab *rp, int fd)
5063 struct parsefile *pf;
5067 /* Check open scripts' fds */
5070 /* We skip pf_fd == 0 case because of the following case:
5071 * $ ash # running ash interactively
5073 * and in script.sh: "exec 9>&0".
5074 * Even though top-level pf_fd _is_ 0,
5075 * it's still ok to use it: "read" builtin uses it,
5076 * why should we cripple "exec" builtin?
5078 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5086 /* Check saved fds of redirects */
5087 fd |= COPYFD_RESTORE;
5088 for (i = 0; i < rp->pair_count; i++) {
5089 if (rp->two_fd[i].copy == fd) {
5097 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5098 * old file descriptors are stashed away so that the redirection can be
5099 * undone by calling popredir.
5101 /* flags passed to redirect */
5102 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5103 #define REDIR_SAVEFD2 03 /* set preverrout */
5105 redirect(union node *redir, int flags)
5107 struct redirtab *sv;
5112 int copied_fd2 = -1;
5122 if (flags & REDIR_PUSH) {
5123 union node *tmp = redir;
5126 #if ENABLE_ASH_BASH_COMPAT
5127 if (tmp->nfile.type == NTO2)
5130 tmp = tmp->nfile.next;
5132 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5133 sv->next = redirlist;
5134 sv->pair_count = sv_pos;
5136 sv->nullredirs = g_nullredirs - 1;
5138 while (sv_pos > 0) {
5140 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5146 fd = redir->nfile.fd;
5147 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5148 right_fd = redir->ndup.dupfd;
5149 //bb_error_msg("doing %d > %d", fd, right_fd);
5150 /* redirect from/to same file descriptor? */
5153 /* "echo >&10" and 10 is a fd opened to a sh script? */
5154 if (is_hidden_fd(sv, right_fd)) {
5155 errno = EBADF; /* as if it is closed */
5156 ash_msg_and_raise_error("%d: %m", right_fd);
5160 newfd = openredirect(redir); /* always >= 0 */
5162 /* Descriptor wasn't open before redirect.
5163 * Mark it for close in the future */
5164 if (need_to_remember(sv, fd)) {
5165 goto remember_to_close;
5170 #if ENABLE_ASH_BASH_COMPAT
5173 if (need_to_remember(sv, fd)) {
5174 /* Copy old descriptor */
5175 /* Careful to not accidentally "save"
5176 * to the same fd as right side fd in N>&M */
5177 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5178 i = fcntl(fd, F_DUPFD, minfd);
5179 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5180 * are closed in popredir() in the child, preventing them from leaking
5181 * into child. (popredir() also cleans up the mess in case of failures)
5186 /* Strange error (e.g. "too many files" EMFILE?) */
5190 ash_msg_and_raise_error("%d: %m", fd);
5193 /* EBADF: it is not open - good, remember to close it */
5196 } else { /* fd is open, save its copy */
5197 /* "exec fd>&-" should not close fds
5198 * which point to script file(s).
5199 * Force them to be restored afterwards */
5200 if (is_hidden_fd(sv, fd))
5201 i |= COPYFD_RESTORE;
5205 sv->two_fd[sv_pos].orig = fd;
5206 sv->two_fd[sv_pos].copy = i;
5210 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5211 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5212 /* Don't want to trigger debugging */
5216 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5218 } else if (fd != newfd) { /* move newfd to fd */
5219 copyfd(newfd, fd | COPYFD_EXACT);
5220 #if ENABLE_ASH_BASH_COMPAT
5221 if (!(redir->nfile.type == NTO2 && fd == 2))
5225 #if ENABLE_ASH_BASH_COMPAT
5226 if (redir->nfile.type == NTO2 && fd == 1) {
5227 /* We already redirected it to fd 1, now copy it to 2 */
5233 } while ((redir = redir->nfile.next) != NULL);
5236 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5237 preverrout_fd = copied_fd2;
5241 * Undo the effects of the last redirection.
5244 popredir(int drop, int restore)
5246 struct redirtab *rp;
5249 if (--g_nullredirs >= 0)
5253 for (i = 0; i < rp->pair_count; i++) {
5254 int fd = rp->two_fd[i].orig;
5255 int copy = rp->two_fd[i].copy;
5256 if (copy == CLOSED) {
5261 if (copy != EMPTY) {
5262 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5263 copy &= ~COPYFD_RESTORE;
5265 copyfd(copy, fd | COPYFD_EXACT);
5267 close(copy & ~COPYFD_RESTORE);
5270 redirlist = rp->next;
5271 g_nullredirs = rp->nullredirs;
5277 * Undo all redirections. Called on error or interrupt.
5281 * Discard all saved file descriptors.
5284 clearredir(int drop)
5290 popredir(drop, /*restore:*/ 0);
5295 redirectsafe(union node *redir, int flags)
5298 volatile int saveint;
5299 struct jmploc *volatile savehandler = exception_handler;
5300 struct jmploc jmploc;
5303 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5304 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5306 exception_handler = &jmploc;
5307 redirect(redir, flags);
5309 exception_handler = savehandler;
5310 if (err && exception_type != EXERROR)
5311 longjmp(exception_handler->loc, 1);
5312 RESTORE_INT(saveint);
5317 /* ============ Routines to expand arguments to commands
5319 * We have to deal with backquotes, shell variables, and file metacharacters.
5322 #if ENABLE_SH_MATH_SUPPORT
5324 ash_arith(const char *s)
5326 arith_eval_hooks_t math_hooks;
5330 math_hooks.lookupvar = lookupvar;
5331 math_hooks.setvar = setvar2;
5332 math_hooks.endofname = endofname;
5335 result = arith(s, &errcode, &math_hooks);
5338 ash_msg_and_raise_error("exponent less than 0");
5340 ash_msg_and_raise_error("divide by zero");
5342 ash_msg_and_raise_error("expression recursion loop detected");
5343 raise_error_syntax(s);
5354 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5355 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5356 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5357 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5358 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5359 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5360 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5361 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5362 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5366 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5367 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5368 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5369 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5370 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5373 * Structure specifying which parts of the string should be searched
5374 * for IFS characters.
5377 struct ifsregion *next; /* next region in list */
5378 int begoff; /* offset of start of region */
5379 int endoff; /* offset of end of region */
5380 int nulonly; /* search for nul bytes only */
5384 struct strlist *list;
5385 struct strlist **lastp;
5388 /* output of current string */
5389 static char *expdest;
5390 /* list of back quote expressions */
5391 static struct nodelist *argbackq;
5392 /* first struct in list of ifs regions */
5393 static struct ifsregion ifsfirst;
5394 /* last struct in list */
5395 static struct ifsregion *ifslastp;
5396 /* holds expanded arg list */
5397 static struct arglist exparg;
5407 expdest = makestrspace(32, expdest);
5408 len = fmtstr(expdest, 32, arith_t_fmt, num);
5409 STADJUST(len, expdest);
5414 esclen(const char *start, const char *p)
5418 while (p > start && (unsigned char)*--p == CTLESC) {
5425 * Remove any CTLESC characters from a string.
5428 rmescapes(char *str, int flag)
5430 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5434 unsigned protect_against_glob;
5437 p = strpbrk(str, qchars);
5443 if (flag & RMESCAPE_ALLOC) {
5444 size_t len = p - str;
5445 size_t fulllen = len + strlen(p) + 1;
5447 if (flag & RMESCAPE_GROW) {
5448 int strloc = str - (char *)stackblock();
5449 r = makestrspace(fulllen, expdest);
5450 /* p and str may be invalidated by makestrspace */
5451 str = (char *)stackblock() + strloc;
5453 } else if (flag & RMESCAPE_HEAP) {
5454 r = ckmalloc(fulllen);
5456 r = stalloc(fulllen);
5460 q = (char *)memcpy(q, str, len) + len;
5464 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5465 globbing = flag & RMESCAPE_GLOB;
5466 protect_against_glob = globbing;
5468 if ((unsigned char)*p == CTLQUOTEMARK) {
5469 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5470 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5471 // Note: both inquotes and protect_against_glob only affect whether
5472 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5473 inquotes = ~inquotes;
5475 protect_against_glob = globbing;
5479 /* naked back slash */
5480 protect_against_glob = 0;
5483 if ((unsigned char)*p == CTLESC) {
5485 if (protect_against_glob && inquotes && *p != '/') {
5489 protect_against_glob = globbing;
5494 if (flag & RMESCAPE_GROW) {
5496 STADJUST(q - r + 1, expdest);
5500 #define pmatch(a, b) !fnmatch((a), (b), 0)
5503 * Prepare a pattern for a expmeta (internal glob(3)) call.
5505 * Returns an stalloced string.
5508 preglob(const char *pattern, int quoted, int flag)
5510 flag |= RMESCAPE_GLOB;
5512 flag |= RMESCAPE_QUOTED;
5514 return rmescapes((char *)pattern, flag);
5518 * Put a string on the stack.
5521 memtodest(const char *p, size_t len, int syntax, int quotes)
5525 q = makestrspace(quotes ? len * 2 : len, q);
5528 unsigned char c = *p++;
5532 int n = SIT(c, syntax);
5533 if (n == CCTL || n == CBACK)
5543 strtodest(const char *p, int syntax, int quotes)
5545 memtodest(p, strlen(p), syntax, quotes);
5549 * Record the fact that we have to scan this region of the
5550 * string for IFS characters.
5553 recordregion(int start, int end, int nulonly)
5555 struct ifsregion *ifsp;
5557 if (ifslastp == NULL) {
5561 ifsp = ckzalloc(sizeof(*ifsp));
5562 /*ifsp->next = NULL; - ckzalloc did it */
5563 ifslastp->next = ifsp;
5567 ifslastp->begoff = start;
5568 ifslastp->endoff = end;
5569 ifslastp->nulonly = nulonly;
5573 removerecordregions(int endoff)
5575 if (ifslastp == NULL)
5578 if (ifsfirst.endoff > endoff) {
5579 while (ifsfirst.next != NULL) {
5580 struct ifsregion *ifsp;
5582 ifsp = ifsfirst.next->next;
5583 free(ifsfirst.next);
5584 ifsfirst.next = ifsp;
5587 if (ifsfirst.begoff > endoff)
5590 ifslastp = &ifsfirst;
5591 ifsfirst.endoff = endoff;
5596 ifslastp = &ifsfirst;
5597 while (ifslastp->next && ifslastp->next->begoff < endoff)
5598 ifslastp=ifslastp->next;
5599 while (ifslastp->next != NULL) {
5600 struct ifsregion *ifsp;
5602 ifsp = ifslastp->next->next;
5603 free(ifslastp->next);
5604 ifslastp->next = ifsp;
5607 if (ifslastp->endoff > endoff)
5608 ifslastp->endoff = endoff;
5612 exptilde(char *startp, char *p, int flags)
5618 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5623 while ((c = *++p) != '\0') {
5630 if (flags & EXP_VARTILDE)
5640 if (*name == '\0') {
5641 home = lookupvar("HOME");
5643 pw = getpwnam(name);
5648 if (!home || !*home)
5651 startloc = expdest - (char *)stackblock();
5652 strtodest(home, SQSYNTAX, quotes);
5653 recordregion(startloc, expdest - (char *)stackblock(), 0);
5661 * Execute a command inside back quotes. If it's a builtin command, we
5662 * want to save its output in a block obtained from malloc. Otherwise
5663 * we fork off a subprocess and get the output of the command via a pipe.
5664 * Should be called with interrupts off.
5666 struct backcmd { /* result of evalbackcmd */
5667 int fd; /* file descriptor to read from */
5668 int nleft; /* number of chars in buffer */
5669 char *buf; /* buffer */
5670 struct job *jp; /* job structure for command */
5673 /* These forward decls are needed to use "eval" code for backticks handling: */
5674 static uint8_t back_exitstatus; /* exit status of backquoted command */
5675 #define EV_EXIT 01 /* exit after evaluating tree */
5676 static void evaltree(union node *, int);
5678 static void FAST_FUNC
5679 evalbackcmd(union node *n, struct backcmd *result)
5690 saveherefd = herefd;
5698 ash_msg_and_raise_error("pipe call failed");
5699 jp = makejob(/*n,*/ 1);
5700 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5705 copyfd(pip[1], 1 | COPYFD_EXACT);
5709 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5713 result->fd = pip[0];
5716 herefd = saveherefd;
5718 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5719 result->fd, result->buf, result->nleft, result->jp));
5723 * Expand stuff in backwards quotes.
5726 expbackq(union node *cmd, int quoted, int quotes)
5734 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5735 struct stackmark smark;
5738 setstackmark(&smark);
5740 startloc = dest - (char *)stackblock();
5742 evalbackcmd(cmd, &in);
5743 popstackmark(&smark);
5750 memtodest(p, i, syntax, quotes);
5754 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5755 TRACE(("expbackq: read returns %d\n", i));
5764 back_exitstatus = waitforjob(in.jp);
5768 /* Eat all trailing newlines */
5770 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5775 recordregion(startloc, dest - (char *)stackblock(), 0);
5776 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5777 (dest - (char *)stackblock()) - startloc,
5778 (dest - (char *)stackblock()) - startloc,
5779 stackblock() + startloc));
5782 #if ENABLE_SH_MATH_SUPPORT
5784 * Expand arithmetic expression. Backup to start of expression,
5785 * evaluate, place result in (backed up) result, adjust string position.
5798 * This routine is slightly over-complicated for
5799 * efficiency. Next we scan backwards looking for the
5800 * start of arithmetic.
5802 start = stackblock();
5809 while ((unsigned char)*p != CTLARI) {
5813 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5818 esc = esclen(start, p);
5828 removerecordregions(begoff);
5835 rmescapes(p + 2, 0);
5837 len = cvtnum(ash_arith(p + 2));
5840 recordregion(begoff, begoff + len, 0);
5844 /* argstr needs it */
5845 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5848 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5849 * characters to allow for further processing. Otherwise treat
5850 * $@ like $* since no splitting will be performed.
5852 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5853 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5854 * for correct expansion of "B=$A" word.
5857 argstr(char *p, int flags, struct strlist *var_str_list)
5859 static const char spclchars[] ALIGN1 = {
5867 CTLBACKQ | CTLQUOTE,
5868 #if ENABLE_SH_MATH_SUPPORT
5873 const char *reject = spclchars;
5874 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5875 int breakall = flags & EXP_WORD;
5880 if (!(flags & EXP_VARTILDE)) {
5882 } else if (flags & EXP_VARTILDE2) {
5887 if (flags & EXP_TILDE) {
5890 flags &= ~EXP_TILDE;
5893 if (*q == CTLESC && (flags & EXP_QWORD))
5896 p = exptilde(p, q, flags);
5899 startloc = expdest - (char *)stackblock();
5903 length += strcspn(p + length, reject);
5907 #if ENABLE_SH_MATH_SUPPORT
5911 /* c == '=' || c == ':' || c == CTLENDARI */
5917 expdest = stack_nputstr(p, length, expdest);
5918 newloc = expdest - (char *)stackblock();
5919 if (breakall && !inquotes && newloc > startloc) {
5920 recordregion(startloc, newloc, 0);
5931 if (flags & EXP_VARTILDE2) {
5935 flags |= EXP_VARTILDE2;
5940 * sort of a hack - expand tildes in variable
5941 * assignments (after the first '=' and after ':'s).
5950 case CTLENDVAR: /* ??? */
5953 /* "$@" syntax adherence hack */
5955 && memcmp(p, dolatstr, 4) == 0
5956 && ( p[4] == CTLQUOTEMARK
5957 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5960 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
5963 inquotes = !inquotes;
5976 p = evalvar(p, flags, var_str_list);
5980 case CTLBACKQ|CTLQUOTE:
5981 expbackq(argbackq->n, c, quotes);
5982 argbackq = argbackq->next;
5984 #if ENABLE_SH_MATH_SUPPORT
5997 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
6000 // This commented out code was added by James Simmons <jsimmons@infradead.org>
6001 // as part of a larger change when he added support for ${var/a/b}.
6002 // However, it broke # and % operators:
6006 //echo ${var#ab} abcdcd abcdcd
6007 //echo ${var##ab} abcdcd abcdcd
6008 //echo ${var#a*b} abcdcd ababcdcd (!)
6009 //echo ${var##a*b} cdcd cdcd
6010 //echo ${var#?} babcdcd ababcdcd (!)
6011 //echo ${var##?} babcdcd babcdcd
6012 //echo ${var#*} ababcdcd babcdcd (!)
6014 //echo ${var%cd} ababcd ababcd
6015 //echo ${var%%cd} ababcd abab (!)
6016 //echo ${var%c*d} ababcd ababcd
6017 //echo ${var%%c*d} abab ababcdcd (!)
6018 //echo ${var%?} ababcdc ababcdc
6019 //echo ${var%%?} ababcdc ababcdcd (!)
6020 //echo ${var%*} ababcdcd ababcdcd
6023 // Commenting it back out helped. Remove it completely if it really
6026 char *loc, *loc2; //, *full;
6032 int match; // = strlen(str);
6033 const char *s = loc2;
6040 match = pmatch(str, s); // this line was deleted
6042 // // chop off end if its '*'
6043 // full = strrchr(str, '*');
6044 // if (full && full != str)
6047 // // If str starts with '*' replace with s.
6048 // if ((*str == '*') && strlen(s) >= match) {
6049 // full = xstrdup(s);
6050 // strncpy(full+strlen(s)-match+1, str+1, match-1);
6052 // full = xstrndup(str, match);
6053 // match = strncmp(s, full, strlen(full));
6057 if (match) // if (!match)
6059 if (quotes && (unsigned char)*loc == CTLESC)
6068 scanright(char *startp, char *rmesc, char *rmescend, char *pattern, int quotes, int match_at_start)
6070 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6071 int try2optimize = match_at_start;
6077 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6078 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6079 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6081 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6082 * and on each iteration they go back two/one char until they reach the beginning.
6083 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6085 /* TODO: document in what other circumstances we are called. */
6087 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6090 const char *s = loc2;
6091 if (match_at_start) {
6095 match = pmatch(pattern, s);
6096 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6100 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6102 /* Maybe we can optimize this:
6103 * if pattern ends with unescaped *, we can avoid checking
6104 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6105 * it wont match truncated "raw_value_of_" strings too.
6107 unsigned plen = strlen(pattern);
6108 /* Does it end with "*"? */
6109 if (plen != 0 && pattern[--plen] == '*') {
6110 /* "xxxx*" is not escaped */
6111 /* "xxx\*" is escaped */
6112 /* "xx\\*" is not escaped */
6113 /* "x\\\*" is escaped */
6115 while (plen != 0 && pattern[--plen] == '\\')
6118 break; /* ends with unescaped "*" */
6126 esc = esclen(startp, loc);
6137 static void varunset(const char *, const char *, const char *, int) NORETURN;
6139 varunset(const char *end, const char *var, const char *umsg, int varflags)
6145 msg = "parameter not set";
6147 if ((unsigned char)*end == CTLENDVAR) {
6148 if (varflags & VSNUL)
6154 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6157 #if ENABLE_ASH_BASH_COMPAT
6159 parse_sub_pattern(char *arg, int inquotes)
6161 char *idx, *repl = NULL;
6170 /* Only the first '/' seen is our separator */
6177 if (!inquotes && c == '\\' && arg[1] == '\\')
6178 arg++; /* skip both \\, not just first one */
6185 #endif /* ENABLE_ASH_BASH_COMPAT */
6188 subevalvar(char *p, char *str, int strloc, int subtype,
6189 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6191 struct nodelist *saveargbackq = argbackq;
6194 char *rmesc, *rmescend;
6195 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6196 IF_ASH_BASH_COMPAT(char null = '\0';)
6197 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6198 int saveherefd = herefd;
6199 int amount, workloc, resetloc;
6201 char *(*scan)(char*, char*, char*, char*, int, int);
6204 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6206 STPUTC('\0', expdest);
6207 herefd = saveherefd;
6208 argbackq = saveargbackq;
6209 startp = (char *)stackblock() + startloc;
6213 setvar(str, startp, 0);
6214 amount = startp - expdest;
6215 STADJUST(amount, expdest);
6218 #if ENABLE_ASH_BASH_COMPAT
6220 loc = str = stackblock() + strloc;
6221 /* Read POS in ${var:POS:LEN} */
6222 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6223 len = str - startp - 1;
6225 /* *loc != '\0', guaranteed by parser */
6229 /* Adjust the length by the number of escapes */
6230 for (ptr = startp; ptr < (str - 1); ptr++) {
6231 if ((unsigned char)*ptr == CTLESC) {
6239 if (*loc++ == ':') {
6243 /* Skip POS in ${var:POS:LEN} */
6245 while (*loc && *loc != ':') {
6247 * bash complains on: var=qwe; echo ${var:1a:123}
6249 ash_msg_and_raise_error(msg_illnum, str);
6253 if (*loc++ == ':') {
6257 if (pos >= orig_len) {
6261 if (len > (orig_len - pos))
6262 len = orig_len - pos;
6264 for (str = startp; pos; str++, pos--) {
6265 if (quotes && (unsigned char)*str == CTLESC)
6268 for (loc = startp; len; len--) {
6269 if (quotes && (unsigned char)*str == CTLESC)
6274 amount = loc - expdest;
6275 STADJUST(amount, expdest);
6280 varunset(p, str, startp, varflags);
6283 resetloc = expdest - (char *)stackblock();
6285 /* We'll comeback here if we grow the stack while handling
6286 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6287 * stack will need rebasing, and we'll need to remove our work
6290 IF_ASH_BASH_COMPAT(restart:)
6292 amount = expdest - ((char *)stackblock() + resetloc);
6293 STADJUST(-amount, expdest);
6294 startp = (char *)stackblock() + startloc;
6297 rmescend = (char *)stackblock() + strloc;
6299 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6300 if (rmesc != startp) {
6302 startp = (char *)stackblock() + startloc;
6306 str = (char *)stackblock() + strloc;
6307 preglob(str, varflags & VSQUOTE, 0);
6308 workloc = expdest - (char *)stackblock();
6310 #if ENABLE_ASH_BASH_COMPAT
6311 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6315 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6320 /* If there's no pattern to match, return the expansion unmolested */
6329 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6331 /* No match, advance */
6332 char *restart_detect = stackblock();
6334 STPUTC(*idx, expdest);
6335 if (quotes && (unsigned char)*idx == CTLESC) {
6338 STPUTC(*idx, expdest);
6340 if (stackblock() != restart_detect)
6345 /* continue; - prone to quadratic behavior, smarter code: */
6348 if (str[0] == '*') {
6349 /* Pattern is "*foo". If "*foo" does not match "long_string",
6350 * it would never match "ong_string" etc, no point in trying.
6357 if (subtype == VSREPLACEALL) {
6359 if (quotes && (unsigned char)*idx == CTLESC)
6368 for (loc = repl; *loc; loc++) {
6369 char *restart_detect = stackblock();
6370 STPUTC(*loc, expdest);
6371 if (stackblock() != restart_detect)
6376 if (subtype == VSREPLACE) {
6378 char *restart_detect = stackblock();
6379 STPUTC(*idx, expdest);
6380 if (stackblock() != restart_detect)
6389 /* We've put the replaced text into a buffer at workloc, now
6390 * move it to the right place and adjust the stack.
6392 startp = stackblock() + startloc;
6393 STPUTC('\0', expdest);
6394 memmove(startp, stackblock() + workloc, len);
6395 startp[len++] = '\0';
6396 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6397 STADJUST(-amount, expdest);
6400 #endif /* ENABLE_ASH_BASH_COMPAT */
6402 subtype -= VSTRIMRIGHT;
6404 if (subtype < 0 || subtype > 7)
6407 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6408 zero = subtype >> 1;
6409 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6410 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6412 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6415 memmove(startp, loc, str - loc);
6416 loc = startp + (str - loc) - 1;
6419 amount = loc - expdest;
6420 STADJUST(amount, expdest);
6426 * Add the value of a specialized variable to the stack string.
6427 * name parameter (examples):
6428 * ash -c 'echo $1' name:'1='
6429 * ash -c 'echo $qwe' name:'qwe='
6430 * ash -c 'echo $$' name:'$='
6431 * ash -c 'echo ${$}' name:'$='
6432 * ash -c 'echo ${$##q}' name:'$=q'
6433 * ash -c 'echo ${#$}' name:'$='
6434 * note: examples with bad shell syntax:
6435 * ash -c 'echo ${#$1}' name:'$=1'
6436 * ash -c 'echo ${#1#}' name:'1=#'
6438 static NOINLINE ssize_t
6439 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6446 int subtype = varflags & VSTYPE;
6447 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6448 int quoted = varflags & VSQUOTE;
6449 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6459 num = shellparam.nparam;
6467 goto check_1char_name;
6469 expdest = makestrspace(NOPTS, expdest);
6470 for (i = NOPTS - 1; i >= 0; i--) {
6472 USTPUTC(optletters(i), expdest);
6478 /* handles cases similar to ${#$1} */
6479 if (name[2] != '\0')
6480 raise_error_syntax("bad substitution");
6487 if (quoted && (flags & EXP_FULL)) {
6488 /* note: this is not meant as PEOF value */
6489 sep = 1 << CHAR_BIT;
6494 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6495 i = SIT(sep, syntax);
6496 if (quotes && (i == CCTL || i == CBACK))
6502 while ((p = *ap++) != NULL) {
6505 partlen = strlen(p);
6508 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6509 memtodest(p, partlen, syntax, quotes);
6515 if (subtype == VSPLUS || subtype == VSLENGTH) {
6521 /* note: may put NUL despite sep != 0
6522 * (see sep = 1 << CHAR_BIT above) */
6528 } /* case '@' and '*' */
6539 num = atoi(name); /* number(name) fails on ${N#str} etc */
6540 if (num < 0 || num > shellparam.nparam)
6542 p = num ? shellparam.p[num - 1] : arg0;
6545 /* NB: name has form "VAR=..." */
6547 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6548 * which should be considered before we check variables. */
6550 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6554 str = var_str_list->text;
6555 eq = strchr(str, '=');
6556 if (!eq) /* stop at first non-assignment */
6559 if (name_len == (unsigned)(eq - str)
6560 && strncmp(str, name, name_len) == 0
6563 /* goto value; - WRONG! */
6564 /* think "A=1 A=2 B=$A" */
6566 var_str_list = var_str_list->next;
6567 } while (var_str_list);
6571 p = lookupvar(name);
6577 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6578 memtodest(p, len, syntax, quotes);
6582 if (subtype == VSPLUS || subtype == VSLENGTH)
6583 STADJUST(-len, expdest);
6588 * Expand a variable, and return a pointer to the next character in the
6592 evalvar(char *p, int flags, struct strlist *var_str_list)
6603 varflags = (unsigned char) *p++;
6604 subtype = varflags & VSTYPE;
6605 quoted = varflags & VSQUOTE;
6607 easy = (!quoted || (*var == '@' && shellparam.nparam));
6608 startloc = expdest - (char *)stackblock();
6609 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6612 varlen = varvalue(var, varflags, flags, var_str_list);
6613 if (varflags & VSNUL)
6616 if (subtype == VSPLUS) {
6617 varlen = -1 - varlen;
6621 if (subtype == VSMINUS) {
6625 p, flags | EXP_TILDE |
6626 (quoted ? EXP_QWORD : EXP_WORD),
6636 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6638 if (subevalvar(p, var, /* strloc: */ 0,
6639 subtype, startloc, varflags,
6645 * Remove any recorded regions beyond
6648 removerecordregions(startloc);
6658 if (varlen < 0 && uflag)
6659 varunset(p, var, 0, 0);
6661 if (subtype == VSLENGTH) {
6662 cvtnum(varlen > 0 ? varlen : 0);
6666 if (subtype == VSNORMAL) {
6677 case VSTRIMRIGHTMAX:
6678 #if ENABLE_ASH_BASH_COMPAT
6691 * Terminate the string and start recording the pattern
6694 STPUTC('\0', expdest);
6695 patloc = expdest - (char *)stackblock();
6696 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6698 //TODO: | EXP_REDIR too? All other such places do it too
6699 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6702 int amount = expdest - (
6703 (char *)stackblock() + patloc - 1
6705 STADJUST(-amount, expdest);
6707 /* Remove any recorded regions beyond start of variable */
6708 removerecordregions(startloc);
6710 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6714 if (subtype != VSNORMAL) { /* skip to end of alternative */
6717 unsigned char c = *p++;
6720 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6722 argbackq = argbackq->next;
6723 } else if (c == CTLVAR) {
6724 if ((*p++ & VSTYPE) != VSNORMAL)
6726 } else if (c == CTLENDVAR) {
6736 * Break the argument string into pieces based upon IFS and add the
6737 * strings to the argument list. The regions of the string to be
6738 * searched for IFS characters have been stored by recordregion.
6741 ifsbreakup(char *string, struct arglist *arglist)
6743 struct ifsregion *ifsp;
6748 const char *ifs, *realifs;
6753 if (ifslastp != NULL) {
6756 realifs = ifsset() ? ifsval() : defifs;
6759 p = string + ifsp->begoff;
6760 nulonly = ifsp->nulonly;
6761 ifs = nulonly ? nullstr : realifs;
6763 while (p < string + ifsp->endoff) {
6765 if ((unsigned char)*p == CTLESC)
6767 if (!strchr(ifs, *p)) {
6772 ifsspc = (strchr(defifs, *p) != NULL);
6773 /* Ignore IFS whitespace at start */
6774 if (q == start && ifsspc) {
6780 sp = stzalloc(sizeof(*sp));
6782 *arglist->lastp = sp;
6783 arglist->lastp = &sp->next;
6787 if (p >= string + ifsp->endoff) {
6791 if ((unsigned char)*p == CTLESC)
6793 if (strchr(ifs, *p) == NULL) {
6797 if (strchr(defifs, *p) == NULL) {
6812 } while (ifsp != NULL);
6821 sp = stzalloc(sizeof(*sp));
6823 *arglist->lastp = sp;
6824 arglist->lastp = &sp->next;
6830 struct ifsregion *p;
6835 struct ifsregion *ifsp;
6841 ifsfirst.next = NULL;
6846 * Add a file name to the list.
6849 addfname(const char *name)
6853 sp = stzalloc(sizeof(*sp));
6854 sp->text = ststrdup(name);
6856 exparg.lastp = &sp->next;
6859 static char *expdir;
6862 * Do metacharacter (i.e. *, ?, [...]) expansion.
6865 expmeta(char *enddir, char *name)
6880 for (p = name; *p; p++) {
6881 if (*p == '*' || *p == '?')
6883 else if (*p == '[') {
6890 if (*q == '/' || *q == '\0')
6897 } else if (*p == '\\')
6899 else if (*p == '/') {
6906 if (metaflag == 0) { /* we've reached the end of the file name */
6907 if (enddir != expdir)
6915 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6926 } while (p < start);
6928 if (enddir == expdir) {
6930 } else if (enddir == expdir + 1 && *expdir == '/') {
6939 if (enddir != expdir)
6941 if (*endname == 0) {
6953 while (!pending_int && (dp = readdir(dirp)) != NULL) {
6954 if (dp->d_name[0] == '.' && !matchdot)
6956 if (pmatch(start, dp->d_name)) {
6958 strcpy(enddir, dp->d_name);
6961 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6964 expmeta(p, endname);
6973 static struct strlist *
6974 msort(struct strlist *list, int len)
6976 struct strlist *p, *q = NULL;
6977 struct strlist **lpp;
6985 for (n = half; --n >= 0;) {
6989 q->next = NULL; /* terminate first half of list */
6990 q = msort(list, half); /* sort first half of list */
6991 p = msort(p, len - half); /* sort second half */
6994 #if ENABLE_LOCALE_SUPPORT
6995 if (strcoll(p->text, q->text) < 0)
6997 if (strcmp(p->text, q->text) < 0)
7021 * Sort the results of file name expansion. It calculates the number of
7022 * strings to sort and then calls msort (short for merge sort) to do the
7025 static struct strlist *
7026 expsort(struct strlist *str)
7032 for (sp = str; sp; sp = sp->next)
7034 return msort(str, len);
7038 expandmeta(struct strlist *str /*, int flag*/)
7040 static const char metachars[] ALIGN1 = {
7043 /* TODO - EXP_REDIR */
7046 struct strlist **savelastp;
7052 if (!strpbrk(str->text, metachars))
7054 savelastp = exparg.lastp;
7057 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7059 int i = strlen(str->text);
7060 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7068 if (exparg.lastp == savelastp) {
7073 *exparg.lastp = str;
7074 rmescapes(str->text, 0);
7075 exparg.lastp = &str->next;
7077 *exparg.lastp = NULL;
7078 *savelastp = sp = expsort(*savelastp);
7079 while (sp->next != NULL)
7081 exparg.lastp = &sp->next;
7088 * Perform variable substitution and command substitution on an argument,
7089 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7090 * perform splitting and file name expansion. When arglist is NULL, perform
7091 * here document expansion.
7094 expandarg(union node *arg, struct arglist *arglist, int flag)
7099 argbackq = arg->narg.backquote;
7100 STARTSTACKSTR(expdest);
7101 ifsfirst.next = NULL;
7103 argstr(arg->narg.text, flag,
7104 /* var_str_list: */ arglist ? arglist->list : NULL);
7105 p = _STPUTC('\0', expdest);
7107 if (arglist == NULL) {
7108 return; /* here document expanded */
7110 p = grabstackstr(p);
7111 exparg.lastp = &exparg.list;
7115 if (flag & EXP_FULL) {
7116 ifsbreakup(p, &exparg);
7117 *exparg.lastp = NULL;
7118 exparg.lastp = &exparg.list;
7119 expandmeta(exparg.list /*, flag*/);
7121 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7123 sp = stzalloc(sizeof(*sp));
7126 exparg.lastp = &sp->next;
7130 *exparg.lastp = NULL;
7132 *arglist->lastp = exparg.list;
7133 arglist->lastp = exparg.lastp;
7138 * Expand shell variables and backquotes inside a here document.
7141 expandhere(union node *arg, int fd)
7144 expandarg(arg, (struct arglist *)NULL, 0);
7145 full_write(fd, stackblock(), expdest - (char *)stackblock());
7149 * Returns true if the pattern matches the string.
7152 patmatch(char *pattern, const char *string)
7154 return pmatch(preglob(pattern, 0, 0), string);
7158 * See if a pattern matches in a case statement.
7161 casematch(union node *pattern, char *val)
7163 struct stackmark smark;
7166 setstackmark(&smark);
7167 argbackq = pattern->narg.backquote;
7168 STARTSTACKSTR(expdest);
7170 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7171 /* var_str_list: */ NULL);
7172 STACKSTRNUL(expdest);
7173 result = patmatch(stackblock(), val);
7174 popstackmark(&smark);
7179 /* ============ find_command */
7183 int (*builtin)(int, char **) FAST_FUNC;
7184 /* unsigned flags; */
7186 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7187 /* "regular" builtins always take precedence over commands,
7188 * regardless of PATH=....%builtin... position */
7189 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7190 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7193 smallint cmdtype; /* CMDxxx */
7196 /* index >= 0 for commands without path (slashes) */
7197 /* (TODO: what exactly does the value mean? PATH position?) */
7198 /* index == -1 for commands with slashes */
7199 /* index == (-2 - applet_no) for NOFORK applets */
7200 const struct builtincmd *cmd;
7201 struct funcnode *func;
7204 /* values of cmdtype */
7205 #define CMDUNKNOWN -1 /* no entry in table for command */
7206 #define CMDNORMAL 0 /* command is an executable program */
7207 #define CMDFUNCTION 1 /* command is a shell function */
7208 #define CMDBUILTIN 2 /* command is a shell builtin */
7210 /* action to find_command() */
7211 #define DO_ERR 0x01 /* prints errors */
7212 #define DO_ABS 0x02 /* checks absolute paths */
7213 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7214 #define DO_ALTPATH 0x08 /* using alternate path */
7215 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7217 static void find_command(char *, struct cmdentry *, int, const char *);
7220 /* ============ Hashing commands */
7223 * When commands are first encountered, they are entered in a hash table.
7224 * This ensures that a full path search will not have to be done for them
7225 * on each invocation.
7227 * We should investigate converting to a linear search, even though that
7228 * would make the command name "hash" a misnomer.
7232 struct tblentry *next; /* next entry in hash chain */
7233 union param param; /* definition of builtin function */
7234 smallint cmdtype; /* CMDxxx */
7235 char rehash; /* if set, cd done since entry created */
7236 char cmdname[1]; /* name of command */
7239 static struct tblentry **cmdtable;
7240 #define INIT_G_cmdtable() do { \
7241 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7244 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7248 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7252 #if ENABLE_FEATURE_SH_STANDALONE
7253 if (applet_no >= 0) {
7254 if (APPLET_IS_NOEXEC(applet_no)) {
7258 run_applet_no_and_exit(applet_no, argv);
7260 /* re-exec ourselves with the new arguments */
7261 execve(bb_busybox_exec_path, argv, envp);
7262 /* If they called chroot or otherwise made the binary no longer
7263 * executable, fall through */
7270 execve(cmd, argv, envp);
7271 } while (errno == EINTR);
7273 execve(cmd, argv, envp);
7279 if (errno == ENOEXEC) {
7283 for (ap = argv; *ap; ap++)
7285 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7287 ap[0] = cmd = (char *)DEFAULT_SHELL;
7290 while ((*ap++ = *argv++) != NULL)
7299 * Exec a program. Never returns. If you change this routine, you may
7300 * have to change the find_command routine as well.
7302 static void shellexec(char **, const char *, int) NORETURN;
7304 shellexec(char **argv, const char *path, int idx)
7310 #if ENABLE_FEATURE_SH_STANDALONE
7314 clearredir(/*drop:*/ 1);
7315 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7316 if (strchr(argv[0], '/') != NULL
7317 #if ENABLE_FEATURE_SH_STANDALONE
7318 || (applet_no = find_applet_by_name(argv[0])) >= 0
7321 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7325 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7326 if (--idx < 0 && pathopt == NULL) {
7327 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7328 if (errno != ENOENT && errno != ENOTDIR)
7335 /* Map to POSIX errors */
7347 exitstatus = exerrno;
7348 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7349 argv[0], e, suppress_int));
7350 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7355 printentry(struct tblentry *cmdp)
7361 idx = cmdp->param.index;
7364 name = path_advance(&path, cmdp->cmdname);
7366 } while (--idx >= 0);
7367 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7371 * Clear out command entries. The argument specifies the first entry in
7372 * PATH which has changed.
7375 clearcmdentry(int firstchange)
7377 struct tblentry **tblp;
7378 struct tblentry **pp;
7379 struct tblentry *cmdp;
7382 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7384 while ((cmdp = *pp) != NULL) {
7385 if ((cmdp->cmdtype == CMDNORMAL &&
7386 cmdp->param.index >= firstchange)
7387 || (cmdp->cmdtype == CMDBUILTIN &&
7388 builtinloc >= firstchange)
7401 * Locate a command in the command hash table. If "add" is nonzero,
7402 * add the command to the table if it is not already present. The
7403 * variable "lastcmdentry" is set to point to the address of the link
7404 * pointing to the entry, so that delete_cmd_entry can delete the
7407 * Interrupts must be off if called with add != 0.
7409 static struct tblentry **lastcmdentry;
7411 static struct tblentry *
7412 cmdlookup(const char *name, int add)
7414 unsigned int hashval;
7416 struct tblentry *cmdp;
7417 struct tblentry **pp;
7420 hashval = (unsigned char)*p << 4;
7422 hashval += (unsigned char)*p++;
7424 pp = &cmdtable[hashval % CMDTABLESIZE];
7425 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7426 if (strcmp(cmdp->cmdname, name) == 0)
7430 if (add && cmdp == NULL) {
7431 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7433 /* + 1 - already done because
7434 * tblentry::cmdname is char[1] */);
7435 /*cmdp->next = NULL; - ckzalloc did it */
7436 cmdp->cmdtype = CMDUNKNOWN;
7437 strcpy(cmdp->cmdname, name);
7444 * Delete the command entry returned on the last lookup.
7447 delete_cmd_entry(void)
7449 struct tblentry *cmdp;
7452 cmdp = *lastcmdentry;
7453 *lastcmdentry = cmdp->next;
7454 if (cmdp->cmdtype == CMDFUNCTION)
7455 freefunc(cmdp->param.func);
7461 * Add a new command entry, replacing any existing command entry for
7462 * the same name - except special builtins.
7465 addcmdentry(char *name, struct cmdentry *entry)
7467 struct tblentry *cmdp;
7469 cmdp = cmdlookup(name, 1);
7470 if (cmdp->cmdtype == CMDFUNCTION) {
7471 freefunc(cmdp->param.func);
7473 cmdp->cmdtype = entry->cmdtype;
7474 cmdp->param = entry->u;
7478 static int FAST_FUNC
7479 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7481 struct tblentry **pp;
7482 struct tblentry *cmdp;
7484 struct cmdentry entry;
7487 if (nextopt("r") != '\0') {
7492 if (*argptr == NULL) {
7493 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7494 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7495 if (cmdp->cmdtype == CMDNORMAL)
7503 while ((name = *argptr) != NULL) {
7504 cmdp = cmdlookup(name, 0);
7506 && (cmdp->cmdtype == CMDNORMAL
7507 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7511 find_command(name, &entry, DO_ERR, pathval());
7512 if (entry.cmdtype == CMDUNKNOWN)
7520 * Called when a cd is done. Marks all commands so the next time they
7521 * are executed they will be rehashed.
7526 struct tblentry **pp;
7527 struct tblentry *cmdp;
7529 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7530 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7531 if (cmdp->cmdtype == CMDNORMAL
7532 || (cmdp->cmdtype == CMDBUILTIN
7533 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7543 * Fix command hash table when PATH changed.
7544 * Called before PATH is changed. The argument is the new value of PATH;
7545 * pathval() still returns the old value at this point.
7546 * Called with interrupts off.
7548 static void FAST_FUNC
7549 changepath(const char *new)
7557 firstchange = 9999; /* assume no change */
7563 if ((*old == '\0' && *new == ':')
7564 || (*old == ':' && *new == '\0')
7568 old = new; /* ignore subsequent differences */
7572 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7579 if (builtinloc < 0 && idx_bltin >= 0)
7580 builtinloc = idx_bltin; /* zap builtins */
7581 if (builtinloc >= 0 && idx_bltin < 0)
7583 clearcmdentry(firstchange);
7584 builtinloc = idx_bltin;
7599 #define TENDBQUOTE 12
7616 typedef smallint token_id_t;
7618 /* first char is indicating which tokens mark the end of a list */
7619 static const char *const tokname_array[] = {
7633 #define KWDOFFSET 13
7634 /* the following are keywords */
7653 /* Wrapper around strcmp for qsort/bsearch/... */
7655 pstrcmp(const void *a, const void *b)
7657 return strcmp((char*) a, (*(char**) b) + 1);
7660 static const char *const *
7661 findkwd(const char *s)
7663 return bsearch(s, tokname_array + KWDOFFSET,
7664 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7665 sizeof(tokname_array[0]), pstrcmp);
7669 * Locate and print what a word is...
7672 describe_command(char *command, int describe_command_verbose)
7674 struct cmdentry entry;
7675 struct tblentry *cmdp;
7676 #if ENABLE_ASH_ALIAS
7677 const struct alias *ap;
7679 const char *path = pathval();
7681 if (describe_command_verbose) {
7685 /* First look at the keywords */
7686 if (findkwd(command)) {
7687 out1str(describe_command_verbose ? " is a shell keyword" : command);
7691 #if ENABLE_ASH_ALIAS
7692 /* Then look at the aliases */
7693 ap = lookupalias(command, 0);
7695 if (!describe_command_verbose) {
7700 out1fmt(" is an alias for %s", ap->val);
7704 /* Then check if it is a tracked alias */
7705 cmdp = cmdlookup(command, 0);
7707 entry.cmdtype = cmdp->cmdtype;
7708 entry.u = cmdp->param;
7710 /* Finally use brute force */
7711 find_command(command, &entry, DO_ABS, path);
7714 switch (entry.cmdtype) {
7716 int j = entry.u.index;
7722 p = path_advance(&path, command);
7726 if (describe_command_verbose) {
7728 (cmdp ? " a tracked alias for" : nullstr), p
7737 if (describe_command_verbose) {
7738 out1str(" is a shell function");
7745 if (describe_command_verbose) {
7746 out1fmt(" is a %sshell builtin",
7747 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7748 "special " : nullstr
7756 if (describe_command_verbose) {
7757 out1str(": not found\n");
7766 static int FAST_FUNC
7767 typecmd(int argc UNUSED_PARAM, char **argv)
7773 /* type -p ... ? (we don't bother checking for 'p') */
7774 if (argv[1] && argv[1][0] == '-') {
7779 err |= describe_command(argv[i++], verbose);
7784 #if ENABLE_ASH_CMDCMD
7785 static int FAST_FUNC
7786 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7794 while ((c = nextopt("pvV")) != '\0')
7796 verify |= VERIFY_VERBOSE;
7798 verify |= VERIFY_BRIEF;
7803 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7804 if (verify && (*argptr != NULL)) {
7805 return describe_command(*argptr, verify - VERIFY_BRIEF);
7813 /* ============ eval.c */
7815 static int funcblocksize; /* size of structures in function */
7816 static int funcstringsize; /* size of strings in node */
7817 static void *funcblock; /* block to allocate function from */
7818 static char *funcstring; /* block to allocate strings from */
7820 /* flags in argument to evaltree */
7821 #define EV_EXIT 01 /* exit after evaluating tree */
7822 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7823 #define EV_BACKCMD 04 /* command executing within back quotes */
7825 static const uint8_t nodesize[N_NUMBER] = {
7826 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7827 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7828 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7829 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7830 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7831 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7832 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7833 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7834 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7835 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7836 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7837 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7838 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7839 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7840 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7841 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7842 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7843 #if ENABLE_ASH_BASH_COMPAT
7844 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7846 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7847 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7848 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7849 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7850 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7851 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7852 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7853 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7854 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7857 static void calcsize(union node *n);
7860 sizenodelist(struct nodelist *lp)
7863 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7870 calcsize(union node *n)
7874 funcblocksize += nodesize[n->type];
7877 calcsize(n->ncmd.redirect);
7878 calcsize(n->ncmd.args);
7879 calcsize(n->ncmd.assign);
7882 sizenodelist(n->npipe.cmdlist);
7887 calcsize(n->nredir.redirect);
7888 calcsize(n->nredir.n);
7895 calcsize(n->nbinary.ch2);
7896 calcsize(n->nbinary.ch1);
7899 calcsize(n->nif.elsepart);
7900 calcsize(n->nif.ifpart);
7901 calcsize(n->nif.test);
7904 funcstringsize += strlen(n->nfor.var) + 1;
7905 calcsize(n->nfor.body);
7906 calcsize(n->nfor.args);
7909 calcsize(n->ncase.cases);
7910 calcsize(n->ncase.expr);
7913 calcsize(n->nclist.body);
7914 calcsize(n->nclist.pattern);
7915 calcsize(n->nclist.next);
7919 sizenodelist(n->narg.backquote);
7920 funcstringsize += strlen(n->narg.text) + 1;
7921 calcsize(n->narg.next);
7924 #if ENABLE_ASH_BASH_COMPAT
7931 calcsize(n->nfile.fname);
7932 calcsize(n->nfile.next);
7936 calcsize(n->ndup.vname);
7937 calcsize(n->ndup.next);
7941 calcsize(n->nhere.doc);
7942 calcsize(n->nhere.next);
7945 calcsize(n->nnot.com);
7951 nodeckstrdup(char *s)
7953 char *rtn = funcstring;
7955 strcpy(funcstring, s);
7956 funcstring += strlen(s) + 1;
7960 static union node *copynode(union node *);
7962 static struct nodelist *
7963 copynodelist(struct nodelist *lp)
7965 struct nodelist *start;
7966 struct nodelist **lpp;
7971 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7972 (*lpp)->n = copynode(lp->n);
7974 lpp = &(*lpp)->next;
7981 copynode(union node *n)
7988 funcblock = (char *) funcblock + nodesize[n->type];
7992 new->ncmd.redirect = copynode(n->ncmd.redirect);
7993 new->ncmd.args = copynode(n->ncmd.args);
7994 new->ncmd.assign = copynode(n->ncmd.assign);
7997 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7998 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8003 new->nredir.redirect = copynode(n->nredir.redirect);
8004 new->nredir.n = copynode(n->nredir.n);
8011 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8012 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8015 new->nif.elsepart = copynode(n->nif.elsepart);
8016 new->nif.ifpart = copynode(n->nif.ifpart);
8017 new->nif.test = copynode(n->nif.test);
8020 new->nfor.var = nodeckstrdup(n->nfor.var);
8021 new->nfor.body = copynode(n->nfor.body);
8022 new->nfor.args = copynode(n->nfor.args);
8025 new->ncase.cases = copynode(n->ncase.cases);
8026 new->ncase.expr = copynode(n->ncase.expr);
8029 new->nclist.body = copynode(n->nclist.body);
8030 new->nclist.pattern = copynode(n->nclist.pattern);
8031 new->nclist.next = copynode(n->nclist.next);
8035 new->narg.backquote = copynodelist(n->narg.backquote);
8036 new->narg.text = nodeckstrdup(n->narg.text);
8037 new->narg.next = copynode(n->narg.next);
8040 #if ENABLE_ASH_BASH_COMPAT
8047 new->nfile.fname = copynode(n->nfile.fname);
8048 new->nfile.fd = n->nfile.fd;
8049 new->nfile.next = copynode(n->nfile.next);
8053 new->ndup.vname = copynode(n->ndup.vname);
8054 new->ndup.dupfd = n->ndup.dupfd;
8055 new->ndup.fd = n->ndup.fd;
8056 new->ndup.next = copynode(n->ndup.next);
8060 new->nhere.doc = copynode(n->nhere.doc);
8061 new->nhere.fd = n->nhere.fd;
8062 new->nhere.next = copynode(n->nhere.next);
8065 new->nnot.com = copynode(n->nnot.com);
8068 new->type = n->type;
8073 * Make a copy of a parse tree.
8075 static struct funcnode *
8076 copyfunc(union node *n)
8081 funcblocksize = offsetof(struct funcnode, n);
8084 blocksize = funcblocksize;
8085 f = ckmalloc(blocksize + funcstringsize);
8086 funcblock = (char *) f + offsetof(struct funcnode, n);
8087 funcstring = (char *) f + blocksize;
8094 * Define a shell function.
8097 defun(char *name, union node *func)
8099 struct cmdentry entry;
8102 entry.cmdtype = CMDFUNCTION;
8103 entry.u.func = copyfunc(func);
8104 addcmdentry(name, &entry);
8108 /* Reasons for skipping commands (see comment on breakcmd routine) */
8109 #define SKIPBREAK (1 << 0)
8110 #define SKIPCONT (1 << 1)
8111 #define SKIPFUNC (1 << 2)
8112 #define SKIPFILE (1 << 3)
8113 #define SKIPEVAL (1 << 4)
8114 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8115 static int skipcount; /* number of levels to skip */
8116 static int funcnest; /* depth of function calls */
8117 static int loopnest; /* current loop nesting level */
8119 /* Forward decl way out to parsing code - dotrap needs it */
8120 static int evalstring(char *s, int mask);
8122 /* Called to execute a trap.
8123 * Single callsite - at the end of evaltree().
8124 * If we return non-zero, exaltree raises EXEXIT exception.
8126 * Perhaps we should avoid entering new trap handlers
8127 * while we are executing a trap handler. [is it a TODO?]
8136 savestatus = exitstatus;
8140 TRACE(("dotrap entered\n"));
8141 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8148 /* non-trapped SIGINT is handled separately by raise_interrupt,
8149 * don't upset it by resetting gotsig[SIGINT-1] */
8150 if (sig == SIGINT && !t)
8153 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8157 want_exexit = evalstring(t, SKIPEVAL);
8158 exitstatus = savestatus;
8160 TRACE(("dotrap returns %d\n", want_exexit));
8165 TRACE(("dotrap returns 0\n"));
8169 /* forward declarations - evaluation is fairly recursive business... */
8170 static void evalloop(union node *, int);
8171 static void evalfor(union node *, int);
8172 static void evalcase(union node *, int);
8173 static void evalsubshell(union node *, int);
8174 static void expredir(union node *);
8175 static void evalpipe(union node *, int);
8176 static void evalcommand(union node *, int);
8177 static int evalbltin(const struct builtincmd *, int, char **);
8178 static void prehash(union node *);
8181 * Evaluate a parse tree. The value is left in the global variable
8185 evaltree(union node *n, int flags)
8187 struct jmploc *volatile savehandler = exception_handler;
8188 struct jmploc jmploc;
8190 void (*evalfn)(union node *, int);
8194 SAVE_INT(int_level);
8197 TRACE(("evaltree(NULL) called\n"));
8200 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8202 exception_handler = &jmploc;
8204 int err = setjmp(jmploc.loc);
8206 /* if it was a signal, check for trap handlers */
8207 if (exception_type == EXSIG) {
8208 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8209 exception_type, err));
8212 /* continue on the way out */
8213 TRACE(("exception %d in evaltree, propagating err=%d\n",
8214 exception_type, err));
8215 exception_handler = savehandler;
8216 longjmp(exception_handler->loc, err);
8223 out1fmt("Node type = %d\n", n->type);
8228 evaltree(n->nnot.com, EV_TESTED);
8229 status = !exitstatus;
8232 expredir(n->nredir.redirect);
8233 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8235 evaltree(n->nredir.n, flags & EV_TESTED);
8236 status = exitstatus;
8238 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8241 evalfn = evalcommand;
8243 if (eflag && !(flags & EV_TESTED))
8255 evalfn = evalsubshell;
8268 #error NAND + 1 != NOR
8270 #if NOR + 1 != NSEMI
8271 #error NOR + 1 != NSEMI
8273 unsigned is_or = n->type - NAND;
8276 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8278 if (!exitstatus == is_or)
8291 evaltree(n->nif.test, EV_TESTED);
8294 if (exitstatus == 0) {
8298 if (n->nif.elsepart) {
8299 n = n->nif.elsepart;
8304 defun(n->narg.text, n->narg.next);
8308 exitstatus = status;
8313 exception_handler = savehandler;
8315 if (checkexit & exitstatus)
8316 evalskip |= SKIPEVAL;
8317 else if (pending_sig && dotrap())
8320 if (flags & EV_EXIT) {
8322 raise_exception(EXEXIT);
8325 RESTORE_INT(int_level);
8326 TRACE(("leaving evaltree (no interrupts)\n"));
8329 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8332 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8335 evalloop(union node *n, int flags)
8345 evaltree(n->nbinary.ch1, EV_TESTED);
8348 if (evalskip == SKIPCONT && --skipcount <= 0) {
8352 if (evalskip == SKIPBREAK && --skipcount <= 0)
8357 if (n->type != NWHILE)
8361 evaltree(n->nbinary.ch2, flags);
8362 status = exitstatus;
8367 exitstatus = status;
8371 evalfor(union node *n, int flags)
8373 struct arglist arglist;
8376 struct stackmark smark;
8378 setstackmark(&smark);
8379 arglist.list = NULL;
8380 arglist.lastp = &arglist.list;
8381 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8382 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8387 *arglist.lastp = NULL;
8392 for (sp = arglist.list; sp; sp = sp->next) {
8393 setvar(n->nfor.var, sp->text, 0);
8394 evaltree(n->nfor.body, flags);
8396 if (evalskip == SKIPCONT && --skipcount <= 0) {
8400 if (evalskip == SKIPBREAK && --skipcount <= 0)
8407 popstackmark(&smark);
8411 evalcase(union node *n, int flags)
8415 struct arglist arglist;
8416 struct stackmark smark;
8418 setstackmark(&smark);
8419 arglist.list = NULL;
8420 arglist.lastp = &arglist.list;
8421 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8423 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8424 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8425 if (casematch(patp, arglist.list->text)) {
8426 if (evalskip == 0) {
8427 evaltree(cp->nclist.body, flags);
8434 popstackmark(&smark);
8438 * Kick off a subshell to evaluate a tree.
8441 evalsubshell(union node *n, int flags)
8444 int backgnd = (n->type == NBACKGND);
8447 expredir(n->nredir.redirect);
8448 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8451 jp = makejob(/*n,*/ 1);
8452 if (forkshell(jp, n, backgnd) == 0) {
8457 flags &= ~EV_TESTED;
8459 redirect(n->nredir.redirect, 0);
8460 evaltreenr(n->nredir.n, flags);
8465 status = waitforjob(jp);
8466 exitstatus = status;
8471 * Compute the names of the files in a redirection list.
8473 static void fixredir(union node *, const char *, int);
8475 expredir(union node *n)
8479 for (redir = n; redir; redir = redir->nfile.next) {
8483 fn.lastp = &fn.list;
8484 switch (redir->type) {
8488 #if ENABLE_ASH_BASH_COMPAT
8493 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8494 #if ENABLE_ASH_BASH_COMPAT
8497 redir->nfile.expfname = fn.list->text;
8500 case NTOFD: /* >& */
8501 if (redir->ndup.vname) {
8502 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8503 if (fn.list == NULL)
8504 ash_msg_and_raise_error("redir error");
8505 #if ENABLE_ASH_BASH_COMPAT
8506 //FIXME: we used expandarg with different args!
8507 if (!isdigit_str9(fn.list->text)) {
8508 /* >&file, not >&fd */
8509 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8510 ash_msg_and_raise_error("redir error");
8512 goto store_expfname;
8515 fixredir(redir, fn.list->text, 1);
8523 * Evaluate a pipeline. All the processes in the pipeline are children
8524 * of the process creating the pipeline. (This differs from some versions
8525 * of the shell, which make the last process in a pipeline the parent
8529 evalpipe(union node *n, int flags)
8532 struct nodelist *lp;
8537 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8539 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8543 jp = makejob(/*n,*/ pipelen);
8545 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8549 if (pipe(pip) < 0) {
8551 ash_msg_and_raise_error("pipe call failed");
8554 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8567 evaltreenr(lp->n, flags);
8573 /* Don't want to trigger debugging */
8577 if (n->npipe.pipe_backgnd == 0) {
8578 exitstatus = waitforjob(jp);
8579 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8585 * Controls whether the shell is interactive or not.
8588 setinteractive(int on)
8590 static smallint is_interactive;
8592 if (++on == is_interactive)
8594 is_interactive = on;
8598 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8599 if (is_interactive > 1) {
8600 /* Looks like they want an interactive shell */
8601 static smallint did_banner;
8604 /* note: ash and hush share this string */
8605 out1fmt("\n\n%s %s\n"
8606 "Enter 'help' for a list of built-in commands."
8609 "built-in shell (ash)"
8623 setinteractive(iflag);
8625 #if ENABLE_FEATURE_EDITING_VI
8627 line_input_state->flags |= VI_MODE;
8629 line_input_state->flags &= ~VI_MODE;
8631 viflag = 0; /* forcibly keep the option off */
8635 static struct localvar *localvars;
8638 * Called after a function returns.
8639 * Interrupts must be off.
8644 struct localvar *lvp;
8647 while ((lvp = localvars) != NULL) {
8648 localvars = lvp->next;
8650 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8651 if (vp == NULL) { /* $- saved */
8652 memcpy(optlist, lvp->text, sizeof(optlist));
8653 free((char*)lvp->text);
8655 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8656 unsetvar(vp->var_text);
8659 vp->var_func(var_end(lvp->text));
8660 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8661 free((char*)vp->var_text);
8662 vp->flags = lvp->flags;
8663 vp->var_text = lvp->text;
8670 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8672 volatile struct shparam saveparam;
8673 struct localvar *volatile savelocalvars;
8674 struct jmploc *volatile savehandler;
8675 struct jmploc jmploc;
8678 saveparam = shellparam;
8679 savelocalvars = localvars;
8680 e = setjmp(jmploc.loc);
8685 savehandler = exception_handler;
8686 exception_handler = &jmploc;
8688 shellparam.malloced = 0;
8692 shellparam.nparam = argc - 1;
8693 shellparam.p = argv + 1;
8694 #if ENABLE_ASH_GETOPTS
8695 shellparam.optind = 1;
8696 shellparam.optoff = -1;
8698 evaltree(&func->n, flags & EV_TESTED);
8704 localvars = savelocalvars;
8705 freeparam(&shellparam);
8706 shellparam = saveparam;
8707 exception_handler = savehandler;
8709 evalskip &= ~SKIPFUNC;
8713 #if ENABLE_ASH_CMDCMD
8715 parse_command_args(char **argv, const char **path)
8728 if (c == '-' && !*cp) {
8735 *path = bb_default_path;
8738 /* run 'typecmd' for other options */
8749 * Make a variable a local variable. When a variable is made local, it's
8750 * value and flags are saved in a localvar structure. The saved values
8751 * will be restored when the shell function returns. We handle the name
8752 * "-" as a special case.
8757 struct localvar *lvp;
8762 lvp = ckzalloc(sizeof(struct localvar));
8763 if (LONE_DASH(name)) {
8765 p = ckmalloc(sizeof(optlist));
8766 lvp->text = memcpy(p, optlist, sizeof(optlist));
8771 vpp = hashvar(name);
8772 vp = *findvar(vpp, name);
8773 eq = strchr(name, '=');
8776 setvareq(name, VSTRFIXED);
8778 setvar(name, NULL, VSTRFIXED);
8779 vp = *vpp; /* the new variable */
8780 lvp->flags = VUNSET;
8782 lvp->text = vp->var_text;
8783 lvp->flags = vp->flags;
8784 vp->flags |= VSTRFIXED|VTEXTFIXED;
8790 lvp->next = localvars;
8796 * The "local" command.
8798 static int FAST_FUNC
8799 localcmd(int argc UNUSED_PARAM, char **argv)
8804 while ((name = *argv++) != NULL) {
8810 static int FAST_FUNC
8811 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8816 static int FAST_FUNC
8817 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8822 static int FAST_FUNC
8823 execcmd(int argc UNUSED_PARAM, char **argv)
8826 iflag = 0; /* exit on error */
8829 shellexec(argv + 1, pathval(), 0);
8835 * The return command.
8837 static int FAST_FUNC
8838 returncmd(int argc UNUSED_PARAM, char **argv)
8841 * If called outside a function, do what ksh does;
8842 * skip the rest of the file.
8844 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8845 return argv[1] ? number(argv[1]) : exitstatus;
8848 /* Forward declarations for builtintab[] */
8849 static int breakcmd(int, char **) FAST_FUNC;
8850 static int dotcmd(int, char **) FAST_FUNC;
8851 static int evalcmd(int, char **) FAST_FUNC;
8852 static int exitcmd(int, char **) FAST_FUNC;
8853 static int exportcmd(int, char **) FAST_FUNC;
8854 #if ENABLE_ASH_GETOPTS
8855 static int getoptscmd(int, char **) FAST_FUNC;
8857 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8858 static int helpcmd(int, char **) FAST_FUNC;
8860 #if ENABLE_SH_MATH_SUPPORT
8861 static int letcmd(int, char **) FAST_FUNC;
8863 static int readcmd(int, char **) FAST_FUNC;
8864 static int setcmd(int, char **) FAST_FUNC;
8865 static int shiftcmd(int, char **) FAST_FUNC;
8866 static int timescmd(int, char **) FAST_FUNC;
8867 static int trapcmd(int, char **) FAST_FUNC;
8868 static int umaskcmd(int, char **) FAST_FUNC;
8869 static int unsetcmd(int, char **) FAST_FUNC;
8870 static int ulimitcmd(int, char **) FAST_FUNC;
8872 #define BUILTIN_NOSPEC "0"
8873 #define BUILTIN_SPECIAL "1"
8874 #define BUILTIN_REGULAR "2"
8875 #define BUILTIN_SPEC_REG "3"
8876 #define BUILTIN_ASSIGN "4"
8877 #define BUILTIN_SPEC_ASSG "5"
8878 #define BUILTIN_REG_ASSG "6"
8879 #define BUILTIN_SPEC_REG_ASSG "7"
8881 /* Stubs for calling non-FAST_FUNC's */
8882 #if ENABLE_ASH_BUILTIN_ECHO
8883 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8885 #if ENABLE_ASH_BUILTIN_PRINTF
8886 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8888 #if ENABLE_ASH_BUILTIN_TEST
8889 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8892 /* Keep these in proper order since it is searched via bsearch() */
8893 static const struct builtincmd builtintab[] = {
8894 { BUILTIN_SPEC_REG "." , dotcmd },
8895 { BUILTIN_SPEC_REG ":" , truecmd },
8896 #if ENABLE_ASH_BUILTIN_TEST
8897 { BUILTIN_REGULAR "[" , testcmd },
8898 #if ENABLE_ASH_BASH_COMPAT
8899 { BUILTIN_REGULAR "[[" , testcmd },
8902 #if ENABLE_ASH_ALIAS
8903 { BUILTIN_REG_ASSG "alias" , aliascmd },
8906 { BUILTIN_REGULAR "bg" , fg_bgcmd },
8908 { BUILTIN_SPEC_REG "break" , breakcmd },
8909 { BUILTIN_REGULAR "cd" , cdcmd },
8910 { BUILTIN_NOSPEC "chdir" , cdcmd },
8911 #if ENABLE_ASH_CMDCMD
8912 { BUILTIN_REGULAR "command" , commandcmd },
8914 { BUILTIN_SPEC_REG "continue", breakcmd },
8915 #if ENABLE_ASH_BUILTIN_ECHO
8916 { BUILTIN_REGULAR "echo" , echocmd },
8918 { BUILTIN_SPEC_REG "eval" , evalcmd },
8919 { BUILTIN_SPEC_REG "exec" , execcmd },
8920 { BUILTIN_SPEC_REG "exit" , exitcmd },
8921 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
8922 { BUILTIN_REGULAR "false" , falsecmd },
8924 { BUILTIN_REGULAR "fg" , fg_bgcmd },
8926 #if ENABLE_ASH_GETOPTS
8927 { BUILTIN_REGULAR "getopts" , getoptscmd },
8929 { BUILTIN_NOSPEC "hash" , hashcmd },
8930 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8931 { BUILTIN_NOSPEC "help" , helpcmd },
8934 { BUILTIN_REGULAR "jobs" , jobscmd },
8935 { BUILTIN_REGULAR "kill" , killcmd },
8937 #if ENABLE_SH_MATH_SUPPORT
8938 { BUILTIN_NOSPEC "let" , letcmd },
8940 { BUILTIN_ASSIGN "local" , localcmd },
8941 #if ENABLE_ASH_BUILTIN_PRINTF
8942 { BUILTIN_REGULAR "printf" , printfcmd },
8944 { BUILTIN_NOSPEC "pwd" , pwdcmd },
8945 { BUILTIN_REGULAR "read" , readcmd },
8946 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8947 { BUILTIN_SPEC_REG "return" , returncmd },
8948 { BUILTIN_SPEC_REG "set" , setcmd },
8949 { BUILTIN_SPEC_REG "shift" , shiftcmd },
8950 #if ENABLE_ASH_BASH_COMPAT
8951 { BUILTIN_SPEC_REG "source" , dotcmd },
8953 #if ENABLE_ASH_BUILTIN_TEST
8954 { BUILTIN_REGULAR "test" , testcmd },
8956 { BUILTIN_SPEC_REG "times" , timescmd },
8957 { BUILTIN_SPEC_REG "trap" , trapcmd },
8958 { BUILTIN_REGULAR "true" , truecmd },
8959 { BUILTIN_NOSPEC "type" , typecmd },
8960 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
8961 { BUILTIN_REGULAR "umask" , umaskcmd },
8962 #if ENABLE_ASH_ALIAS
8963 { BUILTIN_REGULAR "unalias" , unaliascmd },
8965 { BUILTIN_SPEC_REG "unset" , unsetcmd },
8966 { BUILTIN_REGULAR "wait" , waitcmd },
8969 /* Should match the above table! */
8970 #define COMMANDCMD (builtintab + \
8972 1 * ENABLE_ASH_BUILTIN_TEST + \
8973 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8974 1 * ENABLE_ASH_ALIAS + \
8975 1 * ENABLE_ASH_JOB_CONTROL + \
8977 #define EXECCMD (builtintab + \
8979 1 * ENABLE_ASH_BUILTIN_TEST + \
8980 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8981 1 * ENABLE_ASH_ALIAS + \
8982 1 * ENABLE_ASH_JOB_CONTROL + \
8984 1 * ENABLE_ASH_CMDCMD + \
8986 ENABLE_ASH_BUILTIN_ECHO + \
8990 * Search the table of builtin commands.
8992 static struct builtincmd *
8993 find_builtin(const char *name)
8995 struct builtincmd *bp;
8998 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9005 * Execute a simple command.
9008 isassignment(const char *p)
9010 const char *q = endofname(p);
9015 static int FAST_FUNC
9016 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9018 /* Preserve exitstatus of a previous possible redirection
9019 * as POSIX mandates */
9020 return back_exitstatus;
9023 evalcommand(union node *cmd, int flags)
9025 static const struct builtincmd null_bltin = {
9026 "\0\0", bltincmd /* why three NULs? */
9028 struct stackmark smark;
9030 struct arglist arglist;
9031 struct arglist varlist;
9034 const struct strlist *sp;
9035 struct cmdentry cmdentry;
9042 struct builtincmd *bcmd;
9043 smallint cmd_is_exec;
9044 smallint pseudovarflag = 0;
9046 /* First expand the arguments. */
9047 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9048 setstackmark(&smark);
9049 back_exitstatus = 0;
9051 cmdentry.cmdtype = CMDBUILTIN;
9052 cmdentry.u.cmd = &null_bltin;
9053 varlist.lastp = &varlist.list;
9054 *varlist.lastp = NULL;
9055 arglist.lastp = &arglist.list;
9056 *arglist.lastp = NULL;
9059 if (cmd->ncmd.args) {
9060 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9061 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9064 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9065 struct strlist **spp;
9067 spp = arglist.lastp;
9068 if (pseudovarflag && isassignment(argp->narg.text))
9069 expandarg(argp, &arglist, EXP_VARTILDE);
9071 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9073 for (sp = *spp; sp; sp = sp->next)
9077 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9078 for (sp = arglist.list; sp; sp = sp->next) {
9079 TRACE(("evalcommand arg: %s\n", sp->text));
9080 *nargv++ = sp->text;
9085 if (iflag && funcnest == 0 && argc > 0)
9086 lastarg = nargv[-1];
9089 expredir(cmd->ncmd.redirect);
9090 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9092 path = vpath.var_text;
9093 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9094 struct strlist **spp;
9097 spp = varlist.lastp;
9098 expandarg(argp, &varlist, EXP_VARTILDE);
9101 * Modify the command lookup path, if a PATH= assignment
9105 if (varcmp(p, path) == 0)
9109 /* Print the command if xflag is set. */
9112 const char *p = " %s";
9115 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9118 for (n = 0; n < 2; n++) {
9120 fdprintf(preverrout_fd, p, sp->text);
9128 safe_write(preverrout_fd, "\n", 1);
9134 /* Now locate the command. */
9136 const char *oldpath;
9137 int cmd_flag = DO_ERR;
9142 find_command(argv[0], &cmdentry, cmd_flag, path);
9143 if (cmdentry.cmdtype == CMDUNKNOWN) {
9144 flush_stdout_stderr();
9149 /* implement bltin and command here */
9150 if (cmdentry.cmdtype != CMDBUILTIN)
9153 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9154 if (cmdentry.u.cmd == EXECCMD)
9156 #if ENABLE_ASH_CMDCMD
9157 if (cmdentry.u.cmd == COMMANDCMD) {
9159 nargv = parse_command_args(argv, &path);
9162 argc -= nargv - argv;
9164 cmd_flag |= DO_NOFUNC;
9172 /* We have a redirection error. */
9174 raise_exception(EXERROR);
9176 exitstatus = status;
9180 /* Execute the command. */
9181 switch (cmdentry.cmdtype) {
9184 #if ENABLE_FEATURE_SH_NOFORK
9185 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9186 * around run_nofork_applet() call.
9187 * (2) Should this check also be done in forkshell()?
9188 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9190 /* find_command() encodes applet_no as (-2 - applet_no) */
9191 int applet_no = (- cmdentry.u.index - 2);
9192 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9193 listsetvar(varlist.list, VEXPORT|VSTACK);
9194 /* run <applet>_main() */
9195 exitstatus = run_nofork_applet(applet_no, argv);
9199 /* Can we avoid forking off? For example, very last command
9200 * in a script or a subshell does not need forking,
9201 * we can just exec it.
9203 if (!(flags & EV_EXIT) || may_have_traps) {
9204 /* No, forking off a child is necessary */
9206 jp = makejob(/*cmd,*/ 1);
9207 if (forkshell(jp, cmd, FORK_FG) != 0) {
9209 exitstatus = waitforjob(jp);
9211 TRACE(("forked child exited with %d\n", exitstatus));
9216 /* fall through to exec'ing external program */
9218 listsetvar(varlist.list, VEXPORT|VSTACK);
9219 shellexec(argv, path, cmdentry.u.index);
9223 cmdenviron = varlist.list;
9225 struct strlist *list = cmdenviron;
9227 if (spclbltin > 0 || argc == 0) {
9229 if (cmd_is_exec && argc > 1)
9232 listsetvar(list, i);
9234 /* Tight loop with builtins only:
9235 * "while kill -0 $child; do true; done"
9236 * will never exit even if $child died, unless we do this
9237 * to reap the zombie and make kill detect that it's gone: */
9238 dowait(DOWAIT_NONBLOCK, NULL);
9240 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9242 int i = exception_type;
9247 exit_status = 128 + SIGINT;
9249 exit_status = 128 + pending_sig;
9250 exitstatus = exit_status;
9251 if (i == EXINT || spclbltin > 0) {
9253 longjmp(exception_handler->loc, 1);
9260 listsetvar(varlist.list, 0);
9261 /* See above for the rationale */
9262 dowait(DOWAIT_NONBLOCK, NULL);
9263 if (evalfun(cmdentry.u.func, argc, argv, flags))
9270 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9272 /* dsl: I think this is intended to be used to support
9273 * '_' in 'vi' command mode during line editing...
9274 * However I implemented that within libedit itself.
9276 setvar("_", lastarg, 0);
9278 popstackmark(&smark);
9282 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9284 char *volatile savecmdname;
9285 struct jmploc *volatile savehandler;
9286 struct jmploc jmploc;
9289 savecmdname = commandname;
9290 i = setjmp(jmploc.loc);
9293 savehandler = exception_handler;
9294 exception_handler = &jmploc;
9295 commandname = argv[0];
9297 optptr = NULL; /* initialize nextopt */
9298 exitstatus = (*cmd->builtin)(argc, argv);
9299 flush_stdout_stderr();
9301 exitstatus |= ferror(stdout);
9303 commandname = savecmdname;
9304 exception_handler = savehandler;
9310 goodname(const char *p)
9312 return !*endofname(p);
9317 * Search for a command. This is called before we fork so that the
9318 * location of the command will be available in the parent as well as
9319 * the child. The check for "goodname" is an overly conservative
9320 * check that the name will not be subject to expansion.
9323 prehash(union node *n)
9325 struct cmdentry entry;
9327 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9328 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9332 /* ============ Builtin commands
9334 * Builtin commands whose functions are closely tied to evaluation
9335 * are implemented here.
9339 * Handle break and continue commands. Break, continue, and return are
9340 * all handled by setting the evalskip flag. The evaluation routines
9341 * above all check this flag, and if it is set they start skipping
9342 * commands rather than executing them. The variable skipcount is
9343 * the number of loops to break/continue, or the number of function
9344 * levels to return. (The latter is always 1.) It should probably
9345 * be an error to break out of more loops than exist, but it isn't
9346 * in the standard shell so we don't make it one here.
9348 static int FAST_FUNC
9349 breakcmd(int argc UNUSED_PARAM, char **argv)
9351 int n = argv[1] ? number(argv[1]) : 1;
9354 ash_msg_and_raise_error(msg_illnum, argv[1]);
9358 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9365 /* ============ input.c
9367 * This implements the input routines used by the parser.
9371 INPUT_PUSH_FILE = 1,
9372 INPUT_NOFILE_OK = 2,
9375 static smallint checkkwd;
9376 /* values of checkkwd variable */
9377 #define CHKALIAS 0x1
9382 * Push a string back onto the input at this current parsefile level.
9383 * We handle aliases this way.
9385 #if !ENABLE_ASH_ALIAS
9386 #define pushstring(s, ap) pushstring(s)
9389 pushstring(char *s, struct alias *ap)
9396 if (g_parsefile->strpush) {
9397 sp = ckzalloc(sizeof(*sp));
9398 sp->prev = g_parsefile->strpush;
9400 sp = &(g_parsefile->basestrpush);
9402 g_parsefile->strpush = sp;
9403 sp->prev_string = g_parsefile->next_to_pgetc;
9404 sp->prev_left_in_line = g_parsefile->left_in_line;
9405 #if ENABLE_ASH_ALIAS
9408 ap->flag |= ALIASINUSE;
9412 g_parsefile->next_to_pgetc = s;
9413 g_parsefile->left_in_line = len;
9420 struct strpush *sp = g_parsefile->strpush;
9423 #if ENABLE_ASH_ALIAS
9425 if (g_parsefile->next_to_pgetc[-1] == ' '
9426 || g_parsefile->next_to_pgetc[-1] == '\t'
9428 checkkwd |= CHKALIAS;
9430 if (sp->string != sp->ap->val) {
9433 sp->ap->flag &= ~ALIASINUSE;
9434 if (sp->ap->flag & ALIASDEAD) {
9435 unalias(sp->ap->name);
9439 g_parsefile->next_to_pgetc = sp->prev_string;
9440 g_parsefile->left_in_line = sp->prev_left_in_line;
9441 g_parsefile->strpush = sp->prev;
9442 if (sp != &(g_parsefile->basestrpush))
9447 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9448 //it peeks whether it is &>, and then pushes back both chars.
9449 //This function needs to save last *next_to_pgetc to buf[0]
9450 //to make two pungetc() reliable. Currently,
9451 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9456 char *buf = g_parsefile->buf;
9458 g_parsefile->next_to_pgetc = buf;
9459 #if ENABLE_FEATURE_EDITING
9461 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9462 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9464 #if ENABLE_FEATURE_TAB_COMPLETION
9465 line_input_state->path_lookup = pathval();
9467 nr = read_line_input(cmdedit_prompt, buf, IBUFSIZ, line_input_state);
9469 /* Ctrl+C pressed */
9478 if (nr < 0 && errno == 0) {
9479 /* Ctrl+D pressed */
9484 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9488 /* nonblock_safe_read() handles this problem */
9490 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9491 int flags = fcntl(0, F_GETFL);
9492 if (flags >= 0 && (flags & O_NONBLOCK)) {
9493 flags &= ~O_NONBLOCK;
9494 if (fcntl(0, F_SETFL, flags) >= 0) {
9495 out2str("sh: turning off NDELAY mode\n");
9506 * Refill the input buffer and return the next input character:
9508 * 1) If a string was pushed back on the input, pop it;
9509 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9510 * or we are reading from a string so we can't refill the buffer,
9512 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9513 * 4) Process input up to the next newline, deleting nul characters.
9515 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9516 #define pgetc_debug(...) ((void)0)
9523 while (g_parsefile->strpush) {
9524 #if ENABLE_ASH_ALIAS
9525 if (g_parsefile->left_in_line == -1
9526 && g_parsefile->strpush->ap
9527 && g_parsefile->next_to_pgetc[-1] != ' '
9528 && g_parsefile->next_to_pgetc[-1] != '\t'
9530 pgetc_debug("preadbuffer PEOA");
9535 /* try "pgetc" now: */
9536 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9537 g_parsefile->left_in_line,
9538 g_parsefile->next_to_pgetc,
9539 g_parsefile->next_to_pgetc);
9540 if (--g_parsefile->left_in_line >= 0)
9541 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9543 /* on both branches above g_parsefile->left_in_line < 0.
9544 * "pgetc" needs refilling.
9547 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9548 * pungetc() may increment it a few times.
9549 * Assuming it won't increment it to less than -90.
9551 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9552 pgetc_debug("preadbuffer PEOF1");
9553 /* even in failure keep left_in_line and next_to_pgetc
9554 * in lock step, for correct multi-layer pungetc.
9555 * left_in_line was decremented before preadbuffer(),
9556 * must inc next_to_pgetc: */
9557 g_parsefile->next_to_pgetc++;
9561 more = g_parsefile->left_in_buffer;
9563 flush_stdout_stderr();
9567 /* don't try reading again */
9568 g_parsefile->left_in_line = -99;
9569 pgetc_debug("preadbuffer PEOF2");
9570 g_parsefile->next_to_pgetc++;
9575 /* Find out where's the end of line.
9576 * Set g_parsefile->left_in_line
9577 * and g_parsefile->left_in_buffer acordingly.
9578 * NUL chars are deleted.
9580 q = g_parsefile->next_to_pgetc;
9588 memmove(q, q + 1, more);
9592 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9598 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9599 if (g_parsefile->left_in_line < 0)
9604 g_parsefile->left_in_buffer = more;
9609 out2str(g_parsefile->next_to_pgetc);
9613 pgetc_debug("preadbuffer at %d:%p'%s'",
9614 g_parsefile->left_in_line,
9615 g_parsefile->next_to_pgetc,
9616 g_parsefile->next_to_pgetc);
9617 return (unsigned char)*g_parsefile->next_to_pgetc++;
9620 #define pgetc_as_macro() \
9621 (--g_parsefile->left_in_line >= 0 \
9622 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9629 pgetc_debug("pgetc_fast at %d:%p'%s'",
9630 g_parsefile->left_in_line,
9631 g_parsefile->next_to_pgetc,
9632 g_parsefile->next_to_pgetc);
9633 return pgetc_as_macro();
9636 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9637 # define pgetc_fast() pgetc()
9639 # define pgetc_fast() pgetc_as_macro()
9642 #if ENABLE_ASH_ALIAS
9644 pgetc_without_PEOA(void)
9648 pgetc_debug("pgetc_fast at %d:%p'%s'",
9649 g_parsefile->left_in_line,
9650 g_parsefile->next_to_pgetc,
9651 g_parsefile->next_to_pgetc);
9653 } while (c == PEOA);
9657 # define pgetc_without_PEOA() pgetc()
9661 * Read a line from the script.
9664 pfgets(char *line, int len)
9670 while (--nleft > 0) {
9671 c = pgetc_without_PEOA();
9686 * Undo the last call to pgetc. Only one character may be pushed back.
9687 * PEOF may be pushed back.
9692 g_parsefile->left_in_line++;
9693 g_parsefile->next_to_pgetc--;
9694 pgetc_debug("pushed back to %d:%p'%s'",
9695 g_parsefile->left_in_line,
9696 g_parsefile->next_to_pgetc,
9697 g_parsefile->next_to_pgetc);
9701 * To handle the "." command, a stack of input files is used. Pushfile
9702 * adds a new entry to the stack and popfile restores the previous level.
9707 struct parsefile *pf;
9709 pf = ckzalloc(sizeof(*pf));
9710 pf->prev = g_parsefile;
9712 /*pf->strpush = NULL; - ckzalloc did it */
9713 /*pf->basestrpush.prev = NULL;*/
9720 struct parsefile *pf = g_parsefile;
9728 g_parsefile = pf->prev;
9734 * Return to top level.
9739 while (g_parsefile != &basepf)
9744 * Close the file(s) that the shell is reading commands from. Called
9745 * after a fork is done.
9751 if (g_parsefile->pf_fd > 0) {
9752 close(g_parsefile->pf_fd);
9753 g_parsefile->pf_fd = 0;
9758 * Like setinputfile, but takes an open file descriptor. Call this with
9762 setinputfd(int fd, int push)
9764 close_on_exec_on(fd);
9767 g_parsefile->buf = NULL;
9769 g_parsefile->pf_fd = fd;
9770 if (g_parsefile->buf == NULL)
9771 g_parsefile->buf = ckmalloc(IBUFSIZ);
9772 g_parsefile->left_in_buffer = 0;
9773 g_parsefile->left_in_line = 0;
9774 g_parsefile->linno = 1;
9778 * Set the input to take input from a file. If push is set, push the
9779 * old input onto the stack first.
9782 setinputfile(const char *fname, int flags)
9788 fd = open(fname, O_RDONLY);
9790 if (flags & INPUT_NOFILE_OK)
9792 ash_msg_and_raise_error("can't open '%s'", fname);
9795 fd2 = copyfd(fd, 10);
9798 ash_msg_and_raise_error("out of file descriptors");
9801 setinputfd(fd, flags & INPUT_PUSH_FILE);
9808 * Like setinputfile, but takes input from a string.
9811 setinputstring(char *string)
9815 g_parsefile->next_to_pgetc = string;
9816 g_parsefile->left_in_line = strlen(string);
9817 g_parsefile->buf = NULL;
9818 g_parsefile->linno = 1;
9823 /* ============ mail.c
9825 * Routines to check for mail.
9830 #define MAXMBOXES 10
9832 /* times of mailboxes */
9833 static time_t mailtime[MAXMBOXES];
9834 /* Set if MAIL or MAILPATH is changed. */
9835 static smallint mail_var_path_changed;
9838 * Print appropriate message(s) if mail has arrived.
9839 * If mail_var_path_changed is set,
9840 * then the value of MAIL has mail_var_path_changed,
9841 * so we just update the values.
9850 struct stackmark smark;
9853 setstackmark(&smark);
9854 mpath = mpathset() ? mpathval() : mailval();
9855 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9856 p = path_advance(&mpath, nullstr);
9861 for (q = p; *q; q++)
9867 q[-1] = '\0'; /* delete trailing '/' */
9868 if (stat(p, &statb) < 0) {
9872 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9875 pathopt ? pathopt : "you have mail"
9878 *mtp = statb.st_mtime;
9880 mail_var_path_changed = 0;
9881 popstackmark(&smark);
9884 static void FAST_FUNC
9885 changemail(const char *val UNUSED_PARAM)
9887 mail_var_path_changed = 1;
9890 #endif /* ASH_MAIL */
9893 /* ============ ??? */
9896 * Set the shell parameters.
9899 setparam(char **argv)
9905 for (nparam = 0; argv[nparam]; nparam++)
9907 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9909 *ap++ = ckstrdup(*argv++);
9912 freeparam(&shellparam);
9913 shellparam.malloced = 1;
9914 shellparam.nparam = nparam;
9915 shellparam.p = newparam;
9916 #if ENABLE_ASH_GETOPTS
9917 shellparam.optind = 1;
9918 shellparam.optoff = -1;
9923 * Process shell options. The global variable argptr contains a pointer
9924 * to the argument list; we advance it past the options.
9926 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9927 * For a non-interactive shell, an error condition encountered
9928 * by a special built-in ... shall cause the shell to write a diagnostic message
9929 * to standard error and exit as shown in the following table:
9930 * Error Special Built-In
9932 * Utility syntax error (option or operand error) Shall exit
9934 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9935 * we see that bash does not do that (set "finishes" with error code 1 instead,
9936 * and shell continues), and people rely on this behavior!
9938 * set -o barfoo 2>/dev/null
9941 * Oh well. Let's mimic that.
9944 plus_minus_o(char *name, int val)
9949 for (i = 0; i < NOPTS; i++) {
9950 if (strcmp(name, optnames(i)) == 0) {
9955 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9958 for (i = 0; i < NOPTS; i++) {
9960 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9962 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9968 setoption(int flag, int val)
9972 for (i = 0; i < NOPTS; i++) {
9973 if (optletters(i) == flag) {
9978 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9982 options(int cmdline)
9990 while ((p = *argptr) != NULL) {
9992 if (c != '-' && c != '+')
9995 val = 0; /* val = 0 if c == '+' */
9998 if (p[0] == '\0' || LONE_DASH(p)) {
10000 /* "-" means turn off -x and -v */
10003 /* "--" means reset params */
10004 else if (*argptr == NULL)
10007 break; /* "-" or "--" terminates options */
10010 /* first char was + or - */
10011 while ((c = *p++) != '\0') {
10012 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10013 if (c == 'c' && cmdline) {
10014 minusc = p; /* command is after shell args */
10015 } else if (c == 'o') {
10016 if (plus_minus_o(*argptr, val)) {
10017 /* it already printed err message */
10018 return 1; /* error */
10022 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10024 /* bash does not accept +-login, we also won't */
10025 } else if (cmdline && val && (c == '-')) { /* long options */
10026 if (strcmp(p, "login") == 0)
10038 * The shift builtin command.
10040 static int FAST_FUNC
10041 shiftcmd(int argc UNUSED_PARAM, char **argv)
10048 n = number(argv[1]);
10049 if (n > shellparam.nparam)
10050 n = 0; /* bash compat, was = shellparam.nparam; */
10052 shellparam.nparam -= n;
10053 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10054 if (shellparam.malloced)
10057 ap2 = shellparam.p;
10058 while ((*ap2++ = *ap1++) != NULL)
10060 #if ENABLE_ASH_GETOPTS
10061 shellparam.optind = 1;
10062 shellparam.optoff = -1;
10069 * POSIX requires that 'set' (but not export or readonly) output the
10070 * variables in lexicographic order - by the locale's collating order (sigh).
10071 * Maybe we could keep them in an ordered balanced binary tree
10072 * instead of hashed lists.
10073 * For now just roll 'em through qsort for printing...
10076 showvars(const char *sep_prefix, int on, int off)
10079 char **ep, **epend;
10081 ep = listvars(on, off, &epend);
10082 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10084 sep = *sep_prefix ? " " : sep_prefix;
10086 for (; ep < epend; ep++) {
10090 p = strchrnul(*ep, '=');
10093 q = single_quote(++p);
10094 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10100 * The set command builtin.
10102 static int FAST_FUNC
10103 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10108 return showvars(nullstr, 0, VUNSET);
10111 if (!options(0)) { /* if no parse error... */
10114 if (*argptr != NULL) {
10122 #if ENABLE_ASH_RANDOM_SUPPORT
10123 static void FAST_FUNC
10124 change_random(const char *value)
10128 if (value == NULL) {
10129 /* "get", generate */
10130 t = next_random(&random_gen);
10131 /* set without recursion */
10132 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10133 vrandom.flags &= ~VNOFUNC;
10136 t = strtoul(value, NULL, 10);
10137 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10142 #if ENABLE_ASH_GETOPTS
10144 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10153 if (*param_optind < 1)
10155 optnext = optfirst + *param_optind - 1;
10157 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10160 p = optnext[-1] + *optoff;
10161 if (p == NULL || *p == '\0') {
10162 /* Current word is done, advance */
10164 if (p == NULL || *p != '-' || *++p == '\0') {
10171 if (LONE_DASH(p)) /* check for "--" */
10176 for (q = optstr; *q != c;) {
10178 if (optstr[0] == ':') {
10181 err |= setvarsafe("OPTARG", s, 0);
10183 fprintf(stderr, "Illegal option -%c\n", c);
10184 unsetvar("OPTARG");
10194 if (*p == '\0' && (p = *optnext) == NULL) {
10195 if (optstr[0] == ':') {
10198 err |= setvarsafe("OPTARG", s, 0);
10201 fprintf(stderr, "No arg for -%c option\n", c);
10202 unsetvar("OPTARG");
10210 err |= setvarsafe("OPTARG", p, 0);
10213 err |= setvarsafe("OPTARG", nullstr, 0);
10215 *optoff = p ? p - *(optnext - 1) : -1;
10216 *param_optind = optnext - optfirst + 1;
10217 fmtstr(s, sizeof(s), "%d", *param_optind);
10218 err |= setvarsafe("OPTIND", s, VNOFUNC);
10221 err |= setvarsafe(optvar, s, 0);
10225 flush_stdout_stderr();
10226 raise_exception(EXERROR);
10232 * The getopts builtin. Shellparam.optnext points to the next argument
10233 * to be processed. Shellparam.optptr points to the next character to
10234 * be processed in the current argument. If shellparam.optnext is NULL,
10235 * then it's the first time getopts has been called.
10237 static int FAST_FUNC
10238 getoptscmd(int argc, char **argv)
10243 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10245 optbase = shellparam.p;
10246 if (shellparam.optind > shellparam.nparam + 1) {
10247 shellparam.optind = 1;
10248 shellparam.optoff = -1;
10251 optbase = &argv[3];
10252 if (shellparam.optind > argc - 2) {
10253 shellparam.optind = 1;
10254 shellparam.optoff = -1;
10258 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10259 &shellparam.optoff);
10261 #endif /* ASH_GETOPTS */
10264 /* ============ Shell parser */
10267 struct heredoc *next; /* next here document in list */
10268 union node *here; /* redirection node */
10269 char *eofmark; /* string indicating end of input */
10270 smallint striptabs; /* if set, strip leading tabs */
10273 static smallint tokpushback; /* last token pushed back */
10274 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10275 static smallint quoteflag; /* set if (part of) last token was quoted */
10276 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10277 static struct heredoc *heredoclist; /* list of here documents to read */
10278 static char *wordtext; /* text of last word returned by readtoken */
10279 static struct nodelist *backquotelist;
10280 static union node *redirnode;
10281 static struct heredoc *heredoc;
10283 static const char *
10284 tokname(char *buf, int tok)
10287 return tokname_array[tok] + 1;
10288 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10292 /* raise_error_unexpected_syntax:
10293 * Called when an unexpected token is read during the parse. The argument
10294 * is the token that is expected, or -1 if more than one type of token can
10295 * occur at this point.
10297 static void raise_error_unexpected_syntax(int) NORETURN;
10299 raise_error_unexpected_syntax(int token)
10305 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10307 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10308 raise_error_syntax(msg);
10312 #define EOFMARKLEN 79
10314 /* parsing is heavily cross-recursive, need these forward decls */
10315 static union node *andor(void);
10316 static union node *pipeline(void);
10317 static union node *parse_command(void);
10318 static void parseheredoc(void);
10319 static char peektoken(void);
10320 static int readtoken(void);
10322 static union node *
10325 union node *n1, *n2, *n3;
10328 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10329 if (nlflag == 2 && peektoken())
10335 if (tok == TBACKGND) {
10336 if (n2->type == NPIPE) {
10337 n2->npipe.pipe_backgnd = 1;
10339 if (n2->type != NREDIR) {
10340 n3 = stzalloc(sizeof(struct nredir));
10342 /*n3->nredir.redirect = NULL; - stzalloc did it */
10345 n2->type = NBACKGND;
10351 n3 = stzalloc(sizeof(struct nbinary));
10353 n3->nbinary.ch1 = n1;
10354 n3->nbinary.ch2 = n2;
10370 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10378 pungetc(); /* push back EOF on input */
10382 raise_error_unexpected_syntax(-1);
10389 static union node *
10392 union node *n1, *n2, *n3;
10400 } else if (t == TOR) {
10406 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10408 n3 = stzalloc(sizeof(struct nbinary));
10410 n3->nbinary.ch1 = n1;
10411 n3->nbinary.ch2 = n2;
10416 static union node *
10419 union node *n1, *n2, *pipenode;
10420 struct nodelist *lp, *prev;
10424 TRACE(("pipeline: entered\n"));
10425 if (readtoken() == TNOT) {
10427 checkkwd = CHKKWD | CHKALIAS;
10430 n1 = parse_command();
10431 if (readtoken() == TPIPE) {
10432 pipenode = stzalloc(sizeof(struct npipe));
10433 pipenode->type = NPIPE;
10434 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10435 lp = stzalloc(sizeof(struct nodelist));
10436 pipenode->npipe.cmdlist = lp;
10440 lp = stzalloc(sizeof(struct nodelist));
10441 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10442 lp->n = parse_command();
10444 } while (readtoken() == TPIPE);
10450 n2 = stzalloc(sizeof(struct nnot));
10458 static union node *
10463 n = stzalloc(sizeof(struct narg));
10465 /*n->narg.next = NULL; - stzalloc did it */
10466 n->narg.text = wordtext;
10467 n->narg.backquote = backquotelist;
10472 fixredir(union node *n, const char *text, int err)
10476 TRACE(("Fix redir %s %d\n", text, err));
10478 n->ndup.vname = NULL;
10480 fd = bb_strtou(text, NULL, 10);
10481 if (!errno && fd >= 0)
10482 n->ndup.dupfd = fd;
10483 else if (LONE_DASH(text))
10484 n->ndup.dupfd = -1;
10487 raise_error_syntax("bad fd number");
10488 n->ndup.vname = makename();
10493 * Returns true if the text contains nothing to expand (no dollar signs
10497 noexpand(const char *text)
10501 while ((c = *text++) != '\0') {
10502 if (c == CTLQUOTEMARK)
10506 else if (SIT(c, BASESYNTAX) == CCTL)
10515 union node *n = redirnode;
10517 if (readtoken() != TWORD)
10518 raise_error_unexpected_syntax(-1);
10519 if (n->type == NHERE) {
10520 struct heredoc *here = heredoc;
10524 if (quoteflag == 0)
10526 TRACE(("Here document %d\n", n->type));
10527 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10528 raise_error_syntax("illegal eof marker for << redirection");
10529 rmescapes(wordtext, 0);
10530 here->eofmark = wordtext;
10532 if (heredoclist == NULL)
10533 heredoclist = here;
10535 for (p = heredoclist; p->next; p = p->next)
10539 } else if (n->type == NTOFD || n->type == NFROMFD) {
10540 fixredir(n, wordtext, 0);
10542 n->nfile.fname = makename();
10546 static union node *
10549 union node *args, **app;
10550 union node *n = NULL;
10551 union node *vars, **vpp;
10552 union node **rpp, *redir;
10554 #if ENABLE_ASH_BASH_COMPAT
10555 smallint double_brackets_flag = 0;
10565 savecheckkwd = CHKALIAS;
10568 checkkwd = savecheckkwd;
10571 #if ENABLE_ASH_BASH_COMPAT
10572 case TAND: /* "&&" */
10573 case TOR: /* "||" */
10574 if (!double_brackets_flag) {
10578 wordtext = (char *) (t == TAND ? "-a" : "-o");
10581 n = stzalloc(sizeof(struct narg));
10583 /*n->narg.next = NULL; - stzalloc did it */
10584 n->narg.text = wordtext;
10585 #if ENABLE_ASH_BASH_COMPAT
10586 if (strcmp("[[", wordtext) == 0)
10587 double_brackets_flag = 1;
10588 else if (strcmp("]]", wordtext) == 0)
10589 double_brackets_flag = 0;
10591 n->narg.backquote = backquotelist;
10592 if (savecheckkwd && isassignment(wordtext)) {
10594 vpp = &n->narg.next;
10597 app = &n->narg.next;
10602 *rpp = n = redirnode;
10603 rpp = &n->nfile.next;
10604 parsefname(); /* read name of redirection file */
10607 if (args && app == &args->narg.next
10610 struct builtincmd *bcmd;
10613 /* We have a function */
10614 if (readtoken() != TRP)
10615 raise_error_unexpected_syntax(TRP);
10616 name = n->narg.text;
10617 if (!goodname(name)
10618 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10620 raise_error_syntax("bad function name");
10623 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10624 n->narg.next = parse_command();
10637 n = stzalloc(sizeof(struct ncmd));
10639 n->ncmd.args = args;
10640 n->ncmd.assign = vars;
10641 n->ncmd.redirect = redir;
10645 static union node *
10646 parse_command(void)
10648 union node *n1, *n2;
10649 union node *ap, **app;
10650 union node *cp, **cpp;
10651 union node *redir, **rpp;
10658 switch (readtoken()) {
10660 raise_error_unexpected_syntax(-1);
10663 n1 = stzalloc(sizeof(struct nif));
10665 n1->nif.test = list(0);
10666 if (readtoken() != TTHEN)
10667 raise_error_unexpected_syntax(TTHEN);
10668 n1->nif.ifpart = list(0);
10670 while (readtoken() == TELIF) {
10671 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10672 n2 = n2->nif.elsepart;
10674 n2->nif.test = list(0);
10675 if (readtoken() != TTHEN)
10676 raise_error_unexpected_syntax(TTHEN);
10677 n2->nif.ifpart = list(0);
10679 if (lasttoken == TELSE)
10680 n2->nif.elsepart = list(0);
10682 n2->nif.elsepart = NULL;
10690 n1 = stzalloc(sizeof(struct nbinary));
10691 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10692 n1->nbinary.ch1 = list(0);
10695 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
10696 got == TWORD ? wordtext : ""));
10697 raise_error_unexpected_syntax(TDO);
10699 n1->nbinary.ch2 = list(0);
10704 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10705 raise_error_syntax("bad for loop variable");
10706 n1 = stzalloc(sizeof(struct nfor));
10708 n1->nfor.var = wordtext;
10709 checkkwd = CHKKWD | CHKALIAS;
10710 if (readtoken() == TIN) {
10712 while (readtoken() == TWORD) {
10713 n2 = stzalloc(sizeof(struct narg));
10715 /*n2->narg.next = NULL; - stzalloc did it */
10716 n2->narg.text = wordtext;
10717 n2->narg.backquote = backquotelist;
10719 app = &n2->narg.next;
10722 n1->nfor.args = ap;
10723 if (lasttoken != TNL && lasttoken != TSEMI)
10724 raise_error_unexpected_syntax(-1);
10726 n2 = stzalloc(sizeof(struct narg));
10728 /*n2->narg.next = NULL; - stzalloc did it */
10729 n2->narg.text = (char *)dolatstr;
10730 /*n2->narg.backquote = NULL;*/
10731 n1->nfor.args = n2;
10733 * Newline or semicolon here is optional (but note
10734 * that the original Bourne shell only allowed NL).
10736 if (lasttoken != TNL && lasttoken != TSEMI)
10739 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10740 if (readtoken() != TDO)
10741 raise_error_unexpected_syntax(TDO);
10742 n1->nfor.body = list(0);
10746 n1 = stzalloc(sizeof(struct ncase));
10748 if (readtoken() != TWORD)
10749 raise_error_unexpected_syntax(TWORD);
10750 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10752 /*n2->narg.next = NULL; - stzalloc did it */
10753 n2->narg.text = wordtext;
10754 n2->narg.backquote = backquotelist;
10756 checkkwd = CHKKWD | CHKALIAS;
10757 } while (readtoken() == TNL);
10758 if (lasttoken != TIN)
10759 raise_error_unexpected_syntax(TIN);
10760 cpp = &n1->ncase.cases;
10762 checkkwd = CHKNL | CHKKWD;
10764 while (t != TESAC) {
10765 if (lasttoken == TLP)
10767 *cpp = cp = stzalloc(sizeof(struct nclist));
10769 app = &cp->nclist.pattern;
10771 *app = ap = stzalloc(sizeof(struct narg));
10773 /*ap->narg.next = NULL; - stzalloc did it */
10774 ap->narg.text = wordtext;
10775 ap->narg.backquote = backquotelist;
10776 if (readtoken() != TPIPE)
10778 app = &ap->narg.next;
10781 //ap->narg.next = NULL;
10782 if (lasttoken != TRP)
10783 raise_error_unexpected_syntax(TRP);
10784 cp->nclist.body = list(2);
10786 cpp = &cp->nclist.next;
10788 checkkwd = CHKNL | CHKKWD;
10792 raise_error_unexpected_syntax(TENDCASE);
10799 n1 = stzalloc(sizeof(struct nredir));
10800 n1->type = NSUBSHELL;
10801 n1->nredir.n = list(0);
10802 /*n1->nredir.redirect = NULL; - stzalloc did it */
10812 return simplecmd();
10815 if (readtoken() != t)
10816 raise_error_unexpected_syntax(t);
10819 /* Now check for redirection which may follow command */
10820 checkkwd = CHKKWD | CHKALIAS;
10822 while (readtoken() == TREDIR) {
10823 *rpp = n2 = redirnode;
10824 rpp = &n2->nfile.next;
10830 if (n1->type != NSUBSHELL) {
10831 n2 = stzalloc(sizeof(struct nredir));
10836 n1->nredir.redirect = redir;
10841 #if ENABLE_ASH_BASH_COMPAT
10842 static int decode_dollar_squote(void)
10844 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10850 p = strchr(C_escapes, c);
10855 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10859 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10861 } else if (c == 'x') { /* \xHH */
10865 } while (isxdigit(c) && --cnt);
10867 if (cnt == 3) { /* \x but next char is "bad" */
10871 } else { /* simple seq like \\ or \t */
10876 c = bb_process_escape_sequence((void*)&p);
10877 } else { /* unrecognized "\z": print both chars unless ' or " */
10878 if (c != '\'' && c != '"') {
10880 c |= 0x100; /* "please encode \, then me" */
10888 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10889 * is not NULL, read a here document. In the latter case, eofmark is the
10890 * word which marks the end of the document and striptabs is true if
10891 * leading tabs should be stripped from the document. The argument c
10892 * is the first character of the input token or document.
10894 * Because C does not have internal subroutines, I have simulated them
10895 * using goto's to implement the subroutine linkage. The following macros
10896 * will run code that appears at the end of readtoken1.
10898 #define CHECKEND() {goto checkend; checkend_return:;}
10899 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10900 #define PARSESUB() {goto parsesub; parsesub_return:;}
10901 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10902 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10903 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10905 readtoken1(int c, int syntax, char *eofmark, int striptabs)
10907 /* NB: syntax parameter fits into smallint */
10908 /* c parameter is an unsigned char or PEOF or PEOA */
10911 char line[EOFMARKLEN + 1];
10912 struct nodelist *bqlist;
10916 smallint prevsyntax; /* syntax before arithmetic */
10917 #if ENABLE_ASH_EXPAND_PRMT
10918 smallint pssyntax; /* we are expanding a prompt string */
10920 int varnest; /* levels of variables expansion */
10921 int arinest; /* levels of arithmetic expansion */
10922 int parenlevel; /* levels of parens in arithmetic */
10923 int dqvarnest; /* levels of variables expansion within double quotes */
10925 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10928 /* Avoid longjmp clobbering */
10934 (void) &parenlevel;
10937 (void) &prevsyntax;
10940 startlinno = g_parsefile->linno;
10945 #if ENABLE_ASH_EXPAND_PRMT
10946 pssyntax = (syntax == PSSYNTAX);
10950 dblquote = (syntax == DQSYNTAX);
10956 STARTSTACKSTR(out);
10958 /* For each line, until end of word */
10960 CHECKEND(); /* set c to PEOF if at end of here document */
10961 for (;;) { /* until end of line or end of word */
10962 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10963 switch (SIT(c, syntax)) {
10964 case CNL: /* '\n' */
10965 if (syntax == BASESYNTAX)
10966 goto endword; /* exit outer loop */
10968 g_parsefile->linno++;
10972 goto loop; /* continue outer loop */
10977 if (eofmark == NULL || dblquote)
10978 USTPUTC(CTLESC, out);
10979 #if ENABLE_ASH_BASH_COMPAT
10980 if (c == '\\' && bash_dollar_squote) {
10981 c = decode_dollar_squote();
10983 USTPUTC('\\', out);
10984 c = (unsigned char)c;
10990 case CBACK: /* backslash */
10991 c = pgetc_without_PEOA();
10993 USTPUTC(CTLESC, out);
10994 USTPUTC('\\', out);
10996 } else if (c == '\n') {
11000 #if ENABLE_ASH_EXPAND_PRMT
11001 if (c == '$' && pssyntax) {
11002 USTPUTC(CTLESC, out);
11003 USTPUTC('\\', out);
11006 if (dblquote && c != '\\'
11007 && c != '`' && c != '$'
11008 && (c != '"' || eofmark != NULL)
11010 USTPUTC(CTLESC, out);
11011 USTPUTC('\\', out);
11013 if (SIT(c, SQSYNTAX) == CCTL)
11014 USTPUTC(CTLESC, out);
11022 if (eofmark == NULL) {
11023 USTPUTC(CTLQUOTEMARK, out);
11031 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11032 if (eofmark != NULL && arinest == 0
11037 if (dqvarnest == 0) {
11038 syntax = BASESYNTAX;
11045 case CVAR: /* '$' */
11046 PARSESUB(); /* parse substitution */
11048 case CENDVAR: /* '}' */
11051 if (dqvarnest > 0) {
11054 USTPUTC(CTLENDVAR, out);
11059 #if ENABLE_SH_MATH_SUPPORT
11060 case CLP: /* '(' in arithmetic */
11064 case CRP: /* ')' in arithmetic */
11065 if (parenlevel > 0) {
11069 if (pgetc() == ')') {
11070 if (--arinest == 0) {
11071 USTPUTC(CTLENDARI, out);
11072 syntax = prevsyntax;
11073 dblquote = (syntax == DQSYNTAX);
11078 * unbalanced parens
11079 * (don't 2nd guess - no error)
11087 case CBQUOTE: /* '`' */
11091 goto endword; /* exit outer loop */
11095 if (varnest == 0) {
11096 #if ENABLE_ASH_BASH_COMPAT
11098 if (pgetc() == '>')
11099 c = 0x100 + '>'; /* flag &> */
11103 goto endword; /* exit outer loop */
11105 IF_ASH_ALIAS(if (c != PEOA))
11113 #if ENABLE_SH_MATH_SUPPORT
11114 if (syntax == ARISYNTAX)
11115 raise_error_syntax("missing '))'");
11117 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11118 raise_error_syntax("unterminated quoted string");
11119 if (varnest != 0) {
11120 startlinno = g_parsefile->linno;
11122 raise_error_syntax("missing '}'");
11124 USTPUTC('\0', out);
11125 len = out - (char *)stackblock();
11126 out = stackblock();
11127 if (eofmark == NULL) {
11128 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11131 if (isdigit_str9(out)) {
11132 PARSEREDIR(); /* passed as params: out, c */
11133 lasttoken = TREDIR;
11136 /* else: non-number X seen, interpret it
11137 * as "NNNX>file" = "NNNX >file" */
11141 quoteflag = quotef;
11142 backquotelist = bqlist;
11143 grabstackblock(len);
11147 /* end of readtoken routine */
11150 * Check to see whether we are at the end of the here document. When this
11151 * is called, c is set to the first character of the next input line. If
11152 * we are at the end of the here document, this routine sets the c to PEOF.
11156 #if ENABLE_ASH_ALIAS
11158 c = pgetc_without_PEOA();
11161 while (c == '\t') {
11162 c = pgetc_without_PEOA();
11165 if (c == *eofmark) {
11166 if (pfgets(line, sizeof(line)) != NULL) {
11170 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11172 if (*p == '\n' && *q == '\0') {
11174 g_parsefile->linno++;
11175 needprompt = doprompt;
11177 pushstring(line, NULL);
11182 goto checkend_return;
11186 * Parse a redirection operator. The variable "out" points to a string
11187 * specifying the fd to be redirected. The variable "c" contains the
11188 * first character of the redirection operator.
11191 /* out is already checked to be a valid number or "" */
11192 int fd = (*out == '\0' ? -1 : atoi(out));
11195 np = stzalloc(sizeof(struct nfile));
11200 np->type = NAPPEND;
11202 np->type = NCLOBBER;
11205 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11211 #if ENABLE_ASH_BASH_COMPAT
11212 else if (c == 0x100 + '>') { /* this flags &> redirection */
11214 pgetc(); /* this is '>', no need to check */
11218 else { /* c == '<' */
11219 /*np->nfile.fd = 0; - stzalloc did it */
11223 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11224 np = stzalloc(sizeof(struct nhere));
11225 /*np->nfile.fd = 0; - stzalloc did it */
11228 heredoc = stzalloc(sizeof(struct heredoc));
11229 heredoc->here = np;
11232 heredoc->striptabs = 1;
11234 /*heredoc->striptabs = 0; - stzalloc did it */
11240 np->type = NFROMFD;
11244 np->type = NFROMTO;
11256 goto parseredir_return;
11260 * Parse a substitution. At this point, we have read the dollar sign
11261 * and nothing else.
11264 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11265 * (assuming ascii char codes, as the original implementation did) */
11266 #define is_special(c) \
11267 (((unsigned)(c) - 33 < 32) \
11268 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11270 unsigned char subtype;
11274 static const char types[] ALIGN1 = "}-+?=";
11277 if (c > 255 /* PEOA or PEOF */
11278 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11280 #if ENABLE_ASH_BASH_COMPAT
11282 bash_dollar_squote = 1;
11287 } else if (c == '(') { /* $(command) or $((arith)) */
11288 if (pgetc() == '(') {
11289 #if ENABLE_SH_MATH_SUPPORT
11292 raise_error_syntax("you disabled math support for $((arith)) syntax");
11299 USTPUTC(CTLVAR, out);
11300 typeloc = out - (char *)stackblock();
11301 USTPUTC(VSNORMAL, out);
11302 subtype = VSNORMAL;
11310 subtype = VSLENGTH;
11314 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11318 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11319 } else if (isdigit(c)) {
11323 } while (isdigit(c));
11324 } else if (is_special(c)) {
11329 raise_error_syntax("bad substitution");
11331 if (c != '}' && subtype == VSLENGTH)
11336 if (subtype == 0) {
11340 #if ENABLE_ASH_BASH_COMPAT
11341 if (c == ':' || c == '$' || isdigit(c)) {
11343 subtype = VSSUBSTR;
11350 p = strchr(types, c);
11353 subtype = p - types + VSNORMAL;
11358 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11366 #if ENABLE_ASH_BASH_COMPAT
11368 subtype = VSREPLACE;
11371 subtype++; /* VSREPLACEALL */
11380 if (dblquote || arinest)
11382 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11383 if (subtype != VSNORMAL) {
11385 if (dblquote || arinest) {
11390 goto parsesub_return;
11394 * Called to parse command substitutions. Newstyle is set if the command
11395 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11396 * list of commands (passed by reference), and savelen is the number of
11397 * characters on the top of the stack which must be preserved.
11400 struct nodelist **nlpp;
11403 char *volatile str;
11404 struct jmploc jmploc;
11405 struct jmploc *volatile savehandler;
11407 smallint saveprompt = 0;
11410 (void) &saveprompt;
11412 savepbq = parsebackquote;
11413 if (setjmp(jmploc.loc)) {
11415 parsebackquote = 0;
11416 exception_handler = savehandler;
11417 longjmp(exception_handler->loc, 1);
11421 savelen = out - (char *)stackblock();
11423 str = ckmalloc(savelen);
11424 memcpy(str, stackblock(), savelen);
11426 savehandler = exception_handler;
11427 exception_handler = &jmploc;
11430 /* We must read until the closing backquote, giving special
11431 treatment to some slashes, and then push the string and
11432 reread it as input, interpreting it normally. */
11439 STARTSTACKSTR(pout);
11452 g_parsefile->linno++;
11456 * If eating a newline, avoid putting
11457 * the newline into the new character
11458 * stream (via the STPUTC after the
11463 if (pc != '\\' && pc != '`' && pc != '$'
11464 && (!dblquote || pc != '"')
11466 STPUTC('\\', pout);
11468 if (pc <= 255 /* not PEOA or PEOF */) {
11474 IF_ASH_ALIAS(case PEOA:)
11475 startlinno = g_parsefile->linno;
11476 raise_error_syntax("EOF in backquote substitution");
11479 g_parsefile->linno++;
11480 needprompt = doprompt;
11489 STPUTC('\0', pout);
11490 psavelen = pout - (char *)stackblock();
11491 if (psavelen > 0) {
11492 pstr = grabstackstr(pout);
11493 setinputstring(pstr);
11498 nlpp = &(*nlpp)->next;
11499 *nlpp = stzalloc(sizeof(**nlpp));
11500 /* (*nlpp)->next = NULL; - stzalloc did it */
11501 parsebackquote = oldstyle;
11504 saveprompt = doprompt;
11511 doprompt = saveprompt;
11512 else if (readtoken() != TRP)
11513 raise_error_unexpected_syntax(TRP);
11518 * Start reading from old file again, ignoring any pushed back
11519 * tokens left from the backquote parsing
11524 while (stackblocksize() <= savelen)
11526 STARTSTACKSTR(out);
11528 memcpy(out, str, savelen);
11529 STADJUST(savelen, out);
11535 parsebackquote = savepbq;
11536 exception_handler = savehandler;
11537 if (arinest || dblquote)
11538 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11540 USTPUTC(CTLBACKQ, out);
11542 goto parsebackq_oldreturn;
11543 goto parsebackq_newreturn;
11546 #if ENABLE_SH_MATH_SUPPORT
11548 * Parse an arithmetic expansion (indicate start of one and set state)
11551 if (++arinest == 1) {
11552 prevsyntax = syntax;
11553 syntax = ARISYNTAX;
11554 USTPUTC(CTLARI, out);
11561 * we collapse embedded arithmetic expansion to
11562 * parenthesis, which should be equivalent
11566 goto parsearith_return;
11570 } /* end of readtoken */
11573 * Read the next input token.
11574 * If the token is a word, we set backquotelist to the list of cmds in
11575 * backquotes. We set quoteflag to true if any part of the word was
11577 * If the token is TREDIR, then we set redirnode to a structure containing
11579 * In all cases, the variable startlinno is set to the number of the line
11580 * on which the token starts.
11582 * [Change comment: here documents and internal procedures]
11583 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11584 * word parsing code into a separate routine. In this case, readtoken
11585 * doesn't need to have any internal procedures, but parseword does.
11586 * We could also make parseoperator in essence the main routine, and
11587 * have parseword (readtoken1?) handle both words and redirection.]
11589 #define NEW_xxreadtoken
11590 #ifdef NEW_xxreadtoken
11591 /* singles must be first! */
11592 static const char xxreadtoken_chars[7] ALIGN1 = {
11593 '\n', '(', ')', /* singles */
11594 '&', '|', ';', /* doubles */
11598 #define xxreadtoken_singles 3
11599 #define xxreadtoken_doubles 3
11601 static const char xxreadtoken_tokens[] ALIGN1 = {
11602 TNL, TLP, TRP, /* only single occurrence allowed */
11603 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11604 TEOF, /* corresponds to trailing nul */
11605 TAND, TOR, TENDCASE /* if double occurrence */
11620 startlinno = g_parsefile->linno;
11621 for (;;) { /* until token or start of word found */
11623 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11627 while ((c = pgetc()) != '\n' && c != PEOF)
11630 } else if (c == '\\') {
11631 if (pgetc() != '\n') {
11633 break; /* return readtoken1(...) */
11635 startlinno = ++g_parsefile->linno;
11641 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11644 g_parsefile->linno++;
11645 needprompt = doprompt;
11648 p = strchr(xxreadtoken_chars, c);
11650 break; /* return readtoken1(...) */
11652 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11654 if (cc == c) { /* double occurrence? */
11655 p += xxreadtoken_doubles + 1;
11658 #if ENABLE_ASH_BASH_COMPAT
11659 if (c == '&' && cc == '>') /* &> */
11660 break; /* return readtoken1(...) */
11665 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11670 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11672 #else /* old xxreadtoken */
11673 #define RETURN(token) return lasttoken = token
11686 startlinno = g_parsefile->linno;
11687 for (;;) { /* until token or start of word found */
11690 case ' ': case '\t':
11691 IF_ASH_ALIAS(case PEOA:)
11694 while ((c = pgetc()) != '\n' && c != PEOF)
11699 if (pgetc() == '\n') {
11700 startlinno = ++g_parsefile->linno;
11708 g_parsefile->linno++;
11709 needprompt = doprompt;
11714 if (pgetc() == '&')
11719 if (pgetc() == '|')
11724 if (pgetc() == ';')
11737 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11740 #endif /* old xxreadtoken */
11747 smallint alreadyseen = tokpushback;
11750 #if ENABLE_ASH_ALIAS
11759 if (checkkwd & CHKNL) {
11766 if (t != TWORD || quoteflag) {
11771 * check for keywords
11773 if (checkkwd & CHKKWD) {
11774 const char *const *pp;
11776 pp = findkwd(wordtext);
11778 lasttoken = t = pp - tokname_array;
11779 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
11784 if (checkkwd & CHKALIAS) {
11785 #if ENABLE_ASH_ALIAS
11787 ap = lookupalias(wordtext, 1);
11790 pushstring(ap->val, ap);
11800 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11802 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11814 return tokname_array[t][0];
11818 * Read and parse a command. Returns NODE_EOF on end of file.
11819 * (NULL is a valid parse tree indicating a blank line.)
11821 static union node *
11822 parsecmd(int interact)
11827 doprompt = interact;
11829 setprompt(doprompt);
11841 * Input any here documents.
11846 struct heredoc *here;
11849 here = heredoclist;
11850 heredoclist = NULL;
11856 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11857 here->eofmark, here->striptabs);
11858 n = stzalloc(sizeof(struct narg));
11859 n->narg.type = NARG;
11860 /*n->narg.next = NULL; - stzalloc did it */
11861 n->narg.text = wordtext;
11862 n->narg.backquote = backquotelist;
11863 here->here->nhere.doc = n;
11870 * called by editline -- any expansions to the prompt should be added here.
11872 #if ENABLE_ASH_EXPAND_PRMT
11873 static const char *
11874 expandstr(const char *ps)
11878 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11879 * and token processing _can_ alter it (delete NULs etc). */
11880 setinputstring((char *)ps);
11881 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11884 n.narg.type = NARG;
11885 n.narg.next = NULL;
11886 n.narg.text = wordtext;
11887 n.narg.backquote = backquotelist;
11889 expandarg(&n, NULL, 0);
11890 return stackblock();
11895 * Execute a command or commands contained in a string.
11898 evalstring(char *s, int mask)
11901 struct stackmark smark;
11905 setstackmark(&smark);
11908 while ((n = parsecmd(0)) != NODE_EOF) {
11910 popstackmark(&smark);
11923 * The eval command.
11925 static int FAST_FUNC
11926 evalcmd(int argc UNUSED_PARAM, char **argv)
11935 STARTSTACKSTR(concat);
11937 concat = stack_putstr(p, concat);
11941 STPUTC(' ', concat);
11943 STPUTC('\0', concat);
11944 p = grabstackstr(concat);
11946 evalstring(p, ~SKIPEVAL);
11953 * Read and execute commands.
11954 * "Top" is nonzero for the top level command loop;
11955 * it turns on prompting if the shell is interactive.
11961 struct stackmark smark;
11965 TRACE(("cmdloop(%d) called\n", top));
11969 setstackmark(&smark);
11972 showjobs(stderr, SHOW_CHANGED);
11975 if (iflag && top) {
11977 #if ENABLE_ASH_MAIL
11981 n = parsecmd(inter);
11983 if (DEBUG > 2 && debug && (n != NODE_EOF))
11986 if (n == NODE_EOF) {
11987 if (!top || numeof >= 50)
11989 if (!stoppedjobs()) {
11992 out2str("\nUse \"exit\" to leave shell.\n");
11995 } else if (nflag == 0) {
11996 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12001 popstackmark(&smark);
12006 return skip & SKIPEVAL;
12013 * Take commands from a file. To be compatible we should do a path
12014 * search for the file, which is necessary to find sub-commands.
12017 find_dot_file(char *name)
12020 const char *path = pathval();
12023 /* don't try this for absolute or relative paths */
12024 if (strchr(name, '/'))
12027 /* IIRC standards do not say whether . is to be searched.
12028 * And it is even smaller this way, making it unconditional for now:
12030 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12035 while ((fullname = path_advance(&path, name)) != NULL) {
12037 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12039 * Don't bother freeing here, since it will
12040 * be freed by the caller.
12044 if (fullname != name)
12045 stunalloc(fullname);
12048 /* not found in the PATH */
12049 ash_msg_and_raise_error("%s: not found", name);
12053 static int FAST_FUNC
12054 dotcmd(int argc, char **argv)
12057 struct strlist *sp;
12058 volatile struct shparam saveparam;
12060 for (sp = cmdenviron; sp; sp = sp->next)
12061 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12064 /* bash says: "bash: .: filename argument required" */
12065 return 2; /* bash compat */
12068 /* "false; . empty_file; echo $?" should print 0, not 1: */
12071 fullname = find_dot_file(argv[1]);
12075 if (argc) { /* argc > 0, argv[0] != NULL */
12076 saveparam = shellparam;
12077 shellparam.malloced = 0;
12078 shellparam.nparam = argc;
12079 shellparam.p = argv;
12082 setinputfile(fullname, INPUT_PUSH_FILE);
12083 commandname = fullname;
12088 freeparam(&shellparam);
12089 shellparam = saveparam;
12095 static int FAST_FUNC
12096 exitcmd(int argc UNUSED_PARAM, char **argv)
12101 exitstatus = number(argv[1]);
12102 raise_exception(EXEXIT);
12107 * Read a file containing shell functions.
12110 readcmdfile(char *name)
12112 setinputfile(name, INPUT_PUSH_FILE);
12118 /* ============ find_command inplementation */
12121 * Resolve a command name. If you change this routine, you may have to
12122 * change the shellexec routine as well.
12125 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12127 struct tblentry *cmdp;
12134 struct builtincmd *bcmd;
12136 /* If name contains a slash, don't use PATH or hash table */
12137 if (strchr(name, '/') != NULL) {
12138 entry->u.index = -1;
12139 if (act & DO_ABS) {
12140 while (stat(name, &statb) < 0) {
12142 if (errno == EINTR)
12145 entry->cmdtype = CMDUNKNOWN;
12149 entry->cmdtype = CMDNORMAL;
12153 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12155 updatetbl = (path == pathval());
12158 if (strstr(path, "%builtin") != NULL)
12159 act |= DO_ALTBLTIN;
12162 /* If name is in the table, check answer will be ok */
12163 cmdp = cmdlookup(name, 0);
12164 if (cmdp != NULL) {
12167 switch (cmdp->cmdtype) {
12185 } else if (cmdp->rehash == 0)
12186 /* if not invalidated by cd, we're done */
12190 /* If %builtin not in path, check for builtin next */
12191 bcmd = find_builtin(name);
12193 if (IS_BUILTIN_REGULAR(bcmd))
12194 goto builtin_success;
12195 if (act & DO_ALTPATH) {
12196 if (!(act & DO_ALTBLTIN))
12197 goto builtin_success;
12198 } else if (builtinloc <= 0) {
12199 goto builtin_success;
12203 #if ENABLE_FEATURE_SH_STANDALONE
12205 int applet_no = find_applet_by_name(name);
12206 if (applet_no >= 0) {
12207 entry->cmdtype = CMDNORMAL;
12208 entry->u.index = -2 - applet_no;
12214 /* We have to search path. */
12215 prev = -1; /* where to start */
12216 if (cmdp && cmdp->rehash) { /* doing a rehash */
12217 if (cmdp->cmdtype == CMDBUILTIN)
12220 prev = cmdp->param.index;
12226 while ((fullname = path_advance(&path, name)) != NULL) {
12227 stunalloc(fullname);
12228 /* NB: code below will still use fullname
12229 * despite it being "unallocated" */
12232 if (prefix(pathopt, "builtin")) {
12234 goto builtin_success;
12237 if ((act & DO_NOFUNC)
12238 || !prefix(pathopt, "func")
12239 ) { /* ignore unimplemented options */
12243 /* if rehash, don't redo absolute path names */
12244 if (fullname[0] == '/' && idx <= prev) {
12247 TRACE(("searchexec \"%s\": no change\n", name));
12250 while (stat(fullname, &statb) < 0) {
12252 if (errno == EINTR)
12255 if (errno != ENOENT && errno != ENOTDIR)
12259 e = EACCES; /* if we fail, this will be the error */
12260 if (!S_ISREG(statb.st_mode))
12262 if (pathopt) { /* this is a %func directory */
12263 stalloc(strlen(fullname) + 1);
12264 /* NB: stalloc will return space pointed by fullname
12265 * (because we don't have any intervening allocations
12266 * between stunalloc above and this stalloc) */
12267 readcmdfile(fullname);
12268 cmdp = cmdlookup(name, 0);
12269 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12270 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12271 stunalloc(fullname);
12274 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12276 entry->cmdtype = CMDNORMAL;
12277 entry->u.index = idx;
12281 cmdp = cmdlookup(name, 1);
12282 cmdp->cmdtype = CMDNORMAL;
12283 cmdp->param.index = idx;
12288 /* We failed. If there was an entry for this command, delete it */
12289 if (cmdp && updatetbl)
12290 delete_cmd_entry();
12292 ash_msg("%s: %s", name, errmsg(e, "not found"));
12293 entry->cmdtype = CMDUNKNOWN;
12298 entry->cmdtype = CMDBUILTIN;
12299 entry->u.cmd = bcmd;
12303 cmdp = cmdlookup(name, 1);
12304 cmdp->cmdtype = CMDBUILTIN;
12305 cmdp->param.cmd = bcmd;
12309 entry->cmdtype = cmdp->cmdtype;
12310 entry->u = cmdp->param;
12314 /* ============ trap.c */
12317 * The trap builtin.
12319 static int FAST_FUNC
12320 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12324 int signo, exitcode;
12329 for (signo = 0; signo < NSIG; signo++) {
12330 char *tr = trap_ptr[signo];
12332 /* note: bash adds "SIG", but only if invoked
12333 * as "bash". If called as "sh", or if set -o posix,
12334 * then it prints short signal names.
12335 * We are printing short names: */
12336 out1fmt("trap -- %s %s\n",
12338 get_signame(signo));
12339 /* trap_ptr != trap only if we are in special-cased `trap` code.
12340 * In this case, we will exit very soon, no need to free(). */
12341 /* if (trap_ptr != trap && tp[0]) */
12346 if (trap_ptr != trap) {
12359 signo = get_signum(*ap);
12361 /* Mimic bash message exactly */
12362 ash_msg("%s: invalid signal specification", *ap);
12368 if (LONE_DASH(action))
12371 action = ckstrdup(action);
12375 may_have_traps = 1;
12376 trap[signo] = action;
12387 /* ============ Builtins */
12389 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12391 * Lists available builtins
12393 static int FAST_FUNC
12394 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12400 "Built-in commands:\n"
12401 "------------------\n");
12402 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12403 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12404 builtintab[i].name + 1);
12410 #if ENABLE_FEATURE_SH_STANDALONE
12412 const char *a = applet_names;
12414 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12419 a += strlen(a) + 1;
12424 return EXIT_SUCCESS;
12426 #endif /* FEATURE_SH_EXTRA_QUIET */
12429 * The export and readonly commands.
12431 static int FAST_FUNC
12432 exportcmd(int argc UNUSED_PARAM, char **argv)
12438 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12440 if (nextopt("p") != 'p') {
12445 p = strchr(name, '=');
12449 vp = *findvar(hashvar(name), name);
12455 setvar(name, p, flag);
12456 } while ((name = *++aptr) != NULL);
12460 showvars(argv[0], flag, 0);
12465 * Delete a function if it exists.
12468 unsetfunc(const char *name)
12470 struct tblentry *cmdp;
12472 cmdp = cmdlookup(name, 0);
12473 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12474 delete_cmd_entry();
12478 * The unset builtin command. We unset the function before we unset the
12479 * variable to allow a function to be unset when there is a readonly variable
12480 * with the same name.
12482 static int FAST_FUNC
12483 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12490 while ((i = nextopt("vf")) != 0) {
12494 for (ap = argptr; *ap; ap++) {
12507 static const unsigned char timescmd_str[] ALIGN1 = {
12508 ' ', offsetof(struct tms, tms_utime),
12509 '\n', offsetof(struct tms, tms_stime),
12510 ' ', offsetof(struct tms, tms_cutime),
12511 '\n', offsetof(struct tms, tms_cstime),
12514 static int FAST_FUNC
12515 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12517 long clk_tck, s, t;
12518 const unsigned char *p;
12521 clk_tck = sysconf(_SC_CLK_TCK);
12526 t = *(clock_t *)(((char *) &buf) + p[1]);
12528 out1fmt("%ldm%ld.%.3lds%c",
12530 ((t - s * clk_tck) * 1000) / clk_tck,
12538 #if ENABLE_SH_MATH_SUPPORT
12540 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12541 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12543 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12545 static int FAST_FUNC
12546 letcmd(int argc UNUSED_PARAM, char **argv)
12552 ash_msg_and_raise_error("expression expected");
12554 i = ash_arith(*argv);
12562 * The read builtin. Options:
12563 * -r Do not interpret '\' specially
12564 * -s Turn off echo (tty only)
12565 * -n NCHARS Read NCHARS max
12566 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12567 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12568 * -u FD Read from given FD instead of fd 0
12569 * This uses unbuffered input, which may be avoidable in some cases.
12570 * TODO: bash also has:
12571 * -a ARRAY Read into array[0],[1],etc
12572 * -d DELIM End on DELIM char, not newline
12573 * -e Use line editing (tty only)
12575 static int FAST_FUNC
12576 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12578 char *opt_n = NULL;
12579 char *opt_p = NULL;
12580 char *opt_t = NULL;
12581 char *opt_u = NULL;
12582 int read_flags = 0;
12586 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12595 read_flags |= BUILTIN_READ_SILENT;
12601 read_flags |= BUILTIN_READ_RAW;
12611 r = shell_builtin_read(setvar2,
12613 bltinlookup("IFS"), /* can be NULL */
12621 if ((uintptr_t)r > 1)
12622 ash_msg_and_raise_error(r);
12624 return (uintptr_t)r;
12627 static int FAST_FUNC
12628 umaskcmd(int argc UNUSED_PARAM, char **argv)
12630 static const char permuser[3] ALIGN1 = "ugo";
12631 static const char permmode[3] ALIGN1 = "rwx";
12632 static const short permmask[] ALIGN2 = {
12633 S_IRUSR, S_IWUSR, S_IXUSR,
12634 S_IRGRP, S_IWGRP, S_IXGRP,
12635 S_IROTH, S_IWOTH, S_IXOTH
12638 /* TODO: use bb_parse_mode() instead */
12643 int symbolic_mode = 0;
12645 while (nextopt("S") != '\0') {
12656 if (symbolic_mode) {
12660 for (i = 0; i < 3; i++) {
12663 *p++ = permuser[i];
12665 for (j = 0; j < 3; j++) {
12666 if ((mask & permmask[3 * i + j]) == 0) {
12667 *p++ = permmode[j];
12675 out1fmt("%.4o\n", mask);
12678 if (isdigit((unsigned char) *ap)) {
12681 if (*ap >= '8' || *ap < '0')
12682 ash_msg_and_raise_error(msg_illnum, argv[1]);
12683 mask = (mask << 3) + (*ap - '0');
12684 } while (*++ap != '\0');
12687 mask = ~mask & 0777;
12688 if (!bb_parse_mode(ap, &mask)) {
12689 ash_msg_and_raise_error("illegal mode: %s", ap);
12691 umask(~mask & 0777);
12697 static int FAST_FUNC
12698 ulimitcmd(int argc UNUSED_PARAM, char **argv)
12700 return shell_builtin_ulimit(argv);
12703 /* ============ main() and helpers */
12706 * Called to exit the shell.
12708 static void exitshell(void) NORETURN;
12716 status = exitstatus;
12717 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12718 if (setjmp(loc.loc)) {
12719 if (exception_type == EXEXIT)
12720 /* dash bug: it just does _exit(exitstatus) here
12721 * but we have to do setjobctl(0) first!
12722 * (bug is still not fixed in dash-0.5.3 - if you run dash
12723 * under Midnight Commander, on exit from dash MC is backgrounded) */
12724 status = exitstatus;
12727 exception_handler = &loc;
12734 flush_stdout_stderr();
12744 /* from input.c: */
12745 /* we will never free this */
12746 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
12749 signal(SIGCHLD, SIG_DFL);
12750 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12751 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12753 signal(SIGHUP, SIG_DFL);
12759 struct stat st1, st2;
12762 for (envp = environ; envp && *envp; envp++) {
12763 if (strchr(*envp, '=')) {
12764 setvareq(*envp, VEXPORT|VTEXTFIXED);
12768 setvar("PPID", utoa(getppid()), 0);
12770 p = lookupvar("PWD");
12772 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12773 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12780 * Process the shell command line arguments.
12783 procargs(char **argv)
12786 const char *xminusc;
12791 /* if (xargv[0]) - mmm, this is always true! */
12793 for (i = 0; i < NOPTS; i++)
12797 /* it already printed err message */
12798 raise_exception(EXERROR);
12802 if (*xargv == NULL) {
12804 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12807 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12811 for (i = 0; i < NOPTS; i++)
12812 if (optlist[i] == 2)
12817 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12822 } else if (!sflag) {
12823 setinputfile(*xargv, 0);
12826 commandname = arg0;
12829 shellparam.p = xargv;
12830 #if ENABLE_ASH_GETOPTS
12831 shellparam.optind = 1;
12832 shellparam.optoff = -1;
12834 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
12836 shellparam.nparam++;
12843 * Read /etc/profile or .profile.
12846 read_profile(const char *name)
12850 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12859 * This routine is called when an error or an interrupt occurs in an
12860 * interactive shell and control is returned to the main command loop.
12868 /* from input.c: */
12869 g_parsefile->left_in_buffer = 0;
12870 g_parsefile->left_in_line = 0; /* clear input buffer */
12872 /* from parser.c: */
12875 /* from redir.c: */
12876 clearredir(/*drop:*/ 0);
12880 static short profile_buf[16384];
12881 extern int etext();
12885 * Main routine. We initialize things, parse the arguments, execute
12886 * profiles if we're a login shell, and then call cmdloop to execute
12887 * commands. The setjmp call sets up the location to jump to when an
12888 * exception occurs. When an exception occurs the variable "state"
12889 * is used to figure out how far we had gotten.
12891 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
12892 int ash_main(int argc UNUSED_PARAM, char **argv)
12894 const char *shinit;
12895 volatile smallint state;
12896 struct jmploc jmploc;
12897 struct stackmark smark;
12899 /* Initialize global data */
12903 #if ENABLE_ASH_ALIAS
12909 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12912 #if ENABLE_FEATURE_EDITING
12913 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12916 if (setjmp(jmploc.loc)) {
12922 e = exception_type;
12926 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12929 outcslow('\n', stderr);
12931 popstackmark(&smark);
12932 FORCE_INT_ON; /* enable interrupts */
12941 exception_handler = &jmploc;
12944 TRACE(("Shell args: "));
12945 trace_puts_args(argv);
12947 rootpid = getpid();
12950 setstackmark(&smark);
12953 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
12955 const char *hp = lookupvar("HISTFILE");
12958 hp = lookupvar("HOME");
12960 char *defhp = concat_path_file(hp, ".ash_history");
12961 setvar("HISTFILE", defhp, 0);
12967 if (/* argv[0] && */ argv[0][0] == '-')
12971 read_profile("/etc/profile");
12974 read_profile(".profile");
12980 getuid() == geteuid() && getgid() == getegid() &&
12984 shinit = lookupvar("ENV");
12985 if (shinit != NULL && *shinit != '\0') {
12986 read_profile(shinit);
12992 /* evalstring pushes parsefile stack.
12993 * Ensure we don't falsely claim that 0 (stdin)
12994 * is one of stacked source fds.
12995 * Testcase: ash -c 'exec 1>&0' must not complain. */
12996 // if (!sflag) g_parsefile->pf_fd = -1;
12997 // ^^ not necessary since now we special-case fd 0
12998 // in is_hidden_fd() to not be considered "hidden fd"
12999 evalstring(minusc, 0);
13002 if (sflag || minusc == NULL) {
13003 #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13005 const char *hp = lookupvar("HISTFILE");
13007 line_input_state->hist_file = hp;
13010 state4: /* XXX ??? - why isn't this before the "if" statement */
13018 extern void _mcleanup(void);
13028 * Copyright (c) 1989, 1991, 1993, 1994
13029 * The Regents of the University of California. All rights reserved.
13031 * This code is derived from software contributed to Berkeley by
13032 * Kenneth Almquist.
13034 * Redistribution and use in source and binary forms, with or without
13035 * modification, are permitted provided that the following conditions
13037 * 1. Redistributions of source code must retain the above copyright
13038 * notice, this list of conditions and the following disclaimer.
13039 * 2. Redistributions in binary form must reproduce the above copyright
13040 * notice, this list of conditions and the following disclaimer in the
13041 * documentation and/or other materials provided with the distribution.
13042 * 3. Neither the name of the University nor the names of its contributors
13043 * may be used to endorse or promote products derived from this software
13044 * without specific prior written permission.
13046 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13047 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13048 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13049 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13050 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13051 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13052 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13053 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13054 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13055 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF