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
55 #if defined SINGLE_APPLET_MAIN
56 /* STANDALONE does not make sense, and won't compile */
57 #undef CONFIG_FEATURE_SH_STANDALONE
58 #undef ENABLE_FEATURE_SH_STANDALONE
59 #undef IF_FEATURE_SH_STANDALONE
60 #undef IF_NOT_FEATURE_SH_STANDALONE(...)
61 #define ENABLE_FEATURE_SH_STANDALONE 0
62 #define IF_FEATURE_SH_STANDALONE(...)
63 #define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
67 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
70 #if defined(__uClinux__)
71 # error "Do not even bother, ash will not run on NOMMU machine"
75 /* ============ Hash table sizes. Configurable. */
79 #define CMDTABLESIZE 31 /* should be prime */
82 /* ============ Shell options */
84 static const char *const optletters_optnames[] = {
105 #define optletters(n) optletters_optnames[(n)][0]
106 #define optnames(n) (&optletters_optnames[(n)][1])
108 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
111 /* ============ Misc data */
113 static const char homestr[] ALIGN1 = "HOME";
114 static const char snlfmt[] ALIGN1 = "%s\n";
115 static const char msg_illnum[] ALIGN1 = "Illegal number: %s";
118 * We enclose jmp_buf in a structure so that we can declare pointers to
119 * jump locations. The global variable handler contains the location to
120 * jump to when an exception occurs, and the global variable exception_type
121 * contains a code identifying the exception. To implement nested
122 * exception handlers, the user should save the value of handler on entry
123 * to an inner scope, set handler to point to a jmploc structure for the
124 * inner scope, and restore handler on exit from the scope.
130 struct globals_misc {
131 /* pid of main shell */
133 /* shell level: 0 for the main shell, 1 for its children, and so on */
135 #define rootshell (!shlvl)
136 char *minusc; /* argument to -c option */
138 char *curdir; // = nullstr; /* current working directory */
139 char *physdir; // = nullstr; /* physical working directory */
141 char *arg0; /* value of $0 */
143 struct jmploc *exception_handler;
145 volatile int suppress_int; /* counter */
146 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
147 /* last pending signal */
148 volatile /*sig_atomic_t*/ smallint pending_sig;
149 smallint exception_type; /* kind of exception (0..5) */
151 #define EXINT 0 /* SIGINT received */
152 #define EXERROR 1 /* a generic error */
153 #define EXSHELLPROC 2 /* execute a shell procedure */
154 #define EXEXEC 3 /* command execution failed */
155 #define EXEXIT 4 /* exit the shell */
156 #define EXSIG 5 /* trapped signal in wait(1) */
159 char nullstr[1]; /* zero length string */
162 #define eflag optlist[0]
163 #define fflag optlist[1]
164 #define Iflag optlist[2]
165 #define iflag optlist[3]
166 #define mflag optlist[4]
167 #define nflag optlist[5]
168 #define sflag optlist[6]
169 #define xflag optlist[7]
170 #define vflag optlist[8]
171 #define Cflag optlist[9]
172 #define aflag optlist[10]
173 #define bflag optlist[11]
174 #define uflag optlist[12]
175 #define viflag optlist[13]
177 #define nolog optlist[14]
178 #define debug optlist[15]
181 /* trap handler commands */
183 * Sigmode records the current value of the signal handlers for the various
184 * modes. A value of zero means that the current handler is not known.
185 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
187 char sigmode[NSIG - 1];
188 #define S_DFL 1 /* default signal handling (SIG_DFL) */
189 #define S_CATCH 2 /* signal is caught */
190 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
191 #define S_HARD_IGN 4 /* signal is ignored permenantly */
193 /* indicates specified signal received */
194 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
197 /* Rarely referenced stuff */
198 #if ENABLE_ASH_RANDOM_SUPPORT
199 /* Random number generators */
200 int32_t random_galois_LFSR; /* Galois LFSR (fast but weak). signed! */
201 uint32_t random_LCG; /* LCG (fast but weak) */
203 pid_t backgndpid; /* pid of last background process */
204 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
206 extern struct globals_misc *const ash_ptr_to_globals_misc;
207 #define G_misc (*ash_ptr_to_globals_misc)
208 #define rootpid (G_misc.rootpid )
209 #define shlvl (G_misc.shlvl )
210 #define minusc (G_misc.minusc )
211 #define curdir (G_misc.curdir )
212 #define physdir (G_misc.physdir )
213 #define arg0 (G_misc.arg0 )
214 #define exception_handler (G_misc.exception_handler)
215 #define exception_type (G_misc.exception_type )
216 #define suppress_int (G_misc.suppress_int )
217 #define pending_int (G_misc.pending_int )
218 #define pending_sig (G_misc.pending_sig )
219 #define isloginsh (G_misc.isloginsh )
220 #define nullstr (G_misc.nullstr )
221 #define optlist (G_misc.optlist )
222 #define sigmode (G_misc.sigmode )
223 #define gotsig (G_misc.gotsig )
224 #define trap (G_misc.trap )
225 #define random_galois_LFSR (G_misc.random_galois_LFSR)
226 #define random_LCG (G_misc.random_LCG )
227 #define backgndpid (G_misc.backgndpid )
228 #define job_warning (G_misc.job_warning)
229 #define INIT_G_misc() do { \
230 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
237 /* ============ DEBUG */
239 static void trace_printf(const char *fmt, ...);
240 static void trace_vprintf(const char *fmt, va_list va);
241 # define TRACE(param) trace_printf param
242 # define TRACEV(param) trace_vprintf param
243 # define close(fd) do { \
245 if (close(dfd) < 0) \
246 bb_error_msg("bug on %d: closing %d(0x%x)", \
247 __LINE__, dfd, dfd); \
250 # define TRACE(param)
251 # define TRACEV(param)
255 /* ============ Utility functions */
256 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
258 /* C99 says: "char" declaration may be signed or unsigned by default */
259 #define signed_char2int(sc) ((int)(signed char)(sc))
261 static int isdigit_str9(const char *str)
263 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
264 while (--maxlen && isdigit(*str))
266 return (*str == '\0');
270 /* ============ Interrupts / exceptions */
272 * These macros allow the user to suspend the handling of interrupt signals
273 * over a period of time. This is similar to SIGHOLD or to sigblock, but
274 * much more efficient and portable. (But hacking the kernel is so much
275 * more fun than worrying about efficiency and portability. :-))
277 #define INT_OFF do { \
283 * Called to raise an exception. Since C doesn't include exceptions, we
284 * just do a longjmp to the exception handler. The type of exception is
285 * stored in the global variable "exception_type".
287 static void raise_exception(int) NORETURN;
289 raise_exception(int e)
292 if (exception_handler == NULL)
297 longjmp(exception_handler->loc, 1);
300 #define raise_exception(e) do { \
301 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
302 raise_exception(e); \
307 * Called from trap.c when a SIGINT is received. (If the user specifies
308 * that SIGINT is to be trapped or ignored using the trap builtin, then
309 * this routine is not called.) Suppressint is nonzero when interrupts
310 * are held using the INT_OFF macro. (The test for iflag is just
311 * defensive programming.)
313 static void raise_interrupt(void) NORETURN;
315 raise_interrupt(void)
320 /* Signal is not automatically unmasked after it is raised,
321 * do it ourself - unmask all signals */
322 sigprocmask_allsigs(SIG_UNBLOCK);
323 /* pending_sig = 0; - now done in onsig() */
326 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
327 if (!(rootshell && iflag)) {
328 /* Kill ourself with SIGINT */
329 signal(SIGINT, SIG_DFL);
334 raise_exception(ex_type);
338 #define raise_interrupt() do { \
339 TRACE(("raising interrupt on line %d\n", __LINE__)); \
344 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
348 if (--suppress_int == 0 && pending_int) {
352 #define INT_ON int_on()
353 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
361 #define FORCE_INT_ON force_int_on()
363 #define SAVE_INT(v) ((v) = suppress_int)
365 #define RESTORE_INT(v) do { \
367 suppress_int = (v); \
368 if (suppress_int == 0 && pending_int) \
373 /* ============ Stdout/stderr output */
376 outstr(const char *p, FILE *file)
384 flush_stdout_stderr(void)
401 outcslow(int c, FILE *dest)
409 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
411 out1fmt(const char *fmt, ...)
418 r = vprintf(fmt, ap);
424 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
426 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
433 ret = vsnprintf(outbuf, length, fmt, ap);
440 out1str(const char *p)
446 out2str(const char *p)
453 /* ============ Parser structures */
455 /* control characters in argument strings */
456 #define CTLESC ((unsigned char)'\201') /* escape next character */
457 #define CTLVAR ((unsigned char)'\202') /* variable defn */
458 #define CTLENDVAR ((unsigned char)'\203')
459 #define CTLBACKQ ((unsigned char)'\204')
460 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
461 /* CTLBACKQ | CTLQUOTE == '\205' */
462 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
463 #define CTLENDARI ((unsigned char)'\207')
464 #define CTLQUOTEMARK ((unsigned char)'\210')
466 /* variable substitution byte (follows CTLVAR) */
467 #define VSTYPE 0x0f /* type of variable substitution */
468 #define VSNUL 0x10 /* colon--treat the empty string as unset */
469 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
471 /* values of VSTYPE field */
472 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
473 #define VSMINUS 0x2 /* ${var-text} */
474 #define VSPLUS 0x3 /* ${var+text} */
475 #define VSQUESTION 0x4 /* ${var?message} */
476 #define VSASSIGN 0x5 /* ${var=text} */
477 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
478 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
479 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
480 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
481 #define VSLENGTH 0xa /* ${#var} */
482 #if ENABLE_ASH_BASH_COMPAT
483 #define VSSUBSTR 0xc /* ${var:position:length} */
484 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
485 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
488 static const char dolatstr[] ALIGN1 = {
489 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
509 #if ENABLE_ASH_BASH_COMPAT
526 smallint type; /* Nxxxx */
529 union node *redirect;
534 smallint pipe_backgnd;
535 struct nodelist *cmdlist;
541 union node *redirect;
554 union node *elsepart;
581 struct nodelist *backquote;
584 /* nfile and ndup layout must match!
585 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
586 * that it is actually NTO2 (>&file), and change its type.
603 char *_unused_expfname;
622 struct nredir nredir;
623 struct nbinary nbinary;
627 struct nclist nclist;
636 * NODE_EOF is returned by parsecmd when it encounters an end of file.
637 * It must be distinct from NULL.
639 #define NODE_EOF ((union node *) -1L)
642 struct nodelist *next;
655 freefunc(struct funcnode *f)
657 if (f && --f->count < 0)
662 /* ============ Debugging output */
666 static FILE *tracefile;
669 trace_printf(const char *fmt, ...)
676 fprintf(tracefile, "%u ", (int) time(NULL));
678 fprintf(tracefile, "[%u] ", (int) getpid());
680 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
682 vfprintf(tracefile, fmt, va);
687 trace_vprintf(const char *fmt, va_list va)
692 fprintf(tracefile, "%u ", (int) time(NULL));
694 fprintf(tracefile, "[%u] ", (int) getpid());
696 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
697 vfprintf(tracefile, fmt, va);
701 trace_puts(const char *s)
709 trace_puts_quoted(char *s)
716 putc('"', tracefile);
717 for (p = s; *p; p++) {
719 case '\n': c = 'n'; goto backslash;
720 case '\t': c = 't'; goto backslash;
721 case '\r': c = 'r'; goto backslash;
722 case '"': c = '"'; goto backslash;
723 case '\\': c = '\\'; goto backslash;
724 case CTLESC: c = 'e'; goto backslash;
725 case CTLVAR: c = 'v'; goto backslash;
726 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
727 case CTLBACKQ: c = 'q'; goto backslash;
728 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
730 putc('\\', tracefile);
734 if (*p >= ' ' && *p <= '~')
737 putc('\\', tracefile);
738 putc(*p >> 6 & 03, tracefile);
739 putc(*p >> 3 & 07, tracefile);
740 putc(*p & 07, tracefile);
745 putc('"', tracefile);
749 trace_puts_args(char **ap)
756 trace_puts_quoted(*ap);
758 putc('\n', tracefile);
761 putc(' ', tracefile);
776 /* leave open because libedit might be using it */
779 strcpy(s, "./trace");
781 if (!freopen(s, "a", tracefile)) {
782 fprintf(stderr, "Can't re-open %s\n", s);
787 tracefile = fopen(s, "a");
788 if (tracefile == NULL) {
789 fprintf(stderr, "Can't open %s\n", s);
795 flags = fcntl(fileno(tracefile), F_GETFL);
797 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
799 setlinebuf(tracefile);
800 fputs("\nTracing started.\n", tracefile);
804 indent(int amount, char *pfx, FILE *fp)
808 for (i = 0; i < amount; i++) {
809 if (pfx && i == amount - 1)
815 /* little circular references here... */
816 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
819 sharg(union node *arg, FILE *fp)
822 struct nodelist *bqlist;
825 if (arg->type != NARG) {
826 out1fmt("<node type %d>\n", arg->type);
829 bqlist = arg->narg.backquote;
830 for (p = arg->narg.text; *p; p++) {
839 if (subtype == VSLENGTH)
848 switch (subtype & VSTYPE) {
881 out1fmt("<subtype %d>", subtype);
888 case CTLBACKQ|CTLQUOTE:
891 shtree(bqlist->n, -1, NULL, fp);
902 shcmd(union node *cmd, FILE *fp)
910 for (np = cmd->ncmd.args; np; np = np->narg.next) {
916 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
920 switch (np->nfile.type) {
921 case NTO: s = ">>"+1; dftfd = 1; break;
922 case NCLOBBER: s = ">|"; dftfd = 1; break;
923 case NAPPEND: s = ">>"; dftfd = 1; break;
924 #if ENABLE_ASH_BASH_COMPAT
927 case NTOFD: s = ">&"; dftfd = 1; break;
928 case NFROM: s = "<"; break;
929 case NFROMFD: s = "<&"; break;
930 case NFROMTO: s = "<>"; break;
931 default: s = "*error*"; break;
933 if (np->nfile.fd != dftfd)
934 fprintf(fp, "%d", np->nfile.fd);
936 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
937 fprintf(fp, "%d", np->ndup.dupfd);
939 sharg(np->nfile.fname, fp);
946 shtree(union node *n, int ind, char *pfx, FILE *fp)
954 indent(ind, pfx, fp);
971 shtree(n->nbinary.ch1, ind, NULL, fp);
974 shtree(n->nbinary.ch2, ind, NULL, fp);
982 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
983 shtree(lp->n, 0, NULL, fp);
987 if (n->npipe.pipe_backgnd)
993 fprintf(fp, "<node type %d>", n->type);
1001 showtree(union node *n)
1003 trace_puts("showtree called\n");
1004 shtree(n, 1, NULL, stderr);
1010 /* ============ Parser data */
1013 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1016 struct strlist *next;
1023 struct strpush *prev; /* preceding string on stack */
1025 int prev_left_in_line;
1026 #if ENABLE_ASH_ALIAS
1027 struct alias *ap; /* if push was associated with an alias */
1029 char *string; /* remember the string since it may change */
1033 struct parsefile *prev; /* preceding file on stack */
1034 int linno; /* current line */
1035 int fd; /* file descriptor (or -1 if string) */
1036 int left_in_line; /* number of chars left in this line */
1037 int left_in_buffer; /* number of chars left in this buffer past the line */
1038 char *next_to_pgetc; /* next char in buffer */
1039 char *buf; /* input buffer */
1040 struct strpush *strpush; /* for pushing strings at this level */
1041 struct strpush basestrpush; /* so pushing one is fast */
1044 static struct parsefile basepf; /* top level input file */
1045 static struct parsefile *g_parsefile = &basepf; /* current input file */
1046 static int startlinno; /* line # where last token started */
1047 static char *commandname; /* currently executing command */
1048 static struct strlist *cmdenviron; /* environment for builtin command */
1049 static uint8_t exitstatus; /* exit status of last command */
1052 /* ============ Message printing */
1055 ash_vmsg(const char *msg, va_list ap)
1057 fprintf(stderr, "%s: ", arg0);
1059 if (strcmp(arg0, commandname))
1060 fprintf(stderr, "%s: ", commandname);
1061 if (!iflag || g_parsefile->fd)
1062 fprintf(stderr, "line %d: ", startlinno);
1064 vfprintf(stderr, msg, ap);
1065 outcslow('\n', stderr);
1069 * Exverror is called to raise the error exception. If the second argument
1070 * is not NULL then error prints an error message using printf style
1071 * formatting. It then raises the error exception.
1073 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1075 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1079 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1081 TRACE(("\") pid=%d\n", getpid()));
1083 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1088 flush_stdout_stderr();
1089 raise_exception(cond);
1093 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1095 ash_msg_and_raise_error(const char *msg, ...)
1100 ash_vmsg_and_raise(EXERROR, msg, ap);
1105 static void raise_error_syntax(const char *) NORETURN;
1107 raise_error_syntax(const char *msg)
1109 ash_msg_and_raise_error("syntax error: %s", msg);
1113 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1115 ash_msg_and_raise(int cond, const char *msg, ...)
1120 ash_vmsg_and_raise(cond, msg, ap);
1126 * error/warning routines for external builtins
1129 ash_msg(const char *fmt, ...)
1139 * Return a string describing an error. The returned string may be a
1140 * pointer to a static buffer that will be overwritten on the next call.
1141 * Action describes the operation that got the error.
1144 errmsg(int e, const char *em)
1146 if (e == ENOENT || e == ENOTDIR) {
1153 /* ============ Memory allocation */
1156 * It appears that grabstackstr() will barf with such alignments
1157 * because stalloc() will return a string allocated in a new stackblock.
1159 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1161 /* Most machines require the value returned from malloc to be aligned
1162 * in some way. The following macro will get this right
1163 * on many machines. */
1164 SHELL_SIZE = sizeof(union {int i; char *cp; double d; }) - 1,
1165 /* Minimum size of a block */
1166 MINSIZE = SHELL_ALIGN(504),
1169 struct stack_block {
1170 struct stack_block *prev;
1171 char space[MINSIZE];
1175 struct stack_block *stackp;
1178 struct stackmark *marknext;
1182 struct globals_memstack {
1183 struct stack_block *g_stackp; // = &stackbase;
1184 struct stackmark *markp;
1185 char *g_stacknxt; // = stackbase.space;
1186 char *sstrend; // = stackbase.space + MINSIZE;
1187 size_t g_stacknleft; // = MINSIZE;
1188 int herefd; // = -1;
1189 struct stack_block stackbase;
1191 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1192 #define G_memstack (*ash_ptr_to_globals_memstack)
1193 #define g_stackp (G_memstack.g_stackp )
1194 #define markp (G_memstack.markp )
1195 #define g_stacknxt (G_memstack.g_stacknxt )
1196 #define sstrend (G_memstack.sstrend )
1197 #define g_stacknleft (G_memstack.g_stacknleft)
1198 #define herefd (G_memstack.herefd )
1199 #define stackbase (G_memstack.stackbase )
1200 #define INIT_G_memstack() do { \
1201 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1203 g_stackp = &stackbase; \
1204 g_stacknxt = stackbase.space; \
1205 g_stacknleft = MINSIZE; \
1206 sstrend = stackbase.space + MINSIZE; \
1210 #define stackblock() ((void *)g_stacknxt)
1211 #define stackblocksize() g_stacknleft
1215 ckrealloc(void * p, size_t nbytes)
1217 p = realloc(p, nbytes);
1219 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1224 ckmalloc(size_t nbytes)
1226 return ckrealloc(NULL, nbytes);
1230 ckzalloc(size_t nbytes)
1232 return memset(ckmalloc(nbytes), 0, nbytes);
1236 * Make a copy of a string in safe storage.
1239 ckstrdup(const char *s)
1241 char *p = strdup(s);
1243 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1248 * Parse trees for commands are allocated in lifo order, so we use a stack
1249 * to make this more efficient, and also to avoid all sorts of exception
1250 * handling code to handle interrupts in the middle of a parse.
1252 * The size 504 was chosen because the Ultrix malloc handles that size
1256 stalloc(size_t nbytes)
1261 aligned = SHELL_ALIGN(nbytes);
1262 if (aligned > g_stacknleft) {
1265 struct stack_block *sp;
1267 blocksize = aligned;
1268 if (blocksize < MINSIZE)
1269 blocksize = MINSIZE;
1270 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1271 if (len < blocksize)
1272 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1275 sp->prev = g_stackp;
1276 g_stacknxt = sp->space;
1277 g_stacknleft = blocksize;
1278 sstrend = g_stacknxt + blocksize;
1283 g_stacknxt += aligned;
1284 g_stacknleft -= aligned;
1289 stzalloc(size_t nbytes)
1291 return memset(stalloc(nbytes), 0, nbytes);
1298 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1299 write(STDERR_FILENO, "stunalloc\n", 10);
1303 g_stacknleft += g_stacknxt - (char *)p;
1308 * Like strdup but works with the ash stack.
1311 ststrdup(const char *p)
1313 size_t len = strlen(p) + 1;
1314 return memcpy(stalloc(len), p, len);
1318 setstackmark(struct stackmark *mark)
1320 mark->stackp = g_stackp;
1321 mark->stacknxt = g_stacknxt;
1322 mark->stacknleft = g_stacknleft;
1323 mark->marknext = markp;
1328 popstackmark(struct stackmark *mark)
1330 struct stack_block *sp;
1336 markp = mark->marknext;
1337 while (g_stackp != mark->stackp) {
1339 g_stackp = sp->prev;
1342 g_stacknxt = mark->stacknxt;
1343 g_stacknleft = mark->stacknleft;
1344 sstrend = mark->stacknxt + mark->stacknleft;
1349 * When the parser reads in a string, it wants to stick the string on the
1350 * stack and only adjust the stack pointer when it knows how big the
1351 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1352 * of space on top of the stack and stackblocklen returns the length of
1353 * this block. Growstackblock will grow this space by at least one byte,
1354 * possibly moving it (like realloc). Grabstackblock actually allocates the
1355 * part of the block that has been used.
1358 growstackblock(void)
1362 newlen = g_stacknleft * 2;
1363 if (newlen < g_stacknleft)
1364 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1368 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1369 struct stack_block *oldstackp;
1370 struct stackmark *xmark;
1371 struct stack_block *sp;
1372 struct stack_block *prevstackp;
1376 oldstackp = g_stackp;
1378 prevstackp = sp->prev;
1379 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1380 sp = ckrealloc(sp, grosslen);
1381 sp->prev = prevstackp;
1383 g_stacknxt = sp->space;
1384 g_stacknleft = newlen;
1385 sstrend = sp->space + newlen;
1388 * Stack marks pointing to the start of the old block
1389 * must be relocated to point to the new block
1392 while (xmark != NULL && xmark->stackp == oldstackp) {
1393 xmark->stackp = g_stackp;
1394 xmark->stacknxt = g_stacknxt;
1395 xmark->stacknleft = g_stacknleft;
1396 xmark = xmark->marknext;
1400 char *oldspace = g_stacknxt;
1401 size_t oldlen = g_stacknleft;
1402 char *p = stalloc(newlen);
1404 /* free the space we just allocated */
1405 g_stacknxt = memcpy(p, oldspace, oldlen);
1406 g_stacknleft += newlen;
1411 grabstackblock(size_t len)
1413 len = SHELL_ALIGN(len);
1415 g_stacknleft -= len;
1419 * The following routines are somewhat easier to use than the above.
1420 * The user declares a variable of type STACKSTR, which may be declared
1421 * to be a register. The macro STARTSTACKSTR initializes things. Then
1422 * the user uses the macro STPUTC to add characters to the string. In
1423 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1424 * grown as necessary. When the user is done, she can just leave the
1425 * string there and refer to it using stackblock(). Or she can allocate
1426 * the space for it using grabstackstr(). If it is necessary to allow
1427 * someone else to use the stack temporarily and then continue to grow
1428 * the string, the user should use grabstack to allocate the space, and
1429 * then call ungrabstr(p) to return to the previous mode of operation.
1431 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1432 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1433 * is space for at least one character.
1438 size_t len = stackblocksize();
1439 if (herefd >= 0 && len >= 1024) {
1440 full_write(herefd, stackblock(), len);
1441 return stackblock();
1444 return (char *)stackblock() + len;
1448 * Called from CHECKSTRSPACE.
1451 makestrspace(size_t newlen, char *p)
1453 size_t len = p - g_stacknxt;
1454 size_t size = stackblocksize();
1459 size = stackblocksize();
1461 if (nleft >= newlen)
1465 return (char *)stackblock() + len;
1469 stack_nputstr(const char *s, size_t n, char *p)
1471 p = makestrspace(n, p);
1472 p = (char *)memcpy(p, s, n) + n;
1477 stack_putstr(const char *s, char *p)
1479 return stack_nputstr(s, strlen(s), p);
1483 _STPUTC(int c, char *p)
1491 #define STARTSTACKSTR(p) ((p) = stackblock())
1492 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1493 #define CHECKSTRSPACE(n, p) do { \
1496 size_t m = sstrend - q; \
1498 (p) = makestrspace(l, q); \
1500 #define USTPUTC(c, p) (*(p)++ = (c))
1501 #define STACKSTRNUL(p) do { \
1502 if ((p) == sstrend) \
1503 (p) = growstackstr(); \
1506 #define STUNPUTC(p) (--(p))
1507 #define STTOPC(p) ((p)[-1])
1508 #define STADJUST(amount, p) ((p) += (amount))
1510 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1511 #define ungrabstackstr(s, p) stunalloc(s)
1512 #define stackstrend() ((void *)sstrend)
1515 /* ============ String helpers */
1518 * prefix -- see if pfx is a prefix of string.
1521 prefix(const char *string, const char *pfx)
1524 if (*pfx++ != *string++)
1527 return (char *) string;
1531 * Check for a valid number. This should be elsewhere.
1534 is_number(const char *p)
1539 } while (*++p != '\0');
1544 * Convert a string of digits to an integer, printing an error message on
1548 number(const char *s)
1551 ash_msg_and_raise_error(msg_illnum, s);
1556 * Produce a possibly single quoted string suitable as input to the shell.
1557 * The return string is allocated on the stack.
1560 single_quote(const char *s)
1570 len = strchrnul(s, '\'') - s;
1572 q = p = makestrspace(len + 3, p);
1575 q = (char *)memcpy(q, s, len) + len;
1581 len = strspn(s, "'");
1585 q = p = makestrspace(len + 3, p);
1588 q = (char *)memcpy(q, s, len) + len;
1597 return stackblock();
1601 /* ============ nextopt */
1603 static char **argptr; /* argument list for builtin commands */
1604 static char *optionarg; /* set by nextopt (like getopt) */
1605 static char *optptr; /* used by nextopt */
1608 * XXX - should get rid of. Have all builtins use getopt(3).
1609 * The library getopt must have the BSD extension static variable
1610 * "optreset", otherwise it can't be used within the shell safely.
1612 * Standard option processing (a la getopt) for builtin routines.
1613 * The only argument that is passed to nextopt is the option string;
1614 * the other arguments are unnecessary. It returns the character,
1615 * or '\0' on end of input.
1618 nextopt(const char *optstring)
1625 if (p == NULL || *p == '\0') {
1626 /* We ate entire "-param", take next one */
1632 if (*++p == '\0') /* just "-" ? */
1635 if (LONE_DASH(p)) /* "--" ? */
1637 /* p => next "-param" */
1639 /* p => some option char in the middle of a "-param" */
1641 for (q = optstring; *q != c;) {
1643 ash_msg_and_raise_error("illegal option -%c", c);
1651 ash_msg_and_raise_error("no arg for -%c option", c);
1661 /* ============ Shell variables */
1664 * The parsefile structure pointed to by the global variable parsefile
1665 * contains information about the current file being read.
1668 int nparam; /* # of positional parameters (without $0) */
1669 #if ENABLE_ASH_GETOPTS
1670 int optind; /* next parameter to be processed by getopts */
1671 int optoff; /* used by getopts */
1673 unsigned char malloced; /* if parameter list dynamically allocated */
1674 char **p; /* parameter list */
1678 * Free the list of positional parameters.
1681 freeparam(volatile struct shparam *param)
1683 if (param->malloced) {
1685 ap = ap1 = param->p;
1692 #if ENABLE_ASH_GETOPTS
1693 static void FAST_FUNC getoptsreset(const char *value);
1697 struct var *next; /* next entry in hash list */
1698 int flags; /* flags are defined above */
1699 const char *text; /* name=value */
1700 void (*func)(const char *) FAST_FUNC; /* function to be called when */
1701 /* the variable gets set/unset */
1705 struct localvar *next; /* next local variable in list */
1706 struct var *vp; /* the variable that was made local */
1707 int flags; /* saved flags */
1708 const char *text; /* saved text */
1712 #define VEXPORT 0x01 /* variable is exported */
1713 #define VREADONLY 0x02 /* variable cannot be modified */
1714 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1715 #define VTEXTFIXED 0x08 /* text is statically allocated */
1716 #define VSTACK 0x10 /* text is allocated on the stack */
1717 #define VUNSET 0x20 /* the variable is not set */
1718 #define VNOFUNC 0x40 /* don't call the callback function */
1719 #define VNOSET 0x80 /* do not set variable - just readonly test */
1720 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1721 #if ENABLE_ASH_RANDOM_SUPPORT
1722 # define VDYNAMIC 0x200 /* dynamic variable */
1728 static const char defifsvar[] ALIGN1 = "IFS= \t\n";
1729 #define defifs (defifsvar + 4)
1731 static const char defifs[] ALIGN1 = " \t\n";
1735 /* Need to be before varinit_data[] */
1736 #if ENABLE_LOCALE_SUPPORT
1737 static void FAST_FUNC
1738 change_lc_all(const char *value)
1740 if (value && *value != '\0')
1741 setlocale(LC_ALL, value);
1743 static void FAST_FUNC
1744 change_lc_ctype(const char *value)
1746 if (value && *value != '\0')
1747 setlocale(LC_CTYPE, value);
1751 static void chkmail(void);
1752 static void changemail(const char *) FAST_FUNC;
1754 static void changepath(const char *) FAST_FUNC;
1755 #if ENABLE_ASH_RANDOM_SUPPORT
1756 static void change_random(const char *) FAST_FUNC;
1759 static const struct {
1762 void (*func)(const char *) FAST_FUNC;
1763 } varinit_data[] = {
1765 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1767 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
1770 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1771 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1773 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1774 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1775 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1776 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1777 #if ENABLE_ASH_GETOPTS
1778 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1780 #if ENABLE_ASH_RANDOM_SUPPORT
1781 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
1783 #if ENABLE_LOCALE_SUPPORT
1784 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1785 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
1787 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1788 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
1794 struct globals_var {
1795 struct shparam shellparam; /* $@ current positional parameters */
1796 struct redirtab *redirlist;
1798 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1799 struct var *vartab[VTABSIZE];
1800 struct var varinit[ARRAY_SIZE(varinit_data)];
1802 extern struct globals_var *const ash_ptr_to_globals_var;
1803 #define G_var (*ash_ptr_to_globals_var)
1804 #define shellparam (G_var.shellparam )
1805 //#define redirlist (G_var.redirlist )
1806 #define g_nullredirs (G_var.g_nullredirs )
1807 #define preverrout_fd (G_var.preverrout_fd)
1808 #define vartab (G_var.vartab )
1809 #define varinit (G_var.varinit )
1810 #define INIT_G_var() do { \
1812 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1814 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1815 varinit[i].flags = varinit_data[i].flags; \
1816 varinit[i].text = varinit_data[i].text; \
1817 varinit[i].func = varinit_data[i].func; \
1821 #define vifs varinit[0]
1823 # define vmail (&vifs)[1]
1824 # define vmpath (&vmail)[1]
1825 # define vpath (&vmpath)[1]
1827 # define vpath (&vifs)[1]
1829 #define vps1 (&vpath)[1]
1830 #define vps2 (&vps1)[1]
1831 #define vps4 (&vps2)[1]
1832 #if ENABLE_ASH_GETOPTS
1833 # define voptind (&vps4)[1]
1834 # if ENABLE_ASH_RANDOM_SUPPORT
1835 # define vrandom (&voptind)[1]
1838 # if ENABLE_ASH_RANDOM_SUPPORT
1839 # define vrandom (&vps4)[1]
1844 * The following macros access the values of the above variables.
1845 * They have to skip over the name. They return the null string
1846 * for unset variables.
1848 #define ifsval() (vifs.text + 4)
1849 #define ifsset() ((vifs.flags & VUNSET) == 0)
1851 # define mailval() (vmail.text + 5)
1852 # define mpathval() (vmpath.text + 9)
1853 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1855 #define pathval() (vpath.text + 5)
1856 #define ps1val() (vps1.text + 4)
1857 #define ps2val() (vps2.text + 4)
1858 #define ps4val() (vps4.text + 4)
1859 #if ENABLE_ASH_GETOPTS
1860 # define optindval() (voptind.text + 7)
1864 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1865 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1867 #if ENABLE_ASH_GETOPTS
1868 static void FAST_FUNC
1869 getoptsreset(const char *value)
1871 shellparam.optind = number(value);
1872 shellparam.optoff = -1;
1877 * Return of a legal variable name (a letter or underscore followed by zero or
1878 * more letters, underscores, and digits).
1881 endofname(const char *name)
1889 if (!is_in_name(*p))
1896 * Compares two strings up to the first = or '\0'. The first
1897 * string must be terminated by '='; the second may be terminated by
1898 * either '=' or '\0'.
1901 varcmp(const char *p, const char *q)
1905 while ((c = *p) == (d = *q)) {
1920 varequal(const char *a, const char *b)
1922 return !varcmp(a, b);
1926 * Find the appropriate entry in the hash table from the name.
1928 static struct var **
1929 hashvar(const char *p)
1933 hashval = ((unsigned char) *p) << 4;
1934 while (*p && *p != '=')
1935 hashval += (unsigned char) *p++;
1936 return &vartab[hashval % VTABSIZE];
1940 vpcmp(const void *a, const void *b)
1942 return varcmp(*(const char **)a, *(const char **)b);
1946 * This routine initializes the builtin variables.
1956 * PS1 depends on uid
1958 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1959 vps1.text = "PS1=\\w \\$ ";
1962 vps1.text = "PS1=# ";
1965 end = vp + ARRAY_SIZE(varinit);
1967 vpp = hashvar(vp->text);
1970 } while (++vp < end);
1973 static struct var **
1974 findvar(struct var **vpp, const char *name)
1976 for (; *vpp; vpp = &(*vpp)->next) {
1977 if (varequal((*vpp)->text, name)) {
1985 * Find the value of a variable. Returns NULL if not set.
1988 lookupvar(const char *name)
1992 v = *findvar(hashvar(name), name);
1994 #if ENABLE_ASH_RANDOM_SUPPORT
1996 * Dynamic variables are implemented roughly the same way they are
1997 * in bash. Namely, they're "special" so long as they aren't unset.
1998 * As soon as they're unset, they're no longer dynamic, and dynamic
1999 * lookup will no longer happen at that point. -- PFM.
2001 if ((v->flags & VDYNAMIC))
2004 if (!(v->flags & VUNSET))
2005 return strchrnul(v->text, '=') + 1;
2011 * Search the environment of a builtin command.
2014 bltinlookup(const char *name)
2018 for (sp = cmdenviron; sp; sp = sp->next) {
2019 if (varequal(sp->text, name))
2020 return strchrnul(sp->text, '=') + 1;
2022 return lookupvar(name);
2026 * Same as setvar except that the variable and value are passed in
2027 * the first argument as name=value. Since the first argument will
2028 * be actually stored in the table, it should not be a string that
2030 * Called with interrupts off.
2033 setvareq(char *s, int flags)
2035 struct var *vp, **vpp;
2038 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2039 vp = *findvar(vpp, s);
2041 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2044 if (flags & VNOSAVE)
2047 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2053 if (vp->func && (flags & VNOFUNC) == 0)
2054 (*vp->func)(strchrnul(s, '=') + 1);
2056 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2057 free((char*)vp->text);
2059 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2064 vp = ckzalloc(sizeof(*vp));
2066 /*vp->func = NULL; - ckzalloc did it */
2069 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2076 * Set the value of a variable. The flags argument is ored with the
2077 * flags of the variable. If val is NULL, the variable is unset.
2080 setvar(const char *name, const char *val, int flags)
2087 q = endofname(name);
2088 p = strchrnul(q, '=');
2090 if (!namelen || p != q)
2091 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2096 vallen = strlen(val);
2099 nameeq = ckmalloc(namelen + vallen + 2);
2100 p = (char *)memcpy(nameeq, name, namelen) + namelen;
2103 p = (char *)memcpy(p, val, vallen) + vallen;
2106 setvareq(nameeq, flags | VNOSAVE);
2110 #if ENABLE_ASH_GETOPTS
2112 * Safe version of setvar, returns 1 on success 0 on failure.
2115 setvarsafe(const char *name, const char *val, int flags)
2118 volatile int saveint;
2119 struct jmploc *volatile savehandler = exception_handler;
2120 struct jmploc jmploc;
2123 if (setjmp(jmploc.loc))
2126 exception_handler = &jmploc;
2127 setvar(name, val, flags);
2130 exception_handler = savehandler;
2131 RESTORE_INT(saveint);
2137 * Unset the specified variable.
2140 unsetvar(const char *s)
2146 vpp = findvar(hashvar(s), s);
2150 int flags = vp->flags;
2153 if (flags & VREADONLY)
2155 #if ENABLE_ASH_RANDOM_SUPPORT
2156 vp->flags &= ~VDYNAMIC;
2160 if ((flags & VSTRFIXED) == 0) {
2162 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2163 free((char*)vp->text);
2169 vp->flags &= ~VEXPORT;
2179 * Process a linked list of variable assignments.
2182 listsetvar(struct strlist *list_set_var, int flags)
2184 struct strlist *lp = list_set_var;
2190 setvareq(lp->text, flags);
2197 * Generate a list of variables satisfying the given conditions.
2200 listvars(int on, int off, char ***end)
2211 for (vp = *vpp; vp; vp = vp->next) {
2212 if ((vp->flags & mask) == on) {
2213 if (ep == stackstrend())
2214 ep = growstackstr();
2215 *ep++ = (char *) vp->text;
2218 } while (++vpp < vartab + VTABSIZE);
2219 if (ep == stackstrend())
2220 ep = growstackstr();
2224 return grabstackstr(ep);
2228 /* ============ Path search helper
2230 * The variable path (passed by reference) should be set to the start
2231 * of the path before the first call; path_advance will update
2232 * this value as it proceeds. Successive calls to path_advance will return
2233 * the possible path expansions in sequence. If an option (indicated by
2234 * a percent sign) appears in the path entry then the global variable
2235 * pathopt will be set to point to it; otherwise pathopt will be set to
2238 static const char *pathopt; /* set by path_advance */
2241 path_advance(const char **path, const char *name)
2251 for (p = start; *p && *p != ':' && *p != '%'; p++)
2253 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2254 while (stackblocksize() < len)
2258 memcpy(q, start, p - start);
2266 while (*p && *p != ':')
2273 return stalloc(len);
2277 /* ============ Prompt */
2279 static smallint doprompt; /* if set, prompt the user */
2280 static smallint needprompt; /* true if interactive and at start of line */
2282 #if ENABLE_FEATURE_EDITING
2283 static line_input_t *line_input_state;
2284 static const char *cmdedit_prompt;
2286 putprompt(const char *s)
2288 if (ENABLE_ASH_EXPAND_PRMT) {
2289 free((char*)cmdedit_prompt);
2290 cmdedit_prompt = ckstrdup(s);
2297 putprompt(const char *s)
2303 #if ENABLE_ASH_EXPAND_PRMT
2304 /* expandstr() needs parsing machinery, so it is far away ahead... */
2305 static const char *expandstr(const char *ps);
2307 #define expandstr(s) s
2311 setprompt(int whichprompt)
2314 #if ENABLE_ASH_EXPAND_PRMT
2315 struct stackmark smark;
2320 switch (whichprompt) {
2330 #if ENABLE_ASH_EXPAND_PRMT
2331 setstackmark(&smark);
2332 stalloc(stackblocksize());
2334 putprompt(expandstr(prompt));
2335 #if ENABLE_ASH_EXPAND_PRMT
2336 popstackmark(&smark);
2341 /* ============ The cd and pwd commands */
2343 #define CD_PHYSICAL 1
2353 while ((i = nextopt("LP")) != '\0') {
2355 flags ^= CD_PHYSICAL;
2364 * Update curdir (the name of the current directory) in response to a
2368 updatepwd(const char *dir)
2375 cdcomppath = ststrdup(dir);
2378 if (curdir == nullstr)
2380 new = stack_putstr(curdir, new);
2382 new = makestrspace(strlen(dir) + 2, new);
2383 lim = (char *)stackblock() + 1;
2387 if (new > lim && *lim == '/')
2392 if (dir[1] == '/' && dir[2] != '/') {
2398 p = strtok(cdcomppath, "/");
2402 if (p[1] == '.' && p[2] == '\0') {
2414 new = stack_putstr(p, new);
2422 return stackblock();
2426 * Find out what the current directory is. If we already know the current
2427 * directory, this routine returns immediately.
2432 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2433 return dir ? dir : nullstr;
2437 setpwd(const char *val, int setold)
2441 oldcur = dir = curdir;
2444 setvar("OLDPWD", oldcur, VEXPORT);
2447 if (physdir != nullstr) {
2448 if (physdir != oldcur)
2452 if (oldcur == val || !val) {
2458 dir = ckstrdup(val);
2459 if (oldcur != dir && oldcur != nullstr) {
2464 setvar("PWD", dir, VEXPORT);
2467 static void hashcd(void);
2470 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2471 * know that the current directory has changed.
2474 docd(const char *dest, int flags)
2476 const char *dir = 0;
2479 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2482 if (!(flags & CD_PHYSICAL)) {
2483 dir = updatepwd(dest);
2497 static int FAST_FUNC
2498 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2510 dest = bltinlookup(homestr);
2511 else if (LONE_DASH(dest)) {
2512 dest = bltinlookup("OLDPWD");
2534 path = bltinlookup("CDPATH");
2543 p = path_advance(&path, dest);
2544 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2548 if (!docd(p, flags))
2553 ash_msg_and_raise_error("can't cd to %s", dest);
2556 if (flags & CD_PRINT)
2557 out1fmt(snlfmt, curdir);
2561 static int FAST_FUNC
2562 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2565 const char *dir = curdir;
2569 if (physdir == nullstr)
2573 out1fmt(snlfmt, dir);
2578 /* ============ ... */
2581 #define IBUFSIZ COMMON_BUFSIZE
2582 /* buffer for top level input file */
2583 #define basebuf bb_common_bufsiz1
2585 /* Syntax classes */
2586 #define CWORD 0 /* character is nothing special */
2587 #define CNL 1 /* newline character */
2588 #define CBACK 2 /* a backslash character */
2589 #define CSQUOTE 3 /* single quote */
2590 #define CDQUOTE 4 /* double quote */
2591 #define CENDQUOTE 5 /* a terminating quote */
2592 #define CBQUOTE 6 /* backwards single quote */
2593 #define CVAR 7 /* a dollar sign */
2594 #define CENDVAR 8 /* a '}' character */
2595 #define CLP 9 /* a left paren in arithmetic */
2596 #define CRP 10 /* a right paren in arithmetic */
2597 #define CENDFILE 11 /* end of file */
2598 #define CCTL 12 /* like CWORD, except it must be escaped */
2599 #define CSPCL 13 /* these terminate a word */
2600 #define CIGN 14 /* character should be ignored */
2602 #if ENABLE_ASH_ALIAS
2606 #define PEOA_OR_PEOF PEOA
2610 #define PEOA_OR_PEOF PEOF
2613 /* number syntax index */
2614 #define BASESYNTAX 0 /* not in quotes */
2615 #define DQSYNTAX 1 /* in double quotes */
2616 #define SQSYNTAX 2 /* in single quotes */
2617 #define ARISYNTAX 3 /* in arithmetic */
2618 #define PSSYNTAX 4 /* prompt */
2620 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
2621 #define USE_SIT_FUNCTION
2624 #if ENABLE_SH_MATH_SUPPORT
2625 static const char S_I_T[][4] = {
2626 #if ENABLE_ASH_ALIAS
2627 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
2629 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2630 { CNL, CNL, CNL, CNL }, /* 2, \n */
2631 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2632 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2633 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2634 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2635 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2636 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2637 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2638 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2639 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
2640 #ifndef USE_SIT_FUNCTION
2641 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2642 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2643 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2647 static const char S_I_T[][3] = {
2648 #if ENABLE_ASH_ALIAS
2649 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
2651 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2652 { CNL, CNL, CNL }, /* 2, \n */
2653 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2654 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2655 { CVAR, CVAR, CWORD }, /* 5, $ */
2656 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2657 { CSPCL, CWORD, CWORD }, /* 7, ( */
2658 { CSPCL, CWORD, CWORD }, /* 8, ) */
2659 { CBACK, CBACK, CCTL }, /* 9, \ */
2660 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2661 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
2662 #ifndef USE_SIT_FUNCTION
2663 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2664 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2665 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2668 #endif /* SH_MATH_SUPPORT */
2670 #ifdef USE_SIT_FUNCTION
2673 SIT(int c, int syntax)
2675 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2676 #if ENABLE_ASH_ALIAS
2677 static const char syntax_index_table[] ALIGN1 = {
2678 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2679 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2680 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2684 static const char syntax_index_table[] ALIGN1 = {
2685 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2686 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2687 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2694 if (c == PEOF) { /* 2^8+2 */
2697 #if ENABLE_ASH_ALIAS
2698 if (c == PEOA) { /* 2^8+1 */
2703 if ((unsigned char)c >= CTLESC
2704 && (unsigned char)c <= CTLQUOTEMARK
2708 s = strchrnul(spec_symbls, c);
2712 indx = syntax_index_table[s - spec_symbls];
2714 return S_I_T[indx][syntax];
2717 #else /* !USE_SIT_FUNCTION */
2719 #if ENABLE_ASH_ALIAS
2720 #define CSPCL_CIGN_CIGN_CIGN 0
2721 #define CSPCL_CWORD_CWORD_CWORD 1
2722 #define CNL_CNL_CNL_CNL 2
2723 #define CWORD_CCTL_CCTL_CWORD 3
2724 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2725 #define CVAR_CVAR_CWORD_CVAR 5
2726 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2727 #define CSPCL_CWORD_CWORD_CLP 7
2728 #define CSPCL_CWORD_CWORD_CRP 8
2729 #define CBACK_CBACK_CCTL_CBACK 9
2730 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2731 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2732 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2733 #define CWORD_CWORD_CWORD_CWORD 13
2734 #define CCTL_CCTL_CCTL_CCTL 14
2736 #define CSPCL_CWORD_CWORD_CWORD 0
2737 #define CNL_CNL_CNL_CNL 1
2738 #define CWORD_CCTL_CCTL_CWORD 2
2739 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2740 #define CVAR_CVAR_CWORD_CVAR 4
2741 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2742 #define CSPCL_CWORD_CWORD_CLP 6
2743 #define CSPCL_CWORD_CWORD_CRP 7
2744 #define CBACK_CBACK_CCTL_CBACK 8
2745 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2746 #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2747 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2748 #define CWORD_CWORD_CWORD_CWORD 12
2749 #define CCTL_CCTL_CCTL_CCTL 13
2752 static const char syntax_index_table[258] = {
2753 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2754 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2755 #if ENABLE_ASH_ALIAS
2756 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2758 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2760 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2761 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2762 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2763 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2764 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2765 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2766 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2767 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2768 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2769 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2770 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2771 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2772 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2773 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2774 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2775 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2776 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2777 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2778 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2779 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2780 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2781 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2782 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2793 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2794 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2795 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2796 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2797 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2798 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2799 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2800 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2801 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2802 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2803 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2804 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2805 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2806 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2807 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2808 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2809 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2810 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2811 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2812 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2813 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2814 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2815 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2816 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2817 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2818 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2819 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2820 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2821 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2822 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2823 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2824 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2825 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2826 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2827 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2828 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2829 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2830 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2831 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2832 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2833 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2834 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2835 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2836 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2837 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2838 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2839 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2840 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2841 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2842 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2896 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2897 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2919 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2920 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2921 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2923 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2925 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2926 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2927 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2928 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2929 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2931 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2932 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2933 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2934 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2945 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2946 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2947 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2948 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2949 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2950 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2978 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2979 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2980 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2983 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3006 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3007 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3008 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3009 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3010 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3011 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3012 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3013 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
3016 #define SIT(c, syntax) (S_I_T[(int)syntax_index_table[(int)(c) + SYNBASE]][syntax])
3018 #endif /* USE_SIT_FUNCTION */
3021 /* ============ Alias handling */
3023 #if ENABLE_ASH_ALIAS
3025 #define ALIASINUSE 1
3036 static struct alias **atab; // [ATABSIZE];
3037 #define INIT_G_alias() do { \
3038 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3042 static struct alias **
3043 __lookupalias(const char *name) {
3044 unsigned int hashval;
3051 ch = (unsigned char)*p;
3055 ch = (unsigned char)*++p;
3057 app = &atab[hashval % ATABSIZE];
3059 for (; *app; app = &(*app)->next) {
3060 if (strcmp(name, (*app)->name) == 0) {
3068 static struct alias *
3069 lookupalias(const char *name, int check)
3071 struct alias *ap = *__lookupalias(name);
3073 if (check && ap && (ap->flag & ALIASINUSE))
3078 static struct alias *
3079 freealias(struct alias *ap)
3083 if (ap->flag & ALIASINUSE) {
3084 ap->flag |= ALIASDEAD;
3096 setalias(const char *name, const char *val)
3098 struct alias *ap, **app;
3100 app = __lookupalias(name);
3104 if (!(ap->flag & ALIASINUSE)) {
3107 ap->val = ckstrdup(val);
3108 ap->flag &= ~ALIASDEAD;
3111 ap = ckzalloc(sizeof(struct alias));
3112 ap->name = ckstrdup(name);
3113 ap->val = ckstrdup(val);
3114 /*ap->flag = 0; - ckzalloc did it */
3115 /*ap->next = NULL;*/
3122 unalias(const char *name)
3126 app = __lookupalias(name);
3130 *app = freealias(*app);
3141 struct alias *ap, **app;
3145 for (i = 0; i < ATABSIZE; i++) {
3147 for (ap = *app; ap; ap = *app) {
3148 *app = freealias(*app);
3158 printalias(const struct alias *ap)
3160 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3164 * TODO - sort output
3166 static int FAST_FUNC
3167 aliascmd(int argc UNUSED_PARAM, char **argv)
3176 for (i = 0; i < ATABSIZE; i++) {
3177 for (ap = atab[i]; ap; ap = ap->next) {
3183 while ((n = *++argv) != NULL) {
3184 v = strchr(n+1, '=');
3185 if (v == NULL) { /* n+1: funny ksh stuff */
3186 ap = *__lookupalias(n);
3188 fprintf(stderr, "%s: %s not found\n", "alias", n);
3201 static int FAST_FUNC
3202 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3206 while ((i = nextopt("a")) != '\0') {
3212 for (i = 0; *argptr; argptr++) {
3213 if (unalias(*argptr)) {
3214 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3222 #endif /* ASH_ALIAS */
3225 /* ============ jobs.c */
3227 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3230 #define FORK_NOJOB 2
3232 /* mode flags for showjob(s) */
3233 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3234 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3235 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3238 * A job structure contains information about a job. A job is either a
3239 * single process or a set of processes contained in a pipeline. In the
3240 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3244 pid_t pid; /* process id */
3245 int status; /* last process status from wait() */
3246 char *cmd; /* text of command being run */
3250 struct procstat ps0; /* status of process */
3251 struct procstat *ps; /* status or processes when more than one */
3253 int stopstatus; /* status of a stopped job */
3256 nprocs: 16, /* number of processes */
3258 #define JOBRUNNING 0 /* at least one proc running */
3259 #define JOBSTOPPED 1 /* all procs are stopped */
3260 #define JOBDONE 2 /* all procs are completed */
3262 sigint: 1, /* job was killed by SIGINT */
3263 jobctl: 1, /* job running under job control */
3265 waited: 1, /* true if this entry has been waited for */
3266 used: 1, /* true if this entry is in used */
3267 changed: 1; /* true if status has changed */
3268 struct job *prev_job; /* previous job */
3271 static struct job *makejob(/*union node *,*/ int);
3273 #define forkshell(job, node, mode) forkshell(job, mode)
3275 static int forkshell(struct job *, union node *, int);
3276 static int waitforjob(struct job *);
3279 enum { doing_jobctl = 0 };
3280 #define setjobctl(on) do {} while (0)
3282 static smallint doing_jobctl; //references:8
3283 static void setjobctl(int);
3290 ignoresig(int signo)
3292 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3293 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3294 /* No, need to do it */
3295 signal(signo, SIG_IGN);
3297 sigmode[signo - 1] = S_HARD_IGN;
3301 * Signal handler. Only one usage site - in setsignal()
3306 gotsig[signo - 1] = 1;
3308 if (signo == SIGINT && !trap[SIGINT]) {
3309 if (!suppress_int) {
3311 raise_interrupt(); /* does not return */
3315 pending_sig = signo;
3320 * Set the signal handler for the specified signal. The routine figures
3321 * out what it should be set to.
3324 setsignal(int signo)
3327 char cur_act, new_act;
3328 struct sigaction act;
3332 if (t != NULL) { /* trap for this sig is set */
3334 if (t[0] == '\0') /* trap is "": ignore this sig */
3338 if (rootshell && new_act == S_DFL) {
3341 if (iflag || minusc || sflag == 0)
3350 * "In all cases, bash ignores SIGQUIT. Non-builtin
3351 * commands run by bash have signal handlers
3352 * set to the values inherited by the shell
3353 * from its parent". */
3369 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3370 //whereas we have to restore it to what shell got on entry
3371 //from the parent. See comment above
3373 t = &sigmode[signo - 1];
3376 /* current setting is not yet known */
3377 if (sigaction(signo, NULL, &act)) {
3378 /* pretend it worked; maybe we should give a warning,
3379 * but other shells don't. We don't alter sigmode,
3380 * so we retry every time.
3381 * btw, in Linux it never fails. --vda */
3384 if (act.sa_handler == SIG_IGN) {
3385 cur_act = S_HARD_IGN;
3387 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3389 cur_act = S_IGN; /* don't hard ignore these */
3393 if (cur_act == S_HARD_IGN || cur_act == new_act)
3396 act.sa_handler = SIG_DFL;
3399 act.sa_handler = onsig;
3400 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3401 sigfillset(&act.sa_mask); /* ditto */
3404 act.sa_handler = SIG_IGN;
3407 sigaction_set(signo, &act);
3412 /* mode flags for set_curjob */
3413 #define CUR_DELETE 2
3414 #define CUR_RUNNING 1
3415 #define CUR_STOPPED 0
3417 /* mode flags for dowait */
3418 #define DOWAIT_NONBLOCK WNOHANG
3419 #define DOWAIT_BLOCK 0
3422 /* pgrp of shell on invocation */
3423 static int initialpgrp; //references:2
3424 static int ttyfd = -1; //5
3427 static struct job *jobtab; //5
3429 static unsigned njobs; //4
3431 static struct job *curjob; //lots
3432 /* number of presumed living untracked jobs */
3433 static int jobless; //4
3436 set_curjob(struct job *jp, unsigned mode)
3439 struct job **jpp, **curp;
3441 /* first remove from list */
3442 jpp = curp = &curjob;
3447 jpp = &jp1->prev_job;
3449 *jpp = jp1->prev_job;
3451 /* Then re-insert in correct position */
3459 /* job being deleted */
3462 /* newly created job or backgrounded job,
3463 put after all stopped jobs. */
3467 if (!jp1 || jp1->state != JOBSTOPPED)
3470 jpp = &jp1->prev_job;
3476 /* newly stopped job - becomes curjob */
3477 jp->prev_job = *jpp;
3485 jobno(const struct job *jp)
3487 return jp - jobtab + 1;
3492 * Convert a job name to a job structure.
3495 #define getjob(name, getctl) getjob(name)
3498 getjob(const char *name, int getctl)
3502 const char *err_msg = "%s: no such job";
3506 char *(*match)(const char *, const char *);
3521 if (c == '+' || c == '%') {
3523 err_msg = "No current job";
3529 err_msg = "No previous job";
3540 jp = jobtab + num - 1;
3555 if (match(jp->ps[0].cmd, p)) {
3559 err_msg = "%s: ambiguous";
3569 err_msg = "job %s not created under job control";
3570 if (getctl && jp->jobctl == 0)
3575 ash_msg_and_raise_error(err_msg, name);
3579 * Mark a job structure as unused.
3582 freejob(struct job *jp)
3584 struct procstat *ps;
3588 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3589 if (ps->cmd != nullstr)
3592 if (jp->ps != &jp->ps0)
3595 set_curjob(jp, CUR_DELETE);
3601 xtcsetpgrp(int fd, pid_t pgrp)
3603 if (tcsetpgrp(fd, pgrp))
3604 ash_msg_and_raise_error("can't set tty process group (%m)");
3608 * Turn job control on and off.
3610 * Note: This code assumes that the third arg to ioctl is a character
3611 * pointer, which is true on Berkeley systems but not System V. Since
3612 * System V doesn't have job control yet, this isn't a problem now.
3614 * Called with interrupts off.
3622 if (on == doing_jobctl || rootshell == 0)
3626 ofd = fd = open(_PATH_TTY, O_RDWR);
3628 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3629 * That sometimes helps to acquire controlling tty.
3630 * Obviously, a workaround for bugs when someone
3631 * failed to provide a controlling tty to bash! :) */
3637 fd = fcntl(fd, F_DUPFD, 10);
3642 /* fd is a tty at this point */
3643 close_on_exec_on(fd);
3644 do { /* while we are in the background */
3645 pgrp = tcgetpgrp(fd);
3648 ash_msg("can't access tty; job control turned off");
3652 if (pgrp == getpgrp())
3663 xtcsetpgrp(fd, pgrp);
3665 /* turning job control off */
3668 /* was xtcsetpgrp, but this can make exiting ash
3669 * loop forever if pty is already deleted */
3670 tcsetpgrp(fd, pgrp);
3684 static int FAST_FUNC
3685 killcmd(int argc, char **argv)
3688 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3690 if (argv[i][0] == '%') {
3691 struct job *jp = getjob(argv[i], 0);
3692 unsigned pid = jp->ps[0].pid;
3693 /* Enough space for ' -NNN<nul>' */
3694 argv[i] = alloca(sizeof(int)*3 + 3);
3695 /* kill_main has matching code to expect
3696 * leading space. Needed to not confuse
3697 * negative pids with "kill -SIGNAL_NO" syntax */
3698 sprintf(argv[i], " -%u", pid);
3700 } while (argv[++i]);
3702 return kill_main(argc, argv);
3706 showpipe(struct job *jp, FILE *out)
3708 struct procstat *sp;
3709 struct procstat *spend;
3711 spend = jp->ps + jp->nprocs;
3712 for (sp = jp->ps + 1; sp < spend; sp++)
3713 fprintf(out, " | %s", sp->cmd);
3714 outcslow('\n', out);
3715 flush_stdout_stderr();
3720 restartjob(struct job *jp, int mode)
3722 struct procstat *ps;
3728 if (jp->state == JOBDONE)
3730 jp->state = JOBRUNNING;
3732 if (mode == FORK_FG)
3733 xtcsetpgrp(ttyfd, pgid);
3734 killpg(pgid, SIGCONT);
3738 if (WIFSTOPPED(ps->status)) {
3744 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3749 static int FAST_FUNC
3750 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3757 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3762 jp = getjob(*argv, 1);
3763 if (mode == FORK_BG) {
3764 set_curjob(jp, CUR_RUNNING);
3765 fprintf(out, "[%d] ", jobno(jp));
3767 outstr(jp->ps->cmd, out);
3769 retval = restartjob(jp, mode);
3770 } while (*argv && *++argv);
3776 sprint_status(char *s, int status, int sigonly)
3782 if (!WIFEXITED(status)) {
3784 if (WIFSTOPPED(status))
3785 st = WSTOPSIG(status);
3788 st = WTERMSIG(status);
3790 if (st == SIGINT || st == SIGPIPE)
3793 if (WIFSTOPPED(status))
3798 col = fmtstr(s, 32, strsignal(st));
3799 if (WCOREDUMP(status)) {
3800 col += fmtstr(s + col, 16, " (core dumped)");
3802 } else if (!sigonly) {
3803 st = WEXITSTATUS(status);
3805 col = fmtstr(s, 16, "Done(%d)", st);
3807 col = fmtstr(s, 16, "Done");
3814 dowait(int wait_flags, struct job *job)
3819 struct job *thisjob;
3822 TRACE(("dowait(0x%x) called\n", wait_flags));
3824 /* Do a wait system call. If job control is compiled in, we accept
3825 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3826 * NB: _not_ safe_waitpid, we need to detect EINTR */
3827 pid = waitpid(-1, &status,
3828 (doing_jobctl ? (wait_flags | WUNTRACED) : wait_flags));
3829 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3830 pid, status, errno, strerror(errno)));
3836 for (jp = curjob; jp; jp = jp->prev_job) {
3837 struct procstat *sp;
3838 struct procstat *spend;
3839 if (jp->state == JOBDONE)
3842 spend = jp->ps + jp->nprocs;
3845 if (sp->pid == pid) {
3846 TRACE(("Job %d: changing status of proc %d "
3847 "from 0x%x to 0x%x\n",
3848 jobno(jp), pid, sp->status, status));
3849 sp->status = status;
3852 if (sp->status == -1)
3855 if (state == JOBRUNNING)
3857 if (WIFSTOPPED(sp->status)) {
3858 jp->stopstatus = sp->status;
3862 } while (++sp < spend);
3867 if (!WIFSTOPPED(status))
3873 if (state != JOBRUNNING) {
3874 thisjob->changed = 1;
3876 if (thisjob->state != state) {
3877 TRACE(("Job %d: changing state from %d to %d\n",
3878 jobno(thisjob), thisjob->state, state));
3879 thisjob->state = state;
3881 if (state == JOBSTOPPED) {
3882 set_curjob(thisjob, CUR_STOPPED);
3891 if (thisjob && thisjob == job) {
3895 len = sprint_status(s, status, 1);
3906 blocking_wait_with_raise_on_sig(struct job *job)
3908 pid_t pid = dowait(DOWAIT_BLOCK, job);
3909 if (pid <= 0 && pending_sig)
3910 raise_exception(EXSIG);
3916 showjob(FILE *out, struct job *jp, int mode)
3918 struct procstat *ps;
3919 struct procstat *psend;
3926 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
3927 /* just output process (group) id of pipeline */
3928 fprintf(out, "%d\n", ps->pid);
3932 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3937 else if (curjob && jp == curjob->prev_job)
3940 if (mode & SHOW_PIDS)
3941 col += fmtstr(s + col, 16, "%d ", ps->pid);
3943 psend = ps + jp->nprocs;
3945 if (jp->state == JOBRUNNING) {
3946 strcpy(s + col, "Running");
3947 col += sizeof("Running") - 1;
3949 int status = psend[-1].status;
3950 if (jp->state == JOBSTOPPED)
3951 status = jp->stopstatus;
3952 col += sprint_status(s + col, status, 0);
3954 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
3956 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3957 * or prints several "PID | <cmdN>" lines,
3958 * depending on SHOW_PIDS bit.
3959 * We do not print status of individual processes
3960 * between PID and <cmdN>. bash does it, but not very well:
3961 * first line shows overall job status, not process status,
3962 * making it impossible to know 1st process status.
3966 /* for each process */
3969 if (mode & SHOW_PIDS)
3970 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->pid) - 1;
3972 fprintf(out, "%s%*c", s, 33 - col >= 0 ? 33 - col : 0, ' ');
3975 fprintf(out, "%s", ps->cmd);
3979 outcslow('\n', out);
3983 if (jp->state == JOBDONE) {
3984 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3990 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3991 * statuses have changed since the last call to showjobs.
3994 showjobs(FILE *out, int mode)
3998 TRACE(("showjobs(0x%x) called\n", mode));
4000 /* Handle all finished jobs */
4001 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4004 for (jp = curjob; jp; jp = jp->prev_job) {
4005 if (!(mode & SHOW_CHANGED) || jp->changed) {
4006 showjob(out, jp, mode);
4011 static int FAST_FUNC
4012 jobscmd(int argc UNUSED_PARAM, char **argv)
4017 while ((m = nextopt("lp")) != '\0') {
4021 mode |= SHOW_ONLY_PGID;
4027 showjob(stdout, getjob(*argv, 0), mode);
4030 showjobs(stdout, mode);
4037 getstatus(struct job *job)
4042 status = job->ps[job->nprocs - 1].status;
4043 retval = WEXITSTATUS(status);
4044 if (!WIFEXITED(status)) {
4046 retval = WSTOPSIG(status);
4047 if (!WIFSTOPPED(status))
4050 /* XXX: limits number of signals */
4051 retval = WTERMSIG(status);
4053 if (retval == SIGINT)
4059 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4060 jobno(job), job->nprocs, status, retval));
4064 static int FAST_FUNC
4065 waitcmd(int argc UNUSED_PARAM, char **argv)
4072 raise_exception(EXSIG);
4079 /* wait for all jobs */
4083 if (!jp) /* no running procs */
4085 if (jp->state == JOBRUNNING)
4091 * "When bash is waiting for an asynchronous command via
4092 * the wait builtin, the reception of a signal for which a trap
4093 * has been set will cause the wait builtin to return immediately
4094 * with an exit status greater than 128, immediately after which
4095 * the trap is executed."
4096 * Do we do it that way? */
4097 blocking_wait_with_raise_on_sig(NULL);
4103 if (**argv != '%') {
4104 pid_t pid = number(*argv);
4109 if (job->ps[job->nprocs - 1].pid == pid)
4111 job = job->prev_job;
4114 job = getjob(*argv, 0);
4115 /* loop until process terminated or stopped */
4116 while (job->state == JOBRUNNING)
4117 blocking_wait_with_raise_on_sig(NULL);
4119 retval = getstatus(job);
4132 struct job *jp, *jq;
4134 len = njobs * sizeof(*jp);
4136 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4138 offset = (char *)jp - (char *)jq;
4140 /* Relocate pointers */
4143 jq = (struct job *)((char *)jq + l);
4147 #define joff(p) ((struct job *)((char *)(p) + l))
4148 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4149 if (joff(jp)->ps == &jq->ps0)
4150 jmove(joff(jp)->ps);
4151 if (joff(jp)->prev_job)
4152 jmove(joff(jp)->prev_job);
4162 jp = (struct job *)((char *)jp + len);
4166 } while (--jq >= jp);
4171 * Return a new job structure.
4172 * Called with interrupts off.
4175 makejob(/*union node *node,*/ int nprocs)
4180 for (i = njobs, jp = jobtab; ; jp++) {
4187 if (jp->state != JOBDONE || !jp->waited)
4196 memset(jp, 0, sizeof(*jp));
4198 /* jp->jobctl is a bitfield.
4199 * "jp->jobctl |= jobctl" likely to give awful code */
4203 jp->prev_job = curjob;
4208 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4210 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4217 * Return a string identifying a command (to be printed by the
4220 static char *cmdnextc;
4223 cmdputs(const char *s)
4225 static const char vstype[VSTYPE + 1][3] = {
4226 "", "}", "-", "+", "?", "=",
4227 "%", "%%", "#", "##"
4228 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4231 const char *p, *str;
4232 char c, cc[2] = " ";
4237 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4239 while ((c = *p++) != 0) {
4247 if ((subtype & VSTYPE) == VSLENGTH)
4251 if (!(subtype & VSQUOTE) == !(quoted & 1))
4257 str = "\"}" + !(quoted & 1);
4264 case CTLBACKQ+CTLQUOTE:
4267 #if ENABLE_SH_MATH_SUPPORT
4282 if ((subtype & VSTYPE) != VSNORMAL)
4284 str = vstype[subtype & VSTYPE];
4285 if (subtype & VSNUL)
4294 /* These can only happen inside quotes */
4307 while ((c = *str++) != '\0') {
4312 USTPUTC('"', nextc);
4318 /* cmdtxt() and cmdlist() call each other */
4319 static void cmdtxt(union node *n);
4322 cmdlist(union node *np, int sep)
4324 for (; np; np = np->narg.next) {
4328 if (sep && np->narg.next)
4334 cmdtxt(union node *n)
4337 struct nodelist *lp;
4348 lp = n->npipe.cmdlist;
4366 cmdtxt(n->nbinary.ch1);
4382 cmdtxt(n->nif.test);
4384 if (n->nif.elsepart) {
4385 cmdtxt(n->nif.ifpart);
4387 n = n->nif.elsepart;
4405 cmdtxt(n->nbinary.ch1);
4415 cmdputs(n->nfor.var);
4417 cmdlist(n->nfor.args, 1);
4422 cmdputs(n->narg.text);
4426 cmdlist(n->ncmd.args, 1);
4427 cmdlist(n->ncmd.redirect, 0);
4440 cmdputs(n->ncase.expr->narg.text);
4442 for (np = n->ncase.cases; np; np = np->nclist.next) {
4443 cmdtxt(np->nclist.pattern);
4445 cmdtxt(np->nclist.body);
4459 #if ENABLE_ASH_BASH_COMPAT
4474 cmdputs(utoa(n->nfile.fd));
4476 if (n->type == NTOFD || n->type == NFROMFD) {
4477 cmdputs(utoa(n->ndup.dupfd));
4486 commandtext(union node *n)
4490 STARTSTACKSTR(cmdnextc);
4492 name = stackblock();
4493 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4494 name, cmdnextc, cmdnextc));
4495 return ckstrdup(name);
4500 * Fork off a subshell. If we are doing job control, give the subshell its
4501 * own process group. Jp is a job structure that the job is to be added to.
4502 * N is the command that will be evaluated by the child. Both jp and n may
4503 * be NULL. The mode parameter can be one of the following:
4504 * FORK_FG - Fork off a foreground process.
4505 * FORK_BG - Fork off a background process.
4506 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4507 * process group even if job control is on.
4509 * When job control is turned off, background processes have their standard
4510 * input redirected to /dev/null (except for the second and later processes
4513 * Called with interrupts off.
4516 * Clear traps on a fork.
4523 for (tp = trap; tp < &trap[NSIG]; tp++) {
4524 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4528 if ((tp - trap) != 0)
4529 setsignal(tp - trap);
4535 /* Lives far away from here, needed for forkchild */
4536 static void closescript(void);
4538 /* Called after fork(), in child */
4540 # define forkchild(jp, n, mode) forkchild(jp, mode)
4543 forkchild(struct job *jp, union node *n, int mode)
4547 TRACE(("Child shell %d\n", getpid()));
4551 /* man bash: "Non-builtin commands run by bash have signal handlers
4552 * set to the values inherited by the shell from its parent".
4553 * Do we do it correctly? */
4557 if (mode == FORK_NOJOB /* is it `xxx` ? */
4558 && n && n->type == NCMD /* is it single cmd? */
4559 /* && n->ncmd.args->type == NARG - always true? */
4560 && strcmp(n->ncmd.args->narg.text, "trap") == 0
4561 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4562 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4564 TRACE(("Trap hack\n"));
4565 /* Awful hack for `trap` or $(trap).
4567 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4568 * contains an example where "trap" is executed in a subshell:
4570 * save_traps=$(trap)
4572 * eval "$save_traps"
4574 * Standard does not say that "trap" in subshell shall print
4575 * parent shell's traps. It only says that its output
4576 * must have suitable form, but then, in the above example
4577 * (which is not supposed to be normative), it implies that.
4579 * bash (and probably other shell) does implement it
4580 * (traps are reset to defaults, but "trap" still shows them),
4581 * but as a result, "trap" logic is hopelessly messed up:
4584 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4585 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4586 * # true | trap <--- trap is in subshell - no output (ditto)
4587 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4588 * trap -- 'echo Ho' SIGWINCH
4589 * # echo `(trap)` <--- in subshell in subshell - output
4590 * trap -- 'echo Ho' SIGWINCH
4591 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4592 * trap -- 'echo Ho' SIGWINCH
4594 * The rules when to forget and when to not forget traps
4595 * get really complex and nonsensical.
4597 * Our solution: ONLY bare $(trap) or `trap` is special.
4599 free(trap[0]); /* Prevent EXIT trap from firing in `trap` */
4605 /* do job control only in root shell */
4607 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4610 if (jp->nprocs == 0)
4613 pgrp = jp->ps[0].pid;
4614 /* this can fail because we are doing it in the parent also */
4616 if (mode == FORK_FG)
4617 xtcsetpgrp(ttyfd, pgrp);
4622 if (mode == FORK_BG) {
4623 /* man bash: "When job control is not in effect,
4624 * asynchronous commands ignore SIGINT and SIGQUIT" */
4627 if (jp->nprocs == 0) {
4629 if (open(bb_dev_null, O_RDONLY) != 0)
4630 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4634 if (iflag) { /* why if iflag only? */
4639 * "In all cases, bash ignores SIGQUIT. Non-builtin
4640 * commands run by bash have signal handlers
4641 * set to the values inherited by the shell
4643 * Take care of the second rule: */
4647 if (n && n->type == NCMD
4648 && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4650 TRACE(("Job hack\n"));
4651 /* "jobs": we do not want to clear job list for it,
4652 * instead we remove only _its_ own_ job from job list.
4653 * This makes "jobs .... | cat" more useful.
4659 for (jp = curjob; jp; jp = jp->prev_job)
4664 /* Called after fork(), in parent */
4666 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4669 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4671 TRACE(("In parent shell: child = %d\n", pid));
4673 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4679 if (mode != FORK_NOJOB && jp->jobctl) {
4682 if (jp->nprocs == 0)
4685 pgrp = jp->ps[0].pid;
4686 /* This can fail because we are doing it in the child also */
4690 if (mode == FORK_BG) {
4691 backgndpid = pid; /* set $! */
4692 set_curjob(jp, CUR_RUNNING);
4695 struct procstat *ps = &jp->ps[jp->nprocs++];
4700 if (doing_jobctl && n)
4701 ps->cmd = commandtext(n);
4707 forkshell(struct job *jp, union node *n, int mode)
4711 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4714 TRACE(("Fork failed, errno=%d", errno));
4717 ash_msg_and_raise_error("can't fork");
4720 forkchild(jp, n, mode);
4722 forkparent(jp, n, mode, pid);
4727 * Wait for job to finish.
4729 * Under job control we have the problem that while a child process
4730 * is running interrupts generated by the user are sent to the child
4731 * but not to the shell. This means that an infinite loop started by
4732 * an interactive user may be hard to kill. With job control turned off,
4733 * an interactive user may place an interactive program inside a loop.
4734 * If the interactive program catches interrupts, the user doesn't want
4735 * these interrupts to also abort the loop. The approach we take here
4736 * is to have the shell ignore interrupt signals while waiting for a
4737 * foreground process to terminate, and then send itself an interrupt
4738 * signal if the child process was terminated by an interrupt signal.
4739 * Unfortunately, some programs want to do a bit of cleanup and then
4740 * exit on interrupt; unless these processes terminate themselves by
4741 * sending a signal to themselves (instead of calling exit) they will
4742 * confuse this approach.
4744 * Called with interrupts off.
4747 waitforjob(struct job *jp)
4751 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4754 while (jp->state == JOBRUNNING) {
4755 /* In non-interactive shells, we _can_ get
4756 * a keyboard signal here and be EINTRed,
4757 * but we just loop back, waiting for command to complete.
4760 * "If bash is waiting for a command to complete and receives
4761 * a signal for which a trap has been set, the trap
4762 * will not be executed until the command completes."
4764 * Reality is that even if trap is not set, bash
4765 * will not act on the signal until command completes.
4766 * Try this. sleep5intoff.c:
4767 * #include <signal.h>
4768 * #include <unistd.h>
4771 * sigemptyset(&set);
4772 * sigaddset(&set, SIGINT);
4773 * sigaddset(&set, SIGQUIT);
4774 * sigprocmask(SIG_BLOCK, &set, NULL);
4778 * $ bash -c './sleep5intoff; echo hi'
4779 * ^C^C^C^C <--- pressing ^C once a second
4781 * $ bash -c './sleep5intoff; echo hi'
4782 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4785 dowait(DOWAIT_BLOCK, jp);
4792 xtcsetpgrp(ttyfd, rootpid);
4794 * This is truly gross.
4795 * If we're doing job control, then we did a TIOCSPGRP which
4796 * caused us (the shell) to no longer be in the controlling
4797 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4798 * intuit from the subprocess exit status whether a SIGINT
4799 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4801 if (jp->sigint) /* TODO: do the same with all signals */
4802 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4804 if (jp->state == JOBDONE)
4811 * return 1 if there are stopped jobs, otherwise 0
4823 if (jp && jp->state == JOBSTOPPED) {
4824 out2str("You have stopped jobs.\n");
4833 /* ============ redir.c
4835 * Code for dealing with input/output redirection.
4838 #define EMPTY -2 /* marks an unused slot in redirtab */
4839 #define CLOSED -3 /* marks a slot of previously-closed fd */
4842 * Open a file in noclobber mode.
4843 * The code was copied from bash.
4846 noclobberopen(const char *fname)
4849 struct stat finfo, finfo2;
4852 * If the file exists and is a regular file, return an error
4855 r = stat(fname, &finfo);
4856 if (r == 0 && S_ISREG(finfo.st_mode)) {
4862 * If the file was not present (r != 0), make sure we open it
4863 * exclusively so that if it is created before we open it, our open
4864 * will fail. Make sure that we do not truncate an existing file.
4865 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4866 * file was not a regular file, we leave O_EXCL off.
4869 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4870 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4872 /* If the open failed, return the file descriptor right away. */
4877 * OK, the open succeeded, but the file may have been changed from a
4878 * non-regular file to a regular file between the stat and the open.
4879 * We are assuming that the O_EXCL open handles the case where FILENAME
4880 * did not exist and is symlinked to an existing file between the stat
4885 * If we can open it and fstat the file descriptor, and neither check
4886 * revealed that it was a regular file, and the file has not been
4887 * replaced, return the file descriptor.
4889 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4890 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4893 /* The file has been replaced. badness. */
4900 * Handle here documents. Normally we fork off a process to write the
4901 * data to a pipe. If the document is short, we can stuff the data in
4902 * the pipe without forking.
4904 /* openhere needs this forward reference */
4905 static void expandhere(union node *arg, int fd);
4907 openhere(union node *redir)
4913 ash_msg_and_raise_error("pipe call failed");
4914 if (redir->type == NHERE) {
4915 len = strlen(redir->nhere.doc->narg.text);
4916 if (len <= PIPE_BUF) {
4917 full_write(pip[1], redir->nhere.doc->narg.text, len);
4921 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4924 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4925 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4926 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4927 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4928 signal(SIGPIPE, SIG_DFL);
4929 if (redir->type == NHERE)
4930 full_write(pip[1], redir->nhere.doc->narg.text, len);
4932 expandhere(redir->nhere.doc, pip[1]);
4933 _exit(EXIT_SUCCESS);
4941 openredirect(union node *redir)
4946 switch (redir->nfile.type) {
4948 fname = redir->nfile.expfname;
4949 f = open(fname, O_RDONLY);
4954 fname = redir->nfile.expfname;
4955 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4960 #if ENABLE_ASH_BASH_COMPAT
4963 /* Take care of noclobber mode. */
4965 fname = redir->nfile.expfname;
4966 f = noclobberopen(fname);
4973 fname = redir->nfile.expfname;
4974 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4979 fname = redir->nfile.expfname;
4980 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4988 /* Fall through to eliminate warning. */
4989 /* Our single caller does this itself */
4996 f = openhere(redir);
5002 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5004 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5008 * Copy a file descriptor to be >= to. Returns -1
5009 * if the source file descriptor is closed, EMPTY if there are no unused
5010 * file descriptors left.
5012 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5013 * old code was doing close(to) prior to copyfd() to achieve the same */
5015 COPYFD_EXACT = (int)~(INT_MAX),
5016 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5019 copyfd(int from, int to)
5023 if (to & COPYFD_EXACT) {
5024 to &= ~COPYFD_EXACT;
5026 newfd = dup2(from, to);
5028 newfd = fcntl(from, F_DUPFD, to);
5031 if (errno == EMFILE)
5033 /* Happens when source fd is not open: try "echo >&99" */
5034 ash_msg_and_raise_error("%d: %m", from);
5039 /* Struct def and variable are moved down to the first usage site */
5044 struct redirtab *next;
5047 struct two_fd_t two_fd[];
5049 #define redirlist (G_var.redirlist)
5051 static int need_to_remember(struct redirtab *rp, int fd)
5055 if (!rp) /* remembering was not requested */
5058 for (i = 0; i < rp->pair_count; i++) {
5059 if (rp->two_fd[i].orig == fd) {
5060 /* already remembered */
5067 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5068 static int is_hidden_fd(struct redirtab *rp, int fd)
5071 struct parsefile *pf;
5084 fd |= COPYFD_RESTORE;
5085 for (i = 0; i < rp->pair_count; i++) {
5086 if (rp->two_fd[i].copy == fd) {
5094 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5095 * old file descriptors are stashed away so that the redirection can be
5096 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5097 * standard output, and the standard error if it becomes a duplicate of
5098 * stdout, is saved in memory.
5100 /* flags passed to redirect */
5101 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5102 #define REDIR_SAVEFD2 03 /* set preverrout */
5104 redirect(union node *redir, int flags)
5106 struct redirtab *sv;
5111 int copied_fd2 = -1;
5121 if (flags & REDIR_PUSH) {
5122 union node *tmp = redir;
5125 #if ENABLE_ASH_BASH_COMPAT
5126 if (redir->nfile.type == NTO2)
5129 tmp = tmp->nfile.next;
5131 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5132 sv->next = redirlist;
5133 sv->pair_count = sv_pos;
5135 sv->nullredirs = g_nullredirs - 1;
5137 while (sv_pos > 0) {
5139 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5144 fd = redir->nfile.fd;
5145 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5146 int right_fd = redir->ndup.dupfd;
5147 /* redirect from/to same file descriptor? */
5150 /* echo >&10 and 10 is a fd opened to the sh script? */
5151 if (is_hidden_fd(sv, right_fd)) {
5152 errno = EBADF; /* as if it is closed */
5153 ash_msg_and_raise_error("%d: %m", right_fd);
5157 newfd = openredirect(redir); /* always >= 0 */
5159 /* Descriptor wasn't open before redirect.
5160 * Mark it for close in the future */
5161 if (need_to_remember(sv, fd)) {
5162 goto remember_to_close;
5167 #if ENABLE_ASH_BASH_COMPAT
5170 if (need_to_remember(sv, fd)) {
5171 /* Copy old descriptor */
5172 i = fcntl(fd, F_DUPFD, 10);
5173 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5174 * are closed in popredir() in the child, preventing them from leaking
5175 * into child. (popredir() also cleans up the mess in case of failures)
5180 /* Strange error (e.g. "too many files" EMFILE?) */
5184 ash_msg_and_raise_error("%d: %m", fd);
5187 /* EBADF: it is not open - good, remember to close it */
5190 } else { /* fd is open, save its copy */
5191 /* "exec fd>&-" should not close fds
5192 * which point to script file(s).
5193 * Force them to be restored afterwards */
5194 if (is_hidden_fd(sv, fd))
5195 i |= COPYFD_RESTORE;
5199 sv->two_fd[sv_pos].orig = fd;
5200 sv->two_fd[sv_pos].copy = i;
5204 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5205 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5206 /* Don't want to trigger debugging */
5210 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5212 } else if (fd != newfd) { /* move newfd to fd */
5213 copyfd(newfd, fd | COPYFD_EXACT);
5214 #if ENABLE_ASH_BASH_COMPAT
5215 if (!(redir->nfile.type == NTO2 && fd == 2))
5219 #if ENABLE_ASH_BASH_COMPAT
5220 if (redir->nfile.type == NTO2 && fd == 1) {
5221 /* We already redirected it to fd 1, now copy it to 2 */
5227 } while ((redir = redir->nfile.next) != NULL);
5230 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5231 preverrout_fd = copied_fd2;
5235 * Undo the effects of the last redirection.
5238 popredir(int drop, int restore)
5240 struct redirtab *rp;
5243 if (--g_nullredirs >= 0)
5247 for (i = 0; i < rp->pair_count; i++) {
5248 int fd = rp->two_fd[i].orig;
5249 int copy = rp->two_fd[i].copy;
5250 if (copy == CLOSED) {
5255 if (copy != EMPTY) {
5256 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5257 copy &= ~COPYFD_RESTORE;
5259 copyfd(copy, fd | COPYFD_EXACT);
5261 close(copy & ~COPYFD_RESTORE);
5264 redirlist = rp->next;
5265 g_nullredirs = rp->nullredirs;
5271 * Undo all redirections. Called on error or interrupt.
5275 * Discard all saved file descriptors.
5278 clearredir(int drop)
5284 popredir(drop, /*restore:*/ 0);
5289 redirectsafe(union node *redir, int flags)
5292 volatile int saveint;
5293 struct jmploc *volatile savehandler = exception_handler;
5294 struct jmploc jmploc;
5297 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5298 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5300 exception_handler = &jmploc;
5301 redirect(redir, flags);
5303 exception_handler = savehandler;
5304 if (err && exception_type != EXERROR)
5305 longjmp(exception_handler->loc, 1);
5306 RESTORE_INT(saveint);
5311 /* ============ Routines to expand arguments to commands
5313 * We have to deal with backquotes, shell variables, and file metacharacters.
5316 #if ENABLE_SH_MATH_SUPPORT
5318 ash_arith(const char *s)
5320 arith_eval_hooks_t math_hooks;
5324 math_hooks.lookupvar = lookupvar;
5325 math_hooks.setvar = setvar;
5326 math_hooks.endofname = endofname;
5329 result = arith(s, &errcode, &math_hooks);
5332 ash_msg_and_raise_error("exponent less than 0");
5334 ash_msg_and_raise_error("divide by zero");
5336 ash_msg_and_raise_error("expression recursion loop detected");
5337 raise_error_syntax(s);
5348 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5349 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5350 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5351 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5352 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5353 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5354 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5355 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5356 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5360 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5361 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5362 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5363 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5364 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5367 * Structure specifying which parts of the string should be searched
5368 * for IFS characters.
5371 struct ifsregion *next; /* next region in list */
5372 int begoff; /* offset of start of region */
5373 int endoff; /* offset of end of region */
5374 int nulonly; /* search for nul bytes only */
5378 struct strlist *list;
5379 struct strlist **lastp;
5382 /* output of current string */
5383 static char *expdest;
5384 /* list of back quote expressions */
5385 static struct nodelist *argbackq;
5386 /* first struct in list of ifs regions */
5387 static struct ifsregion ifsfirst;
5388 /* last struct in list */
5389 static struct ifsregion *ifslastp;
5390 /* holds expanded arg list */
5391 static struct arglist exparg;
5401 expdest = makestrspace(32, expdest);
5402 len = fmtstr(expdest, 32, arith_t_fmt, num);
5403 STADJUST(len, expdest);
5408 esclen(const char *start, const char *p)
5412 while (p > start && (unsigned char)*--p == CTLESC) {
5419 * Remove any CTLESC characters from a string.
5422 rmescapes(char *str, int flag)
5424 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5428 unsigned protect_against_glob;
5431 p = strpbrk(str, qchars);
5437 if (flag & RMESCAPE_ALLOC) {
5438 size_t len = p - str;
5439 size_t fulllen = len + strlen(p) + 1;
5441 if (flag & RMESCAPE_GROW) {
5442 r = makestrspace(fulllen, expdest);
5443 } else if (flag & RMESCAPE_HEAP) {
5444 r = ckmalloc(fulllen);
5446 r = stalloc(fulllen);
5450 q = (char *)memcpy(q, str, len) + len;
5454 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5455 globbing = flag & RMESCAPE_GLOB;
5456 protect_against_glob = globbing;
5458 if (*p == CTLQUOTEMARK) {
5459 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5460 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5461 // Note: both inquotes and protect_against_glob only affect whether
5462 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5463 inquotes = ~inquotes;
5465 protect_against_glob = globbing;
5469 /* naked back slash */
5470 protect_against_glob = 0;
5475 if (protect_against_glob && inquotes && *p != '/') {
5479 protect_against_glob = globbing;
5484 if (flag & RMESCAPE_GROW) {
5486 STADJUST(q - r + 1, expdest);
5490 #define pmatch(a, b) !fnmatch((a), (b), 0)
5493 * Prepare a pattern for a expmeta (internal glob(3)) call.
5495 * Returns an stalloced string.
5498 preglob(const char *pattern, int quoted, int flag)
5500 flag |= RMESCAPE_GLOB;
5502 flag |= RMESCAPE_QUOTED;
5504 return rmescapes((char *)pattern, flag);
5508 * Put a string on the stack.
5511 memtodest(const char *p, size_t len, int syntax, int quotes)
5515 q = makestrspace(quotes ? len * 2 : len, q);
5518 int c = signed_char2int(*p++);
5522 int n = SIT(c, syntax);
5523 if (n == CCTL || n == CBACK)
5533 strtodest(const char *p, int syntax, int quotes)
5535 memtodest(p, strlen(p), syntax, quotes);
5539 * Record the fact that we have to scan this region of the
5540 * string for IFS characters.
5543 recordregion(int start, int end, int nulonly)
5545 struct ifsregion *ifsp;
5547 if (ifslastp == NULL) {
5551 ifsp = ckzalloc(sizeof(*ifsp));
5552 /*ifsp->next = NULL; - ckzalloc did it */
5553 ifslastp->next = ifsp;
5557 ifslastp->begoff = start;
5558 ifslastp->endoff = end;
5559 ifslastp->nulonly = nulonly;
5563 removerecordregions(int endoff)
5565 if (ifslastp == NULL)
5568 if (ifsfirst.endoff > endoff) {
5569 while (ifsfirst.next != NULL) {
5570 struct ifsregion *ifsp;
5572 ifsp = ifsfirst.next->next;
5573 free(ifsfirst.next);
5574 ifsfirst.next = ifsp;
5577 if (ifsfirst.begoff > endoff)
5580 ifslastp = &ifsfirst;
5581 ifsfirst.endoff = endoff;
5586 ifslastp = &ifsfirst;
5587 while (ifslastp->next && ifslastp->next->begoff < endoff)
5588 ifslastp=ifslastp->next;
5589 while (ifslastp->next != NULL) {
5590 struct ifsregion *ifsp;
5592 ifsp = ifslastp->next->next;
5593 free(ifslastp->next);
5594 ifslastp->next = ifsp;
5597 if (ifslastp->endoff > endoff)
5598 ifslastp->endoff = endoff;
5602 exptilde(char *startp, char *p, int flags)
5608 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5613 while ((c = *++p) != '\0') {
5620 if (flags & EXP_VARTILDE)
5630 if (*name == '\0') {
5631 home = lookupvar(homestr);
5633 pw = getpwnam(name);
5638 if (!home || !*home)
5641 startloc = expdest - (char *)stackblock();
5642 strtodest(home, SQSYNTAX, quotes);
5643 recordregion(startloc, expdest - (char *)stackblock(), 0);
5651 * Execute a command inside back quotes. If it's a builtin command, we
5652 * want to save its output in a block obtained from malloc. Otherwise
5653 * we fork off a subprocess and get the output of the command via a pipe.
5654 * Should be called with interrupts off.
5656 struct backcmd { /* result of evalbackcmd */
5657 int fd; /* file descriptor to read from */
5658 int nleft; /* number of chars in buffer */
5659 char *buf; /* buffer */
5660 struct job *jp; /* job structure for command */
5663 /* These forward decls are needed to use "eval" code for backticks handling: */
5664 static uint8_t back_exitstatus; /* exit status of backquoted command */
5665 #define EV_EXIT 01 /* exit after evaluating tree */
5666 static void evaltree(union node *, int);
5668 static void FAST_FUNC
5669 evalbackcmd(union node *n, struct backcmd *result)
5680 saveherefd = herefd;
5688 ash_msg_and_raise_error("pipe call failed");
5689 jp = makejob(/*n,*/ 1);
5690 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5695 copyfd(pip[1], 1 | COPYFD_EXACT);
5699 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5703 result->fd = pip[0];
5706 herefd = saveherefd;
5708 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5709 result->fd, result->buf, result->nleft, result->jp));
5713 * Expand stuff in backwards quotes.
5716 expbackq(union node *cmd, int quoted, int quotes)
5724 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5725 struct stackmark smark;
5728 setstackmark(&smark);
5730 startloc = dest - (char *)stackblock();
5732 evalbackcmd(cmd, &in);
5733 popstackmark(&smark);
5740 memtodest(p, i, syntax, quotes);
5744 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5745 TRACE(("expbackq: read returns %d\n", i));
5754 back_exitstatus = waitforjob(in.jp);
5758 /* Eat all trailing newlines */
5760 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5765 recordregion(startloc, dest - (char *)stackblock(), 0);
5766 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5767 (dest - (char *)stackblock()) - startloc,
5768 (dest - (char *)stackblock()) - startloc,
5769 stackblock() + startloc));
5772 #if ENABLE_SH_MATH_SUPPORT
5774 * Expand arithmetic expression. Backup to start of expression,
5775 * evaluate, place result in (backed up) result, adjust string position.
5788 * This routine is slightly over-complicated for
5789 * efficiency. Next we scan backwards looking for the
5790 * start of arithmetic.
5792 start = stackblock();
5799 while (*p != CTLARI) {
5803 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5808 esc = esclen(start, p);
5818 removerecordregions(begoff);
5825 rmescapes(p + 2, 0);
5827 len = cvtnum(ash_arith(p + 2));
5830 recordregion(begoff, begoff + len, 0);
5834 /* argstr needs it */
5835 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5838 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5839 * characters to allow for further processing. Otherwise treat
5840 * $@ like $* since no splitting will be performed.
5842 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5843 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5844 * for correct expansion of "B=$A" word.
5847 argstr(char *p, int flags, struct strlist *var_str_list)
5849 static const char spclchars[] ALIGN1 = {
5857 CTLBACKQ | CTLQUOTE,
5858 #if ENABLE_SH_MATH_SUPPORT
5863 const char *reject = spclchars;
5865 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5866 int breakall = flags & EXP_WORD;
5871 if (!(flags & EXP_VARTILDE)) {
5873 } else if (flags & EXP_VARTILDE2) {
5878 if (flags & EXP_TILDE) {
5881 flags &= ~EXP_TILDE;
5884 if (*q == CTLESC && (flags & EXP_QWORD))
5887 p = exptilde(p, q, flags);
5890 startloc = expdest - (char *)stackblock();
5892 length += strcspn(p + length, reject);
5893 c = (unsigned char) p[length];
5896 #if ENABLE_SH_MATH_SUPPORT
5900 /* c == '=' || c == ':' || c == CTLENDARI */
5906 expdest = stack_nputstr(p, length, expdest);
5907 newloc = expdest - (char *)stackblock();
5908 if (breakall && !inquotes && newloc > startloc) {
5909 recordregion(startloc, newloc, 0);
5920 if (flags & EXP_VARTILDE2) {
5924 flags |= EXP_VARTILDE2;
5929 * sort of a hack - expand tildes in variable
5930 * assignments (after the first '=' and after ':'s).
5939 case CTLENDVAR: /* ??? */
5942 /* "$@" syntax adherence hack */
5944 && memcmp(p, dolatstr, 4) == 0
5945 && ( p[4] == CTLQUOTEMARK
5946 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5949 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
5952 inquotes = !inquotes;
5965 p = evalvar(p, flags, var_str_list);
5969 case CTLBACKQ|CTLQUOTE:
5970 expbackq(argbackq->n, c, quotes);
5971 argbackq = argbackq->next;
5973 #if ENABLE_SH_MATH_SUPPORT
5986 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
5989 // This commented out code was added by James Simmons <jsimmons@infradead.org>
5990 // as part of a larger change when he added support for ${var/a/b}.
5991 // However, it broke # and % operators:
5995 //echo ${var#ab} abcdcd abcdcd
5996 //echo ${var##ab} abcdcd abcdcd
5997 //echo ${var#a*b} abcdcd ababcdcd (!)
5998 //echo ${var##a*b} cdcd cdcd
5999 //echo ${var#?} babcdcd ababcdcd (!)
6000 //echo ${var##?} babcdcd babcdcd
6001 //echo ${var#*} ababcdcd babcdcd (!)
6003 //echo ${var%cd} ababcd ababcd
6004 //echo ${var%%cd} ababcd abab (!)
6005 //echo ${var%c*d} ababcd ababcd
6006 //echo ${var%%c*d} abab ababcdcd (!)
6007 //echo ${var%?} ababcdc ababcdc
6008 //echo ${var%%?} ababcdc ababcdcd (!)
6009 //echo ${var%*} ababcdcd ababcdcd
6012 // Commenting it back out helped. Remove it completely if it really
6015 char *loc, *loc2; //, *full;
6021 int match; // = strlen(str);
6022 const char *s = loc2;
6029 match = pmatch(str, s); // this line was deleted
6031 // // chop off end if its '*'
6032 // full = strrchr(str, '*');
6033 // if (full && full != str)
6036 // // If str starts with '*' replace with s.
6037 // if ((*str == '*') && strlen(s) >= match) {
6038 // full = xstrdup(s);
6039 // strncpy(full+strlen(s)-match+1, str+1, match-1);
6041 // full = xstrndup(str, match);
6042 // match = strncmp(s, full, strlen(full));
6046 if (match) // if (!match)
6048 if (quotes && *loc == CTLESC)
6057 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6064 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6067 const char *s = loc2;
6072 match = pmatch(str, s);
6079 esc = esclen(startp, loc);
6090 static void varunset(const char *, const char *, const char *, int) NORETURN;
6092 varunset(const char *end, const char *var, const char *umsg, int varflags)
6098 msg = "parameter not set";
6100 if (*end == CTLENDVAR) {
6101 if (varflags & VSNUL)
6107 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6110 #if ENABLE_ASH_BASH_COMPAT
6112 parse_sub_pattern(char *arg, int inquotes)
6114 char *idx, *repl = NULL;
6123 /* Only the first '/' seen is our separator */
6130 if (!inquotes && c == '\\' && arg[1] == '\\')
6131 arg++; /* skip both \\, not just first one */
6138 #endif /* ENABLE_ASH_BASH_COMPAT */
6141 subevalvar(char *p, char *str, int strloc, int subtype,
6142 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6144 struct nodelist *saveargbackq = argbackq;
6147 char *rmesc, *rmescend;
6148 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6149 IF_ASH_BASH_COMPAT(char null = '\0';)
6150 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6151 int saveherefd = herefd;
6152 int amount, workloc, resetloc;
6154 char *(*scan)(char*, char*, char*, char*, int, int);
6157 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6159 STPUTC('\0', expdest);
6160 herefd = saveherefd;
6161 argbackq = saveargbackq;
6162 startp = (char *)stackblock() + startloc;
6166 setvar(str, startp, 0);
6167 amount = startp - expdest;
6168 STADJUST(amount, expdest);
6171 #if ENABLE_ASH_BASH_COMPAT
6173 loc = str = stackblock() + strloc;
6174 /* Read POS in ${var:POS:LEN} */
6175 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6176 len = str - startp - 1;
6178 /* *loc != '\0', guaranteed by parser */
6182 /* Adjust the length by the number of escapes */
6183 for (ptr = startp; ptr < (str - 1); ptr++) {
6184 if (*ptr == CTLESC) {
6192 if (*loc++ == ':') {
6196 /* Skip POS in ${var:POS:LEN} */
6198 while (*loc && *loc != ':') {
6200 * bash complains on: var=qwe; echo ${var:1a:123}
6202 ash_msg_and_raise_error(msg_illnum, str);
6206 if (*loc++ == ':') {
6210 if (pos >= orig_len) {
6214 if (len > (orig_len - pos))
6215 len = orig_len - pos;
6217 for (str = startp; pos; str++, pos--) {
6218 if (quotes && *str == CTLESC)
6221 for (loc = startp; len; len--) {
6222 if (quotes && *str == CTLESC)
6227 amount = loc - expdest;
6228 STADJUST(amount, expdest);
6233 varunset(p, str, startp, varflags);
6236 resetloc = expdest - (char *)stackblock();
6238 /* We'll comeback here if we grow the stack while handling
6239 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6240 * stack will need rebasing, and we'll need to remove our work
6243 IF_ASH_BASH_COMPAT(restart:)
6245 amount = expdest - ((char *)stackblock() + resetloc);
6246 STADJUST(-amount, expdest);
6247 startp = (char *)stackblock() + startloc;
6250 rmescend = (char *)stackblock() + strloc;
6252 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6253 if (rmesc != startp) {
6255 startp = (char *)stackblock() + startloc;
6259 str = (char *)stackblock() + strloc;
6260 preglob(str, varflags & VSQUOTE, 0);
6261 workloc = expdest - (char *)stackblock();
6263 #if ENABLE_ASH_BASH_COMPAT
6264 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6265 char *idx, *end, *restart_detect;
6268 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6273 /* If there's no pattern to match, return the expansion unmolested */
6281 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6283 /* No match, advance */
6284 restart_detect = stackblock();
6285 STPUTC(*idx, expdest);
6286 if (quotes && *idx == CTLESC) {
6289 STPUTC(*idx, expdest);
6291 if (stackblock() != restart_detect)
6299 if (subtype == VSREPLACEALL) {
6301 if (quotes && *idx == CTLESC)
6310 for (loc = repl; *loc; loc++) {
6311 restart_detect = stackblock();
6312 STPUTC(*loc, expdest);
6313 if (stackblock() != restart_detect)
6318 if (subtype == VSREPLACE) {
6320 restart_detect = stackblock();
6321 STPUTC(*idx, expdest);
6322 if (stackblock() != restart_detect)
6331 /* We've put the replaced text into a buffer at workloc, now
6332 * move it to the right place and adjust the stack.
6334 startp = stackblock() + startloc;
6335 STPUTC('\0', expdest);
6336 memmove(startp, stackblock() + workloc, len);
6337 startp[len++] = '\0';
6338 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6339 STADJUST(-amount, expdest);
6342 #endif /* ENABLE_ASH_BASH_COMPAT */
6344 subtype -= VSTRIMRIGHT;
6346 if (subtype < 0 || subtype > 7)
6349 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6350 zero = subtype >> 1;
6351 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6352 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6354 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6357 memmove(startp, loc, str - loc);
6358 loc = startp + (str - loc) - 1;
6361 amount = loc - expdest;
6362 STADJUST(amount, expdest);
6368 * Add the value of a specialized variable to the stack string.
6371 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6381 int quoted = varflags & VSQUOTE;
6382 int subtype = varflags & VSTYPE;
6383 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6385 if (quoted && (flags & EXP_FULL))
6386 sep = 1 << CHAR_BIT;
6388 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6397 num = shellparam.nparam;
6407 expdest = makestrspace(NOPTS, expdest);
6408 for (i = NOPTS - 1; i >= 0; i--) {
6410 USTPUTC(optletters(i), expdest);
6420 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
6421 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6427 while ((p = *ap++) != NULL) {
6430 partlen = strlen(p);
6433 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6434 memtodest(p, partlen, syntax, quotes);
6440 if (subtype == VSPLUS || subtype == VSLENGTH) {
6461 num = atoi(name); /* number(name) fails on ${N#str} etc */
6462 if (num < 0 || num > shellparam.nparam)
6464 p = num ? shellparam.p[num - 1] : arg0;
6467 /* NB: name has form "VAR=..." */
6469 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6470 * which should be considered before we check variables. */
6472 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6476 str = var_str_list->text;
6477 eq = strchr(str, '=');
6478 if (!eq) /* stop at first non-assignment */
6481 if (name_len == (unsigned)(eq - str)
6482 && strncmp(str, name, name_len) == 0) {
6484 /* goto value; - WRONG! */
6485 /* think "A=1 A=2 B=$A" */
6487 var_str_list = var_str_list->next;
6488 } while (var_str_list);
6492 p = lookupvar(name);
6498 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6499 memtodest(p, len, syntax, quotes);
6503 if (subtype == VSPLUS || subtype == VSLENGTH)
6504 STADJUST(-len, expdest);
6509 * Expand a variable, and return a pointer to the next character in the
6513 evalvar(char *p, int flags, struct strlist *var_str_list)
6524 varflags = (unsigned char) *p++;
6525 subtype = varflags & VSTYPE;
6526 quoted = varflags & VSQUOTE;
6528 easy = (!quoted || (*var == '@' && shellparam.nparam));
6529 startloc = expdest - (char *)stackblock();
6530 p = strchr(p, '=') + 1;
6533 varlen = varvalue(var, varflags, flags, var_str_list);
6534 if (varflags & VSNUL)
6537 if (subtype == VSPLUS) {
6538 varlen = -1 - varlen;
6542 if (subtype == VSMINUS) {
6546 p, flags | EXP_TILDE |
6547 (quoted ? EXP_QWORD : EXP_WORD),
6557 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6559 if (subevalvar(p, var, /* strloc: */ 0,
6560 subtype, startloc, varflags,
6566 * Remove any recorded regions beyond
6569 removerecordregions(startloc);
6579 if (varlen < 0 && uflag)
6580 varunset(p, var, 0, 0);
6582 if (subtype == VSLENGTH) {
6583 cvtnum(varlen > 0 ? varlen : 0);
6587 if (subtype == VSNORMAL) {
6598 case VSTRIMRIGHTMAX:
6599 #if ENABLE_ASH_BASH_COMPAT
6612 * Terminate the string and start recording the pattern
6615 STPUTC('\0', expdest);
6616 patloc = expdest - (char *)stackblock();
6617 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6619 //TODO: | EXP_REDIR too? All other such places do it too
6620 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6623 int amount = expdest - (
6624 (char *)stackblock() + patloc - 1
6626 STADJUST(-amount, expdest);
6628 /* Remove any recorded regions beyond start of variable */
6629 removerecordregions(startloc);
6631 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6635 if (subtype != VSNORMAL) { /* skip to end of alternative */
6641 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6643 argbackq = argbackq->next;
6644 } else if (c == CTLVAR) {
6645 if ((*p++ & VSTYPE) != VSNORMAL)
6647 } else if (c == CTLENDVAR) {
6657 * Break the argument string into pieces based upon IFS and add the
6658 * strings to the argument list. The regions of the string to be
6659 * searched for IFS characters have been stored by recordregion.
6662 ifsbreakup(char *string, struct arglist *arglist)
6664 struct ifsregion *ifsp;
6669 const char *ifs, *realifs;
6674 if (ifslastp != NULL) {
6677 realifs = ifsset() ? ifsval() : defifs;
6680 p = string + ifsp->begoff;
6681 nulonly = ifsp->nulonly;
6682 ifs = nulonly ? nullstr : realifs;
6684 while (p < string + ifsp->endoff) {
6688 if (!strchr(ifs, *p)) {
6693 ifsspc = (strchr(defifs, *p) != NULL);
6694 /* Ignore IFS whitespace at start */
6695 if (q == start && ifsspc) {
6701 sp = stzalloc(sizeof(*sp));
6703 *arglist->lastp = sp;
6704 arglist->lastp = &sp->next;
6708 if (p >= string + ifsp->endoff) {
6714 if (strchr(ifs, *p) == NULL) {
6718 if (strchr(defifs, *p) == NULL) {
6733 } while (ifsp != NULL);
6742 sp = stzalloc(sizeof(*sp));
6744 *arglist->lastp = sp;
6745 arglist->lastp = &sp->next;
6751 struct ifsregion *p;
6756 struct ifsregion *ifsp;
6762 ifsfirst.next = NULL;
6767 * Add a file name to the list.
6770 addfname(const char *name)
6774 sp = stzalloc(sizeof(*sp));
6775 sp->text = ststrdup(name);
6777 exparg.lastp = &sp->next;
6780 static char *expdir;
6783 * Do metacharacter (i.e. *, ?, [...]) expansion.
6786 expmeta(char *enddir, char *name)
6801 for (p = name; *p; p++) {
6802 if (*p == '*' || *p == '?')
6804 else if (*p == '[') {
6811 if (*q == '/' || *q == '\0')
6818 } else if (*p == '\\')
6820 else if (*p == '/') {
6827 if (metaflag == 0) { /* we've reached the end of the file name */
6828 if (enddir != expdir)
6836 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6847 } while (p < start);
6849 if (enddir == expdir) {
6851 } else if (enddir == expdir + 1 && *expdir == '/') {
6860 if (enddir != expdir)
6862 if (*endname == 0) {
6874 while (!pending_int && (dp = readdir(dirp)) != NULL) {
6875 if (dp->d_name[0] == '.' && !matchdot)
6877 if (pmatch(start, dp->d_name)) {
6879 strcpy(enddir, dp->d_name);
6882 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6885 expmeta(p, endname);
6894 static struct strlist *
6895 msort(struct strlist *list, int len)
6897 struct strlist *p, *q = NULL;
6898 struct strlist **lpp;
6906 for (n = half; --n >= 0;) {
6910 q->next = NULL; /* terminate first half of list */
6911 q = msort(list, half); /* sort first half of list */
6912 p = msort(p, len - half); /* sort second half */
6915 #if ENABLE_LOCALE_SUPPORT
6916 if (strcoll(p->text, q->text) < 0)
6918 if (strcmp(p->text, q->text) < 0)
6942 * Sort the results of file name expansion. It calculates the number of
6943 * strings to sort and then calls msort (short for merge sort) to do the
6946 static struct strlist *
6947 expsort(struct strlist *str)
6953 for (sp = str; sp; sp = sp->next)
6955 return msort(str, len);
6959 expandmeta(struct strlist *str /*, int flag*/)
6961 static const char metachars[] ALIGN1 = {
6964 /* TODO - EXP_REDIR */
6967 struct strlist **savelastp;
6973 if (!strpbrk(str->text, metachars))
6975 savelastp = exparg.lastp;
6978 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6980 int i = strlen(str->text);
6981 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6989 if (exparg.lastp == savelastp) {
6994 *exparg.lastp = str;
6995 rmescapes(str->text, 0);
6996 exparg.lastp = &str->next;
6998 *exparg.lastp = NULL;
6999 *savelastp = sp = expsort(*savelastp);
7000 while (sp->next != NULL)
7002 exparg.lastp = &sp->next;
7009 * Perform variable substitution and command substitution on an argument,
7010 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7011 * perform splitting and file name expansion. When arglist is NULL, perform
7012 * here document expansion.
7015 expandarg(union node *arg, struct arglist *arglist, int flag)
7020 argbackq = arg->narg.backquote;
7021 STARTSTACKSTR(expdest);
7022 ifsfirst.next = NULL;
7024 argstr(arg->narg.text, flag,
7025 /* var_str_list: */ arglist ? arglist->list : NULL);
7026 p = _STPUTC('\0', expdest);
7028 if (arglist == NULL) {
7029 return; /* here document expanded */
7031 p = grabstackstr(p);
7032 exparg.lastp = &exparg.list;
7036 if (flag & EXP_FULL) {
7037 ifsbreakup(p, &exparg);
7038 *exparg.lastp = NULL;
7039 exparg.lastp = &exparg.list;
7040 expandmeta(exparg.list /*, flag*/);
7042 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7044 sp = stzalloc(sizeof(*sp));
7047 exparg.lastp = &sp->next;
7051 *exparg.lastp = NULL;
7053 *arglist->lastp = exparg.list;
7054 arglist->lastp = exparg.lastp;
7059 * Expand shell variables and backquotes inside a here document.
7062 expandhere(union node *arg, int fd)
7065 expandarg(arg, (struct arglist *)NULL, 0);
7066 full_write(fd, stackblock(), expdest - (char *)stackblock());
7070 * Returns true if the pattern matches the string.
7073 patmatch(char *pattern, const char *string)
7075 return pmatch(preglob(pattern, 0, 0), string);
7079 * See if a pattern matches in a case statement.
7082 casematch(union node *pattern, char *val)
7084 struct stackmark smark;
7087 setstackmark(&smark);
7088 argbackq = pattern->narg.backquote;
7089 STARTSTACKSTR(expdest);
7091 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7092 /* var_str_list: */ NULL);
7093 STACKSTRNUL(expdest);
7094 result = patmatch(stackblock(), val);
7095 popstackmark(&smark);
7100 /* ============ find_command */
7104 int (*builtin)(int, char **) FAST_FUNC;
7105 /* unsigned flags; */
7107 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7108 /* "regular" builtins always take precedence over commands,
7109 * regardless of PATH=....%builtin... position */
7110 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7111 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7114 smallint cmdtype; /* CMDxxx */
7117 /* index >= 0 for commands without path (slashes) */
7118 /* (TODO: what exactly does the value mean? PATH position?) */
7119 /* index == -1 for commands with slashes */
7120 /* index == (-2 - applet_no) for NOFORK applets */
7121 const struct builtincmd *cmd;
7122 struct funcnode *func;
7125 /* values of cmdtype */
7126 #define CMDUNKNOWN -1 /* no entry in table for command */
7127 #define CMDNORMAL 0 /* command is an executable program */
7128 #define CMDFUNCTION 1 /* command is a shell function */
7129 #define CMDBUILTIN 2 /* command is a shell builtin */
7131 /* action to find_command() */
7132 #define DO_ERR 0x01 /* prints errors */
7133 #define DO_ABS 0x02 /* checks absolute paths */
7134 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7135 #define DO_ALTPATH 0x08 /* using alternate path */
7136 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7138 static void find_command(char *, struct cmdentry *, int, const char *);
7141 /* ============ Hashing commands */
7144 * When commands are first encountered, they are entered in a hash table.
7145 * This ensures that a full path search will not have to be done for them
7146 * on each invocation.
7148 * We should investigate converting to a linear search, even though that
7149 * would make the command name "hash" a misnomer.
7153 struct tblentry *next; /* next entry in hash chain */
7154 union param param; /* definition of builtin function */
7155 smallint cmdtype; /* CMDxxx */
7156 char rehash; /* if set, cd done since entry created */
7157 char cmdname[1]; /* name of command */
7160 static struct tblentry **cmdtable;
7161 #define INIT_G_cmdtable() do { \
7162 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7165 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7169 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7173 #if ENABLE_FEATURE_SH_STANDALONE
7174 if (applet_no >= 0) {
7175 if (APPLET_IS_NOEXEC(applet_no)) {
7178 run_applet_no_and_exit(applet_no, argv);
7180 /* re-exec ourselves with the new arguments */
7181 execve(bb_busybox_exec_path, argv, envp);
7182 /* If they called chroot or otherwise made the binary no longer
7183 * executable, fall through */
7190 execve(cmd, argv, envp);
7191 } while (errno == EINTR);
7193 execve(cmd, argv, envp);
7199 if (errno == ENOEXEC) {
7203 for (ap = argv; *ap; ap++)
7205 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7207 ap[0] = cmd = (char *)DEFAULT_SHELL;
7210 while ((*ap++ = *argv++) != NULL)
7219 * Exec a program. Never returns. If you change this routine, you may
7220 * have to change the find_command routine as well.
7222 static void shellexec(char **, const char *, int) NORETURN;
7224 shellexec(char **argv, const char *path, int idx)
7230 #if ENABLE_FEATURE_SH_STANDALONE
7234 clearredir(/*drop:*/ 1);
7235 envp = listvars(VEXPORT, VUNSET, 0);
7236 if (strchr(argv[0], '/') != NULL
7237 #if ENABLE_FEATURE_SH_STANDALONE
7238 || (applet_no = find_applet_by_name(argv[0])) >= 0
7241 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7245 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7246 if (--idx < 0 && pathopt == NULL) {
7247 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7248 if (errno != ENOENT && errno != ENOTDIR)
7255 /* Map to POSIX errors */
7267 exitstatus = exerrno;
7268 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7269 argv[0], e, suppress_int));
7270 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7275 printentry(struct tblentry *cmdp)
7281 idx = cmdp->param.index;
7284 name = path_advance(&path, cmdp->cmdname);
7286 } while (--idx >= 0);
7287 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7291 * Clear out command entries. The argument specifies the first entry in
7292 * PATH which has changed.
7295 clearcmdentry(int firstchange)
7297 struct tblentry **tblp;
7298 struct tblentry **pp;
7299 struct tblentry *cmdp;
7302 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7304 while ((cmdp = *pp) != NULL) {
7305 if ((cmdp->cmdtype == CMDNORMAL &&
7306 cmdp->param.index >= firstchange)
7307 || (cmdp->cmdtype == CMDBUILTIN &&
7308 builtinloc >= firstchange)
7321 * Locate a command in the command hash table. If "add" is nonzero,
7322 * add the command to the table if it is not already present. The
7323 * variable "lastcmdentry" is set to point to the address of the link
7324 * pointing to the entry, so that delete_cmd_entry can delete the
7327 * Interrupts must be off if called with add != 0.
7329 static struct tblentry **lastcmdentry;
7331 static struct tblentry *
7332 cmdlookup(const char *name, int add)
7334 unsigned int hashval;
7336 struct tblentry *cmdp;
7337 struct tblentry **pp;
7340 hashval = (unsigned char)*p << 4;
7342 hashval += (unsigned char)*p++;
7344 pp = &cmdtable[hashval % CMDTABLESIZE];
7345 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7346 if (strcmp(cmdp->cmdname, name) == 0)
7350 if (add && cmdp == NULL) {
7351 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7353 /* + 1 - already done because
7354 * tblentry::cmdname is char[1] */);
7355 /*cmdp->next = NULL; - ckzalloc did it */
7356 cmdp->cmdtype = CMDUNKNOWN;
7357 strcpy(cmdp->cmdname, name);
7364 * Delete the command entry returned on the last lookup.
7367 delete_cmd_entry(void)
7369 struct tblentry *cmdp;
7372 cmdp = *lastcmdentry;
7373 *lastcmdentry = cmdp->next;
7374 if (cmdp->cmdtype == CMDFUNCTION)
7375 freefunc(cmdp->param.func);
7381 * Add a new command entry, replacing any existing command entry for
7382 * the same name - except special builtins.
7385 addcmdentry(char *name, struct cmdentry *entry)
7387 struct tblentry *cmdp;
7389 cmdp = cmdlookup(name, 1);
7390 if (cmdp->cmdtype == CMDFUNCTION) {
7391 freefunc(cmdp->param.func);
7393 cmdp->cmdtype = entry->cmdtype;
7394 cmdp->param = entry->u;
7398 static int FAST_FUNC
7399 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7401 struct tblentry **pp;
7402 struct tblentry *cmdp;
7404 struct cmdentry entry;
7407 if (nextopt("r") != '\0') {
7412 if (*argptr == NULL) {
7413 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7414 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7415 if (cmdp->cmdtype == CMDNORMAL)
7423 while ((name = *argptr) != NULL) {
7424 cmdp = cmdlookup(name, 0);
7426 && (cmdp->cmdtype == CMDNORMAL
7427 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7431 find_command(name, &entry, DO_ERR, pathval());
7432 if (entry.cmdtype == CMDUNKNOWN)
7440 * Called when a cd is done. Marks all commands so the next time they
7441 * are executed they will be rehashed.
7446 struct tblentry **pp;
7447 struct tblentry *cmdp;
7449 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7450 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7451 if (cmdp->cmdtype == CMDNORMAL
7452 || (cmdp->cmdtype == CMDBUILTIN
7453 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7463 * Fix command hash table when PATH changed.
7464 * Called before PATH is changed. The argument is the new value of PATH;
7465 * pathval() still returns the old value at this point.
7466 * Called with interrupts off.
7468 static void FAST_FUNC
7469 changepath(const char *new)
7477 firstchange = 9999; /* assume no change */
7483 if ((*old == '\0' && *new == ':')
7484 || (*old == ':' && *new == '\0'))
7486 old = new; /* ignore subsequent differences */
7490 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7496 if (builtinloc < 0 && idx_bltin >= 0)
7497 builtinloc = idx_bltin; /* zap builtins */
7498 if (builtinloc >= 0 && idx_bltin < 0)
7500 clearcmdentry(firstchange);
7501 builtinloc = idx_bltin;
7516 #define TENDBQUOTE 12
7533 typedef smallint token_id_t;
7535 /* first char is indicating which tokens mark the end of a list */
7536 static const char *const tokname_array[] = {
7550 #define KWDOFFSET 13
7551 /* the following are keywords */
7573 static char buf[16];
7576 //if (tok < TSEMI) return tokname_array[tok] + 1;
7577 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7582 sprintf(buf + (tok >= TSEMI), "%s%c",
7583 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7587 /* Wrapper around strcmp for qsort/bsearch/... */
7589 pstrcmp(const void *a, const void *b)
7591 return strcmp((char*) a, (*(char**) b) + 1);
7594 static const char *const *
7595 findkwd(const char *s)
7597 return bsearch(s, tokname_array + KWDOFFSET,
7598 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7599 sizeof(tokname_array[0]), pstrcmp);
7603 * Locate and print what a word is...
7606 describe_command(char *command, int describe_command_verbose)
7608 struct cmdentry entry;
7609 struct tblentry *cmdp;
7610 #if ENABLE_ASH_ALIAS
7611 const struct alias *ap;
7613 const char *path = pathval();
7615 if (describe_command_verbose) {
7619 /* First look at the keywords */
7620 if (findkwd(command)) {
7621 out1str(describe_command_verbose ? " is a shell keyword" : command);
7625 #if ENABLE_ASH_ALIAS
7626 /* Then look at the aliases */
7627 ap = lookupalias(command, 0);
7629 if (!describe_command_verbose) {
7634 out1fmt(" is an alias for %s", ap->val);
7638 /* Then check if it is a tracked alias */
7639 cmdp = cmdlookup(command, 0);
7641 entry.cmdtype = cmdp->cmdtype;
7642 entry.u = cmdp->param;
7644 /* Finally use brute force */
7645 find_command(command, &entry, DO_ABS, path);
7648 switch (entry.cmdtype) {
7650 int j = entry.u.index;
7656 p = path_advance(&path, command);
7660 if (describe_command_verbose) {
7662 (cmdp ? " a tracked alias for" : nullstr), p
7671 if (describe_command_verbose) {
7672 out1str(" is a shell function");
7679 if (describe_command_verbose) {
7680 out1fmt(" is a %sshell builtin",
7681 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7682 "special " : nullstr
7690 if (describe_command_verbose) {
7691 out1str(": not found\n");
7696 outstr("\n", stdout);
7700 static int FAST_FUNC
7701 typecmd(int argc UNUSED_PARAM, char **argv)
7707 /* type -p ... ? (we don't bother checking for 'p') */
7708 if (argv[1] && argv[1][0] == '-') {
7713 err |= describe_command(argv[i++], verbose);
7718 #if ENABLE_ASH_CMDCMD
7719 static int FAST_FUNC
7720 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7728 while ((c = nextopt("pvV")) != '\0')
7730 verify |= VERIFY_VERBOSE;
7732 verify |= VERIFY_BRIEF;
7737 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7738 if (verify && (*argptr != NULL)) {
7739 return describe_command(*argptr, verify - VERIFY_BRIEF);
7747 /* ============ eval.c */
7749 static int funcblocksize; /* size of structures in function */
7750 static int funcstringsize; /* size of strings in node */
7751 static void *funcblock; /* block to allocate function from */
7752 static char *funcstring; /* block to allocate strings from */
7754 /* flags in argument to evaltree */
7755 #define EV_EXIT 01 /* exit after evaluating tree */
7756 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7757 #define EV_BACKCMD 04 /* command executing within back quotes */
7759 static const short nodesize[N_NUMBER] = {
7760 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7761 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7762 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7763 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7764 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7765 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7766 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7767 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7768 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7769 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7770 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7771 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7772 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7773 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7774 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7775 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7776 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7777 #if ENABLE_ASH_BASH_COMPAT
7778 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7780 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7781 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7782 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7783 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7784 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7785 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7786 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7787 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7788 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7791 static void calcsize(union node *n);
7794 sizenodelist(struct nodelist *lp)
7797 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7804 calcsize(union node *n)
7808 funcblocksize += nodesize[n->type];
7811 calcsize(n->ncmd.redirect);
7812 calcsize(n->ncmd.args);
7813 calcsize(n->ncmd.assign);
7816 sizenodelist(n->npipe.cmdlist);
7821 calcsize(n->nredir.redirect);
7822 calcsize(n->nredir.n);
7829 calcsize(n->nbinary.ch2);
7830 calcsize(n->nbinary.ch1);
7833 calcsize(n->nif.elsepart);
7834 calcsize(n->nif.ifpart);
7835 calcsize(n->nif.test);
7838 funcstringsize += strlen(n->nfor.var) + 1;
7839 calcsize(n->nfor.body);
7840 calcsize(n->nfor.args);
7843 calcsize(n->ncase.cases);
7844 calcsize(n->ncase.expr);
7847 calcsize(n->nclist.body);
7848 calcsize(n->nclist.pattern);
7849 calcsize(n->nclist.next);
7853 sizenodelist(n->narg.backquote);
7854 funcstringsize += strlen(n->narg.text) + 1;
7855 calcsize(n->narg.next);
7858 #if ENABLE_ASH_BASH_COMPAT
7865 calcsize(n->nfile.fname);
7866 calcsize(n->nfile.next);
7870 calcsize(n->ndup.vname);
7871 calcsize(n->ndup.next);
7875 calcsize(n->nhere.doc);
7876 calcsize(n->nhere.next);
7879 calcsize(n->nnot.com);
7885 nodeckstrdup(char *s)
7887 char *rtn = funcstring;
7889 strcpy(funcstring, s);
7890 funcstring += strlen(s) + 1;
7894 static union node *copynode(union node *);
7896 static struct nodelist *
7897 copynodelist(struct nodelist *lp)
7899 struct nodelist *start;
7900 struct nodelist **lpp;
7905 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7906 (*lpp)->n = copynode(lp->n);
7908 lpp = &(*lpp)->next;
7915 copynode(union node *n)
7922 funcblock = (char *) funcblock + nodesize[n->type];
7926 new->ncmd.redirect = copynode(n->ncmd.redirect);
7927 new->ncmd.args = copynode(n->ncmd.args);
7928 new->ncmd.assign = copynode(n->ncmd.assign);
7931 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7932 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
7937 new->nredir.redirect = copynode(n->nredir.redirect);
7938 new->nredir.n = copynode(n->nredir.n);
7945 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7946 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7949 new->nif.elsepart = copynode(n->nif.elsepart);
7950 new->nif.ifpart = copynode(n->nif.ifpart);
7951 new->nif.test = copynode(n->nif.test);
7954 new->nfor.var = nodeckstrdup(n->nfor.var);
7955 new->nfor.body = copynode(n->nfor.body);
7956 new->nfor.args = copynode(n->nfor.args);
7959 new->ncase.cases = copynode(n->ncase.cases);
7960 new->ncase.expr = copynode(n->ncase.expr);
7963 new->nclist.body = copynode(n->nclist.body);
7964 new->nclist.pattern = copynode(n->nclist.pattern);
7965 new->nclist.next = copynode(n->nclist.next);
7969 new->narg.backquote = copynodelist(n->narg.backquote);
7970 new->narg.text = nodeckstrdup(n->narg.text);
7971 new->narg.next = copynode(n->narg.next);
7974 #if ENABLE_ASH_BASH_COMPAT
7981 new->nfile.fname = copynode(n->nfile.fname);
7982 new->nfile.fd = n->nfile.fd;
7983 new->nfile.next = copynode(n->nfile.next);
7987 new->ndup.vname = copynode(n->ndup.vname);
7988 new->ndup.dupfd = n->ndup.dupfd;
7989 new->ndup.fd = n->ndup.fd;
7990 new->ndup.next = copynode(n->ndup.next);
7994 new->nhere.doc = copynode(n->nhere.doc);
7995 new->nhere.fd = n->nhere.fd;
7996 new->nhere.next = copynode(n->nhere.next);
7999 new->nnot.com = copynode(n->nnot.com);
8002 new->type = n->type;
8007 * Make a copy of a parse tree.
8009 static struct funcnode *
8010 copyfunc(union node *n)
8015 funcblocksize = offsetof(struct funcnode, n);
8018 blocksize = funcblocksize;
8019 f = ckmalloc(blocksize + funcstringsize);
8020 funcblock = (char *) f + offsetof(struct funcnode, n);
8021 funcstring = (char *) f + blocksize;
8028 * Define a shell function.
8031 defun(char *name, union node *func)
8033 struct cmdentry entry;
8036 entry.cmdtype = CMDFUNCTION;
8037 entry.u.func = copyfunc(func);
8038 addcmdentry(name, &entry);
8042 /* Reasons for skipping commands (see comment on breakcmd routine) */
8043 #define SKIPBREAK (1 << 0)
8044 #define SKIPCONT (1 << 1)
8045 #define SKIPFUNC (1 << 2)
8046 #define SKIPFILE (1 << 3)
8047 #define SKIPEVAL (1 << 4)
8048 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8049 static int skipcount; /* number of levels to skip */
8050 static int funcnest; /* depth of function calls */
8051 static int loopnest; /* current loop nesting level */
8053 /* Forward decl way out to parsing code - dotrap needs it */
8054 static int evalstring(char *s, int mask);
8056 /* Called to execute a trap.
8057 * Single callsite - at the end of evaltree().
8058 * If we return non-zero, exaltree raises EXEXIT exception.
8060 * Perhaps we should avoid entering new trap handlers
8061 * while we are executing a trap handler. [is it a TODO?]
8070 savestatus = exitstatus;
8074 TRACE(("dotrap entered\n"));
8075 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8082 /* non-trapped SIGINT is handled separately by raise_interrupt,
8083 * don't upset it by resetting gotsig[SIGINT-1] */
8084 if (sig == SIGINT && !t)
8087 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8091 want_exexit = evalstring(t, SKIPEVAL);
8092 exitstatus = savestatus;
8094 TRACE(("dotrap returns %d\n", want_exexit));
8099 TRACE(("dotrap returns 0\n"));
8103 /* forward declarations - evaluation is fairly recursive business... */
8104 static void evalloop(union node *, int);
8105 static void evalfor(union node *, int);
8106 static void evalcase(union node *, int);
8107 static void evalsubshell(union node *, int);
8108 static void expredir(union node *);
8109 static void evalpipe(union node *, int);
8110 static void evalcommand(union node *, int);
8111 static int evalbltin(const struct builtincmd *, int, char **);
8112 static void prehash(union node *);
8115 * Evaluate a parse tree. The value is left in the global variable
8119 evaltree(union node *n, int flags)
8121 struct jmploc *volatile savehandler = exception_handler;
8122 struct jmploc jmploc;
8124 void (*evalfn)(union node *, int);
8128 SAVE_INT(int_level);
8131 TRACE(("evaltree(NULL) called\n"));
8134 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8136 exception_handler = &jmploc;
8138 int err = setjmp(jmploc.loc);
8140 /* if it was a signal, check for trap handlers */
8141 if (exception_type == EXSIG) {
8142 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8143 exception_type, err));
8146 /* continue on the way out */
8147 TRACE(("exception %d in evaltree, propagating err=%d\n",
8148 exception_type, err));
8149 exception_handler = savehandler;
8150 longjmp(exception_handler->loc, err);
8157 out1fmt("Node type = %d\n", n->type);
8162 evaltree(n->nnot.com, EV_TESTED);
8163 status = !exitstatus;
8166 expredir(n->nredir.redirect);
8167 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8169 evaltree(n->nredir.n, flags & EV_TESTED);
8170 status = exitstatus;
8172 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8175 evalfn = evalcommand;
8177 if (eflag && !(flags & EV_TESTED))
8189 evalfn = evalsubshell;
8202 #error NAND + 1 != NOR
8204 #if NOR + 1 != NSEMI
8205 #error NOR + 1 != NSEMI
8207 unsigned is_or = n->type - NAND;
8210 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8212 if (!exitstatus == is_or)
8225 evaltree(n->nif.test, EV_TESTED);
8228 if (exitstatus == 0) {
8232 if (n->nif.elsepart) {
8233 n = n->nif.elsepart;
8238 defun(n->narg.text, n->narg.next);
8242 exitstatus = status;
8247 exception_handler = savehandler;
8249 if (checkexit & exitstatus)
8250 evalskip |= SKIPEVAL;
8251 else if (pending_sig && dotrap())
8254 if (flags & EV_EXIT) {
8256 raise_exception(EXEXIT);
8259 RESTORE_INT(int_level);
8260 TRACE(("leaving evaltree (no interrupts)\n"));
8263 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8266 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8269 evalloop(union node *n, int flags)
8279 evaltree(n->nbinary.ch1, EV_TESTED);
8282 if (evalskip == SKIPCONT && --skipcount <= 0) {
8286 if (evalskip == SKIPBREAK && --skipcount <= 0)
8291 if (n->type != NWHILE)
8295 evaltree(n->nbinary.ch2, flags);
8296 status = exitstatus;
8301 exitstatus = status;
8305 evalfor(union node *n, int flags)
8307 struct arglist arglist;
8310 struct stackmark smark;
8312 setstackmark(&smark);
8313 arglist.list = NULL;
8314 arglist.lastp = &arglist.list;
8315 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8316 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8321 *arglist.lastp = NULL;
8326 for (sp = arglist.list; sp; sp = sp->next) {
8327 setvar(n->nfor.var, sp->text, 0);
8328 evaltree(n->nfor.body, flags);
8330 if (evalskip == SKIPCONT && --skipcount <= 0) {
8334 if (evalskip == SKIPBREAK && --skipcount <= 0)
8341 popstackmark(&smark);
8345 evalcase(union node *n, int flags)
8349 struct arglist arglist;
8350 struct stackmark smark;
8352 setstackmark(&smark);
8353 arglist.list = NULL;
8354 arglist.lastp = &arglist.list;
8355 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8357 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8358 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8359 if (casematch(patp, arglist.list->text)) {
8360 if (evalskip == 0) {
8361 evaltree(cp->nclist.body, flags);
8368 popstackmark(&smark);
8372 * Kick off a subshell to evaluate a tree.
8375 evalsubshell(union node *n, int flags)
8378 int backgnd = (n->type == NBACKGND);
8381 expredir(n->nredir.redirect);
8382 if (!backgnd && flags & EV_EXIT && !trap[0])
8385 jp = makejob(/*n,*/ 1);
8386 if (forkshell(jp, n, backgnd) == 0) {
8390 flags &=~ EV_TESTED;
8392 redirect(n->nredir.redirect, 0);
8393 evaltreenr(n->nredir.n, flags);
8398 status = waitforjob(jp);
8399 exitstatus = status;
8404 * Compute the names of the files in a redirection list.
8406 static void fixredir(union node *, const char *, int);
8408 expredir(union node *n)
8412 for (redir = n; redir; redir = redir->nfile.next) {
8416 fn.lastp = &fn.list;
8417 switch (redir->type) {
8421 #if ENABLE_ASH_BASH_COMPAT
8426 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8427 #if ENABLE_ASH_BASH_COMPAT
8430 redir->nfile.expfname = fn.list->text;
8433 case NTOFD: /* >& */
8434 if (redir->ndup.vname) {
8435 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8436 if (fn.list == NULL)
8437 ash_msg_and_raise_error("redir error");
8438 #if ENABLE_ASH_BASH_COMPAT
8439 //FIXME: we used expandarg with different args!
8440 if (!isdigit_str9(fn.list->text)) {
8441 /* >&file, not >&fd */
8442 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8443 ash_msg_and_raise_error("redir error");
8445 goto store_expfname;
8448 fixredir(redir, fn.list->text, 1);
8456 * Evaluate a pipeline. All the processes in the pipeline are children
8457 * of the process creating the pipeline. (This differs from some versions
8458 * of the shell, which make the last process in a pipeline the parent
8462 evalpipe(union node *n, int flags)
8465 struct nodelist *lp;
8470 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8472 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8476 jp = makejob(/*n,*/ pipelen);
8478 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8482 if (pipe(pip) < 0) {
8484 ash_msg_and_raise_error("pipe call failed");
8487 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8500 evaltreenr(lp->n, flags);
8506 /* Don't want to trigger debugging */
8510 if (n->npipe.pipe_backgnd == 0) {
8511 exitstatus = waitforjob(jp);
8512 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8518 * Controls whether the shell is interactive or not.
8521 setinteractive(int on)
8523 static smallint is_interactive;
8525 if (++on == is_interactive)
8527 is_interactive = on;
8531 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8532 if (is_interactive > 1) {
8533 /* Looks like they want an interactive shell */
8534 static smallint did_banner;
8539 "%s built-in shell (ash)\n"
8540 "Enter 'help' for a list of built-in commands."
8555 setinteractive(iflag);
8557 #if ENABLE_FEATURE_EDITING_VI
8559 line_input_state->flags |= VI_MODE;
8561 line_input_state->flags &= ~VI_MODE;
8563 viflag = 0; /* forcibly keep the option off */
8567 static struct localvar *localvars;
8570 * Called after a function returns.
8571 * Interrupts must be off.
8576 struct localvar *lvp;
8579 while ((lvp = localvars) != NULL) {
8580 localvars = lvp->next;
8582 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8583 if (vp == NULL) { /* $- saved */
8584 memcpy(optlist, lvp->text, sizeof(optlist));
8585 free((char*)lvp->text);
8587 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8591 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8592 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8593 free((char*)vp->text);
8594 vp->flags = lvp->flags;
8595 vp->text = lvp->text;
8602 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8604 volatile struct shparam saveparam;
8605 struct localvar *volatile savelocalvars;
8606 struct jmploc *volatile savehandler;
8607 struct jmploc jmploc;
8610 saveparam = shellparam;
8611 savelocalvars = localvars;
8612 e = setjmp(jmploc.loc);
8617 savehandler = exception_handler;
8618 exception_handler = &jmploc;
8620 shellparam.malloced = 0;
8624 shellparam.nparam = argc - 1;
8625 shellparam.p = argv + 1;
8626 #if ENABLE_ASH_GETOPTS
8627 shellparam.optind = 1;
8628 shellparam.optoff = -1;
8630 evaltree(&func->n, flags & EV_TESTED);
8636 localvars = savelocalvars;
8637 freeparam(&shellparam);
8638 shellparam = saveparam;
8639 exception_handler = savehandler;
8641 evalskip &= ~SKIPFUNC;
8645 #if ENABLE_ASH_CMDCMD
8647 parse_command_args(char **argv, const char **path)
8660 if (c == '-' && !*cp) {
8667 *path = bb_default_path;
8670 /* run 'typecmd' for other options */
8681 * Make a variable a local variable. When a variable is made local, it's
8682 * value and flags are saved in a localvar structure. The saved values
8683 * will be restored when the shell function returns. We handle the name
8684 * "-" as a special case.
8689 struct localvar *lvp;
8694 lvp = ckzalloc(sizeof(struct localvar));
8695 if (LONE_DASH(name)) {
8697 p = ckmalloc(sizeof(optlist));
8698 lvp->text = memcpy(p, optlist, sizeof(optlist));
8703 vpp = hashvar(name);
8704 vp = *findvar(vpp, name);
8705 eq = strchr(name, '=');
8708 setvareq(name, VSTRFIXED);
8710 setvar(name, NULL, VSTRFIXED);
8711 vp = *vpp; /* the new variable */
8712 lvp->flags = VUNSET;
8714 lvp->text = vp->text;
8715 lvp->flags = vp->flags;
8716 vp->flags |= VSTRFIXED|VTEXTFIXED;
8722 lvp->next = localvars;
8728 * The "local" command.
8730 static int FAST_FUNC
8731 localcmd(int argc UNUSED_PARAM, char **argv)
8736 while ((name = *argv++) != NULL) {
8742 static int FAST_FUNC
8743 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8748 static int FAST_FUNC
8749 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8754 static int FAST_FUNC
8755 execcmd(int argc UNUSED_PARAM, char **argv)
8758 iflag = 0; /* exit on error */
8761 shellexec(argv + 1, pathval(), 0);
8767 * The return command.
8769 static int FAST_FUNC
8770 returncmd(int argc UNUSED_PARAM, char **argv)
8773 * If called outside a function, do what ksh does;
8774 * skip the rest of the file.
8776 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8777 return argv[1] ? number(argv[1]) : exitstatus;
8780 /* Forward declarations for builtintab[] */
8781 static int breakcmd(int, char **) FAST_FUNC;
8782 static int dotcmd(int, char **) FAST_FUNC;
8783 static int evalcmd(int, char **) FAST_FUNC;
8784 static int exitcmd(int, char **) FAST_FUNC;
8785 static int exportcmd(int, char **) FAST_FUNC;
8786 #if ENABLE_ASH_GETOPTS
8787 static int getoptscmd(int, char **) FAST_FUNC;
8789 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8790 static int helpcmd(int, char **) FAST_FUNC;
8792 #if ENABLE_SH_MATH_SUPPORT
8793 static int letcmd(int, char **) FAST_FUNC;
8795 static int readcmd(int, char **) FAST_FUNC;
8796 static int setcmd(int, char **) FAST_FUNC;
8797 static int shiftcmd(int, char **) FAST_FUNC;
8798 static int timescmd(int, char **) FAST_FUNC;
8799 static int trapcmd(int, char **) FAST_FUNC;
8800 static int umaskcmd(int, char **) FAST_FUNC;
8801 static int unsetcmd(int, char **) FAST_FUNC;
8802 static int ulimitcmd(int, char **) FAST_FUNC;
8804 #define BUILTIN_NOSPEC "0"
8805 #define BUILTIN_SPECIAL "1"
8806 #define BUILTIN_REGULAR "2"
8807 #define BUILTIN_SPEC_REG "3"
8808 #define BUILTIN_ASSIGN "4"
8809 #define BUILTIN_SPEC_ASSG "5"
8810 #define BUILTIN_REG_ASSG "6"
8811 #define BUILTIN_SPEC_REG_ASSG "7"
8813 /* Stubs for calling non-FAST_FUNC's */
8814 #if ENABLE_ASH_BUILTIN_ECHO
8815 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8817 #if ENABLE_ASH_BUILTIN_PRINTF
8818 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8820 #if ENABLE_ASH_BUILTIN_TEST
8821 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8824 /* Keep these in proper order since it is searched via bsearch() */
8825 static const struct builtincmd builtintab[] = {
8826 { BUILTIN_SPEC_REG ".", dotcmd },
8827 { BUILTIN_SPEC_REG ":", truecmd },
8828 #if ENABLE_ASH_BUILTIN_TEST
8829 { BUILTIN_REGULAR "[", testcmd },
8830 #if ENABLE_ASH_BASH_COMPAT
8831 { BUILTIN_REGULAR "[[", testcmd },
8834 #if ENABLE_ASH_ALIAS
8835 { BUILTIN_REG_ASSG "alias", aliascmd },
8838 { BUILTIN_REGULAR "bg", fg_bgcmd },
8840 { BUILTIN_SPEC_REG "break", breakcmd },
8841 { BUILTIN_REGULAR "cd", cdcmd },
8842 { BUILTIN_NOSPEC "chdir", cdcmd },
8843 #if ENABLE_ASH_CMDCMD
8844 { BUILTIN_REGULAR "command", commandcmd },
8846 { BUILTIN_SPEC_REG "continue", breakcmd },
8847 #if ENABLE_ASH_BUILTIN_ECHO
8848 { BUILTIN_REGULAR "echo", echocmd },
8850 { BUILTIN_SPEC_REG "eval", evalcmd },
8851 { BUILTIN_SPEC_REG "exec", execcmd },
8852 { BUILTIN_SPEC_REG "exit", exitcmd },
8853 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8854 { BUILTIN_REGULAR "false", falsecmd },
8856 { BUILTIN_REGULAR "fg", fg_bgcmd },
8858 #if ENABLE_ASH_GETOPTS
8859 { BUILTIN_REGULAR "getopts", getoptscmd },
8861 { BUILTIN_NOSPEC "hash", hashcmd },
8862 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8863 { BUILTIN_NOSPEC "help", helpcmd },
8866 { BUILTIN_REGULAR "jobs", jobscmd },
8867 { BUILTIN_REGULAR "kill", killcmd },
8869 #if ENABLE_SH_MATH_SUPPORT
8870 { BUILTIN_NOSPEC "let", letcmd },
8872 { BUILTIN_ASSIGN "local", localcmd },
8873 #if ENABLE_ASH_BUILTIN_PRINTF
8874 { BUILTIN_REGULAR "printf", printfcmd },
8876 { BUILTIN_NOSPEC "pwd", pwdcmd },
8877 { BUILTIN_REGULAR "read", readcmd },
8878 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8879 { BUILTIN_SPEC_REG "return", returncmd },
8880 { BUILTIN_SPEC_REG "set", setcmd },
8881 { BUILTIN_SPEC_REG "shift", shiftcmd },
8882 { BUILTIN_SPEC_REG "source", dotcmd },
8883 #if ENABLE_ASH_BUILTIN_TEST
8884 { BUILTIN_REGULAR "test", testcmd },
8886 { BUILTIN_SPEC_REG "times", timescmd },
8887 { BUILTIN_SPEC_REG "trap", trapcmd },
8888 { BUILTIN_REGULAR "true", truecmd },
8889 { BUILTIN_NOSPEC "type", typecmd },
8890 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8891 { BUILTIN_REGULAR "umask", umaskcmd },
8892 #if ENABLE_ASH_ALIAS
8893 { BUILTIN_REGULAR "unalias", unaliascmd },
8895 { BUILTIN_SPEC_REG "unset", unsetcmd },
8896 { BUILTIN_REGULAR "wait", waitcmd },
8899 /* Should match the above table! */
8900 #define COMMANDCMD (builtintab + \
8902 1 * ENABLE_ASH_BUILTIN_TEST + \
8903 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8904 1 * ENABLE_ASH_ALIAS + \
8905 1 * ENABLE_ASH_JOB_CONTROL + \
8907 #define EXECCMD (builtintab + \
8909 1 * ENABLE_ASH_BUILTIN_TEST + \
8910 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8911 1 * ENABLE_ASH_ALIAS + \
8912 1 * ENABLE_ASH_JOB_CONTROL + \
8914 1 * ENABLE_ASH_CMDCMD + \
8916 ENABLE_ASH_BUILTIN_ECHO + \
8920 * Search the table of builtin commands.
8922 static struct builtincmd *
8923 find_builtin(const char *name)
8925 struct builtincmd *bp;
8928 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8935 * Execute a simple command.
8938 isassignment(const char *p)
8940 const char *q = endofname(p);
8945 static int FAST_FUNC
8946 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8948 /* Preserve exitstatus of a previous possible redirection
8949 * as POSIX mandates */
8950 return back_exitstatus;
8953 evalcommand(union node *cmd, int flags)
8955 static const struct builtincmd null_bltin = {
8956 "\0\0", bltincmd /* why three NULs? */
8958 struct stackmark smark;
8960 struct arglist arglist;
8961 struct arglist varlist;
8964 const struct strlist *sp;
8965 struct cmdentry cmdentry;
8972 struct builtincmd *bcmd;
8973 smallint cmd_is_exec;
8974 smallint pseudovarflag = 0;
8976 /* First expand the arguments. */
8977 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8978 setstackmark(&smark);
8979 back_exitstatus = 0;
8981 cmdentry.cmdtype = CMDBUILTIN;
8982 cmdentry.u.cmd = &null_bltin;
8983 varlist.lastp = &varlist.list;
8984 *varlist.lastp = NULL;
8985 arglist.lastp = &arglist.list;
8986 *arglist.lastp = NULL;
8989 if (cmd->ncmd.args) {
8990 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8991 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8994 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8995 struct strlist **spp;
8997 spp = arglist.lastp;
8998 if (pseudovarflag && isassignment(argp->narg.text))
8999 expandarg(argp, &arglist, EXP_VARTILDE);
9001 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9003 for (sp = *spp; sp; sp = sp->next)
9007 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9008 for (sp = arglist.list; sp; sp = sp->next) {
9009 TRACE(("evalcommand arg: %s\n", sp->text));
9010 *nargv++ = sp->text;
9015 if (iflag && funcnest == 0 && argc > 0)
9016 lastarg = nargv[-1];
9019 expredir(cmd->ncmd.redirect);
9020 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9023 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9024 struct strlist **spp;
9027 spp = varlist.lastp;
9028 expandarg(argp, &varlist, EXP_VARTILDE);
9031 * Modify the command lookup path, if a PATH= assignment
9035 if (varequal(p, path))
9039 /* Print the command if xflag is set. */
9042 const char *p = " %s";
9045 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9048 for (n = 0; n < 2; n++) {
9050 fdprintf(preverrout_fd, p, sp->text);
9058 safe_write(preverrout_fd, "\n", 1);
9064 /* Now locate the command. */
9066 const char *oldpath;
9067 int cmd_flag = DO_ERR;
9072 find_command(argv[0], &cmdentry, cmd_flag, path);
9073 if (cmdentry.cmdtype == CMDUNKNOWN) {
9079 /* implement bltin and command here */
9080 if (cmdentry.cmdtype != CMDBUILTIN)
9083 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9084 if (cmdentry.u.cmd == EXECCMD)
9086 #if ENABLE_ASH_CMDCMD
9087 if (cmdentry.u.cmd == COMMANDCMD) {
9089 nargv = parse_command_args(argv, &path);
9092 argc -= nargv - argv;
9094 cmd_flag |= DO_NOFUNC;
9102 /* We have a redirection error. */
9104 raise_exception(EXERROR);
9106 exitstatus = status;
9110 /* Execute the command. */
9111 switch (cmdentry.cmdtype) {
9114 #if ENABLE_FEATURE_SH_NOFORK
9115 /* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9116 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
9118 /* find_command() encodes applet_no as (-2 - applet_no) */
9119 int applet_no = (- cmdentry.u.index - 2);
9120 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9121 listsetvar(varlist.list, VEXPORT|VSTACK);
9122 /* run <applet>_main() */
9123 exitstatus = run_nofork_applet(applet_no, argv);
9128 /* Fork off a child process if necessary. */
9129 if (!(flags & EV_EXIT) || trap[0]) {
9131 jp = makejob(/*cmd,*/ 1);
9132 if (forkshell(jp, cmd, FORK_FG) != 0) {
9133 exitstatus = waitforjob(jp);
9135 TRACE(("forked child exited with %d\n", exitstatus));
9140 listsetvar(varlist.list, VEXPORT|VSTACK);
9141 shellexec(argv, path, cmdentry.u.index);
9145 cmdenviron = varlist.list;
9147 struct strlist *list = cmdenviron;
9149 if (spclbltin > 0 || argc == 0) {
9151 if (cmd_is_exec && argc > 1)
9154 listsetvar(list, i);
9156 /* Tight loop with builtins only:
9157 * "while kill -0 $child; do true; done"
9158 * will never exit even if $child died, unless we do this
9159 * to reap the zombie and make kill detect that it's gone: */
9160 dowait(DOWAIT_NONBLOCK, NULL);
9162 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9164 int i = exception_type;
9169 exit_status = 128 + SIGINT;
9171 exit_status = 128 + pending_sig;
9172 exitstatus = exit_status;
9173 if (i == EXINT || spclbltin > 0) {
9175 longjmp(exception_handler->loc, 1);
9182 listsetvar(varlist.list, 0);
9183 /* See above for the rationale */
9184 dowait(DOWAIT_NONBLOCK, NULL);
9185 if (evalfun(cmdentry.u.func, argc, argv, flags))
9191 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9193 /* dsl: I think this is intended to be used to support
9194 * '_' in 'vi' command mode during line editing...
9195 * However I implemented that within libedit itself.
9197 setvar("_", lastarg, 0);
9199 popstackmark(&smark);
9203 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9205 char *volatile savecmdname;
9206 struct jmploc *volatile savehandler;
9207 struct jmploc jmploc;
9210 savecmdname = commandname;
9211 i = setjmp(jmploc.loc);
9214 savehandler = exception_handler;
9215 exception_handler = &jmploc;
9216 commandname = argv[0];
9218 optptr = NULL; /* initialize nextopt */
9219 exitstatus = (*cmd->builtin)(argc, argv);
9220 flush_stdout_stderr();
9222 exitstatus |= ferror(stdout);
9224 commandname = savecmdname;
9225 exception_handler = savehandler;
9231 goodname(const char *p)
9233 return !*endofname(p);
9238 * Search for a command. This is called before we fork so that the
9239 * location of the command will be available in the parent as well as
9240 * the child. The check for "goodname" is an overly conservative
9241 * check that the name will not be subject to expansion.
9244 prehash(union node *n)
9246 struct cmdentry entry;
9248 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9249 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9253 /* ============ Builtin commands
9255 * Builtin commands whose functions are closely tied to evaluation
9256 * are implemented here.
9260 * Handle break and continue commands. Break, continue, and return are
9261 * all handled by setting the evalskip flag. The evaluation routines
9262 * above all check this flag, and if it is set they start skipping
9263 * commands rather than executing them. The variable skipcount is
9264 * the number of loops to break/continue, or the number of function
9265 * levels to return. (The latter is always 1.) It should probably
9266 * be an error to break out of more loops than exist, but it isn't
9267 * in the standard shell so we don't make it one here.
9269 static int FAST_FUNC
9270 breakcmd(int argc UNUSED_PARAM, char **argv)
9272 int n = argv[1] ? number(argv[1]) : 1;
9275 ash_msg_and_raise_error(msg_illnum, argv[1]);
9279 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9286 /* ============ input.c
9288 * This implements the input routines used by the parser.
9292 INPUT_PUSH_FILE = 1,
9293 INPUT_NOFILE_OK = 2,
9296 static smallint checkkwd;
9297 /* values of checkkwd variable */
9298 #define CHKALIAS 0x1
9303 * Push a string back onto the input at this current parsefile level.
9304 * We handle aliases this way.
9306 #if !ENABLE_ASH_ALIAS
9307 #define pushstring(s, ap) pushstring(s)
9310 pushstring(char *s, struct alias *ap)
9317 if (g_parsefile->strpush) {
9318 sp = ckzalloc(sizeof(*sp));
9319 sp->prev = g_parsefile->strpush;
9321 sp = &(g_parsefile->basestrpush);
9323 g_parsefile->strpush = sp;
9324 sp->prev_string = g_parsefile->next_to_pgetc;
9325 sp->prev_left_in_line = g_parsefile->left_in_line;
9326 #if ENABLE_ASH_ALIAS
9329 ap->flag |= ALIASINUSE;
9333 g_parsefile->next_to_pgetc = s;
9334 g_parsefile->left_in_line = len;
9341 struct strpush *sp = g_parsefile->strpush;
9344 #if ENABLE_ASH_ALIAS
9346 if (g_parsefile->next_to_pgetc[-1] == ' '
9347 || g_parsefile->next_to_pgetc[-1] == '\t'
9349 checkkwd |= CHKALIAS;
9351 if (sp->string != sp->ap->val) {
9354 sp->ap->flag &= ~ALIASINUSE;
9355 if (sp->ap->flag & ALIASDEAD) {
9356 unalias(sp->ap->name);
9360 g_parsefile->next_to_pgetc = sp->prev_string;
9361 g_parsefile->left_in_line = sp->prev_left_in_line;
9362 g_parsefile->strpush = sp->prev;
9363 if (sp != &(g_parsefile->basestrpush))
9368 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9369 //it peeks whether it is &>, and then pushes back both chars.
9370 //This function needs to save last *next_to_pgetc to buf[0]
9371 //to make two pungetc() reliable. Currently,
9372 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9377 char *buf = g_parsefile->buf;
9379 g_parsefile->next_to_pgetc = buf;
9380 #if ENABLE_FEATURE_EDITING
9382 if (!iflag || g_parsefile->fd != STDIN_FILENO)
9383 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9385 #if ENABLE_FEATURE_TAB_COMPLETION
9386 line_input_state->path_lookup = pathval();
9388 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9390 /* Ctrl+C pressed */
9399 if (nr < 0 && errno == 0) {
9400 /* Ctrl+D pressed */
9405 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9409 /* nonblock_safe_read() handles this problem */
9411 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9412 int flags = fcntl(0, F_GETFL);
9413 if (flags >= 0 && (flags & O_NONBLOCK)) {
9414 flags &= ~O_NONBLOCK;
9415 if (fcntl(0, F_SETFL, flags) >= 0) {
9416 out2str("sh: turning off NDELAY mode\n");
9427 * Refill the input buffer and return the next input character:
9429 * 1) If a string was pushed back on the input, pop it;
9430 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9431 * or we are reading from a string so we can't refill the buffer,
9433 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9434 * 4) Process input up to the next newline, deleting nul characters.
9436 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9437 #define pgetc_debug(...) ((void)0)
9439 * NB: due to SIT(c) internals (syntax_index_table[] vector),
9440 * pgetc() and related functions must return chars SIGN-EXTENDED into ints,
9441 * not zero-extended. Seems fragile to me. Affects only !USE_SIT_FUNCTION case,
9442 * so we can fix it by ditching !USE_SIT_FUNCTION if Unicode requires that.
9450 while (g_parsefile->strpush) {
9451 #if ENABLE_ASH_ALIAS
9452 if (g_parsefile->left_in_line == -1
9453 && g_parsefile->strpush->ap
9454 && g_parsefile->next_to_pgetc[-1] != ' '
9455 && g_parsefile->next_to_pgetc[-1] != '\t'
9457 pgetc_debug("preadbuffer PEOA");
9462 /* try "pgetc" now: */
9463 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9464 g_parsefile->left_in_line,
9465 g_parsefile->next_to_pgetc,
9466 g_parsefile->next_to_pgetc);
9467 if (--g_parsefile->left_in_line >= 0)
9468 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9470 /* on both branches above g_parsefile->left_in_line < 0.
9471 * "pgetc" needs refilling.
9474 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9475 * pungetc() may increment it a few times.
9476 * Assuming it won't increment it to less than -90.
9478 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9479 pgetc_debug("preadbuffer PEOF1");
9480 /* even in failure keep left_in_line and next_to_pgetc
9481 * in lock step, for correct multi-layer pungetc.
9482 * left_in_line was decremented before preadbuffer(),
9483 * must inc next_to_pgetc: */
9484 g_parsefile->next_to_pgetc++;
9488 more = g_parsefile->left_in_buffer;
9490 flush_stdout_stderr();
9494 /* don't try reading again */
9495 g_parsefile->left_in_line = -99;
9496 pgetc_debug("preadbuffer PEOF2");
9497 g_parsefile->next_to_pgetc++;
9502 /* Find out where's the end of line.
9503 * Set g_parsefile->left_in_line
9504 * and g_parsefile->left_in_buffer acordingly.
9505 * NUL chars are deleted.
9507 q = g_parsefile->next_to_pgetc;
9515 memmove(q, q + 1, more);
9519 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9525 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9526 if (g_parsefile->left_in_line < 0)
9531 g_parsefile->left_in_buffer = more;
9536 out2str(g_parsefile->next_to_pgetc);
9540 pgetc_debug("preadbuffer at %d:%p'%s'",
9541 g_parsefile->left_in_line,
9542 g_parsefile->next_to_pgetc,
9543 g_parsefile->next_to_pgetc);
9544 return signed_char2int(*g_parsefile->next_to_pgetc++);
9547 #define pgetc_as_macro() \
9548 (--g_parsefile->left_in_line >= 0 \
9549 ? signed_char2int(*g_parsefile->next_to_pgetc++) \
9556 pgetc_debug("pgetc_fast at %d:%p'%s'",
9557 g_parsefile->left_in_line,
9558 g_parsefile->next_to_pgetc,
9559 g_parsefile->next_to_pgetc);
9560 return pgetc_as_macro();
9563 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9564 #define pgetc_fast() pgetc()
9566 #define pgetc_fast() pgetc_as_macro()
9570 * Same as pgetc(), but ignores PEOA.
9572 #if ENABLE_ASH_ALIAS
9578 pgetc_debug("pgetc_fast at %d:%p'%s'",
9579 g_parsefile->left_in_line,
9580 g_parsefile->next_to_pgetc,
9581 g_parsefile->next_to_pgetc);
9583 } while (c == PEOA);
9587 #define pgetc2() pgetc()
9591 * Read a line from the script.
9594 pfgets(char *line, int len)
9600 while (--nleft > 0) {
9616 * Undo the last call to pgetc. Only one character may be pushed back.
9617 * PEOF may be pushed back.
9622 g_parsefile->left_in_line++;
9623 g_parsefile->next_to_pgetc--;
9624 pgetc_debug("pushed back to %d:%p'%s'",
9625 g_parsefile->left_in_line,
9626 g_parsefile->next_to_pgetc,
9627 g_parsefile->next_to_pgetc);
9631 * To handle the "." command, a stack of input files is used. Pushfile
9632 * adds a new entry to the stack and popfile restores the previous level.
9637 struct parsefile *pf;
9639 pf = ckzalloc(sizeof(*pf));
9640 pf->prev = g_parsefile;
9642 /*pf->strpush = NULL; - ckzalloc did it */
9643 /*pf->basestrpush.prev = NULL;*/
9650 struct parsefile *pf = g_parsefile;
9658 g_parsefile = pf->prev;
9664 * Return to top level.
9669 while (g_parsefile != &basepf)
9674 * Close the file(s) that the shell is reading commands from. Called
9675 * after a fork is done.
9681 if (g_parsefile->fd > 0) {
9682 close(g_parsefile->fd);
9683 g_parsefile->fd = 0;
9688 * Like setinputfile, but takes an open file descriptor. Call this with
9692 setinputfd(int fd, int push)
9694 close_on_exec_on(fd);
9697 g_parsefile->buf = NULL;
9699 g_parsefile->fd = fd;
9700 if (g_parsefile->buf == NULL)
9701 g_parsefile->buf = ckmalloc(IBUFSIZ);
9702 g_parsefile->left_in_buffer = 0;
9703 g_parsefile->left_in_line = 0;
9704 g_parsefile->linno = 1;
9708 * Set the input to take input from a file. If push is set, push the
9709 * old input onto the stack first.
9712 setinputfile(const char *fname, int flags)
9718 fd = open(fname, O_RDONLY);
9720 if (flags & INPUT_NOFILE_OK)
9722 ash_msg_and_raise_error("can't open '%s'", fname);
9725 fd2 = copyfd(fd, 10);
9728 ash_msg_and_raise_error("out of file descriptors");
9731 setinputfd(fd, flags & INPUT_PUSH_FILE);
9738 * Like setinputfile, but takes input from a string.
9741 setinputstring(char *string)
9745 g_parsefile->next_to_pgetc = string;
9746 g_parsefile->left_in_line = strlen(string);
9747 g_parsefile->buf = NULL;
9748 g_parsefile->linno = 1;
9753 /* ============ mail.c
9755 * Routines to check for mail.
9760 #define MAXMBOXES 10
9762 /* times of mailboxes */
9763 static time_t mailtime[MAXMBOXES];
9764 /* Set if MAIL or MAILPATH is changed. */
9765 static smallint mail_var_path_changed;
9768 * Print appropriate message(s) if mail has arrived.
9769 * If mail_var_path_changed is set,
9770 * then the value of MAIL has mail_var_path_changed,
9771 * so we just update the values.
9780 struct stackmark smark;
9783 setstackmark(&smark);
9784 mpath = mpathset() ? mpathval() : mailval();
9785 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9786 p = path_advance(&mpath, nullstr);
9791 for (q = p; *q; q++)
9797 q[-1] = '\0'; /* delete trailing '/' */
9798 if (stat(p, &statb) < 0) {
9802 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9805 pathopt ? pathopt : "you have mail"
9808 *mtp = statb.st_mtime;
9810 mail_var_path_changed = 0;
9811 popstackmark(&smark);
9814 static void FAST_FUNC
9815 changemail(const char *val UNUSED_PARAM)
9817 mail_var_path_changed = 1;
9820 #endif /* ASH_MAIL */
9823 /* ============ ??? */
9826 * Set the shell parameters.
9829 setparam(char **argv)
9835 for (nparam = 0; argv[nparam]; nparam++)
9837 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9839 *ap++ = ckstrdup(*argv++);
9842 freeparam(&shellparam);
9843 shellparam.malloced = 1;
9844 shellparam.nparam = nparam;
9845 shellparam.p = newparam;
9846 #if ENABLE_ASH_GETOPTS
9847 shellparam.optind = 1;
9848 shellparam.optoff = -1;
9853 * Process shell options. The global variable argptr contains a pointer
9854 * to the argument list; we advance it past the options.
9856 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9857 * For a non-interactive shell, an error condition encountered
9858 * by a special built-in ... shall cause the shell to write a diagnostic message
9859 * to standard error and exit as shown in the following table:
9860 * Error Special Built-In
9862 * Utility syntax error (option or operand error) Shall exit
9864 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9865 * we see that bash does not do that (set "finishes" with error code 1 instead,
9866 * and shell continues), and people rely on this behavior!
9868 * set -o barfoo 2>/dev/null
9871 * Oh well. Let's mimic that.
9874 plus_minus_o(char *name, int val)
9879 for (i = 0; i < NOPTS; i++) {
9880 if (strcmp(name, optnames(i)) == 0) {
9885 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9888 for (i = 0; i < NOPTS; i++) {
9890 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9892 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9898 setoption(int flag, int val)
9902 for (i = 0; i < NOPTS; i++) {
9903 if (optletters(i) == flag) {
9908 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9912 options(int cmdline)
9920 while ((p = *argptr) != NULL) {
9922 if (c != '-' && c != '+')
9925 val = 0; /* val = 0 if c == '+' */
9928 if (p[0] == '\0' || LONE_DASH(p)) {
9930 /* "-" means turn off -x and -v */
9933 /* "--" means reset params */
9934 else if (*argptr == NULL)
9937 break; /* "-" or "--" terminates options */
9940 /* first char was + or - */
9941 while ((c = *p++) != '\0') {
9942 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9943 if (c == 'c' && cmdline) {
9944 minusc = p; /* command is after shell args */
9945 } else if (c == 'o') {
9946 if (plus_minus_o(*argptr, val)) {
9947 /* it already printed err message */
9948 return 1; /* error */
9952 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9954 /* bash does not accept +-login, we also won't */
9955 } else if (cmdline && val && (c == '-')) { /* long options */
9956 if (strcmp(p, "login") == 0)
9968 * The shift builtin command.
9970 static int FAST_FUNC
9971 shiftcmd(int argc UNUSED_PARAM, char **argv)
9978 n = number(argv[1]);
9979 if (n > shellparam.nparam)
9980 n = 0; /* bash compat, was = shellparam.nparam; */
9982 shellparam.nparam -= n;
9983 for (ap1 = shellparam.p; --n >= 0; ap1++) {
9984 if (shellparam.malloced)
9988 while ((*ap2++ = *ap1++) != NULL)
9990 #if ENABLE_ASH_GETOPTS
9991 shellparam.optind = 1;
9992 shellparam.optoff = -1;
9999 * POSIX requires that 'set' (but not export or readonly) output the
10000 * variables in lexicographic order - by the locale's collating order (sigh).
10001 * Maybe we could keep them in an ordered balanced binary tree
10002 * instead of hashed lists.
10003 * For now just roll 'em through qsort for printing...
10006 showvars(const char *sep_prefix, int on, int off)
10009 char **ep, **epend;
10011 ep = listvars(on, off, &epend);
10012 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10014 sep = *sep_prefix ? " " : sep_prefix;
10016 for (; ep < epend; ep++) {
10020 p = strchrnul(*ep, '=');
10023 q = single_quote(++p);
10024 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10030 * The set command builtin.
10032 static int FAST_FUNC
10033 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10038 return showvars(nullstr, 0, VUNSET);
10041 if (!options(0)) { /* if no parse error... */
10044 if (*argptr != NULL) {
10052 #if ENABLE_ASH_RANDOM_SUPPORT
10053 static void FAST_FUNC
10054 change_random(const char *value)
10056 /* Galois LFSR parameter */
10057 /* Taps at 32 31 29 1: */
10058 enum { MASK = 0x8000000b };
10059 /* Another example - taps at 32 31 30 10: */
10060 /* MASK = 0x00400007 */
10062 if (value == NULL) {
10063 /* "get", generate */
10066 /* LCG has period of 2^32 and alternating lowest bit */
10067 random_LCG = 1664525 * random_LCG + 1013904223;
10068 /* Galois LFSR has period of 2^32-1 = 3 * 5 * 17 * 257 * 65537 */
10069 t = (random_galois_LFSR << 1);
10070 if (random_galois_LFSR < 0) /* if we just shifted 1 out of msb... */
10072 random_galois_LFSR = t;
10073 /* Both are weak, combining them gives better randomness
10074 * and ~2^64 period. & 0x7fff is probably bash compat
10075 * for $RANDOM range. Combining with subtraction is
10076 * just for fun. + and ^ would work equally well. */
10077 t = (t - random_LCG) & 0x7fff;
10078 /* set without recursion */
10079 setvar(vrandom.text, utoa(t), VNOFUNC);
10080 vrandom.flags &= ~VNOFUNC;
10083 random_galois_LFSR = random_LCG = strtoul(value, NULL, 10);
10088 #if ENABLE_ASH_GETOPTS
10090 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10099 if (*param_optind < 1)
10101 optnext = optfirst + *param_optind - 1;
10103 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10106 p = optnext[-1] + *optoff;
10107 if (p == NULL || *p == '\0') {
10108 /* Current word is done, advance */
10110 if (p == NULL || *p != '-' || *++p == '\0') {
10117 if (LONE_DASH(p)) /* check for "--" */
10122 for (q = optstr; *q != c;) {
10124 if (optstr[0] == ':') {
10127 err |= setvarsafe("OPTARG", s, 0);
10129 fprintf(stderr, "Illegal option -%c\n", c);
10130 unsetvar("OPTARG");
10140 if (*p == '\0' && (p = *optnext) == NULL) {
10141 if (optstr[0] == ':') {
10144 err |= setvarsafe("OPTARG", s, 0);
10147 fprintf(stderr, "No arg for -%c option\n", c);
10148 unsetvar("OPTARG");
10156 err |= setvarsafe("OPTARG", p, 0);
10159 err |= setvarsafe("OPTARG", nullstr, 0);
10161 *optoff = p ? p - *(optnext - 1) : -1;
10162 *param_optind = optnext - optfirst + 1;
10163 fmtstr(s, sizeof(s), "%d", *param_optind);
10164 err |= setvarsafe("OPTIND", s, VNOFUNC);
10167 err |= setvarsafe(optvar, s, 0);
10171 flush_stdout_stderr();
10172 raise_exception(EXERROR);
10178 * The getopts builtin. Shellparam.optnext points to the next argument
10179 * to be processed. Shellparam.optptr points to the next character to
10180 * be processed in the current argument. If shellparam.optnext is NULL,
10181 * then it's the first time getopts has been called.
10183 static int FAST_FUNC
10184 getoptscmd(int argc, char **argv)
10189 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10191 optbase = shellparam.p;
10192 if (shellparam.optind > shellparam.nparam + 1) {
10193 shellparam.optind = 1;
10194 shellparam.optoff = -1;
10197 optbase = &argv[3];
10198 if (shellparam.optind > argc - 2) {
10199 shellparam.optind = 1;
10200 shellparam.optoff = -1;
10204 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10205 &shellparam.optoff);
10207 #endif /* ASH_GETOPTS */
10210 /* ============ Shell parser */
10213 struct heredoc *next; /* next here document in list */
10214 union node *here; /* redirection node */
10215 char *eofmark; /* string indicating end of input */
10216 smallint striptabs; /* if set, strip leading tabs */
10219 static smallint tokpushback; /* last token pushed back */
10220 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10221 static smallint quoteflag; /* set if (part of) last token was quoted */
10222 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10223 static struct heredoc *heredoclist; /* list of here documents to read */
10224 static char *wordtext; /* text of last word returned by readtoken */
10225 static struct nodelist *backquotelist;
10226 static union node *redirnode;
10227 static struct heredoc *heredoc;
10230 * Called when an unexpected token is read during the parse. The argument
10231 * is the token that is expected, or -1 if more than one type of token can
10232 * occur at this point.
10234 static void raise_error_unexpected_syntax(int) NORETURN;
10236 raise_error_unexpected_syntax(int token)
10241 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
10243 sprintf(msg + l, " (expecting %s)", tokname(token));
10244 raise_error_syntax(msg);
10248 #define EOFMARKLEN 79
10250 /* parsing is heavily cross-recursive, need these forward decls */
10251 static union node *andor(void);
10252 static union node *pipeline(void);
10253 static union node *parse_command(void);
10254 static void parseheredoc(void);
10255 static char peektoken(void);
10256 static int readtoken(void);
10258 static union node *
10261 union node *n1, *n2, *n3;
10264 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10265 if (nlflag == 2 && peektoken())
10271 if (tok == TBACKGND) {
10272 if (n2->type == NPIPE) {
10273 n2->npipe.pipe_backgnd = 1;
10275 if (n2->type != NREDIR) {
10276 n3 = stzalloc(sizeof(struct nredir));
10278 /*n3->nredir.redirect = NULL; - stzalloc did it */
10281 n2->type = NBACKGND;
10287 n3 = stzalloc(sizeof(struct nbinary));
10289 n3->nbinary.ch1 = n1;
10290 n3->nbinary.ch2 = n2;
10306 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10314 pungetc(); /* push back EOF on input */
10318 raise_error_unexpected_syntax(-1);
10325 static union node *
10328 union node *n1, *n2, *n3;
10336 } else if (t == TOR) {
10342 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10344 n3 = stzalloc(sizeof(struct nbinary));
10346 n3->nbinary.ch1 = n1;
10347 n3->nbinary.ch2 = n2;
10352 static union node *
10355 union node *n1, *n2, *pipenode;
10356 struct nodelist *lp, *prev;
10360 TRACE(("pipeline: entered\n"));
10361 if (readtoken() == TNOT) {
10363 checkkwd = CHKKWD | CHKALIAS;
10366 n1 = parse_command();
10367 if (readtoken() == TPIPE) {
10368 pipenode = stzalloc(sizeof(struct npipe));
10369 pipenode->type = NPIPE;
10370 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10371 lp = stzalloc(sizeof(struct nodelist));
10372 pipenode->npipe.cmdlist = lp;
10376 lp = stzalloc(sizeof(struct nodelist));
10377 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10378 lp->n = parse_command();
10380 } while (readtoken() == TPIPE);
10386 n2 = stzalloc(sizeof(struct nnot));
10394 static union node *
10399 n = stzalloc(sizeof(struct narg));
10401 /*n->narg.next = NULL; - stzalloc did it */
10402 n->narg.text = wordtext;
10403 n->narg.backquote = backquotelist;
10408 fixredir(union node *n, const char *text, int err)
10412 TRACE(("Fix redir %s %d\n", text, err));
10414 n->ndup.vname = NULL;
10416 fd = bb_strtou(text, NULL, 10);
10417 if (!errno && fd >= 0)
10418 n->ndup.dupfd = fd;
10419 else if (LONE_DASH(text))
10420 n->ndup.dupfd = -1;
10423 raise_error_syntax("bad fd number");
10424 n->ndup.vname = makename();
10429 * Returns true if the text contains nothing to expand (no dollar signs
10433 noexpand(const char *text)
10439 while ((c = *p++) != '\0') {
10440 if (c == CTLQUOTEMARK)
10444 else if (SIT((signed char)c, BASESYNTAX) == CCTL)
10453 union node *n = redirnode;
10455 if (readtoken() != TWORD)
10456 raise_error_unexpected_syntax(-1);
10457 if (n->type == NHERE) {
10458 struct heredoc *here = heredoc;
10462 if (quoteflag == 0)
10464 TRACE(("Here document %d\n", n->type));
10465 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10466 raise_error_syntax("illegal eof marker for << redirection");
10467 rmescapes(wordtext, 0);
10468 here->eofmark = wordtext;
10470 if (heredoclist == NULL)
10471 heredoclist = here;
10473 for (p = heredoclist; p->next; p = p->next)
10477 } else if (n->type == NTOFD || n->type == NFROMFD) {
10478 fixredir(n, wordtext, 0);
10480 n->nfile.fname = makename();
10484 static union node *
10487 union node *args, **app;
10488 union node *n = NULL;
10489 union node *vars, **vpp;
10490 union node **rpp, *redir;
10492 #if ENABLE_ASH_BASH_COMPAT
10493 smallint double_brackets_flag = 0;
10503 savecheckkwd = CHKALIAS;
10506 checkkwd = savecheckkwd;
10509 #if ENABLE_ASH_BASH_COMPAT
10510 case TAND: /* "&&" */
10511 case TOR: /* "||" */
10512 if (!double_brackets_flag) {
10516 wordtext = (char *) (t == TAND ? "-a" : "-o");
10519 n = stzalloc(sizeof(struct narg));
10521 /*n->narg.next = NULL; - stzalloc did it */
10522 n->narg.text = wordtext;
10523 #if ENABLE_ASH_BASH_COMPAT
10524 if (strcmp("[[", wordtext) == 0)
10525 double_brackets_flag = 1;
10526 else if (strcmp("]]", wordtext) == 0)
10527 double_brackets_flag = 0;
10529 n->narg.backquote = backquotelist;
10530 if (savecheckkwd && isassignment(wordtext)) {
10532 vpp = &n->narg.next;
10535 app = &n->narg.next;
10540 *rpp = n = redirnode;
10541 rpp = &n->nfile.next;
10542 parsefname(); /* read name of redirection file */
10545 if (args && app == &args->narg.next
10548 struct builtincmd *bcmd;
10551 /* We have a function */
10552 if (readtoken() != TRP)
10553 raise_error_unexpected_syntax(TRP);
10554 name = n->narg.text;
10555 if (!goodname(name)
10556 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10558 raise_error_syntax("bad function name");
10561 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10562 n->narg.next = parse_command();
10575 n = stzalloc(sizeof(struct ncmd));
10577 n->ncmd.args = args;
10578 n->ncmd.assign = vars;
10579 n->ncmd.redirect = redir;
10583 static union node *
10584 parse_command(void)
10586 union node *n1, *n2;
10587 union node *ap, **app;
10588 union node *cp, **cpp;
10589 union node *redir, **rpp;
10596 switch (readtoken()) {
10598 raise_error_unexpected_syntax(-1);
10601 n1 = stzalloc(sizeof(struct nif));
10603 n1->nif.test = list(0);
10604 if (readtoken() != TTHEN)
10605 raise_error_unexpected_syntax(TTHEN);
10606 n1->nif.ifpart = list(0);
10608 while (readtoken() == TELIF) {
10609 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10610 n2 = n2->nif.elsepart;
10612 n2->nif.test = list(0);
10613 if (readtoken() != TTHEN)
10614 raise_error_unexpected_syntax(TTHEN);
10615 n2->nif.ifpart = list(0);
10617 if (lasttoken == TELSE)
10618 n2->nif.elsepart = list(0);
10620 n2->nif.elsepart = NULL;
10628 n1 = stzalloc(sizeof(struct nbinary));
10629 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10630 n1->nbinary.ch1 = list(0);
10633 TRACE(("expecting DO got %s %s\n", tokname(got),
10634 got == TWORD ? wordtext : ""));
10635 raise_error_unexpected_syntax(TDO);
10637 n1->nbinary.ch2 = list(0);
10642 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10643 raise_error_syntax("bad for loop variable");
10644 n1 = stzalloc(sizeof(struct nfor));
10646 n1->nfor.var = wordtext;
10647 checkkwd = CHKKWD | CHKALIAS;
10648 if (readtoken() == TIN) {
10650 while (readtoken() == TWORD) {
10651 n2 = stzalloc(sizeof(struct narg));
10653 /*n2->narg.next = NULL; - stzalloc did it */
10654 n2->narg.text = wordtext;
10655 n2->narg.backquote = backquotelist;
10657 app = &n2->narg.next;
10660 n1->nfor.args = ap;
10661 if (lasttoken != TNL && lasttoken != TSEMI)
10662 raise_error_unexpected_syntax(-1);
10664 n2 = stzalloc(sizeof(struct narg));
10666 /*n2->narg.next = NULL; - stzalloc did it */
10667 n2->narg.text = (char *)dolatstr;
10668 /*n2->narg.backquote = NULL;*/
10669 n1->nfor.args = n2;
10671 * Newline or semicolon here is optional (but note
10672 * that the original Bourne shell only allowed NL).
10674 if (lasttoken != TNL && lasttoken != TSEMI)
10677 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10678 if (readtoken() != TDO)
10679 raise_error_unexpected_syntax(TDO);
10680 n1->nfor.body = list(0);
10684 n1 = stzalloc(sizeof(struct ncase));
10686 if (readtoken() != TWORD)
10687 raise_error_unexpected_syntax(TWORD);
10688 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10690 /*n2->narg.next = NULL; - stzalloc did it */
10691 n2->narg.text = wordtext;
10692 n2->narg.backquote = backquotelist;
10694 checkkwd = CHKKWD | CHKALIAS;
10695 } while (readtoken() == TNL);
10696 if (lasttoken != TIN)
10697 raise_error_unexpected_syntax(TIN);
10698 cpp = &n1->ncase.cases;
10700 checkkwd = CHKNL | CHKKWD;
10702 while (t != TESAC) {
10703 if (lasttoken == TLP)
10705 *cpp = cp = stzalloc(sizeof(struct nclist));
10707 app = &cp->nclist.pattern;
10709 *app = ap = stzalloc(sizeof(struct narg));
10711 /*ap->narg.next = NULL; - stzalloc did it */
10712 ap->narg.text = wordtext;
10713 ap->narg.backquote = backquotelist;
10714 if (readtoken() != TPIPE)
10716 app = &ap->narg.next;
10719 //ap->narg.next = NULL;
10720 if (lasttoken != TRP)
10721 raise_error_unexpected_syntax(TRP);
10722 cp->nclist.body = list(2);
10724 cpp = &cp->nclist.next;
10726 checkkwd = CHKNL | CHKKWD;
10730 raise_error_unexpected_syntax(TENDCASE);
10737 n1 = stzalloc(sizeof(struct nredir));
10738 n1->type = NSUBSHELL;
10739 n1->nredir.n = list(0);
10740 /*n1->nredir.redirect = NULL; - stzalloc did it */
10750 return simplecmd();
10753 if (readtoken() != t)
10754 raise_error_unexpected_syntax(t);
10757 /* Now check for redirection which may follow command */
10758 checkkwd = CHKKWD | CHKALIAS;
10760 while (readtoken() == TREDIR) {
10761 *rpp = n2 = redirnode;
10762 rpp = &n2->nfile.next;
10768 if (n1->type != NSUBSHELL) {
10769 n2 = stzalloc(sizeof(struct nredir));
10774 n1->nredir.redirect = redir;
10779 #if ENABLE_ASH_BASH_COMPAT
10780 static int decode_dollar_squote(void)
10782 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10788 p = strchr(C_escapes, c);
10793 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10797 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10799 } else if (c == 'x') { /* \xHH */
10803 } while (isxdigit(c) && --cnt);
10805 if (cnt == 3) { /* \x but next char is "bad" */
10809 } else { /* simple seq like \\ or \t */
10814 c = bb_process_escape_sequence((void*)&p);
10815 } else { /* unrecognized "\z": print both chars unless ' or " */
10816 if (c != '\'' && c != '"') {
10818 c |= 0x100; /* "please encode \, then me" */
10826 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10827 * is not NULL, read a here document. In the latter case, eofmark is the
10828 * word which marks the end of the document and striptabs is true if
10829 * leading tabs should be stripped from the document. The argument firstc
10830 * is the first character of the input token or document.
10832 * Because C does not have internal subroutines, I have simulated them
10833 * using goto's to implement the subroutine linkage. The following macros
10834 * will run code that appears at the end of readtoken1.
10836 #define CHECKEND() {goto checkend; checkend_return:;}
10837 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10838 #define PARSESUB() {goto parsesub; parsesub_return:;}
10839 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10840 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10841 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10843 readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
10845 /* NB: syntax parameter fits into smallint */
10849 char line[EOFMARKLEN + 1];
10850 struct nodelist *bqlist;
10854 smallint prevsyntax; /* syntax before arithmetic */
10855 #if ENABLE_ASH_EXPAND_PRMT
10856 smallint pssyntax; /* we are expanding a prompt string */
10858 int varnest; /* levels of variables expansion */
10859 int arinest; /* levels of arithmetic expansion */
10860 int parenlevel; /* levels of parens in arithmetic */
10861 int dqvarnest; /* levels of variables expansion within double quotes */
10863 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10866 /* Avoid longjmp clobbering */
10872 (void) &parenlevel;
10875 (void) &prevsyntax;
10878 startlinno = g_parsefile->linno;
10883 #if ENABLE_ASH_EXPAND_PRMT
10884 pssyntax = (syntax == PSSYNTAX);
10888 dblquote = (syntax == DQSYNTAX);
10894 STARTSTACKSTR(out);
10896 /* For each line, until end of word */
10898 CHECKEND(); /* set c to PEOF if at end of here document */
10899 for (;;) { /* until end of line or end of word */
10900 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10901 switch (SIT(c, syntax)) {
10902 case CNL: /* '\n' */
10903 if (syntax == BASESYNTAX)
10904 goto endword; /* exit outer loop */
10906 g_parsefile->linno++;
10910 goto loop; /* continue outer loop */
10915 if (eofmark == NULL || dblquote)
10916 USTPUTC(CTLESC, out);
10917 #if ENABLE_ASH_BASH_COMPAT
10918 if (c == '\\' && bash_dollar_squote) {
10919 c = decode_dollar_squote();
10921 USTPUTC('\\', out);
10922 c = (unsigned char)c;
10928 case CBACK: /* backslash */
10931 USTPUTC(CTLESC, out);
10932 USTPUTC('\\', out);
10934 } else if (c == '\n') {
10938 #if ENABLE_ASH_EXPAND_PRMT
10939 if (c == '$' && pssyntax) {
10940 USTPUTC(CTLESC, out);
10941 USTPUTC('\\', out);
10944 if (dblquote && c != '\\'
10945 && c != '`' && c != '$'
10946 && (c != '"' || eofmark != NULL)
10948 USTPUTC(CTLESC, out);
10949 USTPUTC('\\', out);
10951 if (SIT(c, SQSYNTAX) == CCTL)
10952 USTPUTC(CTLESC, out);
10960 if (eofmark == NULL) {
10961 USTPUTC(CTLQUOTEMARK, out);
10969 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
10970 if (eofmark != NULL && arinest == 0
10975 if (dqvarnest == 0) {
10976 syntax = BASESYNTAX;
10983 case CVAR: /* '$' */
10984 PARSESUB(); /* parse substitution */
10986 case CENDVAR: /* '}' */
10989 if (dqvarnest > 0) {
10992 USTPUTC(CTLENDVAR, out);
10997 #if ENABLE_SH_MATH_SUPPORT
10998 case CLP: /* '(' in arithmetic */
11002 case CRP: /* ')' in arithmetic */
11003 if (parenlevel > 0) {
11007 if (pgetc() == ')') {
11008 if (--arinest == 0) {
11009 USTPUTC(CTLENDARI, out);
11010 syntax = prevsyntax;
11011 dblquote = (syntax == DQSYNTAX);
11016 * unbalanced parens
11017 * (don't 2nd guess - no error)
11025 case CBQUOTE: /* '`' */
11029 goto endword; /* exit outer loop */
11033 if (varnest == 0) {
11034 #if ENABLE_ASH_BASH_COMPAT
11036 if (pgetc() == '>')
11037 c = 0x100 + '>'; /* flag &> */
11041 goto endword; /* exit outer loop */
11043 #if ENABLE_ASH_ALIAS
11053 #if ENABLE_SH_MATH_SUPPORT
11054 if (syntax == ARISYNTAX)
11055 raise_error_syntax("missing '))'");
11057 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11058 raise_error_syntax("unterminated quoted string");
11059 if (varnest != 0) {
11060 startlinno = g_parsefile->linno;
11062 raise_error_syntax("missing '}'");
11064 USTPUTC('\0', out);
11065 len = out - (char *)stackblock();
11066 out = stackblock();
11067 if (eofmark == NULL) {
11068 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11071 if (isdigit_str9(out)) {
11072 PARSEREDIR(); /* passed as params: out, c */
11073 lasttoken = TREDIR;
11076 /* else: non-number X seen, interpret it
11077 * as "NNNX>file" = "NNNX >file" */
11081 quoteflag = quotef;
11082 backquotelist = bqlist;
11083 grabstackblock(len);
11087 /* end of readtoken routine */
11090 * Check to see whether we are at the end of the here document. When this
11091 * is called, c is set to the first character of the next input line. If
11092 * we are at the end of the here document, this routine sets the c to PEOF.
11096 #if ENABLE_ASH_ALIAS
11102 while (c == '\t') {
11106 if (c == *eofmark) {
11107 if (pfgets(line, sizeof(line)) != NULL) {
11111 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11113 if (*p == '\n' && *q == '\0') {
11115 g_parsefile->linno++;
11116 needprompt = doprompt;
11118 pushstring(line, NULL);
11123 goto checkend_return;
11127 * Parse a redirection operator. The variable "out" points to a string
11128 * specifying the fd to be redirected. The variable "c" contains the
11129 * first character of the redirection operator.
11132 /* out is already checked to be a valid number or "" */
11133 int fd = (*out == '\0' ? -1 : atoi(out));
11136 np = stzalloc(sizeof(struct nfile));
11141 np->type = NAPPEND;
11143 np->type = NCLOBBER;
11146 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11152 #if ENABLE_ASH_BASH_COMPAT
11153 else if (c == 0x100 + '>') { /* this flags &> redirection */
11155 pgetc(); /* this is '>', no need to check */
11159 else { /* c == '<' */
11160 /*np->nfile.fd = 0; - stzalloc did it */
11164 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11165 np = stzalloc(sizeof(struct nhere));
11166 /*np->nfile.fd = 0; - stzalloc did it */
11169 heredoc = stzalloc(sizeof(struct heredoc));
11170 heredoc->here = np;
11173 heredoc->striptabs = 1;
11175 /*heredoc->striptabs = 0; - stzalloc did it */
11181 np->type = NFROMFD;
11185 np->type = NFROMTO;
11197 goto parseredir_return;
11201 * Parse a substitution. At this point, we have read the dollar sign
11202 * and nothing else.
11205 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11206 * (assuming ascii char codes, as the original implementation did) */
11207 #define is_special(c) \
11208 (((unsigned)(c) - 33 < 32) \
11209 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11215 static const char types[] ALIGN1 = "}-+?=";
11218 if (c <= PEOA_OR_PEOF
11219 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11221 #if ENABLE_ASH_BASH_COMPAT
11223 bash_dollar_squote = 1;
11228 } else if (c == '(') { /* $(command) or $((arith)) */
11229 if (pgetc() == '(') {
11230 #if ENABLE_SH_MATH_SUPPORT
11233 raise_error_syntax("you disabled math support for $((arith)) syntax");
11240 USTPUTC(CTLVAR, out);
11241 typeloc = out - (char *)stackblock();
11242 USTPUTC(VSNORMAL, out);
11243 subtype = VSNORMAL;
11251 subtype = VSLENGTH;
11255 if (c > PEOA_OR_PEOF && is_name(c)) {
11259 } while (c > PEOA_OR_PEOF && is_in_name(c));
11260 } else if (isdigit(c)) {
11264 } while (isdigit(c));
11265 } else if (is_special(c)) {
11270 raise_error_syntax("bad substitution");
11275 if (subtype == 0) {
11279 #if ENABLE_ASH_BASH_COMPAT
11280 if (c == ':' || c == '$' || isdigit(c)) {
11282 subtype = VSSUBSTR;
11289 p = strchr(types, c);
11292 subtype = p - types + VSNORMAL;
11297 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11305 #if ENABLE_ASH_BASH_COMPAT
11307 subtype = VSREPLACE;
11310 subtype++; /* VSREPLACEALL */
11319 if (dblquote || arinest)
11321 *((char *)stackblock() + typeloc) = subtype | flags;
11322 if (subtype != VSNORMAL) {
11324 if (dblquote || arinest) {
11329 goto parsesub_return;
11333 * Called to parse command substitutions. Newstyle is set if the command
11334 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11335 * list of commands (passed by reference), and savelen is the number of
11336 * characters on the top of the stack which must be preserved.
11339 struct nodelist **nlpp;
11342 char *volatile str;
11343 struct jmploc jmploc;
11344 struct jmploc *volatile savehandler;
11346 smallint saveprompt = 0;
11349 (void) &saveprompt;
11351 savepbq = parsebackquote;
11352 if (setjmp(jmploc.loc)) {
11354 parsebackquote = 0;
11355 exception_handler = savehandler;
11356 longjmp(exception_handler->loc, 1);
11360 savelen = out - (char *)stackblock();
11362 str = ckmalloc(savelen);
11363 memcpy(str, stackblock(), savelen);
11365 savehandler = exception_handler;
11366 exception_handler = &jmploc;
11369 /* We must read until the closing backquote, giving special
11370 treatment to some slashes, and then push the string and
11371 reread it as input, interpreting it normally. */
11378 STARTSTACKSTR(pout);
11391 g_parsefile->linno++;
11395 * If eating a newline, avoid putting
11396 * the newline into the new character
11397 * stream (via the STPUTC after the
11402 if (pc != '\\' && pc != '`' && pc != '$'
11403 && (!dblquote || pc != '"'))
11404 STPUTC('\\', pout);
11405 if (pc > PEOA_OR_PEOF) {
11411 #if ENABLE_ASH_ALIAS
11414 startlinno = g_parsefile->linno;
11415 raise_error_syntax("EOF in backquote substitution");
11418 g_parsefile->linno++;
11419 needprompt = doprompt;
11428 STPUTC('\0', pout);
11429 psavelen = pout - (char *)stackblock();
11430 if (psavelen > 0) {
11431 pstr = grabstackstr(pout);
11432 setinputstring(pstr);
11437 nlpp = &(*nlpp)->next;
11438 *nlpp = stzalloc(sizeof(**nlpp));
11439 /* (*nlpp)->next = NULL; - stzalloc did it */
11440 parsebackquote = oldstyle;
11443 saveprompt = doprompt;
11450 doprompt = saveprompt;
11451 else if (readtoken() != TRP)
11452 raise_error_unexpected_syntax(TRP);
11457 * Start reading from old file again, ignoring any pushed back
11458 * tokens left from the backquote parsing
11463 while (stackblocksize() <= savelen)
11465 STARTSTACKSTR(out);
11467 memcpy(out, str, savelen);
11468 STADJUST(savelen, out);
11474 parsebackquote = savepbq;
11475 exception_handler = savehandler;
11476 if (arinest || dblquote)
11477 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11479 USTPUTC(CTLBACKQ, out);
11481 goto parsebackq_oldreturn;
11482 goto parsebackq_newreturn;
11485 #if ENABLE_SH_MATH_SUPPORT
11487 * Parse an arithmetic expansion (indicate start of one and set state)
11490 if (++arinest == 1) {
11491 prevsyntax = syntax;
11492 syntax = ARISYNTAX;
11493 USTPUTC(CTLARI, out);
11500 * we collapse embedded arithmetic expansion to
11501 * parenthesis, which should be equivalent
11505 goto parsearith_return;
11509 } /* end of readtoken */
11512 * Read the next input token.
11513 * If the token is a word, we set backquotelist to the list of cmds in
11514 * backquotes. We set quoteflag to true if any part of the word was
11516 * If the token is TREDIR, then we set redirnode to a structure containing
11518 * In all cases, the variable startlinno is set to the number of the line
11519 * on which the token starts.
11521 * [Change comment: here documents and internal procedures]
11522 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11523 * word parsing code into a separate routine. In this case, readtoken
11524 * doesn't need to have any internal procedures, but parseword does.
11525 * We could also make parseoperator in essence the main routine, and
11526 * have parseword (readtoken1?) handle both words and redirection.]
11528 #define NEW_xxreadtoken
11529 #ifdef NEW_xxreadtoken
11530 /* singles must be first! */
11531 static const char xxreadtoken_chars[7] ALIGN1 = {
11532 '\n', '(', ')', /* singles */
11533 '&', '|', ';', /* doubles */
11537 #define xxreadtoken_singles 3
11538 #define xxreadtoken_doubles 3
11540 static const char xxreadtoken_tokens[] ALIGN1 = {
11541 TNL, TLP, TRP, /* only single occurrence allowed */
11542 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11543 TEOF, /* corresponds to trailing nul */
11544 TAND, TOR, TENDCASE /* if double occurrence */
11559 startlinno = g_parsefile->linno;
11560 for (;;) { /* until token or start of word found */
11562 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11566 while ((c = pgetc()) != '\n' && c != PEOF)
11569 } else if (c == '\\') {
11570 if (pgetc() != '\n') {
11572 break; /* return readtoken1(...) */
11574 startlinno = ++g_parsefile->linno;
11580 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11583 g_parsefile->linno++;
11584 needprompt = doprompt;
11587 p = strchr(xxreadtoken_chars, c);
11589 break; /* return readtoken1(...) */
11591 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11593 if (cc == c) { /* double occurrence? */
11594 p += xxreadtoken_doubles + 1;
11597 #if ENABLE_ASH_BASH_COMPAT
11598 if (c == '&' && cc == '>') /* &> */
11599 break; /* return readtoken1(...) */
11604 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11609 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11611 #else /* old xxreadtoken */
11612 #define RETURN(token) return lasttoken = token
11625 startlinno = g_parsefile->linno;
11626 for (;;) { /* until token or start of word found */
11629 case ' ': case '\t':
11630 #if ENABLE_ASH_ALIAS
11635 while ((c = pgetc()) != '\n' && c != PEOF)
11640 if (pgetc() == '\n') {
11641 startlinno = ++g_parsefile->linno;
11649 g_parsefile->linno++;
11650 needprompt = doprompt;
11655 if (pgetc() == '&')
11660 if (pgetc() == '|')
11665 if (pgetc() == ';')
11678 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11681 #endif /* old xxreadtoken */
11688 smallint alreadyseen = tokpushback;
11691 #if ENABLE_ASH_ALIAS
11700 if (checkkwd & CHKNL) {
11707 if (t != TWORD || quoteflag) {
11712 * check for keywords
11714 if (checkkwd & CHKKWD) {
11715 const char *const *pp;
11717 pp = findkwd(wordtext);
11719 lasttoken = t = pp - tokname_array;
11720 TRACE(("keyword %s recognized\n", tokname(t)));
11725 if (checkkwd & CHKALIAS) {
11726 #if ENABLE_ASH_ALIAS
11728 ap = lookupalias(wordtext, 1);
11731 pushstring(ap->val, ap);
11741 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11743 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11755 return tokname_array[t][0];
11759 * Read and parse a command. Returns NODE_EOF on end of file.
11760 * (NULL is a valid parse tree indicating a blank line.)
11762 static union node *
11763 parsecmd(int interact)
11768 doprompt = interact;
11770 setprompt(doprompt);
11782 * Input any here documents.
11787 struct heredoc *here;
11790 here = heredoclist;
11791 heredoclist = NULL;
11797 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11798 here->eofmark, here->striptabs);
11799 n = stzalloc(sizeof(struct narg));
11800 n->narg.type = NARG;
11801 /*n->narg.next = NULL; - stzalloc did it */
11802 n->narg.text = wordtext;
11803 n->narg.backquote = backquotelist;
11804 here->here->nhere.doc = n;
11811 * called by editline -- any expansions to the prompt should be added here.
11813 #if ENABLE_ASH_EXPAND_PRMT
11814 static const char *
11815 expandstr(const char *ps)
11819 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11820 * and token processing _can_ alter it (delete NULs etc). */
11821 setinputstring((char *)ps);
11822 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11825 n.narg.type = NARG;
11826 n.narg.next = NULL;
11827 n.narg.text = wordtext;
11828 n.narg.backquote = backquotelist;
11830 expandarg(&n, NULL, 0);
11831 return stackblock();
11836 * Execute a command or commands contained in a string.
11839 evalstring(char *s, int mask)
11842 struct stackmark smark;
11846 setstackmark(&smark);
11849 while ((n = parsecmd(0)) != NODE_EOF) {
11851 popstackmark(&smark);
11864 * The eval command.
11866 static int FAST_FUNC
11867 evalcmd(int argc UNUSED_PARAM, char **argv)
11876 STARTSTACKSTR(concat);
11878 concat = stack_putstr(p, concat);
11882 STPUTC(' ', concat);
11884 STPUTC('\0', concat);
11885 p = grabstackstr(concat);
11887 evalstring(p, ~SKIPEVAL);
11894 * Read and execute commands. "Top" is nonzero for the top level command
11895 * loop; it turns on prompting if the shell is interactive.
11901 struct stackmark smark;
11905 TRACE(("cmdloop(%d) called\n", top));
11909 setstackmark(&smark);
11912 showjobs(stderr, SHOW_CHANGED);
11915 if (iflag && top) {
11917 #if ENABLE_ASH_MAIL
11921 n = parsecmd(inter);
11923 if (DEBUG > 2 && debug && (n != NODE_EOF))
11926 if (n == NODE_EOF) {
11927 if (!top || numeof >= 50)
11929 if (!stoppedjobs()) {
11932 out2str("\nUse \"exit\" to leave shell.\n");
11935 } else if (nflag == 0) {
11936 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11941 popstackmark(&smark);
11946 return skip & SKIPEVAL;
11953 * Take commands from a file. To be compatible we should do a path
11954 * search for the file, which is necessary to find sub-commands.
11957 find_dot_file(char *name)
11960 const char *path = pathval();
11963 /* don't try this for absolute or relative paths */
11964 if (strchr(name, '/'))
11967 /* IIRC standards do not say whether . is to be searched.
11968 * And it is even smaller this way, making it unconditional for now:
11970 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11975 while ((fullname = path_advance(&path, name)) != NULL) {
11977 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11979 * Don't bother freeing here, since it will
11980 * be freed by the caller.
11984 if (fullname != name)
11985 stunalloc(fullname);
11988 /* not found in the PATH */
11989 ash_msg_and_raise_error("%s: not found", name);
11993 static int FAST_FUNC
11994 dotcmd(int argc, char **argv)
11996 struct strlist *sp;
11997 volatile struct shparam saveparam;
12000 for (sp = cmdenviron; sp; sp = sp->next)
12001 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12003 if (argv[1]) { /* That's what SVR2 does */
12004 char *fullname = find_dot_file(argv[1]);
12007 if (argc) { /* argc > 0, argv[0] != NULL */
12008 saveparam = shellparam;
12009 shellparam.malloced = 0;
12010 shellparam.nparam = argc;
12011 shellparam.p = argv;
12014 setinputfile(fullname, INPUT_PUSH_FILE);
12015 commandname = fullname;
12020 freeparam(&shellparam);
12021 shellparam = saveparam;
12023 status = exitstatus;
12028 static int FAST_FUNC
12029 exitcmd(int argc UNUSED_PARAM, char **argv)
12034 exitstatus = number(argv[1]);
12035 raise_exception(EXEXIT);
12040 * Read a file containing shell functions.
12043 readcmdfile(char *name)
12045 setinputfile(name, INPUT_PUSH_FILE);
12051 /* ============ find_command inplementation */
12054 * Resolve a command name. If you change this routine, you may have to
12055 * change the shellexec routine as well.
12058 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12060 struct tblentry *cmdp;
12067 struct builtincmd *bcmd;
12069 /* If name contains a slash, don't use PATH or hash table */
12070 if (strchr(name, '/') != NULL) {
12071 entry->u.index = -1;
12072 if (act & DO_ABS) {
12073 while (stat(name, &statb) < 0) {
12075 if (errno == EINTR)
12078 entry->cmdtype = CMDUNKNOWN;
12082 entry->cmdtype = CMDNORMAL;
12086 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12088 updatetbl = (path == pathval());
12091 if (strstr(path, "%builtin") != NULL)
12092 act |= DO_ALTBLTIN;
12095 /* If name is in the table, check answer will be ok */
12096 cmdp = cmdlookup(name, 0);
12097 if (cmdp != NULL) {
12100 switch (cmdp->cmdtype) {
12118 } else if (cmdp->rehash == 0)
12119 /* if not invalidated by cd, we're done */
12123 /* If %builtin not in path, check for builtin next */
12124 bcmd = find_builtin(name);
12126 if (IS_BUILTIN_REGULAR(bcmd))
12127 goto builtin_success;
12128 if (act & DO_ALTPATH) {
12129 if (!(act & DO_ALTBLTIN))
12130 goto builtin_success;
12131 } else if (builtinloc <= 0) {
12132 goto builtin_success;
12136 #if ENABLE_FEATURE_SH_STANDALONE
12138 int applet_no = find_applet_by_name(name);
12139 if (applet_no >= 0) {
12140 entry->cmdtype = CMDNORMAL;
12141 entry->u.index = -2 - applet_no;
12147 /* We have to search path. */
12148 prev = -1; /* where to start */
12149 if (cmdp && cmdp->rehash) { /* doing a rehash */
12150 if (cmdp->cmdtype == CMDBUILTIN)
12153 prev = cmdp->param.index;
12159 while ((fullname = path_advance(&path, name)) != NULL) {
12160 stunalloc(fullname);
12161 /* NB: code below will still use fullname
12162 * despite it being "unallocated" */
12165 if (prefix(pathopt, "builtin")) {
12167 goto builtin_success;
12170 if ((act & DO_NOFUNC)
12171 || !prefix(pathopt, "func")
12172 ) { /* ignore unimplemented options */
12176 /* if rehash, don't redo absolute path names */
12177 if (fullname[0] == '/' && idx <= prev) {
12180 TRACE(("searchexec \"%s\": no change\n", name));
12183 while (stat(fullname, &statb) < 0) {
12185 if (errno == EINTR)
12188 if (errno != ENOENT && errno != ENOTDIR)
12192 e = EACCES; /* if we fail, this will be the error */
12193 if (!S_ISREG(statb.st_mode))
12195 if (pathopt) { /* this is a %func directory */
12196 stalloc(strlen(fullname) + 1);
12197 /* NB: stalloc will return space pointed by fullname
12198 * (because we don't have any intervening allocations
12199 * between stunalloc above and this stalloc) */
12200 readcmdfile(fullname);
12201 cmdp = cmdlookup(name, 0);
12202 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12203 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12204 stunalloc(fullname);
12207 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12209 entry->cmdtype = CMDNORMAL;
12210 entry->u.index = idx;
12214 cmdp = cmdlookup(name, 1);
12215 cmdp->cmdtype = CMDNORMAL;
12216 cmdp->param.index = idx;
12221 /* We failed. If there was an entry for this command, delete it */
12222 if (cmdp && updatetbl)
12223 delete_cmd_entry();
12225 ash_msg("%s: %s", name, errmsg(e, "not found"));
12226 entry->cmdtype = CMDUNKNOWN;
12231 entry->cmdtype = CMDBUILTIN;
12232 entry->u.cmd = bcmd;
12236 cmdp = cmdlookup(name, 1);
12237 cmdp->cmdtype = CMDBUILTIN;
12238 cmdp->param.cmd = bcmd;
12242 entry->cmdtype = cmdp->cmdtype;
12243 entry->u = cmdp->param;
12247 /* ============ trap.c */
12250 * The trap builtin.
12252 static int FAST_FUNC
12253 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12262 for (signo = 0; signo < NSIG; signo++) {
12263 if (trap[signo] != NULL) {
12264 out1fmt("trap -- %s %s%s\n",
12265 single_quote(trap[signo]),
12266 (signo == 0 ? "" : "SIG"),
12267 get_signame(signo));
12276 signo = get_signum(*ap);
12278 ash_msg_and_raise_error("%s: bad trap", *ap);
12281 if (LONE_DASH(action))
12284 action = ckstrdup(action);
12287 trap[signo] = action;
12297 /* ============ Builtins */
12299 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12301 * Lists available builtins
12303 static int FAST_FUNC
12304 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12310 "Built-in commands:\n"
12311 "------------------\n");
12312 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12313 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12314 builtintab[i].name + 1);
12320 #if ENABLE_FEATURE_SH_STANDALONE
12322 const char *a = applet_names;
12324 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12329 a += strlen(a) + 1;
12334 return EXIT_SUCCESS;
12336 #endif /* FEATURE_SH_EXTRA_QUIET */
12339 * The export and readonly commands.
12341 static int FAST_FUNC
12342 exportcmd(int argc UNUSED_PARAM, char **argv)
12348 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12350 if (nextopt("p") != 'p') {
12355 p = strchr(name, '=');
12359 vp = *findvar(hashvar(name), name);
12365 setvar(name, p, flag);
12366 } while ((name = *++aptr) != NULL);
12370 showvars(argv[0], flag, 0);
12375 * Delete a function if it exists.
12378 unsetfunc(const char *name)
12380 struct tblentry *cmdp;
12382 cmdp = cmdlookup(name, 0);
12383 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12384 delete_cmd_entry();
12388 * The unset builtin command. We unset the function before we unset the
12389 * variable to allow a function to be unset when there is a readonly variable
12390 * with the same name.
12392 static int FAST_FUNC
12393 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12400 while ((i = nextopt("vf")) != '\0') {
12404 for (ap = argptr; *ap; ap++) {
12420 #include <sys/times.h>
12422 static const unsigned char timescmd_str[] ALIGN1 = {
12423 ' ', offsetof(struct tms, tms_utime),
12424 '\n', offsetof(struct tms, tms_stime),
12425 ' ', offsetof(struct tms, tms_cutime),
12426 '\n', offsetof(struct tms, tms_cstime),
12430 static int FAST_FUNC
12431 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12433 long clk_tck, s, t;
12434 const unsigned char *p;
12437 clk_tck = sysconf(_SC_CLK_TCK);
12442 t = *(clock_t *)(((char *) &buf) + p[1]);
12444 out1fmt("%ldm%ld.%.3lds%c",
12446 ((t - s * clk_tck) * 1000) / clk_tck,
12448 } while (*(p += 2));
12453 #if ENABLE_SH_MATH_SUPPORT
12455 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12456 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12458 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12460 static int FAST_FUNC
12461 letcmd(int argc UNUSED_PARAM, char **argv)
12467 ash_msg_and_raise_error("expression expected");
12469 i = ash_arith(*argv);
12474 #endif /* SH_MATH_SUPPORT */
12477 /* ============ miscbltin.c
12479 * Miscellaneous builtins.
12484 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
12485 typedef enum __rlimit_resource rlim_t;
12489 * The read builtin. Options:
12490 * -r Do not interpret '\' specially
12491 * -s Turn off echo (tty only)
12492 * -n NCHARS Read NCHARS max
12493 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12494 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12495 * -u FD Read from given FD instead of fd 0
12496 * This uses unbuffered input, which may be avoidable in some cases.
12497 * TODO: bash also has:
12498 * -a ARRAY Read into array[0],[1],etc
12499 * -d DELIM End on DELIM char, not newline
12500 * -e Use line editing (tty only)
12502 static int FAST_FUNC
12503 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12505 static const char *const arg_REPLY[] = { "REPLY", NULL };
12518 #if ENABLE_ASH_READ_NCHARS
12519 int nchars = 0; /* if != 0, -n is in effect */
12521 struct termios tty, old_tty;
12523 #if ENABLE_ASH_READ_TIMEOUT
12524 unsigned end_ms = 0;
12525 unsigned timeout = 0;
12530 while ((i = nextopt("p:u:r"
12531 IF_ASH_READ_TIMEOUT("t:")
12532 IF_ASH_READ_NCHARS("n:s")
12536 prompt = optionarg;
12538 #if ENABLE_ASH_READ_NCHARS
12540 nchars = bb_strtou(optionarg, NULL, 10);
12541 if (nchars < 0 || errno)
12542 ash_msg_and_raise_error("invalid count");
12543 /* nchars == 0: off (bash 3.2 does this too) */
12549 #if ENABLE_ASH_READ_TIMEOUT
12551 timeout = bb_strtou(optionarg, NULL, 10);
12552 if (errno || timeout > UINT_MAX / 2048)
12553 ash_msg_and_raise_error("invalid timeout");
12555 #if 0 /* even bash have no -t N.NNN support */
12556 ts.tv_sec = bb_strtou(optionarg, &p, 10);
12558 /* EINVAL means number is ok, but not terminated by NUL */
12559 if (*p == '.' && errno == EINVAL) {
12563 ts.tv_usec = bb_strtou(p, &p2, 10);
12565 ash_msg_and_raise_error("invalid timeout");
12567 /* normalize to usec */
12569 ash_msg_and_raise_error("invalid timeout");
12570 while (scale++ < 6)
12573 } else if (ts.tv_sec < 0 || errno) {
12574 ash_msg_and_raise_error("invalid timeout");
12576 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
12577 ash_msg_and_raise_error("invalid timeout");
12586 fd = bb_strtou(optionarg, NULL, 10);
12587 if (fd < 0 || errno)
12588 ash_msg_and_raise_error("invalid file descriptor");
12594 if (prompt && isatty(fd)) {
12599 ap = (char**)arg_REPLY;
12600 ifs = bltinlookup("IFS");
12603 #if ENABLE_ASH_READ_NCHARS
12604 tcgetattr(fd, &tty);
12606 if (nchars || silent) {
12608 tty.c_lflag &= ~ICANON;
12609 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
12612 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12614 /* if tcgetattr failed, tcsetattr will fail too.
12615 * Ignoring, it's harmless. */
12616 tcsetattr(fd, TCSANOW, &tty);
12623 #if ENABLE_ASH_READ_TIMEOUT
12624 if (timeout) /* NB: ensuring end_ms is nonzero */
12625 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12629 const char *is_ifs;
12631 #if ENABLE_ASH_READ_TIMEOUT
12633 struct pollfd pfd[1];
12635 pfd[0].events = POLLIN;
12636 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12637 if ((int)timeout <= 0 /* already late? */
12638 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12639 ) { /* timed out! */
12640 #if ENABLE_ASH_READ_NCHARS
12641 tcsetattr(fd, TCSANOW, &old_tty);
12647 if (nonblock_safe_read(fd, &c, 1) != 1) {
12659 if (!rflag && c == '\\') {
12665 /* $IFS splitting */
12666 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
12667 is_ifs = strchr(ifs, c);
12668 if (startword && is_ifs) {
12671 /* it is a non-space ifs char */
12673 if (startword == 1) /* first one? */
12674 continue; /* yes, it is not next word yet */
12677 if (ap[1] != NULL && is_ifs) {
12680 beg = stackblock();
12681 setvar(*ap, beg, 0);
12683 /* can we skip one non-space ifs char? (2: yes) */
12684 startword = isspace(c) ? 2 : 1;
12691 /* end of do {} while: */
12692 #if ENABLE_ASH_READ_NCHARS
12698 #if ENABLE_ASH_READ_NCHARS
12699 tcsetattr(fd, TCSANOW, &old_tty);
12703 /* Remove trailing space ifs chars */
12704 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
12706 setvar(*ap, stackblock(), 0);
12707 while (*++ap != NULL)
12708 setvar(*ap, nullstr, 0);
12712 static int FAST_FUNC
12713 umaskcmd(int argc UNUSED_PARAM, char **argv)
12715 static const char permuser[3] ALIGN1 = "ugo";
12716 static const char permmode[3] ALIGN1 = "rwx";
12717 static const short permmask[] ALIGN2 = {
12718 S_IRUSR, S_IWUSR, S_IXUSR,
12719 S_IRGRP, S_IWGRP, S_IXGRP,
12720 S_IROTH, S_IWOTH, S_IXOTH
12723 /* TODO: use bb_parse_mode() instead */
12728 int symbolic_mode = 0;
12730 while (nextopt("S") != '\0') {
12741 if (symbolic_mode) {
12745 for (i = 0; i < 3; i++) {
12748 *p++ = permuser[i];
12750 for (j = 0; j < 3; j++) {
12751 if ((mask & permmask[3 * i + j]) == 0) {
12752 *p++ = permmode[j];
12760 out1fmt("%.4o\n", mask);
12763 if (isdigit((unsigned char) *ap)) {
12766 if (*ap >= '8' || *ap < '0')
12767 ash_msg_and_raise_error(msg_illnum, argv[1]);
12768 mask = (mask << 3) + (*ap - '0');
12769 } while (*++ap != '\0');
12772 mask = ~mask & 0777;
12773 if (!bb_parse_mode(ap, &mask)) {
12774 ash_msg_and_raise_error("illegal mode: %s", ap);
12776 umask(~mask & 0777);
12785 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12786 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12787 * ash by J.T. Conklin.
12792 uint8_t cmd; /* RLIMIT_xxx fit into it */
12793 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
12797 static const struct limits limits_tbl[] = {
12799 { RLIMIT_CPU, 0, 't' },
12801 #ifdef RLIMIT_FSIZE
12802 { RLIMIT_FSIZE, 9, 'f' },
12805 { RLIMIT_DATA, 10, 'd' },
12807 #ifdef RLIMIT_STACK
12808 { RLIMIT_STACK, 10, 's' },
12811 { RLIMIT_CORE, 9, 'c' },
12814 { RLIMIT_RSS, 10, 'm' },
12816 #ifdef RLIMIT_MEMLOCK
12817 { RLIMIT_MEMLOCK, 10, 'l' },
12819 #ifdef RLIMIT_NPROC
12820 { RLIMIT_NPROC, 0, 'p' },
12822 #ifdef RLIMIT_NOFILE
12823 { RLIMIT_NOFILE, 0, 'n' },
12826 { RLIMIT_AS, 10, 'v' },
12828 #ifdef RLIMIT_LOCKS
12829 { RLIMIT_LOCKS, 0, 'w' },
12832 static const char limits_name[] =
12834 "time(seconds)" "\0"
12836 #ifdef RLIMIT_FSIZE
12837 "file(blocks)" "\0"
12842 #ifdef RLIMIT_STACK
12846 "coredump(blocks)" "\0"
12851 #ifdef RLIMIT_MEMLOCK
12852 "locked memory(kb)" "\0"
12854 #ifdef RLIMIT_NPROC
12857 #ifdef RLIMIT_NOFILE
12863 #ifdef RLIMIT_LOCKS
12868 enum limtype { SOFT = 0x1, HARD = 0x2 };
12871 printlim(enum limtype how, const struct rlimit *limit,
12872 const struct limits *l)
12876 val = limit->rlim_max;
12878 val = limit->rlim_cur;
12880 if (val == RLIM_INFINITY)
12881 out1fmt("unlimited\n");
12883 val >>= l->factor_shift;
12884 out1fmt("%lld\n", (long long) val);
12888 static int FAST_FUNC
12889 ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12893 enum limtype how = SOFT | HARD;
12894 const struct limits *l;
12897 struct rlimit limit;
12900 while ((optc = nextopt("HSa"
12904 #ifdef RLIMIT_FSIZE
12910 #ifdef RLIMIT_STACK
12919 #ifdef RLIMIT_MEMLOCK
12922 #ifdef RLIMIT_NPROC
12925 #ifdef RLIMIT_NOFILE
12931 #ifdef RLIMIT_LOCKS
12949 for (l = limits_tbl; l->option != what; l++)
12952 set = *argptr ? 1 : 0;
12956 if (all || argptr[1])
12957 ash_msg_and_raise_error("too many arguments");
12958 if (strncmp(p, "unlimited\n", 9) == 0)
12959 val = RLIM_INFINITY;
12963 while ((c = *p++) >= '0' && c <= '9') {
12964 val = (val * 10) + (long)(c - '0');
12965 // val is actually 'unsigned long int' and can't get < 0
12966 if (val < (rlim_t) 0)
12970 ash_msg_and_raise_error("bad number");
12971 val <<= l->factor_shift;
12975 const char *lname = limits_name;
12976 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
12977 getrlimit(l->cmd, &limit);
12978 out1fmt("%-20s ", lname);
12979 lname += strlen(lname) + 1;
12980 printlim(how, &limit, l);
12985 getrlimit(l->cmd, &limit);
12988 limit.rlim_max = val;
12990 limit.rlim_cur = val;
12991 if (setrlimit(l->cmd, &limit) < 0)
12992 ash_msg_and_raise_error("error setting limit (%m)");
12994 printlim(how, &limit, l);
12999 /* ============ main() and helpers */
13002 * Called to exit the shell.
13004 static void exitshell(void) NORETURN;
13012 status = exitstatus;
13013 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13014 if (setjmp(loc.loc)) {
13015 if (exception_type == EXEXIT)
13016 /* dash bug: it just does _exit(exitstatus) here
13017 * but we have to do setjobctl(0) first!
13018 * (bug is still not fixed in dash-0.5.3 - if you run dash
13019 * under Midnight Commander, on exit from dash MC is backgrounded) */
13020 status = exitstatus;
13023 exception_handler = &loc;
13030 flush_stdout_stderr();
13040 /* from input.c: */
13041 basepf.next_to_pgetc = basepf.buf = basebuf;
13044 signal(SIGCHLD, SIG_DFL);
13049 char ppid[sizeof(int)*3 + 2];
13051 struct stat st1, st2;
13054 for (envp = environ; envp && *envp; envp++) {
13055 if (strchr(*envp, '=')) {
13056 setvareq(*envp, VEXPORT|VTEXTFIXED);
13060 sprintf(ppid, "%u", (unsigned) getppid());
13061 setvar("PPID", ppid, 0);
13063 p = lookupvar("PWD");
13065 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13066 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
13073 * Process the shell command line arguments.
13076 procargs(char **argv)
13079 const char *xminusc;
13084 /* if (xargv[0]) - mmm, this is always true! */
13086 for (i = 0; i < NOPTS; i++)
13090 /* it already printed err message */
13091 raise_exception(EXERROR);
13095 if (*xargv == NULL) {
13097 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13100 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13104 for (i = 0; i < NOPTS; i++)
13105 if (optlist[i] == 2)
13110 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13115 } else if (!sflag) {
13116 setinputfile(*xargv, 0);
13119 commandname = arg0;
13122 shellparam.p = xargv;
13123 #if ENABLE_ASH_GETOPTS
13124 shellparam.optind = 1;
13125 shellparam.optoff = -1;
13127 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13129 shellparam.nparam++;
13136 * Read /etc/profile or .profile.
13139 read_profile(const char *name)
13143 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13152 * This routine is called when an error or an interrupt occurs in an
13153 * interactive shell and control is returned to the main command loop.
13161 /* from input.c: */
13162 g_parsefile->left_in_buffer = 0;
13163 g_parsefile->left_in_line = 0; /* clear input buffer */
13165 /* from parser.c: */
13168 /* from redir.c: */
13169 clearredir(/*drop:*/ 0);
13173 static short profile_buf[16384];
13174 extern int etext();
13178 * Main routine. We initialize things, parse the arguments, execute
13179 * profiles if we're a login shell, and then call cmdloop to execute
13180 * commands. The setjmp call sets up the location to jump to when an
13181 * exception occurs. When an exception occurs the variable "state"
13182 * is used to figure out how far we had gotten.
13184 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13185 int ash_main(int argc UNUSED_PARAM, char **argv)
13187 const char *shinit;
13188 volatile smallint state;
13189 struct jmploc jmploc;
13190 struct stackmark smark;
13192 /* Initialize global data */
13196 #if ENABLE_ASH_ALIAS
13202 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13205 #if ENABLE_FEATURE_EDITING
13206 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13209 if (setjmp(jmploc.loc)) {
13215 e = exception_type;
13219 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13222 outcslow('\n', stderr);
13224 popstackmark(&smark);
13225 FORCE_INT_ON; /* enable interrupts */
13234 exception_handler = &jmploc;
13237 TRACE(("Shell args: "));
13238 trace_puts_args(argv);
13240 rootpid = getpid();
13242 #if ENABLE_ASH_RANDOM_SUPPORT
13243 /* Can use monotonic_ns() for better randomness but for now it is
13244 * not used anywhere else in busybox... so avoid bloat */
13245 random_galois_LFSR = random_LCG = rootpid + monotonic_us();
13248 setstackmark(&smark);
13251 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13253 const char *hp = lookupvar("HISTFILE");
13256 hp = lookupvar("HOME");
13258 char *defhp = concat_path_file(hp, ".ash_history");
13259 setvar("HISTFILE", defhp, 0);
13265 if (/* argv[0] && */ argv[0][0] == '-')
13269 read_profile("/etc/profile");
13272 read_profile(".profile");
13278 getuid() == geteuid() && getgid() == getegid() &&
13282 shinit = lookupvar("ENV");
13283 if (shinit != NULL && *shinit != '\0') {
13284 read_profile(shinit);
13290 /* evalstring pushes parsefile stack.
13291 * Ensure we don't falsely claim that 0 (stdin)
13292 * is one of stacked source fds.
13293 * Testcase: ash -c 'exec 1>&0' must not complain. */
13295 g_parsefile->fd = -1;
13296 evalstring(minusc, 0);
13299 if (sflag || minusc == NULL) {
13300 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13302 const char *hp = lookupvar("HISTFILE");
13304 line_input_state->hist_file = hp;
13307 state4: /* XXX ??? - why isn't this before the "if" statement */
13315 extern void _mcleanup(void);
13325 * Copyright (c) 1989, 1991, 1993, 1994
13326 * The Regents of the University of California. All rights reserved.
13328 * This code is derived from software contributed to Berkeley by
13329 * Kenneth Almquist.
13331 * Redistribution and use in source and binary forms, with or without
13332 * modification, are permitted provided that the following conditions
13334 * 1. Redistributions of source code must retain the above copyright
13335 * notice, this list of conditions and the following disclaimer.
13336 * 2. Redistributions in binary form must reproduce the above copyright
13337 * notice, this list of conditions and the following disclaimer in the
13338 * documentation and/or other materials provided with the distribution.
13339 * 3. Neither the name of the University nor the names of its contributors
13340 * may be used to endorse or promote products derived from this software
13341 * without specific prior written permission.
13343 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13344 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13345 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13346 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13347 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13348 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13349 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13350 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13351 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13352 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF