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 */
76 #if defined(__uClinux__)
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[] = {
1772 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1774 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
1777 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1778 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1780 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1781 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1782 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1783 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1784 #if ENABLE_ASH_GETOPTS
1785 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1787 #if ENABLE_ASH_RANDOM_SUPPORT
1788 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
1790 #if ENABLE_LOCALE_SUPPORT
1791 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1792 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
1794 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1795 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
1801 struct globals_var {
1802 struct shparam shellparam; /* $@ current positional parameters */
1803 struct redirtab *redirlist;
1805 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1806 struct var *vartab[VTABSIZE];
1807 struct var varinit[ARRAY_SIZE(varinit_data)];
1809 extern struct globals_var *const ash_ptr_to_globals_var;
1810 #define G_var (*ash_ptr_to_globals_var)
1811 #define shellparam (G_var.shellparam )
1812 //#define redirlist (G_var.redirlist )
1813 #define g_nullredirs (G_var.g_nullredirs )
1814 #define preverrout_fd (G_var.preverrout_fd)
1815 #define vartab (G_var.vartab )
1816 #define varinit (G_var.varinit )
1817 #define INIT_G_var() do { \
1819 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1821 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1822 varinit[i].flags = varinit_data[i].flags; \
1823 varinit[i].text = varinit_data[i].text; \
1824 varinit[i].func = varinit_data[i].func; \
1828 #define vifs varinit[0]
1830 # define vmail (&vifs)[1]
1831 # define vmpath (&vmail)[1]
1832 # define vpath (&vmpath)[1]
1834 # define vpath (&vifs)[1]
1836 #define vps1 (&vpath)[1]
1837 #define vps2 (&vps1)[1]
1838 #define vps4 (&vps2)[1]
1839 #if ENABLE_ASH_GETOPTS
1840 # define voptind (&vps4)[1]
1841 # if ENABLE_ASH_RANDOM_SUPPORT
1842 # define vrandom (&voptind)[1]
1845 # if ENABLE_ASH_RANDOM_SUPPORT
1846 # define vrandom (&vps4)[1]
1851 * The following macros access the values of the above variables.
1852 * They have to skip over the name. They return the null string
1853 * for unset variables.
1855 #define ifsval() (vifs.text + 4)
1856 #define ifsset() ((vifs.flags & VUNSET) == 0)
1858 # define mailval() (vmail.text + 5)
1859 # define mpathval() (vmpath.text + 9)
1860 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1862 #define pathval() (vpath.text + 5)
1863 #define ps1val() (vps1.text + 4)
1864 #define ps2val() (vps2.text + 4)
1865 #define ps4val() (vps4.text + 4)
1866 #if ENABLE_ASH_GETOPTS
1867 # define optindval() (voptind.text + 7)
1871 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1872 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1874 #if ENABLE_ASH_GETOPTS
1875 static void FAST_FUNC
1876 getoptsreset(const char *value)
1878 shellparam.optind = number(value);
1879 shellparam.optoff = -1;
1884 * Return of a legal variable name (a letter or underscore followed by zero or
1885 * more letters, underscores, and digits).
1888 endofname(const char *name)
1896 if (!is_in_name(*p))
1903 * Compares two strings up to the first = or '\0'. The first
1904 * string must be terminated by '='; the second may be terminated by
1905 * either '=' or '\0'.
1908 varcmp(const char *p, const char *q)
1912 while ((c = *p) == (d = *q)) {
1927 varequal(const char *a, const char *b)
1929 return !varcmp(a, b);
1933 * Find the appropriate entry in the hash table from the name.
1935 static struct var **
1936 hashvar(const char *p)
1940 hashval = ((unsigned char) *p) << 4;
1941 while (*p && *p != '=')
1942 hashval += (unsigned char) *p++;
1943 return &vartab[hashval % VTABSIZE];
1947 vpcmp(const void *a, const void *b)
1949 return varcmp(*(const char **)a, *(const char **)b);
1953 * This routine initializes the builtin variables.
1963 * PS1 depends on uid
1965 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1966 vps1.text = "PS1=\\w \\$ ";
1969 vps1.text = "PS1=# ";
1972 end = vp + ARRAY_SIZE(varinit);
1974 vpp = hashvar(vp->text);
1977 } while (++vp < end);
1980 static struct var **
1981 findvar(struct var **vpp, const char *name)
1983 for (; *vpp; vpp = &(*vpp)->next) {
1984 if (varequal((*vpp)->text, name)) {
1992 * Find the value of a variable. Returns NULL if not set.
1995 lookupvar(const char *name)
1999 v = *findvar(hashvar(name), name);
2001 #if ENABLE_ASH_RANDOM_SUPPORT
2003 * Dynamic variables are implemented roughly the same way they are
2004 * in bash. Namely, they're "special" so long as they aren't unset.
2005 * As soon as they're unset, they're no longer dynamic, and dynamic
2006 * lookup will no longer happen at that point. -- PFM.
2008 if ((v->flags & VDYNAMIC))
2011 if (!(v->flags & VUNSET))
2012 return strchrnul(v->text, '=') + 1;
2018 * Search the environment of a builtin command.
2021 bltinlookup(const char *name)
2025 for (sp = cmdenviron; sp; sp = sp->next) {
2026 if (varequal(sp->text, name))
2027 return strchrnul(sp->text, '=') + 1;
2029 return lookupvar(name);
2033 * Same as setvar except that the variable and value are passed in
2034 * the first argument as name=value. Since the first argument will
2035 * be actually stored in the table, it should not be a string that
2037 * Called with interrupts off.
2040 setvareq(char *s, int flags)
2042 struct var *vp, **vpp;
2045 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2046 vp = *findvar(vpp, s);
2048 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2051 if (flags & VNOSAVE)
2054 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2060 if (vp->func && (flags & VNOFUNC) == 0)
2061 (*vp->func)(strchrnul(s, '=') + 1);
2063 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2064 free((char*)vp->text);
2066 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2071 vp = ckzalloc(sizeof(*vp));
2073 /*vp->func = NULL; - ckzalloc did it */
2076 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2083 * Set the value of a variable. The flags argument is ored with the
2084 * flags of the variable. If val is NULL, the variable is unset.
2087 setvar(const char *name, const char *val, int flags)
2094 q = endofname(name);
2095 p = strchrnul(q, '=');
2097 if (!namelen || p != q)
2098 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2103 vallen = strlen(val);
2106 nameeq = ckmalloc(namelen + vallen + 2);
2107 p = (char *)memcpy(nameeq, name, namelen) + namelen;
2110 p = (char *)memcpy(p, val, vallen) + vallen;
2113 setvareq(nameeq, flags | VNOSAVE);
2117 #if ENABLE_ASH_GETOPTS
2119 * Safe version of setvar, returns 1 on success 0 on failure.
2122 setvarsafe(const char *name, const char *val, int flags)
2125 volatile int saveint;
2126 struct jmploc *volatile savehandler = exception_handler;
2127 struct jmploc jmploc;
2130 if (setjmp(jmploc.loc))
2133 exception_handler = &jmploc;
2134 setvar(name, val, flags);
2137 exception_handler = savehandler;
2138 RESTORE_INT(saveint);
2144 * Unset the specified variable.
2147 unsetvar(const char *s)
2153 vpp = findvar(hashvar(s), s);
2157 int flags = vp->flags;
2160 if (flags & VREADONLY)
2162 #if ENABLE_ASH_RANDOM_SUPPORT
2163 vp->flags &= ~VDYNAMIC;
2167 if ((flags & VSTRFIXED) == 0) {
2169 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2170 free((char*)vp->text);
2176 vp->flags &= ~VEXPORT;
2186 * Process a linked list of variable assignments.
2189 listsetvar(struct strlist *list_set_var, int flags)
2191 struct strlist *lp = list_set_var;
2197 setvareq(lp->text, flags);
2204 * Generate a list of variables satisfying the given conditions.
2207 listvars(int on, int off, char ***end)
2218 for (vp = *vpp; vp; vp = vp->next) {
2219 if ((vp->flags & mask) == on) {
2220 if (ep == stackstrend())
2221 ep = growstackstr();
2222 *ep++ = (char *) vp->text;
2225 } while (++vpp < vartab + VTABSIZE);
2226 if (ep == stackstrend())
2227 ep = growstackstr();
2231 return grabstackstr(ep);
2235 /* ============ Path search helper
2237 * The variable path (passed by reference) should be set to the start
2238 * of the path before the first call; path_advance will update
2239 * this value as it proceeds. Successive calls to path_advance will return
2240 * the possible path expansions in sequence. If an option (indicated by
2241 * a percent sign) appears in the path entry then the global variable
2242 * pathopt will be set to point to it; otherwise pathopt will be set to
2245 static const char *pathopt; /* set by path_advance */
2248 path_advance(const char **path, const char *name)
2258 for (p = start; *p && *p != ':' && *p != '%'; p++)
2260 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2261 while (stackblocksize() < len)
2265 memcpy(q, start, p - start);
2273 while (*p && *p != ':')
2280 return stalloc(len);
2284 /* ============ Prompt */
2286 static smallint doprompt; /* if set, prompt the user */
2287 static smallint needprompt; /* true if interactive and at start of line */
2289 #if ENABLE_FEATURE_EDITING
2290 static line_input_t *line_input_state;
2291 static const char *cmdedit_prompt;
2293 putprompt(const char *s)
2295 if (ENABLE_ASH_EXPAND_PRMT) {
2296 free((char*)cmdedit_prompt);
2297 cmdedit_prompt = ckstrdup(s);
2304 putprompt(const char *s)
2310 #if ENABLE_ASH_EXPAND_PRMT
2311 /* expandstr() needs parsing machinery, so it is far away ahead... */
2312 static const char *expandstr(const char *ps);
2314 #define expandstr(s) s
2318 setprompt(int whichprompt)
2321 #if ENABLE_ASH_EXPAND_PRMT
2322 struct stackmark smark;
2327 switch (whichprompt) {
2337 #if ENABLE_ASH_EXPAND_PRMT
2338 setstackmark(&smark);
2339 stalloc(stackblocksize());
2341 putprompt(expandstr(prompt));
2342 #if ENABLE_ASH_EXPAND_PRMT
2343 popstackmark(&smark);
2348 /* ============ The cd and pwd commands */
2350 #define CD_PHYSICAL 1
2360 while ((i = nextopt("LP")) != '\0') {
2362 flags ^= CD_PHYSICAL;
2371 * Update curdir (the name of the current directory) in response to a
2375 updatepwd(const char *dir)
2382 cdcomppath = ststrdup(dir);
2385 if (curdir == nullstr)
2387 new = stack_putstr(curdir, new);
2389 new = makestrspace(strlen(dir) + 2, new);
2390 lim = (char *)stackblock() + 1;
2394 if (new > lim && *lim == '/')
2399 if (dir[1] == '/' && dir[2] != '/') {
2405 p = strtok(cdcomppath, "/");
2409 if (p[1] == '.' && p[2] == '\0') {
2421 new = stack_putstr(p, new);
2429 return stackblock();
2433 * Find out what the current directory is. If we already know the current
2434 * directory, this routine returns immediately.
2439 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2440 return dir ? dir : nullstr;
2444 setpwd(const char *val, int setold)
2448 oldcur = dir = curdir;
2451 setvar("OLDPWD", oldcur, VEXPORT);
2454 if (physdir != nullstr) {
2455 if (physdir != oldcur)
2459 if (oldcur == val || !val) {
2465 dir = ckstrdup(val);
2466 if (oldcur != dir && oldcur != nullstr) {
2471 setvar("PWD", dir, VEXPORT);
2474 static void hashcd(void);
2477 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2478 * know that the current directory has changed.
2481 docd(const char *dest, int flags)
2483 const char *dir = 0;
2486 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2489 if (!(flags & CD_PHYSICAL)) {
2490 dir = updatepwd(dest);
2504 static int FAST_FUNC
2505 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2517 dest = bltinlookup(homestr);
2518 else if (LONE_DASH(dest)) {
2519 dest = bltinlookup("OLDPWD");
2541 path = bltinlookup("CDPATH");
2550 p = path_advance(&path, dest);
2551 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2555 if (!docd(p, flags))
2560 ash_msg_and_raise_error("can't cd to %s", dest);
2563 if (flags & CD_PRINT)
2564 out1fmt(snlfmt, curdir);
2568 static int FAST_FUNC
2569 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2572 const char *dir = curdir;
2576 if (physdir == nullstr)
2580 out1fmt(snlfmt, dir);
2585 /* ============ ... */
2588 #define IBUFSIZ COMMON_BUFSIZE
2589 /* buffer for top level input file */
2590 #define basebuf bb_common_bufsiz1
2592 /* Syntax classes */
2593 #define CWORD 0 /* character is nothing special */
2594 #define CNL 1 /* newline character */
2595 #define CBACK 2 /* a backslash character */
2596 #define CSQUOTE 3 /* single quote */
2597 #define CDQUOTE 4 /* double quote */
2598 #define CENDQUOTE 5 /* a terminating quote */
2599 #define CBQUOTE 6 /* backwards single quote */
2600 #define CVAR 7 /* a dollar sign */
2601 #define CENDVAR 8 /* a '}' character */
2602 #define CLP 9 /* a left paren in arithmetic */
2603 #define CRP 10 /* a right paren in arithmetic */
2604 #define CENDFILE 11 /* end of file */
2605 #define CCTL 12 /* like CWORD, except it must be escaped */
2606 #define CSPCL 13 /* these terminate a word */
2607 #define CIGN 14 /* character should be ignored */
2610 #if ENABLE_ASH_ALIAS
2614 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2616 #if ENABLE_SH_MATH_SUPPORT
2617 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2619 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2621 static const uint16_t S_I_T[] = {
2622 #if ENABLE_ASH_ALIAS
2623 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2625 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2626 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2627 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2628 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2629 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2630 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2631 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2632 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2633 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2634 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2635 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2636 #if !USE_SIT_FUNCTION
2637 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2638 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2639 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2643 /* Constants below must match table above */
2645 #if ENABLE_ASH_ALIAS
2646 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2648 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2649 CNL_CNL_CNL_CNL , /* 2 */
2650 CWORD_CCTL_CCTL_CWORD , /* 3 */
2651 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2652 CVAR_CVAR_CWORD_CVAR , /* 5 */
2653 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2654 CSPCL_CWORD_CWORD_CLP , /* 7 */
2655 CSPCL_CWORD_CWORD_CRP , /* 8 */
2656 CBACK_CBACK_CCTL_CBACK , /* 9 */
2657 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2658 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2659 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2660 CWORD_CWORD_CWORD_CWORD , /* 13 */
2661 CCTL_CCTL_CCTL_CCTL , /* 14 */
2664 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2665 * caller must ensure proper cast on it if c is *char_ptr!
2667 /* Values for syntax param */
2668 #define BASESYNTAX 0 /* not in quotes */
2669 #define DQSYNTAX 1 /* in double quotes */
2670 #define SQSYNTAX 2 /* in single quotes */
2671 #define ARISYNTAX 3 /* in arithmetic */
2672 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2674 #if USE_SIT_FUNCTION
2677 SIT(int c, int syntax)
2679 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2680 # if ENABLE_ASH_ALIAS
2681 static const uint8_t syntax_index_table[] ALIGN1 = {
2682 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2683 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2684 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2688 static const uint8_t syntax_index_table[] ALIGN1 = {
2689 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2690 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2691 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2700 # if ENABLE_ASH_ALIAS
2706 /* Cast is purely for paranoia here,
2707 * just in case someone passed signed char to us */
2708 if ((unsigned char)c >= CTL_FIRST
2709 && (unsigned char)c <= CTL_LAST
2713 s = strchrnul(spec_symbls, c);
2716 indx = syntax_index_table[s - spec_symbls];
2718 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2721 #else /* !USE_SIT_FUNCTION */
2723 static const uint8_t syntax_index_table[] = {
2724 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2725 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2726 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2727 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2728 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2735 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2736 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2738 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2739 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2758 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2759 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2760 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2761 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2762 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2763 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2764 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2765 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2766 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2767 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2768 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2769 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2770 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2771 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2772 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2773 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2774 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2775 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2776 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2777 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2778 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2779 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2780 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2781 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2782 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2783 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2784 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2785 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2786 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2787 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2788 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2789 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2790 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2791 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2792 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2793 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2794 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2795 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2796 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2797 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2800 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2802 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2803 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2814 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2815 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2816 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2817 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2818 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2819 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2820 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2821 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2822 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2823 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2824 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2825 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2848 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2849 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2850 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2851 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2852 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2853 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2855 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2856 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2857 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2858 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2859 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2860 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2861 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2862 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 162 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 163 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 164 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 165 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 166 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 167 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 168 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 169 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 170 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 171 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 172 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 173 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 174 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 175 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 176 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 177 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 178 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 179 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 180 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 181 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 182 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 183 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 184 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 185 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 186 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 187 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 188 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 189 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 190 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 191 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 192 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 193 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 194 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 195 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 196 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 197 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 198 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 199 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 200 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 201 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 202 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 203 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 204 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 205 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 206 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 207 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 208 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 209 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 210 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 211 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 212 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 213 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 214 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 215 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 216 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 217 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 218 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 219 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 220 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 221 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 222 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 223 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 224 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 225 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 226 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 227 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 228 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 229 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 231 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 232 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 233 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 234 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 235 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 236 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 237 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 238 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 239 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 241 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 242 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 243 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 244 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 245 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 246 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 247 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 248 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 249 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 250 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 251 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 252 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 253 */ CWORD_CWORD_CWORD_CWORD,
2979 /* 254 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 255 */ CWORD_CWORD_CWORD_CWORD,
2981 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2982 # if ENABLE_ASH_ALIAS
2983 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
2987 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
2989 #endif /* !USE_SIT_FUNCTION */
2992 /* ============ Alias handling */
2994 #if ENABLE_ASH_ALIAS
2996 #define ALIASINUSE 1
3007 static struct alias **atab; // [ATABSIZE];
3008 #define INIT_G_alias() do { \
3009 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3013 static struct alias **
3014 __lookupalias(const char *name) {
3015 unsigned int hashval;
3022 ch = (unsigned char)*p;
3026 ch = (unsigned char)*++p;
3028 app = &atab[hashval % ATABSIZE];
3030 for (; *app; app = &(*app)->next) {
3031 if (strcmp(name, (*app)->name) == 0) {
3039 static struct alias *
3040 lookupalias(const char *name, int check)
3042 struct alias *ap = *__lookupalias(name);
3044 if (check && ap && (ap->flag & ALIASINUSE))
3049 static struct alias *
3050 freealias(struct alias *ap)
3054 if (ap->flag & ALIASINUSE) {
3055 ap->flag |= ALIASDEAD;
3067 setalias(const char *name, const char *val)
3069 struct alias *ap, **app;
3071 app = __lookupalias(name);
3075 if (!(ap->flag & ALIASINUSE)) {
3078 ap->val = ckstrdup(val);
3079 ap->flag &= ~ALIASDEAD;
3082 ap = ckzalloc(sizeof(struct alias));
3083 ap->name = ckstrdup(name);
3084 ap->val = ckstrdup(val);
3085 /*ap->flag = 0; - ckzalloc did it */
3086 /*ap->next = NULL;*/
3093 unalias(const char *name)
3097 app = __lookupalias(name);
3101 *app = freealias(*app);
3112 struct alias *ap, **app;
3116 for (i = 0; i < ATABSIZE; i++) {
3118 for (ap = *app; ap; ap = *app) {
3119 *app = freealias(*app);
3129 printalias(const struct alias *ap)
3131 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3135 * TODO - sort output
3137 static int FAST_FUNC
3138 aliascmd(int argc UNUSED_PARAM, char **argv)
3147 for (i = 0; i < ATABSIZE; i++) {
3148 for (ap = atab[i]; ap; ap = ap->next) {
3154 while ((n = *++argv) != NULL) {
3155 v = strchr(n+1, '=');
3156 if (v == NULL) { /* n+1: funny ksh stuff */
3157 ap = *__lookupalias(n);
3159 fprintf(stderr, "%s: %s not found\n", "alias", n);
3172 static int FAST_FUNC
3173 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3177 while ((i = nextopt("a")) != '\0') {
3183 for (i = 0; *argptr; argptr++) {
3184 if (unalias(*argptr)) {
3185 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3193 #endif /* ASH_ALIAS */
3196 /* ============ jobs.c */
3198 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3201 #define FORK_NOJOB 2
3203 /* mode flags for showjob(s) */
3204 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3205 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3206 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3209 * A job structure contains information about a job. A job is either a
3210 * single process or a set of processes contained in a pipeline. In the
3211 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3215 pid_t ps_pid; /* process id */
3216 int ps_status; /* last process status from wait() */
3217 char *ps_cmd; /* text of command being run */
3221 struct procstat ps0; /* status of process */
3222 struct procstat *ps; /* status or processes when more than one */
3224 int stopstatus; /* status of a stopped job */
3227 nprocs: 16, /* number of processes */
3229 #define JOBRUNNING 0 /* at least one proc running */
3230 #define JOBSTOPPED 1 /* all procs are stopped */
3231 #define JOBDONE 2 /* all procs are completed */
3233 sigint: 1, /* job was killed by SIGINT */
3234 jobctl: 1, /* job running under job control */
3236 waited: 1, /* true if this entry has been waited for */
3237 used: 1, /* true if this entry is in used */
3238 changed: 1; /* true if status has changed */
3239 struct job *prev_job; /* previous job */
3242 static struct job *makejob(/*union node *,*/ int);
3243 static int forkshell(struct job *, union node *, int);
3244 static int waitforjob(struct job *);
3247 enum { doing_jobctl = 0 };
3248 #define setjobctl(on) do {} while (0)
3250 static smallint doing_jobctl; //references:8
3251 static void setjobctl(int);
3258 ignoresig(int signo)
3260 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3261 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3262 /* No, need to do it */
3263 signal(signo, SIG_IGN);
3265 sigmode[signo - 1] = S_HARD_IGN;
3269 * Signal handler. Only one usage site - in setsignal()
3274 gotsig[signo - 1] = 1;
3276 if (signo == SIGINT && !trap[SIGINT]) {
3277 if (!suppress_int) {
3279 raise_interrupt(); /* does not return */
3283 pending_sig = signo;
3288 * Set the signal handler for the specified signal. The routine figures
3289 * out what it should be set to.
3292 setsignal(int signo)
3295 char cur_act, new_act;
3296 struct sigaction act;
3300 if (t != NULL) { /* trap for this sig is set */
3302 if (t[0] == '\0') /* trap is "": ignore this sig */
3306 if (rootshell && new_act == S_DFL) {
3309 if (iflag || minusc || sflag == 0)
3318 * "In all cases, bash ignores SIGQUIT. Non-builtin
3319 * commands run by bash have signal handlers
3320 * set to the values inherited by the shell
3321 * from its parent". */
3337 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3338 //whereas we have to restore it to what shell got on entry
3339 //from the parent. See comment above
3341 t = &sigmode[signo - 1];
3344 /* current setting is not yet known */
3345 if (sigaction(signo, NULL, &act)) {
3346 /* pretend it worked; maybe we should give a warning,
3347 * but other shells don't. We don't alter sigmode,
3348 * so we retry every time.
3349 * btw, in Linux it never fails. --vda */
3352 if (act.sa_handler == SIG_IGN) {
3353 cur_act = S_HARD_IGN;
3355 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3357 cur_act = S_IGN; /* don't hard ignore these */
3361 if (cur_act == S_HARD_IGN || cur_act == new_act)
3364 act.sa_handler = SIG_DFL;
3367 act.sa_handler = onsig;
3368 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3369 sigfillset(&act.sa_mask); /* ditto */
3372 act.sa_handler = SIG_IGN;
3375 sigaction_set(signo, &act);
3380 /* mode flags for set_curjob */
3381 #define CUR_DELETE 2
3382 #define CUR_RUNNING 1
3383 #define CUR_STOPPED 0
3385 /* mode flags for dowait */
3386 #define DOWAIT_NONBLOCK WNOHANG
3387 #define DOWAIT_BLOCK 0
3390 /* pgrp of shell on invocation */
3391 static int initialpgrp; //references:2
3392 static int ttyfd = -1; //5
3395 static struct job *jobtab; //5
3397 static unsigned njobs; //4
3399 static struct job *curjob; //lots
3400 /* number of presumed living untracked jobs */
3401 static int jobless; //4
3404 set_curjob(struct job *jp, unsigned mode)
3407 struct job **jpp, **curp;
3409 /* first remove from list */
3410 jpp = curp = &curjob;
3415 jpp = &jp1->prev_job;
3417 *jpp = jp1->prev_job;
3419 /* Then re-insert in correct position */
3427 /* job being deleted */
3430 /* newly created job or backgrounded job,
3431 put after all stopped jobs. */
3435 if (!jp1 || jp1->state != JOBSTOPPED)
3438 jpp = &jp1->prev_job;
3444 /* newly stopped job - becomes curjob */
3445 jp->prev_job = *jpp;
3453 jobno(const struct job *jp)
3455 return jp - jobtab + 1;
3460 * Convert a job name to a job structure.
3463 #define getjob(name, getctl) getjob(name)
3466 getjob(const char *name, int getctl)
3470 const char *err_msg = "%s: no such job";
3474 char *(*match)(const char *, const char *);
3489 if (c == '+' || c == '%') {
3491 err_msg = "No current job";
3497 err_msg = "No previous job";
3508 jp = jobtab + num - 1;
3523 if (match(jp->ps[0].ps_cmd, p)) {
3527 err_msg = "%s: ambiguous";
3537 err_msg = "job %s not created under job control";
3538 if (getctl && jp->jobctl == 0)
3543 ash_msg_and_raise_error(err_msg, name);
3547 * Mark a job structure as unused.
3550 freejob(struct job *jp)
3552 struct procstat *ps;
3556 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3557 if (ps->ps_cmd != nullstr)
3560 if (jp->ps != &jp->ps0)
3563 set_curjob(jp, CUR_DELETE);
3569 xtcsetpgrp(int fd, pid_t pgrp)
3571 if (tcsetpgrp(fd, pgrp))
3572 ash_msg_and_raise_error("can't set tty process group (%m)");
3576 * Turn job control on and off.
3578 * Note: This code assumes that the third arg to ioctl is a character
3579 * pointer, which is true on Berkeley systems but not System V. Since
3580 * System V doesn't have job control yet, this isn't a problem now.
3582 * Called with interrupts off.
3590 if (on == doing_jobctl || rootshell == 0)
3594 ofd = fd = open(_PATH_TTY, O_RDWR);
3596 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3597 * That sometimes helps to acquire controlling tty.
3598 * Obviously, a workaround for bugs when someone
3599 * failed to provide a controlling tty to bash! :) */
3605 fd = fcntl(fd, F_DUPFD, 10);
3610 /* fd is a tty at this point */
3611 close_on_exec_on(fd);
3612 do { /* while we are in the background */
3613 pgrp = tcgetpgrp(fd);
3616 ash_msg("can't access tty; job control turned off");
3620 if (pgrp == getpgrp())
3631 xtcsetpgrp(fd, pgrp);
3633 /* turning job control off */
3636 /* was xtcsetpgrp, but this can make exiting ash
3637 * loop forever if pty is already deleted */
3638 tcsetpgrp(fd, pgrp);
3652 static int FAST_FUNC
3653 killcmd(int argc, char **argv)
3656 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3658 if (argv[i][0] == '%') {
3659 struct job *jp = getjob(argv[i], 0);
3660 unsigned pid = jp->ps[0].ps_pid;
3661 /* Enough space for ' -NNN<nul>' */
3662 argv[i] = alloca(sizeof(int)*3 + 3);
3663 /* kill_main has matching code to expect
3664 * leading space. Needed to not confuse
3665 * negative pids with "kill -SIGNAL_NO" syntax */
3666 sprintf(argv[i], " -%u", pid);
3668 } while (argv[++i]);
3670 return kill_main(argc, argv);
3674 showpipe(struct job *jp /*, FILE *out*/)
3676 struct procstat *ps;
3677 struct procstat *psend;
3679 psend = jp->ps + jp->nprocs;
3680 for (ps = jp->ps + 1; ps < psend; ps++)
3681 printf(" | %s", ps->ps_cmd);
3682 outcslow('\n', stdout);
3683 flush_stdout_stderr();
3688 restartjob(struct job *jp, int mode)
3690 struct procstat *ps;
3696 if (jp->state == JOBDONE)
3698 jp->state = JOBRUNNING;
3699 pgid = jp->ps[0].ps_pid;
3700 if (mode == FORK_FG)
3701 xtcsetpgrp(ttyfd, pgid);
3702 killpg(pgid, SIGCONT);
3706 if (WIFSTOPPED(ps->ps_status)) {
3712 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3717 static int FAST_FUNC
3718 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3724 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3728 jp = getjob(*argv, 1);
3729 if (mode == FORK_BG) {
3730 set_curjob(jp, CUR_RUNNING);
3731 printf("[%d] ", jobno(jp));
3733 out1str(jp->ps[0].ps_cmd);
3734 showpipe(jp /*, stdout*/);
3735 retval = restartjob(jp, mode);
3736 } while (*argv && *++argv);
3742 sprint_status(char *s, int status, int sigonly)
3748 if (!WIFEXITED(status)) {
3750 if (WIFSTOPPED(status))
3751 st = WSTOPSIG(status);
3754 st = WTERMSIG(status);
3756 if (st == SIGINT || st == SIGPIPE)
3759 if (WIFSTOPPED(status))
3764 col = fmtstr(s, 32, strsignal(st));
3765 if (WCOREDUMP(status)) {
3766 col += fmtstr(s + col, 16, " (core dumped)");
3768 } else if (!sigonly) {
3769 st = WEXITSTATUS(status);
3771 col = fmtstr(s, 16, "Done(%d)", st);
3773 col = fmtstr(s, 16, "Done");
3780 dowait(int wait_flags, struct job *job)
3785 struct job *thisjob;
3788 TRACE(("dowait(0x%x) called\n", wait_flags));
3790 /* Do a wait system call. If job control is compiled in, we accept
3791 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3792 * NB: _not_ safe_waitpid, we need to detect EINTR */
3794 wait_flags |= WUNTRACED;
3795 pid = waitpid(-1, &status, wait_flags);
3796 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3797 pid, status, errno, strerror(errno)));
3803 for (jp = curjob; jp; jp = jp->prev_job) {
3804 struct procstat *ps;
3805 struct procstat *psend;
3806 if (jp->state == JOBDONE)
3810 psend = ps + jp->nprocs;
3812 if (ps->ps_pid == pid) {
3813 TRACE(("Job %d: changing status of proc %d "
3814 "from 0x%x to 0x%x\n",
3815 jobno(jp), pid, ps->ps_status, status));
3816 ps->ps_status = status;
3819 if (ps->ps_status == -1)
3822 if (state == JOBRUNNING)
3824 if (WIFSTOPPED(ps->ps_status)) {
3825 jp->stopstatus = ps->ps_status;
3829 } while (++ps < psend);
3834 if (!WIFSTOPPED(status))
3840 if (state != JOBRUNNING) {
3841 thisjob->changed = 1;
3843 if (thisjob->state != state) {
3844 TRACE(("Job %d: changing state from %d to %d\n",
3845 jobno(thisjob), thisjob->state, state));
3846 thisjob->state = state;
3848 if (state == JOBSTOPPED) {
3849 set_curjob(thisjob, CUR_STOPPED);
3858 if (thisjob && thisjob == job) {
3862 len = sprint_status(s, status, 1);
3873 blocking_wait_with_raise_on_sig(struct job *job)
3875 pid_t pid = dowait(DOWAIT_BLOCK, job);
3876 if (pid <= 0 && pending_sig)
3877 raise_exception(EXSIG);
3883 showjob(FILE *out, struct job *jp, int mode)
3885 struct procstat *ps;
3886 struct procstat *psend;
3893 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
3894 /* just output process (group) id of pipeline */
3895 fprintf(out, "%d\n", ps->ps_pid);
3899 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3904 else if (curjob && jp == curjob->prev_job)
3907 if (mode & SHOW_PIDS)
3908 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
3910 psend = ps + jp->nprocs;
3912 if (jp->state == JOBRUNNING) {
3913 strcpy(s + col, "Running");
3914 col += sizeof("Running") - 1;
3916 int status = psend[-1].ps_status;
3917 if (jp->state == JOBSTOPPED)
3918 status = jp->stopstatus;
3919 col += sprint_status(s + col, status, 0);
3921 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
3923 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3924 * or prints several "PID | <cmdN>" lines,
3925 * depending on SHOW_PIDS bit.
3926 * We do not print status of individual processes
3927 * between PID and <cmdN>. bash does it, but not very well:
3928 * first line shows overall job status, not process status,
3929 * making it impossible to know 1st process status.
3933 /* for each process */
3936 if (mode & SHOW_PIDS)
3937 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
3939 fprintf(out, "%s%*c%s%s",
3941 33 - col >= 0 ? 33 - col : 0, ' ',
3942 ps == jp->ps ? "" : "| ",
3945 } while (++ps != psend);
3946 outcslow('\n', out);
3950 if (jp->state == JOBDONE) {
3951 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3957 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3958 * statuses have changed since the last call to showjobs.
3961 showjobs(FILE *out, int mode)
3965 TRACE(("showjobs(0x%x) called\n", mode));
3967 /* Handle all finished jobs */
3968 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
3971 for (jp = curjob; jp; jp = jp->prev_job) {
3972 if (!(mode & SHOW_CHANGED) || jp->changed) {
3973 showjob(out, jp, mode);
3978 static int FAST_FUNC
3979 jobscmd(int argc UNUSED_PARAM, char **argv)
3984 while ((m = nextopt("lp")) != '\0') {
3988 mode |= SHOW_ONLY_PGID;
3994 showjob(stdout, getjob(*argv, 0), mode);
3997 showjobs(stdout, mode);
4004 /* Called only on finished or stopped jobs (no members are running) */
4006 getstatus(struct job *job)
4010 struct procstat *ps;
4012 /* Fetch last member's status */
4013 ps = job->ps + job->nprocs - 1;
4014 status = ps->ps_status;
4016 /* "set -o pipefail" mode: use last _nonzero_ status */
4017 while (status == 0 && --ps >= job->ps)
4018 status = ps->ps_status;
4021 retval = WEXITSTATUS(status);
4022 if (!WIFEXITED(status)) {
4024 retval = WSTOPSIG(status);
4025 if (!WIFSTOPPED(status))
4028 /* XXX: limits number of signals */
4029 retval = WTERMSIG(status);
4031 if (retval == SIGINT)
4037 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4038 jobno(job), job->nprocs, status, retval));
4042 static int FAST_FUNC
4043 waitcmd(int argc UNUSED_PARAM, char **argv)
4050 raise_exception(EXSIG);
4057 /* wait for all jobs */
4061 if (!jp) /* no running procs */
4063 if (jp->state == JOBRUNNING)
4069 * "When bash is waiting for an asynchronous command via
4070 * the wait builtin, the reception of a signal for which a trap
4071 * has been set will cause the wait builtin to return immediately
4072 * with an exit status greater than 128, immediately after which
4073 * the trap is executed."
4074 * Do we do it that way? */
4075 blocking_wait_with_raise_on_sig(NULL);
4081 if (**argv != '%') {
4082 pid_t pid = number(*argv);
4087 if (job->ps[job->nprocs - 1].ps_pid == pid)
4089 job = job->prev_job;
4092 job = getjob(*argv, 0);
4093 /* loop until process terminated or stopped */
4094 while (job->state == JOBRUNNING)
4095 blocking_wait_with_raise_on_sig(NULL);
4097 retval = getstatus(job);
4110 struct job *jp, *jq;
4112 len = njobs * sizeof(*jp);
4114 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4116 offset = (char *)jp - (char *)jq;
4118 /* Relocate pointers */
4121 jq = (struct job *)((char *)jq + l);
4125 #define joff(p) ((struct job *)((char *)(p) + l))
4126 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4127 if (joff(jp)->ps == &jq->ps0)
4128 jmove(joff(jp)->ps);
4129 if (joff(jp)->prev_job)
4130 jmove(joff(jp)->prev_job);
4140 jp = (struct job *)((char *)jp + len);
4144 } while (--jq >= jp);
4149 * Return a new job structure.
4150 * Called with interrupts off.
4153 makejob(/*union node *node,*/ int nprocs)
4158 for (i = njobs, jp = jobtab; ; jp++) {
4165 if (jp->state != JOBDONE || !jp->waited)
4174 memset(jp, 0, sizeof(*jp));
4176 /* jp->jobctl is a bitfield.
4177 * "jp->jobctl |= jobctl" likely to give awful code */
4181 jp->prev_job = curjob;
4186 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4188 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4195 * Return a string identifying a command (to be printed by the
4198 static char *cmdnextc;
4201 cmdputs(const char *s)
4203 static const char vstype[VSTYPE + 1][3] = {
4204 "", "}", "-", "+", "?", "=",
4205 "%", "%%", "#", "##"
4206 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4209 const char *p, *str;
4213 unsigned char subtype = 0;
4217 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4219 while ((c = *p++) != '\0') {
4227 if ((subtype & VSTYPE) == VSLENGTH)
4231 if (!(subtype & VSQUOTE) == !(quoted & 1))
4237 str = "\"}" + !(quoted & 1);
4244 case CTLBACKQ+CTLQUOTE:
4247 #if ENABLE_SH_MATH_SUPPORT
4262 if ((subtype & VSTYPE) != VSNORMAL)
4264 str = vstype[subtype & VSTYPE];
4265 if (subtype & VSNUL)
4274 /* These can only happen inside quotes */
4287 while ((c = *str++) != '\0') {
4290 } /* while *p++ not NUL */
4293 USTPUTC('"', nextc);
4299 /* cmdtxt() and cmdlist() call each other */
4300 static void cmdtxt(union node *n);
4303 cmdlist(union node *np, int sep)
4305 for (; np; np = np->narg.next) {
4309 if (sep && np->narg.next)
4315 cmdtxt(union node *n)
4318 struct nodelist *lp;
4329 lp = n->npipe.cmdlist;
4347 cmdtxt(n->nbinary.ch1);
4363 cmdtxt(n->nif.test);
4365 if (n->nif.elsepart) {
4366 cmdtxt(n->nif.ifpart);
4368 n = n->nif.elsepart;
4386 cmdtxt(n->nbinary.ch1);
4396 cmdputs(n->nfor.var);
4398 cmdlist(n->nfor.args, 1);
4403 cmdputs(n->narg.text);
4407 cmdlist(n->ncmd.args, 1);
4408 cmdlist(n->ncmd.redirect, 0);
4421 cmdputs(n->ncase.expr->narg.text);
4423 for (np = n->ncase.cases; np; np = np->nclist.next) {
4424 cmdtxt(np->nclist.pattern);
4426 cmdtxt(np->nclist.body);
4440 #if ENABLE_ASH_BASH_COMPAT
4455 cmdputs(utoa(n->nfile.fd));
4457 if (n->type == NTOFD || n->type == NFROMFD) {
4458 cmdputs(utoa(n->ndup.dupfd));
4467 commandtext(union node *n)
4471 STARTSTACKSTR(cmdnextc);
4473 name = stackblock();
4474 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4475 name, cmdnextc, cmdnextc));
4476 return ckstrdup(name);
4481 * Fork off a subshell. If we are doing job control, give the subshell its
4482 * own process group. Jp is a job structure that the job is to be added to.
4483 * N is the command that will be evaluated by the child. Both jp and n may
4484 * be NULL. The mode parameter can be one of the following:
4485 * FORK_FG - Fork off a foreground process.
4486 * FORK_BG - Fork off a background process.
4487 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4488 * process group even if job control is on.
4490 * When job control is turned off, background processes have their standard
4491 * input redirected to /dev/null (except for the second and later processes
4494 * Called with interrupts off.
4497 * Clear traps on a fork.
4504 for (tp = trap; tp < &trap[NSIG]; tp++) {
4505 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4507 if (trap_ptr == trap)
4509 /* else: it "belongs" to trap_ptr vector, don't free */
4511 if ((tp - trap) != 0)
4512 setsignal(tp - trap);
4518 /* Lives far away from here, needed for forkchild */
4519 static void closescript(void);
4521 /* Called after fork(), in child */
4522 static NOINLINE void
4523 forkchild(struct job *jp, union node *n, int mode)
4527 TRACE(("Child shell %d\n", getpid()));
4531 /* man bash: "Non-builtin commands run by bash have signal handlers
4532 * set to the values inherited by the shell from its parent".
4533 * Do we do it correctly? */
4537 if (mode == FORK_NOJOB /* is it `xxx` ? */
4538 && n && n->type == NCMD /* is it single cmd? */
4539 /* && n->ncmd.args->type == NARG - always true? */
4540 && strcmp(n->ncmd.args->narg.text, "trap") == 0
4541 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4542 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4544 TRACE(("Trap hack\n"));
4545 /* Awful hack for `trap` or $(trap).
4547 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4548 * contains an example where "trap" is executed in a subshell:
4550 * save_traps=$(trap)
4552 * eval "$save_traps"
4554 * Standard does not say that "trap" in subshell shall print
4555 * parent shell's traps. It only says that its output
4556 * must have suitable form, but then, in the above example
4557 * (which is not supposed to be normative), it implies that.
4559 * bash (and probably other shell) does implement it
4560 * (traps are reset to defaults, but "trap" still shows them),
4561 * but as a result, "trap" logic is hopelessly messed up:
4564 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4565 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4566 * # true | trap <--- trap is in subshell - no output (ditto)
4567 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4568 * trap -- 'echo Ho' SIGWINCH
4569 * # echo `(trap)` <--- in subshell in subshell - output
4570 * trap -- 'echo Ho' SIGWINCH
4571 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4572 * trap -- 'echo Ho' SIGWINCH
4574 * The rules when to forget and when to not forget traps
4575 * get really complex and nonsensical.
4577 * Our solution: ONLY bare $(trap) or `trap` is special.
4579 /* Save trap handler strings for trap builtin to print */
4580 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4581 /* Fall through into clearing traps */
4585 /* do job control only in root shell */
4587 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4590 if (jp->nprocs == 0)
4593 pgrp = jp->ps[0].ps_pid;
4594 /* this can fail because we are doing it in the parent also */
4596 if (mode == FORK_FG)
4597 xtcsetpgrp(ttyfd, pgrp);
4602 if (mode == FORK_BG) {
4603 /* man bash: "When job control is not in effect,
4604 * asynchronous commands ignore SIGINT and SIGQUIT" */
4607 if (jp->nprocs == 0) {
4609 if (open(bb_dev_null, O_RDONLY) != 0)
4610 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4614 if (iflag) { /* why if iflag only? */
4619 * "In all cases, bash ignores SIGQUIT. Non-builtin
4620 * commands run by bash have signal handlers
4621 * set to the values inherited by the shell
4623 * Take care of the second rule: */
4627 if (n && n->type == NCMD
4628 && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4630 TRACE(("Job hack\n"));
4631 /* "jobs": we do not want to clear job list for it,
4632 * instead we remove only _its_ own_ job from job list.
4633 * This makes "jobs .... | cat" more useful.
4639 for (jp = curjob; jp; jp = jp->prev_job)
4644 /* Called after fork(), in parent */
4646 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4649 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4651 TRACE(("In parent shell: child = %d\n", pid));
4653 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4659 if (mode != FORK_NOJOB && jp->jobctl) {
4662 if (jp->nprocs == 0)
4665 pgrp = jp->ps[0].ps_pid;
4666 /* This can fail because we are doing it in the child also */
4670 if (mode == FORK_BG) {
4671 backgndpid = pid; /* set $! */
4672 set_curjob(jp, CUR_RUNNING);
4675 struct procstat *ps = &jp->ps[jp->nprocs++];
4678 ps->ps_cmd = nullstr;
4680 if (doing_jobctl && n)
4681 ps->ps_cmd = commandtext(n);
4687 forkshell(struct job *jp, union node *n, int mode)
4691 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4694 TRACE(("Fork failed, errno=%d", errno));
4697 ash_msg_and_raise_error("can't fork");
4700 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4701 forkchild(jp, n, mode);
4703 forkparent(jp, n, mode, pid);
4709 * Wait for job to finish.
4711 * Under job control we have the problem that while a child process
4712 * is running interrupts generated by the user are sent to the child
4713 * but not to the shell. This means that an infinite loop started by
4714 * an interactive user may be hard to kill. With job control turned off,
4715 * an interactive user may place an interactive program inside a loop.
4716 * If the interactive program catches interrupts, the user doesn't want
4717 * these interrupts to also abort the loop. The approach we take here
4718 * is to have the shell ignore interrupt signals while waiting for a
4719 * foreground process to terminate, and then send itself an interrupt
4720 * signal if the child process was terminated by an interrupt signal.
4721 * Unfortunately, some programs want to do a bit of cleanup and then
4722 * exit on interrupt; unless these processes terminate themselves by
4723 * sending a signal to themselves (instead of calling exit) they will
4724 * confuse this approach.
4726 * Called with interrupts off.
4729 waitforjob(struct job *jp)
4733 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4736 while (jp->state == JOBRUNNING) {
4737 /* In non-interactive shells, we _can_ get
4738 * a keyboard signal here and be EINTRed,
4739 * but we just loop back, waiting for command to complete.
4742 * "If bash is waiting for a command to complete and receives
4743 * a signal for which a trap has been set, the trap
4744 * will not be executed until the command completes."
4746 * Reality is that even if trap is not set, bash
4747 * will not act on the signal until command completes.
4748 * Try this. sleep5intoff.c:
4749 * #include <signal.h>
4750 * #include <unistd.h>
4753 * sigemptyset(&set);
4754 * sigaddset(&set, SIGINT);
4755 * sigaddset(&set, SIGQUIT);
4756 * sigprocmask(SIG_BLOCK, &set, NULL);
4760 * $ bash -c './sleep5intoff; echo hi'
4761 * ^C^C^C^C <--- pressing ^C once a second
4763 * $ bash -c './sleep5intoff; echo hi'
4764 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4767 dowait(DOWAIT_BLOCK, jp);
4774 xtcsetpgrp(ttyfd, rootpid);
4776 * This is truly gross.
4777 * If we're doing job control, then we did a TIOCSPGRP which
4778 * caused us (the shell) to no longer be in the controlling
4779 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4780 * intuit from the subprocess exit status whether a SIGINT
4781 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4783 if (jp->sigint) /* TODO: do the same with all signals */
4784 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4786 if (jp->state == JOBDONE)
4793 * return 1 if there are stopped jobs, otherwise 0
4805 if (jp && jp->state == JOBSTOPPED) {
4806 out2str("You have stopped jobs.\n");
4815 /* ============ redir.c
4817 * Code for dealing with input/output redirection.
4820 #define EMPTY -2 /* marks an unused slot in redirtab */
4821 #define CLOSED -3 /* marks a slot of previously-closed fd */
4824 * Open a file in noclobber mode.
4825 * The code was copied from bash.
4828 noclobberopen(const char *fname)
4831 struct stat finfo, finfo2;
4834 * If the file exists and is a regular file, return an error
4837 r = stat(fname, &finfo);
4838 if (r == 0 && S_ISREG(finfo.st_mode)) {
4844 * If the file was not present (r != 0), make sure we open it
4845 * exclusively so that if it is created before we open it, our open
4846 * will fail. Make sure that we do not truncate an existing file.
4847 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4848 * file was not a regular file, we leave O_EXCL off.
4851 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4852 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4854 /* If the open failed, return the file descriptor right away. */
4859 * OK, the open succeeded, but the file may have been changed from a
4860 * non-regular file to a regular file between the stat and the open.
4861 * We are assuming that the O_EXCL open handles the case where FILENAME
4862 * did not exist and is symlinked to an existing file between the stat
4867 * If we can open it and fstat the file descriptor, and neither check
4868 * revealed that it was a regular file, and the file has not been
4869 * replaced, return the file descriptor.
4871 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4872 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4875 /* The file has been replaced. badness. */
4882 * Handle here documents. Normally we fork off a process to write the
4883 * data to a pipe. If the document is short, we can stuff the data in
4884 * the pipe without forking.
4886 /* openhere needs this forward reference */
4887 static void expandhere(union node *arg, int fd);
4889 openhere(union node *redir)
4895 ash_msg_and_raise_error("pipe call failed");
4896 if (redir->type == NHERE) {
4897 len = strlen(redir->nhere.doc->narg.text);
4898 if (len <= PIPE_BUF) {
4899 full_write(pip[1], redir->nhere.doc->narg.text, len);
4903 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4906 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4907 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4908 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4909 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4910 signal(SIGPIPE, SIG_DFL);
4911 if (redir->type == NHERE)
4912 full_write(pip[1], redir->nhere.doc->narg.text, len);
4914 expandhere(redir->nhere.doc, pip[1]);
4915 _exit(EXIT_SUCCESS);
4923 openredirect(union node *redir)
4928 switch (redir->nfile.type) {
4930 fname = redir->nfile.expfname;
4931 f = open(fname, O_RDONLY);
4936 fname = redir->nfile.expfname;
4937 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4942 #if ENABLE_ASH_BASH_COMPAT
4945 /* Take care of noclobber mode. */
4947 fname = redir->nfile.expfname;
4948 f = noclobberopen(fname);
4955 fname = redir->nfile.expfname;
4956 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4961 fname = redir->nfile.expfname;
4962 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4970 /* Fall through to eliminate warning. */
4971 /* Our single caller does this itself */
4978 f = openhere(redir);
4984 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4986 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
4990 * Copy a file descriptor to be >= to. Returns -1
4991 * if the source file descriptor is closed, EMPTY if there are no unused
4992 * file descriptors left.
4994 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
4995 * old code was doing close(to) prior to copyfd() to achieve the same */
4997 COPYFD_EXACT = (int)~(INT_MAX),
4998 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5001 copyfd(int from, int to)
5005 if (to & COPYFD_EXACT) {
5006 to &= ~COPYFD_EXACT;
5008 newfd = dup2(from, to);
5010 newfd = fcntl(from, F_DUPFD, to);
5013 if (errno == EMFILE)
5015 /* Happens when source fd is not open: try "echo >&99" */
5016 ash_msg_and_raise_error("%d: %m", from);
5021 /* Struct def and variable are moved down to the first usage site */
5026 struct redirtab *next;
5029 struct two_fd_t two_fd[];
5031 #define redirlist (G_var.redirlist)
5033 static int need_to_remember(struct redirtab *rp, int fd)
5037 if (!rp) /* remembering was not requested */
5040 for (i = 0; i < rp->pair_count; i++) {
5041 if (rp->two_fd[i].orig == fd) {
5042 /* already remembered */
5049 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5050 static int is_hidden_fd(struct redirtab *rp, int fd)
5053 struct parsefile *pf;
5066 fd |= COPYFD_RESTORE;
5067 for (i = 0; i < rp->pair_count; i++) {
5068 if (rp->two_fd[i].copy == fd) {
5076 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5077 * old file descriptors are stashed away so that the redirection can be
5078 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5079 * standard output, and the standard error if it becomes a duplicate of
5080 * stdout, is saved in memory.
5082 /* flags passed to redirect */
5083 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5084 #define REDIR_SAVEFD2 03 /* set preverrout */
5086 redirect(union node *redir, int flags)
5088 struct redirtab *sv;
5093 int copied_fd2 = -1;
5103 if (flags & REDIR_PUSH) {
5104 union node *tmp = redir;
5107 #if ENABLE_ASH_BASH_COMPAT
5108 if (tmp->nfile.type == NTO2)
5111 tmp = tmp->nfile.next;
5113 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5114 sv->next = redirlist;
5115 sv->pair_count = sv_pos;
5117 sv->nullredirs = g_nullredirs - 1;
5119 while (sv_pos > 0) {
5121 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5126 fd = redir->nfile.fd;
5127 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5128 int right_fd = redir->ndup.dupfd;
5129 /* redirect from/to same file descriptor? */
5132 /* echo >&10 and 10 is a fd opened to the sh script? */
5133 if (is_hidden_fd(sv, right_fd)) {
5134 errno = EBADF; /* as if it is closed */
5135 ash_msg_and_raise_error("%d: %m", right_fd);
5139 newfd = openredirect(redir); /* always >= 0 */
5141 /* Descriptor wasn't open before redirect.
5142 * Mark it for close in the future */
5143 if (need_to_remember(sv, fd)) {
5144 goto remember_to_close;
5149 #if ENABLE_ASH_BASH_COMPAT
5152 if (need_to_remember(sv, fd)) {
5153 /* Copy old descriptor */
5154 i = fcntl(fd, F_DUPFD, 10);
5155 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5156 * are closed in popredir() in the child, preventing them from leaking
5157 * into child. (popredir() also cleans up the mess in case of failures)
5162 /* Strange error (e.g. "too many files" EMFILE?) */
5166 ash_msg_and_raise_error("%d: %m", fd);
5169 /* EBADF: it is not open - good, remember to close it */
5172 } else { /* fd is open, save its copy */
5173 /* "exec fd>&-" should not close fds
5174 * which point to script file(s).
5175 * Force them to be restored afterwards */
5176 if (is_hidden_fd(sv, fd))
5177 i |= COPYFD_RESTORE;
5181 sv->two_fd[sv_pos].orig = fd;
5182 sv->two_fd[sv_pos].copy = i;
5186 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5187 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5188 /* Don't want to trigger debugging */
5192 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5194 } else if (fd != newfd) { /* move newfd to fd */
5195 copyfd(newfd, fd | COPYFD_EXACT);
5196 #if ENABLE_ASH_BASH_COMPAT
5197 if (!(redir->nfile.type == NTO2 && fd == 2))
5201 #if ENABLE_ASH_BASH_COMPAT
5202 if (redir->nfile.type == NTO2 && fd == 1) {
5203 /* We already redirected it to fd 1, now copy it to 2 */
5209 } while ((redir = redir->nfile.next) != NULL);
5212 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5213 preverrout_fd = copied_fd2;
5217 * Undo the effects of the last redirection.
5220 popredir(int drop, int restore)
5222 struct redirtab *rp;
5225 if (--g_nullredirs >= 0)
5229 for (i = 0; i < rp->pair_count; i++) {
5230 int fd = rp->two_fd[i].orig;
5231 int copy = rp->two_fd[i].copy;
5232 if (copy == CLOSED) {
5237 if (copy != EMPTY) {
5238 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5239 copy &= ~COPYFD_RESTORE;
5241 copyfd(copy, fd | COPYFD_EXACT);
5243 close(copy & ~COPYFD_RESTORE);
5246 redirlist = rp->next;
5247 g_nullredirs = rp->nullredirs;
5253 * Undo all redirections. Called on error or interrupt.
5257 * Discard all saved file descriptors.
5260 clearredir(int drop)
5266 popredir(drop, /*restore:*/ 0);
5271 redirectsafe(union node *redir, int flags)
5274 volatile int saveint;
5275 struct jmploc *volatile savehandler = exception_handler;
5276 struct jmploc jmploc;
5279 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5280 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5282 exception_handler = &jmploc;
5283 redirect(redir, flags);
5285 exception_handler = savehandler;
5286 if (err && exception_type != EXERROR)
5287 longjmp(exception_handler->loc, 1);
5288 RESTORE_INT(saveint);
5293 /* ============ Routines to expand arguments to commands
5295 * We have to deal with backquotes, shell variables, and file metacharacters.
5298 #if ENABLE_SH_MATH_SUPPORT
5300 ash_arith(const char *s)
5302 arith_eval_hooks_t math_hooks;
5306 math_hooks.lookupvar = lookupvar;
5307 math_hooks.setvar = setvar;
5308 math_hooks.endofname = endofname;
5311 result = arith(s, &errcode, &math_hooks);
5314 ash_msg_and_raise_error("exponent less than 0");
5316 ash_msg_and_raise_error("divide by zero");
5318 ash_msg_and_raise_error("expression recursion loop detected");
5319 raise_error_syntax(s);
5330 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5331 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5332 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5333 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5334 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5335 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5336 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5337 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5338 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5342 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5343 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5344 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5345 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5346 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5349 * Structure specifying which parts of the string should be searched
5350 * for IFS characters.
5353 struct ifsregion *next; /* next region in list */
5354 int begoff; /* offset of start of region */
5355 int endoff; /* offset of end of region */
5356 int nulonly; /* search for nul bytes only */
5360 struct strlist *list;
5361 struct strlist **lastp;
5364 /* output of current string */
5365 static char *expdest;
5366 /* list of back quote expressions */
5367 static struct nodelist *argbackq;
5368 /* first struct in list of ifs regions */
5369 static struct ifsregion ifsfirst;
5370 /* last struct in list */
5371 static struct ifsregion *ifslastp;
5372 /* holds expanded arg list */
5373 static struct arglist exparg;
5383 expdest = makestrspace(32, expdest);
5384 len = fmtstr(expdest, 32, arith_t_fmt, num);
5385 STADJUST(len, expdest);
5390 esclen(const char *start, const char *p)
5394 while (p > start && (unsigned char)*--p == CTLESC) {
5401 * Remove any CTLESC characters from a string.
5404 rmescapes(char *str, int flag)
5406 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5410 unsigned protect_against_glob;
5413 p = strpbrk(str, qchars);
5419 if (flag & RMESCAPE_ALLOC) {
5420 size_t len = p - str;
5421 size_t fulllen = len + strlen(p) + 1;
5423 if (flag & RMESCAPE_GROW) {
5424 r = makestrspace(fulllen, expdest);
5425 } else if (flag & RMESCAPE_HEAP) {
5426 r = ckmalloc(fulllen);
5428 r = stalloc(fulllen);
5432 q = (char *)memcpy(q, str, len) + len;
5436 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5437 globbing = flag & RMESCAPE_GLOB;
5438 protect_against_glob = globbing;
5440 if ((unsigned char)*p == CTLQUOTEMARK) {
5441 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5442 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5443 // Note: both inquotes and protect_against_glob only affect whether
5444 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5445 inquotes = ~inquotes;
5447 protect_against_glob = globbing;
5451 /* naked back slash */
5452 protect_against_glob = 0;
5455 if ((unsigned char)*p == CTLESC) {
5457 if (protect_against_glob && inquotes && *p != '/') {
5461 protect_against_glob = globbing;
5466 if (flag & RMESCAPE_GROW) {
5468 STADJUST(q - r + 1, expdest);
5472 #define pmatch(a, b) !fnmatch((a), (b), 0)
5475 * Prepare a pattern for a expmeta (internal glob(3)) call.
5477 * Returns an stalloced string.
5480 preglob(const char *pattern, int quoted, int flag)
5482 flag |= RMESCAPE_GLOB;
5484 flag |= RMESCAPE_QUOTED;
5486 return rmescapes((char *)pattern, flag);
5490 * Put a string on the stack.
5493 memtodest(const char *p, size_t len, int syntax, int quotes)
5497 q = makestrspace(quotes ? len * 2 : len, q);
5500 unsigned char c = *p++;
5504 int n = SIT(c, syntax);
5505 if (n == CCTL || n == CBACK)
5515 strtodest(const char *p, int syntax, int quotes)
5517 memtodest(p, strlen(p), syntax, quotes);
5521 * Record the fact that we have to scan this region of the
5522 * string for IFS characters.
5525 recordregion(int start, int end, int nulonly)
5527 struct ifsregion *ifsp;
5529 if (ifslastp == NULL) {
5533 ifsp = ckzalloc(sizeof(*ifsp));
5534 /*ifsp->next = NULL; - ckzalloc did it */
5535 ifslastp->next = ifsp;
5539 ifslastp->begoff = start;
5540 ifslastp->endoff = end;
5541 ifslastp->nulonly = nulonly;
5545 removerecordregions(int endoff)
5547 if (ifslastp == NULL)
5550 if (ifsfirst.endoff > endoff) {
5551 while (ifsfirst.next != NULL) {
5552 struct ifsregion *ifsp;
5554 ifsp = ifsfirst.next->next;
5555 free(ifsfirst.next);
5556 ifsfirst.next = ifsp;
5559 if (ifsfirst.begoff > endoff)
5562 ifslastp = &ifsfirst;
5563 ifsfirst.endoff = endoff;
5568 ifslastp = &ifsfirst;
5569 while (ifslastp->next && ifslastp->next->begoff < endoff)
5570 ifslastp=ifslastp->next;
5571 while (ifslastp->next != NULL) {
5572 struct ifsregion *ifsp;
5574 ifsp = ifslastp->next->next;
5575 free(ifslastp->next);
5576 ifslastp->next = ifsp;
5579 if (ifslastp->endoff > endoff)
5580 ifslastp->endoff = endoff;
5584 exptilde(char *startp, char *p, int flags)
5590 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5595 while ((c = *++p) != '\0') {
5602 if (flags & EXP_VARTILDE)
5612 if (*name == '\0') {
5613 home = lookupvar(homestr);
5615 pw = getpwnam(name);
5620 if (!home || !*home)
5623 startloc = expdest - (char *)stackblock();
5624 strtodest(home, SQSYNTAX, quotes);
5625 recordregion(startloc, expdest - (char *)stackblock(), 0);
5633 * Execute a command inside back quotes. If it's a builtin command, we
5634 * want to save its output in a block obtained from malloc. Otherwise
5635 * we fork off a subprocess and get the output of the command via a pipe.
5636 * Should be called with interrupts off.
5638 struct backcmd { /* result of evalbackcmd */
5639 int fd; /* file descriptor to read from */
5640 int nleft; /* number of chars in buffer */
5641 char *buf; /* buffer */
5642 struct job *jp; /* job structure for command */
5645 /* These forward decls are needed to use "eval" code for backticks handling: */
5646 static uint8_t back_exitstatus; /* exit status of backquoted command */
5647 #define EV_EXIT 01 /* exit after evaluating tree */
5648 static void evaltree(union node *, int);
5650 static void FAST_FUNC
5651 evalbackcmd(union node *n, struct backcmd *result)
5662 saveherefd = herefd;
5670 ash_msg_and_raise_error("pipe call failed");
5671 jp = makejob(/*n,*/ 1);
5672 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5677 copyfd(pip[1], 1 | COPYFD_EXACT);
5681 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5685 result->fd = pip[0];
5688 herefd = saveherefd;
5690 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5691 result->fd, result->buf, result->nleft, result->jp));
5695 * Expand stuff in backwards quotes.
5698 expbackq(union node *cmd, int quoted, int quotes)
5706 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5707 struct stackmark smark;
5710 setstackmark(&smark);
5712 startloc = dest - (char *)stackblock();
5714 evalbackcmd(cmd, &in);
5715 popstackmark(&smark);
5722 memtodest(p, i, syntax, quotes);
5726 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5727 TRACE(("expbackq: read returns %d\n", i));
5736 back_exitstatus = waitforjob(in.jp);
5740 /* Eat all trailing newlines */
5742 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5747 recordregion(startloc, dest - (char *)stackblock(), 0);
5748 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5749 (dest - (char *)stackblock()) - startloc,
5750 (dest - (char *)stackblock()) - startloc,
5751 stackblock() + startloc));
5754 #if ENABLE_SH_MATH_SUPPORT
5756 * Expand arithmetic expression. Backup to start of expression,
5757 * evaluate, place result in (backed up) result, adjust string position.
5770 * This routine is slightly over-complicated for
5771 * efficiency. Next we scan backwards looking for the
5772 * start of arithmetic.
5774 start = stackblock();
5781 while ((unsigned char)*p != CTLARI) {
5785 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5790 esc = esclen(start, p);
5800 removerecordregions(begoff);
5807 rmescapes(p + 2, 0);
5809 len = cvtnum(ash_arith(p + 2));
5812 recordregion(begoff, begoff + len, 0);
5816 /* argstr needs it */
5817 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5820 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5821 * characters to allow for further processing. Otherwise treat
5822 * $@ like $* since no splitting will be performed.
5824 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5825 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5826 * for correct expansion of "B=$A" word.
5829 argstr(char *p, int flags, struct strlist *var_str_list)
5831 static const char spclchars[] ALIGN1 = {
5839 CTLBACKQ | CTLQUOTE,
5840 #if ENABLE_SH_MATH_SUPPORT
5845 const char *reject = spclchars;
5846 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5847 int breakall = flags & EXP_WORD;
5852 if (!(flags & EXP_VARTILDE)) {
5854 } else if (flags & EXP_VARTILDE2) {
5859 if (flags & EXP_TILDE) {
5862 flags &= ~EXP_TILDE;
5865 if (*q == CTLESC && (flags & EXP_QWORD))
5868 p = exptilde(p, q, flags);
5871 startloc = expdest - (char *)stackblock();
5875 length += strcspn(p + length, reject);
5879 #if ENABLE_SH_MATH_SUPPORT
5883 /* c == '=' || c == ':' || c == CTLENDARI */
5889 expdest = stack_nputstr(p, length, expdest);
5890 newloc = expdest - (char *)stackblock();
5891 if (breakall && !inquotes && newloc > startloc) {
5892 recordregion(startloc, newloc, 0);
5903 if (flags & EXP_VARTILDE2) {
5907 flags |= EXP_VARTILDE2;
5912 * sort of a hack - expand tildes in variable
5913 * assignments (after the first '=' and after ':'s).
5922 case CTLENDVAR: /* ??? */
5925 /* "$@" syntax adherence hack */
5927 && memcmp(p, dolatstr, 4) == 0
5928 && ( p[4] == CTLQUOTEMARK
5929 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5932 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
5935 inquotes = !inquotes;
5948 p = evalvar(p, flags, var_str_list);
5952 case CTLBACKQ|CTLQUOTE:
5953 expbackq(argbackq->n, c, quotes);
5954 argbackq = argbackq->next;
5956 #if ENABLE_SH_MATH_SUPPORT
5969 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
5972 // This commented out code was added by James Simmons <jsimmons@infradead.org>
5973 // as part of a larger change when he added support for ${var/a/b}.
5974 // However, it broke # and % operators:
5978 //echo ${var#ab} abcdcd abcdcd
5979 //echo ${var##ab} abcdcd abcdcd
5980 //echo ${var#a*b} abcdcd ababcdcd (!)
5981 //echo ${var##a*b} cdcd cdcd
5982 //echo ${var#?} babcdcd ababcdcd (!)
5983 //echo ${var##?} babcdcd babcdcd
5984 //echo ${var#*} ababcdcd babcdcd (!)
5986 //echo ${var%cd} ababcd ababcd
5987 //echo ${var%%cd} ababcd abab (!)
5988 //echo ${var%c*d} ababcd ababcd
5989 //echo ${var%%c*d} abab ababcdcd (!)
5990 //echo ${var%?} ababcdc ababcdc
5991 //echo ${var%%?} ababcdc ababcdcd (!)
5992 //echo ${var%*} ababcdcd ababcdcd
5995 // Commenting it back out helped. Remove it completely if it really
5998 char *loc, *loc2; //, *full;
6004 int match; // = strlen(str);
6005 const char *s = loc2;
6012 match = pmatch(str, s); // this line was deleted
6014 // // chop off end if its '*'
6015 // full = strrchr(str, '*');
6016 // if (full && full != str)
6019 // // If str starts with '*' replace with s.
6020 // if ((*str == '*') && strlen(s) >= match) {
6021 // full = xstrdup(s);
6022 // strncpy(full+strlen(s)-match+1, str+1, match-1);
6024 // full = xstrndup(str, match);
6025 // match = strncmp(s, full, strlen(full));
6029 if (match) // if (!match)
6031 if (quotes && (unsigned char)*loc == CTLESC)
6040 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6047 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6050 const char *s = loc2;
6055 match = pmatch(str, s);
6062 esc = esclen(startp, loc);
6073 static void varunset(const char *, const char *, const char *, int) NORETURN;
6075 varunset(const char *end, const char *var, const char *umsg, int varflags)
6081 msg = "parameter not set";
6083 if ((unsigned char)*end == CTLENDVAR) {
6084 if (varflags & VSNUL)
6090 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6093 #if ENABLE_ASH_BASH_COMPAT
6095 parse_sub_pattern(char *arg, int inquotes)
6097 char *idx, *repl = NULL;
6106 /* Only the first '/' seen is our separator */
6113 if (!inquotes && c == '\\' && arg[1] == '\\')
6114 arg++; /* skip both \\, not just first one */
6121 #endif /* ENABLE_ASH_BASH_COMPAT */
6124 subevalvar(char *p, char *str, int strloc, int subtype,
6125 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6127 struct nodelist *saveargbackq = argbackq;
6130 char *rmesc, *rmescend;
6131 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6132 IF_ASH_BASH_COMPAT(char null = '\0';)
6133 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6134 int saveherefd = herefd;
6135 int amount, workloc, resetloc;
6137 char *(*scan)(char*, char*, char*, char*, int, int);
6140 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6142 STPUTC('\0', expdest);
6143 herefd = saveherefd;
6144 argbackq = saveargbackq;
6145 startp = (char *)stackblock() + startloc;
6149 setvar(str, startp, 0);
6150 amount = startp - expdest;
6151 STADJUST(amount, expdest);
6154 #if ENABLE_ASH_BASH_COMPAT
6156 loc = str = stackblock() + strloc;
6157 /* Read POS in ${var:POS:LEN} */
6158 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6159 len = str - startp - 1;
6161 /* *loc != '\0', guaranteed by parser */
6165 /* Adjust the length by the number of escapes */
6166 for (ptr = startp; ptr < (str - 1); ptr++) {
6167 if ((unsigned char)*ptr == CTLESC) {
6175 if (*loc++ == ':') {
6179 /* Skip POS in ${var:POS:LEN} */
6181 while (*loc && *loc != ':') {
6183 * bash complains on: var=qwe; echo ${var:1a:123}
6185 ash_msg_and_raise_error(msg_illnum, str);
6189 if (*loc++ == ':') {
6193 if (pos >= orig_len) {
6197 if (len > (orig_len - pos))
6198 len = orig_len - pos;
6200 for (str = startp; pos; str++, pos--) {
6201 if (quotes && (unsigned char)*str == CTLESC)
6204 for (loc = startp; len; len--) {
6205 if (quotes && (unsigned char)*str == CTLESC)
6210 amount = loc - expdest;
6211 STADJUST(amount, expdest);
6216 varunset(p, str, startp, varflags);
6219 resetloc = expdest - (char *)stackblock();
6221 /* We'll comeback here if we grow the stack while handling
6222 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6223 * stack will need rebasing, and we'll need to remove our work
6226 IF_ASH_BASH_COMPAT(restart:)
6228 amount = expdest - ((char *)stackblock() + resetloc);
6229 STADJUST(-amount, expdest);
6230 startp = (char *)stackblock() + startloc;
6233 rmescend = (char *)stackblock() + strloc;
6235 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6236 if (rmesc != startp) {
6238 startp = (char *)stackblock() + startloc;
6242 str = (char *)stackblock() + strloc;
6243 preglob(str, varflags & VSQUOTE, 0);
6244 workloc = expdest - (char *)stackblock();
6246 #if ENABLE_ASH_BASH_COMPAT
6247 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6248 char *idx, *end, *restart_detect;
6251 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6256 /* If there's no pattern to match, return the expansion unmolested */
6264 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6266 /* No match, advance */
6267 restart_detect = stackblock();
6268 STPUTC(*idx, expdest);
6269 if (quotes && (unsigned char)*idx == CTLESC) {
6272 STPUTC(*idx, expdest);
6274 if (stackblock() != restart_detect)
6282 if (subtype == VSREPLACEALL) {
6284 if (quotes && (unsigned char)*idx == CTLESC)
6293 for (loc = repl; *loc; loc++) {
6294 restart_detect = stackblock();
6295 STPUTC(*loc, expdest);
6296 if (stackblock() != restart_detect)
6301 if (subtype == VSREPLACE) {
6303 restart_detect = stackblock();
6304 STPUTC(*idx, expdest);
6305 if (stackblock() != restart_detect)
6314 /* We've put the replaced text into a buffer at workloc, now
6315 * move it to the right place and adjust the stack.
6317 startp = stackblock() + startloc;
6318 STPUTC('\0', expdest);
6319 memmove(startp, stackblock() + workloc, len);
6320 startp[len++] = '\0';
6321 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6322 STADJUST(-amount, expdest);
6325 #endif /* ENABLE_ASH_BASH_COMPAT */
6327 subtype -= VSTRIMRIGHT;
6329 if (subtype < 0 || subtype > 7)
6332 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6333 zero = subtype >> 1;
6334 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6335 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6337 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6340 memmove(startp, loc, str - loc);
6341 loc = startp + (str - loc) - 1;
6344 amount = loc - expdest;
6345 STADJUST(amount, expdest);
6351 * Add the value of a specialized variable to the stack string.
6352 * name parameter (examples):
6353 * ash -c 'echo $1' name:'1='
6354 * ash -c 'echo $qwe' name:'qwe='
6355 * ash -c 'echo $$' name:'$='
6356 * ash -c 'echo ${$}' name:'$='
6357 * ash -c 'echo ${$##q}' name:'$=q'
6358 * ash -c 'echo ${#$}' name:'$='
6359 * note: examples with bad shell syntax:
6360 * ash -c 'echo ${#$1}' name:'$=1'
6361 * ash -c 'echo ${#1#}' name:'1=#'
6363 static NOINLINE ssize_t
6364 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6371 int subtype = varflags & VSTYPE;
6372 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6373 int quoted = varflags & VSQUOTE;
6374 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6384 num = shellparam.nparam;
6392 goto check_1char_name;
6394 expdest = makestrspace(NOPTS, expdest);
6395 for (i = NOPTS - 1; i >= 0; i--) {
6397 USTPUTC(optletters(i), expdest);
6403 /* handles cases similar to ${#$1} */
6404 if (name[2] != '\0')
6405 raise_error_syntax("bad substitution");
6412 if (quoted && (flags & EXP_FULL)) {
6413 /* note: this is not meant as PEOF value */
6414 sep = 1 << CHAR_BIT;
6419 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6420 i = SIT(sep, syntax);
6421 if (quotes && (i == CCTL || i == CBACK))
6427 while ((p = *ap++) != NULL) {
6430 partlen = strlen(p);
6433 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6434 memtodest(p, partlen, syntax, quotes);
6440 if (subtype == VSPLUS || subtype == VSLENGTH) {
6446 /* note: may put NUL despite sep != 0
6447 * (see sep = 1 << CHAR_BIT above) */
6453 } /* case '@' and '*' */
6464 num = atoi(name); /* number(name) fails on ${N#str} etc */
6465 if (num < 0 || num > shellparam.nparam)
6467 p = num ? shellparam.p[num - 1] : arg0;
6470 /* NB: name has form "VAR=..." */
6472 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6473 * which should be considered before we check variables. */
6475 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6479 str = var_str_list->text;
6480 eq = strchr(str, '=');
6481 if (!eq) /* stop at first non-assignment */
6484 if (name_len == (unsigned)(eq - str)
6485 && strncmp(str, name, name_len) == 0
6488 /* goto value; - WRONG! */
6489 /* think "A=1 A=2 B=$A" */
6491 var_str_list = var_str_list->next;
6492 } while (var_str_list);
6496 p = lookupvar(name);
6502 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6503 memtodest(p, len, syntax, quotes);
6507 if (subtype == VSPLUS || subtype == VSLENGTH)
6508 STADJUST(-len, expdest);
6513 * Expand a variable, and return a pointer to the next character in the
6517 evalvar(char *p, int flags, struct strlist *var_str_list)
6528 varflags = (unsigned char) *p++;
6529 subtype = varflags & VSTYPE;
6530 quoted = varflags & VSQUOTE;
6532 easy = (!quoted || (*var == '@' && shellparam.nparam));
6533 startloc = expdest - (char *)stackblock();
6534 p = strchr(p, '=') + 1;
6537 varlen = varvalue(var, varflags, flags, var_str_list);
6538 if (varflags & VSNUL)
6541 if (subtype == VSPLUS) {
6542 varlen = -1 - varlen;
6546 if (subtype == VSMINUS) {
6550 p, flags | EXP_TILDE |
6551 (quoted ? EXP_QWORD : EXP_WORD),
6561 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6563 if (subevalvar(p, var, /* strloc: */ 0,
6564 subtype, startloc, varflags,
6570 * Remove any recorded regions beyond
6573 removerecordregions(startloc);
6583 if (varlen < 0 && uflag)
6584 varunset(p, var, 0, 0);
6586 if (subtype == VSLENGTH) {
6587 cvtnum(varlen > 0 ? varlen : 0);
6591 if (subtype == VSNORMAL) {
6602 case VSTRIMRIGHTMAX:
6603 #if ENABLE_ASH_BASH_COMPAT
6616 * Terminate the string and start recording the pattern
6619 STPUTC('\0', expdest);
6620 patloc = expdest - (char *)stackblock();
6621 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6623 //TODO: | EXP_REDIR too? All other such places do it too
6624 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6627 int amount = expdest - (
6628 (char *)stackblock() + patloc - 1
6630 STADJUST(-amount, expdest);
6632 /* Remove any recorded regions beyond start of variable */
6633 removerecordregions(startloc);
6635 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6639 if (subtype != VSNORMAL) { /* skip to end of alternative */
6642 unsigned char c = *p++;
6645 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6647 argbackq = argbackq->next;
6648 } else if (c == CTLVAR) {
6649 if ((*p++ & VSTYPE) != VSNORMAL)
6651 } else if (c == CTLENDVAR) {
6661 * Break the argument string into pieces based upon IFS and add the
6662 * strings to the argument list. The regions of the string to be
6663 * searched for IFS characters have been stored by recordregion.
6666 ifsbreakup(char *string, struct arglist *arglist)
6668 struct ifsregion *ifsp;
6673 const char *ifs, *realifs;
6678 if (ifslastp != NULL) {
6681 realifs = ifsset() ? ifsval() : defifs;
6684 p = string + ifsp->begoff;
6685 nulonly = ifsp->nulonly;
6686 ifs = nulonly ? nullstr : realifs;
6688 while (p < string + ifsp->endoff) {
6690 if ((unsigned char)*p == CTLESC)
6692 if (!strchr(ifs, *p)) {
6697 ifsspc = (strchr(defifs, *p) != NULL);
6698 /* Ignore IFS whitespace at start */
6699 if (q == start && ifsspc) {
6705 sp = stzalloc(sizeof(*sp));
6707 *arglist->lastp = sp;
6708 arglist->lastp = &sp->next;
6712 if (p >= string + ifsp->endoff) {
6716 if ((unsigned char)*p == CTLESC)
6718 if (strchr(ifs, *p) == NULL) {
6722 if (strchr(defifs, *p) == NULL) {
6737 } while (ifsp != NULL);
6746 sp = stzalloc(sizeof(*sp));
6748 *arglist->lastp = sp;
6749 arglist->lastp = &sp->next;
6755 struct ifsregion *p;
6760 struct ifsregion *ifsp;
6766 ifsfirst.next = NULL;
6771 * Add a file name to the list.
6774 addfname(const char *name)
6778 sp = stzalloc(sizeof(*sp));
6779 sp->text = ststrdup(name);
6781 exparg.lastp = &sp->next;
6784 static char *expdir;
6787 * Do metacharacter (i.e. *, ?, [...]) expansion.
6790 expmeta(char *enddir, char *name)
6805 for (p = name; *p; p++) {
6806 if (*p == '*' || *p == '?')
6808 else if (*p == '[') {
6815 if (*q == '/' || *q == '\0')
6822 } else if (*p == '\\')
6824 else if (*p == '/') {
6831 if (metaflag == 0) { /* we've reached the end of the file name */
6832 if (enddir != expdir)
6840 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6851 } while (p < start);
6853 if (enddir == expdir) {
6855 } else if (enddir == expdir + 1 && *expdir == '/') {
6864 if (enddir != expdir)
6866 if (*endname == 0) {
6878 while (!pending_int && (dp = readdir(dirp)) != NULL) {
6879 if (dp->d_name[0] == '.' && !matchdot)
6881 if (pmatch(start, dp->d_name)) {
6883 strcpy(enddir, dp->d_name);
6886 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6889 expmeta(p, endname);
6898 static struct strlist *
6899 msort(struct strlist *list, int len)
6901 struct strlist *p, *q = NULL;
6902 struct strlist **lpp;
6910 for (n = half; --n >= 0;) {
6914 q->next = NULL; /* terminate first half of list */
6915 q = msort(list, half); /* sort first half of list */
6916 p = msort(p, len - half); /* sort second half */
6919 #if ENABLE_LOCALE_SUPPORT
6920 if (strcoll(p->text, q->text) < 0)
6922 if (strcmp(p->text, q->text) < 0)
6946 * Sort the results of file name expansion. It calculates the number of
6947 * strings to sort and then calls msort (short for merge sort) to do the
6950 static struct strlist *
6951 expsort(struct strlist *str)
6957 for (sp = str; sp; sp = sp->next)
6959 return msort(str, len);
6963 expandmeta(struct strlist *str /*, int flag*/)
6965 static const char metachars[] ALIGN1 = {
6968 /* TODO - EXP_REDIR */
6971 struct strlist **savelastp;
6977 if (!strpbrk(str->text, metachars))
6979 savelastp = exparg.lastp;
6982 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6984 int i = strlen(str->text);
6985 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6993 if (exparg.lastp == savelastp) {
6998 *exparg.lastp = str;
6999 rmescapes(str->text, 0);
7000 exparg.lastp = &str->next;
7002 *exparg.lastp = NULL;
7003 *savelastp = sp = expsort(*savelastp);
7004 while (sp->next != NULL)
7006 exparg.lastp = &sp->next;
7013 * Perform variable substitution and command substitution on an argument,
7014 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7015 * perform splitting and file name expansion. When arglist is NULL, perform
7016 * here document expansion.
7019 expandarg(union node *arg, struct arglist *arglist, int flag)
7024 argbackq = arg->narg.backquote;
7025 STARTSTACKSTR(expdest);
7026 ifsfirst.next = NULL;
7028 argstr(arg->narg.text, flag,
7029 /* var_str_list: */ arglist ? arglist->list : NULL);
7030 p = _STPUTC('\0', expdest);
7032 if (arglist == NULL) {
7033 return; /* here document expanded */
7035 p = grabstackstr(p);
7036 exparg.lastp = &exparg.list;
7040 if (flag & EXP_FULL) {
7041 ifsbreakup(p, &exparg);
7042 *exparg.lastp = NULL;
7043 exparg.lastp = &exparg.list;
7044 expandmeta(exparg.list /*, flag*/);
7046 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7048 sp = stzalloc(sizeof(*sp));
7051 exparg.lastp = &sp->next;
7055 *exparg.lastp = NULL;
7057 *arglist->lastp = exparg.list;
7058 arglist->lastp = exparg.lastp;
7063 * Expand shell variables and backquotes inside a here document.
7066 expandhere(union node *arg, int fd)
7069 expandarg(arg, (struct arglist *)NULL, 0);
7070 full_write(fd, stackblock(), expdest - (char *)stackblock());
7074 * Returns true if the pattern matches the string.
7077 patmatch(char *pattern, const char *string)
7079 return pmatch(preglob(pattern, 0, 0), string);
7083 * See if a pattern matches in a case statement.
7086 casematch(union node *pattern, char *val)
7088 struct stackmark smark;
7091 setstackmark(&smark);
7092 argbackq = pattern->narg.backquote;
7093 STARTSTACKSTR(expdest);
7095 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7096 /* var_str_list: */ NULL);
7097 STACKSTRNUL(expdest);
7098 result = patmatch(stackblock(), val);
7099 popstackmark(&smark);
7104 /* ============ find_command */
7108 int (*builtin)(int, char **) FAST_FUNC;
7109 /* unsigned flags; */
7111 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7112 /* "regular" builtins always take precedence over commands,
7113 * regardless of PATH=....%builtin... position */
7114 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7115 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7118 smallint cmdtype; /* CMDxxx */
7121 /* index >= 0 for commands without path (slashes) */
7122 /* (TODO: what exactly does the value mean? PATH position?) */
7123 /* index == -1 for commands with slashes */
7124 /* index == (-2 - applet_no) for NOFORK applets */
7125 const struct builtincmd *cmd;
7126 struct funcnode *func;
7129 /* values of cmdtype */
7130 #define CMDUNKNOWN -1 /* no entry in table for command */
7131 #define CMDNORMAL 0 /* command is an executable program */
7132 #define CMDFUNCTION 1 /* command is a shell function */
7133 #define CMDBUILTIN 2 /* command is a shell builtin */
7135 /* action to find_command() */
7136 #define DO_ERR 0x01 /* prints errors */
7137 #define DO_ABS 0x02 /* checks absolute paths */
7138 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7139 #define DO_ALTPATH 0x08 /* using alternate path */
7140 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7142 static void find_command(char *, struct cmdentry *, int, const char *);
7145 /* ============ Hashing commands */
7148 * When commands are first encountered, they are entered in a hash table.
7149 * This ensures that a full path search will not have to be done for them
7150 * on each invocation.
7152 * We should investigate converting to a linear search, even though that
7153 * would make the command name "hash" a misnomer.
7157 struct tblentry *next; /* next entry in hash chain */
7158 union param param; /* definition of builtin function */
7159 smallint cmdtype; /* CMDxxx */
7160 char rehash; /* if set, cd done since entry created */
7161 char cmdname[1]; /* name of command */
7164 static struct tblentry **cmdtable;
7165 #define INIT_G_cmdtable() do { \
7166 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7169 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7173 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7177 #if ENABLE_FEATURE_SH_STANDALONE
7178 if (applet_no >= 0) {
7179 if (APPLET_IS_NOEXEC(applet_no)) {
7182 run_applet_no_and_exit(applet_no, argv);
7184 /* re-exec ourselves with the new arguments */
7185 execve(bb_busybox_exec_path, argv, envp);
7186 /* If they called chroot or otherwise made the binary no longer
7187 * executable, fall through */
7194 execve(cmd, argv, envp);
7195 } while (errno == EINTR);
7197 execve(cmd, argv, envp);
7203 if (errno == ENOEXEC) {
7207 for (ap = argv; *ap; ap++)
7209 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7211 ap[0] = cmd = (char *)DEFAULT_SHELL;
7214 while ((*ap++ = *argv++) != NULL)
7223 * Exec a program. Never returns. If you change this routine, you may
7224 * have to change the find_command routine as well.
7226 static void shellexec(char **, const char *, int) NORETURN;
7228 shellexec(char **argv, const char *path, int idx)
7234 #if ENABLE_FEATURE_SH_STANDALONE
7238 clearredir(/*drop:*/ 1);
7239 envp = listvars(VEXPORT, VUNSET, 0);
7240 if (strchr(argv[0], '/') != NULL
7241 #if ENABLE_FEATURE_SH_STANDALONE
7242 || (applet_no = find_applet_by_name(argv[0])) >= 0
7245 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7249 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7250 if (--idx < 0 && pathopt == NULL) {
7251 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7252 if (errno != ENOENT && errno != ENOTDIR)
7259 /* Map to POSIX errors */
7271 exitstatus = exerrno;
7272 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7273 argv[0], e, suppress_int));
7274 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7279 printentry(struct tblentry *cmdp)
7285 idx = cmdp->param.index;
7288 name = path_advance(&path, cmdp->cmdname);
7290 } while (--idx >= 0);
7291 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7295 * Clear out command entries. The argument specifies the first entry in
7296 * PATH which has changed.
7299 clearcmdentry(int firstchange)
7301 struct tblentry **tblp;
7302 struct tblentry **pp;
7303 struct tblentry *cmdp;
7306 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7308 while ((cmdp = *pp) != NULL) {
7309 if ((cmdp->cmdtype == CMDNORMAL &&
7310 cmdp->param.index >= firstchange)
7311 || (cmdp->cmdtype == CMDBUILTIN &&
7312 builtinloc >= firstchange)
7325 * Locate a command in the command hash table. If "add" is nonzero,
7326 * add the command to the table if it is not already present. The
7327 * variable "lastcmdentry" is set to point to the address of the link
7328 * pointing to the entry, so that delete_cmd_entry can delete the
7331 * Interrupts must be off if called with add != 0.
7333 static struct tblentry **lastcmdentry;
7335 static struct tblentry *
7336 cmdlookup(const char *name, int add)
7338 unsigned int hashval;
7340 struct tblentry *cmdp;
7341 struct tblentry **pp;
7344 hashval = (unsigned char)*p << 4;
7346 hashval += (unsigned char)*p++;
7348 pp = &cmdtable[hashval % CMDTABLESIZE];
7349 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7350 if (strcmp(cmdp->cmdname, name) == 0)
7354 if (add && cmdp == NULL) {
7355 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7357 /* + 1 - already done because
7358 * tblentry::cmdname is char[1] */);
7359 /*cmdp->next = NULL; - ckzalloc did it */
7360 cmdp->cmdtype = CMDUNKNOWN;
7361 strcpy(cmdp->cmdname, name);
7368 * Delete the command entry returned on the last lookup.
7371 delete_cmd_entry(void)
7373 struct tblentry *cmdp;
7376 cmdp = *lastcmdentry;
7377 *lastcmdentry = cmdp->next;
7378 if (cmdp->cmdtype == CMDFUNCTION)
7379 freefunc(cmdp->param.func);
7385 * Add a new command entry, replacing any existing command entry for
7386 * the same name - except special builtins.
7389 addcmdentry(char *name, struct cmdentry *entry)
7391 struct tblentry *cmdp;
7393 cmdp = cmdlookup(name, 1);
7394 if (cmdp->cmdtype == CMDFUNCTION) {
7395 freefunc(cmdp->param.func);
7397 cmdp->cmdtype = entry->cmdtype;
7398 cmdp->param = entry->u;
7402 static int FAST_FUNC
7403 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7405 struct tblentry **pp;
7406 struct tblentry *cmdp;
7408 struct cmdentry entry;
7411 if (nextopt("r") != '\0') {
7416 if (*argptr == NULL) {
7417 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7418 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7419 if (cmdp->cmdtype == CMDNORMAL)
7427 while ((name = *argptr) != NULL) {
7428 cmdp = cmdlookup(name, 0);
7430 && (cmdp->cmdtype == CMDNORMAL
7431 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7435 find_command(name, &entry, DO_ERR, pathval());
7436 if (entry.cmdtype == CMDUNKNOWN)
7444 * Called when a cd is done. Marks all commands so the next time they
7445 * are executed they will be rehashed.
7450 struct tblentry **pp;
7451 struct tblentry *cmdp;
7453 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7454 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7455 if (cmdp->cmdtype == CMDNORMAL
7456 || (cmdp->cmdtype == CMDBUILTIN
7457 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7467 * Fix command hash table when PATH changed.
7468 * Called before PATH is changed. The argument is the new value of PATH;
7469 * pathval() still returns the old value at this point.
7470 * Called with interrupts off.
7472 static void FAST_FUNC
7473 changepath(const char *new)
7481 firstchange = 9999; /* assume no change */
7487 if ((*old == '\0' && *new == ':')
7488 || (*old == ':' && *new == '\0'))
7490 old = new; /* ignore subsequent differences */
7494 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7500 if (builtinloc < 0 && idx_bltin >= 0)
7501 builtinloc = idx_bltin; /* zap builtins */
7502 if (builtinloc >= 0 && idx_bltin < 0)
7504 clearcmdentry(firstchange);
7505 builtinloc = idx_bltin;
7520 #define TENDBQUOTE 12
7537 typedef smallint token_id_t;
7539 /* first char is indicating which tokens mark the end of a list */
7540 static const char *const tokname_array[] = {
7554 #define KWDOFFSET 13
7555 /* the following are keywords */
7577 static char buf[16];
7580 //if (tok < TSEMI) return tokname_array[tok] + 1;
7581 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7586 sprintf(buf + (tok >= TSEMI), "%s%c",
7587 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7591 /* Wrapper around strcmp for qsort/bsearch/... */
7593 pstrcmp(const void *a, const void *b)
7595 return strcmp((char*) a, (*(char**) b) + 1);
7598 static const char *const *
7599 findkwd(const char *s)
7601 return bsearch(s, tokname_array + KWDOFFSET,
7602 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7603 sizeof(tokname_array[0]), pstrcmp);
7607 * Locate and print what a word is...
7610 describe_command(char *command, int describe_command_verbose)
7612 struct cmdentry entry;
7613 struct tblentry *cmdp;
7614 #if ENABLE_ASH_ALIAS
7615 const struct alias *ap;
7617 const char *path = pathval();
7619 if (describe_command_verbose) {
7623 /* First look at the keywords */
7624 if (findkwd(command)) {
7625 out1str(describe_command_verbose ? " is a shell keyword" : command);
7629 #if ENABLE_ASH_ALIAS
7630 /* Then look at the aliases */
7631 ap = lookupalias(command, 0);
7633 if (!describe_command_verbose) {
7638 out1fmt(" is an alias for %s", ap->val);
7642 /* Then check if it is a tracked alias */
7643 cmdp = cmdlookup(command, 0);
7645 entry.cmdtype = cmdp->cmdtype;
7646 entry.u = cmdp->param;
7648 /* Finally use brute force */
7649 find_command(command, &entry, DO_ABS, path);
7652 switch (entry.cmdtype) {
7654 int j = entry.u.index;
7660 p = path_advance(&path, command);
7664 if (describe_command_verbose) {
7666 (cmdp ? " a tracked alias for" : nullstr), p
7675 if (describe_command_verbose) {
7676 out1str(" is a shell function");
7683 if (describe_command_verbose) {
7684 out1fmt(" is a %sshell builtin",
7685 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7686 "special " : nullstr
7694 if (describe_command_verbose) {
7695 out1str(": not found\n");
7704 static int FAST_FUNC
7705 typecmd(int argc UNUSED_PARAM, char **argv)
7711 /* type -p ... ? (we don't bother checking for 'p') */
7712 if (argv[1] && argv[1][0] == '-') {
7717 err |= describe_command(argv[i++], verbose);
7722 #if ENABLE_ASH_CMDCMD
7723 static int FAST_FUNC
7724 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7732 while ((c = nextopt("pvV")) != '\0')
7734 verify |= VERIFY_VERBOSE;
7736 verify |= VERIFY_BRIEF;
7741 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7742 if (verify && (*argptr != NULL)) {
7743 return describe_command(*argptr, verify - VERIFY_BRIEF);
7751 /* ============ eval.c */
7753 static int funcblocksize; /* size of structures in function */
7754 static int funcstringsize; /* size of strings in node */
7755 static void *funcblock; /* block to allocate function from */
7756 static char *funcstring; /* block to allocate strings from */
7758 /* flags in argument to evaltree */
7759 #define EV_EXIT 01 /* exit after evaluating tree */
7760 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7761 #define EV_BACKCMD 04 /* command executing within back quotes */
7763 static const uint8_t nodesize[N_NUMBER] = {
7764 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7765 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7766 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7767 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7768 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7769 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7770 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7771 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7772 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7773 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7774 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7775 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7776 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7777 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7778 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7779 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7780 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7781 #if ENABLE_ASH_BASH_COMPAT
7782 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7784 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7785 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7786 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7787 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7788 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7789 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7790 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7791 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7792 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7795 static void calcsize(union node *n);
7798 sizenodelist(struct nodelist *lp)
7801 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7808 calcsize(union node *n)
7812 funcblocksize += nodesize[n->type];
7815 calcsize(n->ncmd.redirect);
7816 calcsize(n->ncmd.args);
7817 calcsize(n->ncmd.assign);
7820 sizenodelist(n->npipe.cmdlist);
7825 calcsize(n->nredir.redirect);
7826 calcsize(n->nredir.n);
7833 calcsize(n->nbinary.ch2);
7834 calcsize(n->nbinary.ch1);
7837 calcsize(n->nif.elsepart);
7838 calcsize(n->nif.ifpart);
7839 calcsize(n->nif.test);
7842 funcstringsize += strlen(n->nfor.var) + 1;
7843 calcsize(n->nfor.body);
7844 calcsize(n->nfor.args);
7847 calcsize(n->ncase.cases);
7848 calcsize(n->ncase.expr);
7851 calcsize(n->nclist.body);
7852 calcsize(n->nclist.pattern);
7853 calcsize(n->nclist.next);
7857 sizenodelist(n->narg.backquote);
7858 funcstringsize += strlen(n->narg.text) + 1;
7859 calcsize(n->narg.next);
7862 #if ENABLE_ASH_BASH_COMPAT
7869 calcsize(n->nfile.fname);
7870 calcsize(n->nfile.next);
7874 calcsize(n->ndup.vname);
7875 calcsize(n->ndup.next);
7879 calcsize(n->nhere.doc);
7880 calcsize(n->nhere.next);
7883 calcsize(n->nnot.com);
7889 nodeckstrdup(char *s)
7891 char *rtn = funcstring;
7893 strcpy(funcstring, s);
7894 funcstring += strlen(s) + 1;
7898 static union node *copynode(union node *);
7900 static struct nodelist *
7901 copynodelist(struct nodelist *lp)
7903 struct nodelist *start;
7904 struct nodelist **lpp;
7909 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7910 (*lpp)->n = copynode(lp->n);
7912 lpp = &(*lpp)->next;
7919 copynode(union node *n)
7926 funcblock = (char *) funcblock + nodesize[n->type];
7930 new->ncmd.redirect = copynode(n->ncmd.redirect);
7931 new->ncmd.args = copynode(n->ncmd.args);
7932 new->ncmd.assign = copynode(n->ncmd.assign);
7935 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7936 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
7941 new->nredir.redirect = copynode(n->nredir.redirect);
7942 new->nredir.n = copynode(n->nredir.n);
7949 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7950 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7953 new->nif.elsepart = copynode(n->nif.elsepart);
7954 new->nif.ifpart = copynode(n->nif.ifpart);
7955 new->nif.test = copynode(n->nif.test);
7958 new->nfor.var = nodeckstrdup(n->nfor.var);
7959 new->nfor.body = copynode(n->nfor.body);
7960 new->nfor.args = copynode(n->nfor.args);
7963 new->ncase.cases = copynode(n->ncase.cases);
7964 new->ncase.expr = copynode(n->ncase.expr);
7967 new->nclist.body = copynode(n->nclist.body);
7968 new->nclist.pattern = copynode(n->nclist.pattern);
7969 new->nclist.next = copynode(n->nclist.next);
7973 new->narg.backquote = copynodelist(n->narg.backquote);
7974 new->narg.text = nodeckstrdup(n->narg.text);
7975 new->narg.next = copynode(n->narg.next);
7978 #if ENABLE_ASH_BASH_COMPAT
7985 new->nfile.fname = copynode(n->nfile.fname);
7986 new->nfile.fd = n->nfile.fd;
7987 new->nfile.next = copynode(n->nfile.next);
7991 new->ndup.vname = copynode(n->ndup.vname);
7992 new->ndup.dupfd = n->ndup.dupfd;
7993 new->ndup.fd = n->ndup.fd;
7994 new->ndup.next = copynode(n->ndup.next);
7998 new->nhere.doc = copynode(n->nhere.doc);
7999 new->nhere.fd = n->nhere.fd;
8000 new->nhere.next = copynode(n->nhere.next);
8003 new->nnot.com = copynode(n->nnot.com);
8006 new->type = n->type;
8011 * Make a copy of a parse tree.
8013 static struct funcnode *
8014 copyfunc(union node *n)
8019 funcblocksize = offsetof(struct funcnode, n);
8022 blocksize = funcblocksize;
8023 f = ckmalloc(blocksize + funcstringsize);
8024 funcblock = (char *) f + offsetof(struct funcnode, n);
8025 funcstring = (char *) f + blocksize;
8032 * Define a shell function.
8035 defun(char *name, union node *func)
8037 struct cmdentry entry;
8040 entry.cmdtype = CMDFUNCTION;
8041 entry.u.func = copyfunc(func);
8042 addcmdentry(name, &entry);
8046 /* Reasons for skipping commands (see comment on breakcmd routine) */
8047 #define SKIPBREAK (1 << 0)
8048 #define SKIPCONT (1 << 1)
8049 #define SKIPFUNC (1 << 2)
8050 #define SKIPFILE (1 << 3)
8051 #define SKIPEVAL (1 << 4)
8052 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8053 static int skipcount; /* number of levels to skip */
8054 static int funcnest; /* depth of function calls */
8055 static int loopnest; /* current loop nesting level */
8057 /* Forward decl way out to parsing code - dotrap needs it */
8058 static int evalstring(char *s, int mask);
8060 /* Called to execute a trap.
8061 * Single callsite - at the end of evaltree().
8062 * If we return non-zero, exaltree raises EXEXIT exception.
8064 * Perhaps we should avoid entering new trap handlers
8065 * while we are executing a trap handler. [is it a TODO?]
8074 savestatus = exitstatus;
8078 TRACE(("dotrap entered\n"));
8079 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8086 /* non-trapped SIGINT is handled separately by raise_interrupt,
8087 * don't upset it by resetting gotsig[SIGINT-1] */
8088 if (sig == SIGINT && !t)
8091 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8095 want_exexit = evalstring(t, SKIPEVAL);
8096 exitstatus = savestatus;
8098 TRACE(("dotrap returns %d\n", want_exexit));
8103 TRACE(("dotrap returns 0\n"));
8107 /* forward declarations - evaluation is fairly recursive business... */
8108 static void evalloop(union node *, int);
8109 static void evalfor(union node *, int);
8110 static void evalcase(union node *, int);
8111 static void evalsubshell(union node *, int);
8112 static void expredir(union node *);
8113 static void evalpipe(union node *, int);
8114 static void evalcommand(union node *, int);
8115 static int evalbltin(const struct builtincmd *, int, char **);
8116 static void prehash(union node *);
8119 * Evaluate a parse tree. The value is left in the global variable
8123 evaltree(union node *n, int flags)
8125 struct jmploc *volatile savehandler = exception_handler;
8126 struct jmploc jmploc;
8128 void (*evalfn)(union node *, int);
8132 SAVE_INT(int_level);
8135 TRACE(("evaltree(NULL) called\n"));
8138 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8140 exception_handler = &jmploc;
8142 int err = setjmp(jmploc.loc);
8144 /* if it was a signal, check for trap handlers */
8145 if (exception_type == EXSIG) {
8146 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8147 exception_type, err));
8150 /* continue on the way out */
8151 TRACE(("exception %d in evaltree, propagating err=%d\n",
8152 exception_type, err));
8153 exception_handler = savehandler;
8154 longjmp(exception_handler->loc, err);
8161 out1fmt("Node type = %d\n", n->type);
8166 evaltree(n->nnot.com, EV_TESTED);
8167 status = !exitstatus;
8170 expredir(n->nredir.redirect);
8171 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8173 evaltree(n->nredir.n, flags & EV_TESTED);
8174 status = exitstatus;
8176 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8179 evalfn = evalcommand;
8181 if (eflag && !(flags & EV_TESTED))
8193 evalfn = evalsubshell;
8206 #error NAND + 1 != NOR
8208 #if NOR + 1 != NSEMI
8209 #error NOR + 1 != NSEMI
8211 unsigned is_or = n->type - NAND;
8214 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8216 if (!exitstatus == is_or)
8229 evaltree(n->nif.test, EV_TESTED);
8232 if (exitstatus == 0) {
8236 if (n->nif.elsepart) {
8237 n = n->nif.elsepart;
8242 defun(n->narg.text, n->narg.next);
8246 exitstatus = status;
8251 exception_handler = savehandler;
8253 if (checkexit & exitstatus)
8254 evalskip |= SKIPEVAL;
8255 else if (pending_sig && dotrap())
8258 if (flags & EV_EXIT) {
8260 raise_exception(EXEXIT);
8263 RESTORE_INT(int_level);
8264 TRACE(("leaving evaltree (no interrupts)\n"));
8267 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8270 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8273 evalloop(union node *n, int flags)
8283 evaltree(n->nbinary.ch1, EV_TESTED);
8286 if (evalskip == SKIPCONT && --skipcount <= 0) {
8290 if (evalskip == SKIPBREAK && --skipcount <= 0)
8295 if (n->type != NWHILE)
8299 evaltree(n->nbinary.ch2, flags);
8300 status = exitstatus;
8305 exitstatus = status;
8309 evalfor(union node *n, int flags)
8311 struct arglist arglist;
8314 struct stackmark smark;
8316 setstackmark(&smark);
8317 arglist.list = NULL;
8318 arglist.lastp = &arglist.list;
8319 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8320 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8325 *arglist.lastp = NULL;
8330 for (sp = arglist.list; sp; sp = sp->next) {
8331 setvar(n->nfor.var, sp->text, 0);
8332 evaltree(n->nfor.body, flags);
8334 if (evalskip == SKIPCONT && --skipcount <= 0) {
8338 if (evalskip == SKIPBREAK && --skipcount <= 0)
8345 popstackmark(&smark);
8349 evalcase(union node *n, int flags)
8353 struct arglist arglist;
8354 struct stackmark smark;
8356 setstackmark(&smark);
8357 arglist.list = NULL;
8358 arglist.lastp = &arglist.list;
8359 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8361 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8362 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8363 if (casematch(patp, arglist.list->text)) {
8364 if (evalskip == 0) {
8365 evaltree(cp->nclist.body, flags);
8372 popstackmark(&smark);
8376 * Kick off a subshell to evaluate a tree.
8379 evalsubshell(union node *n, int flags)
8382 int backgnd = (n->type == NBACKGND);
8385 expredir(n->nredir.redirect);
8386 if (!backgnd && flags & EV_EXIT && !trap[0])
8389 jp = makejob(/*n,*/ 1);
8390 if (forkshell(jp, n, backgnd) == 0) {
8394 flags &=~ EV_TESTED;
8396 redirect(n->nredir.redirect, 0);
8397 evaltreenr(n->nredir.n, flags);
8402 status = waitforjob(jp);
8403 exitstatus = status;
8408 * Compute the names of the files in a redirection list.
8410 static void fixredir(union node *, const char *, int);
8412 expredir(union node *n)
8416 for (redir = n; redir; redir = redir->nfile.next) {
8420 fn.lastp = &fn.list;
8421 switch (redir->type) {
8425 #if ENABLE_ASH_BASH_COMPAT
8430 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8431 #if ENABLE_ASH_BASH_COMPAT
8434 redir->nfile.expfname = fn.list->text;
8437 case NTOFD: /* >& */
8438 if (redir->ndup.vname) {
8439 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8440 if (fn.list == NULL)
8441 ash_msg_and_raise_error("redir error");
8442 #if ENABLE_ASH_BASH_COMPAT
8443 //FIXME: we used expandarg with different args!
8444 if (!isdigit_str9(fn.list->text)) {
8445 /* >&file, not >&fd */
8446 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8447 ash_msg_and_raise_error("redir error");
8449 goto store_expfname;
8452 fixredir(redir, fn.list->text, 1);
8460 * Evaluate a pipeline. All the processes in the pipeline are children
8461 * of the process creating the pipeline. (This differs from some versions
8462 * of the shell, which make the last process in a pipeline the parent
8466 evalpipe(union node *n, int flags)
8469 struct nodelist *lp;
8474 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8476 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8480 jp = makejob(/*n,*/ pipelen);
8482 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8486 if (pipe(pip) < 0) {
8488 ash_msg_and_raise_error("pipe call failed");
8491 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8504 evaltreenr(lp->n, flags);
8510 /* Don't want to trigger debugging */
8514 if (n->npipe.pipe_backgnd == 0) {
8515 exitstatus = waitforjob(jp);
8516 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8522 * Controls whether the shell is interactive or not.
8525 setinteractive(int on)
8527 static smallint is_interactive;
8529 if (++on == is_interactive)
8531 is_interactive = on;
8535 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8536 if (is_interactive > 1) {
8537 /* Looks like they want an interactive shell */
8538 static smallint did_banner;
8541 /* note: ash and hush share this string */
8542 out1fmt("\n\n%s %s\n"
8543 "Enter 'help' for a list of built-in commands."
8546 "built-in shell (ash)"
8560 setinteractive(iflag);
8562 #if ENABLE_FEATURE_EDITING_VI
8564 line_input_state->flags |= VI_MODE;
8566 line_input_state->flags &= ~VI_MODE;
8568 viflag = 0; /* forcibly keep the option off */
8572 static struct localvar *localvars;
8575 * Called after a function returns.
8576 * Interrupts must be off.
8581 struct localvar *lvp;
8584 while ((lvp = localvars) != NULL) {
8585 localvars = lvp->next;
8587 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8588 if (vp == NULL) { /* $- saved */
8589 memcpy(optlist, lvp->text, sizeof(optlist));
8590 free((char*)lvp->text);
8592 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8596 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8597 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8598 free((char*)vp->text);
8599 vp->flags = lvp->flags;
8600 vp->text = lvp->text;
8607 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8609 volatile struct shparam saveparam;
8610 struct localvar *volatile savelocalvars;
8611 struct jmploc *volatile savehandler;
8612 struct jmploc jmploc;
8615 saveparam = shellparam;
8616 savelocalvars = localvars;
8617 e = setjmp(jmploc.loc);
8622 savehandler = exception_handler;
8623 exception_handler = &jmploc;
8625 shellparam.malloced = 0;
8629 shellparam.nparam = argc - 1;
8630 shellparam.p = argv + 1;
8631 #if ENABLE_ASH_GETOPTS
8632 shellparam.optind = 1;
8633 shellparam.optoff = -1;
8635 evaltree(&func->n, flags & EV_TESTED);
8641 localvars = savelocalvars;
8642 freeparam(&shellparam);
8643 shellparam = saveparam;
8644 exception_handler = savehandler;
8646 evalskip &= ~SKIPFUNC;
8650 #if ENABLE_ASH_CMDCMD
8652 parse_command_args(char **argv, const char **path)
8665 if (c == '-' && !*cp) {
8672 *path = bb_default_path;
8675 /* run 'typecmd' for other options */
8686 * Make a variable a local variable. When a variable is made local, it's
8687 * value and flags are saved in a localvar structure. The saved values
8688 * will be restored when the shell function returns. We handle the name
8689 * "-" as a special case.
8694 struct localvar *lvp;
8699 lvp = ckzalloc(sizeof(struct localvar));
8700 if (LONE_DASH(name)) {
8702 p = ckmalloc(sizeof(optlist));
8703 lvp->text = memcpy(p, optlist, sizeof(optlist));
8708 vpp = hashvar(name);
8709 vp = *findvar(vpp, name);
8710 eq = strchr(name, '=');
8713 setvareq(name, VSTRFIXED);
8715 setvar(name, NULL, VSTRFIXED);
8716 vp = *vpp; /* the new variable */
8717 lvp->flags = VUNSET;
8719 lvp->text = vp->text;
8720 lvp->flags = vp->flags;
8721 vp->flags |= VSTRFIXED|VTEXTFIXED;
8727 lvp->next = localvars;
8733 * The "local" command.
8735 static int FAST_FUNC
8736 localcmd(int argc UNUSED_PARAM, char **argv)
8741 while ((name = *argv++) != NULL) {
8747 static int FAST_FUNC
8748 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8753 static int FAST_FUNC
8754 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8759 static int FAST_FUNC
8760 execcmd(int argc UNUSED_PARAM, char **argv)
8763 iflag = 0; /* exit on error */
8766 shellexec(argv + 1, pathval(), 0);
8772 * The return command.
8774 static int FAST_FUNC
8775 returncmd(int argc UNUSED_PARAM, char **argv)
8778 * If called outside a function, do what ksh does;
8779 * skip the rest of the file.
8781 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8782 return argv[1] ? number(argv[1]) : exitstatus;
8785 /* Forward declarations for builtintab[] */
8786 static int breakcmd(int, char **) FAST_FUNC;
8787 static int dotcmd(int, char **) FAST_FUNC;
8788 static int evalcmd(int, char **) FAST_FUNC;
8789 static int exitcmd(int, char **) FAST_FUNC;
8790 static int exportcmd(int, char **) FAST_FUNC;
8791 #if ENABLE_ASH_GETOPTS
8792 static int getoptscmd(int, char **) FAST_FUNC;
8794 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8795 static int helpcmd(int, char **) FAST_FUNC;
8797 #if ENABLE_SH_MATH_SUPPORT
8798 static int letcmd(int, char **) FAST_FUNC;
8800 static int readcmd(int, char **) FAST_FUNC;
8801 static int setcmd(int, char **) FAST_FUNC;
8802 static int shiftcmd(int, char **) FAST_FUNC;
8803 static int timescmd(int, char **) FAST_FUNC;
8804 static int trapcmd(int, char **) FAST_FUNC;
8805 static int umaskcmd(int, char **) FAST_FUNC;
8806 static int unsetcmd(int, char **) FAST_FUNC;
8807 static int ulimitcmd(int, char **) FAST_FUNC;
8809 #define BUILTIN_NOSPEC "0"
8810 #define BUILTIN_SPECIAL "1"
8811 #define BUILTIN_REGULAR "2"
8812 #define BUILTIN_SPEC_REG "3"
8813 #define BUILTIN_ASSIGN "4"
8814 #define BUILTIN_SPEC_ASSG "5"
8815 #define BUILTIN_REG_ASSG "6"
8816 #define BUILTIN_SPEC_REG_ASSG "7"
8818 /* Stubs for calling non-FAST_FUNC's */
8819 #if ENABLE_ASH_BUILTIN_ECHO
8820 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8822 #if ENABLE_ASH_BUILTIN_PRINTF
8823 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8825 #if ENABLE_ASH_BUILTIN_TEST
8826 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8829 /* Keep these in proper order since it is searched via bsearch() */
8830 static const struct builtincmd builtintab[] = {
8831 { BUILTIN_SPEC_REG ".", dotcmd },
8832 { BUILTIN_SPEC_REG ":", truecmd },
8833 #if ENABLE_ASH_BUILTIN_TEST
8834 { BUILTIN_REGULAR "[", testcmd },
8835 #if ENABLE_ASH_BASH_COMPAT
8836 { BUILTIN_REGULAR "[[", testcmd },
8839 #if ENABLE_ASH_ALIAS
8840 { BUILTIN_REG_ASSG "alias", aliascmd },
8843 { BUILTIN_REGULAR "bg", fg_bgcmd },
8845 { BUILTIN_SPEC_REG "break", breakcmd },
8846 { BUILTIN_REGULAR "cd", cdcmd },
8847 { BUILTIN_NOSPEC "chdir", cdcmd },
8848 #if ENABLE_ASH_CMDCMD
8849 { BUILTIN_REGULAR "command", commandcmd },
8851 { BUILTIN_SPEC_REG "continue", breakcmd },
8852 #if ENABLE_ASH_BUILTIN_ECHO
8853 { BUILTIN_REGULAR "echo", echocmd },
8855 { BUILTIN_SPEC_REG "eval", evalcmd },
8856 { BUILTIN_SPEC_REG "exec", execcmd },
8857 { BUILTIN_SPEC_REG "exit", exitcmd },
8858 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8859 { BUILTIN_REGULAR "false", falsecmd },
8861 { BUILTIN_REGULAR "fg", fg_bgcmd },
8863 #if ENABLE_ASH_GETOPTS
8864 { BUILTIN_REGULAR "getopts", getoptscmd },
8866 { BUILTIN_NOSPEC "hash", hashcmd },
8867 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8868 { BUILTIN_NOSPEC "help", helpcmd },
8871 { BUILTIN_REGULAR "jobs", jobscmd },
8872 { BUILTIN_REGULAR "kill", killcmd },
8874 #if ENABLE_SH_MATH_SUPPORT
8875 { BUILTIN_NOSPEC "let", letcmd },
8877 { BUILTIN_ASSIGN "local", localcmd },
8878 #if ENABLE_ASH_BUILTIN_PRINTF
8879 { BUILTIN_REGULAR "printf", printfcmd },
8881 { BUILTIN_NOSPEC "pwd", pwdcmd },
8882 { BUILTIN_REGULAR "read", readcmd },
8883 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8884 { BUILTIN_SPEC_REG "return", returncmd },
8885 { BUILTIN_SPEC_REG "set", setcmd },
8886 { BUILTIN_SPEC_REG "shift", shiftcmd },
8887 { BUILTIN_SPEC_REG "source", dotcmd },
8888 #if ENABLE_ASH_BUILTIN_TEST
8889 { BUILTIN_REGULAR "test", testcmd },
8891 { BUILTIN_SPEC_REG "times", timescmd },
8892 { BUILTIN_SPEC_REG "trap", trapcmd },
8893 { BUILTIN_REGULAR "true", truecmd },
8894 { BUILTIN_NOSPEC "type", typecmd },
8895 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8896 { BUILTIN_REGULAR "umask", umaskcmd },
8897 #if ENABLE_ASH_ALIAS
8898 { BUILTIN_REGULAR "unalias", unaliascmd },
8900 { BUILTIN_SPEC_REG "unset", unsetcmd },
8901 { BUILTIN_REGULAR "wait", waitcmd },
8904 /* Should match the above table! */
8905 #define COMMANDCMD (builtintab + \
8907 1 * ENABLE_ASH_BUILTIN_TEST + \
8908 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8909 1 * ENABLE_ASH_ALIAS + \
8910 1 * ENABLE_ASH_JOB_CONTROL + \
8912 #define EXECCMD (builtintab + \
8914 1 * ENABLE_ASH_BUILTIN_TEST + \
8915 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8916 1 * ENABLE_ASH_ALIAS + \
8917 1 * ENABLE_ASH_JOB_CONTROL + \
8919 1 * ENABLE_ASH_CMDCMD + \
8921 ENABLE_ASH_BUILTIN_ECHO + \
8925 * Search the table of builtin commands.
8927 static struct builtincmd *
8928 find_builtin(const char *name)
8930 struct builtincmd *bp;
8933 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8940 * Execute a simple command.
8943 isassignment(const char *p)
8945 const char *q = endofname(p);
8950 static int FAST_FUNC
8951 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8953 /* Preserve exitstatus of a previous possible redirection
8954 * as POSIX mandates */
8955 return back_exitstatus;
8958 evalcommand(union node *cmd, int flags)
8960 static const struct builtincmd null_bltin = {
8961 "\0\0", bltincmd /* why three NULs? */
8963 struct stackmark smark;
8965 struct arglist arglist;
8966 struct arglist varlist;
8969 const struct strlist *sp;
8970 struct cmdentry cmdentry;
8977 struct builtincmd *bcmd;
8978 smallint cmd_is_exec;
8979 smallint pseudovarflag = 0;
8981 /* First expand the arguments. */
8982 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8983 setstackmark(&smark);
8984 back_exitstatus = 0;
8986 cmdentry.cmdtype = CMDBUILTIN;
8987 cmdentry.u.cmd = &null_bltin;
8988 varlist.lastp = &varlist.list;
8989 *varlist.lastp = NULL;
8990 arglist.lastp = &arglist.list;
8991 *arglist.lastp = NULL;
8994 if (cmd->ncmd.args) {
8995 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8996 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8999 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9000 struct strlist **spp;
9002 spp = arglist.lastp;
9003 if (pseudovarflag && isassignment(argp->narg.text))
9004 expandarg(argp, &arglist, EXP_VARTILDE);
9006 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9008 for (sp = *spp; sp; sp = sp->next)
9012 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9013 for (sp = arglist.list; sp; sp = sp->next) {
9014 TRACE(("evalcommand arg: %s\n", sp->text));
9015 *nargv++ = sp->text;
9020 if (iflag && funcnest == 0 && argc > 0)
9021 lastarg = nargv[-1];
9024 expredir(cmd->ncmd.redirect);
9025 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9028 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9029 struct strlist **spp;
9032 spp = varlist.lastp;
9033 expandarg(argp, &varlist, EXP_VARTILDE);
9036 * Modify the command lookup path, if a PATH= assignment
9040 if (varequal(p, path))
9044 /* Print the command if xflag is set. */
9047 const char *p = " %s";
9050 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9053 for (n = 0; n < 2; n++) {
9055 fdprintf(preverrout_fd, p, sp->text);
9063 safe_write(preverrout_fd, "\n", 1);
9069 /* Now locate the command. */
9071 const char *oldpath;
9072 int cmd_flag = DO_ERR;
9077 find_command(argv[0], &cmdentry, cmd_flag, path);
9078 if (cmdentry.cmdtype == CMDUNKNOWN) {
9079 flush_stdout_stderr();
9084 /* implement bltin and command here */
9085 if (cmdentry.cmdtype != CMDBUILTIN)
9088 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9089 if (cmdentry.u.cmd == EXECCMD)
9091 #if ENABLE_ASH_CMDCMD
9092 if (cmdentry.u.cmd == COMMANDCMD) {
9094 nargv = parse_command_args(argv, &path);
9097 argc -= nargv - argv;
9099 cmd_flag |= DO_NOFUNC;
9107 /* We have a redirection error. */
9109 raise_exception(EXERROR);
9111 exitstatus = status;
9115 /* Execute the command. */
9116 switch (cmdentry.cmdtype) {
9119 #if ENABLE_FEATURE_SH_NOFORK
9120 /* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9121 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
9123 /* find_command() encodes applet_no as (-2 - applet_no) */
9124 int applet_no = (- cmdentry.u.index - 2);
9125 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9126 listsetvar(varlist.list, VEXPORT|VSTACK);
9127 /* run <applet>_main() */
9128 exitstatus = run_nofork_applet(applet_no, argv);
9133 /* Fork off a child process if necessary. */
9134 if (!(flags & EV_EXIT) || trap[0]) {
9136 jp = makejob(/*cmd,*/ 1);
9137 if (forkshell(jp, cmd, FORK_FG) != 0) {
9138 exitstatus = waitforjob(jp);
9140 TRACE(("forked child exited with %d\n", exitstatus));
9145 listsetvar(varlist.list, VEXPORT|VSTACK);
9146 shellexec(argv, path, cmdentry.u.index);
9150 cmdenviron = varlist.list;
9152 struct strlist *list = cmdenviron;
9154 if (spclbltin > 0 || argc == 0) {
9156 if (cmd_is_exec && argc > 1)
9159 listsetvar(list, i);
9161 /* Tight loop with builtins only:
9162 * "while kill -0 $child; do true; done"
9163 * will never exit even if $child died, unless we do this
9164 * to reap the zombie and make kill detect that it's gone: */
9165 dowait(DOWAIT_NONBLOCK, NULL);
9167 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9169 int i = exception_type;
9174 exit_status = 128 + SIGINT;
9176 exit_status = 128 + pending_sig;
9177 exitstatus = exit_status;
9178 if (i == EXINT || spclbltin > 0) {
9180 longjmp(exception_handler->loc, 1);
9187 listsetvar(varlist.list, 0);
9188 /* See above for the rationale */
9189 dowait(DOWAIT_NONBLOCK, NULL);
9190 if (evalfun(cmdentry.u.func, argc, argv, flags))
9196 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9198 /* dsl: I think this is intended to be used to support
9199 * '_' in 'vi' command mode during line editing...
9200 * However I implemented that within libedit itself.
9202 setvar("_", lastarg, 0);
9204 popstackmark(&smark);
9208 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9210 char *volatile savecmdname;
9211 struct jmploc *volatile savehandler;
9212 struct jmploc jmploc;
9215 savecmdname = commandname;
9216 i = setjmp(jmploc.loc);
9219 savehandler = exception_handler;
9220 exception_handler = &jmploc;
9221 commandname = argv[0];
9223 optptr = NULL; /* initialize nextopt */
9224 exitstatus = (*cmd->builtin)(argc, argv);
9225 flush_stdout_stderr();
9227 exitstatus |= ferror(stdout);
9229 commandname = savecmdname;
9230 exception_handler = savehandler;
9236 goodname(const char *p)
9238 return !*endofname(p);
9243 * Search for a command. This is called before we fork so that the
9244 * location of the command will be available in the parent as well as
9245 * the child. The check for "goodname" is an overly conservative
9246 * check that the name will not be subject to expansion.
9249 prehash(union node *n)
9251 struct cmdentry entry;
9253 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9254 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9258 /* ============ Builtin commands
9260 * Builtin commands whose functions are closely tied to evaluation
9261 * are implemented here.
9265 * Handle break and continue commands. Break, continue, and return are
9266 * all handled by setting the evalskip flag. The evaluation routines
9267 * above all check this flag, and if it is set they start skipping
9268 * commands rather than executing them. The variable skipcount is
9269 * the number of loops to break/continue, or the number of function
9270 * levels to return. (The latter is always 1.) It should probably
9271 * be an error to break out of more loops than exist, but it isn't
9272 * in the standard shell so we don't make it one here.
9274 static int FAST_FUNC
9275 breakcmd(int argc UNUSED_PARAM, char **argv)
9277 int n = argv[1] ? number(argv[1]) : 1;
9280 ash_msg_and_raise_error(msg_illnum, argv[1]);
9284 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9291 /* ============ input.c
9293 * This implements the input routines used by the parser.
9297 INPUT_PUSH_FILE = 1,
9298 INPUT_NOFILE_OK = 2,
9301 static smallint checkkwd;
9302 /* values of checkkwd variable */
9303 #define CHKALIAS 0x1
9308 * Push a string back onto the input at this current parsefile level.
9309 * We handle aliases this way.
9311 #if !ENABLE_ASH_ALIAS
9312 #define pushstring(s, ap) pushstring(s)
9315 pushstring(char *s, struct alias *ap)
9322 if (g_parsefile->strpush) {
9323 sp = ckzalloc(sizeof(*sp));
9324 sp->prev = g_parsefile->strpush;
9326 sp = &(g_parsefile->basestrpush);
9328 g_parsefile->strpush = sp;
9329 sp->prev_string = g_parsefile->next_to_pgetc;
9330 sp->prev_left_in_line = g_parsefile->left_in_line;
9331 #if ENABLE_ASH_ALIAS
9334 ap->flag |= ALIASINUSE;
9338 g_parsefile->next_to_pgetc = s;
9339 g_parsefile->left_in_line = len;
9346 struct strpush *sp = g_parsefile->strpush;
9349 #if ENABLE_ASH_ALIAS
9351 if (g_parsefile->next_to_pgetc[-1] == ' '
9352 || g_parsefile->next_to_pgetc[-1] == '\t'
9354 checkkwd |= CHKALIAS;
9356 if (sp->string != sp->ap->val) {
9359 sp->ap->flag &= ~ALIASINUSE;
9360 if (sp->ap->flag & ALIASDEAD) {
9361 unalias(sp->ap->name);
9365 g_parsefile->next_to_pgetc = sp->prev_string;
9366 g_parsefile->left_in_line = sp->prev_left_in_line;
9367 g_parsefile->strpush = sp->prev;
9368 if (sp != &(g_parsefile->basestrpush))
9373 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9374 //it peeks whether it is &>, and then pushes back both chars.
9375 //This function needs to save last *next_to_pgetc to buf[0]
9376 //to make two pungetc() reliable. Currently,
9377 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9382 char *buf = g_parsefile->buf;
9384 g_parsefile->next_to_pgetc = buf;
9385 #if ENABLE_FEATURE_EDITING
9387 if (!iflag || g_parsefile->fd != STDIN_FILENO)
9388 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9390 #if ENABLE_FEATURE_TAB_COMPLETION
9391 line_input_state->path_lookup = pathval();
9393 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9395 /* Ctrl+C pressed */
9404 if (nr < 0 && errno == 0) {
9405 /* Ctrl+D pressed */
9410 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9414 /* nonblock_safe_read() handles this problem */
9416 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9417 int flags = fcntl(0, F_GETFL);
9418 if (flags >= 0 && (flags & O_NONBLOCK)) {
9419 flags &= ~O_NONBLOCK;
9420 if (fcntl(0, F_SETFL, flags) >= 0) {
9421 out2str("sh: turning off NDELAY mode\n");
9432 * Refill the input buffer and return the next input character:
9434 * 1) If a string was pushed back on the input, pop it;
9435 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9436 * or we are reading from a string so we can't refill the buffer,
9438 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9439 * 4) Process input up to the next newline, deleting nul characters.
9441 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9442 #define pgetc_debug(...) ((void)0)
9449 while (g_parsefile->strpush) {
9450 #if ENABLE_ASH_ALIAS
9451 if (g_parsefile->left_in_line == -1
9452 && g_parsefile->strpush->ap
9453 && g_parsefile->next_to_pgetc[-1] != ' '
9454 && g_parsefile->next_to_pgetc[-1] != '\t'
9456 pgetc_debug("preadbuffer PEOA");
9461 /* try "pgetc" now: */
9462 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9463 g_parsefile->left_in_line,
9464 g_parsefile->next_to_pgetc,
9465 g_parsefile->next_to_pgetc);
9466 if (--g_parsefile->left_in_line >= 0)
9467 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9469 /* on both branches above g_parsefile->left_in_line < 0.
9470 * "pgetc" needs refilling.
9473 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9474 * pungetc() may increment it a few times.
9475 * Assuming it won't increment it to less than -90.
9477 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9478 pgetc_debug("preadbuffer PEOF1");
9479 /* even in failure keep left_in_line and next_to_pgetc
9480 * in lock step, for correct multi-layer pungetc.
9481 * left_in_line was decremented before preadbuffer(),
9482 * must inc next_to_pgetc: */
9483 g_parsefile->next_to_pgetc++;
9487 more = g_parsefile->left_in_buffer;
9489 flush_stdout_stderr();
9493 /* don't try reading again */
9494 g_parsefile->left_in_line = -99;
9495 pgetc_debug("preadbuffer PEOF2");
9496 g_parsefile->next_to_pgetc++;
9501 /* Find out where's the end of line.
9502 * Set g_parsefile->left_in_line
9503 * and g_parsefile->left_in_buffer acordingly.
9504 * NUL chars are deleted.
9506 q = g_parsefile->next_to_pgetc;
9514 memmove(q, q + 1, more);
9518 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9524 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9525 if (g_parsefile->left_in_line < 0)
9530 g_parsefile->left_in_buffer = more;
9535 out2str(g_parsefile->next_to_pgetc);
9539 pgetc_debug("preadbuffer at %d:%p'%s'",
9540 g_parsefile->left_in_line,
9541 g_parsefile->next_to_pgetc,
9542 g_parsefile->next_to_pgetc);
9543 return (unsigned char)*g_parsefile->next_to_pgetc++;
9546 #define pgetc_as_macro() \
9547 (--g_parsefile->left_in_line >= 0 \
9548 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9555 pgetc_debug("pgetc_fast at %d:%p'%s'",
9556 g_parsefile->left_in_line,
9557 g_parsefile->next_to_pgetc,
9558 g_parsefile->next_to_pgetc);
9559 return pgetc_as_macro();
9562 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9563 # define pgetc_fast() pgetc()
9565 # define pgetc_fast() pgetc_as_macro()
9568 #if ENABLE_ASH_ALIAS
9570 pgetc_without_PEOA(void)
9574 pgetc_debug("pgetc_fast at %d:%p'%s'",
9575 g_parsefile->left_in_line,
9576 g_parsefile->next_to_pgetc,
9577 g_parsefile->next_to_pgetc);
9579 } while (c == PEOA);
9583 # define pgetc_without_PEOA() pgetc()
9587 * Read a line from the script.
9590 pfgets(char *line, int len)
9596 while (--nleft > 0) {
9597 c = pgetc_without_PEOA();
9612 * Undo the last call to pgetc. Only one character may be pushed back.
9613 * PEOF may be pushed back.
9618 g_parsefile->left_in_line++;
9619 g_parsefile->next_to_pgetc--;
9620 pgetc_debug("pushed back to %d:%p'%s'",
9621 g_parsefile->left_in_line,
9622 g_parsefile->next_to_pgetc,
9623 g_parsefile->next_to_pgetc);
9627 * To handle the "." command, a stack of input files is used. Pushfile
9628 * adds a new entry to the stack and popfile restores the previous level.
9633 struct parsefile *pf;
9635 pf = ckzalloc(sizeof(*pf));
9636 pf->prev = g_parsefile;
9638 /*pf->strpush = NULL; - ckzalloc did it */
9639 /*pf->basestrpush.prev = NULL;*/
9646 struct parsefile *pf = g_parsefile;
9654 g_parsefile = pf->prev;
9660 * Return to top level.
9665 while (g_parsefile != &basepf)
9670 * Close the file(s) that the shell is reading commands from. Called
9671 * after a fork is done.
9677 if (g_parsefile->fd > 0) {
9678 close(g_parsefile->fd);
9679 g_parsefile->fd = 0;
9684 * Like setinputfile, but takes an open file descriptor. Call this with
9688 setinputfd(int fd, int push)
9690 close_on_exec_on(fd);
9693 g_parsefile->buf = NULL;
9695 g_parsefile->fd = fd;
9696 if (g_parsefile->buf == NULL)
9697 g_parsefile->buf = ckmalloc(IBUFSIZ);
9698 g_parsefile->left_in_buffer = 0;
9699 g_parsefile->left_in_line = 0;
9700 g_parsefile->linno = 1;
9704 * Set the input to take input from a file. If push is set, push the
9705 * old input onto the stack first.
9708 setinputfile(const char *fname, int flags)
9714 fd = open(fname, O_RDONLY);
9716 if (flags & INPUT_NOFILE_OK)
9718 ash_msg_and_raise_error("can't open '%s'", fname);
9721 fd2 = copyfd(fd, 10);
9724 ash_msg_and_raise_error("out of file descriptors");
9727 setinputfd(fd, flags & INPUT_PUSH_FILE);
9734 * Like setinputfile, but takes input from a string.
9737 setinputstring(char *string)
9741 g_parsefile->next_to_pgetc = string;
9742 g_parsefile->left_in_line = strlen(string);
9743 g_parsefile->buf = NULL;
9744 g_parsefile->linno = 1;
9749 /* ============ mail.c
9751 * Routines to check for mail.
9756 #define MAXMBOXES 10
9758 /* times of mailboxes */
9759 static time_t mailtime[MAXMBOXES];
9760 /* Set if MAIL or MAILPATH is changed. */
9761 static smallint mail_var_path_changed;
9764 * Print appropriate message(s) if mail has arrived.
9765 * If mail_var_path_changed is set,
9766 * then the value of MAIL has mail_var_path_changed,
9767 * so we just update the values.
9776 struct stackmark smark;
9779 setstackmark(&smark);
9780 mpath = mpathset() ? mpathval() : mailval();
9781 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9782 p = path_advance(&mpath, nullstr);
9787 for (q = p; *q; q++)
9793 q[-1] = '\0'; /* delete trailing '/' */
9794 if (stat(p, &statb) < 0) {
9798 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9801 pathopt ? pathopt : "you have mail"
9804 *mtp = statb.st_mtime;
9806 mail_var_path_changed = 0;
9807 popstackmark(&smark);
9810 static void FAST_FUNC
9811 changemail(const char *val UNUSED_PARAM)
9813 mail_var_path_changed = 1;
9816 #endif /* ASH_MAIL */
9819 /* ============ ??? */
9822 * Set the shell parameters.
9825 setparam(char **argv)
9831 for (nparam = 0; argv[nparam]; nparam++)
9833 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9835 *ap++ = ckstrdup(*argv++);
9838 freeparam(&shellparam);
9839 shellparam.malloced = 1;
9840 shellparam.nparam = nparam;
9841 shellparam.p = newparam;
9842 #if ENABLE_ASH_GETOPTS
9843 shellparam.optind = 1;
9844 shellparam.optoff = -1;
9849 * Process shell options. The global variable argptr contains a pointer
9850 * to the argument list; we advance it past the options.
9852 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9853 * For a non-interactive shell, an error condition encountered
9854 * by a special built-in ... shall cause the shell to write a diagnostic message
9855 * to standard error and exit as shown in the following table:
9856 * Error Special Built-In
9858 * Utility syntax error (option or operand error) Shall exit
9860 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9861 * we see that bash does not do that (set "finishes" with error code 1 instead,
9862 * and shell continues), and people rely on this behavior!
9864 * set -o barfoo 2>/dev/null
9867 * Oh well. Let's mimic that.
9870 plus_minus_o(char *name, int val)
9875 for (i = 0; i < NOPTS; i++) {
9876 if (strcmp(name, optnames(i)) == 0) {
9881 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9884 for (i = 0; i < NOPTS; i++) {
9886 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9888 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9894 setoption(int flag, int val)
9898 for (i = 0; i < NOPTS; i++) {
9899 if (optletters(i) == flag) {
9904 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9908 options(int cmdline)
9916 while ((p = *argptr) != NULL) {
9918 if (c != '-' && c != '+')
9921 val = 0; /* val = 0 if c == '+' */
9924 if (p[0] == '\0' || LONE_DASH(p)) {
9926 /* "-" means turn off -x and -v */
9929 /* "--" means reset params */
9930 else if (*argptr == NULL)
9933 break; /* "-" or "--" terminates options */
9936 /* first char was + or - */
9937 while ((c = *p++) != '\0') {
9938 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9939 if (c == 'c' && cmdline) {
9940 minusc = p; /* command is after shell args */
9941 } else if (c == 'o') {
9942 if (plus_minus_o(*argptr, val)) {
9943 /* it already printed err message */
9944 return 1; /* error */
9948 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9950 /* bash does not accept +-login, we also won't */
9951 } else if (cmdline && val && (c == '-')) { /* long options */
9952 if (strcmp(p, "login") == 0)
9964 * The shift builtin command.
9966 static int FAST_FUNC
9967 shiftcmd(int argc UNUSED_PARAM, char **argv)
9974 n = number(argv[1]);
9975 if (n > shellparam.nparam)
9976 n = 0; /* bash compat, was = shellparam.nparam; */
9978 shellparam.nparam -= n;
9979 for (ap1 = shellparam.p; --n >= 0; ap1++) {
9980 if (shellparam.malloced)
9984 while ((*ap2++ = *ap1++) != NULL)
9986 #if ENABLE_ASH_GETOPTS
9987 shellparam.optind = 1;
9988 shellparam.optoff = -1;
9995 * POSIX requires that 'set' (but not export or readonly) output the
9996 * variables in lexicographic order - by the locale's collating order (sigh).
9997 * Maybe we could keep them in an ordered balanced binary tree
9998 * instead of hashed lists.
9999 * For now just roll 'em through qsort for printing...
10002 showvars(const char *sep_prefix, int on, int off)
10005 char **ep, **epend;
10007 ep = listvars(on, off, &epend);
10008 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10010 sep = *sep_prefix ? " " : sep_prefix;
10012 for (; ep < epend; ep++) {
10016 p = strchrnul(*ep, '=');
10019 q = single_quote(++p);
10020 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10026 * The set command builtin.
10028 static int FAST_FUNC
10029 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10034 return showvars(nullstr, 0, VUNSET);
10037 if (!options(0)) { /* if no parse error... */
10040 if (*argptr != NULL) {
10048 #if ENABLE_ASH_RANDOM_SUPPORT
10049 static void FAST_FUNC
10050 change_random(const char *value)
10054 if (value == NULL) {
10055 /* "get", generate */
10056 t = next_random(&random_gen);
10057 /* set without recursion */
10058 setvar(vrandom.text, utoa(t), VNOFUNC);
10059 vrandom.flags &= ~VNOFUNC;
10062 t = strtoul(value, NULL, 10);
10063 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10068 #if ENABLE_ASH_GETOPTS
10070 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10079 if (*param_optind < 1)
10081 optnext = optfirst + *param_optind - 1;
10083 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10086 p = optnext[-1] + *optoff;
10087 if (p == NULL || *p == '\0') {
10088 /* Current word is done, advance */
10090 if (p == NULL || *p != '-' || *++p == '\0') {
10097 if (LONE_DASH(p)) /* check for "--" */
10102 for (q = optstr; *q != c;) {
10104 if (optstr[0] == ':') {
10107 err |= setvarsafe("OPTARG", s, 0);
10109 fprintf(stderr, "Illegal option -%c\n", c);
10110 unsetvar("OPTARG");
10120 if (*p == '\0' && (p = *optnext) == NULL) {
10121 if (optstr[0] == ':') {
10124 err |= setvarsafe("OPTARG", s, 0);
10127 fprintf(stderr, "No arg for -%c option\n", c);
10128 unsetvar("OPTARG");
10136 err |= setvarsafe("OPTARG", p, 0);
10139 err |= setvarsafe("OPTARG", nullstr, 0);
10141 *optoff = p ? p - *(optnext - 1) : -1;
10142 *param_optind = optnext - optfirst + 1;
10143 fmtstr(s, sizeof(s), "%d", *param_optind);
10144 err |= setvarsafe("OPTIND", s, VNOFUNC);
10147 err |= setvarsafe(optvar, s, 0);
10151 flush_stdout_stderr();
10152 raise_exception(EXERROR);
10158 * The getopts builtin. Shellparam.optnext points to the next argument
10159 * to be processed. Shellparam.optptr points to the next character to
10160 * be processed in the current argument. If shellparam.optnext is NULL,
10161 * then it's the first time getopts has been called.
10163 static int FAST_FUNC
10164 getoptscmd(int argc, char **argv)
10169 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10171 optbase = shellparam.p;
10172 if (shellparam.optind > shellparam.nparam + 1) {
10173 shellparam.optind = 1;
10174 shellparam.optoff = -1;
10177 optbase = &argv[3];
10178 if (shellparam.optind > argc - 2) {
10179 shellparam.optind = 1;
10180 shellparam.optoff = -1;
10184 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10185 &shellparam.optoff);
10187 #endif /* ASH_GETOPTS */
10190 /* ============ Shell parser */
10193 struct heredoc *next; /* next here document in list */
10194 union node *here; /* redirection node */
10195 char *eofmark; /* string indicating end of input */
10196 smallint striptabs; /* if set, strip leading tabs */
10199 static smallint tokpushback; /* last token pushed back */
10200 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10201 static smallint quoteflag; /* set if (part of) last token was quoted */
10202 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10203 static struct heredoc *heredoclist; /* list of here documents to read */
10204 static char *wordtext; /* text of last word returned by readtoken */
10205 static struct nodelist *backquotelist;
10206 static union node *redirnode;
10207 static struct heredoc *heredoc;
10210 * Called when an unexpected token is read during the parse. The argument
10211 * is the token that is expected, or -1 if more than one type of token can
10212 * occur at this point.
10214 static void raise_error_unexpected_syntax(int) NORETURN;
10216 raise_error_unexpected_syntax(int token)
10221 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
10223 sprintf(msg + l, " (expecting %s)", tokname(token));
10224 raise_error_syntax(msg);
10228 #define EOFMARKLEN 79
10230 /* parsing is heavily cross-recursive, need these forward decls */
10231 static union node *andor(void);
10232 static union node *pipeline(void);
10233 static union node *parse_command(void);
10234 static void parseheredoc(void);
10235 static char peektoken(void);
10236 static int readtoken(void);
10238 static union node *
10241 union node *n1, *n2, *n3;
10244 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10245 if (nlflag == 2 && peektoken())
10251 if (tok == TBACKGND) {
10252 if (n2->type == NPIPE) {
10253 n2->npipe.pipe_backgnd = 1;
10255 if (n2->type != NREDIR) {
10256 n3 = stzalloc(sizeof(struct nredir));
10258 /*n3->nredir.redirect = NULL; - stzalloc did it */
10261 n2->type = NBACKGND;
10267 n3 = stzalloc(sizeof(struct nbinary));
10269 n3->nbinary.ch1 = n1;
10270 n3->nbinary.ch2 = n2;
10286 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10294 pungetc(); /* push back EOF on input */
10298 raise_error_unexpected_syntax(-1);
10305 static union node *
10308 union node *n1, *n2, *n3;
10316 } else if (t == TOR) {
10322 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10324 n3 = stzalloc(sizeof(struct nbinary));
10326 n3->nbinary.ch1 = n1;
10327 n3->nbinary.ch2 = n2;
10332 static union node *
10335 union node *n1, *n2, *pipenode;
10336 struct nodelist *lp, *prev;
10340 TRACE(("pipeline: entered\n"));
10341 if (readtoken() == TNOT) {
10343 checkkwd = CHKKWD | CHKALIAS;
10346 n1 = parse_command();
10347 if (readtoken() == TPIPE) {
10348 pipenode = stzalloc(sizeof(struct npipe));
10349 pipenode->type = NPIPE;
10350 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10351 lp = stzalloc(sizeof(struct nodelist));
10352 pipenode->npipe.cmdlist = lp;
10356 lp = stzalloc(sizeof(struct nodelist));
10357 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10358 lp->n = parse_command();
10360 } while (readtoken() == TPIPE);
10366 n2 = stzalloc(sizeof(struct nnot));
10374 static union node *
10379 n = stzalloc(sizeof(struct narg));
10381 /*n->narg.next = NULL; - stzalloc did it */
10382 n->narg.text = wordtext;
10383 n->narg.backquote = backquotelist;
10388 fixredir(union node *n, const char *text, int err)
10392 TRACE(("Fix redir %s %d\n", text, err));
10394 n->ndup.vname = NULL;
10396 fd = bb_strtou(text, NULL, 10);
10397 if (!errno && fd >= 0)
10398 n->ndup.dupfd = fd;
10399 else if (LONE_DASH(text))
10400 n->ndup.dupfd = -1;
10403 raise_error_syntax("bad fd number");
10404 n->ndup.vname = makename();
10409 * Returns true if the text contains nothing to expand (no dollar signs
10413 noexpand(const char *text)
10417 while ((c = *text++) != '\0') {
10418 if (c == CTLQUOTEMARK)
10422 else if (SIT(c, BASESYNTAX) == CCTL)
10431 union node *n = redirnode;
10433 if (readtoken() != TWORD)
10434 raise_error_unexpected_syntax(-1);
10435 if (n->type == NHERE) {
10436 struct heredoc *here = heredoc;
10440 if (quoteflag == 0)
10442 TRACE(("Here document %d\n", n->type));
10443 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10444 raise_error_syntax("illegal eof marker for << redirection");
10445 rmescapes(wordtext, 0);
10446 here->eofmark = wordtext;
10448 if (heredoclist == NULL)
10449 heredoclist = here;
10451 for (p = heredoclist; p->next; p = p->next)
10455 } else if (n->type == NTOFD || n->type == NFROMFD) {
10456 fixredir(n, wordtext, 0);
10458 n->nfile.fname = makename();
10462 static union node *
10465 union node *args, **app;
10466 union node *n = NULL;
10467 union node *vars, **vpp;
10468 union node **rpp, *redir;
10470 #if ENABLE_ASH_BASH_COMPAT
10471 smallint double_brackets_flag = 0;
10481 savecheckkwd = CHKALIAS;
10484 checkkwd = savecheckkwd;
10487 #if ENABLE_ASH_BASH_COMPAT
10488 case TAND: /* "&&" */
10489 case TOR: /* "||" */
10490 if (!double_brackets_flag) {
10494 wordtext = (char *) (t == TAND ? "-a" : "-o");
10497 n = stzalloc(sizeof(struct narg));
10499 /*n->narg.next = NULL; - stzalloc did it */
10500 n->narg.text = wordtext;
10501 #if ENABLE_ASH_BASH_COMPAT
10502 if (strcmp("[[", wordtext) == 0)
10503 double_brackets_flag = 1;
10504 else if (strcmp("]]", wordtext) == 0)
10505 double_brackets_flag = 0;
10507 n->narg.backquote = backquotelist;
10508 if (savecheckkwd && isassignment(wordtext)) {
10510 vpp = &n->narg.next;
10513 app = &n->narg.next;
10518 *rpp = n = redirnode;
10519 rpp = &n->nfile.next;
10520 parsefname(); /* read name of redirection file */
10523 if (args && app == &args->narg.next
10526 struct builtincmd *bcmd;
10529 /* We have a function */
10530 if (readtoken() != TRP)
10531 raise_error_unexpected_syntax(TRP);
10532 name = n->narg.text;
10533 if (!goodname(name)
10534 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10536 raise_error_syntax("bad function name");
10539 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10540 n->narg.next = parse_command();
10553 n = stzalloc(sizeof(struct ncmd));
10555 n->ncmd.args = args;
10556 n->ncmd.assign = vars;
10557 n->ncmd.redirect = redir;
10561 static union node *
10562 parse_command(void)
10564 union node *n1, *n2;
10565 union node *ap, **app;
10566 union node *cp, **cpp;
10567 union node *redir, **rpp;
10574 switch (readtoken()) {
10576 raise_error_unexpected_syntax(-1);
10579 n1 = stzalloc(sizeof(struct nif));
10581 n1->nif.test = list(0);
10582 if (readtoken() != TTHEN)
10583 raise_error_unexpected_syntax(TTHEN);
10584 n1->nif.ifpart = list(0);
10586 while (readtoken() == TELIF) {
10587 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10588 n2 = n2->nif.elsepart;
10590 n2->nif.test = list(0);
10591 if (readtoken() != TTHEN)
10592 raise_error_unexpected_syntax(TTHEN);
10593 n2->nif.ifpart = list(0);
10595 if (lasttoken == TELSE)
10596 n2->nif.elsepart = list(0);
10598 n2->nif.elsepart = NULL;
10606 n1 = stzalloc(sizeof(struct nbinary));
10607 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10608 n1->nbinary.ch1 = list(0);
10611 TRACE(("expecting DO got %s %s\n", tokname(got),
10612 got == TWORD ? wordtext : ""));
10613 raise_error_unexpected_syntax(TDO);
10615 n1->nbinary.ch2 = list(0);
10620 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10621 raise_error_syntax("bad for loop variable");
10622 n1 = stzalloc(sizeof(struct nfor));
10624 n1->nfor.var = wordtext;
10625 checkkwd = CHKKWD | CHKALIAS;
10626 if (readtoken() == TIN) {
10628 while (readtoken() == TWORD) {
10629 n2 = stzalloc(sizeof(struct narg));
10631 /*n2->narg.next = NULL; - stzalloc did it */
10632 n2->narg.text = wordtext;
10633 n2->narg.backquote = backquotelist;
10635 app = &n2->narg.next;
10638 n1->nfor.args = ap;
10639 if (lasttoken != TNL && lasttoken != TSEMI)
10640 raise_error_unexpected_syntax(-1);
10642 n2 = stzalloc(sizeof(struct narg));
10644 /*n2->narg.next = NULL; - stzalloc did it */
10645 n2->narg.text = (char *)dolatstr;
10646 /*n2->narg.backquote = NULL;*/
10647 n1->nfor.args = n2;
10649 * Newline or semicolon here is optional (but note
10650 * that the original Bourne shell only allowed NL).
10652 if (lasttoken != TNL && lasttoken != TSEMI)
10655 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10656 if (readtoken() != TDO)
10657 raise_error_unexpected_syntax(TDO);
10658 n1->nfor.body = list(0);
10662 n1 = stzalloc(sizeof(struct ncase));
10664 if (readtoken() != TWORD)
10665 raise_error_unexpected_syntax(TWORD);
10666 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10668 /*n2->narg.next = NULL; - stzalloc did it */
10669 n2->narg.text = wordtext;
10670 n2->narg.backquote = backquotelist;
10672 checkkwd = CHKKWD | CHKALIAS;
10673 } while (readtoken() == TNL);
10674 if (lasttoken != TIN)
10675 raise_error_unexpected_syntax(TIN);
10676 cpp = &n1->ncase.cases;
10678 checkkwd = CHKNL | CHKKWD;
10680 while (t != TESAC) {
10681 if (lasttoken == TLP)
10683 *cpp = cp = stzalloc(sizeof(struct nclist));
10685 app = &cp->nclist.pattern;
10687 *app = ap = stzalloc(sizeof(struct narg));
10689 /*ap->narg.next = NULL; - stzalloc did it */
10690 ap->narg.text = wordtext;
10691 ap->narg.backquote = backquotelist;
10692 if (readtoken() != TPIPE)
10694 app = &ap->narg.next;
10697 //ap->narg.next = NULL;
10698 if (lasttoken != TRP)
10699 raise_error_unexpected_syntax(TRP);
10700 cp->nclist.body = list(2);
10702 cpp = &cp->nclist.next;
10704 checkkwd = CHKNL | CHKKWD;
10708 raise_error_unexpected_syntax(TENDCASE);
10715 n1 = stzalloc(sizeof(struct nredir));
10716 n1->type = NSUBSHELL;
10717 n1->nredir.n = list(0);
10718 /*n1->nredir.redirect = NULL; - stzalloc did it */
10728 return simplecmd();
10731 if (readtoken() != t)
10732 raise_error_unexpected_syntax(t);
10735 /* Now check for redirection which may follow command */
10736 checkkwd = CHKKWD | CHKALIAS;
10738 while (readtoken() == TREDIR) {
10739 *rpp = n2 = redirnode;
10740 rpp = &n2->nfile.next;
10746 if (n1->type != NSUBSHELL) {
10747 n2 = stzalloc(sizeof(struct nredir));
10752 n1->nredir.redirect = redir;
10757 #if ENABLE_ASH_BASH_COMPAT
10758 static int decode_dollar_squote(void)
10760 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10766 p = strchr(C_escapes, c);
10771 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10775 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10777 } else if (c == 'x') { /* \xHH */
10781 } while (isxdigit(c) && --cnt);
10783 if (cnt == 3) { /* \x but next char is "bad" */
10787 } else { /* simple seq like \\ or \t */
10792 c = bb_process_escape_sequence((void*)&p);
10793 } else { /* unrecognized "\z": print both chars unless ' or " */
10794 if (c != '\'' && c != '"') {
10796 c |= 0x100; /* "please encode \, then me" */
10804 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10805 * is not NULL, read a here document. In the latter case, eofmark is the
10806 * word which marks the end of the document and striptabs is true if
10807 * leading tabs should be stripped from the document. The argument c
10808 * is the first character of the input token or document.
10810 * Because C does not have internal subroutines, I have simulated them
10811 * using goto's to implement the subroutine linkage. The following macros
10812 * will run code that appears at the end of readtoken1.
10814 #define CHECKEND() {goto checkend; checkend_return:;}
10815 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10816 #define PARSESUB() {goto parsesub; parsesub_return:;}
10817 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10818 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10819 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10821 readtoken1(int c, int syntax, char *eofmark, int striptabs)
10823 /* NB: syntax parameter fits into smallint */
10824 /* c parameter is an unsigned char or PEOF or PEOA */
10827 char line[EOFMARKLEN + 1];
10828 struct nodelist *bqlist;
10832 smallint prevsyntax; /* syntax before arithmetic */
10833 #if ENABLE_ASH_EXPAND_PRMT
10834 smallint pssyntax; /* we are expanding a prompt string */
10836 int varnest; /* levels of variables expansion */
10837 int arinest; /* levels of arithmetic expansion */
10838 int parenlevel; /* levels of parens in arithmetic */
10839 int dqvarnest; /* levels of variables expansion within double quotes */
10841 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10844 /* Avoid longjmp clobbering */
10850 (void) &parenlevel;
10853 (void) &prevsyntax;
10856 startlinno = g_parsefile->linno;
10861 #if ENABLE_ASH_EXPAND_PRMT
10862 pssyntax = (syntax == PSSYNTAX);
10866 dblquote = (syntax == DQSYNTAX);
10872 STARTSTACKSTR(out);
10874 /* For each line, until end of word */
10876 CHECKEND(); /* set c to PEOF if at end of here document */
10877 for (;;) { /* until end of line or end of word */
10878 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10879 switch (SIT(c, syntax)) {
10880 case CNL: /* '\n' */
10881 if (syntax == BASESYNTAX)
10882 goto endword; /* exit outer loop */
10884 g_parsefile->linno++;
10888 goto loop; /* continue outer loop */
10893 if (eofmark == NULL || dblquote)
10894 USTPUTC(CTLESC, out);
10895 #if ENABLE_ASH_BASH_COMPAT
10896 if (c == '\\' && bash_dollar_squote) {
10897 c = decode_dollar_squote();
10899 USTPUTC('\\', out);
10900 c = (unsigned char)c;
10906 case CBACK: /* backslash */
10907 c = pgetc_without_PEOA();
10909 USTPUTC(CTLESC, out);
10910 USTPUTC('\\', out);
10912 } else if (c == '\n') {
10916 #if ENABLE_ASH_EXPAND_PRMT
10917 if (c == '$' && pssyntax) {
10918 USTPUTC(CTLESC, out);
10919 USTPUTC('\\', out);
10922 if (dblquote && c != '\\'
10923 && c != '`' && c != '$'
10924 && (c != '"' || eofmark != NULL)
10926 USTPUTC(CTLESC, out);
10927 USTPUTC('\\', out);
10929 if (SIT(c, SQSYNTAX) == CCTL)
10930 USTPUTC(CTLESC, out);
10938 if (eofmark == NULL) {
10939 USTPUTC(CTLQUOTEMARK, out);
10947 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
10948 if (eofmark != NULL && arinest == 0
10953 if (dqvarnest == 0) {
10954 syntax = BASESYNTAX;
10961 case CVAR: /* '$' */
10962 PARSESUB(); /* parse substitution */
10964 case CENDVAR: /* '}' */
10967 if (dqvarnest > 0) {
10970 USTPUTC(CTLENDVAR, out);
10975 #if ENABLE_SH_MATH_SUPPORT
10976 case CLP: /* '(' in arithmetic */
10980 case CRP: /* ')' in arithmetic */
10981 if (parenlevel > 0) {
10985 if (pgetc() == ')') {
10986 if (--arinest == 0) {
10987 USTPUTC(CTLENDARI, out);
10988 syntax = prevsyntax;
10989 dblquote = (syntax == DQSYNTAX);
10994 * unbalanced parens
10995 * (don't 2nd guess - no error)
11003 case CBQUOTE: /* '`' */
11007 goto endword; /* exit outer loop */
11011 if (varnest == 0) {
11012 #if ENABLE_ASH_BASH_COMPAT
11014 if (pgetc() == '>')
11015 c = 0x100 + '>'; /* flag &> */
11019 goto endword; /* exit outer loop */
11021 IF_ASH_ALIAS(if (c != PEOA))
11029 #if ENABLE_SH_MATH_SUPPORT
11030 if (syntax == ARISYNTAX)
11031 raise_error_syntax("missing '))'");
11033 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11034 raise_error_syntax("unterminated quoted string");
11035 if (varnest != 0) {
11036 startlinno = g_parsefile->linno;
11038 raise_error_syntax("missing '}'");
11040 USTPUTC('\0', out);
11041 len = out - (char *)stackblock();
11042 out = stackblock();
11043 if (eofmark == NULL) {
11044 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11047 if (isdigit_str9(out)) {
11048 PARSEREDIR(); /* passed as params: out, c */
11049 lasttoken = TREDIR;
11052 /* else: non-number X seen, interpret it
11053 * as "NNNX>file" = "NNNX >file" */
11057 quoteflag = quotef;
11058 backquotelist = bqlist;
11059 grabstackblock(len);
11063 /* end of readtoken routine */
11066 * Check to see whether we are at the end of the here document. When this
11067 * is called, c is set to the first character of the next input line. If
11068 * we are at the end of the here document, this routine sets the c to PEOF.
11072 #if ENABLE_ASH_ALIAS
11074 c = pgetc_without_PEOA();
11077 while (c == '\t') {
11078 c = pgetc_without_PEOA();
11081 if (c == *eofmark) {
11082 if (pfgets(line, sizeof(line)) != NULL) {
11086 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11088 if (*p == '\n' && *q == '\0') {
11090 g_parsefile->linno++;
11091 needprompt = doprompt;
11093 pushstring(line, NULL);
11098 goto checkend_return;
11102 * Parse a redirection operator. The variable "out" points to a string
11103 * specifying the fd to be redirected. The variable "c" contains the
11104 * first character of the redirection operator.
11107 /* out is already checked to be a valid number or "" */
11108 int fd = (*out == '\0' ? -1 : atoi(out));
11111 np = stzalloc(sizeof(struct nfile));
11116 np->type = NAPPEND;
11118 np->type = NCLOBBER;
11121 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11127 #if ENABLE_ASH_BASH_COMPAT
11128 else if (c == 0x100 + '>') { /* this flags &> redirection */
11130 pgetc(); /* this is '>', no need to check */
11134 else { /* c == '<' */
11135 /*np->nfile.fd = 0; - stzalloc did it */
11139 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11140 np = stzalloc(sizeof(struct nhere));
11141 /*np->nfile.fd = 0; - stzalloc did it */
11144 heredoc = stzalloc(sizeof(struct heredoc));
11145 heredoc->here = np;
11148 heredoc->striptabs = 1;
11150 /*heredoc->striptabs = 0; - stzalloc did it */
11156 np->type = NFROMFD;
11160 np->type = NFROMTO;
11172 goto parseredir_return;
11176 * Parse a substitution. At this point, we have read the dollar sign
11177 * and nothing else.
11180 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11181 * (assuming ascii char codes, as the original implementation did) */
11182 #define is_special(c) \
11183 (((unsigned)(c) - 33 < 32) \
11184 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11186 unsigned char subtype;
11190 static const char types[] ALIGN1 = "}-+?=";
11193 if (c > 255 /* PEOA or PEOF */
11194 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11196 #if ENABLE_ASH_BASH_COMPAT
11198 bash_dollar_squote = 1;
11203 } else if (c == '(') { /* $(command) or $((arith)) */
11204 if (pgetc() == '(') {
11205 #if ENABLE_SH_MATH_SUPPORT
11208 raise_error_syntax("you disabled math support for $((arith)) syntax");
11215 USTPUTC(CTLVAR, out);
11216 typeloc = out - (char *)stackblock();
11217 USTPUTC(VSNORMAL, out);
11218 subtype = VSNORMAL;
11226 subtype = VSLENGTH;
11230 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11234 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11235 } else if (isdigit(c)) {
11239 } while (isdigit(c));
11240 } else if (is_special(c)) {
11245 raise_error_syntax("bad substitution");
11247 if (c != '}' && subtype == VSLENGTH)
11252 if (subtype == 0) {
11256 #if ENABLE_ASH_BASH_COMPAT
11257 if (c == ':' || c == '$' || isdigit(c)) {
11259 subtype = VSSUBSTR;
11266 p = strchr(types, c);
11269 subtype = p - types + VSNORMAL;
11274 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11282 #if ENABLE_ASH_BASH_COMPAT
11284 subtype = VSREPLACE;
11287 subtype++; /* VSREPLACEALL */
11296 if (dblquote || arinest)
11298 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11299 if (subtype != VSNORMAL) {
11301 if (dblquote || arinest) {
11306 goto parsesub_return;
11310 * Called to parse command substitutions. Newstyle is set if the command
11311 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11312 * list of commands (passed by reference), and savelen is the number of
11313 * characters on the top of the stack which must be preserved.
11316 struct nodelist **nlpp;
11319 char *volatile str;
11320 struct jmploc jmploc;
11321 struct jmploc *volatile savehandler;
11323 smallint saveprompt = 0;
11326 (void) &saveprompt;
11328 savepbq = parsebackquote;
11329 if (setjmp(jmploc.loc)) {
11331 parsebackquote = 0;
11332 exception_handler = savehandler;
11333 longjmp(exception_handler->loc, 1);
11337 savelen = out - (char *)stackblock();
11339 str = ckmalloc(savelen);
11340 memcpy(str, stackblock(), savelen);
11342 savehandler = exception_handler;
11343 exception_handler = &jmploc;
11346 /* We must read until the closing backquote, giving special
11347 treatment to some slashes, and then push the string and
11348 reread it as input, interpreting it normally. */
11355 STARTSTACKSTR(pout);
11368 g_parsefile->linno++;
11372 * If eating a newline, avoid putting
11373 * the newline into the new character
11374 * stream (via the STPUTC after the
11379 if (pc != '\\' && pc != '`' && pc != '$'
11380 && (!dblquote || pc != '"')
11382 STPUTC('\\', pout);
11384 if (pc <= 255 /* not PEOA or PEOF */) {
11390 IF_ASH_ALIAS(case PEOA:)
11391 startlinno = g_parsefile->linno;
11392 raise_error_syntax("EOF in backquote substitution");
11395 g_parsefile->linno++;
11396 needprompt = doprompt;
11405 STPUTC('\0', pout);
11406 psavelen = pout - (char *)stackblock();
11407 if (psavelen > 0) {
11408 pstr = grabstackstr(pout);
11409 setinputstring(pstr);
11414 nlpp = &(*nlpp)->next;
11415 *nlpp = stzalloc(sizeof(**nlpp));
11416 /* (*nlpp)->next = NULL; - stzalloc did it */
11417 parsebackquote = oldstyle;
11420 saveprompt = doprompt;
11427 doprompt = saveprompt;
11428 else if (readtoken() != TRP)
11429 raise_error_unexpected_syntax(TRP);
11434 * Start reading from old file again, ignoring any pushed back
11435 * tokens left from the backquote parsing
11440 while (stackblocksize() <= savelen)
11442 STARTSTACKSTR(out);
11444 memcpy(out, str, savelen);
11445 STADJUST(savelen, out);
11451 parsebackquote = savepbq;
11452 exception_handler = savehandler;
11453 if (arinest || dblquote)
11454 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11456 USTPUTC(CTLBACKQ, out);
11458 goto parsebackq_oldreturn;
11459 goto parsebackq_newreturn;
11462 #if ENABLE_SH_MATH_SUPPORT
11464 * Parse an arithmetic expansion (indicate start of one and set state)
11467 if (++arinest == 1) {
11468 prevsyntax = syntax;
11469 syntax = ARISYNTAX;
11470 USTPUTC(CTLARI, out);
11477 * we collapse embedded arithmetic expansion to
11478 * parenthesis, which should be equivalent
11482 goto parsearith_return;
11486 } /* end of readtoken */
11489 * Read the next input token.
11490 * If the token is a word, we set backquotelist to the list of cmds in
11491 * backquotes. We set quoteflag to true if any part of the word was
11493 * If the token is TREDIR, then we set redirnode to a structure containing
11495 * In all cases, the variable startlinno is set to the number of the line
11496 * on which the token starts.
11498 * [Change comment: here documents and internal procedures]
11499 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11500 * word parsing code into a separate routine. In this case, readtoken
11501 * doesn't need to have any internal procedures, but parseword does.
11502 * We could also make parseoperator in essence the main routine, and
11503 * have parseword (readtoken1?) handle both words and redirection.]
11505 #define NEW_xxreadtoken
11506 #ifdef NEW_xxreadtoken
11507 /* singles must be first! */
11508 static const char xxreadtoken_chars[7] ALIGN1 = {
11509 '\n', '(', ')', /* singles */
11510 '&', '|', ';', /* doubles */
11514 #define xxreadtoken_singles 3
11515 #define xxreadtoken_doubles 3
11517 static const char xxreadtoken_tokens[] ALIGN1 = {
11518 TNL, TLP, TRP, /* only single occurrence allowed */
11519 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11520 TEOF, /* corresponds to trailing nul */
11521 TAND, TOR, TENDCASE /* if double occurrence */
11536 startlinno = g_parsefile->linno;
11537 for (;;) { /* until token or start of word found */
11539 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11543 while ((c = pgetc()) != '\n' && c != PEOF)
11546 } else if (c == '\\') {
11547 if (pgetc() != '\n') {
11549 break; /* return readtoken1(...) */
11551 startlinno = ++g_parsefile->linno;
11557 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11560 g_parsefile->linno++;
11561 needprompt = doprompt;
11564 p = strchr(xxreadtoken_chars, c);
11566 break; /* return readtoken1(...) */
11568 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11570 if (cc == c) { /* double occurrence? */
11571 p += xxreadtoken_doubles + 1;
11574 #if ENABLE_ASH_BASH_COMPAT
11575 if (c == '&' && cc == '>') /* &> */
11576 break; /* return readtoken1(...) */
11581 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11586 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11588 #else /* old xxreadtoken */
11589 #define RETURN(token) return lasttoken = token
11602 startlinno = g_parsefile->linno;
11603 for (;;) { /* until token or start of word found */
11606 case ' ': case '\t':
11607 IF_ASH_ALIAS(case PEOA:)
11610 while ((c = pgetc()) != '\n' && c != PEOF)
11615 if (pgetc() == '\n') {
11616 startlinno = ++g_parsefile->linno;
11624 g_parsefile->linno++;
11625 needprompt = doprompt;
11630 if (pgetc() == '&')
11635 if (pgetc() == '|')
11640 if (pgetc() == ';')
11653 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11656 #endif /* old xxreadtoken */
11663 smallint alreadyseen = tokpushback;
11666 #if ENABLE_ASH_ALIAS
11675 if (checkkwd & CHKNL) {
11682 if (t != TWORD || quoteflag) {
11687 * check for keywords
11689 if (checkkwd & CHKKWD) {
11690 const char *const *pp;
11692 pp = findkwd(wordtext);
11694 lasttoken = t = pp - tokname_array;
11695 TRACE(("keyword %s recognized\n", tokname(t)));
11700 if (checkkwd & CHKALIAS) {
11701 #if ENABLE_ASH_ALIAS
11703 ap = lookupalias(wordtext, 1);
11706 pushstring(ap->val, ap);
11716 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11718 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11730 return tokname_array[t][0];
11734 * Read and parse a command. Returns NODE_EOF on end of file.
11735 * (NULL is a valid parse tree indicating a blank line.)
11737 static union node *
11738 parsecmd(int interact)
11743 doprompt = interact;
11745 setprompt(doprompt);
11757 * Input any here documents.
11762 struct heredoc *here;
11765 here = heredoclist;
11766 heredoclist = NULL;
11772 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11773 here->eofmark, here->striptabs);
11774 n = stzalloc(sizeof(struct narg));
11775 n->narg.type = NARG;
11776 /*n->narg.next = NULL; - stzalloc did it */
11777 n->narg.text = wordtext;
11778 n->narg.backquote = backquotelist;
11779 here->here->nhere.doc = n;
11786 * called by editline -- any expansions to the prompt should be added here.
11788 #if ENABLE_ASH_EXPAND_PRMT
11789 static const char *
11790 expandstr(const char *ps)
11794 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11795 * and token processing _can_ alter it (delete NULs etc). */
11796 setinputstring((char *)ps);
11797 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11800 n.narg.type = NARG;
11801 n.narg.next = NULL;
11802 n.narg.text = wordtext;
11803 n.narg.backquote = backquotelist;
11805 expandarg(&n, NULL, 0);
11806 return stackblock();
11811 * Execute a command or commands contained in a string.
11814 evalstring(char *s, int mask)
11817 struct stackmark smark;
11821 setstackmark(&smark);
11824 while ((n = parsecmd(0)) != NODE_EOF) {
11826 popstackmark(&smark);
11839 * The eval command.
11841 static int FAST_FUNC
11842 evalcmd(int argc UNUSED_PARAM, char **argv)
11851 STARTSTACKSTR(concat);
11853 concat = stack_putstr(p, concat);
11857 STPUTC(' ', concat);
11859 STPUTC('\0', concat);
11860 p = grabstackstr(concat);
11862 evalstring(p, ~SKIPEVAL);
11869 * Read and execute commands.
11870 * "Top" is nonzero for the top level command loop;
11871 * it turns on prompting if the shell is interactive.
11877 struct stackmark smark;
11881 TRACE(("cmdloop(%d) called\n", top));
11885 setstackmark(&smark);
11888 showjobs(stderr, SHOW_CHANGED);
11891 if (iflag && top) {
11893 #if ENABLE_ASH_MAIL
11897 n = parsecmd(inter);
11899 if (DEBUG > 2 && debug && (n != NODE_EOF))
11902 if (n == NODE_EOF) {
11903 if (!top || numeof >= 50)
11905 if (!stoppedjobs()) {
11908 out2str("\nUse \"exit\" to leave shell.\n");
11911 } else if (nflag == 0) {
11912 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11917 popstackmark(&smark);
11922 return skip & SKIPEVAL;
11929 * Take commands from a file. To be compatible we should do a path
11930 * search for the file, which is necessary to find sub-commands.
11933 find_dot_file(char *name)
11936 const char *path = pathval();
11939 /* don't try this for absolute or relative paths */
11940 if (strchr(name, '/'))
11943 /* IIRC standards do not say whether . is to be searched.
11944 * And it is even smaller this way, making it unconditional for now:
11946 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11951 while ((fullname = path_advance(&path, name)) != NULL) {
11953 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11955 * Don't bother freeing here, since it will
11956 * be freed by the caller.
11960 if (fullname != name)
11961 stunalloc(fullname);
11964 /* not found in the PATH */
11965 ash_msg_and_raise_error("%s: not found", name);
11969 static int FAST_FUNC
11970 dotcmd(int argc, char **argv)
11972 struct strlist *sp;
11973 volatile struct shparam saveparam;
11976 for (sp = cmdenviron; sp; sp = sp->next)
11977 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
11979 if (argv[1]) { /* That's what SVR2 does */
11980 char *fullname = find_dot_file(argv[1]);
11983 if (argc) { /* argc > 0, argv[0] != NULL */
11984 saveparam = shellparam;
11985 shellparam.malloced = 0;
11986 shellparam.nparam = argc;
11987 shellparam.p = argv;
11990 setinputfile(fullname, INPUT_PUSH_FILE);
11991 commandname = fullname;
11996 freeparam(&shellparam);
11997 shellparam = saveparam;
11999 status = exitstatus;
12004 static int FAST_FUNC
12005 exitcmd(int argc UNUSED_PARAM, char **argv)
12010 exitstatus = number(argv[1]);
12011 raise_exception(EXEXIT);
12016 * Read a file containing shell functions.
12019 readcmdfile(char *name)
12021 setinputfile(name, INPUT_PUSH_FILE);
12027 /* ============ find_command inplementation */
12030 * Resolve a command name. If you change this routine, you may have to
12031 * change the shellexec routine as well.
12034 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12036 struct tblentry *cmdp;
12043 struct builtincmd *bcmd;
12045 /* If name contains a slash, don't use PATH or hash table */
12046 if (strchr(name, '/') != NULL) {
12047 entry->u.index = -1;
12048 if (act & DO_ABS) {
12049 while (stat(name, &statb) < 0) {
12051 if (errno == EINTR)
12054 entry->cmdtype = CMDUNKNOWN;
12058 entry->cmdtype = CMDNORMAL;
12062 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12064 updatetbl = (path == pathval());
12067 if (strstr(path, "%builtin") != NULL)
12068 act |= DO_ALTBLTIN;
12071 /* If name is in the table, check answer will be ok */
12072 cmdp = cmdlookup(name, 0);
12073 if (cmdp != NULL) {
12076 switch (cmdp->cmdtype) {
12094 } else if (cmdp->rehash == 0)
12095 /* if not invalidated by cd, we're done */
12099 /* If %builtin not in path, check for builtin next */
12100 bcmd = find_builtin(name);
12102 if (IS_BUILTIN_REGULAR(bcmd))
12103 goto builtin_success;
12104 if (act & DO_ALTPATH) {
12105 if (!(act & DO_ALTBLTIN))
12106 goto builtin_success;
12107 } else if (builtinloc <= 0) {
12108 goto builtin_success;
12112 #if ENABLE_FEATURE_SH_STANDALONE
12114 int applet_no = find_applet_by_name(name);
12115 if (applet_no >= 0) {
12116 entry->cmdtype = CMDNORMAL;
12117 entry->u.index = -2 - applet_no;
12123 /* We have to search path. */
12124 prev = -1; /* where to start */
12125 if (cmdp && cmdp->rehash) { /* doing a rehash */
12126 if (cmdp->cmdtype == CMDBUILTIN)
12129 prev = cmdp->param.index;
12135 while ((fullname = path_advance(&path, name)) != NULL) {
12136 stunalloc(fullname);
12137 /* NB: code below will still use fullname
12138 * despite it being "unallocated" */
12141 if (prefix(pathopt, "builtin")) {
12143 goto builtin_success;
12146 if ((act & DO_NOFUNC)
12147 || !prefix(pathopt, "func")
12148 ) { /* ignore unimplemented options */
12152 /* if rehash, don't redo absolute path names */
12153 if (fullname[0] == '/' && idx <= prev) {
12156 TRACE(("searchexec \"%s\": no change\n", name));
12159 while (stat(fullname, &statb) < 0) {
12161 if (errno == EINTR)
12164 if (errno != ENOENT && errno != ENOTDIR)
12168 e = EACCES; /* if we fail, this will be the error */
12169 if (!S_ISREG(statb.st_mode))
12171 if (pathopt) { /* this is a %func directory */
12172 stalloc(strlen(fullname) + 1);
12173 /* NB: stalloc will return space pointed by fullname
12174 * (because we don't have any intervening allocations
12175 * between stunalloc above and this stalloc) */
12176 readcmdfile(fullname);
12177 cmdp = cmdlookup(name, 0);
12178 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12179 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12180 stunalloc(fullname);
12183 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12185 entry->cmdtype = CMDNORMAL;
12186 entry->u.index = idx;
12190 cmdp = cmdlookup(name, 1);
12191 cmdp->cmdtype = CMDNORMAL;
12192 cmdp->param.index = idx;
12197 /* We failed. If there was an entry for this command, delete it */
12198 if (cmdp && updatetbl)
12199 delete_cmd_entry();
12201 ash_msg("%s: %s", name, errmsg(e, "not found"));
12202 entry->cmdtype = CMDUNKNOWN;
12207 entry->cmdtype = CMDBUILTIN;
12208 entry->u.cmd = bcmd;
12212 cmdp = cmdlookup(name, 1);
12213 cmdp->cmdtype = CMDBUILTIN;
12214 cmdp->param.cmd = bcmd;
12218 entry->cmdtype = cmdp->cmdtype;
12219 entry->u = cmdp->param;
12223 /* ============ trap.c */
12226 * The trap builtin.
12228 static int FAST_FUNC
12229 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12238 for (signo = 0; signo < NSIG; signo++) {
12239 char *tr = trap_ptr[signo];
12241 /* note: bash adds "SIG", but only if invoked
12242 * as "bash". If called as "sh", or if set -o posix,
12243 * then it prints short signal names.
12244 * We are printing short names: */
12245 out1fmt("trap -- %s %s\n",
12247 get_signame(signo));
12248 /* trap_ptr != trap only if we are in special-cased `trap` code.
12249 * In this case, we will exit very soon, no need to free(). */
12250 /* if (trap_ptr != trap && tp[0]) */
12255 if (trap_ptr != trap) {
12267 signo = get_signum(*ap);
12269 ash_msg_and_raise_error("%s: bad trap", *ap);
12272 if (LONE_DASH(action))
12275 action = ckstrdup(action);
12278 trap[signo] = action;
12288 /* ============ Builtins */
12290 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12292 * Lists available builtins
12294 static int FAST_FUNC
12295 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12301 "Built-in commands:\n"
12302 "------------------\n");
12303 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12304 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12305 builtintab[i].name + 1);
12311 #if ENABLE_FEATURE_SH_STANDALONE
12313 const char *a = applet_names;
12315 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12320 a += strlen(a) + 1;
12325 return EXIT_SUCCESS;
12327 #endif /* FEATURE_SH_EXTRA_QUIET */
12330 * The export and readonly commands.
12332 static int FAST_FUNC
12333 exportcmd(int argc UNUSED_PARAM, char **argv)
12339 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12341 if (nextopt("p") != 'p') {
12346 p = strchr(name, '=');
12350 vp = *findvar(hashvar(name), name);
12356 setvar(name, p, flag);
12357 } while ((name = *++aptr) != NULL);
12361 showvars(argv[0], flag, 0);
12366 * Delete a function if it exists.
12369 unsetfunc(const char *name)
12371 struct tblentry *cmdp;
12373 cmdp = cmdlookup(name, 0);
12374 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12375 delete_cmd_entry();
12379 * The unset builtin command. We unset the function before we unset the
12380 * variable to allow a function to be unset when there is a readonly variable
12381 * with the same name.
12383 static int FAST_FUNC
12384 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12391 while ((i = nextopt("vf")) != '\0') {
12395 for (ap = argptr; *ap; ap++) {
12411 #include <sys/times.h>
12413 static const unsigned char timescmd_str[] ALIGN1 = {
12414 ' ', offsetof(struct tms, tms_utime),
12415 '\n', offsetof(struct tms, tms_stime),
12416 ' ', offsetof(struct tms, tms_cutime),
12417 '\n', offsetof(struct tms, tms_cstime),
12421 static int FAST_FUNC
12422 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12424 long clk_tck, s, t;
12425 const unsigned char *p;
12428 clk_tck = sysconf(_SC_CLK_TCK);
12433 t = *(clock_t *)(((char *) &buf) + p[1]);
12435 out1fmt("%ldm%ld.%.3lds%c",
12437 ((t - s * clk_tck) * 1000) / clk_tck,
12439 } while (*(p += 2));
12444 #if ENABLE_SH_MATH_SUPPORT
12446 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12447 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12449 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12451 static int FAST_FUNC
12452 letcmd(int argc UNUSED_PARAM, char **argv)
12458 ash_msg_and_raise_error("expression expected");
12460 i = ash_arith(*argv);
12465 #endif /* SH_MATH_SUPPORT */
12468 /* ============ miscbltin.c
12470 * Miscellaneous builtins.
12475 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
12476 typedef enum __rlimit_resource rlim_t;
12480 * The read builtin. Options:
12481 * -r Do not interpret '\' specially
12482 * -s Turn off echo (tty only)
12483 * -n NCHARS Read NCHARS max
12484 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12485 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12486 * -u FD Read from given FD instead of fd 0
12487 * This uses unbuffered input, which may be avoidable in some cases.
12488 * TODO: bash also has:
12489 * -a ARRAY Read into array[0],[1],etc
12490 * -d DELIM End on DELIM char, not newline
12491 * -e Use line editing (tty only)
12493 static int FAST_FUNC
12494 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12496 char *opt_n = NULL;
12497 char *opt_p = NULL;
12498 char *opt_t = NULL;
12499 char *opt_u = NULL;
12500 int read_flags = 0;
12504 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12513 read_flags |= BUILTIN_READ_SILENT;
12519 read_flags |= BUILTIN_READ_RAW;
12529 r = builtin_read(setvar,
12531 bltinlookup("IFS"), /* can be NULL */
12539 if ((uintptr_t)r > 1)
12540 ash_msg_and_raise_error(r);
12542 return (uintptr_t)r;
12545 static int FAST_FUNC
12546 umaskcmd(int argc UNUSED_PARAM, char **argv)
12548 static const char permuser[3] ALIGN1 = "ugo";
12549 static const char permmode[3] ALIGN1 = "rwx";
12550 static const short permmask[] ALIGN2 = {
12551 S_IRUSR, S_IWUSR, S_IXUSR,
12552 S_IRGRP, S_IWGRP, S_IXGRP,
12553 S_IROTH, S_IWOTH, S_IXOTH
12556 /* TODO: use bb_parse_mode() instead */
12561 int symbolic_mode = 0;
12563 while (nextopt("S") != '\0') {
12574 if (symbolic_mode) {
12578 for (i = 0; i < 3; i++) {
12581 *p++ = permuser[i];
12583 for (j = 0; j < 3; j++) {
12584 if ((mask & permmask[3 * i + j]) == 0) {
12585 *p++ = permmode[j];
12593 out1fmt("%.4o\n", mask);
12596 if (isdigit((unsigned char) *ap)) {
12599 if (*ap >= '8' || *ap < '0')
12600 ash_msg_and_raise_error(msg_illnum, argv[1]);
12601 mask = (mask << 3) + (*ap - '0');
12602 } while (*++ap != '\0');
12605 mask = ~mask & 0777;
12606 if (!bb_parse_mode(ap, &mask)) {
12607 ash_msg_and_raise_error("illegal mode: %s", ap);
12609 umask(~mask & 0777);
12618 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12619 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12620 * ash by J.T. Conklin.
12625 uint8_t cmd; /* RLIMIT_xxx fit into it */
12626 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
12630 static const struct limits limits_tbl[] = {
12632 { RLIMIT_CPU, 0, 't' },
12634 #ifdef RLIMIT_FSIZE
12635 { RLIMIT_FSIZE, 9, 'f' },
12638 { RLIMIT_DATA, 10, 'd' },
12640 #ifdef RLIMIT_STACK
12641 { RLIMIT_STACK, 10, 's' },
12644 { RLIMIT_CORE, 9, 'c' },
12647 { RLIMIT_RSS, 10, 'm' },
12649 #ifdef RLIMIT_MEMLOCK
12650 { RLIMIT_MEMLOCK, 10, 'l' },
12652 #ifdef RLIMIT_NPROC
12653 { RLIMIT_NPROC, 0, 'p' },
12655 #ifdef RLIMIT_NOFILE
12656 { RLIMIT_NOFILE, 0, 'n' },
12659 { RLIMIT_AS, 10, 'v' },
12661 #ifdef RLIMIT_LOCKS
12662 { RLIMIT_LOCKS, 0, 'w' },
12665 static const char limits_name[] =
12667 "time(seconds)" "\0"
12669 #ifdef RLIMIT_FSIZE
12670 "file(blocks)" "\0"
12675 #ifdef RLIMIT_STACK
12679 "coredump(blocks)" "\0"
12684 #ifdef RLIMIT_MEMLOCK
12685 "locked memory(kb)" "\0"
12687 #ifdef RLIMIT_NPROC
12690 #ifdef RLIMIT_NOFILE
12696 #ifdef RLIMIT_LOCKS
12701 enum limtype { SOFT = 0x1, HARD = 0x2 };
12704 printlim(enum limtype how, const struct rlimit *limit,
12705 const struct limits *l)
12709 val = limit->rlim_max;
12711 val = limit->rlim_cur;
12713 if (val == RLIM_INFINITY)
12714 out1fmt("unlimited\n");
12716 val >>= l->factor_shift;
12717 out1fmt("%lld\n", (long long) val);
12721 static int FAST_FUNC
12722 ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12725 enum limtype how = SOFT | HARD;
12726 const struct limits *l;
12729 struct rlimit limit;
12732 while ((optc = nextopt("HSa"
12736 #ifdef RLIMIT_FSIZE
12742 #ifdef RLIMIT_STACK
12751 #ifdef RLIMIT_MEMLOCK
12754 #ifdef RLIMIT_NPROC
12757 #ifdef RLIMIT_NOFILE
12763 #ifdef RLIMIT_LOCKS
12781 for (l = limits_tbl; l->option != what; l++)
12784 set = *argptr ? 1 : 0;
12789 if (all || argptr[1])
12790 ash_msg_and_raise_error("too many arguments");
12791 if (strncmp(p, "unlimited\n", 9) == 0)
12792 val = RLIM_INFINITY;
12794 if (sizeof(val) == sizeof(int))
12795 val = bb_strtou(p, NULL, 10);
12796 else if (sizeof(val) == sizeof(long))
12797 val = bb_strtoul(p, NULL, 10);
12799 val = bb_strtoull(p, NULL, 10);
12801 ash_msg_and_raise_error("bad number");
12802 val <<= l->factor_shift;
12806 const char *lname = limits_name;
12807 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
12808 getrlimit(l->cmd, &limit);
12809 out1fmt("%-20s ", lname);
12810 lname += strlen(lname) + 1;
12811 printlim(how, &limit, l);
12816 getrlimit(l->cmd, &limit);
12819 limit.rlim_max = val;
12821 limit.rlim_cur = val;
12822 if (setrlimit(l->cmd, &limit) < 0)
12823 ash_msg_and_raise_error("error setting limit (%m)");
12825 printlim(how, &limit, l);
12830 /* ============ main() and helpers */
12833 * Called to exit the shell.
12835 static void exitshell(void) NORETURN;
12843 status = exitstatus;
12844 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12845 if (setjmp(loc.loc)) {
12846 if (exception_type == EXEXIT)
12847 /* dash bug: it just does _exit(exitstatus) here
12848 * but we have to do setjobctl(0) first!
12849 * (bug is still not fixed in dash-0.5.3 - if you run dash
12850 * under Midnight Commander, on exit from dash MC is backgrounded) */
12851 status = exitstatus;
12854 exception_handler = &loc;
12861 flush_stdout_stderr();
12871 /* from input.c: */
12872 basepf.next_to_pgetc = basepf.buf = basebuf;
12875 signal(SIGCHLD, SIG_DFL);
12876 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12877 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12879 signal(SIGHUP, SIG_DFL);
12885 struct stat st1, st2;
12888 for (envp = environ; envp && *envp; envp++) {
12889 if (strchr(*envp, '=')) {
12890 setvareq(*envp, VEXPORT|VTEXTFIXED);
12894 setvar("PPID", utoa(getppid()), 0);
12896 p = lookupvar("PWD");
12898 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12899 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12906 * Process the shell command line arguments.
12909 procargs(char **argv)
12912 const char *xminusc;
12917 /* if (xargv[0]) - mmm, this is always true! */
12919 for (i = 0; i < NOPTS; i++)
12923 /* it already printed err message */
12924 raise_exception(EXERROR);
12928 if (*xargv == NULL) {
12930 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12933 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12937 for (i = 0; i < NOPTS; i++)
12938 if (optlist[i] == 2)
12943 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12948 } else if (!sflag) {
12949 setinputfile(*xargv, 0);
12952 commandname = arg0;
12955 shellparam.p = xargv;
12956 #if ENABLE_ASH_GETOPTS
12957 shellparam.optind = 1;
12958 shellparam.optoff = -1;
12960 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
12962 shellparam.nparam++;
12969 * Read /etc/profile or .profile.
12972 read_profile(const char *name)
12976 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12985 * This routine is called when an error or an interrupt occurs in an
12986 * interactive shell and control is returned to the main command loop.
12994 /* from input.c: */
12995 g_parsefile->left_in_buffer = 0;
12996 g_parsefile->left_in_line = 0; /* clear input buffer */
12998 /* from parser.c: */
13001 /* from redir.c: */
13002 clearredir(/*drop:*/ 0);
13006 static short profile_buf[16384];
13007 extern int etext();
13011 * Main routine. We initialize things, parse the arguments, execute
13012 * profiles if we're a login shell, and then call cmdloop to execute
13013 * commands. The setjmp call sets up the location to jump to when an
13014 * exception occurs. When an exception occurs the variable "state"
13015 * is used to figure out how far we had gotten.
13017 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13018 int ash_main(int argc UNUSED_PARAM, char **argv)
13020 const char *shinit;
13021 volatile smallint state;
13022 struct jmploc jmploc;
13023 struct stackmark smark;
13025 /* Initialize global data */
13029 #if ENABLE_ASH_ALIAS
13035 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13038 #if ENABLE_FEATURE_EDITING
13039 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13042 if (setjmp(jmploc.loc)) {
13048 e = exception_type;
13052 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13055 outcslow('\n', stderr);
13057 popstackmark(&smark);
13058 FORCE_INT_ON; /* enable interrupts */
13067 exception_handler = &jmploc;
13070 TRACE(("Shell args: "));
13071 trace_puts_args(argv);
13073 rootpid = getpid();
13076 setstackmark(&smark);
13079 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13081 const char *hp = lookupvar("HISTFILE");
13084 hp = lookupvar("HOME");
13086 char *defhp = concat_path_file(hp, ".ash_history");
13087 setvar("HISTFILE", defhp, 0);
13093 if (/* argv[0] && */ argv[0][0] == '-')
13097 read_profile("/etc/profile");
13100 read_profile(".profile");
13106 getuid() == geteuid() && getgid() == getegid() &&
13110 shinit = lookupvar("ENV");
13111 if (shinit != NULL && *shinit != '\0') {
13112 read_profile(shinit);
13118 /* evalstring pushes parsefile stack.
13119 * Ensure we don't falsely claim that 0 (stdin)
13120 * is one of stacked source fds.
13121 * Testcase: ash -c 'exec 1>&0' must not complain. */
13123 g_parsefile->fd = -1;
13124 evalstring(minusc, 0);
13127 if (sflag || minusc == NULL) {
13128 #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13130 const char *hp = lookupvar("HISTFILE");
13132 line_input_state->hist_file = hp;
13135 state4: /* XXX ??? - why isn't this before the "if" statement */
13143 extern void _mcleanup(void);
13153 * Copyright (c) 1989, 1991, 1993, 1994
13154 * The Regents of the University of California. All rights reserved.
13156 * This code is derived from software contributed to Berkeley by
13157 * Kenneth Almquist.
13159 * Redistribution and use in source and binary forms, with or without
13160 * modification, are permitted provided that the following conditions
13162 * 1. Redistributions of source code must retain the above copyright
13163 * notice, this list of conditions and the following disclaimer.
13164 * 2. Redistributions in binary form must reproduce the above copyright
13165 * notice, this list of conditions and the following disclaimer in the
13166 * documentation and/or other materials provided with the distribution.
13167 * 3. Neither the name of the University nor the names of its contributors
13168 * may be used to endorse or promote products derived from this software
13169 * without specific prior written permission.
13171 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13172 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13173 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13174 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13175 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13176 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13177 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13178 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13179 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13180 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF