1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
20 * The following should be set to reflect the type of system you have:
21 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22 * define SYSV if you are running under System V.
23 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24 * define DEBUG=2 to compile in and turn on debugging.
26 * When debugging is on, debugging info will be written to ./trace and
27 * a quit signal will generate a core dump.
30 /* Tweak debug output verbosity here */
37 #define JOBS ENABLE_ASH_JOB_CONTROL
45 #include "busybox.h" /* for applet_names */
46 //TODO: pull in some .h and find out do we have SINGLE_APPLET_MAIN?
47 //#include "applet_tables.h" doesn't work
52 #include "shell_common.h"
53 #include "builtin_read.h"
55 #if ENABLE_ASH_RANDOM_SUPPORT
58 # define CLEAR_RANDOM_T(rnd) ((void)0)
61 #if defined SINGLE_APPLET_MAIN
62 /* STANDALONE does not make sense, and won't compile */
63 # undef CONFIG_FEATURE_SH_STANDALONE
64 # undef ENABLE_FEATURE_SH_STANDALONE
65 # undef IF_FEATURE_SH_STANDALONE
66 # undef IF_NOT_FEATURE_SH_STANDALONE(...)
67 # define ENABLE_FEATURE_SH_STANDALONE 0
68 # define IF_FEATURE_SH_STANDALONE(...)
69 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
73 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
77 # error "Do not even bother, ash will not run on NOMMU machine"
81 /* ============ Hash table sizes. Configurable. */
85 #define CMDTABLESIZE 31 /* should be prime */
88 /* ============ Shell options */
90 static const char *const optletters_optnames[] = {
105 #if ENABLE_ASH_BASH_COMPAT
114 #define optletters(n) optletters_optnames[n][0]
115 #define optnames(n) (optletters_optnames[n] + 1)
117 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
120 /* ============ Misc data */
122 static const char homestr[] ALIGN1 = "HOME";
123 static const char snlfmt[] ALIGN1 = "%s\n";
124 static const char msg_illnum[] ALIGN1 = "Illegal number: %s";
127 * We enclose jmp_buf in a structure so that we can declare pointers to
128 * jump locations. The global variable handler contains the location to
129 * jump to when an exception occurs, and the global variable exception_type
130 * contains a code identifying the exception. To implement nested
131 * exception handlers, the user should save the value of handler on entry
132 * to an inner scope, set handler to point to a jmploc structure for the
133 * inner scope, and restore handler on exit from the scope.
139 struct globals_misc {
140 /* pid of main shell */
142 /* shell level: 0 for the main shell, 1 for its children, and so on */
144 #define rootshell (!shlvl)
145 char *minusc; /* argument to -c option */
147 char *curdir; // = nullstr; /* current working directory */
148 char *physdir; // = nullstr; /* physical working directory */
150 char *arg0; /* value of $0 */
152 struct jmploc *exception_handler;
154 volatile int suppress_int; /* counter */
155 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
156 /* last pending signal */
157 volatile /*sig_atomic_t*/ smallint pending_sig;
158 smallint exception_type; /* kind of exception (0..5) */
160 #define EXINT 0 /* SIGINT received */
161 #define EXERROR 1 /* a generic error */
162 #define EXSHELLPROC 2 /* execute a shell procedure */
163 #define EXEXEC 3 /* command execution failed */
164 #define EXEXIT 4 /* exit the shell */
165 #define EXSIG 5 /* trapped signal in wait(1) */
168 char nullstr[1]; /* zero length string */
171 #define eflag optlist[0]
172 #define fflag optlist[1]
173 #define Iflag optlist[2]
174 #define iflag optlist[3]
175 #define mflag optlist[4]
176 #define nflag optlist[5]
177 #define sflag optlist[6]
178 #define xflag optlist[7]
179 #define vflag optlist[8]
180 #define Cflag optlist[9]
181 #define aflag optlist[10]
182 #define bflag optlist[11]
183 #define uflag optlist[12]
184 #define viflag optlist[13]
185 #if ENABLE_ASH_BASH_COMPAT
186 # define pipefail optlist[14]
191 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
192 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
195 /* trap handler commands */
197 * Sigmode records the current value of the signal handlers for the various
198 * modes. A value of zero means that the current handler is not known.
199 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
201 char sigmode[NSIG - 1];
202 #define S_DFL 1 /* default signal handling (SIG_DFL) */
203 #define S_CATCH 2 /* signal is caught */
204 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
205 #define S_HARD_IGN 4 /* signal is ignored permenantly */
207 /* indicates specified signal received */
208 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
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 trap (G_misc.trap )
238 #define trap_ptr (G_misc.trap_ptr )
239 #define random_gen (G_misc.random_gen )
240 #define backgndpid (G_misc.backgndpid )
241 #define job_warning (G_misc.job_warning)
242 #define INIT_G_misc() do { \
243 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
251 /* ============ DEBUG */
253 static void trace_printf(const char *fmt, ...);
254 static void trace_vprintf(const char *fmt, va_list va);
255 # define TRACE(param) trace_printf param
256 # define TRACEV(param) trace_vprintf param
257 # define close(fd) do { \
259 if (close(dfd) < 0) \
260 bb_error_msg("bug on %d: closing %d(0x%x)", \
261 __LINE__, dfd, dfd); \
264 # define TRACE(param)
265 # define TRACEV(param)
269 /* ============ Utility functions */
270 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
272 static int isdigit_str9(const char *str)
274 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
275 while (--maxlen && isdigit(*str))
277 return (*str == '\0');
281 /* ============ Interrupts / exceptions */
283 * These macros allow the user to suspend the handling of interrupt signals
284 * over a period of time. This is similar to SIGHOLD or to sigblock, but
285 * much more efficient and portable. (But hacking the kernel is so much
286 * more fun than worrying about efficiency and portability. :-))
288 #define INT_OFF do { \
294 * Called to raise an exception. Since C doesn't include exceptions, we
295 * just do a longjmp to the exception handler. The type of exception is
296 * stored in the global variable "exception_type".
298 static void raise_exception(int) NORETURN;
300 raise_exception(int e)
303 if (exception_handler == NULL)
308 longjmp(exception_handler->loc, 1);
311 #define raise_exception(e) do { \
312 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
313 raise_exception(e); \
318 * Called from trap.c when a SIGINT is received. (If the user specifies
319 * that SIGINT is to be trapped or ignored using the trap builtin, then
320 * this routine is not called.) Suppressint is nonzero when interrupts
321 * are held using the INT_OFF macro. (The test for iflag is just
322 * defensive programming.)
324 static void raise_interrupt(void) NORETURN;
326 raise_interrupt(void)
331 /* Signal is not automatically unmasked after it is raised,
332 * do it ourself - unmask all signals */
333 sigprocmask_allsigs(SIG_UNBLOCK);
334 /* pending_sig = 0; - now done in onsig() */
337 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
338 if (!(rootshell && iflag)) {
339 /* Kill ourself with SIGINT */
340 signal(SIGINT, SIG_DFL);
345 raise_exception(ex_type);
349 #define raise_interrupt() do { \
350 TRACE(("raising interrupt on line %d\n", __LINE__)); \
355 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
359 if (--suppress_int == 0 && pending_int) {
363 #define INT_ON int_on()
364 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
372 #define FORCE_INT_ON force_int_on()
374 #define SAVE_INT(v) ((v) = suppress_int)
376 #define RESTORE_INT(v) do { \
378 suppress_int = (v); \
379 if (suppress_int == 0 && pending_int) \
384 /* ============ Stdout/stderr output */
387 outstr(const char *p, FILE *file)
395 flush_stdout_stderr(void)
403 outcslow(int c, FILE *dest)
411 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
413 out1fmt(const char *fmt, ...)
420 r = vprintf(fmt, ap);
426 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
428 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
435 ret = vsnprintf(outbuf, length, fmt, ap);
442 out1str(const char *p)
448 out2str(const char *p)
451 flush_stdout_stderr();
455 /* ============ Parser structures */
457 /* control characters in argument strings */
458 #define CTL_FIRST CTLESC
459 #define CTLESC ((unsigned char)'\201') /* escape next character */
460 #define CTLVAR ((unsigned char)'\202') /* variable defn */
461 #define CTLENDVAR ((unsigned char)'\203')
462 #define CTLBACKQ ((unsigned char)'\204')
463 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
464 /* CTLBACKQ | CTLQUOTE == '\205' */
465 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
466 #define CTLENDARI ((unsigned char)'\207')
467 #define CTLQUOTEMARK ((unsigned char)'\210')
468 #define CTL_LAST CTLQUOTEMARK
470 /* variable substitution byte (follows CTLVAR) */
471 #define VSTYPE 0x0f /* type of variable substitution */
472 #define VSNUL 0x10 /* colon--treat the empty string as unset */
473 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
475 /* values of VSTYPE field */
476 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
477 #define VSMINUS 0x2 /* ${var-text} */
478 #define VSPLUS 0x3 /* ${var+text} */
479 #define VSQUESTION 0x4 /* ${var?message} */
480 #define VSASSIGN 0x5 /* ${var=text} */
481 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
482 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
483 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
484 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
485 #define VSLENGTH 0xa /* ${#var} */
486 #if ENABLE_ASH_BASH_COMPAT
487 #define VSSUBSTR 0xc /* ${var:position:length} */
488 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
489 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
492 static const char dolatstr[] ALIGN1 = {
493 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
513 #if ENABLE_ASH_BASH_COMPAT
530 smallint type; /* Nxxxx */
533 union node *redirect;
538 smallint pipe_backgnd;
539 struct nodelist *cmdlist;
545 union node *redirect;
558 union node *elsepart;
585 struct nodelist *backquote;
588 /* nfile and ndup layout must match!
589 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
590 * that it is actually NTO2 (>&file), and change its type.
607 char *_unused_expfname;
626 struct nredir nredir;
627 struct nbinary nbinary;
631 struct nclist nclist;
640 * NODE_EOF is returned by parsecmd when it encounters an end of file.
641 * It must be distinct from NULL.
643 #define NODE_EOF ((union node *) -1L)
646 struct nodelist *next;
659 freefunc(struct funcnode *f)
661 if (f && --f->count < 0)
666 /* ============ Debugging output */
670 static FILE *tracefile;
673 trace_printf(const char *fmt, ...)
680 fprintf(tracefile, "%u ", (int) time(NULL));
682 fprintf(tracefile, "[%u] ", (int) getpid());
684 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
686 vfprintf(tracefile, fmt, va);
691 trace_vprintf(const char *fmt, va_list va)
696 fprintf(tracefile, "%u ", (int) time(NULL));
698 fprintf(tracefile, "[%u] ", (int) getpid());
700 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
701 vfprintf(tracefile, fmt, va);
705 trace_puts(const char *s)
713 trace_puts_quoted(char *s)
720 putc('"', tracefile);
721 for (p = s; *p; p++) {
722 switch ((unsigned char)*p) {
723 case '\n': c = 'n'; goto backslash;
724 case '\t': c = 't'; goto backslash;
725 case '\r': c = 'r'; goto backslash;
726 case '\"': c = '\"'; goto backslash;
727 case '\\': c = '\\'; goto backslash;
728 case CTLESC: c = 'e'; goto backslash;
729 case CTLVAR: c = 'v'; goto backslash;
730 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
731 case CTLBACKQ: c = 'q'; goto backslash;
732 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
734 putc('\\', tracefile);
738 if (*p >= ' ' && *p <= '~')
741 putc('\\', tracefile);
742 putc((*p >> 6) & 03, tracefile);
743 putc((*p >> 3) & 07, tracefile);
744 putc(*p & 07, tracefile);
749 putc('"', tracefile);
753 trace_puts_args(char **ap)
760 trace_puts_quoted(*ap);
762 putc('\n', tracefile);
765 putc(' ', tracefile);
780 /* leave open because libedit might be using it */
783 strcpy(s, "./trace");
785 if (!freopen(s, "a", tracefile)) {
786 fprintf(stderr, "Can't re-open %s\n", s);
791 tracefile = fopen(s, "a");
792 if (tracefile == NULL) {
793 fprintf(stderr, "Can't open %s\n", s);
799 flags = fcntl(fileno(tracefile), F_GETFL);
801 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
803 setlinebuf(tracefile);
804 fputs("\nTracing started.\n", tracefile);
808 indent(int amount, char *pfx, FILE *fp)
812 for (i = 0; i < amount; i++) {
813 if (pfx && i == amount - 1)
819 /* little circular references here... */
820 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
823 sharg(union node *arg, FILE *fp)
826 struct nodelist *bqlist;
827 unsigned char subtype;
829 if (arg->type != NARG) {
830 out1fmt("<node type %d>\n", arg->type);
833 bqlist = arg->narg.backquote;
834 for (p = arg->narg.text; *p; p++) {
835 switch ((unsigned char)*p) {
843 if (subtype == VSLENGTH)
852 switch (subtype & VSTYPE) {
885 out1fmt("<subtype %d>", subtype);
892 case CTLBACKQ|CTLQUOTE:
895 shtree(bqlist->n, -1, NULL, fp);
906 shcmd(union node *cmd, FILE *fp)
914 for (np = cmd->ncmd.args; np; np = np->narg.next) {
920 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
924 switch (np->nfile.type) {
925 case NTO: s = ">>"+1; dftfd = 1; break;
926 case NCLOBBER: s = ">|"; dftfd = 1; break;
927 case NAPPEND: s = ">>"; dftfd = 1; break;
928 #if ENABLE_ASH_BASH_COMPAT
931 case NTOFD: s = ">&"; dftfd = 1; break;
932 case NFROM: s = "<"; break;
933 case NFROMFD: s = "<&"; break;
934 case NFROMTO: s = "<>"; break;
935 default: s = "*error*"; break;
937 if (np->nfile.fd != dftfd)
938 fprintf(fp, "%d", np->nfile.fd);
940 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
941 fprintf(fp, "%d", np->ndup.dupfd);
943 sharg(np->nfile.fname, fp);
950 shtree(union node *n, int ind, char *pfx, FILE *fp)
958 indent(ind, pfx, fp);
975 shtree(n->nbinary.ch1, ind, NULL, fp);
978 shtree(n->nbinary.ch2, ind, NULL, fp);
986 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
987 shtree(lp->n, 0, NULL, fp);
991 if (n->npipe.pipe_backgnd)
997 fprintf(fp, "<node type %d>", n->type);
1005 showtree(union node *n)
1007 trace_puts("showtree called\n");
1008 shtree(n, 1, NULL, stderr);
1014 /* ============ Parser data */
1017 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1020 struct strlist *next;
1027 struct strpush *prev; /* preceding string on stack */
1029 int prev_left_in_line;
1030 #if ENABLE_ASH_ALIAS
1031 struct alias *ap; /* if push was associated with an alias */
1033 char *string; /* remember the string since it may change */
1037 struct parsefile *prev; /* preceding file on stack */
1038 int linno; /* current line */
1039 int fd; /* file descriptor (or -1 if string) */
1040 int left_in_line; /* number of chars left in this line */
1041 int left_in_buffer; /* number of chars left in this buffer past the line */
1042 char *next_to_pgetc; /* next char in buffer */
1043 char *buf; /* input buffer */
1044 struct strpush *strpush; /* for pushing strings at this level */
1045 struct strpush basestrpush; /* so pushing one is fast */
1048 static struct parsefile basepf; /* top level input file */
1049 static struct parsefile *g_parsefile = &basepf; /* current input file */
1050 static int startlinno; /* line # where last token started */
1051 static char *commandname; /* currently executing command */
1052 static struct strlist *cmdenviron; /* environment for builtin command */
1053 static uint8_t exitstatus; /* exit status of last command */
1056 /* ============ Message printing */
1059 ash_vmsg(const char *msg, va_list ap)
1061 fprintf(stderr, "%s: ", arg0);
1063 if (strcmp(arg0, commandname))
1064 fprintf(stderr, "%s: ", commandname);
1065 if (!iflag || g_parsefile->fd)
1066 fprintf(stderr, "line %d: ", startlinno);
1068 vfprintf(stderr, msg, ap);
1069 outcslow('\n', stderr);
1073 * Exverror is called to raise the error exception. If the second argument
1074 * is not NULL then error prints an error message using printf style
1075 * formatting. It then raises the error exception.
1077 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1079 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1083 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1085 TRACE(("\") pid=%d\n", getpid()));
1087 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1092 flush_stdout_stderr();
1093 raise_exception(cond);
1097 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1099 ash_msg_and_raise_error(const char *msg, ...)
1104 ash_vmsg_and_raise(EXERROR, msg, ap);
1109 static void raise_error_syntax(const char *) NORETURN;
1111 raise_error_syntax(const char *msg)
1113 ash_msg_and_raise_error("syntax error: %s", msg);
1117 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1119 ash_msg_and_raise(int cond, const char *msg, ...)
1124 ash_vmsg_and_raise(cond, msg, ap);
1130 * error/warning routines for external builtins
1133 ash_msg(const char *fmt, ...)
1143 * Return a string describing an error. The returned string may be a
1144 * pointer to a static buffer that will be overwritten on the next call.
1145 * Action describes the operation that got the error.
1148 errmsg(int e, const char *em)
1150 if (e == ENOENT || e == ENOTDIR) {
1157 /* ============ Memory allocation */
1160 /* I consider these wrappers nearly useless:
1161 * ok, they return you to nearest exception handler, but
1162 * how much memory do you leak in the process, making
1163 * memory starvation worse?
1166 ckrealloc(void * p, size_t nbytes)
1168 p = realloc(p, nbytes);
1170 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1175 ckmalloc(size_t nbytes)
1177 return ckrealloc(NULL, nbytes);
1181 ckzalloc(size_t nbytes)
1183 return memset(ckmalloc(nbytes), 0, nbytes);
1187 ckstrdup(const char *s)
1189 char *p = strdup(s);
1191 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1195 /* Using bbox equivalents. They exit if out of memory */
1196 # define ckrealloc xrealloc
1197 # define ckmalloc xmalloc
1198 # define ckzalloc xzalloc
1199 # define ckstrdup xstrdup
1203 * It appears that grabstackstr() will barf with such alignments
1204 * because stalloc() will return a string allocated in a new stackblock.
1206 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1208 /* Most machines require the value returned from malloc to be aligned
1209 * in some way. The following macro will get this right
1210 * on many machines. */
1211 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1212 /* Minimum size of a block */
1213 MINSIZE = SHELL_ALIGN(504),
1216 struct stack_block {
1217 struct stack_block *prev;
1218 char space[MINSIZE];
1222 struct stack_block *stackp;
1225 struct stackmark *marknext;
1229 struct globals_memstack {
1230 struct stack_block *g_stackp; // = &stackbase;
1231 struct stackmark *markp;
1232 char *g_stacknxt; // = stackbase.space;
1233 char *sstrend; // = stackbase.space + MINSIZE;
1234 size_t g_stacknleft; // = MINSIZE;
1235 int herefd; // = -1;
1236 struct stack_block stackbase;
1238 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1239 #define G_memstack (*ash_ptr_to_globals_memstack)
1240 #define g_stackp (G_memstack.g_stackp )
1241 #define markp (G_memstack.markp )
1242 #define g_stacknxt (G_memstack.g_stacknxt )
1243 #define sstrend (G_memstack.sstrend )
1244 #define g_stacknleft (G_memstack.g_stacknleft)
1245 #define herefd (G_memstack.herefd )
1246 #define stackbase (G_memstack.stackbase )
1247 #define INIT_G_memstack() do { \
1248 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1250 g_stackp = &stackbase; \
1251 g_stacknxt = stackbase.space; \
1252 g_stacknleft = MINSIZE; \
1253 sstrend = stackbase.space + MINSIZE; \
1258 #define stackblock() ((void *)g_stacknxt)
1259 #define stackblocksize() g_stacknleft
1262 * Parse trees for commands are allocated in lifo order, so we use a stack
1263 * to make this more efficient, and also to avoid all sorts of exception
1264 * handling code to handle interrupts in the middle of a parse.
1266 * The size 504 was chosen because the Ultrix malloc handles that size
1270 stalloc(size_t nbytes)
1275 aligned = SHELL_ALIGN(nbytes);
1276 if (aligned > g_stacknleft) {
1279 struct stack_block *sp;
1281 blocksize = aligned;
1282 if (blocksize < MINSIZE)
1283 blocksize = MINSIZE;
1284 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1285 if (len < blocksize)
1286 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1289 sp->prev = g_stackp;
1290 g_stacknxt = sp->space;
1291 g_stacknleft = blocksize;
1292 sstrend = g_stacknxt + blocksize;
1297 g_stacknxt += aligned;
1298 g_stacknleft -= aligned;
1303 stzalloc(size_t nbytes)
1305 return memset(stalloc(nbytes), 0, nbytes);
1312 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1313 write(STDERR_FILENO, "stunalloc\n", 10);
1317 g_stacknleft += g_stacknxt - (char *)p;
1322 * Like strdup but works with the ash stack.
1325 ststrdup(const char *p)
1327 size_t len = strlen(p) + 1;
1328 return memcpy(stalloc(len), p, len);
1332 setstackmark(struct stackmark *mark)
1334 mark->stackp = g_stackp;
1335 mark->stacknxt = g_stacknxt;
1336 mark->stacknleft = g_stacknleft;
1337 mark->marknext = markp;
1342 popstackmark(struct stackmark *mark)
1344 struct stack_block *sp;
1350 markp = mark->marknext;
1351 while (g_stackp != mark->stackp) {
1353 g_stackp = sp->prev;
1356 g_stacknxt = mark->stacknxt;
1357 g_stacknleft = mark->stacknleft;
1358 sstrend = mark->stacknxt + mark->stacknleft;
1363 * When the parser reads in a string, it wants to stick the string on the
1364 * stack and only adjust the stack pointer when it knows how big the
1365 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1366 * of space on top of the stack and stackblocklen returns the length of
1367 * this block. Growstackblock will grow this space by at least one byte,
1368 * possibly moving it (like realloc). Grabstackblock actually allocates the
1369 * part of the block that has been used.
1372 growstackblock(void)
1376 newlen = g_stacknleft * 2;
1377 if (newlen < g_stacknleft)
1378 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1382 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1383 struct stack_block *oldstackp;
1384 struct stackmark *xmark;
1385 struct stack_block *sp;
1386 struct stack_block *prevstackp;
1390 oldstackp = g_stackp;
1392 prevstackp = sp->prev;
1393 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1394 sp = ckrealloc(sp, grosslen);
1395 sp->prev = prevstackp;
1397 g_stacknxt = sp->space;
1398 g_stacknleft = newlen;
1399 sstrend = sp->space + newlen;
1402 * Stack marks pointing to the start of the old block
1403 * must be relocated to point to the new block
1406 while (xmark != NULL && xmark->stackp == oldstackp) {
1407 xmark->stackp = g_stackp;
1408 xmark->stacknxt = g_stacknxt;
1409 xmark->stacknleft = g_stacknleft;
1410 xmark = xmark->marknext;
1414 char *oldspace = g_stacknxt;
1415 size_t oldlen = g_stacknleft;
1416 char *p = stalloc(newlen);
1418 /* free the space we just allocated */
1419 g_stacknxt = memcpy(p, oldspace, oldlen);
1420 g_stacknleft += newlen;
1425 grabstackblock(size_t len)
1427 len = SHELL_ALIGN(len);
1429 g_stacknleft -= len;
1433 * The following routines are somewhat easier to use than the above.
1434 * The user declares a variable of type STACKSTR, which may be declared
1435 * to be a register. The macro STARTSTACKSTR initializes things. Then
1436 * the user uses the macro STPUTC to add characters to the string. In
1437 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1438 * grown as necessary. When the user is done, she can just leave the
1439 * string there and refer to it using stackblock(). Or she can allocate
1440 * the space for it using grabstackstr(). If it is necessary to allow
1441 * someone else to use the stack temporarily and then continue to grow
1442 * the string, the user should use grabstack to allocate the space, and
1443 * then call ungrabstr(p) to return to the previous mode of operation.
1445 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1446 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1447 * is space for at least one character.
1452 size_t len = stackblocksize();
1453 if (herefd >= 0 && len >= 1024) {
1454 full_write(herefd, stackblock(), len);
1455 return stackblock();
1458 return (char *)stackblock() + len;
1462 * Called from CHECKSTRSPACE.
1465 makestrspace(size_t newlen, char *p)
1467 size_t len = p - g_stacknxt;
1468 size_t size = stackblocksize();
1473 size = stackblocksize();
1475 if (nleft >= newlen)
1479 return (char *)stackblock() + len;
1483 stack_nputstr(const char *s, size_t n, char *p)
1485 p = makestrspace(n, p);
1486 p = (char *)memcpy(p, s, n) + n;
1491 stack_putstr(const char *s, char *p)
1493 return stack_nputstr(s, strlen(s), p);
1497 _STPUTC(int c, char *p)
1505 #define STARTSTACKSTR(p) ((p) = stackblock())
1506 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1507 #define CHECKSTRSPACE(n, p) do { \
1510 size_t m = sstrend - q; \
1512 (p) = makestrspace(l, q); \
1514 #define USTPUTC(c, p) (*(p)++ = (c))
1515 #define STACKSTRNUL(p) do { \
1516 if ((p) == sstrend) \
1517 (p) = growstackstr(); \
1520 #define STUNPUTC(p) (--(p))
1521 #define STTOPC(p) ((p)[-1])
1522 #define STADJUST(amount, p) ((p) += (amount))
1524 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1525 #define ungrabstackstr(s, p) stunalloc(s)
1526 #define stackstrend() ((void *)sstrend)
1529 /* ============ String helpers */
1532 * prefix -- see if pfx is a prefix of string.
1535 prefix(const char *string, const char *pfx)
1538 if (*pfx++ != *string++)
1541 return (char *) string;
1545 * Check for a valid number. This should be elsewhere.
1548 is_number(const char *p)
1553 } while (*++p != '\0');
1558 * Convert a string of digits to an integer, printing an error message on
1562 number(const char *s)
1565 ash_msg_and_raise_error(msg_illnum, s);
1570 * Produce a possibly single quoted string suitable as input to the shell.
1571 * The return string is allocated on the stack.
1574 single_quote(const char *s)
1584 len = strchrnul(s, '\'') - s;
1586 q = p = makestrspace(len + 3, p);
1589 q = (char *)memcpy(q, s, len) + len;
1598 do len++; while (*++s == '\'');
1600 q = p = makestrspace(len + 3, p);
1603 q = (char *)memcpy(q, s - len, len) + len;
1611 return stackblock();
1615 /* ============ nextopt */
1617 static char **argptr; /* argument list for builtin commands */
1618 static char *optionarg; /* set by nextopt (like getopt) */
1619 static char *optptr; /* used by nextopt */
1622 * XXX - should get rid of. Have all builtins use getopt(3).
1623 * The library getopt must have the BSD extension static variable
1624 * "optreset", otherwise it can't be used within the shell safely.
1626 * Standard option processing (a la getopt) for builtin routines.
1627 * The only argument that is passed to nextopt is the option string;
1628 * the other arguments are unnecessary. It returns the character,
1629 * or '\0' on end of input.
1632 nextopt(const char *optstring)
1639 if (p == NULL || *p == '\0') {
1640 /* We ate entire "-param", take next one */
1646 if (*++p == '\0') /* just "-" ? */
1649 if (LONE_DASH(p)) /* "--" ? */
1651 /* p => next "-param" */
1653 /* p => some option char in the middle of a "-param" */
1655 for (q = optstring; *q != c;) {
1657 ash_msg_and_raise_error("illegal option -%c", c);
1665 ash_msg_and_raise_error("no arg for -%c option", c);
1675 /* ============ Shell variables */
1678 * The parsefile structure pointed to by the global variable parsefile
1679 * contains information about the current file being read.
1682 int nparam; /* # of positional parameters (without $0) */
1683 #if ENABLE_ASH_GETOPTS
1684 int optind; /* next parameter to be processed by getopts */
1685 int optoff; /* used by getopts */
1687 unsigned char malloced; /* if parameter list dynamically allocated */
1688 char **p; /* parameter list */
1692 * Free the list of positional parameters.
1695 freeparam(volatile struct shparam *param)
1697 if (param->malloced) {
1699 ap = ap1 = param->p;
1706 #if ENABLE_ASH_GETOPTS
1707 static void FAST_FUNC getoptsreset(const char *value);
1711 struct var *next; /* next entry in hash list */
1712 int flags; /* flags are defined above */
1713 const char *text; /* name=value */
1714 void (*func)(const char *) FAST_FUNC; /* function to be called when */
1715 /* the variable gets set/unset */
1719 struct localvar *next; /* next local variable in list */
1720 struct var *vp; /* the variable that was made local */
1721 int flags; /* saved flags */
1722 const char *text; /* saved text */
1726 #define VEXPORT 0x01 /* variable is exported */
1727 #define VREADONLY 0x02 /* variable cannot be modified */
1728 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1729 #define VTEXTFIXED 0x08 /* text is statically allocated */
1730 #define VSTACK 0x10 /* text is allocated on the stack */
1731 #define VUNSET 0x20 /* the variable is not set */
1732 #define VNOFUNC 0x40 /* don't call the callback function */
1733 #define VNOSET 0x80 /* do not set variable - just readonly test */
1734 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1735 #if ENABLE_ASH_RANDOM_SUPPORT
1736 # define VDYNAMIC 0x200 /* dynamic variable */
1742 /* Need to be before varinit_data[] */
1743 #if ENABLE_LOCALE_SUPPORT
1744 static void FAST_FUNC
1745 change_lc_all(const char *value)
1747 if (value && *value != '\0')
1748 setlocale(LC_ALL, value);
1750 static void FAST_FUNC
1751 change_lc_ctype(const char *value)
1753 if (value && *value != '\0')
1754 setlocale(LC_CTYPE, value);
1758 static void chkmail(void);
1759 static void changemail(const char *) FAST_FUNC;
1761 static void changepath(const char *) FAST_FUNC;
1762 #if ENABLE_ASH_RANDOM_SUPPORT
1763 static void change_random(const char *) FAST_FUNC;
1766 static const struct {
1769 void (*func)(const char *) FAST_FUNC;
1770 } varinit_data[] = {
1771 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1773 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1774 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1776 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1777 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1778 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1779 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1780 #if ENABLE_ASH_GETOPTS
1781 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1783 #if ENABLE_ASH_RANDOM_SUPPORT
1784 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
1786 #if ENABLE_LOCALE_SUPPORT
1787 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1788 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
1790 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1791 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
1797 struct globals_var {
1798 struct shparam shellparam; /* $@ current positional parameters */
1799 struct redirtab *redirlist;
1801 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1802 struct var *vartab[VTABSIZE];
1803 struct var varinit[ARRAY_SIZE(varinit_data)];
1805 extern struct globals_var *const ash_ptr_to_globals_var;
1806 #define G_var (*ash_ptr_to_globals_var)
1807 #define shellparam (G_var.shellparam )
1808 //#define redirlist (G_var.redirlist )
1809 #define g_nullredirs (G_var.g_nullredirs )
1810 #define preverrout_fd (G_var.preverrout_fd)
1811 #define vartab (G_var.vartab )
1812 #define varinit (G_var.varinit )
1813 #define INIT_G_var() do { \
1815 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1817 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1818 varinit[i].flags = varinit_data[i].flags; \
1819 varinit[i].text = varinit_data[i].text; \
1820 varinit[i].func = varinit_data[i].func; \
1824 #define vifs varinit[0]
1826 # define vmail (&vifs)[1]
1827 # define vmpath (&vmail)[1]
1828 # define vpath (&vmpath)[1]
1830 # define vpath (&vifs)[1]
1832 #define vps1 (&vpath)[1]
1833 #define vps2 (&vps1)[1]
1834 #define vps4 (&vps2)[1]
1835 #if ENABLE_ASH_GETOPTS
1836 # define voptind (&vps4)[1]
1837 # if ENABLE_ASH_RANDOM_SUPPORT
1838 # define vrandom (&voptind)[1]
1841 # if ENABLE_ASH_RANDOM_SUPPORT
1842 # define vrandom (&vps4)[1]
1847 * The following macros access the values of the above variables.
1848 * They have to skip over the name. They return the null string
1849 * for unset variables.
1851 #define ifsval() (vifs.text + 4)
1852 #define ifsset() ((vifs.flags & VUNSET) == 0)
1854 # define mailval() (vmail.text + 5)
1855 # define mpathval() (vmpath.text + 9)
1856 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1858 #define pathval() (vpath.text + 5)
1859 #define ps1val() (vps1.text + 4)
1860 #define ps2val() (vps2.text + 4)
1861 #define ps4val() (vps4.text + 4)
1862 #if ENABLE_ASH_GETOPTS
1863 # define optindval() (voptind.text + 7)
1867 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1868 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1870 #if ENABLE_ASH_GETOPTS
1871 static void FAST_FUNC
1872 getoptsreset(const char *value)
1874 shellparam.optind = number(value);
1875 shellparam.optoff = -1;
1880 * Return of a legal variable name (a letter or underscore followed by zero or
1881 * more letters, underscores, and digits).
1883 static char* FAST_FUNC
1884 endofname(const char *name)
1892 if (!is_in_name(*p))
1899 * Compares two strings up to the first = or '\0'. The first
1900 * string must be terminated by '='; the second may be terminated by
1901 * either '=' or '\0'.
1904 varcmp(const char *p, const char *q)
1908 while ((c = *p) == (d = *q)) {
1923 varequal(const char *a, const char *b)
1925 return !varcmp(a, b);
1929 * Find the appropriate entry in the hash table from the name.
1931 static struct var **
1932 hashvar(const char *p)
1936 hashval = ((unsigned char) *p) << 4;
1937 while (*p && *p != '=')
1938 hashval += (unsigned char) *p++;
1939 return &vartab[hashval % VTABSIZE];
1943 vpcmp(const void *a, const void *b)
1945 return varcmp(*(const char **)a, *(const char **)b);
1949 * This routine initializes the builtin variables.
1959 * PS1 depends on uid
1961 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1962 vps1.text = "PS1=\\w \\$ ";
1965 vps1.text = "PS1=# ";
1968 end = vp + ARRAY_SIZE(varinit);
1970 vpp = hashvar(vp->text);
1973 } while (++vp < end);
1976 static struct var **
1977 findvar(struct var **vpp, const char *name)
1979 for (; *vpp; vpp = &(*vpp)->next) {
1980 if (varequal((*vpp)->text, name)) {
1988 * Find the value of a variable. Returns NULL if not set.
1990 static const char* FAST_FUNC
1991 lookupvar(const char *name)
1995 v = *findvar(hashvar(name), name);
1997 #if ENABLE_ASH_RANDOM_SUPPORT
1999 * Dynamic variables are implemented roughly the same way they are
2000 * in bash. Namely, they're "special" so long as they aren't unset.
2001 * As soon as they're unset, they're no longer dynamic, and dynamic
2002 * lookup will no longer happen at that point. -- PFM.
2004 if ((v->flags & VDYNAMIC))
2007 if (!(v->flags & VUNSET))
2008 return strchrnul(v->text, '=') + 1;
2014 * Search the environment of a builtin command.
2017 bltinlookup(const char *name)
2021 for (sp = cmdenviron; sp; sp = sp->next) {
2022 if (varequal(sp->text, name))
2023 return strchrnul(sp->text, '=') + 1;
2025 return lookupvar(name);
2029 * Same as setvar except that the variable and value are passed in
2030 * the first argument as name=value. Since the first argument will
2031 * be actually stored in the table, it should not be a string that
2033 * Called with interrupts off.
2036 setvareq(char *s, int flags)
2038 struct var *vp, **vpp;
2041 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2042 vp = *findvar(vpp, s);
2044 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2047 if (flags & VNOSAVE)
2050 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2056 if (vp->func && (flags & VNOFUNC) == 0)
2057 (*vp->func)(strchrnul(s, '=') + 1);
2059 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2060 free((char*)vp->text);
2062 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2067 vp = ckzalloc(sizeof(*vp));
2069 /*vp->func = NULL; - ckzalloc did it */
2072 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2079 * Set the value of a variable. The flags argument is ored with the
2080 * flags of the variable. If val is NULL, the variable is unset.
2083 setvar(const char *name, const char *val, int flags)
2090 q = endofname(name);
2091 p = strchrnul(q, '=');
2093 if (!namelen || p != q)
2094 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2099 vallen = strlen(val);
2102 nameeq = ckmalloc(namelen + vallen + 2);
2103 p = (char *)memcpy(nameeq, name, namelen) + namelen;
2106 p = (char *)memcpy(p, val, vallen) + vallen;
2109 setvareq(nameeq, flags | VNOSAVE);
2113 static void FAST_FUNC
2114 setvar2(const char *name, const char *val)
2116 setvar(name, val, 0);
2119 #if ENABLE_ASH_GETOPTS
2121 * Safe version of setvar, returns 1 on success 0 on failure.
2124 setvarsafe(const char *name, const char *val, int flags)
2127 volatile int saveint;
2128 struct jmploc *volatile savehandler = exception_handler;
2129 struct jmploc jmploc;
2132 if (setjmp(jmploc.loc))
2135 exception_handler = &jmploc;
2136 setvar(name, val, flags);
2139 exception_handler = savehandler;
2140 RESTORE_INT(saveint);
2146 * Unset the specified variable.
2149 unsetvar(const char *s)
2155 vpp = findvar(hashvar(s), s);
2159 int flags = vp->flags;
2162 if (flags & VREADONLY)
2164 #if ENABLE_ASH_RANDOM_SUPPORT
2165 vp->flags &= ~VDYNAMIC;
2169 if ((flags & VSTRFIXED) == 0) {
2171 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2172 free((char*)vp->text);
2178 vp->flags &= ~VEXPORT;
2188 * Process a linked list of variable assignments.
2191 listsetvar(struct strlist *list_set_var, int flags)
2193 struct strlist *lp = list_set_var;
2199 setvareq(lp->text, flags);
2206 * Generate a list of variables satisfying the given conditions.
2209 listvars(int on, int off, char ***end)
2220 for (vp = *vpp; vp; vp = vp->next) {
2221 if ((vp->flags & mask) == on) {
2222 if (ep == stackstrend())
2223 ep = growstackstr();
2224 *ep++ = (char *) vp->text;
2227 } while (++vpp < vartab + VTABSIZE);
2228 if (ep == stackstrend())
2229 ep = growstackstr();
2233 return grabstackstr(ep);
2237 /* ============ Path search helper
2239 * The variable path (passed by reference) should be set to the start
2240 * of the path before the first call; path_advance will update
2241 * this value as it proceeds. Successive calls to path_advance will return
2242 * the possible path expansions in sequence. If an option (indicated by
2243 * a percent sign) appears in the path entry then the global variable
2244 * pathopt will be set to point to it; otherwise pathopt will be set to
2247 static const char *pathopt; /* set by path_advance */
2250 path_advance(const char **path, const char *name)
2260 for (p = start; *p && *p != ':' && *p != '%'; p++)
2262 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2263 while (stackblocksize() < len)
2267 memcpy(q, start, p - start);
2275 while (*p && *p != ':')
2282 return stalloc(len);
2286 /* ============ Prompt */
2288 static smallint doprompt; /* if set, prompt the user */
2289 static smallint needprompt; /* true if interactive and at start of line */
2291 #if ENABLE_FEATURE_EDITING
2292 static line_input_t *line_input_state;
2293 static const char *cmdedit_prompt;
2295 putprompt(const char *s)
2297 if (ENABLE_ASH_EXPAND_PRMT) {
2298 free((char*)cmdedit_prompt);
2299 cmdedit_prompt = ckstrdup(s);
2306 putprompt(const char *s)
2312 #if ENABLE_ASH_EXPAND_PRMT
2313 /* expandstr() needs parsing machinery, so it is far away ahead... */
2314 static const char *expandstr(const char *ps);
2316 #define expandstr(s) s
2320 setprompt(int whichprompt)
2323 #if ENABLE_ASH_EXPAND_PRMT
2324 struct stackmark smark;
2329 switch (whichprompt) {
2339 #if ENABLE_ASH_EXPAND_PRMT
2340 setstackmark(&smark);
2341 stalloc(stackblocksize());
2343 putprompt(expandstr(prompt));
2344 #if ENABLE_ASH_EXPAND_PRMT
2345 popstackmark(&smark);
2350 /* ============ The cd and pwd commands */
2352 #define CD_PHYSICAL 1
2362 while ((i = nextopt("LP")) != '\0') {
2364 flags ^= CD_PHYSICAL;
2373 * Update curdir (the name of the current directory) in response to a
2377 updatepwd(const char *dir)
2384 cdcomppath = ststrdup(dir);
2387 if (curdir == nullstr)
2389 new = stack_putstr(curdir, new);
2391 new = makestrspace(strlen(dir) + 2, new);
2392 lim = (char *)stackblock() + 1;
2396 if (new > lim && *lim == '/')
2401 if (dir[1] == '/' && dir[2] != '/') {
2407 p = strtok(cdcomppath, "/");
2411 if (p[1] == '.' && p[2] == '\0') {
2423 new = stack_putstr(p, new);
2431 return stackblock();
2435 * Find out what the current directory is. If we already know the current
2436 * directory, this routine returns immediately.
2441 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2442 return dir ? dir : nullstr;
2446 setpwd(const char *val, int setold)
2450 oldcur = dir = curdir;
2453 setvar("OLDPWD", oldcur, VEXPORT);
2456 if (physdir != nullstr) {
2457 if (physdir != oldcur)
2461 if (oldcur == val || !val) {
2467 dir = ckstrdup(val);
2468 if (oldcur != dir && oldcur != nullstr) {
2473 setvar("PWD", dir, VEXPORT);
2476 static void hashcd(void);
2479 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2480 * know that the current directory has changed.
2483 docd(const char *dest, int flags)
2485 const char *dir = NULL;
2488 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2491 if (!(flags & CD_PHYSICAL)) {
2492 dir = updatepwd(dest);
2506 static int FAST_FUNC
2507 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2519 dest = bltinlookup(homestr);
2520 else if (LONE_DASH(dest)) {
2521 dest = bltinlookup("OLDPWD");
2543 path = bltinlookup("CDPATH");
2552 p = path_advance(&path, dest);
2553 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2557 if (!docd(p, flags))
2562 ash_msg_and_raise_error("can't cd to %s", dest);
2565 if (flags & CD_PRINT)
2566 out1fmt(snlfmt, curdir);
2570 static int FAST_FUNC
2571 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2574 const char *dir = curdir;
2578 if (physdir == nullstr)
2582 out1fmt(snlfmt, dir);
2587 /* ============ ... */
2590 #define IBUFSIZ COMMON_BUFSIZE
2591 /* buffer for top level input file */
2592 #define basebuf bb_common_bufsiz1
2594 /* Syntax classes */
2595 #define CWORD 0 /* character is nothing special */
2596 #define CNL 1 /* newline character */
2597 #define CBACK 2 /* a backslash character */
2598 #define CSQUOTE 3 /* single quote */
2599 #define CDQUOTE 4 /* double quote */
2600 #define CENDQUOTE 5 /* a terminating quote */
2601 #define CBQUOTE 6 /* backwards single quote */
2602 #define CVAR 7 /* a dollar sign */
2603 #define CENDVAR 8 /* a '}' character */
2604 #define CLP 9 /* a left paren in arithmetic */
2605 #define CRP 10 /* a right paren in arithmetic */
2606 #define CENDFILE 11 /* end of file */
2607 #define CCTL 12 /* like CWORD, except it must be escaped */
2608 #define CSPCL 13 /* these terminate a word */
2609 #define CIGN 14 /* character should be ignored */
2612 #if ENABLE_ASH_ALIAS
2616 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2618 #if ENABLE_SH_MATH_SUPPORT
2619 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2621 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2623 static const uint16_t S_I_T[] = {
2624 #if ENABLE_ASH_ALIAS
2625 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2627 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2628 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2629 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2630 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2631 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2632 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2633 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2634 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2635 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2636 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2637 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2638 #if !USE_SIT_FUNCTION
2639 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2640 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2641 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2645 /* Constants below must match table above */
2647 #if ENABLE_ASH_ALIAS
2648 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2650 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2651 CNL_CNL_CNL_CNL , /* 2 */
2652 CWORD_CCTL_CCTL_CWORD , /* 3 */
2653 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2654 CVAR_CVAR_CWORD_CVAR , /* 5 */
2655 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2656 CSPCL_CWORD_CWORD_CLP , /* 7 */
2657 CSPCL_CWORD_CWORD_CRP , /* 8 */
2658 CBACK_CBACK_CCTL_CBACK , /* 9 */
2659 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2660 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2661 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2662 CWORD_CWORD_CWORD_CWORD , /* 13 */
2663 CCTL_CCTL_CCTL_CCTL , /* 14 */
2666 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2667 * caller must ensure proper cast on it if c is *char_ptr!
2669 /* Values for syntax param */
2670 #define BASESYNTAX 0 /* not in quotes */
2671 #define DQSYNTAX 1 /* in double quotes */
2672 #define SQSYNTAX 2 /* in single quotes */
2673 #define ARISYNTAX 3 /* in arithmetic */
2674 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2676 #if USE_SIT_FUNCTION
2679 SIT(int c, int syntax)
2681 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2682 # if ENABLE_ASH_ALIAS
2683 static const uint8_t syntax_index_table[] ALIGN1 = {
2684 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2685 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2686 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2690 static const uint8_t syntax_index_table[] ALIGN1 = {
2691 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2692 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2693 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2702 # if ENABLE_ASH_ALIAS
2708 /* Cast is purely for paranoia here,
2709 * just in case someone passed signed char to us */
2710 if ((unsigned char)c >= CTL_FIRST
2711 && (unsigned char)c <= CTL_LAST
2715 s = strchrnul(spec_symbls, c);
2718 indx = syntax_index_table[s - spec_symbls];
2720 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2723 #else /* !USE_SIT_FUNCTION */
2725 static const uint8_t syntax_index_table[] = {
2726 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2727 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2728 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2737 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2738 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2739 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2760 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2761 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2762 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2763 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2764 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2765 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2766 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2767 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2768 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2769 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2770 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2771 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2772 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2773 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2774 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2775 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2776 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2777 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2778 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2779 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2780 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2781 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2782 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2783 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2784 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2785 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2786 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2787 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2788 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2789 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2790 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2791 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2792 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2793 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2794 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2795 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2796 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2797 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2800 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2802 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2803 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2814 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2815 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2816 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2817 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2819 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2820 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2821 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2822 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2823 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2824 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2825 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2848 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2849 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2850 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2851 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2852 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2853 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2854 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2855 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2857 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2858 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2859 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2860 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2861 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2862 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2863 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2864 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 162 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 163 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 164 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 165 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 166 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 167 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 168 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 169 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 170 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 171 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 172 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 173 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 174 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 175 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 176 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 177 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 178 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 179 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 180 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 181 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 182 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 183 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 184 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 185 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 186 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 187 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 188 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 189 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 190 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 191 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 192 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 193 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 194 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 195 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 196 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 197 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 198 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 199 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 200 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 201 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 202 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 203 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 204 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 205 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 206 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 207 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 208 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 209 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 210 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 211 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 212 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 213 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 214 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 215 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 216 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 217 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 218 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 219 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 220 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 221 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 222 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 223 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 224 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 225 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 226 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 227 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 228 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 229 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 231 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 232 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 233 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 234 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 235 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 236 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 237 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 238 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 239 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 241 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 242 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 243 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 244 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 245 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 246 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 247 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 248 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 249 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 250 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 251 */ CWORD_CWORD_CWORD_CWORD,
2979 /* 252 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 253 */ CWORD_CWORD_CWORD_CWORD,
2981 /* 254 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 255 */ CWORD_CWORD_CWORD_CWORD,
2983 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2984 # if ENABLE_ASH_ALIAS
2985 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
2989 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
2991 #endif /* !USE_SIT_FUNCTION */
2994 /* ============ Alias handling */
2996 #if ENABLE_ASH_ALIAS
2998 #define ALIASINUSE 1
3009 static struct alias **atab; // [ATABSIZE];
3010 #define INIT_G_alias() do { \
3011 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3015 static struct alias **
3016 __lookupalias(const char *name) {
3017 unsigned int hashval;
3024 ch = (unsigned char)*p;
3028 ch = (unsigned char)*++p;
3030 app = &atab[hashval % ATABSIZE];
3032 for (; *app; app = &(*app)->next) {
3033 if (strcmp(name, (*app)->name) == 0) {
3041 static struct alias *
3042 lookupalias(const char *name, int check)
3044 struct alias *ap = *__lookupalias(name);
3046 if (check && ap && (ap->flag & ALIASINUSE))
3051 static struct alias *
3052 freealias(struct alias *ap)
3056 if (ap->flag & ALIASINUSE) {
3057 ap->flag |= ALIASDEAD;
3069 setalias(const char *name, const char *val)
3071 struct alias *ap, **app;
3073 app = __lookupalias(name);
3077 if (!(ap->flag & ALIASINUSE)) {
3080 ap->val = ckstrdup(val);
3081 ap->flag &= ~ALIASDEAD;
3084 ap = ckzalloc(sizeof(struct alias));
3085 ap->name = ckstrdup(name);
3086 ap->val = ckstrdup(val);
3087 /*ap->flag = 0; - ckzalloc did it */
3088 /*ap->next = NULL;*/
3095 unalias(const char *name)
3099 app = __lookupalias(name);
3103 *app = freealias(*app);
3114 struct alias *ap, **app;
3118 for (i = 0; i < ATABSIZE; i++) {
3120 for (ap = *app; ap; ap = *app) {
3121 *app = freealias(*app);
3131 printalias(const struct alias *ap)
3133 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3137 * TODO - sort output
3139 static int FAST_FUNC
3140 aliascmd(int argc UNUSED_PARAM, char **argv)
3149 for (i = 0; i < ATABSIZE; i++) {
3150 for (ap = atab[i]; ap; ap = ap->next) {
3156 while ((n = *++argv) != NULL) {
3157 v = strchr(n+1, '=');
3158 if (v == NULL) { /* n+1: funny ksh stuff */
3159 ap = *__lookupalias(n);
3161 fprintf(stderr, "%s: %s not found\n", "alias", n);
3174 static int FAST_FUNC
3175 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3179 while ((i = nextopt("a")) != '\0') {
3185 for (i = 0; *argptr; argptr++) {
3186 if (unalias(*argptr)) {
3187 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3195 #endif /* ASH_ALIAS */
3198 /* ============ jobs.c */
3200 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3203 #define FORK_NOJOB 2
3205 /* mode flags for showjob(s) */
3206 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3207 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3208 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3211 * A job structure contains information about a job. A job is either a
3212 * single process or a set of processes contained in a pipeline. In the
3213 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3217 pid_t ps_pid; /* process id */
3218 int ps_status; /* last process status from wait() */
3219 char *ps_cmd; /* text of command being run */
3223 struct procstat ps0; /* status of process */
3224 struct procstat *ps; /* status or processes when more than one */
3226 int stopstatus; /* status of a stopped job */
3229 nprocs: 16, /* number of processes */
3231 #define JOBRUNNING 0 /* at least one proc running */
3232 #define JOBSTOPPED 1 /* all procs are stopped */
3233 #define JOBDONE 2 /* all procs are completed */
3235 sigint: 1, /* job was killed by SIGINT */
3236 jobctl: 1, /* job running under job control */
3238 waited: 1, /* true if this entry has been waited for */
3239 used: 1, /* true if this entry is in used */
3240 changed: 1; /* true if status has changed */
3241 struct job *prev_job; /* previous job */
3244 static struct job *makejob(/*union node *,*/ int);
3245 static int forkshell(struct job *, union node *, int);
3246 static int waitforjob(struct job *);
3249 enum { doing_jobctl = 0 };
3250 #define setjobctl(on) do {} while (0)
3252 static smallint doing_jobctl; //references:8
3253 static void setjobctl(int);
3260 ignoresig(int signo)
3262 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3263 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3264 /* No, need to do it */
3265 signal(signo, SIG_IGN);
3267 sigmode[signo - 1] = S_HARD_IGN;
3271 * Signal handler. Only one usage site - in setsignal()
3276 gotsig[signo - 1] = 1;
3278 if (signo == SIGINT && !trap[SIGINT]) {
3279 if (!suppress_int) {
3281 raise_interrupt(); /* does not return */
3285 pending_sig = signo;
3290 * Set the signal handler for the specified signal. The routine figures
3291 * out what it should be set to.
3294 setsignal(int signo)
3297 char cur_act, new_act;
3298 struct sigaction act;
3302 if (t != NULL) { /* trap for this sig is set */
3304 if (t[0] == '\0') /* trap is "": ignore this sig */
3308 if (rootshell && new_act == S_DFL) {
3311 if (iflag || minusc || sflag == 0)
3320 * "In all cases, bash ignores SIGQUIT. Non-builtin
3321 * commands run by bash have signal handlers
3322 * set to the values inherited by the shell
3323 * from its parent". */
3339 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3340 //whereas we have to restore it to what shell got on entry
3341 //from the parent. See comment above
3343 t = &sigmode[signo - 1];
3346 /* current setting is not yet known */
3347 if (sigaction(signo, NULL, &act)) {
3348 /* pretend it worked; maybe we should give a warning,
3349 * but other shells don't. We don't alter sigmode,
3350 * so we retry every time.
3351 * btw, in Linux it never fails. --vda */
3354 if (act.sa_handler == SIG_IGN) {
3355 cur_act = S_HARD_IGN;
3357 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3359 cur_act = S_IGN; /* don't hard ignore these */
3363 if (cur_act == S_HARD_IGN || cur_act == new_act)
3366 act.sa_handler = SIG_DFL;
3369 act.sa_handler = onsig;
3370 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3371 sigfillset(&act.sa_mask); /* ditto */
3374 act.sa_handler = SIG_IGN;
3377 sigaction_set(signo, &act);
3382 /* mode flags for set_curjob */
3383 #define CUR_DELETE 2
3384 #define CUR_RUNNING 1
3385 #define CUR_STOPPED 0
3387 /* mode flags for dowait */
3388 #define DOWAIT_NONBLOCK WNOHANG
3389 #define DOWAIT_BLOCK 0
3392 /* pgrp of shell on invocation */
3393 static int initialpgrp; //references:2
3394 static int ttyfd = -1; //5
3397 static struct job *jobtab; //5
3399 static unsigned njobs; //4
3401 static struct job *curjob; //lots
3402 /* number of presumed living untracked jobs */
3403 static int jobless; //4
3406 set_curjob(struct job *jp, unsigned mode)
3409 struct job **jpp, **curp;
3411 /* first remove from list */
3412 jpp = curp = &curjob;
3417 jpp = &jp1->prev_job;
3419 *jpp = jp1->prev_job;
3421 /* Then re-insert in correct position */
3429 /* job being deleted */
3432 /* newly created job or backgrounded job,
3433 put after all stopped jobs. */
3437 if (!jp1 || jp1->state != JOBSTOPPED)
3440 jpp = &jp1->prev_job;
3446 /* newly stopped job - becomes curjob */
3447 jp->prev_job = *jpp;
3455 jobno(const struct job *jp)
3457 return jp - jobtab + 1;
3462 * Convert a job name to a job structure.
3465 #define getjob(name, getctl) getjob(name)
3468 getjob(const char *name, int getctl)
3472 const char *err_msg = "%s: no such job";
3476 char *(*match)(const char *, const char *);
3491 if (c == '+' || c == '%') {
3493 err_msg = "No current job";
3499 err_msg = "No previous job";
3510 jp = jobtab + num - 1;
3525 if (match(jp->ps[0].ps_cmd, p)) {
3529 err_msg = "%s: ambiguous";
3539 err_msg = "job %s not created under job control";
3540 if (getctl && jp->jobctl == 0)
3545 ash_msg_and_raise_error(err_msg, name);
3549 * Mark a job structure as unused.
3552 freejob(struct job *jp)
3554 struct procstat *ps;
3558 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3559 if (ps->ps_cmd != nullstr)
3562 if (jp->ps != &jp->ps0)
3565 set_curjob(jp, CUR_DELETE);
3571 xtcsetpgrp(int fd, pid_t pgrp)
3573 if (tcsetpgrp(fd, pgrp))
3574 ash_msg_and_raise_error("can't set tty process group (%m)");
3578 * Turn job control on and off.
3580 * Note: This code assumes that the third arg to ioctl is a character
3581 * pointer, which is true on Berkeley systems but not System V. Since
3582 * System V doesn't have job control yet, this isn't a problem now.
3584 * Called with interrupts off.
3592 if (on == doing_jobctl || rootshell == 0)
3596 ofd = fd = open(_PATH_TTY, O_RDWR);
3598 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3599 * That sometimes helps to acquire controlling tty.
3600 * Obviously, a workaround for bugs when someone
3601 * failed to provide a controlling tty to bash! :) */
3607 fd = fcntl(fd, F_DUPFD, 10);
3612 /* fd is a tty at this point */
3613 close_on_exec_on(fd);
3614 do { /* while we are in the background */
3615 pgrp = tcgetpgrp(fd);
3618 ash_msg("can't access tty; job control turned off");
3622 if (pgrp == getpgrp())
3633 xtcsetpgrp(fd, pgrp);
3635 /* turning job control off */
3638 /* was xtcsetpgrp, but this can make exiting ash
3639 * loop forever if pty is already deleted */
3640 tcsetpgrp(fd, pgrp);
3654 static int FAST_FUNC
3655 killcmd(int argc, char **argv)
3658 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3660 if (argv[i][0] == '%') {
3661 struct job *jp = getjob(argv[i], 0);
3662 unsigned pid = jp->ps[0].ps_pid;
3663 /* Enough space for ' -NNN<nul>' */
3664 argv[i] = alloca(sizeof(int)*3 + 3);
3665 /* kill_main has matching code to expect
3666 * leading space. Needed to not confuse
3667 * negative pids with "kill -SIGNAL_NO" syntax */
3668 sprintf(argv[i], " -%u", pid);
3670 } while (argv[++i]);
3672 return kill_main(argc, argv);
3676 showpipe(struct job *jp /*, FILE *out*/)
3678 struct procstat *ps;
3679 struct procstat *psend;
3681 psend = jp->ps + jp->nprocs;
3682 for (ps = jp->ps + 1; ps < psend; ps++)
3683 printf(" | %s", ps->ps_cmd);
3684 outcslow('\n', stdout);
3685 flush_stdout_stderr();
3690 restartjob(struct job *jp, int mode)
3692 struct procstat *ps;
3698 if (jp->state == JOBDONE)
3700 jp->state = JOBRUNNING;
3701 pgid = jp->ps[0].ps_pid;
3702 if (mode == FORK_FG)
3703 xtcsetpgrp(ttyfd, pgid);
3704 killpg(pgid, SIGCONT);
3708 if (WIFSTOPPED(ps->ps_status)) {
3714 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3719 static int FAST_FUNC
3720 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3726 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3730 jp = getjob(*argv, 1);
3731 if (mode == FORK_BG) {
3732 set_curjob(jp, CUR_RUNNING);
3733 printf("[%d] ", jobno(jp));
3735 out1str(jp->ps[0].ps_cmd);
3736 showpipe(jp /*, stdout*/);
3737 retval = restartjob(jp, mode);
3738 } while (*argv && *++argv);
3744 sprint_status(char *s, int status, int sigonly)
3750 if (!WIFEXITED(status)) {
3752 if (WIFSTOPPED(status))
3753 st = WSTOPSIG(status);
3756 st = WTERMSIG(status);
3758 if (st == SIGINT || st == SIGPIPE)
3761 if (WIFSTOPPED(status))
3766 col = fmtstr(s, 32, strsignal(st));
3767 if (WCOREDUMP(status)) {
3768 col += fmtstr(s + col, 16, " (core dumped)");
3770 } else if (!sigonly) {
3771 st = WEXITSTATUS(status);
3773 col = fmtstr(s, 16, "Done(%d)", st);
3775 col = fmtstr(s, 16, "Done");
3782 dowait(int wait_flags, struct job *job)
3787 struct job *thisjob;
3790 TRACE(("dowait(0x%x) called\n", wait_flags));
3792 /* Do a wait system call. If job control is compiled in, we accept
3793 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3794 * NB: _not_ safe_waitpid, we need to detect EINTR */
3796 wait_flags |= WUNTRACED;
3797 pid = waitpid(-1, &status, wait_flags);
3798 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3799 pid, status, errno, strerror(errno)));
3805 for (jp = curjob; jp; jp = jp->prev_job) {
3806 struct procstat *ps;
3807 struct procstat *psend;
3808 if (jp->state == JOBDONE)
3812 psend = ps + jp->nprocs;
3814 if (ps->ps_pid == pid) {
3815 TRACE(("Job %d: changing status of proc %d "
3816 "from 0x%x to 0x%x\n",
3817 jobno(jp), pid, ps->ps_status, status));
3818 ps->ps_status = status;
3821 if (ps->ps_status == -1)
3824 if (state == JOBRUNNING)
3826 if (WIFSTOPPED(ps->ps_status)) {
3827 jp->stopstatus = ps->ps_status;
3831 } while (++ps < psend);
3836 if (!WIFSTOPPED(status))
3842 if (state != JOBRUNNING) {
3843 thisjob->changed = 1;
3845 if (thisjob->state != state) {
3846 TRACE(("Job %d: changing state from %d to %d\n",
3847 jobno(thisjob), thisjob->state, state));
3848 thisjob->state = state;
3850 if (state == JOBSTOPPED) {
3851 set_curjob(thisjob, CUR_STOPPED);
3860 if (thisjob && thisjob == job) {
3864 len = sprint_status(s, status, 1);
3875 blocking_wait_with_raise_on_sig(struct job *job)
3877 pid_t pid = dowait(DOWAIT_BLOCK, job);
3878 if (pid <= 0 && pending_sig)
3879 raise_exception(EXSIG);
3885 showjob(FILE *out, struct job *jp, int mode)
3887 struct procstat *ps;
3888 struct procstat *psend;
3895 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
3896 /* just output process (group) id of pipeline */
3897 fprintf(out, "%d\n", ps->ps_pid);
3901 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3906 else if (curjob && jp == curjob->prev_job)
3909 if (mode & SHOW_PIDS)
3910 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
3912 psend = ps + jp->nprocs;
3914 if (jp->state == JOBRUNNING) {
3915 strcpy(s + col, "Running");
3916 col += sizeof("Running") - 1;
3918 int status = psend[-1].ps_status;
3919 if (jp->state == JOBSTOPPED)
3920 status = jp->stopstatus;
3921 col += sprint_status(s + col, status, 0);
3923 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
3925 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3926 * or prints several "PID | <cmdN>" lines,
3927 * depending on SHOW_PIDS bit.
3928 * We do not print status of individual processes
3929 * between PID and <cmdN>. bash does it, but not very well:
3930 * first line shows overall job status, not process status,
3931 * making it impossible to know 1st process status.
3935 /* for each process */
3938 if (mode & SHOW_PIDS)
3939 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
3941 fprintf(out, "%s%*c%s%s",
3943 33 - col >= 0 ? 33 - col : 0, ' ',
3944 ps == jp->ps ? "" : "| ",
3947 } while (++ps != psend);
3948 outcslow('\n', out);
3952 if (jp->state == JOBDONE) {
3953 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3959 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3960 * statuses have changed since the last call to showjobs.
3963 showjobs(FILE *out, int mode)
3967 TRACE(("showjobs(0x%x) called\n", mode));
3969 /* Handle all finished jobs */
3970 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
3973 for (jp = curjob; jp; jp = jp->prev_job) {
3974 if (!(mode & SHOW_CHANGED) || jp->changed) {
3975 showjob(out, jp, mode);
3980 static int FAST_FUNC
3981 jobscmd(int argc UNUSED_PARAM, char **argv)
3986 while ((m = nextopt("lp")) != '\0') {
3990 mode |= SHOW_ONLY_PGID;
3996 showjob(stdout, getjob(*argv, 0), mode);
3999 showjobs(stdout, mode);
4006 /* Called only on finished or stopped jobs (no members are running) */
4008 getstatus(struct job *job)
4012 struct procstat *ps;
4014 /* Fetch last member's status */
4015 ps = job->ps + job->nprocs - 1;
4016 status = ps->ps_status;
4018 /* "set -o pipefail" mode: use last _nonzero_ status */
4019 while (status == 0 && --ps >= job->ps)
4020 status = ps->ps_status;
4023 retval = WEXITSTATUS(status);
4024 if (!WIFEXITED(status)) {
4026 retval = WSTOPSIG(status);
4027 if (!WIFSTOPPED(status))
4030 /* XXX: limits number of signals */
4031 retval = WTERMSIG(status);
4033 if (retval == SIGINT)
4039 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4040 jobno(job), job->nprocs, status, retval));
4044 static int FAST_FUNC
4045 waitcmd(int argc UNUSED_PARAM, char **argv)
4052 raise_exception(EXSIG);
4059 /* wait for all jobs */
4063 if (!jp) /* no running procs */
4065 if (jp->state == JOBRUNNING)
4071 * "When bash is waiting for an asynchronous command via
4072 * the wait builtin, the reception of a signal for which a trap
4073 * has been set will cause the wait builtin to return immediately
4074 * with an exit status greater than 128, immediately after which
4075 * the trap is executed."
4076 * Do we do it that way? */
4077 blocking_wait_with_raise_on_sig(NULL);
4083 if (**argv != '%') {
4084 pid_t pid = number(*argv);
4089 if (job->ps[job->nprocs - 1].ps_pid == pid)
4091 job = job->prev_job;
4094 job = getjob(*argv, 0);
4095 /* loop until process terminated or stopped */
4096 while (job->state == JOBRUNNING)
4097 blocking_wait_with_raise_on_sig(NULL);
4099 retval = getstatus(job);
4112 struct job *jp, *jq;
4114 len = njobs * sizeof(*jp);
4116 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4118 offset = (char *)jp - (char *)jq;
4120 /* Relocate pointers */
4123 jq = (struct job *)((char *)jq + l);
4127 #define joff(p) ((struct job *)((char *)(p) + l))
4128 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4129 if (joff(jp)->ps == &jq->ps0)
4130 jmove(joff(jp)->ps);
4131 if (joff(jp)->prev_job)
4132 jmove(joff(jp)->prev_job);
4142 jp = (struct job *)((char *)jp + len);
4146 } while (--jq >= jp);
4151 * Return a new job structure.
4152 * Called with interrupts off.
4155 makejob(/*union node *node,*/ int nprocs)
4160 for (i = njobs, jp = jobtab; ; jp++) {
4167 if (jp->state != JOBDONE || !jp->waited)
4176 memset(jp, 0, sizeof(*jp));
4178 /* jp->jobctl is a bitfield.
4179 * "jp->jobctl |= jobctl" likely to give awful code */
4183 jp->prev_job = curjob;
4188 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4190 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4197 * Return a string identifying a command (to be printed by the
4200 static char *cmdnextc;
4203 cmdputs(const char *s)
4205 static const char vstype[VSTYPE + 1][3] = {
4206 "", "}", "-", "+", "?", "=",
4207 "%", "%%", "#", "##"
4208 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4211 const char *p, *str;
4215 unsigned char subtype = 0;
4219 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4221 while ((c = *p++) != '\0') {
4229 if ((subtype & VSTYPE) == VSLENGTH)
4233 if (!(subtype & VSQUOTE) == !(quoted & 1))
4239 str = "\"}" + !(quoted & 1);
4246 case CTLBACKQ+CTLQUOTE:
4249 #if ENABLE_SH_MATH_SUPPORT
4264 if ((subtype & VSTYPE) != VSNORMAL)
4266 str = vstype[subtype & VSTYPE];
4267 if (subtype & VSNUL)
4276 /* These can only happen inside quotes */
4289 while ((c = *str++) != '\0') {
4292 } /* while *p++ not NUL */
4295 USTPUTC('"', nextc);
4301 /* cmdtxt() and cmdlist() call each other */
4302 static void cmdtxt(union node *n);
4305 cmdlist(union node *np, int sep)
4307 for (; np; np = np->narg.next) {
4311 if (sep && np->narg.next)
4317 cmdtxt(union node *n)
4320 struct nodelist *lp;
4331 lp = n->npipe.cmdlist;
4349 cmdtxt(n->nbinary.ch1);
4365 cmdtxt(n->nif.test);
4367 if (n->nif.elsepart) {
4368 cmdtxt(n->nif.ifpart);
4370 n = n->nif.elsepart;
4388 cmdtxt(n->nbinary.ch1);
4398 cmdputs(n->nfor.var);
4400 cmdlist(n->nfor.args, 1);
4405 cmdputs(n->narg.text);
4409 cmdlist(n->ncmd.args, 1);
4410 cmdlist(n->ncmd.redirect, 0);
4423 cmdputs(n->ncase.expr->narg.text);
4425 for (np = n->ncase.cases; np; np = np->nclist.next) {
4426 cmdtxt(np->nclist.pattern);
4428 cmdtxt(np->nclist.body);
4442 #if ENABLE_ASH_BASH_COMPAT
4457 cmdputs(utoa(n->nfile.fd));
4459 if (n->type == NTOFD || n->type == NFROMFD) {
4460 cmdputs(utoa(n->ndup.dupfd));
4469 commandtext(union node *n)
4473 STARTSTACKSTR(cmdnextc);
4475 name = stackblock();
4476 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4477 name, cmdnextc, cmdnextc));
4478 return ckstrdup(name);
4483 * Fork off a subshell. If we are doing job control, give the subshell its
4484 * own process group. Jp is a job structure that the job is to be added to.
4485 * N is the command that will be evaluated by the child. Both jp and n may
4486 * be NULL. The mode parameter can be one of the following:
4487 * FORK_FG - Fork off a foreground process.
4488 * FORK_BG - Fork off a background process.
4489 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4490 * process group even if job control is on.
4492 * When job control is turned off, background processes have their standard
4493 * input redirected to /dev/null (except for the second and later processes
4496 * Called with interrupts off.
4499 * Clear traps on a fork.
4506 for (tp = trap; tp < &trap[NSIG]; tp++) {
4507 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4509 if (trap_ptr == trap)
4511 /* else: it "belongs" to trap_ptr vector, don't free */
4513 if ((tp - trap) != 0)
4514 setsignal(tp - trap);
4520 /* Lives far away from here, needed for forkchild */
4521 static void closescript(void);
4523 /* Called after fork(), in child */
4524 static NOINLINE void
4525 forkchild(struct job *jp, union node *n, int mode)
4529 TRACE(("Child shell %d\n", getpid()));
4533 /* man bash: "Non-builtin commands run by bash have signal handlers
4534 * set to the values inherited by the shell from its parent".
4535 * Do we do it correctly? */
4539 if (mode == FORK_NOJOB /* is it `xxx` ? */
4540 && n && n->type == NCMD /* is it single cmd? */
4541 /* && n->ncmd.args->type == NARG - always true? */
4542 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4543 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4544 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4546 TRACE(("Trap hack\n"));
4547 /* Awful hack for `trap` or $(trap).
4549 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4550 * contains an example where "trap" is executed in a subshell:
4552 * save_traps=$(trap)
4554 * eval "$save_traps"
4556 * Standard does not say that "trap" in subshell shall print
4557 * parent shell's traps. It only says that its output
4558 * must have suitable form, but then, in the above example
4559 * (which is not supposed to be normative), it implies that.
4561 * bash (and probably other shell) does implement it
4562 * (traps are reset to defaults, but "trap" still shows them),
4563 * but as a result, "trap" logic is hopelessly messed up:
4566 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4567 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4568 * # true | trap <--- trap is in subshell - no output (ditto)
4569 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4570 * trap -- 'echo Ho' SIGWINCH
4571 * # echo `(trap)` <--- in subshell in subshell - output
4572 * trap -- 'echo Ho' SIGWINCH
4573 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4574 * trap -- 'echo Ho' SIGWINCH
4576 * The rules when to forget and when to not forget traps
4577 * get really complex and nonsensical.
4579 * Our solution: ONLY bare $(trap) or `trap` is special.
4581 /* Save trap handler strings for trap builtin to print */
4582 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4583 /* Fall through into clearing traps */
4587 /* do job control only in root shell */
4589 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4592 if (jp->nprocs == 0)
4595 pgrp = jp->ps[0].ps_pid;
4596 /* this can fail because we are doing it in the parent also */
4598 if (mode == FORK_FG)
4599 xtcsetpgrp(ttyfd, pgrp);
4604 if (mode == FORK_BG) {
4605 /* man bash: "When job control is not in effect,
4606 * asynchronous commands ignore SIGINT and SIGQUIT" */
4609 if (jp->nprocs == 0) {
4611 if (open(bb_dev_null, O_RDONLY) != 0)
4612 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4616 if (iflag) { /* why if iflag only? */
4621 * "In all cases, bash ignores SIGQUIT. Non-builtin
4622 * commands run by bash have signal handlers
4623 * set to the values inherited by the shell
4625 * Take care of the second rule: */
4629 if (n && n->type == NCMD
4630 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4632 TRACE(("Job hack\n"));
4633 /* "jobs": we do not want to clear job list for it,
4634 * instead we remove only _its_ own_ job from job list.
4635 * This makes "jobs .... | cat" more useful.
4641 for (jp = curjob; jp; jp = jp->prev_job)
4646 /* Called after fork(), in parent */
4648 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4651 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4653 TRACE(("In parent shell: child = %d\n", pid));
4655 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4661 if (mode != FORK_NOJOB && jp->jobctl) {
4664 if (jp->nprocs == 0)
4667 pgrp = jp->ps[0].ps_pid;
4668 /* This can fail because we are doing it in the child also */
4672 if (mode == FORK_BG) {
4673 backgndpid = pid; /* set $! */
4674 set_curjob(jp, CUR_RUNNING);
4677 struct procstat *ps = &jp->ps[jp->nprocs++];
4680 ps->ps_cmd = nullstr;
4682 if (doing_jobctl && n)
4683 ps->ps_cmd = commandtext(n);
4689 forkshell(struct job *jp, union node *n, int mode)
4693 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4696 TRACE(("Fork failed, errno=%d", errno));
4699 ash_msg_and_raise_error("can't fork");
4702 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4703 forkchild(jp, n, mode);
4705 forkparent(jp, n, mode, pid);
4711 * Wait for job to finish.
4713 * Under job control we have the problem that while a child process
4714 * is running interrupts generated by the user are sent to the child
4715 * but not to the shell. This means that an infinite loop started by
4716 * an interactive user may be hard to kill. With job control turned off,
4717 * an interactive user may place an interactive program inside a loop.
4718 * If the interactive program catches interrupts, the user doesn't want
4719 * these interrupts to also abort the loop. The approach we take here
4720 * is to have the shell ignore interrupt signals while waiting for a
4721 * foreground process to terminate, and then send itself an interrupt
4722 * signal if the child process was terminated by an interrupt signal.
4723 * Unfortunately, some programs want to do a bit of cleanup and then
4724 * exit on interrupt; unless these processes terminate themselves by
4725 * sending a signal to themselves (instead of calling exit) they will
4726 * confuse this approach.
4728 * Called with interrupts off.
4731 waitforjob(struct job *jp)
4735 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4738 while (jp->state == JOBRUNNING) {
4739 /* In non-interactive shells, we _can_ get
4740 * a keyboard signal here and be EINTRed,
4741 * but we just loop back, waiting for command to complete.
4744 * "If bash is waiting for a command to complete and receives
4745 * a signal for which a trap has been set, the trap
4746 * will not be executed until the command completes."
4748 * Reality is that even if trap is not set, bash
4749 * will not act on the signal until command completes.
4750 * Try this. sleep5intoff.c:
4751 * #include <signal.h>
4752 * #include <unistd.h>
4755 * sigemptyset(&set);
4756 * sigaddset(&set, SIGINT);
4757 * sigaddset(&set, SIGQUIT);
4758 * sigprocmask(SIG_BLOCK, &set, NULL);
4762 * $ bash -c './sleep5intoff; echo hi'
4763 * ^C^C^C^C <--- pressing ^C once a second
4765 * $ bash -c './sleep5intoff; echo hi'
4766 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4769 dowait(DOWAIT_BLOCK, jp);
4776 xtcsetpgrp(ttyfd, rootpid);
4778 * This is truly gross.
4779 * If we're doing job control, then we did a TIOCSPGRP which
4780 * caused us (the shell) to no longer be in the controlling
4781 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4782 * intuit from the subprocess exit status whether a SIGINT
4783 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4785 if (jp->sigint) /* TODO: do the same with all signals */
4786 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4788 if (jp->state == JOBDONE)
4795 * return 1 if there are stopped jobs, otherwise 0
4807 if (jp && jp->state == JOBSTOPPED) {
4808 out2str("You have stopped jobs.\n");
4817 /* ============ redir.c
4819 * Code for dealing with input/output redirection.
4822 #define EMPTY -2 /* marks an unused slot in redirtab */
4823 #define CLOSED -3 /* marks a slot of previously-closed fd */
4826 * Open a file in noclobber mode.
4827 * The code was copied from bash.
4830 noclobberopen(const char *fname)
4833 struct stat finfo, finfo2;
4836 * If the file exists and is a regular file, return an error
4839 r = stat(fname, &finfo);
4840 if (r == 0 && S_ISREG(finfo.st_mode)) {
4846 * If the file was not present (r != 0), make sure we open it
4847 * exclusively so that if it is created before we open it, our open
4848 * will fail. Make sure that we do not truncate an existing file.
4849 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4850 * file was not a regular file, we leave O_EXCL off.
4853 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4854 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4856 /* If the open failed, return the file descriptor right away. */
4861 * OK, the open succeeded, but the file may have been changed from a
4862 * non-regular file to a regular file between the stat and the open.
4863 * We are assuming that the O_EXCL open handles the case where FILENAME
4864 * did not exist and is symlinked to an existing file between the stat
4869 * If we can open it and fstat the file descriptor, and neither check
4870 * revealed that it was a regular file, and the file has not been
4871 * replaced, return the file descriptor.
4873 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4874 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4877 /* The file has been replaced. badness. */
4884 * Handle here documents. Normally we fork off a process to write the
4885 * data to a pipe. If the document is short, we can stuff the data in
4886 * the pipe without forking.
4888 /* openhere needs this forward reference */
4889 static void expandhere(union node *arg, int fd);
4891 openhere(union node *redir)
4897 ash_msg_and_raise_error("pipe call failed");
4898 if (redir->type == NHERE) {
4899 len = strlen(redir->nhere.doc->narg.text);
4900 if (len <= PIPE_BUF) {
4901 full_write(pip[1], redir->nhere.doc->narg.text, len);
4905 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4908 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4909 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4910 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4911 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4912 signal(SIGPIPE, SIG_DFL);
4913 if (redir->type == NHERE)
4914 full_write(pip[1], redir->nhere.doc->narg.text, len);
4916 expandhere(redir->nhere.doc, pip[1]);
4917 _exit(EXIT_SUCCESS);
4925 openredirect(union node *redir)
4930 switch (redir->nfile.type) {
4932 fname = redir->nfile.expfname;
4933 f = open(fname, O_RDONLY);
4938 fname = redir->nfile.expfname;
4939 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4944 #if ENABLE_ASH_BASH_COMPAT
4947 /* Take care of noclobber mode. */
4949 fname = redir->nfile.expfname;
4950 f = noclobberopen(fname);
4957 fname = redir->nfile.expfname;
4958 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4963 fname = redir->nfile.expfname;
4964 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4972 /* Fall through to eliminate warning. */
4973 /* Our single caller does this itself */
4980 f = openhere(redir);
4986 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4988 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
4992 * Copy a file descriptor to be >= to. Returns -1
4993 * if the source file descriptor is closed, EMPTY if there are no unused
4994 * file descriptors left.
4996 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
4997 * old code was doing close(to) prior to copyfd() to achieve the same */
4999 COPYFD_EXACT = (int)~(INT_MAX),
5000 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5003 copyfd(int from, int to)
5007 if (to & COPYFD_EXACT) {
5008 to &= ~COPYFD_EXACT;
5010 newfd = dup2(from, to);
5012 newfd = fcntl(from, F_DUPFD, to);
5015 if (errno == EMFILE)
5017 /* Happens when source fd is not open: try "echo >&99" */
5018 ash_msg_and_raise_error("%d: %m", from);
5023 /* Struct def and variable are moved down to the first usage site */
5028 struct redirtab *next;
5031 struct two_fd_t two_fd[];
5033 #define redirlist (G_var.redirlist)
5035 static int need_to_remember(struct redirtab *rp, int fd)
5039 if (!rp) /* remembering was not requested */
5042 for (i = 0; i < rp->pair_count; i++) {
5043 if (rp->two_fd[i].orig == fd) {
5044 /* already remembered */
5051 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5052 static int is_hidden_fd(struct redirtab *rp, int fd)
5055 struct parsefile *pf;
5068 fd |= COPYFD_RESTORE;
5069 for (i = 0; i < rp->pair_count; i++) {
5070 if (rp->two_fd[i].copy == fd) {
5078 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5079 * old file descriptors are stashed away so that the redirection can be
5080 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5081 * standard output, and the standard error if it becomes a duplicate of
5082 * stdout, is saved in memory.
5084 /* flags passed to redirect */
5085 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5086 #define REDIR_SAVEFD2 03 /* set preverrout */
5088 redirect(union node *redir, int flags)
5090 struct redirtab *sv;
5095 int copied_fd2 = -1;
5105 if (flags & REDIR_PUSH) {
5106 union node *tmp = redir;
5109 #if ENABLE_ASH_BASH_COMPAT
5110 if (tmp->nfile.type == NTO2)
5113 tmp = tmp->nfile.next;
5115 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5116 sv->next = redirlist;
5117 sv->pair_count = sv_pos;
5119 sv->nullredirs = g_nullredirs - 1;
5121 while (sv_pos > 0) {
5123 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5128 fd = redir->nfile.fd;
5129 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5130 int right_fd = redir->ndup.dupfd;
5131 /* redirect from/to same file descriptor? */
5134 /* echo >&10 and 10 is a fd opened to the sh script? */
5135 if (is_hidden_fd(sv, right_fd)) {
5136 errno = EBADF; /* as if it is closed */
5137 ash_msg_and_raise_error("%d: %m", right_fd);
5141 newfd = openredirect(redir); /* always >= 0 */
5143 /* Descriptor wasn't open before redirect.
5144 * Mark it for close in the future */
5145 if (need_to_remember(sv, fd)) {
5146 goto remember_to_close;
5151 #if ENABLE_ASH_BASH_COMPAT
5154 if (need_to_remember(sv, fd)) {
5155 /* Copy old descriptor */
5156 i = fcntl(fd, F_DUPFD, 10);
5157 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5158 * are closed in popredir() in the child, preventing them from leaking
5159 * into child. (popredir() also cleans up the mess in case of failures)
5164 /* Strange error (e.g. "too many files" EMFILE?) */
5168 ash_msg_and_raise_error("%d: %m", fd);
5171 /* EBADF: it is not open - good, remember to close it */
5174 } else { /* fd is open, save its copy */
5175 /* "exec fd>&-" should not close fds
5176 * which point to script file(s).
5177 * Force them to be restored afterwards */
5178 if (is_hidden_fd(sv, fd))
5179 i |= COPYFD_RESTORE;
5183 sv->two_fd[sv_pos].orig = fd;
5184 sv->two_fd[sv_pos].copy = i;
5188 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5189 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5190 /* Don't want to trigger debugging */
5194 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5196 } else if (fd != newfd) { /* move newfd to fd */
5197 copyfd(newfd, fd | COPYFD_EXACT);
5198 #if ENABLE_ASH_BASH_COMPAT
5199 if (!(redir->nfile.type == NTO2 && fd == 2))
5203 #if ENABLE_ASH_BASH_COMPAT
5204 if (redir->nfile.type == NTO2 && fd == 1) {
5205 /* We already redirected it to fd 1, now copy it to 2 */
5211 } while ((redir = redir->nfile.next) != NULL);
5214 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5215 preverrout_fd = copied_fd2;
5219 * Undo the effects of the last redirection.
5222 popredir(int drop, int restore)
5224 struct redirtab *rp;
5227 if (--g_nullredirs >= 0)
5231 for (i = 0; i < rp->pair_count; i++) {
5232 int fd = rp->two_fd[i].orig;
5233 int copy = rp->two_fd[i].copy;
5234 if (copy == CLOSED) {
5239 if (copy != EMPTY) {
5240 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5241 copy &= ~COPYFD_RESTORE;
5243 copyfd(copy, fd | COPYFD_EXACT);
5245 close(copy & ~COPYFD_RESTORE);
5248 redirlist = rp->next;
5249 g_nullredirs = rp->nullredirs;
5255 * Undo all redirections. Called on error or interrupt.
5259 * Discard all saved file descriptors.
5262 clearredir(int drop)
5268 popredir(drop, /*restore:*/ 0);
5273 redirectsafe(union node *redir, int flags)
5276 volatile int saveint;
5277 struct jmploc *volatile savehandler = exception_handler;
5278 struct jmploc jmploc;
5281 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5282 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5284 exception_handler = &jmploc;
5285 redirect(redir, flags);
5287 exception_handler = savehandler;
5288 if (err && exception_type != EXERROR)
5289 longjmp(exception_handler->loc, 1);
5290 RESTORE_INT(saveint);
5295 /* ============ Routines to expand arguments to commands
5297 * We have to deal with backquotes, shell variables, and file metacharacters.
5300 #if ENABLE_SH_MATH_SUPPORT
5302 ash_arith(const char *s)
5304 arith_eval_hooks_t math_hooks;
5308 math_hooks.lookupvar = lookupvar;
5309 math_hooks.setvar = setvar2;
5310 math_hooks.endofname = endofname;
5313 result = arith(s, &errcode, &math_hooks);
5316 ash_msg_and_raise_error("exponent less than 0");
5318 ash_msg_and_raise_error("divide by zero");
5320 ash_msg_and_raise_error("expression recursion loop detected");
5321 raise_error_syntax(s);
5332 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5333 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5334 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5335 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5336 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5337 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5338 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5339 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5340 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5344 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5345 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5346 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5347 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5348 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5351 * Structure specifying which parts of the string should be searched
5352 * for IFS characters.
5355 struct ifsregion *next; /* next region in list */
5356 int begoff; /* offset of start of region */
5357 int endoff; /* offset of end of region */
5358 int nulonly; /* search for nul bytes only */
5362 struct strlist *list;
5363 struct strlist **lastp;
5366 /* output of current string */
5367 static char *expdest;
5368 /* list of back quote expressions */
5369 static struct nodelist *argbackq;
5370 /* first struct in list of ifs regions */
5371 static struct ifsregion ifsfirst;
5372 /* last struct in list */
5373 static struct ifsregion *ifslastp;
5374 /* holds expanded arg list */
5375 static struct arglist exparg;
5385 expdest = makestrspace(32, expdest);
5386 len = fmtstr(expdest, 32, arith_t_fmt, num);
5387 STADJUST(len, expdest);
5392 esclen(const char *start, const char *p)
5396 while (p > start && (unsigned char)*--p == CTLESC) {
5403 * Remove any CTLESC characters from a string.
5406 rmescapes(char *str, int flag)
5408 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5412 unsigned protect_against_glob;
5415 p = strpbrk(str, qchars);
5421 if (flag & RMESCAPE_ALLOC) {
5422 size_t len = p - str;
5423 size_t fulllen = len + strlen(p) + 1;
5425 if (flag & RMESCAPE_GROW) {
5426 r = makestrspace(fulllen, expdest);
5427 } else if (flag & RMESCAPE_HEAP) {
5428 r = ckmalloc(fulllen);
5430 r = stalloc(fulllen);
5434 q = (char *)memcpy(q, str, len) + len;
5438 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5439 globbing = flag & RMESCAPE_GLOB;
5440 protect_against_glob = globbing;
5442 if ((unsigned char)*p == CTLQUOTEMARK) {
5443 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5444 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5445 // Note: both inquotes and protect_against_glob only affect whether
5446 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5447 inquotes = ~inquotes;
5449 protect_against_glob = globbing;
5453 /* naked back slash */
5454 protect_against_glob = 0;
5457 if ((unsigned char)*p == CTLESC) {
5459 if (protect_against_glob && inquotes && *p != '/') {
5463 protect_against_glob = globbing;
5468 if (flag & RMESCAPE_GROW) {
5470 STADJUST(q - r + 1, expdest);
5474 #define pmatch(a, b) !fnmatch((a), (b), 0)
5477 * Prepare a pattern for a expmeta (internal glob(3)) call.
5479 * Returns an stalloced string.
5482 preglob(const char *pattern, int quoted, int flag)
5484 flag |= RMESCAPE_GLOB;
5486 flag |= RMESCAPE_QUOTED;
5488 return rmescapes((char *)pattern, flag);
5492 * Put a string on the stack.
5495 memtodest(const char *p, size_t len, int syntax, int quotes)
5499 q = makestrspace(quotes ? len * 2 : len, q);
5502 unsigned char c = *p++;
5506 int n = SIT(c, syntax);
5507 if (n == CCTL || n == CBACK)
5517 strtodest(const char *p, int syntax, int quotes)
5519 memtodest(p, strlen(p), syntax, quotes);
5523 * Record the fact that we have to scan this region of the
5524 * string for IFS characters.
5527 recordregion(int start, int end, int nulonly)
5529 struct ifsregion *ifsp;
5531 if (ifslastp == NULL) {
5535 ifsp = ckzalloc(sizeof(*ifsp));
5536 /*ifsp->next = NULL; - ckzalloc did it */
5537 ifslastp->next = ifsp;
5541 ifslastp->begoff = start;
5542 ifslastp->endoff = end;
5543 ifslastp->nulonly = nulonly;
5547 removerecordregions(int endoff)
5549 if (ifslastp == NULL)
5552 if (ifsfirst.endoff > endoff) {
5553 while (ifsfirst.next != NULL) {
5554 struct ifsregion *ifsp;
5556 ifsp = ifsfirst.next->next;
5557 free(ifsfirst.next);
5558 ifsfirst.next = ifsp;
5561 if (ifsfirst.begoff > endoff)
5564 ifslastp = &ifsfirst;
5565 ifsfirst.endoff = endoff;
5570 ifslastp = &ifsfirst;
5571 while (ifslastp->next && ifslastp->next->begoff < endoff)
5572 ifslastp=ifslastp->next;
5573 while (ifslastp->next != NULL) {
5574 struct ifsregion *ifsp;
5576 ifsp = ifslastp->next->next;
5577 free(ifslastp->next);
5578 ifslastp->next = ifsp;
5581 if (ifslastp->endoff > endoff)
5582 ifslastp->endoff = endoff;
5586 exptilde(char *startp, char *p, int flags)
5592 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5597 while ((c = *++p) != '\0') {
5604 if (flags & EXP_VARTILDE)
5614 if (*name == '\0') {
5615 home = lookupvar(homestr);
5617 pw = getpwnam(name);
5622 if (!home || !*home)
5625 startloc = expdest - (char *)stackblock();
5626 strtodest(home, SQSYNTAX, quotes);
5627 recordregion(startloc, expdest - (char *)stackblock(), 0);
5635 * Execute a command inside back quotes. If it's a builtin command, we
5636 * want to save its output in a block obtained from malloc. Otherwise
5637 * we fork off a subprocess and get the output of the command via a pipe.
5638 * Should be called with interrupts off.
5640 struct backcmd { /* result of evalbackcmd */
5641 int fd; /* file descriptor to read from */
5642 int nleft; /* number of chars in buffer */
5643 char *buf; /* buffer */
5644 struct job *jp; /* job structure for command */
5647 /* These forward decls are needed to use "eval" code for backticks handling: */
5648 static uint8_t back_exitstatus; /* exit status of backquoted command */
5649 #define EV_EXIT 01 /* exit after evaluating tree */
5650 static void evaltree(union node *, int);
5652 static void FAST_FUNC
5653 evalbackcmd(union node *n, struct backcmd *result)
5664 saveherefd = herefd;
5672 ash_msg_and_raise_error("pipe call failed");
5673 jp = makejob(/*n,*/ 1);
5674 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5679 copyfd(pip[1], 1 | COPYFD_EXACT);
5683 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5687 result->fd = pip[0];
5690 herefd = saveherefd;
5692 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5693 result->fd, result->buf, result->nleft, result->jp));
5697 * Expand stuff in backwards quotes.
5700 expbackq(union node *cmd, int quoted, int quotes)
5708 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5709 struct stackmark smark;
5712 setstackmark(&smark);
5714 startloc = dest - (char *)stackblock();
5716 evalbackcmd(cmd, &in);
5717 popstackmark(&smark);
5724 memtodest(p, i, syntax, quotes);
5728 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5729 TRACE(("expbackq: read returns %d\n", i));
5738 back_exitstatus = waitforjob(in.jp);
5742 /* Eat all trailing newlines */
5744 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5749 recordregion(startloc, dest - (char *)stackblock(), 0);
5750 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5751 (dest - (char *)stackblock()) - startloc,
5752 (dest - (char *)stackblock()) - startloc,
5753 stackblock() + startloc));
5756 #if ENABLE_SH_MATH_SUPPORT
5758 * Expand arithmetic expression. Backup to start of expression,
5759 * evaluate, place result in (backed up) result, adjust string position.
5772 * This routine is slightly over-complicated for
5773 * efficiency. Next we scan backwards looking for the
5774 * start of arithmetic.
5776 start = stackblock();
5783 while ((unsigned char)*p != CTLARI) {
5787 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5792 esc = esclen(start, p);
5802 removerecordregions(begoff);
5809 rmescapes(p + 2, 0);
5811 len = cvtnum(ash_arith(p + 2));
5814 recordregion(begoff, begoff + len, 0);
5818 /* argstr needs it */
5819 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5822 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5823 * characters to allow for further processing. Otherwise treat
5824 * $@ like $* since no splitting will be performed.
5826 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5827 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5828 * for correct expansion of "B=$A" word.
5831 argstr(char *p, int flags, struct strlist *var_str_list)
5833 static const char spclchars[] ALIGN1 = {
5841 CTLBACKQ | CTLQUOTE,
5842 #if ENABLE_SH_MATH_SUPPORT
5847 const char *reject = spclchars;
5848 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5849 int breakall = flags & EXP_WORD;
5854 if (!(flags & EXP_VARTILDE)) {
5856 } else if (flags & EXP_VARTILDE2) {
5861 if (flags & EXP_TILDE) {
5864 flags &= ~EXP_TILDE;
5867 if (*q == CTLESC && (flags & EXP_QWORD))
5870 p = exptilde(p, q, flags);
5873 startloc = expdest - (char *)stackblock();
5877 length += strcspn(p + length, reject);
5881 #if ENABLE_SH_MATH_SUPPORT
5885 /* c == '=' || c == ':' || c == CTLENDARI */
5891 expdest = stack_nputstr(p, length, expdest);
5892 newloc = expdest - (char *)stackblock();
5893 if (breakall && !inquotes && newloc > startloc) {
5894 recordregion(startloc, newloc, 0);
5905 if (flags & EXP_VARTILDE2) {
5909 flags |= EXP_VARTILDE2;
5914 * sort of a hack - expand tildes in variable
5915 * assignments (after the first '=' and after ':'s).
5924 case CTLENDVAR: /* ??? */
5927 /* "$@" syntax adherence hack */
5929 && memcmp(p, dolatstr, 4) == 0
5930 && ( p[4] == CTLQUOTEMARK
5931 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5934 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
5937 inquotes = !inquotes;
5950 p = evalvar(p, flags, var_str_list);
5954 case CTLBACKQ|CTLQUOTE:
5955 expbackq(argbackq->n, c, quotes);
5956 argbackq = argbackq->next;
5958 #if ENABLE_SH_MATH_SUPPORT
5971 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
5974 // This commented out code was added by James Simmons <jsimmons@infradead.org>
5975 // as part of a larger change when he added support for ${var/a/b}.
5976 // However, it broke # and % operators:
5980 //echo ${var#ab} abcdcd abcdcd
5981 //echo ${var##ab} abcdcd abcdcd
5982 //echo ${var#a*b} abcdcd ababcdcd (!)
5983 //echo ${var##a*b} cdcd cdcd
5984 //echo ${var#?} babcdcd ababcdcd (!)
5985 //echo ${var##?} babcdcd babcdcd
5986 //echo ${var#*} ababcdcd babcdcd (!)
5988 //echo ${var%cd} ababcd ababcd
5989 //echo ${var%%cd} ababcd abab (!)
5990 //echo ${var%c*d} ababcd ababcd
5991 //echo ${var%%c*d} abab ababcdcd (!)
5992 //echo ${var%?} ababcdc ababcdc
5993 //echo ${var%%?} ababcdc ababcdcd (!)
5994 //echo ${var%*} ababcdcd ababcdcd
5997 // Commenting it back out helped. Remove it completely if it really
6000 char *loc, *loc2; //, *full;
6006 int match; // = strlen(str);
6007 const char *s = loc2;
6014 match = pmatch(str, s); // this line was deleted
6016 // // chop off end if its '*'
6017 // full = strrchr(str, '*');
6018 // if (full && full != str)
6021 // // If str starts with '*' replace with s.
6022 // if ((*str == '*') && strlen(s) >= match) {
6023 // full = xstrdup(s);
6024 // strncpy(full+strlen(s)-match+1, str+1, match-1);
6026 // full = xstrndup(str, match);
6027 // match = strncmp(s, full, strlen(full));
6031 if (match) // if (!match)
6033 if (quotes && (unsigned char)*loc == CTLESC)
6042 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6049 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6052 const char *s = loc2;
6057 match = pmatch(str, s);
6064 esc = esclen(startp, loc);
6075 static void varunset(const char *, const char *, const char *, int) NORETURN;
6077 varunset(const char *end, const char *var, const char *umsg, int varflags)
6083 msg = "parameter not set";
6085 if ((unsigned char)*end == CTLENDVAR) {
6086 if (varflags & VSNUL)
6092 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6095 #if ENABLE_ASH_BASH_COMPAT
6097 parse_sub_pattern(char *arg, int inquotes)
6099 char *idx, *repl = NULL;
6108 /* Only the first '/' seen is our separator */
6115 if (!inquotes && c == '\\' && arg[1] == '\\')
6116 arg++; /* skip both \\, not just first one */
6123 #endif /* ENABLE_ASH_BASH_COMPAT */
6126 subevalvar(char *p, char *str, int strloc, int subtype,
6127 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6129 struct nodelist *saveargbackq = argbackq;
6132 char *rmesc, *rmescend;
6133 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6134 IF_ASH_BASH_COMPAT(char null = '\0';)
6135 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6136 int saveherefd = herefd;
6137 int amount, workloc, resetloc;
6139 char *(*scan)(char*, char*, char*, char*, int, int);
6142 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6144 STPUTC('\0', expdest);
6145 herefd = saveherefd;
6146 argbackq = saveargbackq;
6147 startp = (char *)stackblock() + startloc;
6151 setvar(str, startp, 0);
6152 amount = startp - expdest;
6153 STADJUST(amount, expdest);
6156 #if ENABLE_ASH_BASH_COMPAT
6158 loc = str = stackblock() + strloc;
6159 /* Read POS in ${var:POS:LEN} */
6160 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6161 len = str - startp - 1;
6163 /* *loc != '\0', guaranteed by parser */
6167 /* Adjust the length by the number of escapes */
6168 for (ptr = startp; ptr < (str - 1); ptr++) {
6169 if ((unsigned char)*ptr == CTLESC) {
6177 if (*loc++ == ':') {
6181 /* Skip POS in ${var:POS:LEN} */
6183 while (*loc && *loc != ':') {
6185 * bash complains on: var=qwe; echo ${var:1a:123}
6187 ash_msg_and_raise_error(msg_illnum, str);
6191 if (*loc++ == ':') {
6195 if (pos >= orig_len) {
6199 if (len > (orig_len - pos))
6200 len = orig_len - pos;
6202 for (str = startp; pos; str++, pos--) {
6203 if (quotes && (unsigned char)*str == CTLESC)
6206 for (loc = startp; len; len--) {
6207 if (quotes && (unsigned char)*str == CTLESC)
6212 amount = loc - expdest;
6213 STADJUST(amount, expdest);
6218 varunset(p, str, startp, varflags);
6221 resetloc = expdest - (char *)stackblock();
6223 /* We'll comeback here if we grow the stack while handling
6224 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6225 * stack will need rebasing, and we'll need to remove our work
6228 IF_ASH_BASH_COMPAT(restart:)
6230 amount = expdest - ((char *)stackblock() + resetloc);
6231 STADJUST(-amount, expdest);
6232 startp = (char *)stackblock() + startloc;
6235 rmescend = (char *)stackblock() + strloc;
6237 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6238 if (rmesc != startp) {
6240 startp = (char *)stackblock() + startloc;
6244 str = (char *)stackblock() + strloc;
6245 preglob(str, varflags & VSQUOTE, 0);
6246 workloc = expdest - (char *)stackblock();
6248 #if ENABLE_ASH_BASH_COMPAT
6249 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6250 char *idx, *end, *restart_detect;
6253 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6258 /* If there's no pattern to match, return the expansion unmolested */
6266 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6268 /* No match, advance */
6269 restart_detect = stackblock();
6270 STPUTC(*idx, expdest);
6271 if (quotes && (unsigned char)*idx == CTLESC) {
6274 STPUTC(*idx, expdest);
6276 if (stackblock() != restart_detect)
6284 if (subtype == VSREPLACEALL) {
6286 if (quotes && (unsigned char)*idx == CTLESC)
6295 for (loc = repl; *loc; loc++) {
6296 restart_detect = stackblock();
6297 STPUTC(*loc, expdest);
6298 if (stackblock() != restart_detect)
6303 if (subtype == VSREPLACE) {
6305 restart_detect = stackblock();
6306 STPUTC(*idx, expdest);
6307 if (stackblock() != restart_detect)
6316 /* We've put the replaced text into a buffer at workloc, now
6317 * move it to the right place and adjust the stack.
6319 startp = stackblock() + startloc;
6320 STPUTC('\0', expdest);
6321 memmove(startp, stackblock() + workloc, len);
6322 startp[len++] = '\0';
6323 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6324 STADJUST(-amount, expdest);
6327 #endif /* ENABLE_ASH_BASH_COMPAT */
6329 subtype -= VSTRIMRIGHT;
6331 if (subtype < 0 || subtype > 7)
6334 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6335 zero = subtype >> 1;
6336 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6337 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6339 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6342 memmove(startp, loc, str - loc);
6343 loc = startp + (str - loc) - 1;
6346 amount = loc - expdest;
6347 STADJUST(amount, expdest);
6353 * Add the value of a specialized variable to the stack string.
6354 * name parameter (examples):
6355 * ash -c 'echo $1' name:'1='
6356 * ash -c 'echo $qwe' name:'qwe='
6357 * ash -c 'echo $$' name:'$='
6358 * ash -c 'echo ${$}' name:'$='
6359 * ash -c 'echo ${$##q}' name:'$=q'
6360 * ash -c 'echo ${#$}' name:'$='
6361 * note: examples with bad shell syntax:
6362 * ash -c 'echo ${#$1}' name:'$=1'
6363 * ash -c 'echo ${#1#}' name:'1=#'
6365 static NOINLINE ssize_t
6366 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6373 int subtype = varflags & VSTYPE;
6374 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6375 int quoted = varflags & VSQUOTE;
6376 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6386 num = shellparam.nparam;
6394 goto check_1char_name;
6396 expdest = makestrspace(NOPTS, expdest);
6397 for (i = NOPTS - 1; i >= 0; i--) {
6399 USTPUTC(optletters(i), expdest);
6405 /* handles cases similar to ${#$1} */
6406 if (name[2] != '\0')
6407 raise_error_syntax("bad substitution");
6414 if (quoted && (flags & EXP_FULL)) {
6415 /* note: this is not meant as PEOF value */
6416 sep = 1 << CHAR_BIT;
6421 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6422 i = SIT(sep, syntax);
6423 if (quotes && (i == CCTL || i == CBACK))
6429 while ((p = *ap++) != NULL) {
6432 partlen = strlen(p);
6435 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6436 memtodest(p, partlen, syntax, quotes);
6442 if (subtype == VSPLUS || subtype == VSLENGTH) {
6448 /* note: may put NUL despite sep != 0
6449 * (see sep = 1 << CHAR_BIT above) */
6455 } /* case '@' and '*' */
6466 num = atoi(name); /* number(name) fails on ${N#str} etc */
6467 if (num < 0 || num > shellparam.nparam)
6469 p = num ? shellparam.p[num - 1] : arg0;
6472 /* NB: name has form "VAR=..." */
6474 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6475 * which should be considered before we check variables. */
6477 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6481 str = var_str_list->text;
6482 eq = strchr(str, '=');
6483 if (!eq) /* stop at first non-assignment */
6486 if (name_len == (unsigned)(eq - str)
6487 && strncmp(str, name, name_len) == 0
6490 /* goto value; - WRONG! */
6491 /* think "A=1 A=2 B=$A" */
6493 var_str_list = var_str_list->next;
6494 } while (var_str_list);
6498 p = lookupvar(name);
6504 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6505 memtodest(p, len, syntax, quotes);
6509 if (subtype == VSPLUS || subtype == VSLENGTH)
6510 STADJUST(-len, expdest);
6515 * Expand a variable, and return a pointer to the next character in the
6519 evalvar(char *p, int flags, struct strlist *var_str_list)
6530 varflags = (unsigned char) *p++;
6531 subtype = varflags & VSTYPE;
6532 quoted = varflags & VSQUOTE;
6534 easy = (!quoted || (*var == '@' && shellparam.nparam));
6535 startloc = expdest - (char *)stackblock();
6536 p = strchr(p, '=') + 1;
6539 varlen = varvalue(var, varflags, flags, var_str_list);
6540 if (varflags & VSNUL)
6543 if (subtype == VSPLUS) {
6544 varlen = -1 - varlen;
6548 if (subtype == VSMINUS) {
6552 p, flags | EXP_TILDE |
6553 (quoted ? EXP_QWORD : EXP_WORD),
6563 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6565 if (subevalvar(p, var, /* strloc: */ 0,
6566 subtype, startloc, varflags,
6572 * Remove any recorded regions beyond
6575 removerecordregions(startloc);
6585 if (varlen < 0 && uflag)
6586 varunset(p, var, 0, 0);
6588 if (subtype == VSLENGTH) {
6589 cvtnum(varlen > 0 ? varlen : 0);
6593 if (subtype == VSNORMAL) {
6604 case VSTRIMRIGHTMAX:
6605 #if ENABLE_ASH_BASH_COMPAT
6618 * Terminate the string and start recording the pattern
6621 STPUTC('\0', expdest);
6622 patloc = expdest - (char *)stackblock();
6623 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6625 //TODO: | EXP_REDIR too? All other such places do it too
6626 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6629 int amount = expdest - (
6630 (char *)stackblock() + patloc - 1
6632 STADJUST(-amount, expdest);
6634 /* Remove any recorded regions beyond start of variable */
6635 removerecordregions(startloc);
6637 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6641 if (subtype != VSNORMAL) { /* skip to end of alternative */
6644 unsigned char c = *p++;
6647 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6649 argbackq = argbackq->next;
6650 } else if (c == CTLVAR) {
6651 if ((*p++ & VSTYPE) != VSNORMAL)
6653 } else if (c == CTLENDVAR) {
6663 * Break the argument string into pieces based upon IFS and add the
6664 * strings to the argument list. The regions of the string to be
6665 * searched for IFS characters have been stored by recordregion.
6668 ifsbreakup(char *string, struct arglist *arglist)
6670 struct ifsregion *ifsp;
6675 const char *ifs, *realifs;
6680 if (ifslastp != NULL) {
6683 realifs = ifsset() ? ifsval() : defifs;
6686 p = string + ifsp->begoff;
6687 nulonly = ifsp->nulonly;
6688 ifs = nulonly ? nullstr : realifs;
6690 while (p < string + ifsp->endoff) {
6692 if ((unsigned char)*p == CTLESC)
6694 if (!strchr(ifs, *p)) {
6699 ifsspc = (strchr(defifs, *p) != NULL);
6700 /* Ignore IFS whitespace at start */
6701 if (q == start && ifsspc) {
6707 sp = stzalloc(sizeof(*sp));
6709 *arglist->lastp = sp;
6710 arglist->lastp = &sp->next;
6714 if (p >= string + ifsp->endoff) {
6718 if ((unsigned char)*p == CTLESC)
6720 if (strchr(ifs, *p) == NULL) {
6724 if (strchr(defifs, *p) == NULL) {
6739 } while (ifsp != NULL);
6748 sp = stzalloc(sizeof(*sp));
6750 *arglist->lastp = sp;
6751 arglist->lastp = &sp->next;
6757 struct ifsregion *p;
6762 struct ifsregion *ifsp;
6768 ifsfirst.next = NULL;
6773 * Add a file name to the list.
6776 addfname(const char *name)
6780 sp = stzalloc(sizeof(*sp));
6781 sp->text = ststrdup(name);
6783 exparg.lastp = &sp->next;
6786 static char *expdir;
6789 * Do metacharacter (i.e. *, ?, [...]) expansion.
6792 expmeta(char *enddir, char *name)
6807 for (p = name; *p; p++) {
6808 if (*p == '*' || *p == '?')
6810 else if (*p == '[') {
6817 if (*q == '/' || *q == '\0')
6824 } else if (*p == '\\')
6826 else if (*p == '/') {
6833 if (metaflag == 0) { /* we've reached the end of the file name */
6834 if (enddir != expdir)
6842 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6853 } while (p < start);
6855 if (enddir == expdir) {
6857 } else if (enddir == expdir + 1 && *expdir == '/') {
6866 if (enddir != expdir)
6868 if (*endname == 0) {
6880 while (!pending_int && (dp = readdir(dirp)) != NULL) {
6881 if (dp->d_name[0] == '.' && !matchdot)
6883 if (pmatch(start, dp->d_name)) {
6885 strcpy(enddir, dp->d_name);
6888 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6891 expmeta(p, endname);
6900 static struct strlist *
6901 msort(struct strlist *list, int len)
6903 struct strlist *p, *q = NULL;
6904 struct strlist **lpp;
6912 for (n = half; --n >= 0;) {
6916 q->next = NULL; /* terminate first half of list */
6917 q = msort(list, half); /* sort first half of list */
6918 p = msort(p, len - half); /* sort second half */
6921 #if ENABLE_LOCALE_SUPPORT
6922 if (strcoll(p->text, q->text) < 0)
6924 if (strcmp(p->text, q->text) < 0)
6948 * Sort the results of file name expansion. It calculates the number of
6949 * strings to sort and then calls msort (short for merge sort) to do the
6952 static struct strlist *
6953 expsort(struct strlist *str)
6959 for (sp = str; sp; sp = sp->next)
6961 return msort(str, len);
6965 expandmeta(struct strlist *str /*, int flag*/)
6967 static const char metachars[] ALIGN1 = {
6970 /* TODO - EXP_REDIR */
6973 struct strlist **savelastp;
6979 if (!strpbrk(str->text, metachars))
6981 savelastp = exparg.lastp;
6984 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6986 int i = strlen(str->text);
6987 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6995 if (exparg.lastp == savelastp) {
7000 *exparg.lastp = str;
7001 rmescapes(str->text, 0);
7002 exparg.lastp = &str->next;
7004 *exparg.lastp = NULL;
7005 *savelastp = sp = expsort(*savelastp);
7006 while (sp->next != NULL)
7008 exparg.lastp = &sp->next;
7015 * Perform variable substitution and command substitution on an argument,
7016 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7017 * perform splitting and file name expansion. When arglist is NULL, perform
7018 * here document expansion.
7021 expandarg(union node *arg, struct arglist *arglist, int flag)
7026 argbackq = arg->narg.backquote;
7027 STARTSTACKSTR(expdest);
7028 ifsfirst.next = NULL;
7030 argstr(arg->narg.text, flag,
7031 /* var_str_list: */ arglist ? arglist->list : NULL);
7032 p = _STPUTC('\0', expdest);
7034 if (arglist == NULL) {
7035 return; /* here document expanded */
7037 p = grabstackstr(p);
7038 exparg.lastp = &exparg.list;
7042 if (flag & EXP_FULL) {
7043 ifsbreakup(p, &exparg);
7044 *exparg.lastp = NULL;
7045 exparg.lastp = &exparg.list;
7046 expandmeta(exparg.list /*, flag*/);
7048 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7050 sp = stzalloc(sizeof(*sp));
7053 exparg.lastp = &sp->next;
7057 *exparg.lastp = NULL;
7059 *arglist->lastp = exparg.list;
7060 arglist->lastp = exparg.lastp;
7065 * Expand shell variables and backquotes inside a here document.
7068 expandhere(union node *arg, int fd)
7071 expandarg(arg, (struct arglist *)NULL, 0);
7072 full_write(fd, stackblock(), expdest - (char *)stackblock());
7076 * Returns true if the pattern matches the string.
7079 patmatch(char *pattern, const char *string)
7081 return pmatch(preglob(pattern, 0, 0), string);
7085 * See if a pattern matches in a case statement.
7088 casematch(union node *pattern, char *val)
7090 struct stackmark smark;
7093 setstackmark(&smark);
7094 argbackq = pattern->narg.backquote;
7095 STARTSTACKSTR(expdest);
7097 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7098 /* var_str_list: */ NULL);
7099 STACKSTRNUL(expdest);
7100 result = patmatch(stackblock(), val);
7101 popstackmark(&smark);
7106 /* ============ find_command */
7110 int (*builtin)(int, char **) FAST_FUNC;
7111 /* unsigned flags; */
7113 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7114 /* "regular" builtins always take precedence over commands,
7115 * regardless of PATH=....%builtin... position */
7116 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7117 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7120 smallint cmdtype; /* CMDxxx */
7123 /* index >= 0 for commands without path (slashes) */
7124 /* (TODO: what exactly does the value mean? PATH position?) */
7125 /* index == -1 for commands with slashes */
7126 /* index == (-2 - applet_no) for NOFORK applets */
7127 const struct builtincmd *cmd;
7128 struct funcnode *func;
7131 /* values of cmdtype */
7132 #define CMDUNKNOWN -1 /* no entry in table for command */
7133 #define CMDNORMAL 0 /* command is an executable program */
7134 #define CMDFUNCTION 1 /* command is a shell function */
7135 #define CMDBUILTIN 2 /* command is a shell builtin */
7137 /* action to find_command() */
7138 #define DO_ERR 0x01 /* prints errors */
7139 #define DO_ABS 0x02 /* checks absolute paths */
7140 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7141 #define DO_ALTPATH 0x08 /* using alternate path */
7142 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7144 static void find_command(char *, struct cmdentry *, int, const char *);
7147 /* ============ Hashing commands */
7150 * When commands are first encountered, they are entered in a hash table.
7151 * This ensures that a full path search will not have to be done for them
7152 * on each invocation.
7154 * We should investigate converting to a linear search, even though that
7155 * would make the command name "hash" a misnomer.
7159 struct tblentry *next; /* next entry in hash chain */
7160 union param param; /* definition of builtin function */
7161 smallint cmdtype; /* CMDxxx */
7162 char rehash; /* if set, cd done since entry created */
7163 char cmdname[1]; /* name of command */
7166 static struct tblentry **cmdtable;
7167 #define INIT_G_cmdtable() do { \
7168 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7171 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7175 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7179 #if ENABLE_FEATURE_SH_STANDALONE
7180 if (applet_no >= 0) {
7181 if (APPLET_IS_NOEXEC(applet_no)) {
7184 run_applet_no_and_exit(applet_no, argv);
7186 /* re-exec ourselves with the new arguments */
7187 execve(bb_busybox_exec_path, argv, envp);
7188 /* If they called chroot or otherwise made the binary no longer
7189 * executable, fall through */
7196 execve(cmd, argv, envp);
7197 } while (errno == EINTR);
7199 execve(cmd, argv, envp);
7205 if (errno == ENOEXEC) {
7209 for (ap = argv; *ap; ap++)
7211 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7213 ap[0] = cmd = (char *)DEFAULT_SHELL;
7216 while ((*ap++ = *argv++) != NULL)
7225 * Exec a program. Never returns. If you change this routine, you may
7226 * have to change the find_command routine as well.
7228 static void shellexec(char **, const char *, int) NORETURN;
7230 shellexec(char **argv, const char *path, int idx)
7236 #if ENABLE_FEATURE_SH_STANDALONE
7240 clearredir(/*drop:*/ 1);
7241 envp = listvars(VEXPORT, VUNSET, 0);
7242 if (strchr(argv[0], '/') != NULL
7243 #if ENABLE_FEATURE_SH_STANDALONE
7244 || (applet_no = find_applet_by_name(argv[0])) >= 0
7247 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7251 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7252 if (--idx < 0 && pathopt == NULL) {
7253 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7254 if (errno != ENOENT && errno != ENOTDIR)
7261 /* Map to POSIX errors */
7273 exitstatus = exerrno;
7274 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7275 argv[0], e, suppress_int));
7276 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7281 printentry(struct tblentry *cmdp)
7287 idx = cmdp->param.index;
7290 name = path_advance(&path, cmdp->cmdname);
7292 } while (--idx >= 0);
7293 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7297 * Clear out command entries. The argument specifies the first entry in
7298 * PATH which has changed.
7301 clearcmdentry(int firstchange)
7303 struct tblentry **tblp;
7304 struct tblentry **pp;
7305 struct tblentry *cmdp;
7308 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7310 while ((cmdp = *pp) != NULL) {
7311 if ((cmdp->cmdtype == CMDNORMAL &&
7312 cmdp->param.index >= firstchange)
7313 || (cmdp->cmdtype == CMDBUILTIN &&
7314 builtinloc >= firstchange)
7327 * Locate a command in the command hash table. If "add" is nonzero,
7328 * add the command to the table if it is not already present. The
7329 * variable "lastcmdentry" is set to point to the address of the link
7330 * pointing to the entry, so that delete_cmd_entry can delete the
7333 * Interrupts must be off if called with add != 0.
7335 static struct tblentry **lastcmdentry;
7337 static struct tblentry *
7338 cmdlookup(const char *name, int add)
7340 unsigned int hashval;
7342 struct tblentry *cmdp;
7343 struct tblentry **pp;
7346 hashval = (unsigned char)*p << 4;
7348 hashval += (unsigned char)*p++;
7350 pp = &cmdtable[hashval % CMDTABLESIZE];
7351 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7352 if (strcmp(cmdp->cmdname, name) == 0)
7356 if (add && cmdp == NULL) {
7357 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7359 /* + 1 - already done because
7360 * tblentry::cmdname is char[1] */);
7361 /*cmdp->next = NULL; - ckzalloc did it */
7362 cmdp->cmdtype = CMDUNKNOWN;
7363 strcpy(cmdp->cmdname, name);
7370 * Delete the command entry returned on the last lookup.
7373 delete_cmd_entry(void)
7375 struct tblentry *cmdp;
7378 cmdp = *lastcmdentry;
7379 *lastcmdentry = cmdp->next;
7380 if (cmdp->cmdtype == CMDFUNCTION)
7381 freefunc(cmdp->param.func);
7387 * Add a new command entry, replacing any existing command entry for
7388 * the same name - except special builtins.
7391 addcmdentry(char *name, struct cmdentry *entry)
7393 struct tblentry *cmdp;
7395 cmdp = cmdlookup(name, 1);
7396 if (cmdp->cmdtype == CMDFUNCTION) {
7397 freefunc(cmdp->param.func);
7399 cmdp->cmdtype = entry->cmdtype;
7400 cmdp->param = entry->u;
7404 static int FAST_FUNC
7405 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7407 struct tblentry **pp;
7408 struct tblentry *cmdp;
7410 struct cmdentry entry;
7413 if (nextopt("r") != '\0') {
7418 if (*argptr == NULL) {
7419 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7420 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7421 if (cmdp->cmdtype == CMDNORMAL)
7429 while ((name = *argptr) != NULL) {
7430 cmdp = cmdlookup(name, 0);
7432 && (cmdp->cmdtype == CMDNORMAL
7433 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7437 find_command(name, &entry, DO_ERR, pathval());
7438 if (entry.cmdtype == CMDUNKNOWN)
7446 * Called when a cd is done. Marks all commands so the next time they
7447 * are executed they will be rehashed.
7452 struct tblentry **pp;
7453 struct tblentry *cmdp;
7455 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7456 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7457 if (cmdp->cmdtype == CMDNORMAL
7458 || (cmdp->cmdtype == CMDBUILTIN
7459 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7469 * Fix command hash table when PATH changed.
7470 * Called before PATH is changed. The argument is the new value of PATH;
7471 * pathval() still returns the old value at this point.
7472 * Called with interrupts off.
7474 static void FAST_FUNC
7475 changepath(const char *new)
7483 firstchange = 9999; /* assume no change */
7489 if ((*old == '\0' && *new == ':')
7490 || (*old == ':' && *new == '\0'))
7492 old = new; /* ignore subsequent differences */
7496 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7502 if (builtinloc < 0 && idx_bltin >= 0)
7503 builtinloc = idx_bltin; /* zap builtins */
7504 if (builtinloc >= 0 && idx_bltin < 0)
7506 clearcmdentry(firstchange);
7507 builtinloc = idx_bltin;
7522 #define TENDBQUOTE 12
7539 typedef smallint token_id_t;
7541 /* first char is indicating which tokens mark the end of a list */
7542 static const char *const tokname_array[] = {
7556 #define KWDOFFSET 13
7557 /* the following are keywords */
7579 static char buf[16];
7582 //if (tok < TSEMI) return tokname_array[tok] + 1;
7583 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7588 sprintf(buf + (tok >= TSEMI), "%s%c",
7589 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7593 /* Wrapper around strcmp for qsort/bsearch/... */
7595 pstrcmp(const void *a, const void *b)
7597 return strcmp((char*) a, (*(char**) b) + 1);
7600 static const char *const *
7601 findkwd(const char *s)
7603 return bsearch(s, tokname_array + KWDOFFSET,
7604 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7605 sizeof(tokname_array[0]), pstrcmp);
7609 * Locate and print what a word is...
7612 describe_command(char *command, int describe_command_verbose)
7614 struct cmdentry entry;
7615 struct tblentry *cmdp;
7616 #if ENABLE_ASH_ALIAS
7617 const struct alias *ap;
7619 const char *path = pathval();
7621 if (describe_command_verbose) {
7625 /* First look at the keywords */
7626 if (findkwd(command)) {
7627 out1str(describe_command_verbose ? " is a shell keyword" : command);
7631 #if ENABLE_ASH_ALIAS
7632 /* Then look at the aliases */
7633 ap = lookupalias(command, 0);
7635 if (!describe_command_verbose) {
7640 out1fmt(" is an alias for %s", ap->val);
7644 /* Then check if it is a tracked alias */
7645 cmdp = cmdlookup(command, 0);
7647 entry.cmdtype = cmdp->cmdtype;
7648 entry.u = cmdp->param;
7650 /* Finally use brute force */
7651 find_command(command, &entry, DO_ABS, path);
7654 switch (entry.cmdtype) {
7656 int j = entry.u.index;
7662 p = path_advance(&path, command);
7666 if (describe_command_verbose) {
7668 (cmdp ? " a tracked alias for" : nullstr), p
7677 if (describe_command_verbose) {
7678 out1str(" is a shell function");
7685 if (describe_command_verbose) {
7686 out1fmt(" is a %sshell builtin",
7687 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7688 "special " : nullstr
7696 if (describe_command_verbose) {
7697 out1str(": not found\n");
7706 static int FAST_FUNC
7707 typecmd(int argc UNUSED_PARAM, char **argv)
7713 /* type -p ... ? (we don't bother checking for 'p') */
7714 if (argv[1] && argv[1][0] == '-') {
7719 err |= describe_command(argv[i++], verbose);
7724 #if ENABLE_ASH_CMDCMD
7725 static int FAST_FUNC
7726 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7734 while ((c = nextopt("pvV")) != '\0')
7736 verify |= VERIFY_VERBOSE;
7738 verify |= VERIFY_BRIEF;
7743 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7744 if (verify && (*argptr != NULL)) {
7745 return describe_command(*argptr, verify - VERIFY_BRIEF);
7753 /* ============ eval.c */
7755 static int funcblocksize; /* size of structures in function */
7756 static int funcstringsize; /* size of strings in node */
7757 static void *funcblock; /* block to allocate function from */
7758 static char *funcstring; /* block to allocate strings from */
7760 /* flags in argument to evaltree */
7761 #define EV_EXIT 01 /* exit after evaluating tree */
7762 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7763 #define EV_BACKCMD 04 /* command executing within back quotes */
7765 static const uint8_t nodesize[N_NUMBER] = {
7766 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7767 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7768 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7769 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7770 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7771 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7772 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7773 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7774 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7775 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7776 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7777 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7778 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7779 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7780 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7781 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7782 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7783 #if ENABLE_ASH_BASH_COMPAT
7784 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7786 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7787 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7788 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7789 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7790 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7791 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7792 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7793 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7794 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7797 static void calcsize(union node *n);
7800 sizenodelist(struct nodelist *lp)
7803 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7810 calcsize(union node *n)
7814 funcblocksize += nodesize[n->type];
7817 calcsize(n->ncmd.redirect);
7818 calcsize(n->ncmd.args);
7819 calcsize(n->ncmd.assign);
7822 sizenodelist(n->npipe.cmdlist);
7827 calcsize(n->nredir.redirect);
7828 calcsize(n->nredir.n);
7835 calcsize(n->nbinary.ch2);
7836 calcsize(n->nbinary.ch1);
7839 calcsize(n->nif.elsepart);
7840 calcsize(n->nif.ifpart);
7841 calcsize(n->nif.test);
7844 funcstringsize += strlen(n->nfor.var) + 1;
7845 calcsize(n->nfor.body);
7846 calcsize(n->nfor.args);
7849 calcsize(n->ncase.cases);
7850 calcsize(n->ncase.expr);
7853 calcsize(n->nclist.body);
7854 calcsize(n->nclist.pattern);
7855 calcsize(n->nclist.next);
7859 sizenodelist(n->narg.backquote);
7860 funcstringsize += strlen(n->narg.text) + 1;
7861 calcsize(n->narg.next);
7864 #if ENABLE_ASH_BASH_COMPAT
7871 calcsize(n->nfile.fname);
7872 calcsize(n->nfile.next);
7876 calcsize(n->ndup.vname);
7877 calcsize(n->ndup.next);
7881 calcsize(n->nhere.doc);
7882 calcsize(n->nhere.next);
7885 calcsize(n->nnot.com);
7891 nodeckstrdup(char *s)
7893 char *rtn = funcstring;
7895 strcpy(funcstring, s);
7896 funcstring += strlen(s) + 1;
7900 static union node *copynode(union node *);
7902 static struct nodelist *
7903 copynodelist(struct nodelist *lp)
7905 struct nodelist *start;
7906 struct nodelist **lpp;
7911 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7912 (*lpp)->n = copynode(lp->n);
7914 lpp = &(*lpp)->next;
7921 copynode(union node *n)
7928 funcblock = (char *) funcblock + nodesize[n->type];
7932 new->ncmd.redirect = copynode(n->ncmd.redirect);
7933 new->ncmd.args = copynode(n->ncmd.args);
7934 new->ncmd.assign = copynode(n->ncmd.assign);
7937 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7938 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
7943 new->nredir.redirect = copynode(n->nredir.redirect);
7944 new->nredir.n = copynode(n->nredir.n);
7951 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7952 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7955 new->nif.elsepart = copynode(n->nif.elsepart);
7956 new->nif.ifpart = copynode(n->nif.ifpart);
7957 new->nif.test = copynode(n->nif.test);
7960 new->nfor.var = nodeckstrdup(n->nfor.var);
7961 new->nfor.body = copynode(n->nfor.body);
7962 new->nfor.args = copynode(n->nfor.args);
7965 new->ncase.cases = copynode(n->ncase.cases);
7966 new->ncase.expr = copynode(n->ncase.expr);
7969 new->nclist.body = copynode(n->nclist.body);
7970 new->nclist.pattern = copynode(n->nclist.pattern);
7971 new->nclist.next = copynode(n->nclist.next);
7975 new->narg.backquote = copynodelist(n->narg.backquote);
7976 new->narg.text = nodeckstrdup(n->narg.text);
7977 new->narg.next = copynode(n->narg.next);
7980 #if ENABLE_ASH_BASH_COMPAT
7987 new->nfile.fname = copynode(n->nfile.fname);
7988 new->nfile.fd = n->nfile.fd;
7989 new->nfile.next = copynode(n->nfile.next);
7993 new->ndup.vname = copynode(n->ndup.vname);
7994 new->ndup.dupfd = n->ndup.dupfd;
7995 new->ndup.fd = n->ndup.fd;
7996 new->ndup.next = copynode(n->ndup.next);
8000 new->nhere.doc = copynode(n->nhere.doc);
8001 new->nhere.fd = n->nhere.fd;
8002 new->nhere.next = copynode(n->nhere.next);
8005 new->nnot.com = copynode(n->nnot.com);
8008 new->type = n->type;
8013 * Make a copy of a parse tree.
8015 static struct funcnode *
8016 copyfunc(union node *n)
8021 funcblocksize = offsetof(struct funcnode, n);
8024 blocksize = funcblocksize;
8025 f = ckmalloc(blocksize + funcstringsize);
8026 funcblock = (char *) f + offsetof(struct funcnode, n);
8027 funcstring = (char *) f + blocksize;
8034 * Define a shell function.
8037 defun(char *name, union node *func)
8039 struct cmdentry entry;
8042 entry.cmdtype = CMDFUNCTION;
8043 entry.u.func = copyfunc(func);
8044 addcmdentry(name, &entry);
8048 /* Reasons for skipping commands (see comment on breakcmd routine) */
8049 #define SKIPBREAK (1 << 0)
8050 #define SKIPCONT (1 << 1)
8051 #define SKIPFUNC (1 << 2)
8052 #define SKIPFILE (1 << 3)
8053 #define SKIPEVAL (1 << 4)
8054 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8055 static int skipcount; /* number of levels to skip */
8056 static int funcnest; /* depth of function calls */
8057 static int loopnest; /* current loop nesting level */
8059 /* Forward decl way out to parsing code - dotrap needs it */
8060 static int evalstring(char *s, int mask);
8062 /* Called to execute a trap.
8063 * Single callsite - at the end of evaltree().
8064 * If we return non-zero, exaltree raises EXEXIT exception.
8066 * Perhaps we should avoid entering new trap handlers
8067 * while we are executing a trap handler. [is it a TODO?]
8076 savestatus = exitstatus;
8080 TRACE(("dotrap entered\n"));
8081 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8088 /* non-trapped SIGINT is handled separately by raise_interrupt,
8089 * don't upset it by resetting gotsig[SIGINT-1] */
8090 if (sig == SIGINT && !t)
8093 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8097 want_exexit = evalstring(t, SKIPEVAL);
8098 exitstatus = savestatus;
8100 TRACE(("dotrap returns %d\n", want_exexit));
8105 TRACE(("dotrap returns 0\n"));
8109 /* forward declarations - evaluation is fairly recursive business... */
8110 static void evalloop(union node *, int);
8111 static void evalfor(union node *, int);
8112 static void evalcase(union node *, int);
8113 static void evalsubshell(union node *, int);
8114 static void expredir(union node *);
8115 static void evalpipe(union node *, int);
8116 static void evalcommand(union node *, int);
8117 static int evalbltin(const struct builtincmd *, int, char **);
8118 static void prehash(union node *);
8121 * Evaluate a parse tree. The value is left in the global variable
8125 evaltree(union node *n, int flags)
8127 struct jmploc *volatile savehandler = exception_handler;
8128 struct jmploc jmploc;
8130 void (*evalfn)(union node *, int);
8134 SAVE_INT(int_level);
8137 TRACE(("evaltree(NULL) called\n"));
8140 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8142 exception_handler = &jmploc;
8144 int err = setjmp(jmploc.loc);
8146 /* if it was a signal, check for trap handlers */
8147 if (exception_type == EXSIG) {
8148 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8149 exception_type, err));
8152 /* continue on the way out */
8153 TRACE(("exception %d in evaltree, propagating err=%d\n",
8154 exception_type, err));
8155 exception_handler = savehandler;
8156 longjmp(exception_handler->loc, err);
8163 out1fmt("Node type = %d\n", n->type);
8168 evaltree(n->nnot.com, EV_TESTED);
8169 status = !exitstatus;
8172 expredir(n->nredir.redirect);
8173 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8175 evaltree(n->nredir.n, flags & EV_TESTED);
8176 status = exitstatus;
8178 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8181 evalfn = evalcommand;
8183 if (eflag && !(flags & EV_TESTED))
8195 evalfn = evalsubshell;
8208 #error NAND + 1 != NOR
8210 #if NOR + 1 != NSEMI
8211 #error NOR + 1 != NSEMI
8213 unsigned is_or = n->type - NAND;
8216 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8218 if (!exitstatus == is_or)
8231 evaltree(n->nif.test, EV_TESTED);
8234 if (exitstatus == 0) {
8238 if (n->nif.elsepart) {
8239 n = n->nif.elsepart;
8244 defun(n->narg.text, n->narg.next);
8248 exitstatus = status;
8253 exception_handler = savehandler;
8255 if (checkexit & exitstatus)
8256 evalskip |= SKIPEVAL;
8257 else if (pending_sig && dotrap())
8260 if (flags & EV_EXIT) {
8262 raise_exception(EXEXIT);
8265 RESTORE_INT(int_level);
8266 TRACE(("leaving evaltree (no interrupts)\n"));
8269 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8272 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8275 evalloop(union node *n, int flags)
8285 evaltree(n->nbinary.ch1, EV_TESTED);
8288 if (evalskip == SKIPCONT && --skipcount <= 0) {
8292 if (evalskip == SKIPBREAK && --skipcount <= 0)
8297 if (n->type != NWHILE)
8301 evaltree(n->nbinary.ch2, flags);
8302 status = exitstatus;
8307 exitstatus = status;
8311 evalfor(union node *n, int flags)
8313 struct arglist arglist;
8316 struct stackmark smark;
8318 setstackmark(&smark);
8319 arglist.list = NULL;
8320 arglist.lastp = &arglist.list;
8321 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8322 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8327 *arglist.lastp = NULL;
8332 for (sp = arglist.list; sp; sp = sp->next) {
8333 setvar(n->nfor.var, sp->text, 0);
8334 evaltree(n->nfor.body, flags);
8336 if (evalskip == SKIPCONT && --skipcount <= 0) {
8340 if (evalskip == SKIPBREAK && --skipcount <= 0)
8347 popstackmark(&smark);
8351 evalcase(union node *n, int flags)
8355 struct arglist arglist;
8356 struct stackmark smark;
8358 setstackmark(&smark);
8359 arglist.list = NULL;
8360 arglist.lastp = &arglist.list;
8361 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8363 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8364 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8365 if (casematch(patp, arglist.list->text)) {
8366 if (evalskip == 0) {
8367 evaltree(cp->nclist.body, flags);
8374 popstackmark(&smark);
8378 * Kick off a subshell to evaluate a tree.
8381 evalsubshell(union node *n, int flags)
8384 int backgnd = (n->type == NBACKGND);
8387 expredir(n->nredir.redirect);
8388 if (!backgnd && flags & EV_EXIT && !trap[0])
8391 jp = makejob(/*n,*/ 1);
8392 if (forkshell(jp, n, backgnd) == 0) {
8396 flags &=~ EV_TESTED;
8398 redirect(n->nredir.redirect, 0);
8399 evaltreenr(n->nredir.n, flags);
8404 status = waitforjob(jp);
8405 exitstatus = status;
8410 * Compute the names of the files in a redirection list.
8412 static void fixredir(union node *, const char *, int);
8414 expredir(union node *n)
8418 for (redir = n; redir; redir = redir->nfile.next) {
8422 fn.lastp = &fn.list;
8423 switch (redir->type) {
8427 #if ENABLE_ASH_BASH_COMPAT
8432 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8433 #if ENABLE_ASH_BASH_COMPAT
8436 redir->nfile.expfname = fn.list->text;
8439 case NTOFD: /* >& */
8440 if (redir->ndup.vname) {
8441 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8442 if (fn.list == NULL)
8443 ash_msg_and_raise_error("redir error");
8444 #if ENABLE_ASH_BASH_COMPAT
8445 //FIXME: we used expandarg with different args!
8446 if (!isdigit_str9(fn.list->text)) {
8447 /* >&file, not >&fd */
8448 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8449 ash_msg_and_raise_error("redir error");
8451 goto store_expfname;
8454 fixredir(redir, fn.list->text, 1);
8462 * Evaluate a pipeline. All the processes in the pipeline are children
8463 * of the process creating the pipeline. (This differs from some versions
8464 * of the shell, which make the last process in a pipeline the parent
8468 evalpipe(union node *n, int flags)
8471 struct nodelist *lp;
8476 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8478 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8482 jp = makejob(/*n,*/ pipelen);
8484 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8488 if (pipe(pip) < 0) {
8490 ash_msg_and_raise_error("pipe call failed");
8493 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8506 evaltreenr(lp->n, flags);
8512 /* Don't want to trigger debugging */
8516 if (n->npipe.pipe_backgnd == 0) {
8517 exitstatus = waitforjob(jp);
8518 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8524 * Controls whether the shell is interactive or not.
8527 setinteractive(int on)
8529 static smallint is_interactive;
8531 if (++on == is_interactive)
8533 is_interactive = on;
8537 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8538 if (is_interactive > 1) {
8539 /* Looks like they want an interactive shell */
8540 static smallint did_banner;
8543 /* note: ash and hush share this string */
8544 out1fmt("\n\n%s %s\n"
8545 "Enter 'help' for a list of built-in commands."
8548 "built-in shell (ash)"
8562 setinteractive(iflag);
8564 #if ENABLE_FEATURE_EDITING_VI
8566 line_input_state->flags |= VI_MODE;
8568 line_input_state->flags &= ~VI_MODE;
8570 viflag = 0; /* forcibly keep the option off */
8574 static struct localvar *localvars;
8577 * Called after a function returns.
8578 * Interrupts must be off.
8583 struct localvar *lvp;
8586 while ((lvp = localvars) != NULL) {
8587 localvars = lvp->next;
8589 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8590 if (vp == NULL) { /* $- saved */
8591 memcpy(optlist, lvp->text, sizeof(optlist));
8592 free((char*)lvp->text);
8594 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8598 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8599 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8600 free((char*)vp->text);
8601 vp->flags = lvp->flags;
8602 vp->text = lvp->text;
8609 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8611 volatile struct shparam saveparam;
8612 struct localvar *volatile savelocalvars;
8613 struct jmploc *volatile savehandler;
8614 struct jmploc jmploc;
8617 saveparam = shellparam;
8618 savelocalvars = localvars;
8619 e = setjmp(jmploc.loc);
8624 savehandler = exception_handler;
8625 exception_handler = &jmploc;
8627 shellparam.malloced = 0;
8631 shellparam.nparam = argc - 1;
8632 shellparam.p = argv + 1;
8633 #if ENABLE_ASH_GETOPTS
8634 shellparam.optind = 1;
8635 shellparam.optoff = -1;
8637 evaltree(&func->n, flags & EV_TESTED);
8643 localvars = savelocalvars;
8644 freeparam(&shellparam);
8645 shellparam = saveparam;
8646 exception_handler = savehandler;
8648 evalskip &= ~SKIPFUNC;
8652 #if ENABLE_ASH_CMDCMD
8654 parse_command_args(char **argv, const char **path)
8667 if (c == '-' && !*cp) {
8674 *path = bb_default_path;
8677 /* run 'typecmd' for other options */
8688 * Make a variable a local variable. When a variable is made local, it's
8689 * value and flags are saved in a localvar structure. The saved values
8690 * will be restored when the shell function returns. We handle the name
8691 * "-" as a special case.
8696 struct localvar *lvp;
8701 lvp = ckzalloc(sizeof(struct localvar));
8702 if (LONE_DASH(name)) {
8704 p = ckmalloc(sizeof(optlist));
8705 lvp->text = memcpy(p, optlist, sizeof(optlist));
8710 vpp = hashvar(name);
8711 vp = *findvar(vpp, name);
8712 eq = strchr(name, '=');
8715 setvareq(name, VSTRFIXED);
8717 setvar(name, NULL, VSTRFIXED);
8718 vp = *vpp; /* the new variable */
8719 lvp->flags = VUNSET;
8721 lvp->text = vp->text;
8722 lvp->flags = vp->flags;
8723 vp->flags |= VSTRFIXED|VTEXTFIXED;
8729 lvp->next = localvars;
8735 * The "local" command.
8737 static int FAST_FUNC
8738 localcmd(int argc UNUSED_PARAM, char **argv)
8743 while ((name = *argv++) != NULL) {
8749 static int FAST_FUNC
8750 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8755 static int FAST_FUNC
8756 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8761 static int FAST_FUNC
8762 execcmd(int argc UNUSED_PARAM, char **argv)
8765 iflag = 0; /* exit on error */
8768 shellexec(argv + 1, pathval(), 0);
8774 * The return command.
8776 static int FAST_FUNC
8777 returncmd(int argc UNUSED_PARAM, char **argv)
8780 * If called outside a function, do what ksh does;
8781 * skip the rest of the file.
8783 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8784 return argv[1] ? number(argv[1]) : exitstatus;
8787 /* Forward declarations for builtintab[] */
8788 static int breakcmd(int, char **) FAST_FUNC;
8789 static int dotcmd(int, char **) FAST_FUNC;
8790 static int evalcmd(int, char **) FAST_FUNC;
8791 static int exitcmd(int, char **) FAST_FUNC;
8792 static int exportcmd(int, char **) FAST_FUNC;
8793 #if ENABLE_ASH_GETOPTS
8794 static int getoptscmd(int, char **) FAST_FUNC;
8796 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8797 static int helpcmd(int, char **) FAST_FUNC;
8799 #if ENABLE_SH_MATH_SUPPORT
8800 static int letcmd(int, char **) FAST_FUNC;
8802 static int readcmd(int, char **) FAST_FUNC;
8803 static int setcmd(int, char **) FAST_FUNC;
8804 static int shiftcmd(int, char **) FAST_FUNC;
8805 static int timescmd(int, char **) FAST_FUNC;
8806 static int trapcmd(int, char **) FAST_FUNC;
8807 static int umaskcmd(int, char **) FAST_FUNC;
8808 static int unsetcmd(int, char **) FAST_FUNC;
8809 static int ulimitcmd(int, char **) FAST_FUNC;
8811 #define BUILTIN_NOSPEC "0"
8812 #define BUILTIN_SPECIAL "1"
8813 #define BUILTIN_REGULAR "2"
8814 #define BUILTIN_SPEC_REG "3"
8815 #define BUILTIN_ASSIGN "4"
8816 #define BUILTIN_SPEC_ASSG "5"
8817 #define BUILTIN_REG_ASSG "6"
8818 #define BUILTIN_SPEC_REG_ASSG "7"
8820 /* Stubs for calling non-FAST_FUNC's */
8821 #if ENABLE_ASH_BUILTIN_ECHO
8822 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8824 #if ENABLE_ASH_BUILTIN_PRINTF
8825 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8827 #if ENABLE_ASH_BUILTIN_TEST
8828 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8831 /* Keep these in proper order since it is searched via bsearch() */
8832 static const struct builtincmd builtintab[] = {
8833 { BUILTIN_SPEC_REG ".", dotcmd },
8834 { BUILTIN_SPEC_REG ":", truecmd },
8835 #if ENABLE_ASH_BUILTIN_TEST
8836 { BUILTIN_REGULAR "[", testcmd },
8837 #if ENABLE_ASH_BASH_COMPAT
8838 { BUILTIN_REGULAR "[[", testcmd },
8841 #if ENABLE_ASH_ALIAS
8842 { BUILTIN_REG_ASSG "alias", aliascmd },
8845 { BUILTIN_REGULAR "bg", fg_bgcmd },
8847 { BUILTIN_SPEC_REG "break", breakcmd },
8848 { BUILTIN_REGULAR "cd", cdcmd },
8849 { BUILTIN_NOSPEC "chdir", cdcmd },
8850 #if ENABLE_ASH_CMDCMD
8851 { BUILTIN_REGULAR "command", commandcmd },
8853 { BUILTIN_SPEC_REG "continue", breakcmd },
8854 #if ENABLE_ASH_BUILTIN_ECHO
8855 { BUILTIN_REGULAR "echo", echocmd },
8857 { BUILTIN_SPEC_REG "eval", evalcmd },
8858 { BUILTIN_SPEC_REG "exec", execcmd },
8859 { BUILTIN_SPEC_REG "exit", exitcmd },
8860 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8861 { BUILTIN_REGULAR "false", falsecmd },
8863 { BUILTIN_REGULAR "fg", fg_bgcmd },
8865 #if ENABLE_ASH_GETOPTS
8866 { BUILTIN_REGULAR "getopts", getoptscmd },
8868 { BUILTIN_NOSPEC "hash", hashcmd },
8869 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8870 { BUILTIN_NOSPEC "help", helpcmd },
8873 { BUILTIN_REGULAR "jobs", jobscmd },
8874 { BUILTIN_REGULAR "kill", killcmd },
8876 #if ENABLE_SH_MATH_SUPPORT
8877 { BUILTIN_NOSPEC "let", letcmd },
8879 { BUILTIN_ASSIGN "local", localcmd },
8880 #if ENABLE_ASH_BUILTIN_PRINTF
8881 { BUILTIN_REGULAR "printf", printfcmd },
8883 { BUILTIN_NOSPEC "pwd", pwdcmd },
8884 { BUILTIN_REGULAR "read", readcmd },
8885 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8886 { BUILTIN_SPEC_REG "return", returncmd },
8887 { BUILTIN_SPEC_REG "set", setcmd },
8888 { BUILTIN_SPEC_REG "shift", shiftcmd },
8889 { BUILTIN_SPEC_REG "source", dotcmd },
8890 #if ENABLE_ASH_BUILTIN_TEST
8891 { BUILTIN_REGULAR "test", testcmd },
8893 { BUILTIN_SPEC_REG "times", timescmd },
8894 { BUILTIN_SPEC_REG "trap", trapcmd },
8895 { BUILTIN_REGULAR "true", truecmd },
8896 { BUILTIN_NOSPEC "type", typecmd },
8897 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8898 { BUILTIN_REGULAR "umask", umaskcmd },
8899 #if ENABLE_ASH_ALIAS
8900 { BUILTIN_REGULAR "unalias", unaliascmd },
8902 { BUILTIN_SPEC_REG "unset", unsetcmd },
8903 { BUILTIN_REGULAR "wait", waitcmd },
8906 /* Should match the above table! */
8907 #define COMMANDCMD (builtintab + \
8909 1 * ENABLE_ASH_BUILTIN_TEST + \
8910 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8911 1 * ENABLE_ASH_ALIAS + \
8912 1 * ENABLE_ASH_JOB_CONTROL + \
8914 #define EXECCMD (builtintab + \
8916 1 * ENABLE_ASH_BUILTIN_TEST + \
8917 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8918 1 * ENABLE_ASH_ALIAS + \
8919 1 * ENABLE_ASH_JOB_CONTROL + \
8921 1 * ENABLE_ASH_CMDCMD + \
8923 ENABLE_ASH_BUILTIN_ECHO + \
8927 * Search the table of builtin commands.
8929 static struct builtincmd *
8930 find_builtin(const char *name)
8932 struct builtincmd *bp;
8935 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8942 * Execute a simple command.
8945 isassignment(const char *p)
8947 const char *q = endofname(p);
8952 static int FAST_FUNC
8953 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8955 /* Preserve exitstatus of a previous possible redirection
8956 * as POSIX mandates */
8957 return back_exitstatus;
8960 evalcommand(union node *cmd, int flags)
8962 static const struct builtincmd null_bltin = {
8963 "\0\0", bltincmd /* why three NULs? */
8965 struct stackmark smark;
8967 struct arglist arglist;
8968 struct arglist varlist;
8971 const struct strlist *sp;
8972 struct cmdentry cmdentry;
8979 struct builtincmd *bcmd;
8980 smallint cmd_is_exec;
8981 smallint pseudovarflag = 0;
8983 /* First expand the arguments. */
8984 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8985 setstackmark(&smark);
8986 back_exitstatus = 0;
8988 cmdentry.cmdtype = CMDBUILTIN;
8989 cmdentry.u.cmd = &null_bltin;
8990 varlist.lastp = &varlist.list;
8991 *varlist.lastp = NULL;
8992 arglist.lastp = &arglist.list;
8993 *arglist.lastp = NULL;
8996 if (cmd->ncmd.args) {
8997 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8998 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9001 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9002 struct strlist **spp;
9004 spp = arglist.lastp;
9005 if (pseudovarflag && isassignment(argp->narg.text))
9006 expandarg(argp, &arglist, EXP_VARTILDE);
9008 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9010 for (sp = *spp; sp; sp = sp->next)
9014 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9015 for (sp = arglist.list; sp; sp = sp->next) {
9016 TRACE(("evalcommand arg: %s\n", sp->text));
9017 *nargv++ = sp->text;
9022 if (iflag && funcnest == 0 && argc > 0)
9023 lastarg = nargv[-1];
9026 expredir(cmd->ncmd.redirect);
9027 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9030 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9031 struct strlist **spp;
9034 spp = varlist.lastp;
9035 expandarg(argp, &varlist, EXP_VARTILDE);
9038 * Modify the command lookup path, if a PATH= assignment
9042 if (varequal(p, path))
9046 /* Print the command if xflag is set. */
9049 const char *p = " %s";
9052 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9055 for (n = 0; n < 2; n++) {
9057 fdprintf(preverrout_fd, p, sp->text);
9065 safe_write(preverrout_fd, "\n", 1);
9071 /* Now locate the command. */
9073 const char *oldpath;
9074 int cmd_flag = DO_ERR;
9079 find_command(argv[0], &cmdentry, cmd_flag, path);
9080 if (cmdentry.cmdtype == CMDUNKNOWN) {
9081 flush_stdout_stderr();
9086 /* implement bltin and command here */
9087 if (cmdentry.cmdtype != CMDBUILTIN)
9090 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9091 if (cmdentry.u.cmd == EXECCMD)
9093 #if ENABLE_ASH_CMDCMD
9094 if (cmdentry.u.cmd == COMMANDCMD) {
9096 nargv = parse_command_args(argv, &path);
9099 argc -= nargv - argv;
9101 cmd_flag |= DO_NOFUNC;
9109 /* We have a redirection error. */
9111 raise_exception(EXERROR);
9113 exitstatus = status;
9117 /* Execute the command. */
9118 switch (cmdentry.cmdtype) {
9121 #if ENABLE_FEATURE_SH_NOFORK
9122 /* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9123 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
9125 /* find_command() encodes applet_no as (-2 - applet_no) */
9126 int applet_no = (- cmdentry.u.index - 2);
9127 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9128 listsetvar(varlist.list, VEXPORT|VSTACK);
9129 /* run <applet>_main() */
9130 exitstatus = run_nofork_applet(applet_no, argv);
9135 /* Fork off a child process if necessary. */
9136 if (!(flags & EV_EXIT) || trap[0]) {
9138 jp = makejob(/*cmd,*/ 1);
9139 if (forkshell(jp, cmd, FORK_FG) != 0) {
9140 exitstatus = waitforjob(jp);
9142 TRACE(("forked child exited with %d\n", exitstatus));
9147 listsetvar(varlist.list, VEXPORT|VSTACK);
9148 shellexec(argv, path, cmdentry.u.index);
9152 cmdenviron = varlist.list;
9154 struct strlist *list = cmdenviron;
9156 if (spclbltin > 0 || argc == 0) {
9158 if (cmd_is_exec && argc > 1)
9161 listsetvar(list, i);
9163 /* Tight loop with builtins only:
9164 * "while kill -0 $child; do true; done"
9165 * will never exit even if $child died, unless we do this
9166 * to reap the zombie and make kill detect that it's gone: */
9167 dowait(DOWAIT_NONBLOCK, NULL);
9169 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9171 int i = exception_type;
9176 exit_status = 128 + SIGINT;
9178 exit_status = 128 + pending_sig;
9179 exitstatus = exit_status;
9180 if (i == EXINT || spclbltin > 0) {
9182 longjmp(exception_handler->loc, 1);
9189 listsetvar(varlist.list, 0);
9190 /* See above for the rationale */
9191 dowait(DOWAIT_NONBLOCK, NULL);
9192 if (evalfun(cmdentry.u.func, argc, argv, flags))
9198 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9200 /* dsl: I think this is intended to be used to support
9201 * '_' in 'vi' command mode during line editing...
9202 * However I implemented that within libedit itself.
9204 setvar("_", lastarg, 0);
9206 popstackmark(&smark);
9210 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9212 char *volatile savecmdname;
9213 struct jmploc *volatile savehandler;
9214 struct jmploc jmploc;
9217 savecmdname = commandname;
9218 i = setjmp(jmploc.loc);
9221 savehandler = exception_handler;
9222 exception_handler = &jmploc;
9223 commandname = argv[0];
9225 optptr = NULL; /* initialize nextopt */
9226 exitstatus = (*cmd->builtin)(argc, argv);
9227 flush_stdout_stderr();
9229 exitstatus |= ferror(stdout);
9231 commandname = savecmdname;
9232 exception_handler = savehandler;
9238 goodname(const char *p)
9240 return !*endofname(p);
9245 * Search for a command. This is called before we fork so that the
9246 * location of the command will be available in the parent as well as
9247 * the child. The check for "goodname" is an overly conservative
9248 * check that the name will not be subject to expansion.
9251 prehash(union node *n)
9253 struct cmdentry entry;
9255 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9256 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9260 /* ============ Builtin commands
9262 * Builtin commands whose functions are closely tied to evaluation
9263 * are implemented here.
9267 * Handle break and continue commands. Break, continue, and return are
9268 * all handled by setting the evalskip flag. The evaluation routines
9269 * above all check this flag, and if it is set they start skipping
9270 * commands rather than executing them. The variable skipcount is
9271 * the number of loops to break/continue, or the number of function
9272 * levels to return. (The latter is always 1.) It should probably
9273 * be an error to break out of more loops than exist, but it isn't
9274 * in the standard shell so we don't make it one here.
9276 static int FAST_FUNC
9277 breakcmd(int argc UNUSED_PARAM, char **argv)
9279 int n = argv[1] ? number(argv[1]) : 1;
9282 ash_msg_and_raise_error(msg_illnum, argv[1]);
9286 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9293 /* ============ input.c
9295 * This implements the input routines used by the parser.
9299 INPUT_PUSH_FILE = 1,
9300 INPUT_NOFILE_OK = 2,
9303 static smallint checkkwd;
9304 /* values of checkkwd variable */
9305 #define CHKALIAS 0x1
9310 * Push a string back onto the input at this current parsefile level.
9311 * We handle aliases this way.
9313 #if !ENABLE_ASH_ALIAS
9314 #define pushstring(s, ap) pushstring(s)
9317 pushstring(char *s, struct alias *ap)
9324 if (g_parsefile->strpush) {
9325 sp = ckzalloc(sizeof(*sp));
9326 sp->prev = g_parsefile->strpush;
9328 sp = &(g_parsefile->basestrpush);
9330 g_parsefile->strpush = sp;
9331 sp->prev_string = g_parsefile->next_to_pgetc;
9332 sp->prev_left_in_line = g_parsefile->left_in_line;
9333 #if ENABLE_ASH_ALIAS
9336 ap->flag |= ALIASINUSE;
9340 g_parsefile->next_to_pgetc = s;
9341 g_parsefile->left_in_line = len;
9348 struct strpush *sp = g_parsefile->strpush;
9351 #if ENABLE_ASH_ALIAS
9353 if (g_parsefile->next_to_pgetc[-1] == ' '
9354 || g_parsefile->next_to_pgetc[-1] == '\t'
9356 checkkwd |= CHKALIAS;
9358 if (sp->string != sp->ap->val) {
9361 sp->ap->flag &= ~ALIASINUSE;
9362 if (sp->ap->flag & ALIASDEAD) {
9363 unalias(sp->ap->name);
9367 g_parsefile->next_to_pgetc = sp->prev_string;
9368 g_parsefile->left_in_line = sp->prev_left_in_line;
9369 g_parsefile->strpush = sp->prev;
9370 if (sp != &(g_parsefile->basestrpush))
9375 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9376 //it peeks whether it is &>, and then pushes back both chars.
9377 //This function needs to save last *next_to_pgetc to buf[0]
9378 //to make two pungetc() reliable. Currently,
9379 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9384 char *buf = g_parsefile->buf;
9386 g_parsefile->next_to_pgetc = buf;
9387 #if ENABLE_FEATURE_EDITING
9389 if (!iflag || g_parsefile->fd != STDIN_FILENO)
9390 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9392 #if ENABLE_FEATURE_TAB_COMPLETION
9393 line_input_state->path_lookup = pathval();
9395 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9397 /* Ctrl+C pressed */
9406 if (nr < 0 && errno == 0) {
9407 /* Ctrl+D pressed */
9412 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9416 /* nonblock_safe_read() handles this problem */
9418 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9419 int flags = fcntl(0, F_GETFL);
9420 if (flags >= 0 && (flags & O_NONBLOCK)) {
9421 flags &= ~O_NONBLOCK;
9422 if (fcntl(0, F_SETFL, flags) >= 0) {
9423 out2str("sh: turning off NDELAY mode\n");
9434 * Refill the input buffer and return the next input character:
9436 * 1) If a string was pushed back on the input, pop it;
9437 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9438 * or we are reading from a string so we can't refill the buffer,
9440 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9441 * 4) Process input up to the next newline, deleting nul characters.
9443 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9444 #define pgetc_debug(...) ((void)0)
9451 while (g_parsefile->strpush) {
9452 #if ENABLE_ASH_ALIAS
9453 if (g_parsefile->left_in_line == -1
9454 && g_parsefile->strpush->ap
9455 && g_parsefile->next_to_pgetc[-1] != ' '
9456 && g_parsefile->next_to_pgetc[-1] != '\t'
9458 pgetc_debug("preadbuffer PEOA");
9463 /* try "pgetc" now: */
9464 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9465 g_parsefile->left_in_line,
9466 g_parsefile->next_to_pgetc,
9467 g_parsefile->next_to_pgetc);
9468 if (--g_parsefile->left_in_line >= 0)
9469 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9471 /* on both branches above g_parsefile->left_in_line < 0.
9472 * "pgetc" needs refilling.
9475 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9476 * pungetc() may increment it a few times.
9477 * Assuming it won't increment it to less than -90.
9479 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9480 pgetc_debug("preadbuffer PEOF1");
9481 /* even in failure keep left_in_line and next_to_pgetc
9482 * in lock step, for correct multi-layer pungetc.
9483 * left_in_line was decremented before preadbuffer(),
9484 * must inc next_to_pgetc: */
9485 g_parsefile->next_to_pgetc++;
9489 more = g_parsefile->left_in_buffer;
9491 flush_stdout_stderr();
9495 /* don't try reading again */
9496 g_parsefile->left_in_line = -99;
9497 pgetc_debug("preadbuffer PEOF2");
9498 g_parsefile->next_to_pgetc++;
9503 /* Find out where's the end of line.
9504 * Set g_parsefile->left_in_line
9505 * and g_parsefile->left_in_buffer acordingly.
9506 * NUL chars are deleted.
9508 q = g_parsefile->next_to_pgetc;
9516 memmove(q, q + 1, more);
9520 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9526 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9527 if (g_parsefile->left_in_line < 0)
9532 g_parsefile->left_in_buffer = more;
9537 out2str(g_parsefile->next_to_pgetc);
9541 pgetc_debug("preadbuffer at %d:%p'%s'",
9542 g_parsefile->left_in_line,
9543 g_parsefile->next_to_pgetc,
9544 g_parsefile->next_to_pgetc);
9545 return (unsigned char)*g_parsefile->next_to_pgetc++;
9548 #define pgetc_as_macro() \
9549 (--g_parsefile->left_in_line >= 0 \
9550 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9557 pgetc_debug("pgetc_fast at %d:%p'%s'",
9558 g_parsefile->left_in_line,
9559 g_parsefile->next_to_pgetc,
9560 g_parsefile->next_to_pgetc);
9561 return pgetc_as_macro();
9564 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9565 # define pgetc_fast() pgetc()
9567 # define pgetc_fast() pgetc_as_macro()
9570 #if ENABLE_ASH_ALIAS
9572 pgetc_without_PEOA(void)
9576 pgetc_debug("pgetc_fast at %d:%p'%s'",
9577 g_parsefile->left_in_line,
9578 g_parsefile->next_to_pgetc,
9579 g_parsefile->next_to_pgetc);
9581 } while (c == PEOA);
9585 # define pgetc_without_PEOA() pgetc()
9589 * Read a line from the script.
9592 pfgets(char *line, int len)
9598 while (--nleft > 0) {
9599 c = pgetc_without_PEOA();
9614 * Undo the last call to pgetc. Only one character may be pushed back.
9615 * PEOF may be pushed back.
9620 g_parsefile->left_in_line++;
9621 g_parsefile->next_to_pgetc--;
9622 pgetc_debug("pushed back to %d:%p'%s'",
9623 g_parsefile->left_in_line,
9624 g_parsefile->next_to_pgetc,
9625 g_parsefile->next_to_pgetc);
9629 * To handle the "." command, a stack of input files is used. Pushfile
9630 * adds a new entry to the stack and popfile restores the previous level.
9635 struct parsefile *pf;
9637 pf = ckzalloc(sizeof(*pf));
9638 pf->prev = g_parsefile;
9640 /*pf->strpush = NULL; - ckzalloc did it */
9641 /*pf->basestrpush.prev = NULL;*/
9648 struct parsefile *pf = g_parsefile;
9656 g_parsefile = pf->prev;
9662 * Return to top level.
9667 while (g_parsefile != &basepf)
9672 * Close the file(s) that the shell is reading commands from. Called
9673 * after a fork is done.
9679 if (g_parsefile->fd > 0) {
9680 close(g_parsefile->fd);
9681 g_parsefile->fd = 0;
9686 * Like setinputfile, but takes an open file descriptor. Call this with
9690 setinputfd(int fd, int push)
9692 close_on_exec_on(fd);
9695 g_parsefile->buf = NULL;
9697 g_parsefile->fd = fd;
9698 if (g_parsefile->buf == NULL)
9699 g_parsefile->buf = ckmalloc(IBUFSIZ);
9700 g_parsefile->left_in_buffer = 0;
9701 g_parsefile->left_in_line = 0;
9702 g_parsefile->linno = 1;
9706 * Set the input to take input from a file. If push is set, push the
9707 * old input onto the stack first.
9710 setinputfile(const char *fname, int flags)
9716 fd = open(fname, O_RDONLY);
9718 if (flags & INPUT_NOFILE_OK)
9720 ash_msg_and_raise_error("can't open '%s'", fname);
9723 fd2 = copyfd(fd, 10);
9726 ash_msg_and_raise_error("out of file descriptors");
9729 setinputfd(fd, flags & INPUT_PUSH_FILE);
9736 * Like setinputfile, but takes input from a string.
9739 setinputstring(char *string)
9743 g_parsefile->next_to_pgetc = string;
9744 g_parsefile->left_in_line = strlen(string);
9745 g_parsefile->buf = NULL;
9746 g_parsefile->linno = 1;
9751 /* ============ mail.c
9753 * Routines to check for mail.
9758 #define MAXMBOXES 10
9760 /* times of mailboxes */
9761 static time_t mailtime[MAXMBOXES];
9762 /* Set if MAIL or MAILPATH is changed. */
9763 static smallint mail_var_path_changed;
9766 * Print appropriate message(s) if mail has arrived.
9767 * If mail_var_path_changed is set,
9768 * then the value of MAIL has mail_var_path_changed,
9769 * so we just update the values.
9778 struct stackmark smark;
9781 setstackmark(&smark);
9782 mpath = mpathset() ? mpathval() : mailval();
9783 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9784 p = path_advance(&mpath, nullstr);
9789 for (q = p; *q; q++)
9795 q[-1] = '\0'; /* delete trailing '/' */
9796 if (stat(p, &statb) < 0) {
9800 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9803 pathopt ? pathopt : "you have mail"
9806 *mtp = statb.st_mtime;
9808 mail_var_path_changed = 0;
9809 popstackmark(&smark);
9812 static void FAST_FUNC
9813 changemail(const char *val UNUSED_PARAM)
9815 mail_var_path_changed = 1;
9818 #endif /* ASH_MAIL */
9821 /* ============ ??? */
9824 * Set the shell parameters.
9827 setparam(char **argv)
9833 for (nparam = 0; argv[nparam]; nparam++)
9835 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9837 *ap++ = ckstrdup(*argv++);
9840 freeparam(&shellparam);
9841 shellparam.malloced = 1;
9842 shellparam.nparam = nparam;
9843 shellparam.p = newparam;
9844 #if ENABLE_ASH_GETOPTS
9845 shellparam.optind = 1;
9846 shellparam.optoff = -1;
9851 * Process shell options. The global variable argptr contains a pointer
9852 * to the argument list; we advance it past the options.
9854 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9855 * For a non-interactive shell, an error condition encountered
9856 * by a special built-in ... shall cause the shell to write a diagnostic message
9857 * to standard error and exit as shown in the following table:
9858 * Error Special Built-In
9860 * Utility syntax error (option or operand error) Shall exit
9862 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9863 * we see that bash does not do that (set "finishes" with error code 1 instead,
9864 * and shell continues), and people rely on this behavior!
9866 * set -o barfoo 2>/dev/null
9869 * Oh well. Let's mimic that.
9872 plus_minus_o(char *name, int val)
9877 for (i = 0; i < NOPTS; i++) {
9878 if (strcmp(name, optnames(i)) == 0) {
9883 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9886 for (i = 0; i < NOPTS; i++) {
9888 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9890 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9896 setoption(int flag, int val)
9900 for (i = 0; i < NOPTS; i++) {
9901 if (optletters(i) == flag) {
9906 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9910 options(int cmdline)
9918 while ((p = *argptr) != NULL) {
9920 if (c != '-' && c != '+')
9923 val = 0; /* val = 0 if c == '+' */
9926 if (p[0] == '\0' || LONE_DASH(p)) {
9928 /* "-" means turn off -x and -v */
9931 /* "--" means reset params */
9932 else if (*argptr == NULL)
9935 break; /* "-" or "--" terminates options */
9938 /* first char was + or - */
9939 while ((c = *p++) != '\0') {
9940 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9941 if (c == 'c' && cmdline) {
9942 minusc = p; /* command is after shell args */
9943 } else if (c == 'o') {
9944 if (plus_minus_o(*argptr, val)) {
9945 /* it already printed err message */
9946 return 1; /* error */
9950 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9952 /* bash does not accept +-login, we also won't */
9953 } else if (cmdline && val && (c == '-')) { /* long options */
9954 if (strcmp(p, "login") == 0)
9966 * The shift builtin command.
9968 static int FAST_FUNC
9969 shiftcmd(int argc UNUSED_PARAM, char **argv)
9976 n = number(argv[1]);
9977 if (n > shellparam.nparam)
9978 n = 0; /* bash compat, was = shellparam.nparam; */
9980 shellparam.nparam -= n;
9981 for (ap1 = shellparam.p; --n >= 0; ap1++) {
9982 if (shellparam.malloced)
9986 while ((*ap2++ = *ap1++) != NULL)
9988 #if ENABLE_ASH_GETOPTS
9989 shellparam.optind = 1;
9990 shellparam.optoff = -1;
9997 * POSIX requires that 'set' (but not export or readonly) output the
9998 * variables in lexicographic order - by the locale's collating order (sigh).
9999 * Maybe we could keep them in an ordered balanced binary tree
10000 * instead of hashed lists.
10001 * For now just roll 'em through qsort for printing...
10004 showvars(const char *sep_prefix, int on, int off)
10007 char **ep, **epend;
10009 ep = listvars(on, off, &epend);
10010 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10012 sep = *sep_prefix ? " " : sep_prefix;
10014 for (; ep < epend; ep++) {
10018 p = strchrnul(*ep, '=');
10021 q = single_quote(++p);
10022 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10028 * The set command builtin.
10030 static int FAST_FUNC
10031 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10036 return showvars(nullstr, 0, VUNSET);
10039 if (!options(0)) { /* if no parse error... */
10042 if (*argptr != NULL) {
10050 #if ENABLE_ASH_RANDOM_SUPPORT
10051 static void FAST_FUNC
10052 change_random(const char *value)
10056 if (value == NULL) {
10057 /* "get", generate */
10058 t = next_random(&random_gen);
10059 /* set without recursion */
10060 setvar(vrandom.text, utoa(t), VNOFUNC);
10061 vrandom.flags &= ~VNOFUNC;
10064 t = strtoul(value, NULL, 10);
10065 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10070 #if ENABLE_ASH_GETOPTS
10072 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10081 if (*param_optind < 1)
10083 optnext = optfirst + *param_optind - 1;
10085 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10088 p = optnext[-1] + *optoff;
10089 if (p == NULL || *p == '\0') {
10090 /* Current word is done, advance */
10092 if (p == NULL || *p != '-' || *++p == '\0') {
10099 if (LONE_DASH(p)) /* check for "--" */
10104 for (q = optstr; *q != c;) {
10106 if (optstr[0] == ':') {
10109 err |= setvarsafe("OPTARG", s, 0);
10111 fprintf(stderr, "Illegal option -%c\n", c);
10112 unsetvar("OPTARG");
10122 if (*p == '\0' && (p = *optnext) == NULL) {
10123 if (optstr[0] == ':') {
10126 err |= setvarsafe("OPTARG", s, 0);
10129 fprintf(stderr, "No arg for -%c option\n", c);
10130 unsetvar("OPTARG");
10138 err |= setvarsafe("OPTARG", p, 0);
10141 err |= setvarsafe("OPTARG", nullstr, 0);
10143 *optoff = p ? p - *(optnext - 1) : -1;
10144 *param_optind = optnext - optfirst + 1;
10145 fmtstr(s, sizeof(s), "%d", *param_optind);
10146 err |= setvarsafe("OPTIND", s, VNOFUNC);
10149 err |= setvarsafe(optvar, s, 0);
10153 flush_stdout_stderr();
10154 raise_exception(EXERROR);
10160 * The getopts builtin. Shellparam.optnext points to the next argument
10161 * to be processed. Shellparam.optptr points to the next character to
10162 * be processed in the current argument. If shellparam.optnext is NULL,
10163 * then it's the first time getopts has been called.
10165 static int FAST_FUNC
10166 getoptscmd(int argc, char **argv)
10171 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10173 optbase = shellparam.p;
10174 if (shellparam.optind > shellparam.nparam + 1) {
10175 shellparam.optind = 1;
10176 shellparam.optoff = -1;
10179 optbase = &argv[3];
10180 if (shellparam.optind > argc - 2) {
10181 shellparam.optind = 1;
10182 shellparam.optoff = -1;
10186 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10187 &shellparam.optoff);
10189 #endif /* ASH_GETOPTS */
10192 /* ============ Shell parser */
10195 struct heredoc *next; /* next here document in list */
10196 union node *here; /* redirection node */
10197 char *eofmark; /* string indicating end of input */
10198 smallint striptabs; /* if set, strip leading tabs */
10201 static smallint tokpushback; /* last token pushed back */
10202 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10203 static smallint quoteflag; /* set if (part of) last token was quoted */
10204 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10205 static struct heredoc *heredoclist; /* list of here documents to read */
10206 static char *wordtext; /* text of last word returned by readtoken */
10207 static struct nodelist *backquotelist;
10208 static union node *redirnode;
10209 static struct heredoc *heredoc;
10212 * Called when an unexpected token is read during the parse. The argument
10213 * is the token that is expected, or -1 if more than one type of token can
10214 * occur at this point.
10216 static void raise_error_unexpected_syntax(int) NORETURN;
10218 raise_error_unexpected_syntax(int token)
10223 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
10225 sprintf(msg + l, " (expecting %s)", tokname(token));
10226 raise_error_syntax(msg);
10230 #define EOFMARKLEN 79
10232 /* parsing is heavily cross-recursive, need these forward decls */
10233 static union node *andor(void);
10234 static union node *pipeline(void);
10235 static union node *parse_command(void);
10236 static void parseheredoc(void);
10237 static char peektoken(void);
10238 static int readtoken(void);
10240 static union node *
10243 union node *n1, *n2, *n3;
10246 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10247 if (nlflag == 2 && peektoken())
10253 if (tok == TBACKGND) {
10254 if (n2->type == NPIPE) {
10255 n2->npipe.pipe_backgnd = 1;
10257 if (n2->type != NREDIR) {
10258 n3 = stzalloc(sizeof(struct nredir));
10260 /*n3->nredir.redirect = NULL; - stzalloc did it */
10263 n2->type = NBACKGND;
10269 n3 = stzalloc(sizeof(struct nbinary));
10271 n3->nbinary.ch1 = n1;
10272 n3->nbinary.ch2 = n2;
10288 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10296 pungetc(); /* push back EOF on input */
10300 raise_error_unexpected_syntax(-1);
10307 static union node *
10310 union node *n1, *n2, *n3;
10318 } else if (t == TOR) {
10324 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10326 n3 = stzalloc(sizeof(struct nbinary));
10328 n3->nbinary.ch1 = n1;
10329 n3->nbinary.ch2 = n2;
10334 static union node *
10337 union node *n1, *n2, *pipenode;
10338 struct nodelist *lp, *prev;
10342 TRACE(("pipeline: entered\n"));
10343 if (readtoken() == TNOT) {
10345 checkkwd = CHKKWD | CHKALIAS;
10348 n1 = parse_command();
10349 if (readtoken() == TPIPE) {
10350 pipenode = stzalloc(sizeof(struct npipe));
10351 pipenode->type = NPIPE;
10352 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10353 lp = stzalloc(sizeof(struct nodelist));
10354 pipenode->npipe.cmdlist = lp;
10358 lp = stzalloc(sizeof(struct nodelist));
10359 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10360 lp->n = parse_command();
10362 } while (readtoken() == TPIPE);
10368 n2 = stzalloc(sizeof(struct nnot));
10376 static union node *
10381 n = stzalloc(sizeof(struct narg));
10383 /*n->narg.next = NULL; - stzalloc did it */
10384 n->narg.text = wordtext;
10385 n->narg.backquote = backquotelist;
10390 fixredir(union node *n, const char *text, int err)
10394 TRACE(("Fix redir %s %d\n", text, err));
10396 n->ndup.vname = NULL;
10398 fd = bb_strtou(text, NULL, 10);
10399 if (!errno && fd >= 0)
10400 n->ndup.dupfd = fd;
10401 else if (LONE_DASH(text))
10402 n->ndup.dupfd = -1;
10405 raise_error_syntax("bad fd number");
10406 n->ndup.vname = makename();
10411 * Returns true if the text contains nothing to expand (no dollar signs
10415 noexpand(const char *text)
10419 while ((c = *text++) != '\0') {
10420 if (c == CTLQUOTEMARK)
10424 else if (SIT(c, BASESYNTAX) == CCTL)
10433 union node *n = redirnode;
10435 if (readtoken() != TWORD)
10436 raise_error_unexpected_syntax(-1);
10437 if (n->type == NHERE) {
10438 struct heredoc *here = heredoc;
10442 if (quoteflag == 0)
10444 TRACE(("Here document %d\n", n->type));
10445 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10446 raise_error_syntax("illegal eof marker for << redirection");
10447 rmescapes(wordtext, 0);
10448 here->eofmark = wordtext;
10450 if (heredoclist == NULL)
10451 heredoclist = here;
10453 for (p = heredoclist; p->next; p = p->next)
10457 } else if (n->type == NTOFD || n->type == NFROMFD) {
10458 fixredir(n, wordtext, 0);
10460 n->nfile.fname = makename();
10464 static union node *
10467 union node *args, **app;
10468 union node *n = NULL;
10469 union node *vars, **vpp;
10470 union node **rpp, *redir;
10472 #if ENABLE_ASH_BASH_COMPAT
10473 smallint double_brackets_flag = 0;
10483 savecheckkwd = CHKALIAS;
10486 checkkwd = savecheckkwd;
10489 #if ENABLE_ASH_BASH_COMPAT
10490 case TAND: /* "&&" */
10491 case TOR: /* "||" */
10492 if (!double_brackets_flag) {
10496 wordtext = (char *) (t == TAND ? "-a" : "-o");
10499 n = stzalloc(sizeof(struct narg));
10501 /*n->narg.next = NULL; - stzalloc did it */
10502 n->narg.text = wordtext;
10503 #if ENABLE_ASH_BASH_COMPAT
10504 if (strcmp("[[", wordtext) == 0)
10505 double_brackets_flag = 1;
10506 else if (strcmp("]]", wordtext) == 0)
10507 double_brackets_flag = 0;
10509 n->narg.backquote = backquotelist;
10510 if (savecheckkwd && isassignment(wordtext)) {
10512 vpp = &n->narg.next;
10515 app = &n->narg.next;
10520 *rpp = n = redirnode;
10521 rpp = &n->nfile.next;
10522 parsefname(); /* read name of redirection file */
10525 if (args && app == &args->narg.next
10528 struct builtincmd *bcmd;
10531 /* We have a function */
10532 if (readtoken() != TRP)
10533 raise_error_unexpected_syntax(TRP);
10534 name = n->narg.text;
10535 if (!goodname(name)
10536 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10538 raise_error_syntax("bad function name");
10541 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10542 n->narg.next = parse_command();
10555 n = stzalloc(sizeof(struct ncmd));
10557 n->ncmd.args = args;
10558 n->ncmd.assign = vars;
10559 n->ncmd.redirect = redir;
10563 static union node *
10564 parse_command(void)
10566 union node *n1, *n2;
10567 union node *ap, **app;
10568 union node *cp, **cpp;
10569 union node *redir, **rpp;
10576 switch (readtoken()) {
10578 raise_error_unexpected_syntax(-1);
10581 n1 = stzalloc(sizeof(struct nif));
10583 n1->nif.test = list(0);
10584 if (readtoken() != TTHEN)
10585 raise_error_unexpected_syntax(TTHEN);
10586 n1->nif.ifpart = list(0);
10588 while (readtoken() == TELIF) {
10589 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10590 n2 = n2->nif.elsepart;
10592 n2->nif.test = list(0);
10593 if (readtoken() != TTHEN)
10594 raise_error_unexpected_syntax(TTHEN);
10595 n2->nif.ifpart = list(0);
10597 if (lasttoken == TELSE)
10598 n2->nif.elsepart = list(0);
10600 n2->nif.elsepart = NULL;
10608 n1 = stzalloc(sizeof(struct nbinary));
10609 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10610 n1->nbinary.ch1 = list(0);
10613 TRACE(("expecting DO got %s %s\n", tokname(got),
10614 got == TWORD ? wordtext : ""));
10615 raise_error_unexpected_syntax(TDO);
10617 n1->nbinary.ch2 = list(0);
10622 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10623 raise_error_syntax("bad for loop variable");
10624 n1 = stzalloc(sizeof(struct nfor));
10626 n1->nfor.var = wordtext;
10627 checkkwd = CHKKWD | CHKALIAS;
10628 if (readtoken() == TIN) {
10630 while (readtoken() == TWORD) {
10631 n2 = stzalloc(sizeof(struct narg));
10633 /*n2->narg.next = NULL; - stzalloc did it */
10634 n2->narg.text = wordtext;
10635 n2->narg.backquote = backquotelist;
10637 app = &n2->narg.next;
10640 n1->nfor.args = ap;
10641 if (lasttoken != TNL && lasttoken != TSEMI)
10642 raise_error_unexpected_syntax(-1);
10644 n2 = stzalloc(sizeof(struct narg));
10646 /*n2->narg.next = NULL; - stzalloc did it */
10647 n2->narg.text = (char *)dolatstr;
10648 /*n2->narg.backquote = NULL;*/
10649 n1->nfor.args = n2;
10651 * Newline or semicolon here is optional (but note
10652 * that the original Bourne shell only allowed NL).
10654 if (lasttoken != TNL && lasttoken != TSEMI)
10657 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10658 if (readtoken() != TDO)
10659 raise_error_unexpected_syntax(TDO);
10660 n1->nfor.body = list(0);
10664 n1 = stzalloc(sizeof(struct ncase));
10666 if (readtoken() != TWORD)
10667 raise_error_unexpected_syntax(TWORD);
10668 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10670 /*n2->narg.next = NULL; - stzalloc did it */
10671 n2->narg.text = wordtext;
10672 n2->narg.backquote = backquotelist;
10674 checkkwd = CHKKWD | CHKALIAS;
10675 } while (readtoken() == TNL);
10676 if (lasttoken != TIN)
10677 raise_error_unexpected_syntax(TIN);
10678 cpp = &n1->ncase.cases;
10680 checkkwd = CHKNL | CHKKWD;
10682 while (t != TESAC) {
10683 if (lasttoken == TLP)
10685 *cpp = cp = stzalloc(sizeof(struct nclist));
10687 app = &cp->nclist.pattern;
10689 *app = ap = stzalloc(sizeof(struct narg));
10691 /*ap->narg.next = NULL; - stzalloc did it */
10692 ap->narg.text = wordtext;
10693 ap->narg.backquote = backquotelist;
10694 if (readtoken() != TPIPE)
10696 app = &ap->narg.next;
10699 //ap->narg.next = NULL;
10700 if (lasttoken != TRP)
10701 raise_error_unexpected_syntax(TRP);
10702 cp->nclist.body = list(2);
10704 cpp = &cp->nclist.next;
10706 checkkwd = CHKNL | CHKKWD;
10710 raise_error_unexpected_syntax(TENDCASE);
10717 n1 = stzalloc(sizeof(struct nredir));
10718 n1->type = NSUBSHELL;
10719 n1->nredir.n = list(0);
10720 /*n1->nredir.redirect = NULL; - stzalloc did it */
10730 return simplecmd();
10733 if (readtoken() != t)
10734 raise_error_unexpected_syntax(t);
10737 /* Now check for redirection which may follow command */
10738 checkkwd = CHKKWD | CHKALIAS;
10740 while (readtoken() == TREDIR) {
10741 *rpp = n2 = redirnode;
10742 rpp = &n2->nfile.next;
10748 if (n1->type != NSUBSHELL) {
10749 n2 = stzalloc(sizeof(struct nredir));
10754 n1->nredir.redirect = redir;
10759 #if ENABLE_ASH_BASH_COMPAT
10760 static int decode_dollar_squote(void)
10762 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10768 p = strchr(C_escapes, c);
10773 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10777 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10779 } else if (c == 'x') { /* \xHH */
10783 } while (isxdigit(c) && --cnt);
10785 if (cnt == 3) { /* \x but next char is "bad" */
10789 } else { /* simple seq like \\ or \t */
10794 c = bb_process_escape_sequence((void*)&p);
10795 } else { /* unrecognized "\z": print both chars unless ' or " */
10796 if (c != '\'' && c != '"') {
10798 c |= 0x100; /* "please encode \, then me" */
10806 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10807 * is not NULL, read a here document. In the latter case, eofmark is the
10808 * word which marks the end of the document and striptabs is true if
10809 * leading tabs should be stripped from the document. The argument c
10810 * is the first character of the input token or document.
10812 * Because C does not have internal subroutines, I have simulated them
10813 * using goto's to implement the subroutine linkage. The following macros
10814 * will run code that appears at the end of readtoken1.
10816 #define CHECKEND() {goto checkend; checkend_return:;}
10817 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10818 #define PARSESUB() {goto parsesub; parsesub_return:;}
10819 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10820 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10821 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10823 readtoken1(int c, int syntax, char *eofmark, int striptabs)
10825 /* NB: syntax parameter fits into smallint */
10826 /* c parameter is an unsigned char or PEOF or PEOA */
10829 char line[EOFMARKLEN + 1];
10830 struct nodelist *bqlist;
10834 smallint prevsyntax; /* syntax before arithmetic */
10835 #if ENABLE_ASH_EXPAND_PRMT
10836 smallint pssyntax; /* we are expanding a prompt string */
10838 int varnest; /* levels of variables expansion */
10839 int arinest; /* levels of arithmetic expansion */
10840 int parenlevel; /* levels of parens in arithmetic */
10841 int dqvarnest; /* levels of variables expansion within double quotes */
10843 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10846 /* Avoid longjmp clobbering */
10852 (void) &parenlevel;
10855 (void) &prevsyntax;
10858 startlinno = g_parsefile->linno;
10863 #if ENABLE_ASH_EXPAND_PRMT
10864 pssyntax = (syntax == PSSYNTAX);
10868 dblquote = (syntax == DQSYNTAX);
10874 STARTSTACKSTR(out);
10876 /* For each line, until end of word */
10878 CHECKEND(); /* set c to PEOF if at end of here document */
10879 for (;;) { /* until end of line or end of word */
10880 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10881 switch (SIT(c, syntax)) {
10882 case CNL: /* '\n' */
10883 if (syntax == BASESYNTAX)
10884 goto endword; /* exit outer loop */
10886 g_parsefile->linno++;
10890 goto loop; /* continue outer loop */
10895 if (eofmark == NULL || dblquote)
10896 USTPUTC(CTLESC, out);
10897 #if ENABLE_ASH_BASH_COMPAT
10898 if (c == '\\' && bash_dollar_squote) {
10899 c = decode_dollar_squote();
10901 USTPUTC('\\', out);
10902 c = (unsigned char)c;
10908 case CBACK: /* backslash */
10909 c = pgetc_without_PEOA();
10911 USTPUTC(CTLESC, out);
10912 USTPUTC('\\', out);
10914 } else if (c == '\n') {
10918 #if ENABLE_ASH_EXPAND_PRMT
10919 if (c == '$' && pssyntax) {
10920 USTPUTC(CTLESC, out);
10921 USTPUTC('\\', out);
10924 if (dblquote && c != '\\'
10925 && c != '`' && c != '$'
10926 && (c != '"' || eofmark != NULL)
10928 USTPUTC(CTLESC, out);
10929 USTPUTC('\\', out);
10931 if (SIT(c, SQSYNTAX) == CCTL)
10932 USTPUTC(CTLESC, out);
10940 if (eofmark == NULL) {
10941 USTPUTC(CTLQUOTEMARK, out);
10949 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
10950 if (eofmark != NULL && arinest == 0
10955 if (dqvarnest == 0) {
10956 syntax = BASESYNTAX;
10963 case CVAR: /* '$' */
10964 PARSESUB(); /* parse substitution */
10966 case CENDVAR: /* '}' */
10969 if (dqvarnest > 0) {
10972 USTPUTC(CTLENDVAR, out);
10977 #if ENABLE_SH_MATH_SUPPORT
10978 case CLP: /* '(' in arithmetic */
10982 case CRP: /* ')' in arithmetic */
10983 if (parenlevel > 0) {
10987 if (pgetc() == ')') {
10988 if (--arinest == 0) {
10989 USTPUTC(CTLENDARI, out);
10990 syntax = prevsyntax;
10991 dblquote = (syntax == DQSYNTAX);
10996 * unbalanced parens
10997 * (don't 2nd guess - no error)
11005 case CBQUOTE: /* '`' */
11009 goto endword; /* exit outer loop */
11013 if (varnest == 0) {
11014 #if ENABLE_ASH_BASH_COMPAT
11016 if (pgetc() == '>')
11017 c = 0x100 + '>'; /* flag &> */
11021 goto endword; /* exit outer loop */
11023 IF_ASH_ALIAS(if (c != PEOA))
11031 #if ENABLE_SH_MATH_SUPPORT
11032 if (syntax == ARISYNTAX)
11033 raise_error_syntax("missing '))'");
11035 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11036 raise_error_syntax("unterminated quoted string");
11037 if (varnest != 0) {
11038 startlinno = g_parsefile->linno;
11040 raise_error_syntax("missing '}'");
11042 USTPUTC('\0', out);
11043 len = out - (char *)stackblock();
11044 out = stackblock();
11045 if (eofmark == NULL) {
11046 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11049 if (isdigit_str9(out)) {
11050 PARSEREDIR(); /* passed as params: out, c */
11051 lasttoken = TREDIR;
11054 /* else: non-number X seen, interpret it
11055 * as "NNNX>file" = "NNNX >file" */
11059 quoteflag = quotef;
11060 backquotelist = bqlist;
11061 grabstackblock(len);
11065 /* end of readtoken routine */
11068 * Check to see whether we are at the end of the here document. When this
11069 * is called, c is set to the first character of the next input line. If
11070 * we are at the end of the here document, this routine sets the c to PEOF.
11074 #if ENABLE_ASH_ALIAS
11076 c = pgetc_without_PEOA();
11079 while (c == '\t') {
11080 c = pgetc_without_PEOA();
11083 if (c == *eofmark) {
11084 if (pfgets(line, sizeof(line)) != NULL) {
11088 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11090 if (*p == '\n' && *q == '\0') {
11092 g_parsefile->linno++;
11093 needprompt = doprompt;
11095 pushstring(line, NULL);
11100 goto checkend_return;
11104 * Parse a redirection operator. The variable "out" points to a string
11105 * specifying the fd to be redirected. The variable "c" contains the
11106 * first character of the redirection operator.
11109 /* out is already checked to be a valid number or "" */
11110 int fd = (*out == '\0' ? -1 : atoi(out));
11113 np = stzalloc(sizeof(struct nfile));
11118 np->type = NAPPEND;
11120 np->type = NCLOBBER;
11123 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11129 #if ENABLE_ASH_BASH_COMPAT
11130 else if (c == 0x100 + '>') { /* this flags &> redirection */
11132 pgetc(); /* this is '>', no need to check */
11136 else { /* c == '<' */
11137 /*np->nfile.fd = 0; - stzalloc did it */
11141 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11142 np = stzalloc(sizeof(struct nhere));
11143 /*np->nfile.fd = 0; - stzalloc did it */
11146 heredoc = stzalloc(sizeof(struct heredoc));
11147 heredoc->here = np;
11150 heredoc->striptabs = 1;
11152 /*heredoc->striptabs = 0; - stzalloc did it */
11158 np->type = NFROMFD;
11162 np->type = NFROMTO;
11174 goto parseredir_return;
11178 * Parse a substitution. At this point, we have read the dollar sign
11179 * and nothing else.
11182 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11183 * (assuming ascii char codes, as the original implementation did) */
11184 #define is_special(c) \
11185 (((unsigned)(c) - 33 < 32) \
11186 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11188 unsigned char subtype;
11192 static const char types[] ALIGN1 = "}-+?=";
11195 if (c > 255 /* PEOA or PEOF */
11196 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11198 #if ENABLE_ASH_BASH_COMPAT
11200 bash_dollar_squote = 1;
11205 } else if (c == '(') { /* $(command) or $((arith)) */
11206 if (pgetc() == '(') {
11207 #if ENABLE_SH_MATH_SUPPORT
11210 raise_error_syntax("you disabled math support for $((arith)) syntax");
11217 USTPUTC(CTLVAR, out);
11218 typeloc = out - (char *)stackblock();
11219 USTPUTC(VSNORMAL, out);
11220 subtype = VSNORMAL;
11228 subtype = VSLENGTH;
11232 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11236 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11237 } else if (isdigit(c)) {
11241 } while (isdigit(c));
11242 } else if (is_special(c)) {
11247 raise_error_syntax("bad substitution");
11249 if (c != '}' && subtype == VSLENGTH)
11254 if (subtype == 0) {
11258 #if ENABLE_ASH_BASH_COMPAT
11259 if (c == ':' || c == '$' || isdigit(c)) {
11261 subtype = VSSUBSTR;
11268 p = strchr(types, c);
11271 subtype = p - types + VSNORMAL;
11276 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11284 #if ENABLE_ASH_BASH_COMPAT
11286 subtype = VSREPLACE;
11289 subtype++; /* VSREPLACEALL */
11298 if (dblquote || arinest)
11300 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11301 if (subtype != VSNORMAL) {
11303 if (dblquote || arinest) {
11308 goto parsesub_return;
11312 * Called to parse command substitutions. Newstyle is set if the command
11313 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11314 * list of commands (passed by reference), and savelen is the number of
11315 * characters on the top of the stack which must be preserved.
11318 struct nodelist **nlpp;
11321 char *volatile str;
11322 struct jmploc jmploc;
11323 struct jmploc *volatile savehandler;
11325 smallint saveprompt = 0;
11328 (void) &saveprompt;
11330 savepbq = parsebackquote;
11331 if (setjmp(jmploc.loc)) {
11333 parsebackquote = 0;
11334 exception_handler = savehandler;
11335 longjmp(exception_handler->loc, 1);
11339 savelen = out - (char *)stackblock();
11341 str = ckmalloc(savelen);
11342 memcpy(str, stackblock(), savelen);
11344 savehandler = exception_handler;
11345 exception_handler = &jmploc;
11348 /* We must read until the closing backquote, giving special
11349 treatment to some slashes, and then push the string and
11350 reread it as input, interpreting it normally. */
11357 STARTSTACKSTR(pout);
11370 g_parsefile->linno++;
11374 * If eating a newline, avoid putting
11375 * the newline into the new character
11376 * stream (via the STPUTC after the
11381 if (pc != '\\' && pc != '`' && pc != '$'
11382 && (!dblquote || pc != '"')
11384 STPUTC('\\', pout);
11386 if (pc <= 255 /* not PEOA or PEOF */) {
11392 IF_ASH_ALIAS(case PEOA:)
11393 startlinno = g_parsefile->linno;
11394 raise_error_syntax("EOF in backquote substitution");
11397 g_parsefile->linno++;
11398 needprompt = doprompt;
11407 STPUTC('\0', pout);
11408 psavelen = pout - (char *)stackblock();
11409 if (psavelen > 0) {
11410 pstr = grabstackstr(pout);
11411 setinputstring(pstr);
11416 nlpp = &(*nlpp)->next;
11417 *nlpp = stzalloc(sizeof(**nlpp));
11418 /* (*nlpp)->next = NULL; - stzalloc did it */
11419 parsebackquote = oldstyle;
11422 saveprompt = doprompt;
11429 doprompt = saveprompt;
11430 else if (readtoken() != TRP)
11431 raise_error_unexpected_syntax(TRP);
11436 * Start reading from old file again, ignoring any pushed back
11437 * tokens left from the backquote parsing
11442 while (stackblocksize() <= savelen)
11444 STARTSTACKSTR(out);
11446 memcpy(out, str, savelen);
11447 STADJUST(savelen, out);
11453 parsebackquote = savepbq;
11454 exception_handler = savehandler;
11455 if (arinest || dblquote)
11456 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11458 USTPUTC(CTLBACKQ, out);
11460 goto parsebackq_oldreturn;
11461 goto parsebackq_newreturn;
11464 #if ENABLE_SH_MATH_SUPPORT
11466 * Parse an arithmetic expansion (indicate start of one and set state)
11469 if (++arinest == 1) {
11470 prevsyntax = syntax;
11471 syntax = ARISYNTAX;
11472 USTPUTC(CTLARI, out);
11479 * we collapse embedded arithmetic expansion to
11480 * parenthesis, which should be equivalent
11484 goto parsearith_return;
11488 } /* end of readtoken */
11491 * Read the next input token.
11492 * If the token is a word, we set backquotelist to the list of cmds in
11493 * backquotes. We set quoteflag to true if any part of the word was
11495 * If the token is TREDIR, then we set redirnode to a structure containing
11497 * In all cases, the variable startlinno is set to the number of the line
11498 * on which the token starts.
11500 * [Change comment: here documents and internal procedures]
11501 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11502 * word parsing code into a separate routine. In this case, readtoken
11503 * doesn't need to have any internal procedures, but parseword does.
11504 * We could also make parseoperator in essence the main routine, and
11505 * have parseword (readtoken1?) handle both words and redirection.]
11507 #define NEW_xxreadtoken
11508 #ifdef NEW_xxreadtoken
11509 /* singles must be first! */
11510 static const char xxreadtoken_chars[7] ALIGN1 = {
11511 '\n', '(', ')', /* singles */
11512 '&', '|', ';', /* doubles */
11516 #define xxreadtoken_singles 3
11517 #define xxreadtoken_doubles 3
11519 static const char xxreadtoken_tokens[] ALIGN1 = {
11520 TNL, TLP, TRP, /* only single occurrence allowed */
11521 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11522 TEOF, /* corresponds to trailing nul */
11523 TAND, TOR, TENDCASE /* if double occurrence */
11538 startlinno = g_parsefile->linno;
11539 for (;;) { /* until token or start of word found */
11541 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11545 while ((c = pgetc()) != '\n' && c != PEOF)
11548 } else if (c == '\\') {
11549 if (pgetc() != '\n') {
11551 break; /* return readtoken1(...) */
11553 startlinno = ++g_parsefile->linno;
11559 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11562 g_parsefile->linno++;
11563 needprompt = doprompt;
11566 p = strchr(xxreadtoken_chars, c);
11568 break; /* return readtoken1(...) */
11570 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11572 if (cc == c) { /* double occurrence? */
11573 p += xxreadtoken_doubles + 1;
11576 #if ENABLE_ASH_BASH_COMPAT
11577 if (c == '&' && cc == '>') /* &> */
11578 break; /* return readtoken1(...) */
11583 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11588 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11590 #else /* old xxreadtoken */
11591 #define RETURN(token) return lasttoken = token
11604 startlinno = g_parsefile->linno;
11605 for (;;) { /* until token or start of word found */
11608 case ' ': case '\t':
11609 IF_ASH_ALIAS(case PEOA:)
11612 while ((c = pgetc()) != '\n' && c != PEOF)
11617 if (pgetc() == '\n') {
11618 startlinno = ++g_parsefile->linno;
11626 g_parsefile->linno++;
11627 needprompt = doprompt;
11632 if (pgetc() == '&')
11637 if (pgetc() == '|')
11642 if (pgetc() == ';')
11655 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11658 #endif /* old xxreadtoken */
11665 smallint alreadyseen = tokpushback;
11668 #if ENABLE_ASH_ALIAS
11677 if (checkkwd & CHKNL) {
11684 if (t != TWORD || quoteflag) {
11689 * check for keywords
11691 if (checkkwd & CHKKWD) {
11692 const char *const *pp;
11694 pp = findkwd(wordtext);
11696 lasttoken = t = pp - tokname_array;
11697 TRACE(("keyword %s recognized\n", tokname(t)));
11702 if (checkkwd & CHKALIAS) {
11703 #if ENABLE_ASH_ALIAS
11705 ap = lookupalias(wordtext, 1);
11708 pushstring(ap->val, ap);
11718 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11720 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11732 return tokname_array[t][0];
11736 * Read and parse a command. Returns NODE_EOF on end of file.
11737 * (NULL is a valid parse tree indicating a blank line.)
11739 static union node *
11740 parsecmd(int interact)
11745 doprompt = interact;
11747 setprompt(doprompt);
11759 * Input any here documents.
11764 struct heredoc *here;
11767 here = heredoclist;
11768 heredoclist = NULL;
11774 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11775 here->eofmark, here->striptabs);
11776 n = stzalloc(sizeof(struct narg));
11777 n->narg.type = NARG;
11778 /*n->narg.next = NULL; - stzalloc did it */
11779 n->narg.text = wordtext;
11780 n->narg.backquote = backquotelist;
11781 here->here->nhere.doc = n;
11788 * called by editline -- any expansions to the prompt should be added here.
11790 #if ENABLE_ASH_EXPAND_PRMT
11791 static const char *
11792 expandstr(const char *ps)
11796 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11797 * and token processing _can_ alter it (delete NULs etc). */
11798 setinputstring((char *)ps);
11799 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11802 n.narg.type = NARG;
11803 n.narg.next = NULL;
11804 n.narg.text = wordtext;
11805 n.narg.backquote = backquotelist;
11807 expandarg(&n, NULL, 0);
11808 return stackblock();
11813 * Execute a command or commands contained in a string.
11816 evalstring(char *s, int mask)
11819 struct stackmark smark;
11823 setstackmark(&smark);
11826 while ((n = parsecmd(0)) != NODE_EOF) {
11828 popstackmark(&smark);
11841 * The eval command.
11843 static int FAST_FUNC
11844 evalcmd(int argc UNUSED_PARAM, char **argv)
11853 STARTSTACKSTR(concat);
11855 concat = stack_putstr(p, concat);
11859 STPUTC(' ', concat);
11861 STPUTC('\0', concat);
11862 p = grabstackstr(concat);
11864 evalstring(p, ~SKIPEVAL);
11871 * Read and execute commands.
11872 * "Top" is nonzero for the top level command loop;
11873 * it turns on prompting if the shell is interactive.
11879 struct stackmark smark;
11883 TRACE(("cmdloop(%d) called\n", top));
11887 setstackmark(&smark);
11890 showjobs(stderr, SHOW_CHANGED);
11893 if (iflag && top) {
11895 #if ENABLE_ASH_MAIL
11899 n = parsecmd(inter);
11901 if (DEBUG > 2 && debug && (n != NODE_EOF))
11904 if (n == NODE_EOF) {
11905 if (!top || numeof >= 50)
11907 if (!stoppedjobs()) {
11910 out2str("\nUse \"exit\" to leave shell.\n");
11913 } else if (nflag == 0) {
11914 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11919 popstackmark(&smark);
11924 return skip & SKIPEVAL;
11931 * Take commands from a file. To be compatible we should do a path
11932 * search for the file, which is necessary to find sub-commands.
11935 find_dot_file(char *name)
11938 const char *path = pathval();
11941 /* don't try this for absolute or relative paths */
11942 if (strchr(name, '/'))
11945 /* IIRC standards do not say whether . is to be searched.
11946 * And it is even smaller this way, making it unconditional for now:
11948 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11953 while ((fullname = path_advance(&path, name)) != NULL) {
11955 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11957 * Don't bother freeing here, since it will
11958 * be freed by the caller.
11962 if (fullname != name)
11963 stunalloc(fullname);
11966 /* not found in the PATH */
11967 ash_msg_and_raise_error("%s: not found", name);
11971 static int FAST_FUNC
11972 dotcmd(int argc, char **argv)
11974 struct strlist *sp;
11975 volatile struct shparam saveparam;
11978 for (sp = cmdenviron; sp; sp = sp->next)
11979 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
11981 if (argv[1]) { /* That's what SVR2 does */
11982 char *fullname = find_dot_file(argv[1]);
11985 if (argc) { /* argc > 0, argv[0] != NULL */
11986 saveparam = shellparam;
11987 shellparam.malloced = 0;
11988 shellparam.nparam = argc;
11989 shellparam.p = argv;
11992 setinputfile(fullname, INPUT_PUSH_FILE);
11993 commandname = fullname;
11998 freeparam(&shellparam);
11999 shellparam = saveparam;
12001 status = exitstatus;
12006 static int FAST_FUNC
12007 exitcmd(int argc UNUSED_PARAM, char **argv)
12012 exitstatus = number(argv[1]);
12013 raise_exception(EXEXIT);
12018 * Read a file containing shell functions.
12021 readcmdfile(char *name)
12023 setinputfile(name, INPUT_PUSH_FILE);
12029 /* ============ find_command inplementation */
12032 * Resolve a command name. If you change this routine, you may have to
12033 * change the shellexec routine as well.
12036 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12038 struct tblentry *cmdp;
12045 struct builtincmd *bcmd;
12047 /* If name contains a slash, don't use PATH or hash table */
12048 if (strchr(name, '/') != NULL) {
12049 entry->u.index = -1;
12050 if (act & DO_ABS) {
12051 while (stat(name, &statb) < 0) {
12053 if (errno == EINTR)
12056 entry->cmdtype = CMDUNKNOWN;
12060 entry->cmdtype = CMDNORMAL;
12064 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12066 updatetbl = (path == pathval());
12069 if (strstr(path, "%builtin") != NULL)
12070 act |= DO_ALTBLTIN;
12073 /* If name is in the table, check answer will be ok */
12074 cmdp = cmdlookup(name, 0);
12075 if (cmdp != NULL) {
12078 switch (cmdp->cmdtype) {
12096 } else if (cmdp->rehash == 0)
12097 /* if not invalidated by cd, we're done */
12101 /* If %builtin not in path, check for builtin next */
12102 bcmd = find_builtin(name);
12104 if (IS_BUILTIN_REGULAR(bcmd))
12105 goto builtin_success;
12106 if (act & DO_ALTPATH) {
12107 if (!(act & DO_ALTBLTIN))
12108 goto builtin_success;
12109 } else if (builtinloc <= 0) {
12110 goto builtin_success;
12114 #if ENABLE_FEATURE_SH_STANDALONE
12116 int applet_no = find_applet_by_name(name);
12117 if (applet_no >= 0) {
12118 entry->cmdtype = CMDNORMAL;
12119 entry->u.index = -2 - applet_no;
12125 /* We have to search path. */
12126 prev = -1; /* where to start */
12127 if (cmdp && cmdp->rehash) { /* doing a rehash */
12128 if (cmdp->cmdtype == CMDBUILTIN)
12131 prev = cmdp->param.index;
12137 while ((fullname = path_advance(&path, name)) != NULL) {
12138 stunalloc(fullname);
12139 /* NB: code below will still use fullname
12140 * despite it being "unallocated" */
12143 if (prefix(pathopt, "builtin")) {
12145 goto builtin_success;
12148 if ((act & DO_NOFUNC)
12149 || !prefix(pathopt, "func")
12150 ) { /* ignore unimplemented options */
12154 /* if rehash, don't redo absolute path names */
12155 if (fullname[0] == '/' && idx <= prev) {
12158 TRACE(("searchexec \"%s\": no change\n", name));
12161 while (stat(fullname, &statb) < 0) {
12163 if (errno == EINTR)
12166 if (errno != ENOENT && errno != ENOTDIR)
12170 e = EACCES; /* if we fail, this will be the error */
12171 if (!S_ISREG(statb.st_mode))
12173 if (pathopt) { /* this is a %func directory */
12174 stalloc(strlen(fullname) + 1);
12175 /* NB: stalloc will return space pointed by fullname
12176 * (because we don't have any intervening allocations
12177 * between stunalloc above and this stalloc) */
12178 readcmdfile(fullname);
12179 cmdp = cmdlookup(name, 0);
12180 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12181 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12182 stunalloc(fullname);
12185 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12187 entry->cmdtype = CMDNORMAL;
12188 entry->u.index = idx;
12192 cmdp = cmdlookup(name, 1);
12193 cmdp->cmdtype = CMDNORMAL;
12194 cmdp->param.index = idx;
12199 /* We failed. If there was an entry for this command, delete it */
12200 if (cmdp && updatetbl)
12201 delete_cmd_entry();
12203 ash_msg("%s: %s", name, errmsg(e, "not found"));
12204 entry->cmdtype = CMDUNKNOWN;
12209 entry->cmdtype = CMDBUILTIN;
12210 entry->u.cmd = bcmd;
12214 cmdp = cmdlookup(name, 1);
12215 cmdp->cmdtype = CMDBUILTIN;
12216 cmdp->param.cmd = bcmd;
12220 entry->cmdtype = cmdp->cmdtype;
12221 entry->u = cmdp->param;
12225 /* ============ trap.c */
12228 * The trap builtin.
12230 static int FAST_FUNC
12231 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12240 for (signo = 0; signo < NSIG; signo++) {
12241 char *tr = trap_ptr[signo];
12243 /* note: bash adds "SIG", but only if invoked
12244 * as "bash". If called as "sh", or if set -o posix,
12245 * then it prints short signal names.
12246 * We are printing short names: */
12247 out1fmt("trap -- %s %s\n",
12249 get_signame(signo));
12250 /* trap_ptr != trap only if we are in special-cased `trap` code.
12251 * In this case, we will exit very soon, no need to free(). */
12252 /* if (trap_ptr != trap && tp[0]) */
12257 if (trap_ptr != trap) {
12269 signo = get_signum(*ap);
12271 ash_msg_and_raise_error("%s: bad trap", *ap);
12274 if (LONE_DASH(action))
12277 action = ckstrdup(action);
12280 trap[signo] = action;
12290 /* ============ Builtins */
12292 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12294 * Lists available builtins
12296 static int FAST_FUNC
12297 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12303 "Built-in commands:\n"
12304 "------------------\n");
12305 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12306 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12307 builtintab[i].name + 1);
12313 #if ENABLE_FEATURE_SH_STANDALONE
12315 const char *a = applet_names;
12317 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12322 a += strlen(a) + 1;
12327 return EXIT_SUCCESS;
12329 #endif /* FEATURE_SH_EXTRA_QUIET */
12332 * The export and readonly commands.
12334 static int FAST_FUNC
12335 exportcmd(int argc UNUSED_PARAM, char **argv)
12341 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12343 if (nextopt("p") != 'p') {
12348 p = strchr(name, '=');
12352 vp = *findvar(hashvar(name), name);
12358 setvar(name, p, flag);
12359 } while ((name = *++aptr) != NULL);
12363 showvars(argv[0], flag, 0);
12368 * Delete a function if it exists.
12371 unsetfunc(const char *name)
12373 struct tblentry *cmdp;
12375 cmdp = cmdlookup(name, 0);
12376 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12377 delete_cmd_entry();
12381 * The unset builtin command. We unset the function before we unset the
12382 * variable to allow a function to be unset when there is a readonly variable
12383 * with the same name.
12385 static int FAST_FUNC
12386 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12393 while ((i = nextopt("vf")) != '\0') {
12397 for (ap = argptr; *ap; ap++) {
12413 #include <sys/times.h>
12415 static const unsigned char timescmd_str[] ALIGN1 = {
12416 ' ', offsetof(struct tms, tms_utime),
12417 '\n', offsetof(struct tms, tms_stime),
12418 ' ', offsetof(struct tms, tms_cutime),
12419 '\n', offsetof(struct tms, tms_cstime),
12423 static int FAST_FUNC
12424 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12426 long clk_tck, s, t;
12427 const unsigned char *p;
12430 clk_tck = sysconf(_SC_CLK_TCK);
12435 t = *(clock_t *)(((char *) &buf) + p[1]);
12437 out1fmt("%ldm%ld.%.3lds%c",
12439 ((t - s * clk_tck) * 1000) / clk_tck,
12441 } while (*(p += 2));
12446 #if ENABLE_SH_MATH_SUPPORT
12448 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12449 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12451 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12453 static int FAST_FUNC
12454 letcmd(int argc UNUSED_PARAM, char **argv)
12460 ash_msg_and_raise_error("expression expected");
12462 i = ash_arith(*argv);
12467 #endif /* SH_MATH_SUPPORT */
12470 /* ============ miscbltin.c
12472 * Miscellaneous builtins.
12477 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
12478 typedef enum __rlimit_resource rlim_t;
12482 * The read builtin. Options:
12483 * -r Do not interpret '\' specially
12484 * -s Turn off echo (tty only)
12485 * -n NCHARS Read NCHARS max
12486 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12487 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12488 * -u FD Read from given FD instead of fd 0
12489 * This uses unbuffered input, which may be avoidable in some cases.
12490 * TODO: bash also has:
12491 * -a ARRAY Read into array[0],[1],etc
12492 * -d DELIM End on DELIM char, not newline
12493 * -e Use line editing (tty only)
12495 static int FAST_FUNC
12496 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12498 char *opt_n = NULL;
12499 char *opt_p = NULL;
12500 char *opt_t = NULL;
12501 char *opt_u = NULL;
12502 int read_flags = 0;
12506 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12515 read_flags |= BUILTIN_READ_SILENT;
12521 read_flags |= BUILTIN_READ_RAW;
12531 r = shell_builtin_read(setvar2,
12533 bltinlookup("IFS"), /* can be NULL */
12541 if ((uintptr_t)r > 1)
12542 ash_msg_and_raise_error(r);
12544 return (uintptr_t)r;
12547 static int FAST_FUNC
12548 umaskcmd(int argc UNUSED_PARAM, char **argv)
12550 static const char permuser[3] ALIGN1 = "ugo";
12551 static const char permmode[3] ALIGN1 = "rwx";
12552 static const short permmask[] ALIGN2 = {
12553 S_IRUSR, S_IWUSR, S_IXUSR,
12554 S_IRGRP, S_IWGRP, S_IXGRP,
12555 S_IROTH, S_IWOTH, S_IXOTH
12558 /* TODO: use bb_parse_mode() instead */
12563 int symbolic_mode = 0;
12565 while (nextopt("S") != '\0') {
12576 if (symbolic_mode) {
12580 for (i = 0; i < 3; i++) {
12583 *p++ = permuser[i];
12585 for (j = 0; j < 3; j++) {
12586 if ((mask & permmask[3 * i + j]) == 0) {
12587 *p++ = permmode[j];
12595 out1fmt("%.4o\n", mask);
12598 if (isdigit((unsigned char) *ap)) {
12601 if (*ap >= '8' || *ap < '0')
12602 ash_msg_and_raise_error(msg_illnum, argv[1]);
12603 mask = (mask << 3) + (*ap - '0');
12604 } while (*++ap != '\0');
12607 mask = ~mask & 0777;
12608 if (!bb_parse_mode(ap, &mask)) {
12609 ash_msg_and_raise_error("illegal mode: %s", ap);
12611 umask(~mask & 0777);
12620 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12621 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12622 * ash by J.T. Conklin.
12627 uint8_t cmd; /* RLIMIT_xxx fit into it */
12628 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
12632 static const struct limits limits_tbl[] = {
12634 { RLIMIT_CPU, 0, 't' },
12636 #ifdef RLIMIT_FSIZE
12637 { RLIMIT_FSIZE, 9, 'f' },
12640 { RLIMIT_DATA, 10, 'd' },
12642 #ifdef RLIMIT_STACK
12643 { RLIMIT_STACK, 10, 's' },
12646 { RLIMIT_CORE, 9, 'c' },
12649 { RLIMIT_RSS, 10, 'm' },
12651 #ifdef RLIMIT_MEMLOCK
12652 { RLIMIT_MEMLOCK, 10, 'l' },
12654 #ifdef RLIMIT_NPROC
12655 { RLIMIT_NPROC, 0, 'p' },
12657 #ifdef RLIMIT_NOFILE
12658 { RLIMIT_NOFILE, 0, 'n' },
12661 { RLIMIT_AS, 10, 'v' },
12663 #ifdef RLIMIT_LOCKS
12664 { RLIMIT_LOCKS, 0, 'w' },
12667 static const char limits_name[] =
12669 "time(seconds)" "\0"
12671 #ifdef RLIMIT_FSIZE
12672 "file(blocks)" "\0"
12677 #ifdef RLIMIT_STACK
12681 "coredump(blocks)" "\0"
12686 #ifdef RLIMIT_MEMLOCK
12687 "locked memory(kb)" "\0"
12689 #ifdef RLIMIT_NPROC
12692 #ifdef RLIMIT_NOFILE
12698 #ifdef RLIMIT_LOCKS
12703 enum limtype { SOFT = 0x1, HARD = 0x2 };
12706 printlim(enum limtype how, const struct rlimit *limit,
12707 const struct limits *l)
12711 val = limit->rlim_max;
12713 val = limit->rlim_cur;
12715 if (val == RLIM_INFINITY)
12716 out1fmt("unlimited\n");
12718 val >>= l->factor_shift;
12719 out1fmt("%lld\n", (long long) val);
12723 static int FAST_FUNC
12724 ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12727 enum limtype how = SOFT | HARD;
12728 const struct limits *l;
12731 struct rlimit limit;
12734 while ((optc = nextopt("HSa"
12738 #ifdef RLIMIT_FSIZE
12744 #ifdef RLIMIT_STACK
12753 #ifdef RLIMIT_MEMLOCK
12756 #ifdef RLIMIT_NPROC
12759 #ifdef RLIMIT_NOFILE
12765 #ifdef RLIMIT_LOCKS
12783 for (l = limits_tbl; l->option != what; l++)
12786 set = *argptr ? 1 : 0;
12791 if (all || argptr[1])
12792 ash_msg_and_raise_error("too many arguments");
12793 if (strncmp(p, "unlimited\n", 9) == 0)
12794 val = RLIM_INFINITY;
12796 if (sizeof(val) == sizeof(int))
12797 val = bb_strtou(p, NULL, 10);
12798 else if (sizeof(val) == sizeof(long))
12799 val = bb_strtoul(p, NULL, 10);
12801 val = bb_strtoull(p, NULL, 10);
12803 ash_msg_and_raise_error("bad number");
12804 val <<= l->factor_shift;
12808 const char *lname = limits_name;
12809 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
12810 getrlimit(l->cmd, &limit);
12811 out1fmt("%-20s ", lname);
12812 lname += strlen(lname) + 1;
12813 printlim(how, &limit, l);
12818 getrlimit(l->cmd, &limit);
12821 limit.rlim_max = val;
12823 limit.rlim_cur = val;
12824 if (setrlimit(l->cmd, &limit) < 0)
12825 ash_msg_and_raise_error("error setting limit (%m)");
12827 printlim(how, &limit, l);
12832 /* ============ main() and helpers */
12835 * Called to exit the shell.
12837 static void exitshell(void) NORETURN;
12845 status = exitstatus;
12846 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12847 if (setjmp(loc.loc)) {
12848 if (exception_type == EXEXIT)
12849 /* dash bug: it just does _exit(exitstatus) here
12850 * but we have to do setjobctl(0) first!
12851 * (bug is still not fixed in dash-0.5.3 - if you run dash
12852 * under Midnight Commander, on exit from dash MC is backgrounded) */
12853 status = exitstatus;
12856 exception_handler = &loc;
12863 flush_stdout_stderr();
12873 /* from input.c: */
12874 basepf.next_to_pgetc = basepf.buf = basebuf;
12877 signal(SIGCHLD, SIG_DFL);
12878 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12879 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12881 signal(SIGHUP, SIG_DFL);
12887 struct stat st1, st2;
12890 for (envp = environ; envp && *envp; envp++) {
12891 if (strchr(*envp, '=')) {
12892 setvareq(*envp, VEXPORT|VTEXTFIXED);
12896 setvar("PPID", utoa(getppid()), 0);
12898 p = lookupvar("PWD");
12900 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12901 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12908 * Process the shell command line arguments.
12911 procargs(char **argv)
12914 const char *xminusc;
12919 /* if (xargv[0]) - mmm, this is always true! */
12921 for (i = 0; i < NOPTS; i++)
12925 /* it already printed err message */
12926 raise_exception(EXERROR);
12930 if (*xargv == NULL) {
12932 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12935 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12939 for (i = 0; i < NOPTS; i++)
12940 if (optlist[i] == 2)
12945 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12950 } else if (!sflag) {
12951 setinputfile(*xargv, 0);
12954 commandname = arg0;
12957 shellparam.p = xargv;
12958 #if ENABLE_ASH_GETOPTS
12959 shellparam.optind = 1;
12960 shellparam.optoff = -1;
12962 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
12964 shellparam.nparam++;
12971 * Read /etc/profile or .profile.
12974 read_profile(const char *name)
12978 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12987 * This routine is called when an error or an interrupt occurs in an
12988 * interactive shell and control is returned to the main command loop.
12996 /* from input.c: */
12997 g_parsefile->left_in_buffer = 0;
12998 g_parsefile->left_in_line = 0; /* clear input buffer */
13000 /* from parser.c: */
13003 /* from redir.c: */
13004 clearredir(/*drop:*/ 0);
13008 static short profile_buf[16384];
13009 extern int etext();
13013 * Main routine. We initialize things, parse the arguments, execute
13014 * profiles if we're a login shell, and then call cmdloop to execute
13015 * commands. The setjmp call sets up the location to jump to when an
13016 * exception occurs. When an exception occurs the variable "state"
13017 * is used to figure out how far we had gotten.
13019 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13020 int ash_main(int argc UNUSED_PARAM, char **argv)
13022 const char *shinit;
13023 volatile smallint state;
13024 struct jmploc jmploc;
13025 struct stackmark smark;
13027 /* Initialize global data */
13031 #if ENABLE_ASH_ALIAS
13037 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13040 #if ENABLE_FEATURE_EDITING
13041 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13044 if (setjmp(jmploc.loc)) {
13050 e = exception_type;
13054 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13057 outcslow('\n', stderr);
13059 popstackmark(&smark);
13060 FORCE_INT_ON; /* enable interrupts */
13069 exception_handler = &jmploc;
13072 TRACE(("Shell args: "));
13073 trace_puts_args(argv);
13075 rootpid = getpid();
13078 setstackmark(&smark);
13081 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13083 const char *hp = lookupvar("HISTFILE");
13086 hp = lookupvar("HOME");
13088 char *defhp = concat_path_file(hp, ".ash_history");
13089 setvar("HISTFILE", defhp, 0);
13095 if (/* argv[0] && */ argv[0][0] == '-')
13099 read_profile("/etc/profile");
13102 read_profile(".profile");
13108 getuid() == geteuid() && getgid() == getegid() &&
13112 shinit = lookupvar("ENV");
13113 if (shinit != NULL && *shinit != '\0') {
13114 read_profile(shinit);
13120 /* evalstring pushes parsefile stack.
13121 * Ensure we don't falsely claim that 0 (stdin)
13122 * is one of stacked source fds.
13123 * Testcase: ash -c 'exec 1>&0' must not complain. */
13125 g_parsefile->fd = -1;
13126 evalstring(minusc, 0);
13129 if (sflag || minusc == NULL) {
13130 #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13132 const char *hp = lookupvar("HISTFILE");
13134 line_input_state->hist_file = hp;
13137 state4: /* XXX ??? - why isn't this before the "if" statement */
13145 extern void _mcleanup(void);
13155 * Copyright (c) 1989, 1991, 1993, 1994
13156 * The Regents of the University of California. All rights reserved.
13158 * This code is derived from software contributed to Berkeley by
13159 * Kenneth Almquist.
13161 * Redistribution and use in source and binary forms, with or without
13162 * modification, are permitted provided that the following conditions
13164 * 1. Redistributions of source code must retain the above copyright
13165 * notice, this list of conditions and the following disclaimer.
13166 * 2. Redistributions in binary form must reproduce the above copyright
13167 * notice, this list of conditions and the following disclaimer in the
13168 * documentation and/or other materials provided with the distribution.
13169 * 3. Neither the name of the University nor the names of its contributors
13170 * may be used to endorse or promote products derived from this software
13171 * without specific prior written permission.
13173 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13174 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13175 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13176 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13177 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13178 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13179 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13180 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13181 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13182 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF