1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * Copyright (c) 1989, 1991, 1993, 1994
6 * The Regents of the University of California. All rights reserved.
8 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
9 * was re-ported from NetBSD and debianized.
11 * This code is derived from software contributed to Berkeley by
14 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
16 * Original BSD copyright notice is retained at the end of this file.
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 */
39 #define JOBS ENABLE_ASH_JOB_CONTROL
47 #include "busybox.h" /* for applet_names */
48 //TODO: pull in some .h and find out do we have SINGLE_APPLET_MAIN?
49 //#include "applet_tables.h" doesn't work
54 #if ENABLE_ASH_RANDOM_SUPPORT
57 # define CLEAR_RANDOM_T(rnd) ((void)0)
60 #if defined SINGLE_APPLET_MAIN
61 /* STANDALONE does not make sense, and won't compile */
62 # undef CONFIG_FEATURE_SH_STANDALONE
63 # undef ENABLE_FEATURE_SH_STANDALONE
64 # undef IF_FEATURE_SH_STANDALONE
65 # undef IF_NOT_FEATURE_SH_STANDALONE(...)
66 # define ENABLE_FEATURE_SH_STANDALONE 0
67 # define IF_FEATURE_SH_STANDALONE(...)
68 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
72 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
75 #if defined(__uClinux__)
76 # error "Do not even bother, ash will not run on NOMMU machine"
80 /* ============ Hash table sizes. Configurable. */
84 #define CMDTABLESIZE 31 /* should be prime */
87 /* ============ Shell options */
89 static const char *const optletters_optnames[] = {
110 #define optletters(n) optletters_optnames[(n)][0]
111 #define optnames(n) (&optletters_optnames[(n)][1])
113 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
116 /* ============ Misc data */
118 static const char homestr[] ALIGN1 = "HOME";
119 static const char snlfmt[] ALIGN1 = "%s\n";
120 static const char msg_illnum[] ALIGN1 = "Illegal number: %s";
123 * We enclose jmp_buf in a structure so that we can declare pointers to
124 * jump locations. The global variable handler contains the location to
125 * jump to when an exception occurs, and the global variable exception_type
126 * contains a code identifying the exception. To implement nested
127 * exception handlers, the user should save the value of handler on entry
128 * to an inner scope, set handler to point to a jmploc structure for the
129 * inner scope, and restore handler on exit from the scope.
135 struct globals_misc {
136 /* pid of main shell */
138 /* shell level: 0 for the main shell, 1 for its children, and so on */
140 #define rootshell (!shlvl)
141 char *minusc; /* argument to -c option */
143 char *curdir; // = nullstr; /* current working directory */
144 char *physdir; // = nullstr; /* physical working directory */
146 char *arg0; /* value of $0 */
148 struct jmploc *exception_handler;
150 volatile int suppress_int; /* counter */
151 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
152 /* last pending signal */
153 volatile /*sig_atomic_t*/ smallint pending_sig;
154 smallint exception_type; /* kind of exception (0..5) */
156 #define EXINT 0 /* SIGINT received */
157 #define EXERROR 1 /* a generic error */
158 #define EXSHELLPROC 2 /* execute a shell procedure */
159 #define EXEXEC 3 /* command execution failed */
160 #define EXEXIT 4 /* exit the shell */
161 #define EXSIG 5 /* trapped signal in wait(1) */
164 char nullstr[1]; /* zero length string */
167 #define eflag optlist[0]
168 #define fflag optlist[1]
169 #define Iflag optlist[2]
170 #define iflag optlist[3]
171 #define mflag optlist[4]
172 #define nflag optlist[5]
173 #define sflag optlist[6]
174 #define xflag optlist[7]
175 #define vflag optlist[8]
176 #define Cflag optlist[9]
177 #define aflag optlist[10]
178 #define bflag optlist[11]
179 #define uflag optlist[12]
180 #define viflag optlist[13]
182 #define nolog optlist[14]
183 #define debug optlist[15]
186 /* trap handler commands */
188 * Sigmode records the current value of the signal handlers for the various
189 * modes. A value of zero means that the current handler is not known.
190 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
192 char sigmode[NSIG - 1];
193 #define S_DFL 1 /* default signal handling (SIG_DFL) */
194 #define S_CATCH 2 /* signal is caught */
195 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
196 #define S_HARD_IGN 4 /* signal is ignored permenantly */
198 /* indicates specified signal received */
199 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
201 char **trap_ptr; /* used only by "trap hack" */
203 /* Rarely referenced stuff */
204 #if ENABLE_ASH_RANDOM_SUPPORT
207 pid_t backgndpid; /* pid of last background process */
208 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
210 extern struct globals_misc *const ash_ptr_to_globals_misc;
211 #define G_misc (*ash_ptr_to_globals_misc)
212 #define rootpid (G_misc.rootpid )
213 #define shlvl (G_misc.shlvl )
214 #define minusc (G_misc.minusc )
215 #define curdir (G_misc.curdir )
216 #define physdir (G_misc.physdir )
217 #define arg0 (G_misc.arg0 )
218 #define exception_handler (G_misc.exception_handler)
219 #define exception_type (G_misc.exception_type )
220 #define suppress_int (G_misc.suppress_int )
221 #define pending_int (G_misc.pending_int )
222 #define pending_sig (G_misc.pending_sig )
223 #define isloginsh (G_misc.isloginsh )
224 #define nullstr (G_misc.nullstr )
225 #define optlist (G_misc.optlist )
226 #define sigmode (G_misc.sigmode )
227 #define gotsig (G_misc.gotsig )
228 #define trap (G_misc.trap )
229 #define trap_ptr (G_misc.trap_ptr )
230 #define random_gen (G_misc.random_gen )
231 #define backgndpid (G_misc.backgndpid )
232 #define job_warning (G_misc.job_warning)
233 #define INIT_G_misc() do { \
234 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
242 /* ============ DEBUG */
244 static void trace_printf(const char *fmt, ...);
245 static void trace_vprintf(const char *fmt, va_list va);
246 # define TRACE(param) trace_printf param
247 # define TRACEV(param) trace_vprintf param
248 # define close(fd) do { \
250 if (close(dfd) < 0) \
251 bb_error_msg("bug on %d: closing %d(0x%x)", \
252 __LINE__, dfd, dfd); \
255 # define TRACE(param)
256 # define TRACEV(param)
260 /* ============ Utility functions */
261 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
263 /* C99 says: "char" declaration may be signed or unsigned by default */
264 #define signed_char2int(sc) ((int)(signed char)(sc))
266 static int isdigit_str9(const char *str)
268 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
269 while (--maxlen && isdigit(*str))
271 return (*str == '\0');
275 /* ============ Interrupts / exceptions */
277 * These macros allow the user to suspend the handling of interrupt signals
278 * over a period of time. This is similar to SIGHOLD or to sigblock, but
279 * much more efficient and portable. (But hacking the kernel is so much
280 * more fun than worrying about efficiency and portability. :-))
282 #define INT_OFF do { \
288 * Called to raise an exception. Since C doesn't include exceptions, we
289 * just do a longjmp to the exception handler. The type of exception is
290 * stored in the global variable "exception_type".
292 static void raise_exception(int) NORETURN;
294 raise_exception(int e)
297 if (exception_handler == NULL)
302 longjmp(exception_handler->loc, 1);
305 #define raise_exception(e) do { \
306 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
307 raise_exception(e); \
312 * Called from trap.c when a SIGINT is received. (If the user specifies
313 * that SIGINT is to be trapped or ignored using the trap builtin, then
314 * this routine is not called.) Suppressint is nonzero when interrupts
315 * are held using the INT_OFF macro. (The test for iflag is just
316 * defensive programming.)
318 static void raise_interrupt(void) NORETURN;
320 raise_interrupt(void)
325 /* Signal is not automatically unmasked after it is raised,
326 * do it ourself - unmask all signals */
327 sigprocmask_allsigs(SIG_UNBLOCK);
328 /* pending_sig = 0; - now done in onsig() */
331 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
332 if (!(rootshell && iflag)) {
333 /* Kill ourself with SIGINT */
334 signal(SIGINT, SIG_DFL);
339 raise_exception(ex_type);
343 #define raise_interrupt() do { \
344 TRACE(("raising interrupt on line %d\n", __LINE__)); \
349 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
353 if (--suppress_int == 0 && pending_int) {
357 #define INT_ON int_on()
358 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
366 #define FORCE_INT_ON force_int_on()
368 #define SAVE_INT(v) ((v) = suppress_int)
370 #define RESTORE_INT(v) do { \
372 suppress_int = (v); \
373 if (suppress_int == 0 && pending_int) \
378 /* ============ Stdout/stderr output */
381 outstr(const char *p, FILE *file)
389 flush_stdout_stderr(void)
406 outcslow(int c, FILE *dest)
414 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
416 out1fmt(const char *fmt, ...)
423 r = vprintf(fmt, ap);
429 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
431 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
438 ret = vsnprintf(outbuf, length, fmt, ap);
445 out1str(const char *p)
451 out2str(const char *p)
458 /* ============ Parser structures */
460 /* control characters in argument strings */
461 #define CTLESC ((unsigned char)'\201') /* escape next character */
462 #define CTLVAR ((unsigned char)'\202') /* variable defn */
463 #define CTLENDVAR ((unsigned char)'\203')
464 #define CTLBACKQ ((unsigned char)'\204')
465 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
466 /* CTLBACKQ | CTLQUOTE == '\205' */
467 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
468 #define CTLENDARI ((unsigned char)'\207')
469 #define CTLQUOTEMARK ((unsigned char)'\210')
471 /* variable substitution byte (follows CTLVAR) */
472 #define VSTYPE 0x0f /* type of variable substitution */
473 #define VSNUL 0x10 /* colon--treat the empty string as unset */
474 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
476 /* values of VSTYPE field */
477 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
478 #define VSMINUS 0x2 /* ${var-text} */
479 #define VSPLUS 0x3 /* ${var+text} */
480 #define VSQUESTION 0x4 /* ${var?message} */
481 #define VSASSIGN 0x5 /* ${var=text} */
482 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
483 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
484 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
485 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
486 #define VSLENGTH 0xa /* ${#var} */
487 #if ENABLE_ASH_BASH_COMPAT
488 #define VSSUBSTR 0xc /* ${var:position:length} */
489 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
490 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
493 static const char dolatstr[] ALIGN1 = {
494 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
514 #if ENABLE_ASH_BASH_COMPAT
531 smallint type; /* Nxxxx */
534 union node *redirect;
539 smallint pipe_backgnd;
540 struct nodelist *cmdlist;
546 union node *redirect;
559 union node *elsepart;
586 struct nodelist *backquote;
589 /* nfile and ndup layout must match!
590 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
591 * that it is actually NTO2 (>&file), and change its type.
608 char *_unused_expfname;
627 struct nredir nredir;
628 struct nbinary nbinary;
632 struct nclist nclist;
641 * NODE_EOF is returned by parsecmd when it encounters an end of file.
642 * It must be distinct from NULL.
644 #define NODE_EOF ((union node *) -1L)
647 struct nodelist *next;
660 freefunc(struct funcnode *f)
662 if (f && --f->count < 0)
667 /* ============ Debugging output */
671 static FILE *tracefile;
674 trace_printf(const char *fmt, ...)
681 fprintf(tracefile, "%u ", (int) time(NULL));
683 fprintf(tracefile, "[%u] ", (int) getpid());
685 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
687 vfprintf(tracefile, fmt, va);
692 trace_vprintf(const char *fmt, va_list va)
697 fprintf(tracefile, "%u ", (int) time(NULL));
699 fprintf(tracefile, "[%u] ", (int) getpid());
701 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
702 vfprintf(tracefile, fmt, va);
706 trace_puts(const char *s)
714 trace_puts_quoted(char *s)
721 putc('"', tracefile);
722 for (p = s; *p; p++) {
724 case '\n': c = 'n'; goto backslash;
725 case '\t': c = 't'; goto backslash;
726 case '\r': c = 'r'; goto backslash;
727 case '"': c = '"'; goto backslash;
728 case '\\': c = '\\'; goto backslash;
729 case CTLESC: c = 'e'; goto backslash;
730 case CTLVAR: c = 'v'; goto backslash;
731 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
732 case CTLBACKQ: c = 'q'; goto backslash;
733 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
735 putc('\\', tracefile);
739 if (*p >= ' ' && *p <= '~')
742 putc('\\', tracefile);
743 putc(*p >> 6 & 03, tracefile);
744 putc(*p >> 3 & 07, tracefile);
745 putc(*p & 07, tracefile);
750 putc('"', tracefile);
754 trace_puts_args(char **ap)
761 trace_puts_quoted(*ap);
763 putc('\n', tracefile);
766 putc(' ', tracefile);
781 /* leave open because libedit might be using it */
784 strcpy(s, "./trace");
786 if (!freopen(s, "a", tracefile)) {
787 fprintf(stderr, "Can't re-open %s\n", s);
792 tracefile = fopen(s, "a");
793 if (tracefile == NULL) {
794 fprintf(stderr, "Can't open %s\n", s);
800 flags = fcntl(fileno(tracefile), F_GETFL);
802 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
804 setlinebuf(tracefile);
805 fputs("\nTracing started.\n", tracefile);
809 indent(int amount, char *pfx, FILE *fp)
813 for (i = 0; i < amount; i++) {
814 if (pfx && i == amount - 1)
820 /* little circular references here... */
821 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
824 sharg(union node *arg, FILE *fp)
827 struct nodelist *bqlist;
830 if (arg->type != NARG) {
831 out1fmt("<node type %d>\n", arg->type);
834 bqlist = arg->narg.backquote;
835 for (p = arg->narg.text; *p; p++) {
844 if (subtype == VSLENGTH)
853 switch (subtype & VSTYPE) {
886 out1fmt("<subtype %d>", subtype);
893 case CTLBACKQ|CTLQUOTE:
896 shtree(bqlist->n, -1, NULL, fp);
907 shcmd(union node *cmd, FILE *fp)
915 for (np = cmd->ncmd.args; np; np = np->narg.next) {
921 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
925 switch (np->nfile.type) {
926 case NTO: s = ">>"+1; dftfd = 1; break;
927 case NCLOBBER: s = ">|"; dftfd = 1; break;
928 case NAPPEND: s = ">>"; dftfd = 1; break;
929 #if ENABLE_ASH_BASH_COMPAT
932 case NTOFD: s = ">&"; dftfd = 1; break;
933 case NFROM: s = "<"; break;
934 case NFROMFD: s = "<&"; break;
935 case NFROMTO: s = "<>"; break;
936 default: s = "*error*"; break;
938 if (np->nfile.fd != dftfd)
939 fprintf(fp, "%d", np->nfile.fd);
941 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
942 fprintf(fp, "%d", np->ndup.dupfd);
944 sharg(np->nfile.fname, fp);
951 shtree(union node *n, int ind, char *pfx, FILE *fp)
959 indent(ind, pfx, fp);
976 shtree(n->nbinary.ch1, ind, NULL, fp);
979 shtree(n->nbinary.ch2, ind, NULL, fp);
987 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
988 shtree(lp->n, 0, NULL, fp);
992 if (n->npipe.pipe_backgnd)
998 fprintf(fp, "<node type %d>", n->type);
1006 showtree(union node *n)
1008 trace_puts("showtree called\n");
1009 shtree(n, 1, NULL, stderr);
1015 /* ============ Parser data */
1018 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1021 struct strlist *next;
1028 struct strpush *prev; /* preceding string on stack */
1030 int prev_left_in_line;
1031 #if ENABLE_ASH_ALIAS
1032 struct alias *ap; /* if push was associated with an alias */
1034 char *string; /* remember the string since it may change */
1038 struct parsefile *prev; /* preceding file on stack */
1039 int linno; /* current line */
1040 int fd; /* file descriptor (or -1 if string) */
1041 int left_in_line; /* number of chars left in this line */
1042 int left_in_buffer; /* number of chars left in this buffer past the line */
1043 char *next_to_pgetc; /* next char in buffer */
1044 char *buf; /* input buffer */
1045 struct strpush *strpush; /* for pushing strings at this level */
1046 struct strpush basestrpush; /* so pushing one is fast */
1049 static struct parsefile basepf; /* top level input file */
1050 static struct parsefile *g_parsefile = &basepf; /* current input file */
1051 static int startlinno; /* line # where last token started */
1052 static char *commandname; /* currently executing command */
1053 static struct strlist *cmdenviron; /* environment for builtin command */
1054 static uint8_t exitstatus; /* exit status of last command */
1057 /* ============ Message printing */
1060 ash_vmsg(const char *msg, va_list ap)
1062 fprintf(stderr, "%s: ", arg0);
1064 if (strcmp(arg0, commandname))
1065 fprintf(stderr, "%s: ", commandname);
1066 if (!iflag || g_parsefile->fd)
1067 fprintf(stderr, "line %d: ", startlinno);
1069 vfprintf(stderr, msg, ap);
1070 outcslow('\n', stderr);
1074 * Exverror is called to raise the error exception. If the second argument
1075 * is not NULL then error prints an error message using printf style
1076 * formatting. It then raises the error exception.
1078 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1080 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1084 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1086 TRACE(("\") pid=%d\n", getpid()));
1088 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1093 flush_stdout_stderr();
1094 raise_exception(cond);
1098 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1100 ash_msg_and_raise_error(const char *msg, ...)
1105 ash_vmsg_and_raise(EXERROR, msg, ap);
1110 static void raise_error_syntax(const char *) NORETURN;
1112 raise_error_syntax(const char *msg)
1114 ash_msg_and_raise_error("syntax error: %s", msg);
1118 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1120 ash_msg_and_raise(int cond, const char *msg, ...)
1125 ash_vmsg_and_raise(cond, msg, ap);
1131 * error/warning routines for external builtins
1134 ash_msg(const char *fmt, ...)
1144 * Return a string describing an error. The returned string may be a
1145 * pointer to a static buffer that will be overwritten on the next call.
1146 * Action describes the operation that got the error.
1149 errmsg(int e, const char *em)
1151 if (e == ENOENT || e == ENOTDIR) {
1158 /* ============ Memory allocation */
1161 /* I consider these wrappers nearly useless:
1162 * ok, they return you to nearest exception handler, but
1163 * how much memory do you leak in the process, making
1164 * memory starvation worse?
1167 ckrealloc(void * p, size_t nbytes)
1169 p = realloc(p, nbytes);
1171 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1176 ckmalloc(size_t nbytes)
1178 return ckrealloc(NULL, nbytes);
1182 ckzalloc(size_t nbytes)
1184 return memset(ckmalloc(nbytes), 0, nbytes);
1188 ckstrdup(const char *s)
1190 char *p = strdup(s);
1192 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1196 /* Using bbox equivalents. They exit if out of memory */
1197 # define ckrealloc xrealloc
1198 # define ckmalloc xmalloc
1199 # define ckzalloc xzalloc
1200 # define ckstrdup xstrdup
1204 * It appears that grabstackstr() will barf with such alignments
1205 * because stalloc() will return a string allocated in a new stackblock.
1207 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1209 /* Most machines require the value returned from malloc to be aligned
1210 * in some way. The following macro will get this right
1211 * on many machines. */
1212 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1213 /* Minimum size of a block */
1214 MINSIZE = SHELL_ALIGN(504),
1217 struct stack_block {
1218 struct stack_block *prev;
1219 char space[MINSIZE];
1223 struct stack_block *stackp;
1226 struct stackmark *marknext;
1230 struct globals_memstack {
1231 struct stack_block *g_stackp; // = &stackbase;
1232 struct stackmark *markp;
1233 char *g_stacknxt; // = stackbase.space;
1234 char *sstrend; // = stackbase.space + MINSIZE;
1235 size_t g_stacknleft; // = MINSIZE;
1236 int herefd; // = -1;
1237 struct stack_block stackbase;
1239 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1240 #define G_memstack (*ash_ptr_to_globals_memstack)
1241 #define g_stackp (G_memstack.g_stackp )
1242 #define markp (G_memstack.markp )
1243 #define g_stacknxt (G_memstack.g_stacknxt )
1244 #define sstrend (G_memstack.sstrend )
1245 #define g_stacknleft (G_memstack.g_stacknleft)
1246 #define herefd (G_memstack.herefd )
1247 #define stackbase (G_memstack.stackbase )
1248 #define INIT_G_memstack() do { \
1249 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1251 g_stackp = &stackbase; \
1252 g_stacknxt = stackbase.space; \
1253 g_stacknleft = MINSIZE; \
1254 sstrend = stackbase.space + MINSIZE; \
1259 #define stackblock() ((void *)g_stacknxt)
1260 #define stackblocksize() g_stacknleft
1263 * Parse trees for commands are allocated in lifo order, so we use a stack
1264 * to make this more efficient, and also to avoid all sorts of exception
1265 * handling code to handle interrupts in the middle of a parse.
1267 * The size 504 was chosen because the Ultrix malloc handles that size
1271 stalloc(size_t nbytes)
1276 aligned = SHELL_ALIGN(nbytes);
1277 if (aligned > g_stacknleft) {
1280 struct stack_block *sp;
1282 blocksize = aligned;
1283 if (blocksize < MINSIZE)
1284 blocksize = MINSIZE;
1285 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1286 if (len < blocksize)
1287 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1290 sp->prev = g_stackp;
1291 g_stacknxt = sp->space;
1292 g_stacknleft = blocksize;
1293 sstrend = g_stacknxt + blocksize;
1298 g_stacknxt += aligned;
1299 g_stacknleft -= aligned;
1304 stzalloc(size_t nbytes)
1306 return memset(stalloc(nbytes), 0, nbytes);
1313 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1314 write(STDERR_FILENO, "stunalloc\n", 10);
1318 g_stacknleft += g_stacknxt - (char *)p;
1323 * Like strdup but works with the ash stack.
1326 ststrdup(const char *p)
1328 size_t len = strlen(p) + 1;
1329 return memcpy(stalloc(len), p, len);
1333 setstackmark(struct stackmark *mark)
1335 mark->stackp = g_stackp;
1336 mark->stacknxt = g_stacknxt;
1337 mark->stacknleft = g_stacknleft;
1338 mark->marknext = markp;
1343 popstackmark(struct stackmark *mark)
1345 struct stack_block *sp;
1351 markp = mark->marknext;
1352 while (g_stackp != mark->stackp) {
1354 g_stackp = sp->prev;
1357 g_stacknxt = mark->stacknxt;
1358 g_stacknleft = mark->stacknleft;
1359 sstrend = mark->stacknxt + mark->stacknleft;
1364 * When the parser reads in a string, it wants to stick the string on the
1365 * stack and only adjust the stack pointer when it knows how big the
1366 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1367 * of space on top of the stack and stackblocklen returns the length of
1368 * this block. Growstackblock will grow this space by at least one byte,
1369 * possibly moving it (like realloc). Grabstackblock actually allocates the
1370 * part of the block that has been used.
1373 growstackblock(void)
1377 newlen = g_stacknleft * 2;
1378 if (newlen < g_stacknleft)
1379 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1383 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1384 struct stack_block *oldstackp;
1385 struct stackmark *xmark;
1386 struct stack_block *sp;
1387 struct stack_block *prevstackp;
1391 oldstackp = g_stackp;
1393 prevstackp = sp->prev;
1394 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1395 sp = ckrealloc(sp, grosslen);
1396 sp->prev = prevstackp;
1398 g_stacknxt = sp->space;
1399 g_stacknleft = newlen;
1400 sstrend = sp->space + newlen;
1403 * Stack marks pointing to the start of the old block
1404 * must be relocated to point to the new block
1407 while (xmark != NULL && xmark->stackp == oldstackp) {
1408 xmark->stackp = g_stackp;
1409 xmark->stacknxt = g_stacknxt;
1410 xmark->stacknleft = g_stacknleft;
1411 xmark = xmark->marknext;
1415 char *oldspace = g_stacknxt;
1416 size_t oldlen = g_stacknleft;
1417 char *p = stalloc(newlen);
1419 /* free the space we just allocated */
1420 g_stacknxt = memcpy(p, oldspace, oldlen);
1421 g_stacknleft += newlen;
1426 grabstackblock(size_t len)
1428 len = SHELL_ALIGN(len);
1430 g_stacknleft -= len;
1434 * The following routines are somewhat easier to use than the above.
1435 * The user declares a variable of type STACKSTR, which may be declared
1436 * to be a register. The macro STARTSTACKSTR initializes things. Then
1437 * the user uses the macro STPUTC to add characters to the string. In
1438 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1439 * grown as necessary. When the user is done, she can just leave the
1440 * string there and refer to it using stackblock(). Or she can allocate
1441 * the space for it using grabstackstr(). If it is necessary to allow
1442 * someone else to use the stack temporarily and then continue to grow
1443 * the string, the user should use grabstack to allocate the space, and
1444 * then call ungrabstr(p) to return to the previous mode of operation.
1446 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1447 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1448 * is space for at least one character.
1453 size_t len = stackblocksize();
1454 if (herefd >= 0 && len >= 1024) {
1455 full_write(herefd, stackblock(), len);
1456 return stackblock();
1459 return (char *)stackblock() + len;
1463 * Called from CHECKSTRSPACE.
1466 makestrspace(size_t newlen, char *p)
1468 size_t len = p - g_stacknxt;
1469 size_t size = stackblocksize();
1474 size = stackblocksize();
1476 if (nleft >= newlen)
1480 return (char *)stackblock() + len;
1484 stack_nputstr(const char *s, size_t n, char *p)
1486 p = makestrspace(n, p);
1487 p = (char *)memcpy(p, s, n) + n;
1492 stack_putstr(const char *s, char *p)
1494 return stack_nputstr(s, strlen(s), p);
1498 _STPUTC(int c, char *p)
1506 #define STARTSTACKSTR(p) ((p) = stackblock())
1507 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1508 #define CHECKSTRSPACE(n, p) do { \
1511 size_t m = sstrend - q; \
1513 (p) = makestrspace(l, q); \
1515 #define USTPUTC(c, p) (*(p)++ = (c))
1516 #define STACKSTRNUL(p) do { \
1517 if ((p) == sstrend) \
1518 (p) = growstackstr(); \
1521 #define STUNPUTC(p) (--(p))
1522 #define STTOPC(p) ((p)[-1])
1523 #define STADJUST(amount, p) ((p) += (amount))
1525 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1526 #define ungrabstackstr(s, p) stunalloc(s)
1527 #define stackstrend() ((void *)sstrend)
1530 /* ============ String helpers */
1533 * prefix -- see if pfx is a prefix of string.
1536 prefix(const char *string, const char *pfx)
1539 if (*pfx++ != *string++)
1542 return (char *) string;
1546 * Check for a valid number. This should be elsewhere.
1549 is_number(const char *p)
1554 } while (*++p != '\0');
1559 * Convert a string of digits to an integer, printing an error message on
1563 number(const char *s)
1566 ash_msg_and_raise_error(msg_illnum, s);
1571 * Produce a possibly single quoted string suitable as input to the shell.
1572 * The return string is allocated on the stack.
1575 single_quote(const char *s)
1585 len = strchrnul(s, '\'') - s;
1587 q = p = makestrspace(len + 3, p);
1590 q = (char *)memcpy(q, s, len) + len;
1596 len = strspn(s, "'");
1600 q = p = makestrspace(len + 3, p);
1603 q = (char *)memcpy(q, s, len) + len;
1612 return stackblock();
1616 /* ============ nextopt */
1618 static char **argptr; /* argument list for builtin commands */
1619 static char *optionarg; /* set by nextopt (like getopt) */
1620 static char *optptr; /* used by nextopt */
1623 * XXX - should get rid of. Have all builtins use getopt(3).
1624 * The library getopt must have the BSD extension static variable
1625 * "optreset", otherwise it can't be used within the shell safely.
1627 * Standard option processing (a la getopt) for builtin routines.
1628 * The only argument that is passed to nextopt is the option string;
1629 * the other arguments are unnecessary. It returns the character,
1630 * or '\0' on end of input.
1633 nextopt(const char *optstring)
1640 if (p == NULL || *p == '\0') {
1641 /* We ate entire "-param", take next one */
1647 if (*++p == '\0') /* just "-" ? */
1650 if (LONE_DASH(p)) /* "--" ? */
1652 /* p => next "-param" */
1654 /* p => some option char in the middle of a "-param" */
1656 for (q = optstring; *q != c;) {
1658 ash_msg_and_raise_error("illegal option -%c", c);
1666 ash_msg_and_raise_error("no arg for -%c option", c);
1676 /* ============ Shell variables */
1679 * The parsefile structure pointed to by the global variable parsefile
1680 * contains information about the current file being read.
1683 int nparam; /* # of positional parameters (without $0) */
1684 #if ENABLE_ASH_GETOPTS
1685 int optind; /* next parameter to be processed by getopts */
1686 int optoff; /* used by getopts */
1688 unsigned char malloced; /* if parameter list dynamically allocated */
1689 char **p; /* parameter list */
1693 * Free the list of positional parameters.
1696 freeparam(volatile struct shparam *param)
1698 if (param->malloced) {
1700 ap = ap1 = param->p;
1707 #if ENABLE_ASH_GETOPTS
1708 static void FAST_FUNC getoptsreset(const char *value);
1712 struct var *next; /* next entry in hash list */
1713 int flags; /* flags are defined above */
1714 const char *text; /* name=value */
1715 void (*func)(const char *) FAST_FUNC; /* function to be called when */
1716 /* the variable gets set/unset */
1720 struct localvar *next; /* next local variable in list */
1721 struct var *vp; /* the variable that was made local */
1722 int flags; /* saved flags */
1723 const char *text; /* saved text */
1727 #define VEXPORT 0x01 /* variable is exported */
1728 #define VREADONLY 0x02 /* variable cannot be modified */
1729 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1730 #define VTEXTFIXED 0x08 /* text is statically allocated */
1731 #define VSTACK 0x10 /* text is allocated on the stack */
1732 #define VUNSET 0x20 /* the variable is not set */
1733 #define VNOFUNC 0x40 /* don't call the callback function */
1734 #define VNOSET 0x80 /* do not set variable - just readonly test */
1735 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1736 #if ENABLE_ASH_RANDOM_SUPPORT
1737 # define VDYNAMIC 0x200 /* dynamic variable */
1743 static const char defifsvar[] ALIGN1 = "IFS= \t\n";
1744 #define defifs (defifsvar + 4)
1746 static const char defifs[] ALIGN1 = " \t\n";
1750 /* Need to be before varinit_data[] */
1751 #if ENABLE_LOCALE_SUPPORT
1752 static void FAST_FUNC
1753 change_lc_all(const char *value)
1755 if (value && *value != '\0')
1756 setlocale(LC_ALL, value);
1758 static void FAST_FUNC
1759 change_lc_ctype(const char *value)
1761 if (value && *value != '\0')
1762 setlocale(LC_CTYPE, value);
1766 static void chkmail(void);
1767 static void changemail(const char *) FAST_FUNC;
1769 static void changepath(const char *) FAST_FUNC;
1770 #if ENABLE_ASH_RANDOM_SUPPORT
1771 static void change_random(const char *) FAST_FUNC;
1774 static const struct {
1777 void (*func)(const char *) FAST_FUNC;
1778 } varinit_data[] = {
1780 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1782 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
1785 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1786 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1788 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1789 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1790 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1791 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1792 #if ENABLE_ASH_GETOPTS
1793 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1795 #if ENABLE_ASH_RANDOM_SUPPORT
1796 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
1798 #if ENABLE_LOCALE_SUPPORT
1799 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1800 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
1802 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1803 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
1809 struct globals_var {
1810 struct shparam shellparam; /* $@ current positional parameters */
1811 struct redirtab *redirlist;
1813 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1814 struct var *vartab[VTABSIZE];
1815 struct var varinit[ARRAY_SIZE(varinit_data)];
1817 extern struct globals_var *const ash_ptr_to_globals_var;
1818 #define G_var (*ash_ptr_to_globals_var)
1819 #define shellparam (G_var.shellparam )
1820 //#define redirlist (G_var.redirlist )
1821 #define g_nullredirs (G_var.g_nullredirs )
1822 #define preverrout_fd (G_var.preverrout_fd)
1823 #define vartab (G_var.vartab )
1824 #define varinit (G_var.varinit )
1825 #define INIT_G_var() do { \
1827 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1829 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1830 varinit[i].flags = varinit_data[i].flags; \
1831 varinit[i].text = varinit_data[i].text; \
1832 varinit[i].func = varinit_data[i].func; \
1836 #define vifs varinit[0]
1838 # define vmail (&vifs)[1]
1839 # define vmpath (&vmail)[1]
1840 # define vpath (&vmpath)[1]
1842 # define vpath (&vifs)[1]
1844 #define vps1 (&vpath)[1]
1845 #define vps2 (&vps1)[1]
1846 #define vps4 (&vps2)[1]
1847 #if ENABLE_ASH_GETOPTS
1848 # define voptind (&vps4)[1]
1849 # if ENABLE_ASH_RANDOM_SUPPORT
1850 # define vrandom (&voptind)[1]
1853 # if ENABLE_ASH_RANDOM_SUPPORT
1854 # define vrandom (&vps4)[1]
1859 * The following macros access the values of the above variables.
1860 * They have to skip over the name. They return the null string
1861 * for unset variables.
1863 #define ifsval() (vifs.text + 4)
1864 #define ifsset() ((vifs.flags & VUNSET) == 0)
1866 # define mailval() (vmail.text + 5)
1867 # define mpathval() (vmpath.text + 9)
1868 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1870 #define pathval() (vpath.text + 5)
1871 #define ps1val() (vps1.text + 4)
1872 #define ps2val() (vps2.text + 4)
1873 #define ps4val() (vps4.text + 4)
1874 #if ENABLE_ASH_GETOPTS
1875 # define optindval() (voptind.text + 7)
1879 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1880 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1882 #if ENABLE_ASH_GETOPTS
1883 static void FAST_FUNC
1884 getoptsreset(const char *value)
1886 shellparam.optind = number(value);
1887 shellparam.optoff = -1;
1892 * Return of a legal variable name (a letter or underscore followed by zero or
1893 * more letters, underscores, and digits).
1896 endofname(const char *name)
1904 if (!is_in_name(*p))
1911 * Compares two strings up to the first = or '\0'. The first
1912 * string must be terminated by '='; the second may be terminated by
1913 * either '=' or '\0'.
1916 varcmp(const char *p, const char *q)
1920 while ((c = *p) == (d = *q)) {
1935 varequal(const char *a, const char *b)
1937 return !varcmp(a, b);
1941 * Find the appropriate entry in the hash table from the name.
1943 static struct var **
1944 hashvar(const char *p)
1948 hashval = ((unsigned char) *p) << 4;
1949 while (*p && *p != '=')
1950 hashval += (unsigned char) *p++;
1951 return &vartab[hashval % VTABSIZE];
1955 vpcmp(const void *a, const void *b)
1957 return varcmp(*(const char **)a, *(const char **)b);
1961 * This routine initializes the builtin variables.
1971 * PS1 depends on uid
1973 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1974 vps1.text = "PS1=\\w \\$ ";
1977 vps1.text = "PS1=# ";
1980 end = vp + ARRAY_SIZE(varinit);
1982 vpp = hashvar(vp->text);
1985 } while (++vp < end);
1988 static struct var **
1989 findvar(struct var **vpp, const char *name)
1991 for (; *vpp; vpp = &(*vpp)->next) {
1992 if (varequal((*vpp)->text, name)) {
2000 * Find the value of a variable. Returns NULL if not set.
2003 lookupvar(const char *name)
2007 v = *findvar(hashvar(name), name);
2009 #if ENABLE_ASH_RANDOM_SUPPORT
2011 * Dynamic variables are implemented roughly the same way they are
2012 * in bash. Namely, they're "special" so long as they aren't unset.
2013 * As soon as they're unset, they're no longer dynamic, and dynamic
2014 * lookup will no longer happen at that point. -- PFM.
2016 if ((v->flags & VDYNAMIC))
2019 if (!(v->flags & VUNSET))
2020 return strchrnul(v->text, '=') + 1;
2026 * Search the environment of a builtin command.
2029 bltinlookup(const char *name)
2033 for (sp = cmdenviron; sp; sp = sp->next) {
2034 if (varequal(sp->text, name))
2035 return strchrnul(sp->text, '=') + 1;
2037 return lookupvar(name);
2041 * Same as setvar except that the variable and value are passed in
2042 * the first argument as name=value. Since the first argument will
2043 * be actually stored in the table, it should not be a string that
2045 * Called with interrupts off.
2048 setvareq(char *s, int flags)
2050 struct var *vp, **vpp;
2053 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2054 vp = *findvar(vpp, s);
2056 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2059 if (flags & VNOSAVE)
2062 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2068 if (vp->func && (flags & VNOFUNC) == 0)
2069 (*vp->func)(strchrnul(s, '=') + 1);
2071 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2072 free((char*)vp->text);
2074 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2079 vp = ckzalloc(sizeof(*vp));
2081 /*vp->func = NULL; - ckzalloc did it */
2084 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2091 * Set the value of a variable. The flags argument is ored with the
2092 * flags of the variable. If val is NULL, the variable is unset.
2095 setvar(const char *name, const char *val, int flags)
2102 q = endofname(name);
2103 p = strchrnul(q, '=');
2105 if (!namelen || p != q)
2106 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2111 vallen = strlen(val);
2114 nameeq = ckmalloc(namelen + vallen + 2);
2115 p = (char *)memcpy(nameeq, name, namelen) + namelen;
2118 p = (char *)memcpy(p, val, vallen) + vallen;
2121 setvareq(nameeq, flags | VNOSAVE);
2125 #if ENABLE_ASH_GETOPTS
2127 * Safe version of setvar, returns 1 on success 0 on failure.
2130 setvarsafe(const char *name, const char *val, int flags)
2133 volatile int saveint;
2134 struct jmploc *volatile savehandler = exception_handler;
2135 struct jmploc jmploc;
2138 if (setjmp(jmploc.loc))
2141 exception_handler = &jmploc;
2142 setvar(name, val, flags);
2145 exception_handler = savehandler;
2146 RESTORE_INT(saveint);
2152 * Unset the specified variable.
2155 unsetvar(const char *s)
2161 vpp = findvar(hashvar(s), s);
2165 int flags = vp->flags;
2168 if (flags & VREADONLY)
2170 #if ENABLE_ASH_RANDOM_SUPPORT
2171 vp->flags &= ~VDYNAMIC;
2175 if ((flags & VSTRFIXED) == 0) {
2177 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2178 free((char*)vp->text);
2184 vp->flags &= ~VEXPORT;
2194 * Process a linked list of variable assignments.
2197 listsetvar(struct strlist *list_set_var, int flags)
2199 struct strlist *lp = list_set_var;
2205 setvareq(lp->text, flags);
2212 * Generate a list of variables satisfying the given conditions.
2215 listvars(int on, int off, char ***end)
2226 for (vp = *vpp; vp; vp = vp->next) {
2227 if ((vp->flags & mask) == on) {
2228 if (ep == stackstrend())
2229 ep = growstackstr();
2230 *ep++ = (char *) vp->text;
2233 } while (++vpp < vartab + VTABSIZE);
2234 if (ep == stackstrend())
2235 ep = growstackstr();
2239 return grabstackstr(ep);
2243 /* ============ Path search helper
2245 * The variable path (passed by reference) should be set to the start
2246 * of the path before the first call; path_advance will update
2247 * this value as it proceeds. Successive calls to path_advance will return
2248 * the possible path expansions in sequence. If an option (indicated by
2249 * a percent sign) appears in the path entry then the global variable
2250 * pathopt will be set to point to it; otherwise pathopt will be set to
2253 static const char *pathopt; /* set by path_advance */
2256 path_advance(const char **path, const char *name)
2266 for (p = start; *p && *p != ':' && *p != '%'; p++)
2268 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2269 while (stackblocksize() < len)
2273 memcpy(q, start, p - start);
2281 while (*p && *p != ':')
2288 return stalloc(len);
2292 /* ============ Prompt */
2294 static smallint doprompt; /* if set, prompt the user */
2295 static smallint needprompt; /* true if interactive and at start of line */
2297 #if ENABLE_FEATURE_EDITING
2298 static line_input_t *line_input_state;
2299 static const char *cmdedit_prompt;
2301 putprompt(const char *s)
2303 if (ENABLE_ASH_EXPAND_PRMT) {
2304 free((char*)cmdedit_prompt);
2305 cmdedit_prompt = ckstrdup(s);
2312 putprompt(const char *s)
2318 #if ENABLE_ASH_EXPAND_PRMT
2319 /* expandstr() needs parsing machinery, so it is far away ahead... */
2320 static const char *expandstr(const char *ps);
2322 #define expandstr(s) s
2326 setprompt(int whichprompt)
2329 #if ENABLE_ASH_EXPAND_PRMT
2330 struct stackmark smark;
2335 switch (whichprompt) {
2345 #if ENABLE_ASH_EXPAND_PRMT
2346 setstackmark(&smark);
2347 stalloc(stackblocksize());
2349 putprompt(expandstr(prompt));
2350 #if ENABLE_ASH_EXPAND_PRMT
2351 popstackmark(&smark);
2356 /* ============ The cd and pwd commands */
2358 #define CD_PHYSICAL 1
2368 while ((i = nextopt("LP")) != '\0') {
2370 flags ^= CD_PHYSICAL;
2379 * Update curdir (the name of the current directory) in response to a
2383 updatepwd(const char *dir)
2390 cdcomppath = ststrdup(dir);
2393 if (curdir == nullstr)
2395 new = stack_putstr(curdir, new);
2397 new = makestrspace(strlen(dir) + 2, new);
2398 lim = (char *)stackblock() + 1;
2402 if (new > lim && *lim == '/')
2407 if (dir[1] == '/' && dir[2] != '/') {
2413 p = strtok(cdcomppath, "/");
2417 if (p[1] == '.' && p[2] == '\0') {
2429 new = stack_putstr(p, new);
2437 return stackblock();
2441 * Find out what the current directory is. If we already know the current
2442 * directory, this routine returns immediately.
2447 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2448 return dir ? dir : nullstr;
2452 setpwd(const char *val, int setold)
2456 oldcur = dir = curdir;
2459 setvar("OLDPWD", oldcur, VEXPORT);
2462 if (physdir != nullstr) {
2463 if (physdir != oldcur)
2467 if (oldcur == val || !val) {
2473 dir = ckstrdup(val);
2474 if (oldcur != dir && oldcur != nullstr) {
2479 setvar("PWD", dir, VEXPORT);
2482 static void hashcd(void);
2485 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2486 * know that the current directory has changed.
2489 docd(const char *dest, int flags)
2491 const char *dir = 0;
2494 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2497 if (!(flags & CD_PHYSICAL)) {
2498 dir = updatepwd(dest);
2512 static int FAST_FUNC
2513 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2525 dest = bltinlookup(homestr);
2526 else if (LONE_DASH(dest)) {
2527 dest = bltinlookup("OLDPWD");
2549 path = bltinlookup("CDPATH");
2558 p = path_advance(&path, dest);
2559 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2563 if (!docd(p, flags))
2568 ash_msg_and_raise_error("can't cd to %s", dest);
2571 if (flags & CD_PRINT)
2572 out1fmt(snlfmt, curdir);
2576 static int FAST_FUNC
2577 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2580 const char *dir = curdir;
2584 if (physdir == nullstr)
2588 out1fmt(snlfmt, dir);
2593 /* ============ ... */
2596 #define IBUFSIZ COMMON_BUFSIZE
2597 /* buffer for top level input file */
2598 #define basebuf bb_common_bufsiz1
2600 /* Syntax classes */
2601 #define CWORD 0 /* character is nothing special */
2602 #define CNL 1 /* newline character */
2603 #define CBACK 2 /* a backslash character */
2604 #define CSQUOTE 3 /* single quote */
2605 #define CDQUOTE 4 /* double quote */
2606 #define CENDQUOTE 5 /* a terminating quote */
2607 #define CBQUOTE 6 /* backwards single quote */
2608 #define CVAR 7 /* a dollar sign */
2609 #define CENDVAR 8 /* a '}' character */
2610 #define CLP 9 /* a left paren in arithmetic */
2611 #define CRP 10 /* a right paren in arithmetic */
2612 #define CENDFILE 11 /* end of file */
2613 #define CCTL 12 /* like CWORD, except it must be escaped */
2614 #define CSPCL 13 /* these terminate a word */
2615 #define CIGN 14 /* character should be ignored */
2617 #if ENABLE_ASH_ALIAS
2621 #define PEOA_OR_PEOF PEOA
2625 #define PEOA_OR_PEOF PEOF
2628 /* number syntax index */
2629 #define BASESYNTAX 0 /* not in quotes */
2630 #define DQSYNTAX 1 /* in double quotes */
2631 #define SQSYNTAX 2 /* in single quotes */
2632 #define ARISYNTAX 3 /* in arithmetic */
2633 #define PSSYNTAX 4 /* prompt */
2635 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
2636 #define USE_SIT_FUNCTION
2639 #if ENABLE_SH_MATH_SUPPORT
2640 static const char S_I_T[][4] = {
2641 #if ENABLE_ASH_ALIAS
2642 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
2644 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2645 { CNL, CNL, CNL, CNL }, /* 2, \n */
2646 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2647 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2648 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2649 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2650 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2651 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2652 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2653 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2654 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
2655 #ifndef USE_SIT_FUNCTION
2656 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2657 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2658 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2662 static const char S_I_T[][3] = {
2663 #if ENABLE_ASH_ALIAS
2664 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
2666 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2667 { CNL, CNL, CNL }, /* 2, \n */
2668 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2669 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2670 { CVAR, CVAR, CWORD }, /* 5, $ */
2671 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2672 { CSPCL, CWORD, CWORD }, /* 7, ( */
2673 { CSPCL, CWORD, CWORD }, /* 8, ) */
2674 { CBACK, CBACK, CCTL }, /* 9, \ */
2675 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2676 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
2677 #ifndef USE_SIT_FUNCTION
2678 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2679 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2680 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2683 #endif /* SH_MATH_SUPPORT */
2685 #ifdef USE_SIT_FUNCTION
2688 SIT(int c, int syntax)
2690 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2691 #if ENABLE_ASH_ALIAS
2692 static const char syntax_index_table[] ALIGN1 = {
2693 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2694 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2695 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2699 static const char syntax_index_table[] ALIGN1 = {
2700 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2701 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2702 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2709 if (c == PEOF) { /* 2^8+2 */
2712 #if ENABLE_ASH_ALIAS
2713 if (c == PEOA) { /* 2^8+1 */
2718 if ((unsigned char)c >= CTLESC
2719 && (unsigned char)c <= CTLQUOTEMARK
2723 s = strchrnul(spec_symbls, c);
2727 indx = syntax_index_table[s - spec_symbls];
2729 return S_I_T[indx][syntax];
2732 #else /* !USE_SIT_FUNCTION */
2734 #if ENABLE_ASH_ALIAS
2735 #define CSPCL_CIGN_CIGN_CIGN 0
2736 #define CSPCL_CWORD_CWORD_CWORD 1
2737 #define CNL_CNL_CNL_CNL 2
2738 #define CWORD_CCTL_CCTL_CWORD 3
2739 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2740 #define CVAR_CVAR_CWORD_CVAR 5
2741 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2742 #define CSPCL_CWORD_CWORD_CLP 7
2743 #define CSPCL_CWORD_CWORD_CRP 8
2744 #define CBACK_CBACK_CCTL_CBACK 9
2745 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2746 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2747 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2748 #define CWORD_CWORD_CWORD_CWORD 13
2749 #define CCTL_CCTL_CCTL_CCTL 14
2751 #define CSPCL_CWORD_CWORD_CWORD 0
2752 #define CNL_CNL_CNL_CNL 1
2753 #define CWORD_CCTL_CCTL_CWORD 2
2754 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2755 #define CVAR_CVAR_CWORD_CVAR 4
2756 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2757 #define CSPCL_CWORD_CWORD_CLP 6
2758 #define CSPCL_CWORD_CWORD_CRP 7
2759 #define CBACK_CBACK_CCTL_CBACK 8
2760 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2761 #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2762 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2763 #define CWORD_CWORD_CWORD_CWORD 12
2764 #define CCTL_CCTL_CCTL_CCTL 13
2767 static const char syntax_index_table[258] = {
2768 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2769 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2770 #if ENABLE_ASH_ALIAS
2771 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2773 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2774 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2775 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2776 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2777 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2778 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2779 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2780 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2781 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2782 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2793 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2794 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2795 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2796 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2797 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2798 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2799 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2800 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2801 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2802 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2803 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2804 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2805 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2806 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2807 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2808 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2809 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2810 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2811 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2812 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2813 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2814 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2815 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2816 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2817 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2818 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2819 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2820 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2821 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2822 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2823 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2824 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2825 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2826 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2827 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2828 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2829 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2830 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2831 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2832 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2833 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2834 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2835 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2836 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2837 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2838 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2839 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2840 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2841 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2842 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2911 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2912 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2934 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2935 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2936 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2938 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2940 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2941 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2942 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2943 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2944 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2946 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2947 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2948 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2949 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2960 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2961 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2962 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2963 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2964 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2965 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2993 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2994 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2995 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2998 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
3006 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
3007 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
3008 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3009 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3010 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3011 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3012 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3013 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3014 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3015 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3016 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3017 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3018 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3019 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3020 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3021 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3022 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3023 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3024 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3025 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3026 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3027 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3028 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
3031 #define SIT(c, syntax) (S_I_T[(int)syntax_index_table[(int)(c) + SYNBASE]][syntax])
3033 #endif /* USE_SIT_FUNCTION */
3036 /* ============ Alias handling */
3038 #if ENABLE_ASH_ALIAS
3040 #define ALIASINUSE 1
3051 static struct alias **atab; // [ATABSIZE];
3052 #define INIT_G_alias() do { \
3053 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3057 static struct alias **
3058 __lookupalias(const char *name) {
3059 unsigned int hashval;
3066 ch = (unsigned char)*p;
3070 ch = (unsigned char)*++p;
3072 app = &atab[hashval % ATABSIZE];
3074 for (; *app; app = &(*app)->next) {
3075 if (strcmp(name, (*app)->name) == 0) {
3083 static struct alias *
3084 lookupalias(const char *name, int check)
3086 struct alias *ap = *__lookupalias(name);
3088 if (check && ap && (ap->flag & ALIASINUSE))
3093 static struct alias *
3094 freealias(struct alias *ap)
3098 if (ap->flag & ALIASINUSE) {
3099 ap->flag |= ALIASDEAD;
3111 setalias(const char *name, const char *val)
3113 struct alias *ap, **app;
3115 app = __lookupalias(name);
3119 if (!(ap->flag & ALIASINUSE)) {
3122 ap->val = ckstrdup(val);
3123 ap->flag &= ~ALIASDEAD;
3126 ap = ckzalloc(sizeof(struct alias));
3127 ap->name = ckstrdup(name);
3128 ap->val = ckstrdup(val);
3129 /*ap->flag = 0; - ckzalloc did it */
3130 /*ap->next = NULL;*/
3137 unalias(const char *name)
3141 app = __lookupalias(name);
3145 *app = freealias(*app);
3156 struct alias *ap, **app;
3160 for (i = 0; i < ATABSIZE; i++) {
3162 for (ap = *app; ap; ap = *app) {
3163 *app = freealias(*app);
3173 printalias(const struct alias *ap)
3175 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3179 * TODO - sort output
3181 static int FAST_FUNC
3182 aliascmd(int argc UNUSED_PARAM, char **argv)
3191 for (i = 0; i < ATABSIZE; i++) {
3192 for (ap = atab[i]; ap; ap = ap->next) {
3198 while ((n = *++argv) != NULL) {
3199 v = strchr(n+1, '=');
3200 if (v == NULL) { /* n+1: funny ksh stuff */
3201 ap = *__lookupalias(n);
3203 fprintf(stderr, "%s: %s not found\n", "alias", n);
3216 static int FAST_FUNC
3217 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3221 while ((i = nextopt("a")) != '\0') {
3227 for (i = 0; *argptr; argptr++) {
3228 if (unalias(*argptr)) {
3229 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3237 #endif /* ASH_ALIAS */
3240 /* ============ jobs.c */
3242 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3245 #define FORK_NOJOB 2
3247 /* mode flags for showjob(s) */
3248 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3249 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3250 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3253 * A job structure contains information about a job. A job is either a
3254 * single process or a set of processes contained in a pipeline. In the
3255 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3259 pid_t pid; /* process id */
3260 int status; /* last process status from wait() */
3261 char *cmd; /* text of command being run */
3265 struct procstat ps0; /* status of process */
3266 struct procstat *ps; /* status or processes when more than one */
3268 int stopstatus; /* status of a stopped job */
3271 nprocs: 16, /* number of processes */
3273 #define JOBRUNNING 0 /* at least one proc running */
3274 #define JOBSTOPPED 1 /* all procs are stopped */
3275 #define JOBDONE 2 /* all procs are completed */
3277 sigint: 1, /* job was killed by SIGINT */
3278 jobctl: 1, /* job running under job control */
3280 waited: 1, /* true if this entry has been waited for */
3281 used: 1, /* true if this entry is in used */
3282 changed: 1; /* true if status has changed */
3283 struct job *prev_job; /* previous job */
3286 static struct job *makejob(/*union node *,*/ int);
3287 static int forkshell(struct job *, union node *, int);
3288 static int waitforjob(struct job *);
3291 enum { doing_jobctl = 0 };
3292 #define setjobctl(on) do {} while (0)
3294 static smallint doing_jobctl; //references:8
3295 static void setjobctl(int);
3302 ignoresig(int signo)
3304 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3305 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3306 /* No, need to do it */
3307 signal(signo, SIG_IGN);
3309 sigmode[signo - 1] = S_HARD_IGN;
3313 * Signal handler. Only one usage site - in setsignal()
3318 gotsig[signo - 1] = 1;
3320 if (signo == SIGINT && !trap[SIGINT]) {
3321 if (!suppress_int) {
3323 raise_interrupt(); /* does not return */
3327 pending_sig = signo;
3332 * Set the signal handler for the specified signal. The routine figures
3333 * out what it should be set to.
3336 setsignal(int signo)
3339 char cur_act, new_act;
3340 struct sigaction act;
3344 if (t != NULL) { /* trap for this sig is set */
3346 if (t[0] == '\0') /* trap is "": ignore this sig */
3350 if (rootshell && new_act == S_DFL) {
3353 if (iflag || minusc || sflag == 0)
3362 * "In all cases, bash ignores SIGQUIT. Non-builtin
3363 * commands run by bash have signal handlers
3364 * set to the values inherited by the shell
3365 * from its parent". */
3381 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3382 //whereas we have to restore it to what shell got on entry
3383 //from the parent. See comment above
3385 t = &sigmode[signo - 1];
3388 /* current setting is not yet known */
3389 if (sigaction(signo, NULL, &act)) {
3390 /* pretend it worked; maybe we should give a warning,
3391 * but other shells don't. We don't alter sigmode,
3392 * so we retry every time.
3393 * btw, in Linux it never fails. --vda */
3396 if (act.sa_handler == SIG_IGN) {
3397 cur_act = S_HARD_IGN;
3399 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3401 cur_act = S_IGN; /* don't hard ignore these */
3405 if (cur_act == S_HARD_IGN || cur_act == new_act)
3408 act.sa_handler = SIG_DFL;
3411 act.sa_handler = onsig;
3412 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3413 sigfillset(&act.sa_mask); /* ditto */
3416 act.sa_handler = SIG_IGN;
3419 sigaction_set(signo, &act);
3424 /* mode flags for set_curjob */
3425 #define CUR_DELETE 2
3426 #define CUR_RUNNING 1
3427 #define CUR_STOPPED 0
3429 /* mode flags for dowait */
3430 #define DOWAIT_NONBLOCK WNOHANG
3431 #define DOWAIT_BLOCK 0
3434 /* pgrp of shell on invocation */
3435 static int initialpgrp; //references:2
3436 static int ttyfd = -1; //5
3439 static struct job *jobtab; //5
3441 static unsigned njobs; //4
3443 static struct job *curjob; //lots
3444 /* number of presumed living untracked jobs */
3445 static int jobless; //4
3448 set_curjob(struct job *jp, unsigned mode)
3451 struct job **jpp, **curp;
3453 /* first remove from list */
3454 jpp = curp = &curjob;
3459 jpp = &jp1->prev_job;
3461 *jpp = jp1->prev_job;
3463 /* Then re-insert in correct position */
3471 /* job being deleted */
3474 /* newly created job or backgrounded job,
3475 put after all stopped jobs. */
3479 if (!jp1 || jp1->state != JOBSTOPPED)
3482 jpp = &jp1->prev_job;
3488 /* newly stopped job - becomes curjob */
3489 jp->prev_job = *jpp;
3497 jobno(const struct job *jp)
3499 return jp - jobtab + 1;
3504 * Convert a job name to a job structure.
3507 #define getjob(name, getctl) getjob(name)
3510 getjob(const char *name, int getctl)
3514 const char *err_msg = "%s: no such job";
3518 char *(*match)(const char *, const char *);
3533 if (c == '+' || c == '%') {
3535 err_msg = "No current job";
3541 err_msg = "No previous job";
3552 jp = jobtab + num - 1;
3567 if (match(jp->ps[0].cmd, p)) {
3571 err_msg = "%s: ambiguous";
3581 err_msg = "job %s not created under job control";
3582 if (getctl && jp->jobctl == 0)
3587 ash_msg_and_raise_error(err_msg, name);
3591 * Mark a job structure as unused.
3594 freejob(struct job *jp)
3596 struct procstat *ps;
3600 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3601 if (ps->cmd != nullstr)
3604 if (jp->ps != &jp->ps0)
3607 set_curjob(jp, CUR_DELETE);
3613 xtcsetpgrp(int fd, pid_t pgrp)
3615 if (tcsetpgrp(fd, pgrp))
3616 ash_msg_and_raise_error("can't set tty process group (%m)");
3620 * Turn job control on and off.
3622 * Note: This code assumes that the third arg to ioctl is a character
3623 * pointer, which is true on Berkeley systems but not System V. Since
3624 * System V doesn't have job control yet, this isn't a problem now.
3626 * Called with interrupts off.
3634 if (on == doing_jobctl || rootshell == 0)
3638 ofd = fd = open(_PATH_TTY, O_RDWR);
3640 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3641 * That sometimes helps to acquire controlling tty.
3642 * Obviously, a workaround for bugs when someone
3643 * failed to provide a controlling tty to bash! :) */
3649 fd = fcntl(fd, F_DUPFD, 10);
3654 /* fd is a tty at this point */
3655 close_on_exec_on(fd);
3656 do { /* while we are in the background */
3657 pgrp = tcgetpgrp(fd);
3660 ash_msg("can't access tty; job control turned off");
3664 if (pgrp == getpgrp())
3675 xtcsetpgrp(fd, pgrp);
3677 /* turning job control off */
3680 /* was xtcsetpgrp, but this can make exiting ash
3681 * loop forever if pty is already deleted */
3682 tcsetpgrp(fd, pgrp);
3696 static int FAST_FUNC
3697 killcmd(int argc, char **argv)
3700 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3702 if (argv[i][0] == '%') {
3703 struct job *jp = getjob(argv[i], 0);
3704 unsigned pid = jp->ps[0].pid;
3705 /* Enough space for ' -NNN<nul>' */
3706 argv[i] = alloca(sizeof(int)*3 + 3);
3707 /* kill_main has matching code to expect
3708 * leading space. Needed to not confuse
3709 * negative pids with "kill -SIGNAL_NO" syntax */
3710 sprintf(argv[i], " -%u", pid);
3712 } while (argv[++i]);
3714 return kill_main(argc, argv);
3718 showpipe(struct job *jp, FILE *out)
3720 struct procstat *sp;
3721 struct procstat *spend;
3723 spend = jp->ps + jp->nprocs;
3724 for (sp = jp->ps + 1; sp < spend; sp++)
3725 fprintf(out, " | %s", sp->cmd);
3726 outcslow('\n', out);
3727 flush_stdout_stderr();
3732 restartjob(struct job *jp, int mode)
3734 struct procstat *ps;
3740 if (jp->state == JOBDONE)
3742 jp->state = JOBRUNNING;
3744 if (mode == FORK_FG)
3745 xtcsetpgrp(ttyfd, pgid);
3746 killpg(pgid, SIGCONT);
3750 if (WIFSTOPPED(ps->status)) {
3756 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3761 static int FAST_FUNC
3762 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3769 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3774 jp = getjob(*argv, 1);
3775 if (mode == FORK_BG) {
3776 set_curjob(jp, CUR_RUNNING);
3777 fprintf(out, "[%d] ", jobno(jp));
3779 outstr(jp->ps->cmd, out);
3781 retval = restartjob(jp, mode);
3782 } while (*argv && *++argv);
3788 sprint_status(char *s, int status, int sigonly)
3794 if (!WIFEXITED(status)) {
3796 if (WIFSTOPPED(status))
3797 st = WSTOPSIG(status);
3800 st = WTERMSIG(status);
3802 if (st == SIGINT || st == SIGPIPE)
3805 if (WIFSTOPPED(status))
3810 col = fmtstr(s, 32, strsignal(st));
3811 if (WCOREDUMP(status)) {
3812 col += fmtstr(s + col, 16, " (core dumped)");
3814 } else if (!sigonly) {
3815 st = WEXITSTATUS(status);
3817 col = fmtstr(s, 16, "Done(%d)", st);
3819 col = fmtstr(s, 16, "Done");
3826 dowait(int wait_flags, struct job *job)
3831 struct job *thisjob;
3834 TRACE(("dowait(0x%x) called\n", wait_flags));
3836 /* Do a wait system call. If job control is compiled in, we accept
3837 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3838 * NB: _not_ safe_waitpid, we need to detect EINTR */
3839 pid = waitpid(-1, &status,
3840 (doing_jobctl ? (wait_flags | WUNTRACED) : wait_flags));
3841 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3842 pid, status, errno, strerror(errno)));
3848 for (jp = curjob; jp; jp = jp->prev_job) {
3849 struct procstat *sp;
3850 struct procstat *spend;
3851 if (jp->state == JOBDONE)
3854 spend = jp->ps + jp->nprocs;
3857 if (sp->pid == pid) {
3858 TRACE(("Job %d: changing status of proc %d "
3859 "from 0x%x to 0x%x\n",
3860 jobno(jp), pid, sp->status, status));
3861 sp->status = status;
3864 if (sp->status == -1)
3867 if (state == JOBRUNNING)
3869 if (WIFSTOPPED(sp->status)) {
3870 jp->stopstatus = sp->status;
3874 } while (++sp < spend);
3879 if (!WIFSTOPPED(status))
3885 if (state != JOBRUNNING) {
3886 thisjob->changed = 1;
3888 if (thisjob->state != state) {
3889 TRACE(("Job %d: changing state from %d to %d\n",
3890 jobno(thisjob), thisjob->state, state));
3891 thisjob->state = state;
3893 if (state == JOBSTOPPED) {
3894 set_curjob(thisjob, CUR_STOPPED);
3903 if (thisjob && thisjob == job) {
3907 len = sprint_status(s, status, 1);
3918 blocking_wait_with_raise_on_sig(struct job *job)
3920 pid_t pid = dowait(DOWAIT_BLOCK, job);
3921 if (pid <= 0 && pending_sig)
3922 raise_exception(EXSIG);
3928 showjob(FILE *out, struct job *jp, int mode)
3930 struct procstat *ps;
3931 struct procstat *psend;
3938 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
3939 /* just output process (group) id of pipeline */
3940 fprintf(out, "%d\n", ps->pid);
3944 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3949 else if (curjob && jp == curjob->prev_job)
3952 if (mode & SHOW_PIDS)
3953 col += fmtstr(s + col, 16, "%d ", ps->pid);
3955 psend = ps + jp->nprocs;
3957 if (jp->state == JOBRUNNING) {
3958 strcpy(s + col, "Running");
3959 col += sizeof("Running") - 1;
3961 int status = psend[-1].status;
3962 if (jp->state == JOBSTOPPED)
3963 status = jp->stopstatus;
3964 col += sprint_status(s + col, status, 0);
3966 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
3968 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3969 * or prints several "PID | <cmdN>" lines,
3970 * depending on SHOW_PIDS bit.
3971 * We do not print status of individual processes
3972 * between PID and <cmdN>. bash does it, but not very well:
3973 * first line shows overall job status, not process status,
3974 * making it impossible to know 1st process status.
3978 /* for each process */
3981 if (mode & SHOW_PIDS)
3982 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->pid) - 1;
3984 fprintf(out, "%s%*c", s, 33 - col >= 0 ? 33 - col : 0, ' ');
3987 fprintf(out, "%s", ps->cmd);
3991 outcslow('\n', out);
3995 if (jp->state == JOBDONE) {
3996 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4002 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4003 * statuses have changed since the last call to showjobs.
4006 showjobs(FILE *out, int mode)
4010 TRACE(("showjobs(0x%x) called\n", mode));
4012 /* Handle all finished jobs */
4013 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4016 for (jp = curjob; jp; jp = jp->prev_job) {
4017 if (!(mode & SHOW_CHANGED) || jp->changed) {
4018 showjob(out, jp, mode);
4023 static int FAST_FUNC
4024 jobscmd(int argc UNUSED_PARAM, char **argv)
4029 while ((m = nextopt("lp")) != '\0') {
4033 mode |= SHOW_ONLY_PGID;
4039 showjob(stdout, getjob(*argv, 0), mode);
4042 showjobs(stdout, mode);
4049 getstatus(struct job *job)
4054 status = job->ps[job->nprocs - 1].status;
4055 retval = WEXITSTATUS(status);
4056 if (!WIFEXITED(status)) {
4058 retval = WSTOPSIG(status);
4059 if (!WIFSTOPPED(status))
4062 /* XXX: limits number of signals */
4063 retval = WTERMSIG(status);
4065 if (retval == SIGINT)
4071 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4072 jobno(job), job->nprocs, status, retval));
4076 static int FAST_FUNC
4077 waitcmd(int argc UNUSED_PARAM, char **argv)
4084 raise_exception(EXSIG);
4091 /* wait for all jobs */
4095 if (!jp) /* no running procs */
4097 if (jp->state == JOBRUNNING)
4103 * "When bash is waiting for an asynchronous command via
4104 * the wait builtin, the reception of a signal for which a trap
4105 * has been set will cause the wait builtin to return immediately
4106 * with an exit status greater than 128, immediately after which
4107 * the trap is executed."
4108 * Do we do it that way? */
4109 blocking_wait_with_raise_on_sig(NULL);
4115 if (**argv != '%') {
4116 pid_t pid = number(*argv);
4121 if (job->ps[job->nprocs - 1].pid == pid)
4123 job = job->prev_job;
4126 job = getjob(*argv, 0);
4127 /* loop until process terminated or stopped */
4128 while (job->state == JOBRUNNING)
4129 blocking_wait_with_raise_on_sig(NULL);
4131 retval = getstatus(job);
4144 struct job *jp, *jq;
4146 len = njobs * sizeof(*jp);
4148 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4150 offset = (char *)jp - (char *)jq;
4152 /* Relocate pointers */
4155 jq = (struct job *)((char *)jq + l);
4159 #define joff(p) ((struct job *)((char *)(p) + l))
4160 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4161 if (joff(jp)->ps == &jq->ps0)
4162 jmove(joff(jp)->ps);
4163 if (joff(jp)->prev_job)
4164 jmove(joff(jp)->prev_job);
4174 jp = (struct job *)((char *)jp + len);
4178 } while (--jq >= jp);
4183 * Return a new job structure.
4184 * Called with interrupts off.
4187 makejob(/*union node *node,*/ int nprocs)
4192 for (i = njobs, jp = jobtab; ; jp++) {
4199 if (jp->state != JOBDONE || !jp->waited)
4208 memset(jp, 0, sizeof(*jp));
4210 /* jp->jobctl is a bitfield.
4211 * "jp->jobctl |= jobctl" likely to give awful code */
4215 jp->prev_job = curjob;
4220 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4222 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4229 * Return a string identifying a command (to be printed by the
4232 static char *cmdnextc;
4235 cmdputs(const char *s)
4237 static const char vstype[VSTYPE + 1][3] = {
4238 "", "}", "-", "+", "?", "=",
4239 "%", "%%", "#", "##"
4240 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4243 const char *p, *str;
4244 char c, cc[2] = " ";
4249 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4251 while ((c = *p++) != 0) {
4259 if ((subtype & VSTYPE) == VSLENGTH)
4263 if (!(subtype & VSQUOTE) == !(quoted & 1))
4269 str = "\"}" + !(quoted & 1);
4276 case CTLBACKQ+CTLQUOTE:
4279 #if ENABLE_SH_MATH_SUPPORT
4294 if ((subtype & VSTYPE) != VSNORMAL)
4296 str = vstype[subtype & VSTYPE];
4297 if (subtype & VSNUL)
4306 /* These can only happen inside quotes */
4319 while ((c = *str++) != '\0') {
4324 USTPUTC('"', nextc);
4330 /* cmdtxt() and cmdlist() call each other */
4331 static void cmdtxt(union node *n);
4334 cmdlist(union node *np, int sep)
4336 for (; np; np = np->narg.next) {
4340 if (sep && np->narg.next)
4346 cmdtxt(union node *n)
4349 struct nodelist *lp;
4360 lp = n->npipe.cmdlist;
4378 cmdtxt(n->nbinary.ch1);
4394 cmdtxt(n->nif.test);
4396 if (n->nif.elsepart) {
4397 cmdtxt(n->nif.ifpart);
4399 n = n->nif.elsepart;
4417 cmdtxt(n->nbinary.ch1);
4427 cmdputs(n->nfor.var);
4429 cmdlist(n->nfor.args, 1);
4434 cmdputs(n->narg.text);
4438 cmdlist(n->ncmd.args, 1);
4439 cmdlist(n->ncmd.redirect, 0);
4452 cmdputs(n->ncase.expr->narg.text);
4454 for (np = n->ncase.cases; np; np = np->nclist.next) {
4455 cmdtxt(np->nclist.pattern);
4457 cmdtxt(np->nclist.body);
4471 #if ENABLE_ASH_BASH_COMPAT
4486 cmdputs(utoa(n->nfile.fd));
4488 if (n->type == NTOFD || n->type == NFROMFD) {
4489 cmdputs(utoa(n->ndup.dupfd));
4498 commandtext(union node *n)
4502 STARTSTACKSTR(cmdnextc);
4504 name = stackblock();
4505 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4506 name, cmdnextc, cmdnextc));
4507 return ckstrdup(name);
4512 * Fork off a subshell. If we are doing job control, give the subshell its
4513 * own process group. Jp is a job structure that the job is to be added to.
4514 * N is the command that will be evaluated by the child. Both jp and n may
4515 * be NULL. The mode parameter can be one of the following:
4516 * FORK_FG - Fork off a foreground process.
4517 * FORK_BG - Fork off a background process.
4518 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4519 * process group even if job control is on.
4521 * When job control is turned off, background processes have their standard
4522 * input redirected to /dev/null (except for the second and later processes
4525 * Called with interrupts off.
4528 * Clear traps on a fork.
4535 for (tp = trap; tp < &trap[NSIG]; tp++) {
4536 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4538 if (trap_ptr == trap)
4540 /* else: it "belongs" to trap_ptr vector, don't free */
4542 if ((tp - trap) != 0)
4543 setsignal(tp - trap);
4549 /* Lives far away from here, needed for forkchild */
4550 static void closescript(void);
4552 /* Called after fork(), in child */
4553 static NOINLINE void
4554 forkchild(struct job *jp, union node *n, int mode)
4558 TRACE(("Child shell %d\n", getpid()));
4562 /* man bash: "Non-builtin commands run by bash have signal handlers
4563 * set to the values inherited by the shell from its parent".
4564 * Do we do it correctly? */
4568 if (mode == FORK_NOJOB /* is it `xxx` ? */
4569 && n && n->type == NCMD /* is it single cmd? */
4570 /* && n->ncmd.args->type == NARG - always true? */
4571 && strcmp(n->ncmd.args->narg.text, "trap") == 0
4572 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4573 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4575 TRACE(("Trap hack\n"));
4576 /* Awful hack for `trap` or $(trap).
4578 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4579 * contains an example where "trap" is executed in a subshell:
4581 * save_traps=$(trap)
4583 * eval "$save_traps"
4585 * Standard does not say that "trap" in subshell shall print
4586 * parent shell's traps. It only says that its output
4587 * must have suitable form, but then, in the above example
4588 * (which is not supposed to be normative), it implies that.
4590 * bash (and probably other shell) does implement it
4591 * (traps are reset to defaults, but "trap" still shows them),
4592 * but as a result, "trap" logic is hopelessly messed up:
4595 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4596 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4597 * # true | trap <--- trap is in subshell - no output (ditto)
4598 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4599 * trap -- 'echo Ho' SIGWINCH
4600 * # echo `(trap)` <--- in subshell in subshell - output
4601 * trap -- 'echo Ho' SIGWINCH
4602 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4603 * trap -- 'echo Ho' SIGWINCH
4605 * The rules when to forget and when to not forget traps
4606 * get really complex and nonsensical.
4608 * Our solution: ONLY bare $(trap) or `trap` is special.
4610 /* Save trap handler strings for trap builtin to print */
4611 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4612 /* Fall through into clearing traps */
4616 /* do job control only in root shell */
4618 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4621 if (jp->nprocs == 0)
4624 pgrp = jp->ps[0].pid;
4625 /* this can fail because we are doing it in the parent also */
4627 if (mode == FORK_FG)
4628 xtcsetpgrp(ttyfd, pgrp);
4633 if (mode == FORK_BG) {
4634 /* man bash: "When job control is not in effect,
4635 * asynchronous commands ignore SIGINT and SIGQUIT" */
4638 if (jp->nprocs == 0) {
4640 if (open(bb_dev_null, O_RDONLY) != 0)
4641 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4645 if (iflag) { /* why if iflag only? */
4650 * "In all cases, bash ignores SIGQUIT. Non-builtin
4651 * commands run by bash have signal handlers
4652 * set to the values inherited by the shell
4654 * Take care of the second rule: */
4658 if (n && n->type == NCMD
4659 && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4661 TRACE(("Job hack\n"));
4662 /* "jobs": we do not want to clear job list for it,
4663 * instead we remove only _its_ own_ job from job list.
4664 * This makes "jobs .... | cat" more useful.
4670 for (jp = curjob; jp; jp = jp->prev_job)
4675 /* Called after fork(), in parent */
4677 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4680 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4682 TRACE(("In parent shell: child = %d\n", pid));
4684 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4690 if (mode != FORK_NOJOB && jp->jobctl) {
4693 if (jp->nprocs == 0)
4696 pgrp = jp->ps[0].pid;
4697 /* This can fail because we are doing it in the child also */
4701 if (mode == FORK_BG) {
4702 backgndpid = pid; /* set $! */
4703 set_curjob(jp, CUR_RUNNING);
4706 struct procstat *ps = &jp->ps[jp->nprocs++];
4711 if (doing_jobctl && n)
4712 ps->cmd = commandtext(n);
4718 forkshell(struct job *jp, union node *n, int mode)
4722 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4725 TRACE(("Fork failed, errno=%d", errno));
4728 ash_msg_and_raise_error("can't fork");
4731 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4732 forkchild(jp, n, mode);
4734 forkparent(jp, n, mode, pid);
4740 * Wait for job to finish.
4742 * Under job control we have the problem that while a child process
4743 * is running interrupts generated by the user are sent to the child
4744 * but not to the shell. This means that an infinite loop started by
4745 * an interactive user may be hard to kill. With job control turned off,
4746 * an interactive user may place an interactive program inside a loop.
4747 * If the interactive program catches interrupts, the user doesn't want
4748 * these interrupts to also abort the loop. The approach we take here
4749 * is to have the shell ignore interrupt signals while waiting for a
4750 * foreground process to terminate, and then send itself an interrupt
4751 * signal if the child process was terminated by an interrupt signal.
4752 * Unfortunately, some programs want to do a bit of cleanup and then
4753 * exit on interrupt; unless these processes terminate themselves by
4754 * sending a signal to themselves (instead of calling exit) they will
4755 * confuse this approach.
4757 * Called with interrupts off.
4760 waitforjob(struct job *jp)
4764 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4767 while (jp->state == JOBRUNNING) {
4768 /* In non-interactive shells, we _can_ get
4769 * a keyboard signal here and be EINTRed,
4770 * but we just loop back, waiting for command to complete.
4773 * "If bash is waiting for a command to complete and receives
4774 * a signal for which a trap has been set, the trap
4775 * will not be executed until the command completes."
4777 * Reality is that even if trap is not set, bash
4778 * will not act on the signal until command completes.
4779 * Try this. sleep5intoff.c:
4780 * #include <signal.h>
4781 * #include <unistd.h>
4784 * sigemptyset(&set);
4785 * sigaddset(&set, SIGINT);
4786 * sigaddset(&set, SIGQUIT);
4787 * sigprocmask(SIG_BLOCK, &set, NULL);
4791 * $ bash -c './sleep5intoff; echo hi'
4792 * ^C^C^C^C <--- pressing ^C once a second
4794 * $ bash -c './sleep5intoff; echo hi'
4795 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4798 dowait(DOWAIT_BLOCK, jp);
4805 xtcsetpgrp(ttyfd, rootpid);
4807 * This is truly gross.
4808 * If we're doing job control, then we did a TIOCSPGRP which
4809 * caused us (the shell) to no longer be in the controlling
4810 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4811 * intuit from the subprocess exit status whether a SIGINT
4812 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4814 if (jp->sigint) /* TODO: do the same with all signals */
4815 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4817 if (jp->state == JOBDONE)
4824 * return 1 if there are stopped jobs, otherwise 0
4836 if (jp && jp->state == JOBSTOPPED) {
4837 out2str("You have stopped jobs.\n");
4846 /* ============ redir.c
4848 * Code for dealing with input/output redirection.
4851 #define EMPTY -2 /* marks an unused slot in redirtab */
4852 #define CLOSED -3 /* marks a slot of previously-closed fd */
4855 * Open a file in noclobber mode.
4856 * The code was copied from bash.
4859 noclobberopen(const char *fname)
4862 struct stat finfo, finfo2;
4865 * If the file exists and is a regular file, return an error
4868 r = stat(fname, &finfo);
4869 if (r == 0 && S_ISREG(finfo.st_mode)) {
4875 * If the file was not present (r != 0), make sure we open it
4876 * exclusively so that if it is created before we open it, our open
4877 * will fail. Make sure that we do not truncate an existing file.
4878 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4879 * file was not a regular file, we leave O_EXCL off.
4882 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4883 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4885 /* If the open failed, return the file descriptor right away. */
4890 * OK, the open succeeded, but the file may have been changed from a
4891 * non-regular file to a regular file between the stat and the open.
4892 * We are assuming that the O_EXCL open handles the case where FILENAME
4893 * did not exist and is symlinked to an existing file between the stat
4898 * If we can open it and fstat the file descriptor, and neither check
4899 * revealed that it was a regular file, and the file has not been
4900 * replaced, return the file descriptor.
4902 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4903 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4906 /* The file has been replaced. badness. */
4913 * Handle here documents. Normally we fork off a process to write the
4914 * data to a pipe. If the document is short, we can stuff the data in
4915 * the pipe without forking.
4917 /* openhere needs this forward reference */
4918 static void expandhere(union node *arg, int fd);
4920 openhere(union node *redir)
4926 ash_msg_and_raise_error("pipe call failed");
4927 if (redir->type == NHERE) {
4928 len = strlen(redir->nhere.doc->narg.text);
4929 if (len <= PIPE_BUF) {
4930 full_write(pip[1], redir->nhere.doc->narg.text, len);
4934 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4937 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4938 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4939 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4940 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4941 signal(SIGPIPE, SIG_DFL);
4942 if (redir->type == NHERE)
4943 full_write(pip[1], redir->nhere.doc->narg.text, len);
4945 expandhere(redir->nhere.doc, pip[1]);
4946 _exit(EXIT_SUCCESS);
4954 openredirect(union node *redir)
4959 switch (redir->nfile.type) {
4961 fname = redir->nfile.expfname;
4962 f = open(fname, O_RDONLY);
4967 fname = redir->nfile.expfname;
4968 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4973 #if ENABLE_ASH_BASH_COMPAT
4976 /* Take care of noclobber mode. */
4978 fname = redir->nfile.expfname;
4979 f = noclobberopen(fname);
4986 fname = redir->nfile.expfname;
4987 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4992 fname = redir->nfile.expfname;
4993 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5001 /* Fall through to eliminate warning. */
5002 /* Our single caller does this itself */
5009 f = openhere(redir);
5015 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5017 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5021 * Copy a file descriptor to be >= to. Returns -1
5022 * if the source file descriptor is closed, EMPTY if there are no unused
5023 * file descriptors left.
5025 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5026 * old code was doing close(to) prior to copyfd() to achieve the same */
5028 COPYFD_EXACT = (int)~(INT_MAX),
5029 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5032 copyfd(int from, int to)
5036 if (to & COPYFD_EXACT) {
5037 to &= ~COPYFD_EXACT;
5039 newfd = dup2(from, to);
5041 newfd = fcntl(from, F_DUPFD, to);
5044 if (errno == EMFILE)
5046 /* Happens when source fd is not open: try "echo >&99" */
5047 ash_msg_and_raise_error("%d: %m", from);
5052 /* Struct def and variable are moved down to the first usage site */
5057 struct redirtab *next;
5060 struct two_fd_t two_fd[];
5062 #define redirlist (G_var.redirlist)
5064 static int need_to_remember(struct redirtab *rp, int fd)
5068 if (!rp) /* remembering was not requested */
5071 for (i = 0; i < rp->pair_count; i++) {
5072 if (rp->two_fd[i].orig == fd) {
5073 /* already remembered */
5080 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5081 static int is_hidden_fd(struct redirtab *rp, int fd)
5084 struct parsefile *pf;
5097 fd |= COPYFD_RESTORE;
5098 for (i = 0; i < rp->pair_count; i++) {
5099 if (rp->two_fd[i].copy == fd) {
5107 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5108 * old file descriptors are stashed away so that the redirection can be
5109 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5110 * standard output, and the standard error if it becomes a duplicate of
5111 * stdout, is saved in memory.
5113 /* flags passed to redirect */
5114 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5115 #define REDIR_SAVEFD2 03 /* set preverrout */
5117 redirect(union node *redir, int flags)
5119 struct redirtab *sv;
5124 int copied_fd2 = -1;
5134 if (flags & REDIR_PUSH) {
5135 union node *tmp = redir;
5138 #if ENABLE_ASH_BASH_COMPAT
5139 if (redir->nfile.type == NTO2)
5142 tmp = tmp->nfile.next;
5144 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5145 sv->next = redirlist;
5146 sv->pair_count = sv_pos;
5148 sv->nullredirs = g_nullredirs - 1;
5150 while (sv_pos > 0) {
5152 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5157 fd = redir->nfile.fd;
5158 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5159 int right_fd = redir->ndup.dupfd;
5160 /* redirect from/to same file descriptor? */
5163 /* echo >&10 and 10 is a fd opened to the sh script? */
5164 if (is_hidden_fd(sv, right_fd)) {
5165 errno = EBADF; /* as if it is closed */
5166 ash_msg_and_raise_error("%d: %m", right_fd);
5170 newfd = openredirect(redir); /* always >= 0 */
5172 /* Descriptor wasn't open before redirect.
5173 * Mark it for close in the future */
5174 if (need_to_remember(sv, fd)) {
5175 goto remember_to_close;
5180 #if ENABLE_ASH_BASH_COMPAT
5183 if (need_to_remember(sv, fd)) {
5184 /* Copy old descriptor */
5185 i = fcntl(fd, F_DUPFD, 10);
5186 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5187 * are closed in popredir() in the child, preventing them from leaking
5188 * into child. (popredir() also cleans up the mess in case of failures)
5193 /* Strange error (e.g. "too many files" EMFILE?) */
5197 ash_msg_and_raise_error("%d: %m", fd);
5200 /* EBADF: it is not open - good, remember to close it */
5203 } else { /* fd is open, save its copy */
5204 /* "exec fd>&-" should not close fds
5205 * which point to script file(s).
5206 * Force them to be restored afterwards */
5207 if (is_hidden_fd(sv, fd))
5208 i |= COPYFD_RESTORE;
5212 sv->two_fd[sv_pos].orig = fd;
5213 sv->two_fd[sv_pos].copy = i;
5217 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5218 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5219 /* Don't want to trigger debugging */
5223 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5225 } else if (fd != newfd) { /* move newfd to fd */
5226 copyfd(newfd, fd | COPYFD_EXACT);
5227 #if ENABLE_ASH_BASH_COMPAT
5228 if (!(redir->nfile.type == NTO2 && fd == 2))
5232 #if ENABLE_ASH_BASH_COMPAT
5233 if (redir->nfile.type == NTO2 && fd == 1) {
5234 /* We already redirected it to fd 1, now copy it to 2 */
5240 } while ((redir = redir->nfile.next) != NULL);
5243 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5244 preverrout_fd = copied_fd2;
5248 * Undo the effects of the last redirection.
5251 popredir(int drop, int restore)
5253 struct redirtab *rp;
5256 if (--g_nullredirs >= 0)
5260 for (i = 0; i < rp->pair_count; i++) {
5261 int fd = rp->two_fd[i].orig;
5262 int copy = rp->two_fd[i].copy;
5263 if (copy == CLOSED) {
5268 if (copy != EMPTY) {
5269 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5270 copy &= ~COPYFD_RESTORE;
5272 copyfd(copy, fd | COPYFD_EXACT);
5274 close(copy & ~COPYFD_RESTORE);
5277 redirlist = rp->next;
5278 g_nullredirs = rp->nullredirs;
5284 * Undo all redirections. Called on error or interrupt.
5288 * Discard all saved file descriptors.
5291 clearredir(int drop)
5297 popredir(drop, /*restore:*/ 0);
5302 redirectsafe(union node *redir, int flags)
5305 volatile int saveint;
5306 struct jmploc *volatile savehandler = exception_handler;
5307 struct jmploc jmploc;
5310 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5311 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5313 exception_handler = &jmploc;
5314 redirect(redir, flags);
5316 exception_handler = savehandler;
5317 if (err && exception_type != EXERROR)
5318 longjmp(exception_handler->loc, 1);
5319 RESTORE_INT(saveint);
5324 /* ============ Routines to expand arguments to commands
5326 * We have to deal with backquotes, shell variables, and file metacharacters.
5329 #if ENABLE_SH_MATH_SUPPORT
5331 ash_arith(const char *s)
5333 arith_eval_hooks_t math_hooks;
5337 math_hooks.lookupvar = lookupvar;
5338 math_hooks.setvar = setvar;
5339 math_hooks.endofname = endofname;
5342 result = arith(s, &errcode, &math_hooks);
5345 ash_msg_and_raise_error("exponent less than 0");
5347 ash_msg_and_raise_error("divide by zero");
5349 ash_msg_and_raise_error("expression recursion loop detected");
5350 raise_error_syntax(s);
5361 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5362 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5363 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5364 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5365 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5366 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5367 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5368 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5369 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5373 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5374 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5375 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5376 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5377 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5380 * Structure specifying which parts of the string should be searched
5381 * for IFS characters.
5384 struct ifsregion *next; /* next region in list */
5385 int begoff; /* offset of start of region */
5386 int endoff; /* offset of end of region */
5387 int nulonly; /* search for nul bytes only */
5391 struct strlist *list;
5392 struct strlist **lastp;
5395 /* output of current string */
5396 static char *expdest;
5397 /* list of back quote expressions */
5398 static struct nodelist *argbackq;
5399 /* first struct in list of ifs regions */
5400 static struct ifsregion ifsfirst;
5401 /* last struct in list */
5402 static struct ifsregion *ifslastp;
5403 /* holds expanded arg list */
5404 static struct arglist exparg;
5414 expdest = makestrspace(32, expdest);
5415 len = fmtstr(expdest, 32, arith_t_fmt, num);
5416 STADJUST(len, expdest);
5421 esclen(const char *start, const char *p)
5425 while (p > start && (unsigned char)*--p == CTLESC) {
5432 * Remove any CTLESC characters from a string.
5435 rmescapes(char *str, int flag)
5437 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5441 unsigned protect_against_glob;
5444 p = strpbrk(str, qchars);
5450 if (flag & RMESCAPE_ALLOC) {
5451 size_t len = p - str;
5452 size_t fulllen = len + strlen(p) + 1;
5454 if (flag & RMESCAPE_GROW) {
5455 r = makestrspace(fulllen, expdest);
5456 } else if (flag & RMESCAPE_HEAP) {
5457 r = ckmalloc(fulllen);
5459 r = stalloc(fulllen);
5463 q = (char *)memcpy(q, str, len) + len;
5467 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5468 globbing = flag & RMESCAPE_GLOB;
5469 protect_against_glob = globbing;
5471 if (*p == CTLQUOTEMARK) {
5472 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5473 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5474 // Note: both inquotes and protect_against_glob only affect whether
5475 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5476 inquotes = ~inquotes;
5478 protect_against_glob = globbing;
5482 /* naked back slash */
5483 protect_against_glob = 0;
5488 if (protect_against_glob && inquotes && *p != '/') {
5492 protect_against_glob = globbing;
5497 if (flag & RMESCAPE_GROW) {
5499 STADJUST(q - r + 1, expdest);
5503 #define pmatch(a, b) !fnmatch((a), (b), 0)
5506 * Prepare a pattern for a expmeta (internal glob(3)) call.
5508 * Returns an stalloced string.
5511 preglob(const char *pattern, int quoted, int flag)
5513 flag |= RMESCAPE_GLOB;
5515 flag |= RMESCAPE_QUOTED;
5517 return rmescapes((char *)pattern, flag);
5521 * Put a string on the stack.
5524 memtodest(const char *p, size_t len, int syntax, int quotes)
5528 q = makestrspace(quotes ? len * 2 : len, q);
5531 int c = signed_char2int(*p++);
5535 int n = SIT(c, syntax);
5536 if (n == CCTL || n == CBACK)
5546 strtodest(const char *p, int syntax, int quotes)
5548 memtodest(p, strlen(p), syntax, quotes);
5552 * Record the fact that we have to scan this region of the
5553 * string for IFS characters.
5556 recordregion(int start, int end, int nulonly)
5558 struct ifsregion *ifsp;
5560 if (ifslastp == NULL) {
5564 ifsp = ckzalloc(sizeof(*ifsp));
5565 /*ifsp->next = NULL; - ckzalloc did it */
5566 ifslastp->next = ifsp;
5570 ifslastp->begoff = start;
5571 ifslastp->endoff = end;
5572 ifslastp->nulonly = nulonly;
5576 removerecordregions(int endoff)
5578 if (ifslastp == NULL)
5581 if (ifsfirst.endoff > endoff) {
5582 while (ifsfirst.next != NULL) {
5583 struct ifsregion *ifsp;
5585 ifsp = ifsfirst.next->next;
5586 free(ifsfirst.next);
5587 ifsfirst.next = ifsp;
5590 if (ifsfirst.begoff > endoff)
5593 ifslastp = &ifsfirst;
5594 ifsfirst.endoff = endoff;
5599 ifslastp = &ifsfirst;
5600 while (ifslastp->next && ifslastp->next->begoff < endoff)
5601 ifslastp=ifslastp->next;
5602 while (ifslastp->next != NULL) {
5603 struct ifsregion *ifsp;
5605 ifsp = ifslastp->next->next;
5606 free(ifslastp->next);
5607 ifslastp->next = ifsp;
5610 if (ifslastp->endoff > endoff)
5611 ifslastp->endoff = endoff;
5615 exptilde(char *startp, char *p, int flags)
5621 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5626 while ((c = *++p) != '\0') {
5633 if (flags & EXP_VARTILDE)
5643 if (*name == '\0') {
5644 home = lookupvar(homestr);
5646 pw = getpwnam(name);
5651 if (!home || !*home)
5654 startloc = expdest - (char *)stackblock();
5655 strtodest(home, SQSYNTAX, quotes);
5656 recordregion(startloc, expdest - (char *)stackblock(), 0);
5664 * Execute a command inside back quotes. If it's a builtin command, we
5665 * want to save its output in a block obtained from malloc. Otherwise
5666 * we fork off a subprocess and get the output of the command via a pipe.
5667 * Should be called with interrupts off.
5669 struct backcmd { /* result of evalbackcmd */
5670 int fd; /* file descriptor to read from */
5671 int nleft; /* number of chars in buffer */
5672 char *buf; /* buffer */
5673 struct job *jp; /* job structure for command */
5676 /* These forward decls are needed to use "eval" code for backticks handling: */
5677 static uint8_t back_exitstatus; /* exit status of backquoted command */
5678 #define EV_EXIT 01 /* exit after evaluating tree */
5679 static void evaltree(union node *, int);
5681 static void FAST_FUNC
5682 evalbackcmd(union node *n, struct backcmd *result)
5693 saveherefd = herefd;
5701 ash_msg_and_raise_error("pipe call failed");
5702 jp = makejob(/*n,*/ 1);
5703 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5708 copyfd(pip[1], 1 | COPYFD_EXACT);
5712 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5716 result->fd = pip[0];
5719 herefd = saveherefd;
5721 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5722 result->fd, result->buf, result->nleft, result->jp));
5726 * Expand stuff in backwards quotes.
5729 expbackq(union node *cmd, int quoted, int quotes)
5737 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5738 struct stackmark smark;
5741 setstackmark(&smark);
5743 startloc = dest - (char *)stackblock();
5745 evalbackcmd(cmd, &in);
5746 popstackmark(&smark);
5753 memtodest(p, i, syntax, quotes);
5757 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5758 TRACE(("expbackq: read returns %d\n", i));
5767 back_exitstatus = waitforjob(in.jp);
5771 /* Eat all trailing newlines */
5773 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5778 recordregion(startloc, dest - (char *)stackblock(), 0);
5779 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5780 (dest - (char *)stackblock()) - startloc,
5781 (dest - (char *)stackblock()) - startloc,
5782 stackblock() + startloc));
5785 #if ENABLE_SH_MATH_SUPPORT
5787 * Expand arithmetic expression. Backup to start of expression,
5788 * evaluate, place result in (backed up) result, adjust string position.
5801 * This routine is slightly over-complicated for
5802 * efficiency. Next we scan backwards looking for the
5803 * start of arithmetic.
5805 start = stackblock();
5812 while (*p != CTLARI) {
5816 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5821 esc = esclen(start, p);
5831 removerecordregions(begoff);
5838 rmescapes(p + 2, 0);
5840 len = cvtnum(ash_arith(p + 2));
5843 recordregion(begoff, begoff + len, 0);
5847 /* argstr needs it */
5848 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5851 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5852 * characters to allow for further processing. Otherwise treat
5853 * $@ like $* since no splitting will be performed.
5855 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5856 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5857 * for correct expansion of "B=$A" word.
5860 argstr(char *p, int flags, struct strlist *var_str_list)
5862 static const char spclchars[] ALIGN1 = {
5870 CTLBACKQ | CTLQUOTE,
5871 #if ENABLE_SH_MATH_SUPPORT
5876 const char *reject = spclchars;
5878 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5879 int breakall = flags & EXP_WORD;
5884 if (!(flags & EXP_VARTILDE)) {
5886 } else if (flags & EXP_VARTILDE2) {
5891 if (flags & EXP_TILDE) {
5894 flags &= ~EXP_TILDE;
5897 if (*q == CTLESC && (flags & EXP_QWORD))
5900 p = exptilde(p, q, flags);
5903 startloc = expdest - (char *)stackblock();
5905 length += strcspn(p + length, reject);
5906 c = (unsigned char) p[length];
5909 #if ENABLE_SH_MATH_SUPPORT
5913 /* c == '=' || c == ':' || c == CTLENDARI */
5919 expdest = stack_nputstr(p, length, expdest);
5920 newloc = expdest - (char *)stackblock();
5921 if (breakall && !inquotes && newloc > startloc) {
5922 recordregion(startloc, newloc, 0);
5933 if (flags & EXP_VARTILDE2) {
5937 flags |= EXP_VARTILDE2;
5942 * sort of a hack - expand tildes in variable
5943 * assignments (after the first '=' and after ':'s).
5952 case CTLENDVAR: /* ??? */
5955 /* "$@" syntax adherence hack */
5957 && memcmp(p, dolatstr, 4) == 0
5958 && ( p[4] == CTLQUOTEMARK
5959 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5962 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
5965 inquotes = !inquotes;
5978 p = evalvar(p, flags, var_str_list);
5982 case CTLBACKQ|CTLQUOTE:
5983 expbackq(argbackq->n, c, quotes);
5984 argbackq = argbackq->next;
5986 #if ENABLE_SH_MATH_SUPPORT
5999 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
6002 // This commented out code was added by James Simmons <jsimmons@infradead.org>
6003 // as part of a larger change when he added support for ${var/a/b}.
6004 // However, it broke # and % operators:
6008 //echo ${var#ab} abcdcd abcdcd
6009 //echo ${var##ab} abcdcd abcdcd
6010 //echo ${var#a*b} abcdcd ababcdcd (!)
6011 //echo ${var##a*b} cdcd cdcd
6012 //echo ${var#?} babcdcd ababcdcd (!)
6013 //echo ${var##?} babcdcd babcdcd
6014 //echo ${var#*} ababcdcd babcdcd (!)
6016 //echo ${var%cd} ababcd ababcd
6017 //echo ${var%%cd} ababcd abab (!)
6018 //echo ${var%c*d} ababcd ababcd
6019 //echo ${var%%c*d} abab ababcdcd (!)
6020 //echo ${var%?} ababcdc ababcdc
6021 //echo ${var%%?} ababcdc ababcdcd (!)
6022 //echo ${var%*} ababcdcd ababcdcd
6025 // Commenting it back out helped. Remove it completely if it really
6028 char *loc, *loc2; //, *full;
6034 int match; // = strlen(str);
6035 const char *s = loc2;
6042 match = pmatch(str, s); // this line was deleted
6044 // // chop off end if its '*'
6045 // full = strrchr(str, '*');
6046 // if (full && full != str)
6049 // // If str starts with '*' replace with s.
6050 // if ((*str == '*') && strlen(s) >= match) {
6051 // full = xstrdup(s);
6052 // strncpy(full+strlen(s)-match+1, str+1, match-1);
6054 // full = xstrndup(str, match);
6055 // match = strncmp(s, full, strlen(full));
6059 if (match) // if (!match)
6061 if (quotes && *loc == CTLESC)
6070 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6077 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6080 const char *s = loc2;
6085 match = pmatch(str, s);
6092 esc = esclen(startp, loc);
6103 static void varunset(const char *, const char *, const char *, int) NORETURN;
6105 varunset(const char *end, const char *var, const char *umsg, int varflags)
6111 msg = "parameter not set";
6113 if (*end == CTLENDVAR) {
6114 if (varflags & VSNUL)
6120 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6123 #if ENABLE_ASH_BASH_COMPAT
6125 parse_sub_pattern(char *arg, int inquotes)
6127 char *idx, *repl = NULL;
6136 /* Only the first '/' seen is our separator */
6143 if (!inquotes && c == '\\' && arg[1] == '\\')
6144 arg++; /* skip both \\, not just first one */
6151 #endif /* ENABLE_ASH_BASH_COMPAT */
6154 subevalvar(char *p, char *str, int strloc, int subtype,
6155 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6157 struct nodelist *saveargbackq = argbackq;
6160 char *rmesc, *rmescend;
6161 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6162 IF_ASH_BASH_COMPAT(char null = '\0';)
6163 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6164 int saveherefd = herefd;
6165 int amount, workloc, resetloc;
6167 char *(*scan)(char*, char*, char*, char*, int, int);
6170 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6172 STPUTC('\0', expdest);
6173 herefd = saveherefd;
6174 argbackq = saveargbackq;
6175 startp = (char *)stackblock() + startloc;
6179 setvar(str, startp, 0);
6180 amount = startp - expdest;
6181 STADJUST(amount, expdest);
6184 #if ENABLE_ASH_BASH_COMPAT
6186 loc = str = stackblock() + strloc;
6187 /* Read POS in ${var:POS:LEN} */
6188 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6189 len = str - startp - 1;
6191 /* *loc != '\0', guaranteed by parser */
6195 /* Adjust the length by the number of escapes */
6196 for (ptr = startp; ptr < (str - 1); ptr++) {
6197 if (*ptr == CTLESC) {
6205 if (*loc++ == ':') {
6209 /* Skip POS in ${var:POS:LEN} */
6211 while (*loc && *loc != ':') {
6213 * bash complains on: var=qwe; echo ${var:1a:123}
6215 ash_msg_and_raise_error(msg_illnum, str);
6219 if (*loc++ == ':') {
6223 if (pos >= orig_len) {
6227 if (len > (orig_len - pos))
6228 len = orig_len - pos;
6230 for (str = startp; pos; str++, pos--) {
6231 if (quotes && *str == CTLESC)
6234 for (loc = startp; len; len--) {
6235 if (quotes && *str == CTLESC)
6240 amount = loc - expdest;
6241 STADJUST(amount, expdest);
6246 varunset(p, str, startp, varflags);
6249 resetloc = expdest - (char *)stackblock();
6251 /* We'll comeback here if we grow the stack while handling
6252 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6253 * stack will need rebasing, and we'll need to remove our work
6256 IF_ASH_BASH_COMPAT(restart:)
6258 amount = expdest - ((char *)stackblock() + resetloc);
6259 STADJUST(-amount, expdest);
6260 startp = (char *)stackblock() + startloc;
6263 rmescend = (char *)stackblock() + strloc;
6265 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6266 if (rmesc != startp) {
6268 startp = (char *)stackblock() + startloc;
6272 str = (char *)stackblock() + strloc;
6273 preglob(str, varflags & VSQUOTE, 0);
6274 workloc = expdest - (char *)stackblock();
6276 #if ENABLE_ASH_BASH_COMPAT
6277 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6278 char *idx, *end, *restart_detect;
6281 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6286 /* If there's no pattern to match, return the expansion unmolested */
6294 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6296 /* No match, advance */
6297 restart_detect = stackblock();
6298 STPUTC(*idx, expdest);
6299 if (quotes && *idx == CTLESC) {
6302 STPUTC(*idx, expdest);
6304 if (stackblock() != restart_detect)
6312 if (subtype == VSREPLACEALL) {
6314 if (quotes && *idx == CTLESC)
6323 for (loc = repl; *loc; loc++) {
6324 restart_detect = stackblock();
6325 STPUTC(*loc, expdest);
6326 if (stackblock() != restart_detect)
6331 if (subtype == VSREPLACE) {
6333 restart_detect = stackblock();
6334 STPUTC(*idx, expdest);
6335 if (stackblock() != restart_detect)
6344 /* We've put the replaced text into a buffer at workloc, now
6345 * move it to the right place and adjust the stack.
6347 startp = stackblock() + startloc;
6348 STPUTC('\0', expdest);
6349 memmove(startp, stackblock() + workloc, len);
6350 startp[len++] = '\0';
6351 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6352 STADJUST(-amount, expdest);
6355 #endif /* ENABLE_ASH_BASH_COMPAT */
6357 subtype -= VSTRIMRIGHT;
6359 if (subtype < 0 || subtype > 7)
6362 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6363 zero = subtype >> 1;
6364 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6365 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6367 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6370 memmove(startp, loc, str - loc);
6371 loc = startp + (str - loc) - 1;
6374 amount = loc - expdest;
6375 STADJUST(amount, expdest);
6381 * Add the value of a specialized variable to the stack string.
6382 * name parameter (examples):
6383 * ash -c 'echo $1' name:'1='
6384 * ash -c 'echo $qwe' name:'qwe='
6385 * ash -c 'echo $$' name:'$='
6386 * ash -c 'echo ${$}' name:'$='
6387 * ash -c 'echo ${$##q}' name:'$=q'
6388 * ash -c 'echo ${#$}' name:'$='
6389 * note: examples with bad shell syntax:
6390 * ash -c 'echo ${#$1}' name:'$=1'
6391 * ash -c 'echo ${#1#}' name:'1=#'
6393 static NOINLINE ssize_t
6394 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6404 int quoted = varflags & VSQUOTE;
6405 int subtype = varflags & VSTYPE;
6406 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6408 if (quoted && (flags & EXP_FULL))
6409 sep = 1 << CHAR_BIT;
6411 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6420 num = shellparam.nparam;
6428 goto check_1char_name;
6430 expdest = makestrspace(NOPTS, expdest);
6431 for (i = NOPTS - 1; i >= 0; i--) {
6433 USTPUTC(optletters(i), expdest);
6439 /* handles cases similar to ${#$1} */
6440 if (name[2] != '\0')
6441 raise_error_syntax("bad substitution");
6449 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
6450 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6456 while ((p = *ap++) != NULL) {
6459 partlen = strlen(p);
6462 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6463 memtodest(p, partlen, syntax, quotes);
6469 if (subtype == VSPLUS || subtype == VSLENGTH) {
6490 num = atoi(name); /* number(name) fails on ${N#str} etc */
6491 if (num < 0 || num > shellparam.nparam)
6493 p = num ? shellparam.p[num - 1] : arg0;
6496 /* NB: name has form "VAR=..." */
6498 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6499 * which should be considered before we check variables. */
6501 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6505 str = var_str_list->text;
6506 eq = strchr(str, '=');
6507 if (!eq) /* stop at first non-assignment */
6510 if (name_len == (unsigned)(eq - str)
6511 && strncmp(str, name, name_len) == 0) {
6513 /* goto value; - WRONG! */
6514 /* think "A=1 A=2 B=$A" */
6516 var_str_list = var_str_list->next;
6517 } while (var_str_list);
6521 p = lookupvar(name);
6527 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6528 memtodest(p, len, syntax, quotes);
6532 if (subtype == VSPLUS || subtype == VSLENGTH)
6533 STADJUST(-len, expdest);
6538 * Expand a variable, and return a pointer to the next character in the
6542 evalvar(char *p, int flags, struct strlist *var_str_list)
6553 varflags = (unsigned char) *p++;
6554 subtype = varflags & VSTYPE;
6555 quoted = varflags & VSQUOTE;
6557 easy = (!quoted || (*var == '@' && shellparam.nparam));
6558 startloc = expdest - (char *)stackblock();
6559 p = strchr(p, '=') + 1;
6562 varlen = varvalue(var, varflags, flags, var_str_list);
6563 if (varflags & VSNUL)
6566 if (subtype == VSPLUS) {
6567 varlen = -1 - varlen;
6571 if (subtype == VSMINUS) {
6575 p, flags | EXP_TILDE |
6576 (quoted ? EXP_QWORD : EXP_WORD),
6586 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6588 if (subevalvar(p, var, /* strloc: */ 0,
6589 subtype, startloc, varflags,
6595 * Remove any recorded regions beyond
6598 removerecordregions(startloc);
6608 if (varlen < 0 && uflag)
6609 varunset(p, var, 0, 0);
6611 if (subtype == VSLENGTH) {
6612 cvtnum(varlen > 0 ? varlen : 0);
6616 if (subtype == VSNORMAL) {
6627 case VSTRIMRIGHTMAX:
6628 #if ENABLE_ASH_BASH_COMPAT
6641 * Terminate the string and start recording the pattern
6644 STPUTC('\0', expdest);
6645 patloc = expdest - (char *)stackblock();
6646 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6648 //TODO: | EXP_REDIR too? All other such places do it too
6649 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6652 int amount = expdest - (
6653 (char *)stackblock() + patloc - 1
6655 STADJUST(-amount, expdest);
6657 /* Remove any recorded regions beyond start of variable */
6658 removerecordregions(startloc);
6660 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6664 if (subtype != VSNORMAL) { /* skip to end of alternative */
6670 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6672 argbackq = argbackq->next;
6673 } else if (c == CTLVAR) {
6674 if ((*p++ & VSTYPE) != VSNORMAL)
6676 } else if (c == CTLENDVAR) {
6686 * Break the argument string into pieces based upon IFS and add the
6687 * strings to the argument list. The regions of the string to be
6688 * searched for IFS characters have been stored by recordregion.
6691 ifsbreakup(char *string, struct arglist *arglist)
6693 struct ifsregion *ifsp;
6698 const char *ifs, *realifs;
6703 if (ifslastp != NULL) {
6706 realifs = ifsset() ? ifsval() : defifs;
6709 p = string + ifsp->begoff;
6710 nulonly = ifsp->nulonly;
6711 ifs = nulonly ? nullstr : realifs;
6713 while (p < string + ifsp->endoff) {
6717 if (!strchr(ifs, *p)) {
6722 ifsspc = (strchr(defifs, *p) != NULL);
6723 /* Ignore IFS whitespace at start */
6724 if (q == start && ifsspc) {
6730 sp = stzalloc(sizeof(*sp));
6732 *arglist->lastp = sp;
6733 arglist->lastp = &sp->next;
6737 if (p >= string + ifsp->endoff) {
6743 if (strchr(ifs, *p) == NULL) {
6747 if (strchr(defifs, *p) == NULL) {
6762 } while (ifsp != NULL);
6771 sp = stzalloc(sizeof(*sp));
6773 *arglist->lastp = sp;
6774 arglist->lastp = &sp->next;
6780 struct ifsregion *p;
6785 struct ifsregion *ifsp;
6791 ifsfirst.next = NULL;
6796 * Add a file name to the list.
6799 addfname(const char *name)
6803 sp = stzalloc(sizeof(*sp));
6804 sp->text = ststrdup(name);
6806 exparg.lastp = &sp->next;
6809 static char *expdir;
6812 * Do metacharacter (i.e. *, ?, [...]) expansion.
6815 expmeta(char *enddir, char *name)
6830 for (p = name; *p; p++) {
6831 if (*p == '*' || *p == '?')
6833 else if (*p == '[') {
6840 if (*q == '/' || *q == '\0')
6847 } else if (*p == '\\')
6849 else if (*p == '/') {
6856 if (metaflag == 0) { /* we've reached the end of the file name */
6857 if (enddir != expdir)
6865 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6876 } while (p < start);
6878 if (enddir == expdir) {
6880 } else if (enddir == expdir + 1 && *expdir == '/') {
6889 if (enddir != expdir)
6891 if (*endname == 0) {
6903 while (!pending_int && (dp = readdir(dirp)) != NULL) {
6904 if (dp->d_name[0] == '.' && !matchdot)
6906 if (pmatch(start, dp->d_name)) {
6908 strcpy(enddir, dp->d_name);
6911 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6914 expmeta(p, endname);
6923 static struct strlist *
6924 msort(struct strlist *list, int len)
6926 struct strlist *p, *q = NULL;
6927 struct strlist **lpp;
6935 for (n = half; --n >= 0;) {
6939 q->next = NULL; /* terminate first half of list */
6940 q = msort(list, half); /* sort first half of list */
6941 p = msort(p, len - half); /* sort second half */
6944 #if ENABLE_LOCALE_SUPPORT
6945 if (strcoll(p->text, q->text) < 0)
6947 if (strcmp(p->text, q->text) < 0)
6971 * Sort the results of file name expansion. It calculates the number of
6972 * strings to sort and then calls msort (short for merge sort) to do the
6975 static struct strlist *
6976 expsort(struct strlist *str)
6982 for (sp = str; sp; sp = sp->next)
6984 return msort(str, len);
6988 expandmeta(struct strlist *str /*, int flag*/)
6990 static const char metachars[] ALIGN1 = {
6993 /* TODO - EXP_REDIR */
6996 struct strlist **savelastp;
7002 if (!strpbrk(str->text, metachars))
7004 savelastp = exparg.lastp;
7007 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7009 int i = strlen(str->text);
7010 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7018 if (exparg.lastp == savelastp) {
7023 *exparg.lastp = str;
7024 rmescapes(str->text, 0);
7025 exparg.lastp = &str->next;
7027 *exparg.lastp = NULL;
7028 *savelastp = sp = expsort(*savelastp);
7029 while (sp->next != NULL)
7031 exparg.lastp = &sp->next;
7038 * Perform variable substitution and command substitution on an argument,
7039 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7040 * perform splitting and file name expansion. When arglist is NULL, perform
7041 * here document expansion.
7044 expandarg(union node *arg, struct arglist *arglist, int flag)
7049 argbackq = arg->narg.backquote;
7050 STARTSTACKSTR(expdest);
7051 ifsfirst.next = NULL;
7053 argstr(arg->narg.text, flag,
7054 /* var_str_list: */ arglist ? arglist->list : NULL);
7055 p = _STPUTC('\0', expdest);
7057 if (arglist == NULL) {
7058 return; /* here document expanded */
7060 p = grabstackstr(p);
7061 exparg.lastp = &exparg.list;
7065 if (flag & EXP_FULL) {
7066 ifsbreakup(p, &exparg);
7067 *exparg.lastp = NULL;
7068 exparg.lastp = &exparg.list;
7069 expandmeta(exparg.list /*, flag*/);
7071 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7073 sp = stzalloc(sizeof(*sp));
7076 exparg.lastp = &sp->next;
7080 *exparg.lastp = NULL;
7082 *arglist->lastp = exparg.list;
7083 arglist->lastp = exparg.lastp;
7088 * Expand shell variables and backquotes inside a here document.
7091 expandhere(union node *arg, int fd)
7094 expandarg(arg, (struct arglist *)NULL, 0);
7095 full_write(fd, stackblock(), expdest - (char *)stackblock());
7099 * Returns true if the pattern matches the string.
7102 patmatch(char *pattern, const char *string)
7104 return pmatch(preglob(pattern, 0, 0), string);
7108 * See if a pattern matches in a case statement.
7111 casematch(union node *pattern, char *val)
7113 struct stackmark smark;
7116 setstackmark(&smark);
7117 argbackq = pattern->narg.backquote;
7118 STARTSTACKSTR(expdest);
7120 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7121 /* var_str_list: */ NULL);
7122 STACKSTRNUL(expdest);
7123 result = patmatch(stackblock(), val);
7124 popstackmark(&smark);
7129 /* ============ find_command */
7133 int (*builtin)(int, char **) FAST_FUNC;
7134 /* unsigned flags; */
7136 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7137 /* "regular" builtins always take precedence over commands,
7138 * regardless of PATH=....%builtin... position */
7139 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7140 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7143 smallint cmdtype; /* CMDxxx */
7146 /* index >= 0 for commands without path (slashes) */
7147 /* (TODO: what exactly does the value mean? PATH position?) */
7148 /* index == -1 for commands with slashes */
7149 /* index == (-2 - applet_no) for NOFORK applets */
7150 const struct builtincmd *cmd;
7151 struct funcnode *func;
7154 /* values of cmdtype */
7155 #define CMDUNKNOWN -1 /* no entry in table for command */
7156 #define CMDNORMAL 0 /* command is an executable program */
7157 #define CMDFUNCTION 1 /* command is a shell function */
7158 #define CMDBUILTIN 2 /* command is a shell builtin */
7160 /* action to find_command() */
7161 #define DO_ERR 0x01 /* prints errors */
7162 #define DO_ABS 0x02 /* checks absolute paths */
7163 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7164 #define DO_ALTPATH 0x08 /* using alternate path */
7165 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7167 static void find_command(char *, struct cmdentry *, int, const char *);
7170 /* ============ Hashing commands */
7173 * When commands are first encountered, they are entered in a hash table.
7174 * This ensures that a full path search will not have to be done for them
7175 * on each invocation.
7177 * We should investigate converting to a linear search, even though that
7178 * would make the command name "hash" a misnomer.
7182 struct tblentry *next; /* next entry in hash chain */
7183 union param param; /* definition of builtin function */
7184 smallint cmdtype; /* CMDxxx */
7185 char rehash; /* if set, cd done since entry created */
7186 char cmdname[1]; /* name of command */
7189 static struct tblentry **cmdtable;
7190 #define INIT_G_cmdtable() do { \
7191 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7194 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7198 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7202 #if ENABLE_FEATURE_SH_STANDALONE
7203 if (applet_no >= 0) {
7204 if (APPLET_IS_NOEXEC(applet_no)) {
7207 run_applet_no_and_exit(applet_no, argv);
7209 /* re-exec ourselves with the new arguments */
7210 execve(bb_busybox_exec_path, argv, envp);
7211 /* If they called chroot or otherwise made the binary no longer
7212 * executable, fall through */
7219 execve(cmd, argv, envp);
7220 } while (errno == EINTR);
7222 execve(cmd, argv, envp);
7228 if (errno == ENOEXEC) {
7232 for (ap = argv; *ap; ap++)
7234 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7236 ap[0] = cmd = (char *)DEFAULT_SHELL;
7239 while ((*ap++ = *argv++) != NULL)
7248 * Exec a program. Never returns. If you change this routine, you may
7249 * have to change the find_command routine as well.
7251 static void shellexec(char **, const char *, int) NORETURN;
7253 shellexec(char **argv, const char *path, int idx)
7259 #if ENABLE_FEATURE_SH_STANDALONE
7263 clearredir(/*drop:*/ 1);
7264 envp = listvars(VEXPORT, VUNSET, 0);
7265 if (strchr(argv[0], '/') != NULL
7266 #if ENABLE_FEATURE_SH_STANDALONE
7267 || (applet_no = find_applet_by_name(argv[0])) >= 0
7270 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7274 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7275 if (--idx < 0 && pathopt == NULL) {
7276 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7277 if (errno != ENOENT && errno != ENOTDIR)
7284 /* Map to POSIX errors */
7296 exitstatus = exerrno;
7297 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7298 argv[0], e, suppress_int));
7299 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7304 printentry(struct tblentry *cmdp)
7310 idx = cmdp->param.index;
7313 name = path_advance(&path, cmdp->cmdname);
7315 } while (--idx >= 0);
7316 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7320 * Clear out command entries. The argument specifies the first entry in
7321 * PATH which has changed.
7324 clearcmdentry(int firstchange)
7326 struct tblentry **tblp;
7327 struct tblentry **pp;
7328 struct tblentry *cmdp;
7331 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7333 while ((cmdp = *pp) != NULL) {
7334 if ((cmdp->cmdtype == CMDNORMAL &&
7335 cmdp->param.index >= firstchange)
7336 || (cmdp->cmdtype == CMDBUILTIN &&
7337 builtinloc >= firstchange)
7350 * Locate a command in the command hash table. If "add" is nonzero,
7351 * add the command to the table if it is not already present. The
7352 * variable "lastcmdentry" is set to point to the address of the link
7353 * pointing to the entry, so that delete_cmd_entry can delete the
7356 * Interrupts must be off if called with add != 0.
7358 static struct tblentry **lastcmdentry;
7360 static struct tblentry *
7361 cmdlookup(const char *name, int add)
7363 unsigned int hashval;
7365 struct tblentry *cmdp;
7366 struct tblentry **pp;
7369 hashval = (unsigned char)*p << 4;
7371 hashval += (unsigned char)*p++;
7373 pp = &cmdtable[hashval % CMDTABLESIZE];
7374 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7375 if (strcmp(cmdp->cmdname, name) == 0)
7379 if (add && cmdp == NULL) {
7380 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7382 /* + 1 - already done because
7383 * tblentry::cmdname is char[1] */);
7384 /*cmdp->next = NULL; - ckzalloc did it */
7385 cmdp->cmdtype = CMDUNKNOWN;
7386 strcpy(cmdp->cmdname, name);
7393 * Delete the command entry returned on the last lookup.
7396 delete_cmd_entry(void)
7398 struct tblentry *cmdp;
7401 cmdp = *lastcmdentry;
7402 *lastcmdentry = cmdp->next;
7403 if (cmdp->cmdtype == CMDFUNCTION)
7404 freefunc(cmdp->param.func);
7410 * Add a new command entry, replacing any existing command entry for
7411 * the same name - except special builtins.
7414 addcmdentry(char *name, struct cmdentry *entry)
7416 struct tblentry *cmdp;
7418 cmdp = cmdlookup(name, 1);
7419 if (cmdp->cmdtype == CMDFUNCTION) {
7420 freefunc(cmdp->param.func);
7422 cmdp->cmdtype = entry->cmdtype;
7423 cmdp->param = entry->u;
7427 static int FAST_FUNC
7428 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7430 struct tblentry **pp;
7431 struct tblentry *cmdp;
7433 struct cmdentry entry;
7436 if (nextopt("r") != '\0') {
7441 if (*argptr == NULL) {
7442 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7443 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7444 if (cmdp->cmdtype == CMDNORMAL)
7452 while ((name = *argptr) != NULL) {
7453 cmdp = cmdlookup(name, 0);
7455 && (cmdp->cmdtype == CMDNORMAL
7456 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7460 find_command(name, &entry, DO_ERR, pathval());
7461 if (entry.cmdtype == CMDUNKNOWN)
7469 * Called when a cd is done. Marks all commands so the next time they
7470 * are executed they will be rehashed.
7475 struct tblentry **pp;
7476 struct tblentry *cmdp;
7478 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7479 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7480 if (cmdp->cmdtype == CMDNORMAL
7481 || (cmdp->cmdtype == CMDBUILTIN
7482 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7492 * Fix command hash table when PATH changed.
7493 * Called before PATH is changed. The argument is the new value of PATH;
7494 * pathval() still returns the old value at this point.
7495 * Called with interrupts off.
7497 static void FAST_FUNC
7498 changepath(const char *new)
7506 firstchange = 9999; /* assume no change */
7512 if ((*old == '\0' && *new == ':')
7513 || (*old == ':' && *new == '\0'))
7515 old = new; /* ignore subsequent differences */
7519 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7525 if (builtinloc < 0 && idx_bltin >= 0)
7526 builtinloc = idx_bltin; /* zap builtins */
7527 if (builtinloc >= 0 && idx_bltin < 0)
7529 clearcmdentry(firstchange);
7530 builtinloc = idx_bltin;
7545 #define TENDBQUOTE 12
7562 typedef smallint token_id_t;
7564 /* first char is indicating which tokens mark the end of a list */
7565 static const char *const tokname_array[] = {
7579 #define KWDOFFSET 13
7580 /* the following are keywords */
7602 static char buf[16];
7605 //if (tok < TSEMI) return tokname_array[tok] + 1;
7606 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7611 sprintf(buf + (tok >= TSEMI), "%s%c",
7612 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7616 /* Wrapper around strcmp for qsort/bsearch/... */
7618 pstrcmp(const void *a, const void *b)
7620 return strcmp((char*) a, (*(char**) b) + 1);
7623 static const char *const *
7624 findkwd(const char *s)
7626 return bsearch(s, tokname_array + KWDOFFSET,
7627 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7628 sizeof(tokname_array[0]), pstrcmp);
7632 * Locate and print what a word is...
7635 describe_command(char *command, int describe_command_verbose)
7637 struct cmdentry entry;
7638 struct tblentry *cmdp;
7639 #if ENABLE_ASH_ALIAS
7640 const struct alias *ap;
7642 const char *path = pathval();
7644 if (describe_command_verbose) {
7648 /* First look at the keywords */
7649 if (findkwd(command)) {
7650 out1str(describe_command_verbose ? " is a shell keyword" : command);
7654 #if ENABLE_ASH_ALIAS
7655 /* Then look at the aliases */
7656 ap = lookupalias(command, 0);
7658 if (!describe_command_verbose) {
7663 out1fmt(" is an alias for %s", ap->val);
7667 /* Then check if it is a tracked alias */
7668 cmdp = cmdlookup(command, 0);
7670 entry.cmdtype = cmdp->cmdtype;
7671 entry.u = cmdp->param;
7673 /* Finally use brute force */
7674 find_command(command, &entry, DO_ABS, path);
7677 switch (entry.cmdtype) {
7679 int j = entry.u.index;
7685 p = path_advance(&path, command);
7689 if (describe_command_verbose) {
7691 (cmdp ? " a tracked alias for" : nullstr), p
7700 if (describe_command_verbose) {
7701 out1str(" is a shell function");
7708 if (describe_command_verbose) {
7709 out1fmt(" is a %sshell builtin",
7710 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7711 "special " : nullstr
7719 if (describe_command_verbose) {
7720 out1str(": not found\n");
7725 outstr("\n", stdout);
7729 static int FAST_FUNC
7730 typecmd(int argc UNUSED_PARAM, char **argv)
7736 /* type -p ... ? (we don't bother checking for 'p') */
7737 if (argv[1] && argv[1][0] == '-') {
7742 err |= describe_command(argv[i++], verbose);
7747 #if ENABLE_ASH_CMDCMD
7748 static int FAST_FUNC
7749 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7757 while ((c = nextopt("pvV")) != '\0')
7759 verify |= VERIFY_VERBOSE;
7761 verify |= VERIFY_BRIEF;
7766 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7767 if (verify && (*argptr != NULL)) {
7768 return describe_command(*argptr, verify - VERIFY_BRIEF);
7776 /* ============ eval.c */
7778 static int funcblocksize; /* size of structures in function */
7779 static int funcstringsize; /* size of strings in node */
7780 static void *funcblock; /* block to allocate function from */
7781 static char *funcstring; /* block to allocate strings from */
7783 /* flags in argument to evaltree */
7784 #define EV_EXIT 01 /* exit after evaluating tree */
7785 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7786 #define EV_BACKCMD 04 /* command executing within back quotes */
7788 static const uint8_t nodesize[N_NUMBER] = {
7789 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7790 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7791 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7792 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7793 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7794 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7795 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7796 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7797 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7798 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7799 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7800 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7801 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7802 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7803 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7804 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7805 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7806 #if ENABLE_ASH_BASH_COMPAT
7807 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7809 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7810 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7811 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7812 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7813 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7814 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7815 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7816 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7817 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7820 static void calcsize(union node *n);
7823 sizenodelist(struct nodelist *lp)
7826 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7833 calcsize(union node *n)
7837 funcblocksize += nodesize[n->type];
7840 calcsize(n->ncmd.redirect);
7841 calcsize(n->ncmd.args);
7842 calcsize(n->ncmd.assign);
7845 sizenodelist(n->npipe.cmdlist);
7850 calcsize(n->nredir.redirect);
7851 calcsize(n->nredir.n);
7858 calcsize(n->nbinary.ch2);
7859 calcsize(n->nbinary.ch1);
7862 calcsize(n->nif.elsepart);
7863 calcsize(n->nif.ifpart);
7864 calcsize(n->nif.test);
7867 funcstringsize += strlen(n->nfor.var) + 1;
7868 calcsize(n->nfor.body);
7869 calcsize(n->nfor.args);
7872 calcsize(n->ncase.cases);
7873 calcsize(n->ncase.expr);
7876 calcsize(n->nclist.body);
7877 calcsize(n->nclist.pattern);
7878 calcsize(n->nclist.next);
7882 sizenodelist(n->narg.backquote);
7883 funcstringsize += strlen(n->narg.text) + 1;
7884 calcsize(n->narg.next);
7887 #if ENABLE_ASH_BASH_COMPAT
7894 calcsize(n->nfile.fname);
7895 calcsize(n->nfile.next);
7899 calcsize(n->ndup.vname);
7900 calcsize(n->ndup.next);
7904 calcsize(n->nhere.doc);
7905 calcsize(n->nhere.next);
7908 calcsize(n->nnot.com);
7914 nodeckstrdup(char *s)
7916 char *rtn = funcstring;
7918 strcpy(funcstring, s);
7919 funcstring += strlen(s) + 1;
7923 static union node *copynode(union node *);
7925 static struct nodelist *
7926 copynodelist(struct nodelist *lp)
7928 struct nodelist *start;
7929 struct nodelist **lpp;
7934 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7935 (*lpp)->n = copynode(lp->n);
7937 lpp = &(*lpp)->next;
7944 copynode(union node *n)
7951 funcblock = (char *) funcblock + nodesize[n->type];
7955 new->ncmd.redirect = copynode(n->ncmd.redirect);
7956 new->ncmd.args = copynode(n->ncmd.args);
7957 new->ncmd.assign = copynode(n->ncmd.assign);
7960 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7961 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
7966 new->nredir.redirect = copynode(n->nredir.redirect);
7967 new->nredir.n = copynode(n->nredir.n);
7974 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7975 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7978 new->nif.elsepart = copynode(n->nif.elsepart);
7979 new->nif.ifpart = copynode(n->nif.ifpart);
7980 new->nif.test = copynode(n->nif.test);
7983 new->nfor.var = nodeckstrdup(n->nfor.var);
7984 new->nfor.body = copynode(n->nfor.body);
7985 new->nfor.args = copynode(n->nfor.args);
7988 new->ncase.cases = copynode(n->ncase.cases);
7989 new->ncase.expr = copynode(n->ncase.expr);
7992 new->nclist.body = copynode(n->nclist.body);
7993 new->nclist.pattern = copynode(n->nclist.pattern);
7994 new->nclist.next = copynode(n->nclist.next);
7998 new->narg.backquote = copynodelist(n->narg.backquote);
7999 new->narg.text = nodeckstrdup(n->narg.text);
8000 new->narg.next = copynode(n->narg.next);
8003 #if ENABLE_ASH_BASH_COMPAT
8010 new->nfile.fname = copynode(n->nfile.fname);
8011 new->nfile.fd = n->nfile.fd;
8012 new->nfile.next = copynode(n->nfile.next);
8016 new->ndup.vname = copynode(n->ndup.vname);
8017 new->ndup.dupfd = n->ndup.dupfd;
8018 new->ndup.fd = n->ndup.fd;
8019 new->ndup.next = copynode(n->ndup.next);
8023 new->nhere.doc = copynode(n->nhere.doc);
8024 new->nhere.fd = n->nhere.fd;
8025 new->nhere.next = copynode(n->nhere.next);
8028 new->nnot.com = copynode(n->nnot.com);
8031 new->type = n->type;
8036 * Make a copy of a parse tree.
8038 static struct funcnode *
8039 copyfunc(union node *n)
8044 funcblocksize = offsetof(struct funcnode, n);
8047 blocksize = funcblocksize;
8048 f = ckmalloc(blocksize + funcstringsize);
8049 funcblock = (char *) f + offsetof(struct funcnode, n);
8050 funcstring = (char *) f + blocksize;
8057 * Define a shell function.
8060 defun(char *name, union node *func)
8062 struct cmdentry entry;
8065 entry.cmdtype = CMDFUNCTION;
8066 entry.u.func = copyfunc(func);
8067 addcmdentry(name, &entry);
8071 /* Reasons for skipping commands (see comment on breakcmd routine) */
8072 #define SKIPBREAK (1 << 0)
8073 #define SKIPCONT (1 << 1)
8074 #define SKIPFUNC (1 << 2)
8075 #define SKIPFILE (1 << 3)
8076 #define SKIPEVAL (1 << 4)
8077 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8078 static int skipcount; /* number of levels to skip */
8079 static int funcnest; /* depth of function calls */
8080 static int loopnest; /* current loop nesting level */
8082 /* Forward decl way out to parsing code - dotrap needs it */
8083 static int evalstring(char *s, int mask);
8085 /* Called to execute a trap.
8086 * Single callsite - at the end of evaltree().
8087 * If we return non-zero, exaltree raises EXEXIT exception.
8089 * Perhaps we should avoid entering new trap handlers
8090 * while we are executing a trap handler. [is it a TODO?]
8099 savestatus = exitstatus;
8103 TRACE(("dotrap entered\n"));
8104 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8111 /* non-trapped SIGINT is handled separately by raise_interrupt,
8112 * don't upset it by resetting gotsig[SIGINT-1] */
8113 if (sig == SIGINT && !t)
8116 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8120 want_exexit = evalstring(t, SKIPEVAL);
8121 exitstatus = savestatus;
8123 TRACE(("dotrap returns %d\n", want_exexit));
8128 TRACE(("dotrap returns 0\n"));
8132 /* forward declarations - evaluation is fairly recursive business... */
8133 static void evalloop(union node *, int);
8134 static void evalfor(union node *, int);
8135 static void evalcase(union node *, int);
8136 static void evalsubshell(union node *, int);
8137 static void expredir(union node *);
8138 static void evalpipe(union node *, int);
8139 static void evalcommand(union node *, int);
8140 static int evalbltin(const struct builtincmd *, int, char **);
8141 static void prehash(union node *);
8144 * Evaluate a parse tree. The value is left in the global variable
8148 evaltree(union node *n, int flags)
8150 struct jmploc *volatile savehandler = exception_handler;
8151 struct jmploc jmploc;
8153 void (*evalfn)(union node *, int);
8157 SAVE_INT(int_level);
8160 TRACE(("evaltree(NULL) called\n"));
8163 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8165 exception_handler = &jmploc;
8167 int err = setjmp(jmploc.loc);
8169 /* if it was a signal, check for trap handlers */
8170 if (exception_type == EXSIG) {
8171 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8172 exception_type, err));
8175 /* continue on the way out */
8176 TRACE(("exception %d in evaltree, propagating err=%d\n",
8177 exception_type, err));
8178 exception_handler = savehandler;
8179 longjmp(exception_handler->loc, err);
8186 out1fmt("Node type = %d\n", n->type);
8191 evaltree(n->nnot.com, EV_TESTED);
8192 status = !exitstatus;
8195 expredir(n->nredir.redirect);
8196 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8198 evaltree(n->nredir.n, flags & EV_TESTED);
8199 status = exitstatus;
8201 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8204 evalfn = evalcommand;
8206 if (eflag && !(flags & EV_TESTED))
8218 evalfn = evalsubshell;
8231 #error NAND + 1 != NOR
8233 #if NOR + 1 != NSEMI
8234 #error NOR + 1 != NSEMI
8236 unsigned is_or = n->type - NAND;
8239 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8241 if (!exitstatus == is_or)
8254 evaltree(n->nif.test, EV_TESTED);
8257 if (exitstatus == 0) {
8261 if (n->nif.elsepart) {
8262 n = n->nif.elsepart;
8267 defun(n->narg.text, n->narg.next);
8271 exitstatus = status;
8276 exception_handler = savehandler;
8278 if (checkexit & exitstatus)
8279 evalskip |= SKIPEVAL;
8280 else if (pending_sig && dotrap())
8283 if (flags & EV_EXIT) {
8285 raise_exception(EXEXIT);
8288 RESTORE_INT(int_level);
8289 TRACE(("leaving evaltree (no interrupts)\n"));
8292 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8295 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8298 evalloop(union node *n, int flags)
8308 evaltree(n->nbinary.ch1, EV_TESTED);
8311 if (evalskip == SKIPCONT && --skipcount <= 0) {
8315 if (evalskip == SKIPBREAK && --skipcount <= 0)
8320 if (n->type != NWHILE)
8324 evaltree(n->nbinary.ch2, flags);
8325 status = exitstatus;
8330 exitstatus = status;
8334 evalfor(union node *n, int flags)
8336 struct arglist arglist;
8339 struct stackmark smark;
8341 setstackmark(&smark);
8342 arglist.list = NULL;
8343 arglist.lastp = &arglist.list;
8344 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8345 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8350 *arglist.lastp = NULL;
8355 for (sp = arglist.list; sp; sp = sp->next) {
8356 setvar(n->nfor.var, sp->text, 0);
8357 evaltree(n->nfor.body, flags);
8359 if (evalskip == SKIPCONT && --skipcount <= 0) {
8363 if (evalskip == SKIPBREAK && --skipcount <= 0)
8370 popstackmark(&smark);
8374 evalcase(union node *n, int flags)
8378 struct arglist arglist;
8379 struct stackmark smark;
8381 setstackmark(&smark);
8382 arglist.list = NULL;
8383 arglist.lastp = &arglist.list;
8384 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8386 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8387 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8388 if (casematch(patp, arglist.list->text)) {
8389 if (evalskip == 0) {
8390 evaltree(cp->nclist.body, flags);
8397 popstackmark(&smark);
8401 * Kick off a subshell to evaluate a tree.
8404 evalsubshell(union node *n, int flags)
8407 int backgnd = (n->type == NBACKGND);
8410 expredir(n->nredir.redirect);
8411 if (!backgnd && flags & EV_EXIT && !trap[0])
8414 jp = makejob(/*n,*/ 1);
8415 if (forkshell(jp, n, backgnd) == 0) {
8419 flags &=~ EV_TESTED;
8421 redirect(n->nredir.redirect, 0);
8422 evaltreenr(n->nredir.n, flags);
8427 status = waitforjob(jp);
8428 exitstatus = status;
8433 * Compute the names of the files in a redirection list.
8435 static void fixredir(union node *, const char *, int);
8437 expredir(union node *n)
8441 for (redir = n; redir; redir = redir->nfile.next) {
8445 fn.lastp = &fn.list;
8446 switch (redir->type) {
8450 #if ENABLE_ASH_BASH_COMPAT
8455 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8456 #if ENABLE_ASH_BASH_COMPAT
8459 redir->nfile.expfname = fn.list->text;
8462 case NTOFD: /* >& */
8463 if (redir->ndup.vname) {
8464 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8465 if (fn.list == NULL)
8466 ash_msg_and_raise_error("redir error");
8467 #if ENABLE_ASH_BASH_COMPAT
8468 //FIXME: we used expandarg with different args!
8469 if (!isdigit_str9(fn.list->text)) {
8470 /* >&file, not >&fd */
8471 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8472 ash_msg_and_raise_error("redir error");
8474 goto store_expfname;
8477 fixredir(redir, fn.list->text, 1);
8485 * Evaluate a pipeline. All the processes in the pipeline are children
8486 * of the process creating the pipeline. (This differs from some versions
8487 * of the shell, which make the last process in a pipeline the parent
8491 evalpipe(union node *n, int flags)
8494 struct nodelist *lp;
8499 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8501 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8505 jp = makejob(/*n,*/ pipelen);
8507 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8511 if (pipe(pip) < 0) {
8513 ash_msg_and_raise_error("pipe call failed");
8516 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8529 evaltreenr(lp->n, flags);
8535 /* Don't want to trigger debugging */
8539 if (n->npipe.pipe_backgnd == 0) {
8540 exitstatus = waitforjob(jp);
8541 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8547 * Controls whether the shell is interactive or not.
8550 setinteractive(int on)
8552 static smallint is_interactive;
8554 if (++on == is_interactive)
8556 is_interactive = on;
8560 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8561 if (is_interactive > 1) {
8562 /* Looks like they want an interactive shell */
8563 static smallint did_banner;
8566 /* note: ash and hush share this string */
8567 out1fmt("\n\n%s %s\n"
8568 "Enter 'help' for a list of built-in commands."
8571 "built-in shell (ash)"
8585 setinteractive(iflag);
8587 #if ENABLE_FEATURE_EDITING_VI
8589 line_input_state->flags |= VI_MODE;
8591 line_input_state->flags &= ~VI_MODE;
8593 viflag = 0; /* forcibly keep the option off */
8597 static struct localvar *localvars;
8600 * Called after a function returns.
8601 * Interrupts must be off.
8606 struct localvar *lvp;
8609 while ((lvp = localvars) != NULL) {
8610 localvars = lvp->next;
8612 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8613 if (vp == NULL) { /* $- saved */
8614 memcpy(optlist, lvp->text, sizeof(optlist));
8615 free((char*)lvp->text);
8617 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8621 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8622 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8623 free((char*)vp->text);
8624 vp->flags = lvp->flags;
8625 vp->text = lvp->text;
8632 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8634 volatile struct shparam saveparam;
8635 struct localvar *volatile savelocalvars;
8636 struct jmploc *volatile savehandler;
8637 struct jmploc jmploc;
8640 saveparam = shellparam;
8641 savelocalvars = localvars;
8642 e = setjmp(jmploc.loc);
8647 savehandler = exception_handler;
8648 exception_handler = &jmploc;
8650 shellparam.malloced = 0;
8654 shellparam.nparam = argc - 1;
8655 shellparam.p = argv + 1;
8656 #if ENABLE_ASH_GETOPTS
8657 shellparam.optind = 1;
8658 shellparam.optoff = -1;
8660 evaltree(&func->n, flags & EV_TESTED);
8666 localvars = savelocalvars;
8667 freeparam(&shellparam);
8668 shellparam = saveparam;
8669 exception_handler = savehandler;
8671 evalskip &= ~SKIPFUNC;
8675 #if ENABLE_ASH_CMDCMD
8677 parse_command_args(char **argv, const char **path)
8690 if (c == '-' && !*cp) {
8697 *path = bb_default_path;
8700 /* run 'typecmd' for other options */
8711 * Make a variable a local variable. When a variable is made local, it's
8712 * value and flags are saved in a localvar structure. The saved values
8713 * will be restored when the shell function returns. We handle the name
8714 * "-" as a special case.
8719 struct localvar *lvp;
8724 lvp = ckzalloc(sizeof(struct localvar));
8725 if (LONE_DASH(name)) {
8727 p = ckmalloc(sizeof(optlist));
8728 lvp->text = memcpy(p, optlist, sizeof(optlist));
8733 vpp = hashvar(name);
8734 vp = *findvar(vpp, name);
8735 eq = strchr(name, '=');
8738 setvareq(name, VSTRFIXED);
8740 setvar(name, NULL, VSTRFIXED);
8741 vp = *vpp; /* the new variable */
8742 lvp->flags = VUNSET;
8744 lvp->text = vp->text;
8745 lvp->flags = vp->flags;
8746 vp->flags |= VSTRFIXED|VTEXTFIXED;
8752 lvp->next = localvars;
8758 * The "local" command.
8760 static int FAST_FUNC
8761 localcmd(int argc UNUSED_PARAM, char **argv)
8766 while ((name = *argv++) != NULL) {
8772 static int FAST_FUNC
8773 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8778 static int FAST_FUNC
8779 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8784 static int FAST_FUNC
8785 execcmd(int argc UNUSED_PARAM, char **argv)
8788 iflag = 0; /* exit on error */
8791 shellexec(argv + 1, pathval(), 0);
8797 * The return command.
8799 static int FAST_FUNC
8800 returncmd(int argc UNUSED_PARAM, char **argv)
8803 * If called outside a function, do what ksh does;
8804 * skip the rest of the file.
8806 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8807 return argv[1] ? number(argv[1]) : exitstatus;
8810 /* Forward declarations for builtintab[] */
8811 static int breakcmd(int, char **) FAST_FUNC;
8812 static int dotcmd(int, char **) FAST_FUNC;
8813 static int evalcmd(int, char **) FAST_FUNC;
8814 static int exitcmd(int, char **) FAST_FUNC;
8815 static int exportcmd(int, char **) FAST_FUNC;
8816 #if ENABLE_ASH_GETOPTS
8817 static int getoptscmd(int, char **) FAST_FUNC;
8819 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8820 static int helpcmd(int, char **) FAST_FUNC;
8822 #if ENABLE_SH_MATH_SUPPORT
8823 static int letcmd(int, char **) FAST_FUNC;
8825 static int readcmd(int, char **) FAST_FUNC;
8826 static int setcmd(int, char **) FAST_FUNC;
8827 static int shiftcmd(int, char **) FAST_FUNC;
8828 static int timescmd(int, char **) FAST_FUNC;
8829 static int trapcmd(int, char **) FAST_FUNC;
8830 static int umaskcmd(int, char **) FAST_FUNC;
8831 static int unsetcmd(int, char **) FAST_FUNC;
8832 static int ulimitcmd(int, char **) FAST_FUNC;
8834 #define BUILTIN_NOSPEC "0"
8835 #define BUILTIN_SPECIAL "1"
8836 #define BUILTIN_REGULAR "2"
8837 #define BUILTIN_SPEC_REG "3"
8838 #define BUILTIN_ASSIGN "4"
8839 #define BUILTIN_SPEC_ASSG "5"
8840 #define BUILTIN_REG_ASSG "6"
8841 #define BUILTIN_SPEC_REG_ASSG "7"
8843 /* Stubs for calling non-FAST_FUNC's */
8844 #if ENABLE_ASH_BUILTIN_ECHO
8845 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8847 #if ENABLE_ASH_BUILTIN_PRINTF
8848 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8850 #if ENABLE_ASH_BUILTIN_TEST
8851 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8854 /* Keep these in proper order since it is searched via bsearch() */
8855 static const struct builtincmd builtintab[] = {
8856 { BUILTIN_SPEC_REG ".", dotcmd },
8857 { BUILTIN_SPEC_REG ":", truecmd },
8858 #if ENABLE_ASH_BUILTIN_TEST
8859 { BUILTIN_REGULAR "[", testcmd },
8860 #if ENABLE_ASH_BASH_COMPAT
8861 { BUILTIN_REGULAR "[[", testcmd },
8864 #if ENABLE_ASH_ALIAS
8865 { BUILTIN_REG_ASSG "alias", aliascmd },
8868 { BUILTIN_REGULAR "bg", fg_bgcmd },
8870 { BUILTIN_SPEC_REG "break", breakcmd },
8871 { BUILTIN_REGULAR "cd", cdcmd },
8872 { BUILTIN_NOSPEC "chdir", cdcmd },
8873 #if ENABLE_ASH_CMDCMD
8874 { BUILTIN_REGULAR "command", commandcmd },
8876 { BUILTIN_SPEC_REG "continue", breakcmd },
8877 #if ENABLE_ASH_BUILTIN_ECHO
8878 { BUILTIN_REGULAR "echo", echocmd },
8880 { BUILTIN_SPEC_REG "eval", evalcmd },
8881 { BUILTIN_SPEC_REG "exec", execcmd },
8882 { BUILTIN_SPEC_REG "exit", exitcmd },
8883 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8884 { BUILTIN_REGULAR "false", falsecmd },
8886 { BUILTIN_REGULAR "fg", fg_bgcmd },
8888 #if ENABLE_ASH_GETOPTS
8889 { BUILTIN_REGULAR "getopts", getoptscmd },
8891 { BUILTIN_NOSPEC "hash", hashcmd },
8892 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8893 { BUILTIN_NOSPEC "help", helpcmd },
8896 { BUILTIN_REGULAR "jobs", jobscmd },
8897 { BUILTIN_REGULAR "kill", killcmd },
8899 #if ENABLE_SH_MATH_SUPPORT
8900 { BUILTIN_NOSPEC "let", letcmd },
8902 { BUILTIN_ASSIGN "local", localcmd },
8903 #if ENABLE_ASH_BUILTIN_PRINTF
8904 { BUILTIN_REGULAR "printf", printfcmd },
8906 { BUILTIN_NOSPEC "pwd", pwdcmd },
8907 { BUILTIN_REGULAR "read", readcmd },
8908 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8909 { BUILTIN_SPEC_REG "return", returncmd },
8910 { BUILTIN_SPEC_REG "set", setcmd },
8911 { BUILTIN_SPEC_REG "shift", shiftcmd },
8912 { BUILTIN_SPEC_REG "source", dotcmd },
8913 #if ENABLE_ASH_BUILTIN_TEST
8914 { BUILTIN_REGULAR "test", testcmd },
8916 { BUILTIN_SPEC_REG "times", timescmd },
8917 { BUILTIN_SPEC_REG "trap", trapcmd },
8918 { BUILTIN_REGULAR "true", truecmd },
8919 { BUILTIN_NOSPEC "type", typecmd },
8920 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8921 { BUILTIN_REGULAR "umask", umaskcmd },
8922 #if ENABLE_ASH_ALIAS
8923 { BUILTIN_REGULAR "unalias", unaliascmd },
8925 { BUILTIN_SPEC_REG "unset", unsetcmd },
8926 { BUILTIN_REGULAR "wait", waitcmd },
8929 /* Should match the above table! */
8930 #define COMMANDCMD (builtintab + \
8932 1 * ENABLE_ASH_BUILTIN_TEST + \
8933 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8934 1 * ENABLE_ASH_ALIAS + \
8935 1 * ENABLE_ASH_JOB_CONTROL + \
8937 #define EXECCMD (builtintab + \
8939 1 * ENABLE_ASH_BUILTIN_TEST + \
8940 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8941 1 * ENABLE_ASH_ALIAS + \
8942 1 * ENABLE_ASH_JOB_CONTROL + \
8944 1 * ENABLE_ASH_CMDCMD + \
8946 ENABLE_ASH_BUILTIN_ECHO + \
8950 * Search the table of builtin commands.
8952 static struct builtincmd *
8953 find_builtin(const char *name)
8955 struct builtincmd *bp;
8958 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8965 * Execute a simple command.
8968 isassignment(const char *p)
8970 const char *q = endofname(p);
8975 static int FAST_FUNC
8976 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8978 /* Preserve exitstatus of a previous possible redirection
8979 * as POSIX mandates */
8980 return back_exitstatus;
8983 evalcommand(union node *cmd, int flags)
8985 static const struct builtincmd null_bltin = {
8986 "\0\0", bltincmd /* why three NULs? */
8988 struct stackmark smark;
8990 struct arglist arglist;
8991 struct arglist varlist;
8994 const struct strlist *sp;
8995 struct cmdentry cmdentry;
9002 struct builtincmd *bcmd;
9003 smallint cmd_is_exec;
9004 smallint pseudovarflag = 0;
9006 /* First expand the arguments. */
9007 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9008 setstackmark(&smark);
9009 back_exitstatus = 0;
9011 cmdentry.cmdtype = CMDBUILTIN;
9012 cmdentry.u.cmd = &null_bltin;
9013 varlist.lastp = &varlist.list;
9014 *varlist.lastp = NULL;
9015 arglist.lastp = &arglist.list;
9016 *arglist.lastp = NULL;
9019 if (cmd->ncmd.args) {
9020 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9021 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9024 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9025 struct strlist **spp;
9027 spp = arglist.lastp;
9028 if (pseudovarflag && isassignment(argp->narg.text))
9029 expandarg(argp, &arglist, EXP_VARTILDE);
9031 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9033 for (sp = *spp; sp; sp = sp->next)
9037 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9038 for (sp = arglist.list; sp; sp = sp->next) {
9039 TRACE(("evalcommand arg: %s\n", sp->text));
9040 *nargv++ = sp->text;
9045 if (iflag && funcnest == 0 && argc > 0)
9046 lastarg = nargv[-1];
9049 expredir(cmd->ncmd.redirect);
9050 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9053 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9054 struct strlist **spp;
9057 spp = varlist.lastp;
9058 expandarg(argp, &varlist, EXP_VARTILDE);
9061 * Modify the command lookup path, if a PATH= assignment
9065 if (varequal(p, path))
9069 /* Print the command if xflag is set. */
9072 const char *p = " %s";
9075 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9078 for (n = 0; n < 2; n++) {
9080 fdprintf(preverrout_fd, p, sp->text);
9088 safe_write(preverrout_fd, "\n", 1);
9094 /* Now locate the command. */
9096 const char *oldpath;
9097 int cmd_flag = DO_ERR;
9102 find_command(argv[0], &cmdentry, cmd_flag, path);
9103 if (cmdentry.cmdtype == CMDUNKNOWN) {
9109 /* implement bltin and command here */
9110 if (cmdentry.cmdtype != CMDBUILTIN)
9113 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9114 if (cmdentry.u.cmd == EXECCMD)
9116 #if ENABLE_ASH_CMDCMD
9117 if (cmdentry.u.cmd == COMMANDCMD) {
9119 nargv = parse_command_args(argv, &path);
9122 argc -= nargv - argv;
9124 cmd_flag |= DO_NOFUNC;
9132 /* We have a redirection error. */
9134 raise_exception(EXERROR);
9136 exitstatus = status;
9140 /* Execute the command. */
9141 switch (cmdentry.cmdtype) {
9144 #if ENABLE_FEATURE_SH_NOFORK
9145 /* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9146 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
9148 /* find_command() encodes applet_no as (-2 - applet_no) */
9149 int applet_no = (- cmdentry.u.index - 2);
9150 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9151 listsetvar(varlist.list, VEXPORT|VSTACK);
9152 /* run <applet>_main() */
9153 exitstatus = run_nofork_applet(applet_no, argv);
9158 /* Fork off a child process if necessary. */
9159 if (!(flags & EV_EXIT) || trap[0]) {
9161 jp = makejob(/*cmd,*/ 1);
9162 if (forkshell(jp, cmd, FORK_FG) != 0) {
9163 exitstatus = waitforjob(jp);
9165 TRACE(("forked child exited with %d\n", exitstatus));
9170 listsetvar(varlist.list, VEXPORT|VSTACK);
9171 shellexec(argv, path, cmdentry.u.index);
9175 cmdenviron = varlist.list;
9177 struct strlist *list = cmdenviron;
9179 if (spclbltin > 0 || argc == 0) {
9181 if (cmd_is_exec && argc > 1)
9184 listsetvar(list, i);
9186 /* Tight loop with builtins only:
9187 * "while kill -0 $child; do true; done"
9188 * will never exit even if $child died, unless we do this
9189 * to reap the zombie and make kill detect that it's gone: */
9190 dowait(DOWAIT_NONBLOCK, NULL);
9192 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9194 int i = exception_type;
9199 exit_status = 128 + SIGINT;
9201 exit_status = 128 + pending_sig;
9202 exitstatus = exit_status;
9203 if (i == EXINT || spclbltin > 0) {
9205 longjmp(exception_handler->loc, 1);
9212 listsetvar(varlist.list, 0);
9213 /* See above for the rationale */
9214 dowait(DOWAIT_NONBLOCK, NULL);
9215 if (evalfun(cmdentry.u.func, argc, argv, flags))
9221 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9223 /* dsl: I think this is intended to be used to support
9224 * '_' in 'vi' command mode during line editing...
9225 * However I implemented that within libedit itself.
9227 setvar("_", lastarg, 0);
9229 popstackmark(&smark);
9233 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9235 char *volatile savecmdname;
9236 struct jmploc *volatile savehandler;
9237 struct jmploc jmploc;
9240 savecmdname = commandname;
9241 i = setjmp(jmploc.loc);
9244 savehandler = exception_handler;
9245 exception_handler = &jmploc;
9246 commandname = argv[0];
9248 optptr = NULL; /* initialize nextopt */
9249 exitstatus = (*cmd->builtin)(argc, argv);
9250 flush_stdout_stderr();
9252 exitstatus |= ferror(stdout);
9254 commandname = savecmdname;
9255 exception_handler = savehandler;
9261 goodname(const char *p)
9263 return !*endofname(p);
9268 * Search for a command. This is called before we fork so that the
9269 * location of the command will be available in the parent as well as
9270 * the child. The check for "goodname" is an overly conservative
9271 * check that the name will not be subject to expansion.
9274 prehash(union node *n)
9276 struct cmdentry entry;
9278 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9279 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9283 /* ============ Builtin commands
9285 * Builtin commands whose functions are closely tied to evaluation
9286 * are implemented here.
9290 * Handle break and continue commands. Break, continue, and return are
9291 * all handled by setting the evalskip flag. The evaluation routines
9292 * above all check this flag, and if it is set they start skipping
9293 * commands rather than executing them. The variable skipcount is
9294 * the number of loops to break/continue, or the number of function
9295 * levels to return. (The latter is always 1.) It should probably
9296 * be an error to break out of more loops than exist, but it isn't
9297 * in the standard shell so we don't make it one here.
9299 static int FAST_FUNC
9300 breakcmd(int argc UNUSED_PARAM, char **argv)
9302 int n = argv[1] ? number(argv[1]) : 1;
9305 ash_msg_and_raise_error(msg_illnum, argv[1]);
9309 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9316 /* ============ input.c
9318 * This implements the input routines used by the parser.
9322 INPUT_PUSH_FILE = 1,
9323 INPUT_NOFILE_OK = 2,
9326 static smallint checkkwd;
9327 /* values of checkkwd variable */
9328 #define CHKALIAS 0x1
9333 * Push a string back onto the input at this current parsefile level.
9334 * We handle aliases this way.
9336 #if !ENABLE_ASH_ALIAS
9337 #define pushstring(s, ap) pushstring(s)
9340 pushstring(char *s, struct alias *ap)
9347 if (g_parsefile->strpush) {
9348 sp = ckzalloc(sizeof(*sp));
9349 sp->prev = g_parsefile->strpush;
9351 sp = &(g_parsefile->basestrpush);
9353 g_parsefile->strpush = sp;
9354 sp->prev_string = g_parsefile->next_to_pgetc;
9355 sp->prev_left_in_line = g_parsefile->left_in_line;
9356 #if ENABLE_ASH_ALIAS
9359 ap->flag |= ALIASINUSE;
9363 g_parsefile->next_to_pgetc = s;
9364 g_parsefile->left_in_line = len;
9371 struct strpush *sp = g_parsefile->strpush;
9374 #if ENABLE_ASH_ALIAS
9376 if (g_parsefile->next_to_pgetc[-1] == ' '
9377 || g_parsefile->next_to_pgetc[-1] == '\t'
9379 checkkwd |= CHKALIAS;
9381 if (sp->string != sp->ap->val) {
9384 sp->ap->flag &= ~ALIASINUSE;
9385 if (sp->ap->flag & ALIASDEAD) {
9386 unalias(sp->ap->name);
9390 g_parsefile->next_to_pgetc = sp->prev_string;
9391 g_parsefile->left_in_line = sp->prev_left_in_line;
9392 g_parsefile->strpush = sp->prev;
9393 if (sp != &(g_parsefile->basestrpush))
9398 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9399 //it peeks whether it is &>, and then pushes back both chars.
9400 //This function needs to save last *next_to_pgetc to buf[0]
9401 //to make two pungetc() reliable. Currently,
9402 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9407 char *buf = g_parsefile->buf;
9409 g_parsefile->next_to_pgetc = buf;
9410 #if ENABLE_FEATURE_EDITING
9412 if (!iflag || g_parsefile->fd != STDIN_FILENO)
9413 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9415 #if ENABLE_FEATURE_TAB_COMPLETION
9416 line_input_state->path_lookup = pathval();
9418 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9420 /* Ctrl+C pressed */
9429 if (nr < 0 && errno == 0) {
9430 /* Ctrl+D pressed */
9435 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9439 /* nonblock_safe_read() handles this problem */
9441 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9442 int flags = fcntl(0, F_GETFL);
9443 if (flags >= 0 && (flags & O_NONBLOCK)) {
9444 flags &= ~O_NONBLOCK;
9445 if (fcntl(0, F_SETFL, flags) >= 0) {
9446 out2str("sh: turning off NDELAY mode\n");
9457 * Refill the input buffer and return the next input character:
9459 * 1) If a string was pushed back on the input, pop it;
9460 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9461 * or we are reading from a string so we can't refill the buffer,
9463 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9464 * 4) Process input up to the next newline, deleting nul characters.
9466 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9467 #define pgetc_debug(...) ((void)0)
9469 * NB: due to SIT(c) internals (syntax_index_table[] vector),
9470 * pgetc() and related functions must return chars SIGN-EXTENDED into ints,
9471 * not zero-extended. Seems fragile to me. Affects only !USE_SIT_FUNCTION case,
9472 * so we can fix it by ditching !USE_SIT_FUNCTION if Unicode requires that.
9480 while (g_parsefile->strpush) {
9481 #if ENABLE_ASH_ALIAS
9482 if (g_parsefile->left_in_line == -1
9483 && g_parsefile->strpush->ap
9484 && g_parsefile->next_to_pgetc[-1] != ' '
9485 && g_parsefile->next_to_pgetc[-1] != '\t'
9487 pgetc_debug("preadbuffer PEOA");
9492 /* try "pgetc" now: */
9493 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9494 g_parsefile->left_in_line,
9495 g_parsefile->next_to_pgetc,
9496 g_parsefile->next_to_pgetc);
9497 if (--g_parsefile->left_in_line >= 0)
9498 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9500 /* on both branches above g_parsefile->left_in_line < 0.
9501 * "pgetc" needs refilling.
9504 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9505 * pungetc() may increment it a few times.
9506 * Assuming it won't increment it to less than -90.
9508 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9509 pgetc_debug("preadbuffer PEOF1");
9510 /* even in failure keep left_in_line and next_to_pgetc
9511 * in lock step, for correct multi-layer pungetc.
9512 * left_in_line was decremented before preadbuffer(),
9513 * must inc next_to_pgetc: */
9514 g_parsefile->next_to_pgetc++;
9518 more = g_parsefile->left_in_buffer;
9520 flush_stdout_stderr();
9524 /* don't try reading again */
9525 g_parsefile->left_in_line = -99;
9526 pgetc_debug("preadbuffer PEOF2");
9527 g_parsefile->next_to_pgetc++;
9532 /* Find out where's the end of line.
9533 * Set g_parsefile->left_in_line
9534 * and g_parsefile->left_in_buffer acordingly.
9535 * NUL chars are deleted.
9537 q = g_parsefile->next_to_pgetc;
9545 memmove(q, q + 1, more);
9549 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9555 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9556 if (g_parsefile->left_in_line < 0)
9561 g_parsefile->left_in_buffer = more;
9566 out2str(g_parsefile->next_to_pgetc);
9570 pgetc_debug("preadbuffer at %d:%p'%s'",
9571 g_parsefile->left_in_line,
9572 g_parsefile->next_to_pgetc,
9573 g_parsefile->next_to_pgetc);
9574 return signed_char2int(*g_parsefile->next_to_pgetc++);
9577 #define pgetc_as_macro() \
9578 (--g_parsefile->left_in_line >= 0 \
9579 ? signed_char2int(*g_parsefile->next_to_pgetc++) \
9586 pgetc_debug("pgetc_fast at %d:%p'%s'",
9587 g_parsefile->left_in_line,
9588 g_parsefile->next_to_pgetc,
9589 g_parsefile->next_to_pgetc);
9590 return pgetc_as_macro();
9593 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9594 #define pgetc_fast() pgetc()
9596 #define pgetc_fast() pgetc_as_macro()
9600 * Same as pgetc(), but ignores PEOA.
9602 #if ENABLE_ASH_ALIAS
9608 pgetc_debug("pgetc_fast at %d:%p'%s'",
9609 g_parsefile->left_in_line,
9610 g_parsefile->next_to_pgetc,
9611 g_parsefile->next_to_pgetc);
9613 } while (c == PEOA);
9617 #define pgetc2() pgetc()
9621 * Read a line from the script.
9624 pfgets(char *line, int len)
9630 while (--nleft > 0) {
9646 * Undo the last call to pgetc. Only one character may be pushed back.
9647 * PEOF may be pushed back.
9652 g_parsefile->left_in_line++;
9653 g_parsefile->next_to_pgetc--;
9654 pgetc_debug("pushed back to %d:%p'%s'",
9655 g_parsefile->left_in_line,
9656 g_parsefile->next_to_pgetc,
9657 g_parsefile->next_to_pgetc);
9661 * To handle the "." command, a stack of input files is used. Pushfile
9662 * adds a new entry to the stack and popfile restores the previous level.
9667 struct parsefile *pf;
9669 pf = ckzalloc(sizeof(*pf));
9670 pf->prev = g_parsefile;
9672 /*pf->strpush = NULL; - ckzalloc did it */
9673 /*pf->basestrpush.prev = NULL;*/
9680 struct parsefile *pf = g_parsefile;
9688 g_parsefile = pf->prev;
9694 * Return to top level.
9699 while (g_parsefile != &basepf)
9704 * Close the file(s) that the shell is reading commands from. Called
9705 * after a fork is done.
9711 if (g_parsefile->fd > 0) {
9712 close(g_parsefile->fd);
9713 g_parsefile->fd = 0;
9718 * Like setinputfile, but takes an open file descriptor. Call this with
9722 setinputfd(int fd, int push)
9724 close_on_exec_on(fd);
9727 g_parsefile->buf = NULL;
9729 g_parsefile->fd = fd;
9730 if (g_parsefile->buf == NULL)
9731 g_parsefile->buf = ckmalloc(IBUFSIZ);
9732 g_parsefile->left_in_buffer = 0;
9733 g_parsefile->left_in_line = 0;
9734 g_parsefile->linno = 1;
9738 * Set the input to take input from a file. If push is set, push the
9739 * old input onto the stack first.
9742 setinputfile(const char *fname, int flags)
9748 fd = open(fname, O_RDONLY);
9750 if (flags & INPUT_NOFILE_OK)
9752 ash_msg_and_raise_error("can't open '%s'", fname);
9755 fd2 = copyfd(fd, 10);
9758 ash_msg_and_raise_error("out of file descriptors");
9761 setinputfd(fd, flags & INPUT_PUSH_FILE);
9768 * Like setinputfile, but takes input from a string.
9771 setinputstring(char *string)
9775 g_parsefile->next_to_pgetc = string;
9776 g_parsefile->left_in_line = strlen(string);
9777 g_parsefile->buf = NULL;
9778 g_parsefile->linno = 1;
9783 /* ============ mail.c
9785 * Routines to check for mail.
9790 #define MAXMBOXES 10
9792 /* times of mailboxes */
9793 static time_t mailtime[MAXMBOXES];
9794 /* Set if MAIL or MAILPATH is changed. */
9795 static smallint mail_var_path_changed;
9798 * Print appropriate message(s) if mail has arrived.
9799 * If mail_var_path_changed is set,
9800 * then the value of MAIL has mail_var_path_changed,
9801 * so we just update the values.
9810 struct stackmark smark;
9813 setstackmark(&smark);
9814 mpath = mpathset() ? mpathval() : mailval();
9815 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9816 p = path_advance(&mpath, nullstr);
9821 for (q = p; *q; q++)
9827 q[-1] = '\0'; /* delete trailing '/' */
9828 if (stat(p, &statb) < 0) {
9832 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9835 pathopt ? pathopt : "you have mail"
9838 *mtp = statb.st_mtime;
9840 mail_var_path_changed = 0;
9841 popstackmark(&smark);
9844 static void FAST_FUNC
9845 changemail(const char *val UNUSED_PARAM)
9847 mail_var_path_changed = 1;
9850 #endif /* ASH_MAIL */
9853 /* ============ ??? */
9856 * Set the shell parameters.
9859 setparam(char **argv)
9865 for (nparam = 0; argv[nparam]; nparam++)
9867 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9869 *ap++ = ckstrdup(*argv++);
9872 freeparam(&shellparam);
9873 shellparam.malloced = 1;
9874 shellparam.nparam = nparam;
9875 shellparam.p = newparam;
9876 #if ENABLE_ASH_GETOPTS
9877 shellparam.optind = 1;
9878 shellparam.optoff = -1;
9883 * Process shell options. The global variable argptr contains a pointer
9884 * to the argument list; we advance it past the options.
9886 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9887 * For a non-interactive shell, an error condition encountered
9888 * by a special built-in ... shall cause the shell to write a diagnostic message
9889 * to standard error and exit as shown in the following table:
9890 * Error Special Built-In
9892 * Utility syntax error (option or operand error) Shall exit
9894 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9895 * we see that bash does not do that (set "finishes" with error code 1 instead,
9896 * and shell continues), and people rely on this behavior!
9898 * set -o barfoo 2>/dev/null
9901 * Oh well. Let's mimic that.
9904 plus_minus_o(char *name, int val)
9909 for (i = 0; i < NOPTS; i++) {
9910 if (strcmp(name, optnames(i)) == 0) {
9915 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9918 for (i = 0; i < NOPTS; i++) {
9920 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9922 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9928 setoption(int flag, int val)
9932 for (i = 0; i < NOPTS; i++) {
9933 if (optletters(i) == flag) {
9938 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9942 options(int cmdline)
9950 while ((p = *argptr) != NULL) {
9952 if (c != '-' && c != '+')
9955 val = 0; /* val = 0 if c == '+' */
9958 if (p[0] == '\0' || LONE_DASH(p)) {
9960 /* "-" means turn off -x and -v */
9963 /* "--" means reset params */
9964 else if (*argptr == NULL)
9967 break; /* "-" or "--" terminates options */
9970 /* first char was + or - */
9971 while ((c = *p++) != '\0') {
9972 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9973 if (c == 'c' && cmdline) {
9974 minusc = p; /* command is after shell args */
9975 } else if (c == 'o') {
9976 if (plus_minus_o(*argptr, val)) {
9977 /* it already printed err message */
9978 return 1; /* error */
9982 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9984 /* bash does not accept +-login, we also won't */
9985 } else if (cmdline && val && (c == '-')) { /* long options */
9986 if (strcmp(p, "login") == 0)
9998 * The shift builtin command.
10000 static int FAST_FUNC
10001 shiftcmd(int argc UNUSED_PARAM, char **argv)
10008 n = number(argv[1]);
10009 if (n > shellparam.nparam)
10010 n = 0; /* bash compat, was = shellparam.nparam; */
10012 shellparam.nparam -= n;
10013 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10014 if (shellparam.malloced)
10017 ap2 = shellparam.p;
10018 while ((*ap2++ = *ap1++) != NULL)
10020 #if ENABLE_ASH_GETOPTS
10021 shellparam.optind = 1;
10022 shellparam.optoff = -1;
10029 * POSIX requires that 'set' (but not export or readonly) output the
10030 * variables in lexicographic order - by the locale's collating order (sigh).
10031 * Maybe we could keep them in an ordered balanced binary tree
10032 * instead of hashed lists.
10033 * For now just roll 'em through qsort for printing...
10036 showvars(const char *sep_prefix, int on, int off)
10039 char **ep, **epend;
10041 ep = listvars(on, off, &epend);
10042 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10044 sep = *sep_prefix ? " " : sep_prefix;
10046 for (; ep < epend; ep++) {
10050 p = strchrnul(*ep, '=');
10053 q = single_quote(++p);
10054 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10060 * The set command builtin.
10062 static int FAST_FUNC
10063 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10068 return showvars(nullstr, 0, VUNSET);
10071 if (!options(0)) { /* if no parse error... */
10074 if (*argptr != NULL) {
10082 #if ENABLE_ASH_RANDOM_SUPPORT
10083 static void FAST_FUNC
10084 change_random(const char *value)
10088 if (value == NULL) {
10089 /* "get", generate */
10090 t = next_random(&random_gen);
10091 /* set without recursion */
10092 setvar(vrandom.text, utoa(t), VNOFUNC);
10093 vrandom.flags &= ~VNOFUNC;
10096 t = strtoul(value, NULL, 10);
10097 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10102 #if ENABLE_ASH_GETOPTS
10104 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10113 if (*param_optind < 1)
10115 optnext = optfirst + *param_optind - 1;
10117 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10120 p = optnext[-1] + *optoff;
10121 if (p == NULL || *p == '\0') {
10122 /* Current word is done, advance */
10124 if (p == NULL || *p != '-' || *++p == '\0') {
10131 if (LONE_DASH(p)) /* check for "--" */
10136 for (q = optstr; *q != c;) {
10138 if (optstr[0] == ':') {
10141 err |= setvarsafe("OPTARG", s, 0);
10143 fprintf(stderr, "Illegal option -%c\n", c);
10144 unsetvar("OPTARG");
10154 if (*p == '\0' && (p = *optnext) == NULL) {
10155 if (optstr[0] == ':') {
10158 err |= setvarsafe("OPTARG", s, 0);
10161 fprintf(stderr, "No arg for -%c option\n", c);
10162 unsetvar("OPTARG");
10170 err |= setvarsafe("OPTARG", p, 0);
10173 err |= setvarsafe("OPTARG", nullstr, 0);
10175 *optoff = p ? p - *(optnext - 1) : -1;
10176 *param_optind = optnext - optfirst + 1;
10177 fmtstr(s, sizeof(s), "%d", *param_optind);
10178 err |= setvarsafe("OPTIND", s, VNOFUNC);
10181 err |= setvarsafe(optvar, s, 0);
10185 flush_stdout_stderr();
10186 raise_exception(EXERROR);
10192 * The getopts builtin. Shellparam.optnext points to the next argument
10193 * to be processed. Shellparam.optptr points to the next character to
10194 * be processed in the current argument. If shellparam.optnext is NULL,
10195 * then it's the first time getopts has been called.
10197 static int FAST_FUNC
10198 getoptscmd(int argc, char **argv)
10203 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10205 optbase = shellparam.p;
10206 if (shellparam.optind > shellparam.nparam + 1) {
10207 shellparam.optind = 1;
10208 shellparam.optoff = -1;
10211 optbase = &argv[3];
10212 if (shellparam.optind > argc - 2) {
10213 shellparam.optind = 1;
10214 shellparam.optoff = -1;
10218 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10219 &shellparam.optoff);
10221 #endif /* ASH_GETOPTS */
10224 /* ============ Shell parser */
10227 struct heredoc *next; /* next here document in list */
10228 union node *here; /* redirection node */
10229 char *eofmark; /* string indicating end of input */
10230 smallint striptabs; /* if set, strip leading tabs */
10233 static smallint tokpushback; /* last token pushed back */
10234 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10235 static smallint quoteflag; /* set if (part of) last token was quoted */
10236 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10237 static struct heredoc *heredoclist; /* list of here documents to read */
10238 static char *wordtext; /* text of last word returned by readtoken */
10239 static struct nodelist *backquotelist;
10240 static union node *redirnode;
10241 static struct heredoc *heredoc;
10244 * Called when an unexpected token is read during the parse. The argument
10245 * is the token that is expected, or -1 if more than one type of token can
10246 * occur at this point.
10248 static void raise_error_unexpected_syntax(int) NORETURN;
10250 raise_error_unexpected_syntax(int token)
10255 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
10257 sprintf(msg + l, " (expecting %s)", tokname(token));
10258 raise_error_syntax(msg);
10262 #define EOFMARKLEN 79
10264 /* parsing is heavily cross-recursive, need these forward decls */
10265 static union node *andor(void);
10266 static union node *pipeline(void);
10267 static union node *parse_command(void);
10268 static void parseheredoc(void);
10269 static char peektoken(void);
10270 static int readtoken(void);
10272 static union node *
10275 union node *n1, *n2, *n3;
10278 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10279 if (nlflag == 2 && peektoken())
10285 if (tok == TBACKGND) {
10286 if (n2->type == NPIPE) {
10287 n2->npipe.pipe_backgnd = 1;
10289 if (n2->type != NREDIR) {
10290 n3 = stzalloc(sizeof(struct nredir));
10292 /*n3->nredir.redirect = NULL; - stzalloc did it */
10295 n2->type = NBACKGND;
10301 n3 = stzalloc(sizeof(struct nbinary));
10303 n3->nbinary.ch1 = n1;
10304 n3->nbinary.ch2 = n2;
10320 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10328 pungetc(); /* push back EOF on input */
10332 raise_error_unexpected_syntax(-1);
10339 static union node *
10342 union node *n1, *n2, *n3;
10350 } else if (t == TOR) {
10356 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10358 n3 = stzalloc(sizeof(struct nbinary));
10360 n3->nbinary.ch1 = n1;
10361 n3->nbinary.ch2 = n2;
10366 static union node *
10369 union node *n1, *n2, *pipenode;
10370 struct nodelist *lp, *prev;
10374 TRACE(("pipeline: entered\n"));
10375 if (readtoken() == TNOT) {
10377 checkkwd = CHKKWD | CHKALIAS;
10380 n1 = parse_command();
10381 if (readtoken() == TPIPE) {
10382 pipenode = stzalloc(sizeof(struct npipe));
10383 pipenode->type = NPIPE;
10384 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10385 lp = stzalloc(sizeof(struct nodelist));
10386 pipenode->npipe.cmdlist = lp;
10390 lp = stzalloc(sizeof(struct nodelist));
10391 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10392 lp->n = parse_command();
10394 } while (readtoken() == TPIPE);
10400 n2 = stzalloc(sizeof(struct nnot));
10408 static union node *
10413 n = stzalloc(sizeof(struct narg));
10415 /*n->narg.next = NULL; - stzalloc did it */
10416 n->narg.text = wordtext;
10417 n->narg.backquote = backquotelist;
10422 fixredir(union node *n, const char *text, int err)
10426 TRACE(("Fix redir %s %d\n", text, err));
10428 n->ndup.vname = NULL;
10430 fd = bb_strtou(text, NULL, 10);
10431 if (!errno && fd >= 0)
10432 n->ndup.dupfd = fd;
10433 else if (LONE_DASH(text))
10434 n->ndup.dupfd = -1;
10437 raise_error_syntax("bad fd number");
10438 n->ndup.vname = makename();
10443 * Returns true if the text contains nothing to expand (no dollar signs
10447 noexpand(const char *text)
10453 while ((c = *p++) != '\0') {
10454 if (c == CTLQUOTEMARK)
10458 else if (SIT((signed char)c, BASESYNTAX) == CCTL)
10467 union node *n = redirnode;
10469 if (readtoken() != TWORD)
10470 raise_error_unexpected_syntax(-1);
10471 if (n->type == NHERE) {
10472 struct heredoc *here = heredoc;
10476 if (quoteflag == 0)
10478 TRACE(("Here document %d\n", n->type));
10479 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10480 raise_error_syntax("illegal eof marker for << redirection");
10481 rmescapes(wordtext, 0);
10482 here->eofmark = wordtext;
10484 if (heredoclist == NULL)
10485 heredoclist = here;
10487 for (p = heredoclist; p->next; p = p->next)
10491 } else if (n->type == NTOFD || n->type == NFROMFD) {
10492 fixredir(n, wordtext, 0);
10494 n->nfile.fname = makename();
10498 static union node *
10501 union node *args, **app;
10502 union node *n = NULL;
10503 union node *vars, **vpp;
10504 union node **rpp, *redir;
10506 #if ENABLE_ASH_BASH_COMPAT
10507 smallint double_brackets_flag = 0;
10517 savecheckkwd = CHKALIAS;
10520 checkkwd = savecheckkwd;
10523 #if ENABLE_ASH_BASH_COMPAT
10524 case TAND: /* "&&" */
10525 case TOR: /* "||" */
10526 if (!double_brackets_flag) {
10530 wordtext = (char *) (t == TAND ? "-a" : "-o");
10533 n = stzalloc(sizeof(struct narg));
10535 /*n->narg.next = NULL; - stzalloc did it */
10536 n->narg.text = wordtext;
10537 #if ENABLE_ASH_BASH_COMPAT
10538 if (strcmp("[[", wordtext) == 0)
10539 double_brackets_flag = 1;
10540 else if (strcmp("]]", wordtext) == 0)
10541 double_brackets_flag = 0;
10543 n->narg.backquote = backquotelist;
10544 if (savecheckkwd && isassignment(wordtext)) {
10546 vpp = &n->narg.next;
10549 app = &n->narg.next;
10554 *rpp = n = redirnode;
10555 rpp = &n->nfile.next;
10556 parsefname(); /* read name of redirection file */
10559 if (args && app == &args->narg.next
10562 struct builtincmd *bcmd;
10565 /* We have a function */
10566 if (readtoken() != TRP)
10567 raise_error_unexpected_syntax(TRP);
10568 name = n->narg.text;
10569 if (!goodname(name)
10570 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10572 raise_error_syntax("bad function name");
10575 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10576 n->narg.next = parse_command();
10589 n = stzalloc(sizeof(struct ncmd));
10591 n->ncmd.args = args;
10592 n->ncmd.assign = vars;
10593 n->ncmd.redirect = redir;
10597 static union node *
10598 parse_command(void)
10600 union node *n1, *n2;
10601 union node *ap, **app;
10602 union node *cp, **cpp;
10603 union node *redir, **rpp;
10610 switch (readtoken()) {
10612 raise_error_unexpected_syntax(-1);
10615 n1 = stzalloc(sizeof(struct nif));
10617 n1->nif.test = list(0);
10618 if (readtoken() != TTHEN)
10619 raise_error_unexpected_syntax(TTHEN);
10620 n1->nif.ifpart = list(0);
10622 while (readtoken() == TELIF) {
10623 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10624 n2 = n2->nif.elsepart;
10626 n2->nif.test = list(0);
10627 if (readtoken() != TTHEN)
10628 raise_error_unexpected_syntax(TTHEN);
10629 n2->nif.ifpart = list(0);
10631 if (lasttoken == TELSE)
10632 n2->nif.elsepart = list(0);
10634 n2->nif.elsepart = NULL;
10642 n1 = stzalloc(sizeof(struct nbinary));
10643 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10644 n1->nbinary.ch1 = list(0);
10647 TRACE(("expecting DO got %s %s\n", tokname(got),
10648 got == TWORD ? wordtext : ""));
10649 raise_error_unexpected_syntax(TDO);
10651 n1->nbinary.ch2 = list(0);
10656 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10657 raise_error_syntax("bad for loop variable");
10658 n1 = stzalloc(sizeof(struct nfor));
10660 n1->nfor.var = wordtext;
10661 checkkwd = CHKKWD | CHKALIAS;
10662 if (readtoken() == TIN) {
10664 while (readtoken() == TWORD) {
10665 n2 = stzalloc(sizeof(struct narg));
10667 /*n2->narg.next = NULL; - stzalloc did it */
10668 n2->narg.text = wordtext;
10669 n2->narg.backquote = backquotelist;
10671 app = &n2->narg.next;
10674 n1->nfor.args = ap;
10675 if (lasttoken != TNL && lasttoken != TSEMI)
10676 raise_error_unexpected_syntax(-1);
10678 n2 = stzalloc(sizeof(struct narg));
10680 /*n2->narg.next = NULL; - stzalloc did it */
10681 n2->narg.text = (char *)dolatstr;
10682 /*n2->narg.backquote = NULL;*/
10683 n1->nfor.args = n2;
10685 * Newline or semicolon here is optional (but note
10686 * that the original Bourne shell only allowed NL).
10688 if (lasttoken != TNL && lasttoken != TSEMI)
10691 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10692 if (readtoken() != TDO)
10693 raise_error_unexpected_syntax(TDO);
10694 n1->nfor.body = list(0);
10698 n1 = stzalloc(sizeof(struct ncase));
10700 if (readtoken() != TWORD)
10701 raise_error_unexpected_syntax(TWORD);
10702 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10704 /*n2->narg.next = NULL; - stzalloc did it */
10705 n2->narg.text = wordtext;
10706 n2->narg.backquote = backquotelist;
10708 checkkwd = CHKKWD | CHKALIAS;
10709 } while (readtoken() == TNL);
10710 if (lasttoken != TIN)
10711 raise_error_unexpected_syntax(TIN);
10712 cpp = &n1->ncase.cases;
10714 checkkwd = CHKNL | CHKKWD;
10716 while (t != TESAC) {
10717 if (lasttoken == TLP)
10719 *cpp = cp = stzalloc(sizeof(struct nclist));
10721 app = &cp->nclist.pattern;
10723 *app = ap = stzalloc(sizeof(struct narg));
10725 /*ap->narg.next = NULL; - stzalloc did it */
10726 ap->narg.text = wordtext;
10727 ap->narg.backquote = backquotelist;
10728 if (readtoken() != TPIPE)
10730 app = &ap->narg.next;
10733 //ap->narg.next = NULL;
10734 if (lasttoken != TRP)
10735 raise_error_unexpected_syntax(TRP);
10736 cp->nclist.body = list(2);
10738 cpp = &cp->nclist.next;
10740 checkkwd = CHKNL | CHKKWD;
10744 raise_error_unexpected_syntax(TENDCASE);
10751 n1 = stzalloc(sizeof(struct nredir));
10752 n1->type = NSUBSHELL;
10753 n1->nredir.n = list(0);
10754 /*n1->nredir.redirect = NULL; - stzalloc did it */
10764 return simplecmd();
10767 if (readtoken() != t)
10768 raise_error_unexpected_syntax(t);
10771 /* Now check for redirection which may follow command */
10772 checkkwd = CHKKWD | CHKALIAS;
10774 while (readtoken() == TREDIR) {
10775 *rpp = n2 = redirnode;
10776 rpp = &n2->nfile.next;
10782 if (n1->type != NSUBSHELL) {
10783 n2 = stzalloc(sizeof(struct nredir));
10788 n1->nredir.redirect = redir;
10793 #if ENABLE_ASH_BASH_COMPAT
10794 static int decode_dollar_squote(void)
10796 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10802 p = strchr(C_escapes, c);
10807 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10811 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10813 } else if (c == 'x') { /* \xHH */
10817 } while (isxdigit(c) && --cnt);
10819 if (cnt == 3) { /* \x but next char is "bad" */
10823 } else { /* simple seq like \\ or \t */
10828 c = bb_process_escape_sequence((void*)&p);
10829 } else { /* unrecognized "\z": print both chars unless ' or " */
10830 if (c != '\'' && c != '"') {
10832 c |= 0x100; /* "please encode \, then me" */
10840 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10841 * is not NULL, read a here document. In the latter case, eofmark is the
10842 * word which marks the end of the document and striptabs is true if
10843 * leading tabs should be stripped from the document. The argument firstc
10844 * is the first character of the input token or document.
10846 * Because C does not have internal subroutines, I have simulated them
10847 * using goto's to implement the subroutine linkage. The following macros
10848 * will run code that appears at the end of readtoken1.
10850 #define CHECKEND() {goto checkend; checkend_return:;}
10851 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10852 #define PARSESUB() {goto parsesub; parsesub_return:;}
10853 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10854 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10855 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10857 readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
10859 /* NB: syntax parameter fits into smallint */
10863 char line[EOFMARKLEN + 1];
10864 struct nodelist *bqlist;
10868 smallint prevsyntax; /* syntax before arithmetic */
10869 #if ENABLE_ASH_EXPAND_PRMT
10870 smallint pssyntax; /* we are expanding a prompt string */
10872 int varnest; /* levels of variables expansion */
10873 int arinest; /* levels of arithmetic expansion */
10874 int parenlevel; /* levels of parens in arithmetic */
10875 int dqvarnest; /* levels of variables expansion within double quotes */
10877 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10880 /* Avoid longjmp clobbering */
10886 (void) &parenlevel;
10889 (void) &prevsyntax;
10892 startlinno = g_parsefile->linno;
10897 #if ENABLE_ASH_EXPAND_PRMT
10898 pssyntax = (syntax == PSSYNTAX);
10902 dblquote = (syntax == DQSYNTAX);
10908 STARTSTACKSTR(out);
10910 /* For each line, until end of word */
10912 CHECKEND(); /* set c to PEOF if at end of here document */
10913 for (;;) { /* until end of line or end of word */
10914 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10915 switch (SIT(c, syntax)) {
10916 case CNL: /* '\n' */
10917 if (syntax == BASESYNTAX)
10918 goto endword; /* exit outer loop */
10920 g_parsefile->linno++;
10924 goto loop; /* continue outer loop */
10929 if (eofmark == NULL || dblquote)
10930 USTPUTC(CTLESC, out);
10931 #if ENABLE_ASH_BASH_COMPAT
10932 if (c == '\\' && bash_dollar_squote) {
10933 c = decode_dollar_squote();
10935 USTPUTC('\\', out);
10936 c = (unsigned char)c;
10942 case CBACK: /* backslash */
10945 USTPUTC(CTLESC, out);
10946 USTPUTC('\\', out);
10948 } else if (c == '\n') {
10952 #if ENABLE_ASH_EXPAND_PRMT
10953 if (c == '$' && pssyntax) {
10954 USTPUTC(CTLESC, out);
10955 USTPUTC('\\', out);
10958 if (dblquote && c != '\\'
10959 && c != '`' && c != '$'
10960 && (c != '"' || eofmark != NULL)
10962 USTPUTC(CTLESC, out);
10963 USTPUTC('\\', out);
10965 if (SIT(c, SQSYNTAX) == CCTL)
10966 USTPUTC(CTLESC, out);
10974 if (eofmark == NULL) {
10975 USTPUTC(CTLQUOTEMARK, out);
10983 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
10984 if (eofmark != NULL && arinest == 0
10989 if (dqvarnest == 0) {
10990 syntax = BASESYNTAX;
10997 case CVAR: /* '$' */
10998 PARSESUB(); /* parse substitution */
11000 case CENDVAR: /* '}' */
11003 if (dqvarnest > 0) {
11006 USTPUTC(CTLENDVAR, out);
11011 #if ENABLE_SH_MATH_SUPPORT
11012 case CLP: /* '(' in arithmetic */
11016 case CRP: /* ')' in arithmetic */
11017 if (parenlevel > 0) {
11021 if (pgetc() == ')') {
11022 if (--arinest == 0) {
11023 USTPUTC(CTLENDARI, out);
11024 syntax = prevsyntax;
11025 dblquote = (syntax == DQSYNTAX);
11030 * unbalanced parens
11031 * (don't 2nd guess - no error)
11039 case CBQUOTE: /* '`' */
11043 goto endword; /* exit outer loop */
11047 if (varnest == 0) {
11048 #if ENABLE_ASH_BASH_COMPAT
11050 if (pgetc() == '>')
11051 c = 0x100 + '>'; /* flag &> */
11055 goto endword; /* exit outer loop */
11057 #if ENABLE_ASH_ALIAS
11067 #if ENABLE_SH_MATH_SUPPORT
11068 if (syntax == ARISYNTAX)
11069 raise_error_syntax("missing '))'");
11071 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11072 raise_error_syntax("unterminated quoted string");
11073 if (varnest != 0) {
11074 startlinno = g_parsefile->linno;
11076 raise_error_syntax("missing '}'");
11078 USTPUTC('\0', out);
11079 len = out - (char *)stackblock();
11080 out = stackblock();
11081 if (eofmark == NULL) {
11082 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11085 if (isdigit_str9(out)) {
11086 PARSEREDIR(); /* passed as params: out, c */
11087 lasttoken = TREDIR;
11090 /* else: non-number X seen, interpret it
11091 * as "NNNX>file" = "NNNX >file" */
11095 quoteflag = quotef;
11096 backquotelist = bqlist;
11097 grabstackblock(len);
11101 /* end of readtoken routine */
11104 * Check to see whether we are at the end of the here document. When this
11105 * is called, c is set to the first character of the next input line. If
11106 * we are at the end of the here document, this routine sets the c to PEOF.
11110 #if ENABLE_ASH_ALIAS
11116 while (c == '\t') {
11120 if (c == *eofmark) {
11121 if (pfgets(line, sizeof(line)) != NULL) {
11125 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11127 if (*p == '\n' && *q == '\0') {
11129 g_parsefile->linno++;
11130 needprompt = doprompt;
11132 pushstring(line, NULL);
11137 goto checkend_return;
11141 * Parse a redirection operator. The variable "out" points to a string
11142 * specifying the fd to be redirected. The variable "c" contains the
11143 * first character of the redirection operator.
11146 /* out is already checked to be a valid number or "" */
11147 int fd = (*out == '\0' ? -1 : atoi(out));
11150 np = stzalloc(sizeof(struct nfile));
11155 np->type = NAPPEND;
11157 np->type = NCLOBBER;
11160 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11166 #if ENABLE_ASH_BASH_COMPAT
11167 else if (c == 0x100 + '>') { /* this flags &> redirection */
11169 pgetc(); /* this is '>', no need to check */
11173 else { /* c == '<' */
11174 /*np->nfile.fd = 0; - stzalloc did it */
11178 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11179 np = stzalloc(sizeof(struct nhere));
11180 /*np->nfile.fd = 0; - stzalloc did it */
11183 heredoc = stzalloc(sizeof(struct heredoc));
11184 heredoc->here = np;
11187 heredoc->striptabs = 1;
11189 /*heredoc->striptabs = 0; - stzalloc did it */
11195 np->type = NFROMFD;
11199 np->type = NFROMTO;
11211 goto parseredir_return;
11215 * Parse a substitution. At this point, we have read the dollar sign
11216 * and nothing else.
11219 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11220 * (assuming ascii char codes, as the original implementation did) */
11221 #define is_special(c) \
11222 (((unsigned)(c) - 33 < 32) \
11223 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11229 static const char types[] ALIGN1 = "}-+?=";
11232 if (c <= PEOA_OR_PEOF
11233 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11235 #if ENABLE_ASH_BASH_COMPAT
11237 bash_dollar_squote = 1;
11242 } else if (c == '(') { /* $(command) or $((arith)) */
11243 if (pgetc() == '(') {
11244 #if ENABLE_SH_MATH_SUPPORT
11247 raise_error_syntax("you disabled math support for $((arith)) syntax");
11254 USTPUTC(CTLVAR, out);
11255 typeloc = out - (char *)stackblock();
11256 USTPUTC(VSNORMAL, out);
11257 subtype = VSNORMAL;
11265 subtype = VSLENGTH;
11269 if (c > PEOA_OR_PEOF && is_name(c)) {
11273 } while (c > PEOA_OR_PEOF && is_in_name(c));
11274 } else if (isdigit(c)) {
11278 } while (isdigit(c));
11279 } else if (is_special(c)) {
11284 raise_error_syntax("bad substitution");
11286 if (c != '}' && subtype == VSLENGTH)
11291 if (subtype == 0) {
11295 #if ENABLE_ASH_BASH_COMPAT
11296 if (c == ':' || c == '$' || isdigit(c)) {
11298 subtype = VSSUBSTR;
11305 p = strchr(types, c);
11308 subtype = p - types + VSNORMAL;
11313 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11321 #if ENABLE_ASH_BASH_COMPAT
11323 subtype = VSREPLACE;
11326 subtype++; /* VSREPLACEALL */
11335 if (dblquote || arinest)
11337 *((char *)stackblock() + typeloc) = subtype | flags;
11338 if (subtype != VSNORMAL) {
11340 if (dblquote || arinest) {
11345 goto parsesub_return;
11349 * Called to parse command substitutions. Newstyle is set if the command
11350 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11351 * list of commands (passed by reference), and savelen is the number of
11352 * characters on the top of the stack which must be preserved.
11355 struct nodelist **nlpp;
11358 char *volatile str;
11359 struct jmploc jmploc;
11360 struct jmploc *volatile savehandler;
11362 smallint saveprompt = 0;
11365 (void) &saveprompt;
11367 savepbq = parsebackquote;
11368 if (setjmp(jmploc.loc)) {
11370 parsebackquote = 0;
11371 exception_handler = savehandler;
11372 longjmp(exception_handler->loc, 1);
11376 savelen = out - (char *)stackblock();
11378 str = ckmalloc(savelen);
11379 memcpy(str, stackblock(), savelen);
11381 savehandler = exception_handler;
11382 exception_handler = &jmploc;
11385 /* We must read until the closing backquote, giving special
11386 treatment to some slashes, and then push the string and
11387 reread it as input, interpreting it normally. */
11394 STARTSTACKSTR(pout);
11407 g_parsefile->linno++;
11411 * If eating a newline, avoid putting
11412 * the newline into the new character
11413 * stream (via the STPUTC after the
11418 if (pc != '\\' && pc != '`' && pc != '$'
11419 && (!dblquote || pc != '"'))
11420 STPUTC('\\', pout);
11421 if (pc > PEOA_OR_PEOF) {
11427 #if ENABLE_ASH_ALIAS
11430 startlinno = g_parsefile->linno;
11431 raise_error_syntax("EOF in backquote substitution");
11434 g_parsefile->linno++;
11435 needprompt = doprompt;
11444 STPUTC('\0', pout);
11445 psavelen = pout - (char *)stackblock();
11446 if (psavelen > 0) {
11447 pstr = grabstackstr(pout);
11448 setinputstring(pstr);
11453 nlpp = &(*nlpp)->next;
11454 *nlpp = stzalloc(sizeof(**nlpp));
11455 /* (*nlpp)->next = NULL; - stzalloc did it */
11456 parsebackquote = oldstyle;
11459 saveprompt = doprompt;
11466 doprompt = saveprompt;
11467 else if (readtoken() != TRP)
11468 raise_error_unexpected_syntax(TRP);
11473 * Start reading from old file again, ignoring any pushed back
11474 * tokens left from the backquote parsing
11479 while (stackblocksize() <= savelen)
11481 STARTSTACKSTR(out);
11483 memcpy(out, str, savelen);
11484 STADJUST(savelen, out);
11490 parsebackquote = savepbq;
11491 exception_handler = savehandler;
11492 if (arinest || dblquote)
11493 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11495 USTPUTC(CTLBACKQ, out);
11497 goto parsebackq_oldreturn;
11498 goto parsebackq_newreturn;
11501 #if ENABLE_SH_MATH_SUPPORT
11503 * Parse an arithmetic expansion (indicate start of one and set state)
11506 if (++arinest == 1) {
11507 prevsyntax = syntax;
11508 syntax = ARISYNTAX;
11509 USTPUTC(CTLARI, out);
11516 * we collapse embedded arithmetic expansion to
11517 * parenthesis, which should be equivalent
11521 goto parsearith_return;
11525 } /* end of readtoken */
11528 * Read the next input token.
11529 * If the token is a word, we set backquotelist to the list of cmds in
11530 * backquotes. We set quoteflag to true if any part of the word was
11532 * If the token is TREDIR, then we set redirnode to a structure containing
11534 * In all cases, the variable startlinno is set to the number of the line
11535 * on which the token starts.
11537 * [Change comment: here documents and internal procedures]
11538 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11539 * word parsing code into a separate routine. In this case, readtoken
11540 * doesn't need to have any internal procedures, but parseword does.
11541 * We could also make parseoperator in essence the main routine, and
11542 * have parseword (readtoken1?) handle both words and redirection.]
11544 #define NEW_xxreadtoken
11545 #ifdef NEW_xxreadtoken
11546 /* singles must be first! */
11547 static const char xxreadtoken_chars[7] ALIGN1 = {
11548 '\n', '(', ')', /* singles */
11549 '&', '|', ';', /* doubles */
11553 #define xxreadtoken_singles 3
11554 #define xxreadtoken_doubles 3
11556 static const char xxreadtoken_tokens[] ALIGN1 = {
11557 TNL, TLP, TRP, /* only single occurrence allowed */
11558 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11559 TEOF, /* corresponds to trailing nul */
11560 TAND, TOR, TENDCASE /* if double occurrence */
11575 startlinno = g_parsefile->linno;
11576 for (;;) { /* until token or start of word found */
11578 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11582 while ((c = pgetc()) != '\n' && c != PEOF)
11585 } else if (c == '\\') {
11586 if (pgetc() != '\n') {
11588 break; /* return readtoken1(...) */
11590 startlinno = ++g_parsefile->linno;
11596 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11599 g_parsefile->linno++;
11600 needprompt = doprompt;
11603 p = strchr(xxreadtoken_chars, c);
11605 break; /* return readtoken1(...) */
11607 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11609 if (cc == c) { /* double occurrence? */
11610 p += xxreadtoken_doubles + 1;
11613 #if ENABLE_ASH_BASH_COMPAT
11614 if (c == '&' && cc == '>') /* &> */
11615 break; /* return readtoken1(...) */
11620 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11625 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11627 #else /* old xxreadtoken */
11628 #define RETURN(token) return lasttoken = token
11641 startlinno = g_parsefile->linno;
11642 for (;;) { /* until token or start of word found */
11645 case ' ': case '\t':
11646 #if ENABLE_ASH_ALIAS
11651 while ((c = pgetc()) != '\n' && c != PEOF)
11656 if (pgetc() == '\n') {
11657 startlinno = ++g_parsefile->linno;
11665 g_parsefile->linno++;
11666 needprompt = doprompt;
11671 if (pgetc() == '&')
11676 if (pgetc() == '|')
11681 if (pgetc() == ';')
11694 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11697 #endif /* old xxreadtoken */
11704 smallint alreadyseen = tokpushback;
11707 #if ENABLE_ASH_ALIAS
11716 if (checkkwd & CHKNL) {
11723 if (t != TWORD || quoteflag) {
11728 * check for keywords
11730 if (checkkwd & CHKKWD) {
11731 const char *const *pp;
11733 pp = findkwd(wordtext);
11735 lasttoken = t = pp - tokname_array;
11736 TRACE(("keyword %s recognized\n", tokname(t)));
11741 if (checkkwd & CHKALIAS) {
11742 #if ENABLE_ASH_ALIAS
11744 ap = lookupalias(wordtext, 1);
11747 pushstring(ap->val, ap);
11757 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11759 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11771 return tokname_array[t][0];
11775 * Read and parse a command. Returns NODE_EOF on end of file.
11776 * (NULL is a valid parse tree indicating a blank line.)
11778 static union node *
11779 parsecmd(int interact)
11784 doprompt = interact;
11786 setprompt(doprompt);
11798 * Input any here documents.
11803 struct heredoc *here;
11806 here = heredoclist;
11807 heredoclist = NULL;
11813 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11814 here->eofmark, here->striptabs);
11815 n = stzalloc(sizeof(struct narg));
11816 n->narg.type = NARG;
11817 /*n->narg.next = NULL; - stzalloc did it */
11818 n->narg.text = wordtext;
11819 n->narg.backquote = backquotelist;
11820 here->here->nhere.doc = n;
11827 * called by editline -- any expansions to the prompt should be added here.
11829 #if ENABLE_ASH_EXPAND_PRMT
11830 static const char *
11831 expandstr(const char *ps)
11835 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11836 * and token processing _can_ alter it (delete NULs etc). */
11837 setinputstring((char *)ps);
11838 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11841 n.narg.type = NARG;
11842 n.narg.next = NULL;
11843 n.narg.text = wordtext;
11844 n.narg.backquote = backquotelist;
11846 expandarg(&n, NULL, 0);
11847 return stackblock();
11852 * Execute a command or commands contained in a string.
11855 evalstring(char *s, int mask)
11858 struct stackmark smark;
11862 setstackmark(&smark);
11865 while ((n = parsecmd(0)) != NODE_EOF) {
11867 popstackmark(&smark);
11880 * The eval command.
11882 static int FAST_FUNC
11883 evalcmd(int argc UNUSED_PARAM, char **argv)
11892 STARTSTACKSTR(concat);
11894 concat = stack_putstr(p, concat);
11898 STPUTC(' ', concat);
11900 STPUTC('\0', concat);
11901 p = grabstackstr(concat);
11903 evalstring(p, ~SKIPEVAL);
11910 * Read and execute commands. "Top" is nonzero for the top level command
11911 * loop; it turns on prompting if the shell is interactive.
11917 struct stackmark smark;
11921 TRACE(("cmdloop(%d) called\n", top));
11925 setstackmark(&smark);
11928 showjobs(stderr, SHOW_CHANGED);
11931 if (iflag && top) {
11933 #if ENABLE_ASH_MAIL
11937 n = parsecmd(inter);
11939 if (DEBUG > 2 && debug && (n != NODE_EOF))
11942 if (n == NODE_EOF) {
11943 if (!top || numeof >= 50)
11945 if (!stoppedjobs()) {
11948 out2str("\nUse \"exit\" to leave shell.\n");
11951 } else if (nflag == 0) {
11952 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11957 popstackmark(&smark);
11962 return skip & SKIPEVAL;
11969 * Take commands from a file. To be compatible we should do a path
11970 * search for the file, which is necessary to find sub-commands.
11973 find_dot_file(char *name)
11976 const char *path = pathval();
11979 /* don't try this for absolute or relative paths */
11980 if (strchr(name, '/'))
11983 /* IIRC standards do not say whether . is to be searched.
11984 * And it is even smaller this way, making it unconditional for now:
11986 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11991 while ((fullname = path_advance(&path, name)) != NULL) {
11993 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11995 * Don't bother freeing here, since it will
11996 * be freed by the caller.
12000 if (fullname != name)
12001 stunalloc(fullname);
12004 /* not found in the PATH */
12005 ash_msg_and_raise_error("%s: not found", name);
12009 static int FAST_FUNC
12010 dotcmd(int argc, char **argv)
12012 struct strlist *sp;
12013 volatile struct shparam saveparam;
12016 for (sp = cmdenviron; sp; sp = sp->next)
12017 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12019 if (argv[1]) { /* That's what SVR2 does */
12020 char *fullname = find_dot_file(argv[1]);
12023 if (argc) { /* argc > 0, argv[0] != NULL */
12024 saveparam = shellparam;
12025 shellparam.malloced = 0;
12026 shellparam.nparam = argc;
12027 shellparam.p = argv;
12030 setinputfile(fullname, INPUT_PUSH_FILE);
12031 commandname = fullname;
12036 freeparam(&shellparam);
12037 shellparam = saveparam;
12039 status = exitstatus;
12044 static int FAST_FUNC
12045 exitcmd(int argc UNUSED_PARAM, char **argv)
12050 exitstatus = number(argv[1]);
12051 raise_exception(EXEXIT);
12056 * Read a file containing shell functions.
12059 readcmdfile(char *name)
12061 setinputfile(name, INPUT_PUSH_FILE);
12067 /* ============ find_command inplementation */
12070 * Resolve a command name. If you change this routine, you may have to
12071 * change the shellexec routine as well.
12074 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12076 struct tblentry *cmdp;
12083 struct builtincmd *bcmd;
12085 /* If name contains a slash, don't use PATH or hash table */
12086 if (strchr(name, '/') != NULL) {
12087 entry->u.index = -1;
12088 if (act & DO_ABS) {
12089 while (stat(name, &statb) < 0) {
12091 if (errno == EINTR)
12094 entry->cmdtype = CMDUNKNOWN;
12098 entry->cmdtype = CMDNORMAL;
12102 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12104 updatetbl = (path == pathval());
12107 if (strstr(path, "%builtin") != NULL)
12108 act |= DO_ALTBLTIN;
12111 /* If name is in the table, check answer will be ok */
12112 cmdp = cmdlookup(name, 0);
12113 if (cmdp != NULL) {
12116 switch (cmdp->cmdtype) {
12134 } else if (cmdp->rehash == 0)
12135 /* if not invalidated by cd, we're done */
12139 /* If %builtin not in path, check for builtin next */
12140 bcmd = find_builtin(name);
12142 if (IS_BUILTIN_REGULAR(bcmd))
12143 goto builtin_success;
12144 if (act & DO_ALTPATH) {
12145 if (!(act & DO_ALTBLTIN))
12146 goto builtin_success;
12147 } else if (builtinloc <= 0) {
12148 goto builtin_success;
12152 #if ENABLE_FEATURE_SH_STANDALONE
12154 int applet_no = find_applet_by_name(name);
12155 if (applet_no >= 0) {
12156 entry->cmdtype = CMDNORMAL;
12157 entry->u.index = -2 - applet_no;
12163 /* We have to search path. */
12164 prev = -1; /* where to start */
12165 if (cmdp && cmdp->rehash) { /* doing a rehash */
12166 if (cmdp->cmdtype == CMDBUILTIN)
12169 prev = cmdp->param.index;
12175 while ((fullname = path_advance(&path, name)) != NULL) {
12176 stunalloc(fullname);
12177 /* NB: code below will still use fullname
12178 * despite it being "unallocated" */
12181 if (prefix(pathopt, "builtin")) {
12183 goto builtin_success;
12186 if ((act & DO_NOFUNC)
12187 || !prefix(pathopt, "func")
12188 ) { /* ignore unimplemented options */
12192 /* if rehash, don't redo absolute path names */
12193 if (fullname[0] == '/' && idx <= prev) {
12196 TRACE(("searchexec \"%s\": no change\n", name));
12199 while (stat(fullname, &statb) < 0) {
12201 if (errno == EINTR)
12204 if (errno != ENOENT && errno != ENOTDIR)
12208 e = EACCES; /* if we fail, this will be the error */
12209 if (!S_ISREG(statb.st_mode))
12211 if (pathopt) { /* this is a %func directory */
12212 stalloc(strlen(fullname) + 1);
12213 /* NB: stalloc will return space pointed by fullname
12214 * (because we don't have any intervening allocations
12215 * between stunalloc above and this stalloc) */
12216 readcmdfile(fullname);
12217 cmdp = cmdlookup(name, 0);
12218 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12219 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12220 stunalloc(fullname);
12223 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12225 entry->cmdtype = CMDNORMAL;
12226 entry->u.index = idx;
12230 cmdp = cmdlookup(name, 1);
12231 cmdp->cmdtype = CMDNORMAL;
12232 cmdp->param.index = idx;
12237 /* We failed. If there was an entry for this command, delete it */
12238 if (cmdp && updatetbl)
12239 delete_cmd_entry();
12241 ash_msg("%s: %s", name, errmsg(e, "not found"));
12242 entry->cmdtype = CMDUNKNOWN;
12247 entry->cmdtype = CMDBUILTIN;
12248 entry->u.cmd = bcmd;
12252 cmdp = cmdlookup(name, 1);
12253 cmdp->cmdtype = CMDBUILTIN;
12254 cmdp->param.cmd = bcmd;
12258 entry->cmdtype = cmdp->cmdtype;
12259 entry->u = cmdp->param;
12263 /* ============ trap.c */
12266 * The trap builtin.
12268 static int FAST_FUNC
12269 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12278 for (signo = 0; signo < NSIG; signo++) {
12279 char *tr = trap_ptr[signo];
12281 /* note: bash adds "SIG", but only if invoked
12282 * as "bash". If called as "sh", or if set -o posix,
12283 * then it prints short signal names.
12284 * We are printing short names: */
12285 out1fmt("trap -- %s %s\n",
12287 get_signame(signo));
12288 /* trap_ptr != trap only if we are in special-cased `trap` code.
12289 * In this case, we will exit very soon, no need to free(). */
12290 /* if (trap_ptr != trap && tp[0]) */
12295 if (trap_ptr != trap) {
12307 signo = get_signum(*ap);
12309 ash_msg_and_raise_error("%s: bad trap", *ap);
12312 if (LONE_DASH(action))
12315 action = ckstrdup(action);
12318 trap[signo] = action;
12328 /* ============ Builtins */
12330 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12332 * Lists available builtins
12334 static int FAST_FUNC
12335 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12341 "Built-in commands:\n"
12342 "------------------\n");
12343 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12344 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12345 builtintab[i].name + 1);
12351 #if ENABLE_FEATURE_SH_STANDALONE
12353 const char *a = applet_names;
12355 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12360 a += strlen(a) + 1;
12365 return EXIT_SUCCESS;
12367 #endif /* FEATURE_SH_EXTRA_QUIET */
12370 * The export and readonly commands.
12372 static int FAST_FUNC
12373 exportcmd(int argc UNUSED_PARAM, char **argv)
12379 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12381 if (nextopt("p") != 'p') {
12386 p = strchr(name, '=');
12390 vp = *findvar(hashvar(name), name);
12396 setvar(name, p, flag);
12397 } while ((name = *++aptr) != NULL);
12401 showvars(argv[0], flag, 0);
12406 * Delete a function if it exists.
12409 unsetfunc(const char *name)
12411 struct tblentry *cmdp;
12413 cmdp = cmdlookup(name, 0);
12414 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12415 delete_cmd_entry();
12419 * The unset builtin command. We unset the function before we unset the
12420 * variable to allow a function to be unset when there is a readonly variable
12421 * with the same name.
12423 static int FAST_FUNC
12424 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12431 while ((i = nextopt("vf")) != '\0') {
12435 for (ap = argptr; *ap; ap++) {
12451 #include <sys/times.h>
12453 static const unsigned char timescmd_str[] ALIGN1 = {
12454 ' ', offsetof(struct tms, tms_utime),
12455 '\n', offsetof(struct tms, tms_stime),
12456 ' ', offsetof(struct tms, tms_cutime),
12457 '\n', offsetof(struct tms, tms_cstime),
12461 static int FAST_FUNC
12462 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12464 long clk_tck, s, t;
12465 const unsigned char *p;
12468 clk_tck = sysconf(_SC_CLK_TCK);
12473 t = *(clock_t *)(((char *) &buf) + p[1]);
12475 out1fmt("%ldm%ld.%.3lds%c",
12477 ((t - s * clk_tck) * 1000) / clk_tck,
12479 } while (*(p += 2));
12484 #if ENABLE_SH_MATH_SUPPORT
12486 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12487 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12489 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12491 static int FAST_FUNC
12492 letcmd(int argc UNUSED_PARAM, char **argv)
12498 ash_msg_and_raise_error("expression expected");
12500 i = ash_arith(*argv);
12505 #endif /* SH_MATH_SUPPORT */
12508 /* ============ miscbltin.c
12510 * Miscellaneous builtins.
12515 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
12516 typedef enum __rlimit_resource rlim_t;
12520 * The read builtin. Options:
12521 * -r Do not interpret '\' specially
12522 * -s Turn off echo (tty only)
12523 * -n NCHARS Read NCHARS max
12524 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12525 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12526 * -u FD Read from given FD instead of fd 0
12527 * This uses unbuffered input, which may be avoidable in some cases.
12528 * TODO: bash also has:
12529 * -a ARRAY Read into array[0],[1],etc
12530 * -d DELIM End on DELIM char, not newline
12531 * -e Use line editing (tty only)
12533 static int FAST_FUNC
12534 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12536 static const char *const arg_REPLY[] = { "REPLY", NULL };
12549 #if ENABLE_ASH_READ_NCHARS
12550 int nchars = 0; /* if != 0, -n is in effect */
12552 struct termios tty, old_tty;
12554 #if ENABLE_ASH_READ_TIMEOUT
12555 unsigned end_ms = 0;
12556 unsigned timeout = 0;
12561 while ((i = nextopt("p:u:r"
12562 IF_ASH_READ_TIMEOUT("t:")
12563 IF_ASH_READ_NCHARS("n:s")
12567 prompt = optionarg;
12569 #if ENABLE_ASH_READ_NCHARS
12571 nchars = bb_strtou(optionarg, NULL, 10);
12572 if (nchars < 0 || errno)
12573 ash_msg_and_raise_error("invalid count");
12574 /* nchars == 0: off (bash 3.2 does this too) */
12580 #if ENABLE_ASH_READ_TIMEOUT
12582 timeout = bb_strtou(optionarg, NULL, 10);
12583 if (errno || timeout > UINT_MAX / 2048)
12584 ash_msg_and_raise_error("invalid timeout");
12586 #if 0 /* even bash have no -t N.NNN support */
12587 ts.tv_sec = bb_strtou(optionarg, &p, 10);
12589 /* EINVAL means number is ok, but not terminated by NUL */
12590 if (*p == '.' && errno == EINVAL) {
12594 ts.tv_usec = bb_strtou(p, &p2, 10);
12596 ash_msg_and_raise_error("invalid timeout");
12598 /* normalize to usec */
12600 ash_msg_and_raise_error("invalid timeout");
12601 while (scale++ < 6)
12604 } else if (ts.tv_sec < 0 || errno) {
12605 ash_msg_and_raise_error("invalid timeout");
12607 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
12608 ash_msg_and_raise_error("invalid timeout");
12617 fd = bb_strtou(optionarg, NULL, 10);
12618 if (fd < 0 || errno)
12619 ash_msg_and_raise_error("invalid file descriptor");
12625 if (prompt && isatty(fd)) {
12630 ap = (char**)arg_REPLY;
12631 ifs = bltinlookup("IFS");
12634 #if ENABLE_ASH_READ_NCHARS
12635 tcgetattr(fd, &tty);
12637 if (nchars || silent) {
12639 tty.c_lflag &= ~ICANON;
12640 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
12643 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12645 /* if tcgetattr failed, tcsetattr will fail too.
12646 * Ignoring, it's harmless. */
12647 tcsetattr(fd, TCSANOW, &tty);
12654 #if ENABLE_ASH_READ_TIMEOUT
12655 if (timeout) /* NB: ensuring end_ms is nonzero */
12656 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12660 const char *is_ifs;
12662 #if ENABLE_ASH_READ_TIMEOUT
12664 struct pollfd pfd[1];
12666 pfd[0].events = POLLIN;
12667 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12668 if ((int)timeout <= 0 /* already late? */
12669 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12670 ) { /* timed out! */
12671 #if ENABLE_ASH_READ_NCHARS
12672 tcsetattr(fd, TCSANOW, &old_tty);
12678 if (nonblock_safe_read(fd, &c, 1) != 1) {
12690 if (!rflag && c == '\\') {
12696 /* $IFS splitting */
12697 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
12698 is_ifs = strchr(ifs, c);
12699 if (startword && is_ifs) {
12702 /* it is a non-space ifs char */
12704 if (startword == 1) /* first one? */
12705 continue; /* yes, it is not next word yet */
12708 if (ap[1] != NULL && is_ifs) {
12711 beg = stackblock();
12712 setvar(*ap, beg, 0);
12714 /* can we skip one non-space ifs char? (2: yes) */
12715 startword = isspace(c) ? 2 : 1;
12722 /* end of do {} while: */
12723 #if ENABLE_ASH_READ_NCHARS
12729 #if ENABLE_ASH_READ_NCHARS
12730 tcsetattr(fd, TCSANOW, &old_tty);
12734 /* Remove trailing space ifs chars */
12735 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
12737 setvar(*ap, stackblock(), 0);
12738 while (*++ap != NULL)
12739 setvar(*ap, nullstr, 0);
12743 static int FAST_FUNC
12744 umaskcmd(int argc UNUSED_PARAM, char **argv)
12746 static const char permuser[3] ALIGN1 = "ugo";
12747 static const char permmode[3] ALIGN1 = "rwx";
12748 static const short permmask[] ALIGN2 = {
12749 S_IRUSR, S_IWUSR, S_IXUSR,
12750 S_IRGRP, S_IWGRP, S_IXGRP,
12751 S_IROTH, S_IWOTH, S_IXOTH
12754 /* TODO: use bb_parse_mode() instead */
12759 int symbolic_mode = 0;
12761 while (nextopt("S") != '\0') {
12772 if (symbolic_mode) {
12776 for (i = 0; i < 3; i++) {
12779 *p++ = permuser[i];
12781 for (j = 0; j < 3; j++) {
12782 if ((mask & permmask[3 * i + j]) == 0) {
12783 *p++ = permmode[j];
12791 out1fmt("%.4o\n", mask);
12794 if (isdigit((unsigned char) *ap)) {
12797 if (*ap >= '8' || *ap < '0')
12798 ash_msg_and_raise_error(msg_illnum, argv[1]);
12799 mask = (mask << 3) + (*ap - '0');
12800 } while (*++ap != '\0');
12803 mask = ~mask & 0777;
12804 if (!bb_parse_mode(ap, &mask)) {
12805 ash_msg_and_raise_error("illegal mode: %s", ap);
12807 umask(~mask & 0777);
12816 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12817 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12818 * ash by J.T. Conklin.
12823 uint8_t cmd; /* RLIMIT_xxx fit into it */
12824 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
12828 static const struct limits limits_tbl[] = {
12830 { RLIMIT_CPU, 0, 't' },
12832 #ifdef RLIMIT_FSIZE
12833 { RLIMIT_FSIZE, 9, 'f' },
12836 { RLIMIT_DATA, 10, 'd' },
12838 #ifdef RLIMIT_STACK
12839 { RLIMIT_STACK, 10, 's' },
12842 { RLIMIT_CORE, 9, 'c' },
12845 { RLIMIT_RSS, 10, 'm' },
12847 #ifdef RLIMIT_MEMLOCK
12848 { RLIMIT_MEMLOCK, 10, 'l' },
12850 #ifdef RLIMIT_NPROC
12851 { RLIMIT_NPROC, 0, 'p' },
12853 #ifdef RLIMIT_NOFILE
12854 { RLIMIT_NOFILE, 0, 'n' },
12857 { RLIMIT_AS, 10, 'v' },
12859 #ifdef RLIMIT_LOCKS
12860 { RLIMIT_LOCKS, 0, 'w' },
12863 static const char limits_name[] =
12865 "time(seconds)" "\0"
12867 #ifdef RLIMIT_FSIZE
12868 "file(blocks)" "\0"
12873 #ifdef RLIMIT_STACK
12877 "coredump(blocks)" "\0"
12882 #ifdef RLIMIT_MEMLOCK
12883 "locked memory(kb)" "\0"
12885 #ifdef RLIMIT_NPROC
12888 #ifdef RLIMIT_NOFILE
12894 #ifdef RLIMIT_LOCKS
12899 enum limtype { SOFT = 0x1, HARD = 0x2 };
12902 printlim(enum limtype how, const struct rlimit *limit,
12903 const struct limits *l)
12907 val = limit->rlim_max;
12909 val = limit->rlim_cur;
12911 if (val == RLIM_INFINITY)
12912 out1fmt("unlimited\n");
12914 val >>= l->factor_shift;
12915 out1fmt("%lld\n", (long long) val);
12919 static int FAST_FUNC
12920 ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12923 enum limtype how = SOFT | HARD;
12924 const struct limits *l;
12927 struct rlimit limit;
12930 while ((optc = nextopt("HSa"
12934 #ifdef RLIMIT_FSIZE
12940 #ifdef RLIMIT_STACK
12949 #ifdef RLIMIT_MEMLOCK
12952 #ifdef RLIMIT_NPROC
12955 #ifdef RLIMIT_NOFILE
12961 #ifdef RLIMIT_LOCKS
12979 for (l = limits_tbl; l->option != what; l++)
12982 set = *argptr ? 1 : 0;
12987 if (all || argptr[1])
12988 ash_msg_and_raise_error("too many arguments");
12989 if (strncmp(p, "unlimited\n", 9) == 0)
12990 val = RLIM_INFINITY;
12992 if (sizeof(val) == sizeof(int))
12993 val = bb_strtou(p, NULL, 10);
12994 else if (sizeof(val) == sizeof(long))
12995 val = bb_strtoul(p, NULL, 10);
12997 val = bb_strtoull(p, NULL, 10);
12999 ash_msg_and_raise_error("bad number");
13000 val <<= l->factor_shift;
13004 const char *lname = limits_name;
13005 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
13006 getrlimit(l->cmd, &limit);
13007 out1fmt("%-20s ", lname);
13008 lname += strlen(lname) + 1;
13009 printlim(how, &limit, l);
13014 getrlimit(l->cmd, &limit);
13017 limit.rlim_max = val;
13019 limit.rlim_cur = val;
13020 if (setrlimit(l->cmd, &limit) < 0)
13021 ash_msg_and_raise_error("error setting limit (%m)");
13023 printlim(how, &limit, l);
13028 /* ============ main() and helpers */
13031 * Called to exit the shell.
13033 static void exitshell(void) NORETURN;
13041 status = exitstatus;
13042 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13043 if (setjmp(loc.loc)) {
13044 if (exception_type == EXEXIT)
13045 /* dash bug: it just does _exit(exitstatus) here
13046 * but we have to do setjobctl(0) first!
13047 * (bug is still not fixed in dash-0.5.3 - if you run dash
13048 * under Midnight Commander, on exit from dash MC is backgrounded) */
13049 status = exitstatus;
13052 exception_handler = &loc;
13059 flush_stdout_stderr();
13069 /* from input.c: */
13070 basepf.next_to_pgetc = basepf.buf = basebuf;
13073 signal(SIGCHLD, SIG_DFL);
13079 struct stat st1, st2;
13082 for (envp = environ; envp && *envp; envp++) {
13083 if (strchr(*envp, '=')) {
13084 setvareq(*envp, VEXPORT|VTEXTFIXED);
13088 setvar("PPID", utoa(getppid()), 0);
13090 p = lookupvar("PWD");
13092 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13093 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
13100 * Process the shell command line arguments.
13103 procargs(char **argv)
13106 const char *xminusc;
13111 /* if (xargv[0]) - mmm, this is always true! */
13113 for (i = 0; i < NOPTS; i++)
13117 /* it already printed err message */
13118 raise_exception(EXERROR);
13122 if (*xargv == NULL) {
13124 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13127 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13131 for (i = 0; i < NOPTS; i++)
13132 if (optlist[i] == 2)
13137 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13142 } else if (!sflag) {
13143 setinputfile(*xargv, 0);
13146 commandname = arg0;
13149 shellparam.p = xargv;
13150 #if ENABLE_ASH_GETOPTS
13151 shellparam.optind = 1;
13152 shellparam.optoff = -1;
13154 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13156 shellparam.nparam++;
13163 * Read /etc/profile or .profile.
13166 read_profile(const char *name)
13170 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13179 * This routine is called when an error or an interrupt occurs in an
13180 * interactive shell and control is returned to the main command loop.
13188 /* from input.c: */
13189 g_parsefile->left_in_buffer = 0;
13190 g_parsefile->left_in_line = 0; /* clear input buffer */
13192 /* from parser.c: */
13195 /* from redir.c: */
13196 clearredir(/*drop:*/ 0);
13200 static short profile_buf[16384];
13201 extern int etext();
13205 * Main routine. We initialize things, parse the arguments, execute
13206 * profiles if we're a login shell, and then call cmdloop to execute
13207 * commands. The setjmp call sets up the location to jump to when an
13208 * exception occurs. When an exception occurs the variable "state"
13209 * is used to figure out how far we had gotten.
13211 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13212 int ash_main(int argc UNUSED_PARAM, char **argv)
13214 const char *shinit;
13215 volatile smallint state;
13216 struct jmploc jmploc;
13217 struct stackmark smark;
13219 /* Initialize global data */
13223 #if ENABLE_ASH_ALIAS
13229 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13232 #if ENABLE_FEATURE_EDITING
13233 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13236 if (setjmp(jmploc.loc)) {
13242 e = exception_type;
13246 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13249 outcslow('\n', stderr);
13251 popstackmark(&smark);
13252 FORCE_INT_ON; /* enable interrupts */
13261 exception_handler = &jmploc;
13264 TRACE(("Shell args: "));
13265 trace_puts_args(argv);
13267 rootpid = getpid();
13270 setstackmark(&smark);
13273 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13275 const char *hp = lookupvar("HISTFILE");
13278 hp = lookupvar("HOME");
13280 char *defhp = concat_path_file(hp, ".ash_history");
13281 setvar("HISTFILE", defhp, 0);
13287 if (/* argv[0] && */ argv[0][0] == '-')
13291 read_profile("/etc/profile");
13294 read_profile(".profile");
13300 getuid() == geteuid() && getgid() == getegid() &&
13304 shinit = lookupvar("ENV");
13305 if (shinit != NULL && *shinit != '\0') {
13306 read_profile(shinit);
13312 /* evalstring pushes parsefile stack.
13313 * Ensure we don't falsely claim that 0 (stdin)
13314 * is one of stacked source fds.
13315 * Testcase: ash -c 'exec 1>&0' must not complain. */
13317 g_parsefile->fd = -1;
13318 evalstring(minusc, 0);
13321 if (sflag || minusc == NULL) {
13322 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13324 const char *hp = lookupvar("HISTFILE");
13326 line_input_state->hist_file = hp;
13329 state4: /* XXX ??? - why isn't this before the "if" statement */
13337 extern void _mcleanup(void);
13347 * Copyright (c) 1989, 1991, 1993, 1994
13348 * The Regents of the University of California. All rights reserved.
13350 * This code is derived from software contributed to Berkeley by
13351 * Kenneth Almquist.
13353 * Redistribution and use in source and binary forms, with or without
13354 * modification, are permitted provided that the following conditions
13356 * 1. Redistributions of source code must retain the above copyright
13357 * notice, this list of conditions and the following disclaimer.
13358 * 2. Redistributions in binary form must reproduce the above copyright
13359 * notice, this list of conditions and the following disclaimer in the
13360 * documentation and/or other materials provided with the distribution.
13361 * 3. Neither the name of the University nor the names of its contributors
13362 * may be used to endorse or promote products derived from this software
13363 * without specific prior written permission.
13365 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13366 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13367 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13368 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13369 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13370 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13371 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13372 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13373 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13374 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF