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) */
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.
4603 /* do job control only in root shell */
4605 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4608 if (jp->nprocs == 0)
4611 pgrp = jp->ps[0].pid;
4612 /* this can fail because we are doing it in the parent also */
4614 if (mode == FORK_FG)
4615 xtcsetpgrp(ttyfd, pgrp);
4620 if (mode == FORK_BG) {
4621 /* man bash: "When job control is not in effect,
4622 * asynchronous commands ignore SIGINT and SIGQUIT" */
4625 if (jp->nprocs == 0) {
4627 if (open(bb_dev_null, O_RDONLY) != 0)
4628 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4632 if (iflag) { /* why if iflag only? */
4637 * "In all cases, bash ignores SIGQUIT. Non-builtin
4638 * commands run by bash have signal handlers
4639 * set to the values inherited by the shell
4641 * Take care of the second rule: */
4645 if (n && n->type == NCMD
4646 && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4648 TRACE(("Job hack\n"));
4649 /* "jobs": we do not want to clear job list for it,
4650 * instead we remove only _its_ own_ job from job list.
4651 * This makes "jobs .... | cat" more useful.
4657 for (jp = curjob; jp; jp = jp->prev_job)
4662 /* Called after fork(), in parent */
4664 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4667 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4669 TRACE(("In parent shell: child = %d\n", pid));
4671 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4677 if (mode != FORK_NOJOB && jp->jobctl) {
4680 if (jp->nprocs == 0)
4683 pgrp = jp->ps[0].pid;
4684 /* This can fail because we are doing it in the child also */
4688 if (mode == FORK_BG) {
4689 backgndpid = pid; /* set $! */
4690 set_curjob(jp, CUR_RUNNING);
4693 struct procstat *ps = &jp->ps[jp->nprocs++];
4698 if (doing_jobctl && n)
4699 ps->cmd = commandtext(n);
4705 forkshell(struct job *jp, union node *n, int mode)
4709 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4712 TRACE(("Fork failed, errno=%d", errno));
4715 ash_msg_and_raise_error("can't fork");
4718 forkchild(jp, n, mode);
4720 forkparent(jp, n, mode, pid);
4725 * Wait for job to finish.
4727 * Under job control we have the problem that while a child process
4728 * is running interrupts generated by the user are sent to the child
4729 * but not to the shell. This means that an infinite loop started by
4730 * an interactive user may be hard to kill. With job control turned off,
4731 * an interactive user may place an interactive program inside a loop.
4732 * If the interactive program catches interrupts, the user doesn't want
4733 * these interrupts to also abort the loop. The approach we take here
4734 * is to have the shell ignore interrupt signals while waiting for a
4735 * foreground process to terminate, and then send itself an interrupt
4736 * signal if the child process was terminated by an interrupt signal.
4737 * Unfortunately, some programs want to do a bit of cleanup and then
4738 * exit on interrupt; unless these processes terminate themselves by
4739 * sending a signal to themselves (instead of calling exit) they will
4740 * confuse this approach.
4742 * Called with interrupts off.
4745 waitforjob(struct job *jp)
4749 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4752 while (jp->state == JOBRUNNING) {
4753 /* In non-interactive shells, we _can_ get
4754 * a keyboard signal here and be EINTRed,
4755 * but we just loop back, waiting for command to complete.
4758 * "If bash is waiting for a command to complete and receives
4759 * a signal for which a trap has been set, the trap
4760 * will not be executed until the command completes."
4762 * Reality is that even if trap is not set, bash
4763 * will not act on the signal until command completes.
4764 * Try this. sleep5intoff.c:
4765 * #include <signal.h>
4766 * #include <unistd.h>
4769 * sigemptyset(&set);
4770 * sigaddset(&set, SIGINT);
4771 * sigaddset(&set, SIGQUIT);
4772 * sigprocmask(SIG_BLOCK, &set, NULL);
4776 * $ bash -c './sleep5intoff; echo hi'
4777 * ^C^C^C^C <--- pressing ^C once a second
4779 * $ bash -c './sleep5intoff; echo hi'
4780 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4783 dowait(DOWAIT_BLOCK, jp);
4790 xtcsetpgrp(ttyfd, rootpid);
4792 * This is truly gross.
4793 * If we're doing job control, then we did a TIOCSPGRP which
4794 * caused us (the shell) to no longer be in the controlling
4795 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4796 * intuit from the subprocess exit status whether a SIGINT
4797 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4799 if (jp->sigint) /* TODO: do the same with all signals */
4800 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4802 if (jp->state == JOBDONE)
4809 * return 1 if there are stopped jobs, otherwise 0
4821 if (jp && jp->state == JOBSTOPPED) {
4822 out2str("You have stopped jobs.\n");
4831 /* ============ redir.c
4833 * Code for dealing with input/output redirection.
4836 #define EMPTY -2 /* marks an unused slot in redirtab */
4837 #define CLOSED -3 /* marks a slot of previously-closed fd */
4840 * Open a file in noclobber mode.
4841 * The code was copied from bash.
4844 noclobberopen(const char *fname)
4847 struct stat finfo, finfo2;
4850 * If the file exists and is a regular file, return an error
4853 r = stat(fname, &finfo);
4854 if (r == 0 && S_ISREG(finfo.st_mode)) {
4860 * If the file was not present (r != 0), make sure we open it
4861 * exclusively so that if it is created before we open it, our open
4862 * will fail. Make sure that we do not truncate an existing file.
4863 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4864 * file was not a regular file, we leave O_EXCL off.
4867 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4868 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4870 /* If the open failed, return the file descriptor right away. */
4875 * OK, the open succeeded, but the file may have been changed from a
4876 * non-regular file to a regular file between the stat and the open.
4877 * We are assuming that the O_EXCL open handles the case where FILENAME
4878 * did not exist and is symlinked to an existing file between the stat
4883 * If we can open it and fstat the file descriptor, and neither check
4884 * revealed that it was a regular file, and the file has not been
4885 * replaced, return the file descriptor.
4887 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4888 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4891 /* The file has been replaced. badness. */
4898 * Handle here documents. Normally we fork off a process to write the
4899 * data to a pipe. If the document is short, we can stuff the data in
4900 * the pipe without forking.
4902 /* openhere needs this forward reference */
4903 static void expandhere(union node *arg, int fd);
4905 openhere(union node *redir)
4911 ash_msg_and_raise_error("pipe call failed");
4912 if (redir->type == NHERE) {
4913 len = strlen(redir->nhere.doc->narg.text);
4914 if (len <= PIPE_BUF) {
4915 full_write(pip[1], redir->nhere.doc->narg.text, len);
4919 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4922 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4923 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4924 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4925 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4926 signal(SIGPIPE, SIG_DFL);
4927 if (redir->type == NHERE)
4928 full_write(pip[1], redir->nhere.doc->narg.text, len);
4930 expandhere(redir->nhere.doc, pip[1]);
4931 _exit(EXIT_SUCCESS);
4939 openredirect(union node *redir)
4944 switch (redir->nfile.type) {
4946 fname = redir->nfile.expfname;
4947 f = open(fname, O_RDONLY);
4952 fname = redir->nfile.expfname;
4953 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4958 #if ENABLE_ASH_BASH_COMPAT
4961 /* Take care of noclobber mode. */
4963 fname = redir->nfile.expfname;
4964 f = noclobberopen(fname);
4971 fname = redir->nfile.expfname;
4972 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4977 fname = redir->nfile.expfname;
4978 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4986 /* Fall through to eliminate warning. */
4987 /* Our single caller does this itself */
4994 f = openhere(redir);
5000 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5002 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5006 * Copy a file descriptor to be >= to. Returns -1
5007 * if the source file descriptor is closed, EMPTY if there are no unused
5008 * file descriptors left.
5010 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5011 * old code was doing close(to) prior to copyfd() to achieve the same */
5013 COPYFD_EXACT = (int)~(INT_MAX),
5014 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5017 copyfd(int from, int to)
5021 if (to & COPYFD_EXACT) {
5022 to &= ~COPYFD_EXACT;
5024 newfd = dup2(from, to);
5026 newfd = fcntl(from, F_DUPFD, to);
5029 if (errno == EMFILE)
5031 /* Happens when source fd is not open: try "echo >&99" */
5032 ash_msg_and_raise_error("%d: %m", from);
5037 /* Struct def and variable are moved down to the first usage site */
5042 struct redirtab *next;
5045 struct two_fd_t two_fd[0];
5047 #define redirlist (G_var.redirlist)
5049 static int need_to_remember(struct redirtab *rp, int fd)
5053 if (!rp) /* remembering was not requested */
5056 for (i = 0; i < rp->pair_count; i++) {
5057 if (rp->two_fd[i].orig == fd) {
5058 /* already remembered */
5065 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5066 static int is_hidden_fd(struct redirtab *rp, int fd)
5069 struct parsefile *pf;
5082 fd |= COPYFD_RESTORE;
5083 for (i = 0; i < rp->pair_count; i++) {
5084 if (rp->two_fd[i].copy == fd) {
5092 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5093 * old file descriptors are stashed away so that the redirection can be
5094 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5095 * standard output, and the standard error if it becomes a duplicate of
5096 * stdout, is saved in memory.
5098 /* flags passed to redirect */
5099 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5100 #define REDIR_SAVEFD2 03 /* set preverrout */
5102 redirect(union node *redir, int flags)
5104 struct redirtab *sv;
5109 int copied_fd2 = -1;
5119 if (flags & REDIR_PUSH) {
5120 union node *tmp = redir;
5123 #if ENABLE_ASH_BASH_COMPAT
5124 if (redir->nfile.type == NTO2)
5127 tmp = tmp->nfile.next;
5129 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5130 sv->next = redirlist;
5131 sv->pair_count = sv_pos;
5133 sv->nullredirs = g_nullredirs - 1;
5135 while (sv_pos > 0) {
5137 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5142 fd = redir->nfile.fd;
5143 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5144 int right_fd = redir->ndup.dupfd;
5145 /* redirect from/to same file descriptor? */
5148 /* echo >&10 and 10 is a fd opened to the sh script? */
5149 if (is_hidden_fd(sv, right_fd)) {
5150 errno = EBADF; /* as if it is closed */
5151 ash_msg_and_raise_error("%d: %m", right_fd);
5155 newfd = openredirect(redir); /* always >= 0 */
5157 /* Descriptor wasn't open before redirect.
5158 * Mark it for close in the future */
5159 if (need_to_remember(sv, fd)) {
5160 goto remember_to_close;
5165 #if ENABLE_ASH_BASH_COMPAT
5168 if (need_to_remember(sv, fd)) {
5169 /* Copy old descriptor */
5170 i = fcntl(fd, F_DUPFD, 10);
5171 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5172 * are closed in popredir() in the child, preventing them from leaking
5173 * into child. (popredir() also cleans up the mess in case of failures)
5178 /* Strange error (e.g. "too many files" EMFILE?) */
5182 ash_msg_and_raise_error("%d: %m", fd);
5185 /* EBADF: it is not open - good, remember to close it */
5188 } else { /* fd is open, save its copy */
5189 /* "exec fd>&-" should not close fds
5190 * which point to script file(s).
5191 * Force them to be restored afterwards */
5192 if (is_hidden_fd(sv, fd))
5193 i |= COPYFD_RESTORE;
5197 sv->two_fd[sv_pos].orig = fd;
5198 sv->two_fd[sv_pos].copy = i;
5202 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5203 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5204 /* Don't want to trigger debugging */
5208 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5210 } else if (fd != newfd) { /* move newfd to fd */
5211 copyfd(newfd, fd | COPYFD_EXACT);
5212 #if ENABLE_ASH_BASH_COMPAT
5213 if (!(redir->nfile.type == NTO2 && fd == 2))
5217 #if ENABLE_ASH_BASH_COMPAT
5218 if (redir->nfile.type == NTO2 && fd == 1) {
5219 /* We already redirected it to fd 1, now copy it to 2 */
5225 } while ((redir = redir->nfile.next) != NULL);
5228 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5229 preverrout_fd = copied_fd2;
5233 * Undo the effects of the last redirection.
5236 popredir(int drop, int restore)
5238 struct redirtab *rp;
5241 if (--g_nullredirs >= 0)
5245 for (i = 0; i < rp->pair_count; i++) {
5246 int fd = rp->two_fd[i].orig;
5247 int copy = rp->two_fd[i].copy;
5248 if (copy == CLOSED) {
5253 if (copy != EMPTY) {
5254 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5255 copy &= ~COPYFD_RESTORE;
5257 copyfd(copy, fd | COPYFD_EXACT);
5259 close(copy & ~COPYFD_RESTORE);
5262 redirlist = rp->next;
5263 g_nullredirs = rp->nullredirs;
5269 * Undo all redirections. Called on error or interrupt.
5273 * Discard all saved file descriptors.
5276 clearredir(int drop)
5282 popredir(drop, /*restore:*/ 0);
5287 redirectsafe(union node *redir, int flags)
5290 volatile int saveint;
5291 struct jmploc *volatile savehandler = exception_handler;
5292 struct jmploc jmploc;
5295 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5296 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5298 exception_handler = &jmploc;
5299 redirect(redir, flags);
5301 exception_handler = savehandler;
5302 if (err && exception_type != EXERROR)
5303 longjmp(exception_handler->loc, 1);
5304 RESTORE_INT(saveint);
5309 /* ============ Routines to expand arguments to commands
5311 * We have to deal with backquotes, shell variables, and file metacharacters.
5314 #if ENABLE_SH_MATH_SUPPORT
5316 ash_arith(const char *s)
5318 arith_eval_hooks_t math_hooks;
5322 math_hooks.lookupvar = lookupvar;
5323 math_hooks.setvar = setvar;
5324 math_hooks.endofname = endofname;
5327 result = arith(s, &errcode, &math_hooks);
5330 ash_msg_and_raise_error("exponent less than 0");
5332 ash_msg_and_raise_error("divide by zero");
5334 ash_msg_and_raise_error("expression recursion loop detected");
5335 raise_error_syntax(s);
5346 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5347 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5348 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5349 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5350 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5351 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5352 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5353 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5354 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5358 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5359 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5360 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5361 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5362 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5365 * Structure specifying which parts of the string should be searched
5366 * for IFS characters.
5369 struct ifsregion *next; /* next region in list */
5370 int begoff; /* offset of start of region */
5371 int endoff; /* offset of end of region */
5372 int nulonly; /* search for nul bytes only */
5376 struct strlist *list;
5377 struct strlist **lastp;
5380 /* output of current string */
5381 static char *expdest;
5382 /* list of back quote expressions */
5383 static struct nodelist *argbackq;
5384 /* first struct in list of ifs regions */
5385 static struct ifsregion ifsfirst;
5386 /* last struct in list */
5387 static struct ifsregion *ifslastp;
5388 /* holds expanded arg list */
5389 static struct arglist exparg;
5399 expdest = makestrspace(32, expdest);
5400 len = fmtstr(expdest, 32, arith_t_fmt, num);
5401 STADJUST(len, expdest);
5406 esclen(const char *start, const char *p)
5410 while (p > start && (unsigned char)*--p == CTLESC) {
5417 * Remove any CTLESC characters from a string.
5420 rmescapes(char *str, int flag)
5422 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5426 unsigned protect_against_glob;
5429 p = strpbrk(str, qchars);
5435 if (flag & RMESCAPE_ALLOC) {
5436 size_t len = p - str;
5437 size_t fulllen = len + strlen(p) + 1;
5439 if (flag & RMESCAPE_GROW) {
5440 r = makestrspace(fulllen, expdest);
5441 } else if (flag & RMESCAPE_HEAP) {
5442 r = ckmalloc(fulllen);
5444 r = stalloc(fulllen);
5448 q = (char *)memcpy(q, str, len) + len;
5452 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5453 globbing = flag & RMESCAPE_GLOB;
5454 protect_against_glob = globbing;
5456 if (*p == CTLQUOTEMARK) {
5457 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5458 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5459 // Note: both inquotes and protect_against_glob only affect whether
5460 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5461 inquotes = ~inquotes;
5463 protect_against_glob = globbing;
5467 /* naked back slash */
5468 protect_against_glob = 0;
5473 if (protect_against_glob && inquotes && *p != '/') {
5477 protect_against_glob = globbing;
5482 if (flag & RMESCAPE_GROW) {
5484 STADJUST(q - r + 1, expdest);
5488 #define pmatch(a, b) !fnmatch((a), (b), 0)
5491 * Prepare a pattern for a expmeta (internal glob(3)) call.
5493 * Returns an stalloced string.
5496 preglob(const char *pattern, int quoted, int flag)
5498 flag |= RMESCAPE_GLOB;
5500 flag |= RMESCAPE_QUOTED;
5502 return rmescapes((char *)pattern, flag);
5506 * Put a string on the stack.
5509 memtodest(const char *p, size_t len, int syntax, int quotes)
5513 q = makestrspace(quotes ? len * 2 : len, q);
5516 int c = signed_char2int(*p++);
5520 int n = SIT(c, syntax);
5521 if (n == CCTL || n == CBACK)
5531 strtodest(const char *p, int syntax, int quotes)
5533 memtodest(p, strlen(p), syntax, quotes);
5537 * Record the fact that we have to scan this region of the
5538 * string for IFS characters.
5541 recordregion(int start, int end, int nulonly)
5543 struct ifsregion *ifsp;
5545 if (ifslastp == NULL) {
5549 ifsp = ckzalloc(sizeof(*ifsp));
5550 /*ifsp->next = NULL; - ckzalloc did it */
5551 ifslastp->next = ifsp;
5555 ifslastp->begoff = start;
5556 ifslastp->endoff = end;
5557 ifslastp->nulonly = nulonly;
5561 removerecordregions(int endoff)
5563 if (ifslastp == NULL)
5566 if (ifsfirst.endoff > endoff) {
5567 while (ifsfirst.next != NULL) {
5568 struct ifsregion *ifsp;
5570 ifsp = ifsfirst.next->next;
5571 free(ifsfirst.next);
5572 ifsfirst.next = ifsp;
5575 if (ifsfirst.begoff > endoff)
5578 ifslastp = &ifsfirst;
5579 ifsfirst.endoff = endoff;
5584 ifslastp = &ifsfirst;
5585 while (ifslastp->next && ifslastp->next->begoff < endoff)
5586 ifslastp=ifslastp->next;
5587 while (ifslastp->next != NULL) {
5588 struct ifsregion *ifsp;
5590 ifsp = ifslastp->next->next;
5591 free(ifslastp->next);
5592 ifslastp->next = ifsp;
5595 if (ifslastp->endoff > endoff)
5596 ifslastp->endoff = endoff;
5600 exptilde(char *startp, char *p, int flags)
5606 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5611 while ((c = *++p) != '\0') {
5618 if (flags & EXP_VARTILDE)
5628 if (*name == '\0') {
5629 home = lookupvar(homestr);
5631 pw = getpwnam(name);
5636 if (!home || !*home)
5639 startloc = expdest - (char *)stackblock();
5640 strtodest(home, SQSYNTAX, quotes);
5641 recordregion(startloc, expdest - (char *)stackblock(), 0);
5649 * Execute a command inside back quotes. If it's a builtin command, we
5650 * want to save its output in a block obtained from malloc. Otherwise
5651 * we fork off a subprocess and get the output of the command via a pipe.
5652 * Should be called with interrupts off.
5654 struct backcmd { /* result of evalbackcmd */
5655 int fd; /* file descriptor to read from */
5656 int nleft; /* number of chars in buffer */
5657 char *buf; /* buffer */
5658 struct job *jp; /* job structure for command */
5661 /* These forward decls are needed to use "eval" code for backticks handling: */
5662 static uint8_t back_exitstatus; /* exit status of backquoted command */
5663 #define EV_EXIT 01 /* exit after evaluating tree */
5664 static void evaltree(union node *, int);
5666 static void FAST_FUNC
5667 evalbackcmd(union node *n, struct backcmd *result)
5678 saveherefd = herefd;
5686 ash_msg_and_raise_error("pipe call failed");
5687 jp = makejob(/*n,*/ 1);
5688 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5693 copyfd(pip[1], 1 | COPYFD_EXACT);
5697 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5701 result->fd = pip[0];
5704 herefd = saveherefd;
5706 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5707 result->fd, result->buf, result->nleft, result->jp));
5711 * Expand stuff in backwards quotes.
5714 expbackq(union node *cmd, int quoted, int quotes)
5722 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5723 struct stackmark smark;
5726 setstackmark(&smark);
5728 startloc = dest - (char *)stackblock();
5730 evalbackcmd(cmd, &in);
5731 popstackmark(&smark);
5738 memtodest(p, i, syntax, quotes);
5742 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5743 TRACE(("expbackq: read returns %d\n", i));
5752 back_exitstatus = waitforjob(in.jp);
5756 /* Eat all trailing newlines */
5758 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5763 recordregion(startloc, dest - (char *)stackblock(), 0);
5764 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5765 (dest - (char *)stackblock()) - startloc,
5766 (dest - (char *)stackblock()) - startloc,
5767 stackblock() + startloc));
5770 #if ENABLE_SH_MATH_SUPPORT
5772 * Expand arithmetic expression. Backup to start of expression,
5773 * evaluate, place result in (backed up) result, adjust string position.
5786 * This routine is slightly over-complicated for
5787 * efficiency. Next we scan backwards looking for the
5788 * start of arithmetic.
5790 start = stackblock();
5797 while (*p != CTLARI) {
5801 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5806 esc = esclen(start, p);
5816 removerecordregions(begoff);
5823 rmescapes(p + 2, 0);
5825 len = cvtnum(ash_arith(p + 2));
5828 recordregion(begoff, begoff + len, 0);
5832 /* argstr needs it */
5833 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5836 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5837 * characters to allow for further processing. Otherwise treat
5838 * $@ like $* since no splitting will be performed.
5840 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5841 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5842 * for correct expansion of "B=$A" word.
5845 argstr(char *p, int flags, struct strlist *var_str_list)
5847 static const char spclchars[] ALIGN1 = {
5855 CTLBACKQ | CTLQUOTE,
5856 #if ENABLE_SH_MATH_SUPPORT
5861 const char *reject = spclchars;
5863 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5864 int breakall = flags & EXP_WORD;
5869 if (!(flags & EXP_VARTILDE)) {
5871 } else if (flags & EXP_VARTILDE2) {
5876 if (flags & EXP_TILDE) {
5879 flags &= ~EXP_TILDE;
5882 if (*q == CTLESC && (flags & EXP_QWORD))
5885 p = exptilde(p, q, flags);
5888 startloc = expdest - (char *)stackblock();
5890 length += strcspn(p + length, reject);
5891 c = (unsigned char) p[length];
5894 #if ENABLE_SH_MATH_SUPPORT
5898 /* c == '=' || c == ':' || c == CTLENDARI */
5904 expdest = stack_nputstr(p, length, expdest);
5905 newloc = expdest - (char *)stackblock();
5906 if (breakall && !inquotes && newloc > startloc) {
5907 recordregion(startloc, newloc, 0);
5918 if (flags & EXP_VARTILDE2) {
5922 flags |= EXP_VARTILDE2;
5927 * sort of a hack - expand tildes in variable
5928 * assignments (after the first '=' and after ':'s).
5937 case CTLENDVAR: /* ??? */
5940 /* "$@" syntax adherence hack */
5942 && memcmp(p, dolatstr, 4) == 0
5943 && ( p[4] == CTLQUOTEMARK
5944 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5947 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
5950 inquotes = !inquotes;
5963 p = evalvar(p, flags, var_str_list);
5967 case CTLBACKQ|CTLQUOTE:
5968 expbackq(argbackq->n, c, quotes);
5969 argbackq = argbackq->next;
5971 #if ENABLE_SH_MATH_SUPPORT
5984 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
5987 // This commented out code was added by James Simmons <jsimmons@infradead.org>
5988 // as part of a larger change when he added support for ${var/a/b}.
5989 // However, it broke # and % operators:
5993 //echo ${var#ab} abcdcd abcdcd
5994 //echo ${var##ab} abcdcd abcdcd
5995 //echo ${var#a*b} abcdcd ababcdcd (!)
5996 //echo ${var##a*b} cdcd cdcd
5997 //echo ${var#?} babcdcd ababcdcd (!)
5998 //echo ${var##?} babcdcd babcdcd
5999 //echo ${var#*} ababcdcd babcdcd (!)
6001 //echo ${var%cd} ababcd ababcd
6002 //echo ${var%%cd} ababcd abab (!)
6003 //echo ${var%c*d} ababcd ababcd
6004 //echo ${var%%c*d} abab ababcdcd (!)
6005 //echo ${var%?} ababcdc ababcdc
6006 //echo ${var%%?} ababcdc ababcdcd (!)
6007 //echo ${var%*} ababcdcd ababcdcd
6010 // Commenting it back out helped. Remove it completely if it really
6013 char *loc, *loc2; //, *full;
6019 int match; // = strlen(str);
6020 const char *s = loc2;
6027 match = pmatch(str, s); // this line was deleted
6029 // // chop off end if its '*'
6030 // full = strrchr(str, '*');
6031 // if (full && full != str)
6034 // // If str starts with '*' replace with s.
6035 // if ((*str == '*') && strlen(s) >= match) {
6036 // full = xstrdup(s);
6037 // strncpy(full+strlen(s)-match+1, str+1, match-1);
6039 // full = xstrndup(str, match);
6040 // match = strncmp(s, full, strlen(full));
6044 if (match) // if (!match)
6046 if (quotes && *loc == CTLESC)
6055 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6062 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6065 const char *s = loc2;
6070 match = pmatch(str, s);
6077 esc = esclen(startp, loc);
6088 static void varunset(const char *, const char *, const char *, int) NORETURN;
6090 varunset(const char *end, const char *var, const char *umsg, int varflags)
6096 msg = "parameter not set";
6098 if (*end == CTLENDVAR) {
6099 if (varflags & VSNUL)
6105 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6108 #if ENABLE_ASH_BASH_COMPAT
6110 parse_sub_pattern(char *arg, int inquotes)
6112 char *idx, *repl = NULL;
6121 /* Only the first '/' seen is our separator */
6128 if (!inquotes && c == '\\' && arg[1] == '\\')
6129 arg++; /* skip both \\, not just first one */
6136 #endif /* ENABLE_ASH_BASH_COMPAT */
6139 subevalvar(char *p, char *str, int strloc, int subtype,
6140 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6142 struct nodelist *saveargbackq = argbackq;
6145 char *rmesc, *rmescend;
6146 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6147 IF_ASH_BASH_COMPAT(char null = '\0';)
6148 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6149 int saveherefd = herefd;
6150 int amount, workloc, resetloc;
6152 char *(*scan)(char*, char*, char*, char*, int, int);
6155 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6157 STPUTC('\0', expdest);
6158 herefd = saveherefd;
6159 argbackq = saveargbackq;
6160 startp = (char *)stackblock() + startloc;
6164 setvar(str, startp, 0);
6165 amount = startp - expdest;
6166 STADJUST(amount, expdest);
6169 #if ENABLE_ASH_BASH_COMPAT
6171 loc = str = stackblock() + strloc;
6172 /* Read POS in ${var:POS:LEN} */
6173 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6174 len = str - startp - 1;
6176 /* *loc != '\0', guaranteed by parser */
6180 /* Adjust the length by the number of escapes */
6181 for (ptr = startp; ptr < (str - 1); ptr++) {
6182 if (*ptr == CTLESC) {
6190 if (*loc++ == ':') {
6194 /* Skip POS in ${var:POS:LEN} */
6196 while (*loc && *loc != ':') {
6198 * bash complains on: var=qwe; echo ${var:1a:123}
6200 ash_msg_and_raise_error(msg_illnum, str);
6204 if (*loc++ == ':') {
6208 if (pos >= orig_len) {
6212 if (len > (orig_len - pos))
6213 len = orig_len - pos;
6215 for (str = startp; pos; str++, pos--) {
6216 if (quotes && *str == CTLESC)
6219 for (loc = startp; len; len--) {
6220 if (quotes && *str == CTLESC)
6225 amount = loc - expdest;
6226 STADJUST(amount, expdest);
6231 varunset(p, str, startp, varflags);
6234 resetloc = expdest - (char *)stackblock();
6236 /* We'll comeback here if we grow the stack while handling
6237 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6238 * stack will need rebasing, and we'll need to remove our work
6241 IF_ASH_BASH_COMPAT(restart:)
6243 amount = expdest - ((char *)stackblock() + resetloc);
6244 STADJUST(-amount, expdest);
6245 startp = (char *)stackblock() + startloc;
6248 rmescend = (char *)stackblock() + strloc;
6250 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6251 if (rmesc != startp) {
6253 startp = (char *)stackblock() + startloc;
6257 str = (char *)stackblock() + strloc;
6258 preglob(str, varflags & VSQUOTE, 0);
6259 workloc = expdest - (char *)stackblock();
6261 #if ENABLE_ASH_BASH_COMPAT
6262 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6263 char *idx, *end, *restart_detect;
6266 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6271 /* If there's no pattern to match, return the expansion unmolested */
6279 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6281 /* No match, advance */
6282 restart_detect = stackblock();
6283 STPUTC(*idx, expdest);
6284 if (quotes && *idx == CTLESC) {
6287 STPUTC(*idx, expdest);
6289 if (stackblock() != restart_detect)
6297 if (subtype == VSREPLACEALL) {
6299 if (quotes && *idx == CTLESC)
6308 for (loc = repl; *loc; loc++) {
6309 restart_detect = stackblock();
6310 STPUTC(*loc, expdest);
6311 if (stackblock() != restart_detect)
6316 if (subtype == VSREPLACE) {
6318 restart_detect = stackblock();
6319 STPUTC(*idx, expdest);
6320 if (stackblock() != restart_detect)
6329 /* We've put the replaced text into a buffer at workloc, now
6330 * move it to the right place and adjust the stack.
6332 startp = stackblock() + startloc;
6333 STPUTC('\0', expdest);
6334 memmove(startp, stackblock() + workloc, len);
6335 startp[len++] = '\0';
6336 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6337 STADJUST(-amount, expdest);
6340 #endif /* ENABLE_ASH_BASH_COMPAT */
6342 subtype -= VSTRIMRIGHT;
6344 if (subtype < 0 || subtype > 7)
6347 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6348 zero = subtype >> 1;
6349 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6350 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6352 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6355 memmove(startp, loc, str - loc);
6356 loc = startp + (str - loc) - 1;
6359 amount = loc - expdest;
6360 STADJUST(amount, expdest);
6366 * Add the value of a specialized variable to the stack string.
6369 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6379 int quoted = varflags & VSQUOTE;
6380 int subtype = varflags & VSTYPE;
6381 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6383 if (quoted && (flags & EXP_FULL))
6384 sep = 1 << CHAR_BIT;
6386 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6395 num = shellparam.nparam;
6405 expdest = makestrspace(NOPTS, expdest);
6406 for (i = NOPTS - 1; i >= 0; i--) {
6408 USTPUTC(optletters(i), expdest);
6418 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
6419 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6425 while ((p = *ap++) != NULL) {
6428 partlen = strlen(p);
6431 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6432 memtodest(p, partlen, syntax, quotes);
6438 if (subtype == VSPLUS || subtype == VSLENGTH) {
6459 num = atoi(name); /* number(name) fails on ${N#str} etc */
6460 if (num < 0 || num > shellparam.nparam)
6462 p = num ? shellparam.p[num - 1] : arg0;
6465 /* NB: name has form "VAR=..." */
6467 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6468 * which should be considered before we check variables. */
6470 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6474 str = var_str_list->text;
6475 eq = strchr(str, '=');
6476 if (!eq) /* stop at first non-assignment */
6479 if (name_len == (unsigned)(eq - str)
6480 && strncmp(str, name, name_len) == 0) {
6482 /* goto value; - WRONG! */
6483 /* think "A=1 A=2 B=$A" */
6485 var_str_list = var_str_list->next;
6486 } while (var_str_list);
6490 p = lookupvar(name);
6496 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6497 memtodest(p, len, syntax, quotes);
6501 if (subtype == VSPLUS || subtype == VSLENGTH)
6502 STADJUST(-len, expdest);
6507 * Expand a variable, and return a pointer to the next character in the
6511 evalvar(char *p, int flags, struct strlist *var_str_list)
6522 varflags = (unsigned char) *p++;
6523 subtype = varflags & VSTYPE;
6524 quoted = varflags & VSQUOTE;
6526 easy = (!quoted || (*var == '@' && shellparam.nparam));
6527 startloc = expdest - (char *)stackblock();
6528 p = strchr(p, '=') + 1;
6531 varlen = varvalue(var, varflags, flags, var_str_list);
6532 if (varflags & VSNUL)
6535 if (subtype == VSPLUS) {
6536 varlen = -1 - varlen;
6540 if (subtype == VSMINUS) {
6544 p, flags | EXP_TILDE |
6545 (quoted ? EXP_QWORD : EXP_WORD),
6555 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6557 if (subevalvar(p, var, /* strloc: */ 0,
6558 subtype, startloc, varflags,
6564 * Remove any recorded regions beyond
6567 removerecordregions(startloc);
6577 if (varlen < 0 && uflag)
6578 varunset(p, var, 0, 0);
6580 if (subtype == VSLENGTH) {
6581 cvtnum(varlen > 0 ? varlen : 0);
6585 if (subtype == VSNORMAL) {
6596 case VSTRIMRIGHTMAX:
6597 #if ENABLE_ASH_BASH_COMPAT
6610 * Terminate the string and start recording the pattern
6613 STPUTC('\0', expdest);
6614 patloc = expdest - (char *)stackblock();
6615 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6617 //TODO: | EXP_REDIR too? All other such places do it too
6618 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6621 int amount = expdest - (
6622 (char *)stackblock() + patloc - 1
6624 STADJUST(-amount, expdest);
6626 /* Remove any recorded regions beyond start of variable */
6627 removerecordregions(startloc);
6629 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6633 if (subtype != VSNORMAL) { /* skip to end of alternative */
6639 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6641 argbackq = argbackq->next;
6642 } else if (c == CTLVAR) {
6643 if ((*p++ & VSTYPE) != VSNORMAL)
6645 } else if (c == CTLENDVAR) {
6655 * Break the argument string into pieces based upon IFS and add the
6656 * strings to the argument list. The regions of the string to be
6657 * searched for IFS characters have been stored by recordregion.
6660 ifsbreakup(char *string, struct arglist *arglist)
6662 struct ifsregion *ifsp;
6667 const char *ifs, *realifs;
6672 if (ifslastp != NULL) {
6675 realifs = ifsset() ? ifsval() : defifs;
6678 p = string + ifsp->begoff;
6679 nulonly = ifsp->nulonly;
6680 ifs = nulonly ? nullstr : realifs;
6682 while (p < string + ifsp->endoff) {
6686 if (!strchr(ifs, *p)) {
6691 ifsspc = (strchr(defifs, *p) != NULL);
6692 /* Ignore IFS whitespace at start */
6693 if (q == start && ifsspc) {
6699 sp = stzalloc(sizeof(*sp));
6701 *arglist->lastp = sp;
6702 arglist->lastp = &sp->next;
6706 if (p >= string + ifsp->endoff) {
6712 if (strchr(ifs, *p) == NULL) {
6716 if (strchr(defifs, *p) == NULL) {
6731 } while (ifsp != NULL);
6740 sp = stzalloc(sizeof(*sp));
6742 *arglist->lastp = sp;
6743 arglist->lastp = &sp->next;
6749 struct ifsregion *p;
6754 struct ifsregion *ifsp;
6760 ifsfirst.next = NULL;
6765 * Add a file name to the list.
6768 addfname(const char *name)
6772 sp = stzalloc(sizeof(*sp));
6773 sp->text = ststrdup(name);
6775 exparg.lastp = &sp->next;
6778 static char *expdir;
6781 * Do metacharacter (i.e. *, ?, [...]) expansion.
6784 expmeta(char *enddir, char *name)
6799 for (p = name; *p; p++) {
6800 if (*p == '*' || *p == '?')
6802 else if (*p == '[') {
6809 if (*q == '/' || *q == '\0')
6816 } else if (*p == '\\')
6818 else if (*p == '/') {
6825 if (metaflag == 0) { /* we've reached the end of the file name */
6826 if (enddir != expdir)
6834 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6845 } while (p < start);
6847 if (enddir == expdir) {
6849 } else if (enddir == expdir + 1 && *expdir == '/') {
6858 if (enddir != expdir)
6860 if (*endname == 0) {
6872 while (!pending_int && (dp = readdir(dirp)) != NULL) {
6873 if (dp->d_name[0] == '.' && !matchdot)
6875 if (pmatch(start, dp->d_name)) {
6877 strcpy(enddir, dp->d_name);
6880 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6883 expmeta(p, endname);
6892 static struct strlist *
6893 msort(struct strlist *list, int len)
6895 struct strlist *p, *q = NULL;
6896 struct strlist **lpp;
6904 for (n = half; --n >= 0;) {
6908 q->next = NULL; /* terminate first half of list */
6909 q = msort(list, half); /* sort first half of list */
6910 p = msort(p, len - half); /* sort second half */
6913 #if ENABLE_LOCALE_SUPPORT
6914 if (strcoll(p->text, q->text) < 0)
6916 if (strcmp(p->text, q->text) < 0)
6940 * Sort the results of file name expansion. It calculates the number of
6941 * strings to sort and then calls msort (short for merge sort) to do the
6944 static struct strlist *
6945 expsort(struct strlist *str)
6951 for (sp = str; sp; sp = sp->next)
6953 return msort(str, len);
6957 expandmeta(struct strlist *str /*, int flag*/)
6959 static const char metachars[] ALIGN1 = {
6962 /* TODO - EXP_REDIR */
6965 struct strlist **savelastp;
6971 if (!strpbrk(str->text, metachars))
6973 savelastp = exparg.lastp;
6976 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6978 int i = strlen(str->text);
6979 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6987 if (exparg.lastp == savelastp) {
6992 *exparg.lastp = str;
6993 rmescapes(str->text, 0);
6994 exparg.lastp = &str->next;
6996 *exparg.lastp = NULL;
6997 *savelastp = sp = expsort(*savelastp);
6998 while (sp->next != NULL)
7000 exparg.lastp = &sp->next;
7007 * Perform variable substitution and command substitution on an argument,
7008 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7009 * perform splitting and file name expansion. When arglist is NULL, perform
7010 * here document expansion.
7013 expandarg(union node *arg, struct arglist *arglist, int flag)
7018 argbackq = arg->narg.backquote;
7019 STARTSTACKSTR(expdest);
7020 ifsfirst.next = NULL;
7022 argstr(arg->narg.text, flag,
7023 /* var_str_list: */ arglist ? arglist->list : NULL);
7024 p = _STPUTC('\0', expdest);
7026 if (arglist == NULL) {
7027 return; /* here document expanded */
7029 p = grabstackstr(p);
7030 exparg.lastp = &exparg.list;
7034 if (flag & EXP_FULL) {
7035 ifsbreakup(p, &exparg);
7036 *exparg.lastp = NULL;
7037 exparg.lastp = &exparg.list;
7038 expandmeta(exparg.list /*, flag*/);
7040 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7042 sp = stzalloc(sizeof(*sp));
7045 exparg.lastp = &sp->next;
7049 *exparg.lastp = NULL;
7051 *arglist->lastp = exparg.list;
7052 arglist->lastp = exparg.lastp;
7057 * Expand shell variables and backquotes inside a here document.
7060 expandhere(union node *arg, int fd)
7063 expandarg(arg, (struct arglist *)NULL, 0);
7064 full_write(fd, stackblock(), expdest - (char *)stackblock());
7068 * Returns true if the pattern matches the string.
7071 patmatch(char *pattern, const char *string)
7073 return pmatch(preglob(pattern, 0, 0), string);
7077 * See if a pattern matches in a case statement.
7080 casematch(union node *pattern, char *val)
7082 struct stackmark smark;
7085 setstackmark(&smark);
7086 argbackq = pattern->narg.backquote;
7087 STARTSTACKSTR(expdest);
7089 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7090 /* var_str_list: */ NULL);
7091 STACKSTRNUL(expdest);
7092 result = patmatch(stackblock(), val);
7093 popstackmark(&smark);
7098 /* ============ find_command */
7102 int (*builtin)(int, char **) FAST_FUNC;
7103 /* unsigned flags; */
7105 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7106 /* "regular" builtins always take precedence over commands,
7107 * regardless of PATH=....%builtin... position */
7108 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7109 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7112 smallint cmdtype; /* CMDxxx */
7115 /* index >= 0 for commands without path (slashes) */
7116 /* (TODO: what exactly does the value mean? PATH position?) */
7117 /* index == -1 for commands with slashes */
7118 /* index == (-2 - applet_no) for NOFORK applets */
7119 const struct builtincmd *cmd;
7120 struct funcnode *func;
7123 /* values of cmdtype */
7124 #define CMDUNKNOWN -1 /* no entry in table for command */
7125 #define CMDNORMAL 0 /* command is an executable program */
7126 #define CMDFUNCTION 1 /* command is a shell function */
7127 #define CMDBUILTIN 2 /* command is a shell builtin */
7129 /* action to find_command() */
7130 #define DO_ERR 0x01 /* prints errors */
7131 #define DO_ABS 0x02 /* checks absolute paths */
7132 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7133 #define DO_ALTPATH 0x08 /* using alternate path */
7134 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7136 static void find_command(char *, struct cmdentry *, int, const char *);
7139 /* ============ Hashing commands */
7142 * When commands are first encountered, they are entered in a hash table.
7143 * This ensures that a full path search will not have to be done for them
7144 * on each invocation.
7146 * We should investigate converting to a linear search, even though that
7147 * would make the command name "hash" a misnomer.
7151 struct tblentry *next; /* next entry in hash chain */
7152 union param param; /* definition of builtin function */
7153 smallint cmdtype; /* CMDxxx */
7154 char rehash; /* if set, cd done since entry created */
7155 char cmdname[1]; /* name of command */
7158 static struct tblentry **cmdtable;
7159 #define INIT_G_cmdtable() do { \
7160 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7163 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7167 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7171 #if ENABLE_FEATURE_SH_STANDALONE
7172 if (applet_no >= 0) {
7173 if (APPLET_IS_NOEXEC(applet_no)) {
7176 run_applet_no_and_exit(applet_no, argv);
7178 /* re-exec ourselves with the new arguments */
7179 execve(bb_busybox_exec_path, argv, envp);
7180 /* If they called chroot or otherwise made the binary no longer
7181 * executable, fall through */
7188 execve(cmd, argv, envp);
7189 } while (errno == EINTR);
7191 execve(cmd, argv, envp);
7197 if (errno == ENOEXEC) {
7201 for (ap = argv; *ap; ap++)
7203 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7205 ap[0] = cmd = (char *)DEFAULT_SHELL;
7208 while ((*ap++ = *argv++) != NULL)
7217 * Exec a program. Never returns. If you change this routine, you may
7218 * have to change the find_command routine as well.
7220 static void shellexec(char **, const char *, int) NORETURN;
7222 shellexec(char **argv, const char *path, int idx)
7228 #if ENABLE_FEATURE_SH_STANDALONE
7232 clearredir(/*drop:*/ 1);
7233 envp = listvars(VEXPORT, VUNSET, 0);
7234 if (strchr(argv[0], '/') != NULL
7235 #if ENABLE_FEATURE_SH_STANDALONE
7236 || (applet_no = find_applet_by_name(argv[0])) >= 0
7239 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7243 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7244 if (--idx < 0 && pathopt == NULL) {
7245 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7246 if (errno != ENOENT && errno != ENOTDIR)
7253 /* Map to POSIX errors */
7265 exitstatus = exerrno;
7266 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7267 argv[0], e, suppress_int));
7268 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7273 printentry(struct tblentry *cmdp)
7279 idx = cmdp->param.index;
7282 name = path_advance(&path, cmdp->cmdname);
7284 } while (--idx >= 0);
7285 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7289 * Clear out command entries. The argument specifies the first entry in
7290 * PATH which has changed.
7293 clearcmdentry(int firstchange)
7295 struct tblentry **tblp;
7296 struct tblentry **pp;
7297 struct tblentry *cmdp;
7300 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7302 while ((cmdp = *pp) != NULL) {
7303 if ((cmdp->cmdtype == CMDNORMAL &&
7304 cmdp->param.index >= firstchange)
7305 || (cmdp->cmdtype == CMDBUILTIN &&
7306 builtinloc >= firstchange)
7319 * Locate a command in the command hash table. If "add" is nonzero,
7320 * add the command to the table if it is not already present. The
7321 * variable "lastcmdentry" is set to point to the address of the link
7322 * pointing to the entry, so that delete_cmd_entry can delete the
7325 * Interrupts must be off if called with add != 0.
7327 static struct tblentry **lastcmdentry;
7329 static struct tblentry *
7330 cmdlookup(const char *name, int add)
7332 unsigned int hashval;
7334 struct tblentry *cmdp;
7335 struct tblentry **pp;
7338 hashval = (unsigned char)*p << 4;
7340 hashval += (unsigned char)*p++;
7342 pp = &cmdtable[hashval % CMDTABLESIZE];
7343 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7344 if (strcmp(cmdp->cmdname, name) == 0)
7348 if (add && cmdp == NULL) {
7349 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7351 /* + 1 - already done because
7352 * tblentry::cmdname is char[1] */);
7353 /*cmdp->next = NULL; - ckzalloc did it */
7354 cmdp->cmdtype = CMDUNKNOWN;
7355 strcpy(cmdp->cmdname, name);
7362 * Delete the command entry returned on the last lookup.
7365 delete_cmd_entry(void)
7367 struct tblentry *cmdp;
7370 cmdp = *lastcmdentry;
7371 *lastcmdentry = cmdp->next;
7372 if (cmdp->cmdtype == CMDFUNCTION)
7373 freefunc(cmdp->param.func);
7379 * Add a new command entry, replacing any existing command entry for
7380 * the same name - except special builtins.
7383 addcmdentry(char *name, struct cmdentry *entry)
7385 struct tblentry *cmdp;
7387 cmdp = cmdlookup(name, 1);
7388 if (cmdp->cmdtype == CMDFUNCTION) {
7389 freefunc(cmdp->param.func);
7391 cmdp->cmdtype = entry->cmdtype;
7392 cmdp->param = entry->u;
7396 static int FAST_FUNC
7397 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7399 struct tblentry **pp;
7400 struct tblentry *cmdp;
7402 struct cmdentry entry;
7405 if (nextopt("r") != '\0') {
7410 if (*argptr == NULL) {
7411 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7412 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7413 if (cmdp->cmdtype == CMDNORMAL)
7421 while ((name = *argptr) != NULL) {
7422 cmdp = cmdlookup(name, 0);
7424 && (cmdp->cmdtype == CMDNORMAL
7425 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7429 find_command(name, &entry, DO_ERR, pathval());
7430 if (entry.cmdtype == CMDUNKNOWN)
7438 * Called when a cd is done. Marks all commands so the next time they
7439 * are executed they will be rehashed.
7444 struct tblentry **pp;
7445 struct tblentry *cmdp;
7447 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7448 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7449 if (cmdp->cmdtype == CMDNORMAL
7450 || (cmdp->cmdtype == CMDBUILTIN
7451 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7461 * Fix command hash table when PATH changed.
7462 * Called before PATH is changed. The argument is the new value of PATH;
7463 * pathval() still returns the old value at this point.
7464 * Called with interrupts off.
7466 static void FAST_FUNC
7467 changepath(const char *new)
7475 firstchange = 9999; /* assume no change */
7481 if ((*old == '\0' && *new == ':')
7482 || (*old == ':' && *new == '\0'))
7484 old = new; /* ignore subsequent differences */
7488 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7494 if (builtinloc < 0 && idx_bltin >= 0)
7495 builtinloc = idx_bltin; /* zap builtins */
7496 if (builtinloc >= 0 && idx_bltin < 0)
7498 clearcmdentry(firstchange);
7499 builtinloc = idx_bltin;
7514 #define TENDBQUOTE 12
7531 typedef smallint token_id_t;
7533 /* first char is indicating which tokens mark the end of a list */
7534 static const char *const tokname_array[] = {
7548 #define KWDOFFSET 13
7549 /* the following are keywords */
7571 static char buf[16];
7574 //if (tok < TSEMI) return tokname_array[tok] + 1;
7575 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7580 sprintf(buf + (tok >= TSEMI), "%s%c",
7581 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7585 /* Wrapper around strcmp for qsort/bsearch/... */
7587 pstrcmp(const void *a, const void *b)
7589 return strcmp((char*) a, (*(char**) b) + 1);
7592 static const char *const *
7593 findkwd(const char *s)
7595 return bsearch(s, tokname_array + KWDOFFSET,
7596 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7597 sizeof(tokname_array[0]), pstrcmp);
7601 * Locate and print what a word is...
7604 describe_command(char *command, int describe_command_verbose)
7606 struct cmdentry entry;
7607 struct tblentry *cmdp;
7608 #if ENABLE_ASH_ALIAS
7609 const struct alias *ap;
7611 const char *path = pathval();
7613 if (describe_command_verbose) {
7617 /* First look at the keywords */
7618 if (findkwd(command)) {
7619 out1str(describe_command_verbose ? " is a shell keyword" : command);
7623 #if ENABLE_ASH_ALIAS
7624 /* Then look at the aliases */
7625 ap = lookupalias(command, 0);
7627 if (!describe_command_verbose) {
7632 out1fmt(" is an alias for %s", ap->val);
7636 /* Then check if it is a tracked alias */
7637 cmdp = cmdlookup(command, 0);
7639 entry.cmdtype = cmdp->cmdtype;
7640 entry.u = cmdp->param;
7642 /* Finally use brute force */
7643 find_command(command, &entry, DO_ABS, path);
7646 switch (entry.cmdtype) {
7648 int j = entry.u.index;
7654 p = path_advance(&path, command);
7658 if (describe_command_verbose) {
7660 (cmdp ? " a tracked alias for" : nullstr), p
7669 if (describe_command_verbose) {
7670 out1str(" is a shell function");
7677 if (describe_command_verbose) {
7678 out1fmt(" is a %sshell builtin",
7679 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7680 "special " : nullstr
7688 if (describe_command_verbose) {
7689 out1str(": not found\n");
7694 outstr("\n", stdout);
7698 static int FAST_FUNC
7699 typecmd(int argc UNUSED_PARAM, char **argv)
7705 /* type -p ... ? (we don't bother checking for 'p') */
7706 if (argv[1] && argv[1][0] == '-') {
7711 err |= describe_command(argv[i++], verbose);
7716 #if ENABLE_ASH_CMDCMD
7717 static int FAST_FUNC
7718 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7726 while ((c = nextopt("pvV")) != '\0')
7728 verify |= VERIFY_VERBOSE;
7730 verify |= VERIFY_BRIEF;
7735 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7736 if (verify && (*argptr != NULL)) {
7737 return describe_command(*argptr, verify - VERIFY_BRIEF);
7745 /* ============ eval.c */
7747 static int funcblocksize; /* size of structures in function */
7748 static int funcstringsize; /* size of strings in node */
7749 static void *funcblock; /* block to allocate function from */
7750 static char *funcstring; /* block to allocate strings from */
7752 /* flags in argument to evaltree */
7753 #define EV_EXIT 01 /* exit after evaluating tree */
7754 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7755 #define EV_BACKCMD 04 /* command executing within back quotes */
7757 static const short nodesize[N_NUMBER] = {
7758 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7759 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7760 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7761 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7762 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7763 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7764 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7765 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7766 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7767 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7768 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7769 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7770 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7771 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7772 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7773 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7774 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7775 #if ENABLE_ASH_BASH_COMPAT
7776 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7778 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7779 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7780 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7781 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7782 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7783 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7784 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7785 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7786 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7789 static void calcsize(union node *n);
7792 sizenodelist(struct nodelist *lp)
7795 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7802 calcsize(union node *n)
7806 funcblocksize += nodesize[n->type];
7809 calcsize(n->ncmd.redirect);
7810 calcsize(n->ncmd.args);
7811 calcsize(n->ncmd.assign);
7814 sizenodelist(n->npipe.cmdlist);
7819 calcsize(n->nredir.redirect);
7820 calcsize(n->nredir.n);
7827 calcsize(n->nbinary.ch2);
7828 calcsize(n->nbinary.ch1);
7831 calcsize(n->nif.elsepart);
7832 calcsize(n->nif.ifpart);
7833 calcsize(n->nif.test);
7836 funcstringsize += strlen(n->nfor.var) + 1;
7837 calcsize(n->nfor.body);
7838 calcsize(n->nfor.args);
7841 calcsize(n->ncase.cases);
7842 calcsize(n->ncase.expr);
7845 calcsize(n->nclist.body);
7846 calcsize(n->nclist.pattern);
7847 calcsize(n->nclist.next);
7851 sizenodelist(n->narg.backquote);
7852 funcstringsize += strlen(n->narg.text) + 1;
7853 calcsize(n->narg.next);
7856 #if ENABLE_ASH_BASH_COMPAT
7863 calcsize(n->nfile.fname);
7864 calcsize(n->nfile.next);
7868 calcsize(n->ndup.vname);
7869 calcsize(n->ndup.next);
7873 calcsize(n->nhere.doc);
7874 calcsize(n->nhere.next);
7877 calcsize(n->nnot.com);
7883 nodeckstrdup(char *s)
7885 char *rtn = funcstring;
7887 strcpy(funcstring, s);
7888 funcstring += strlen(s) + 1;
7892 static union node *copynode(union node *);
7894 static struct nodelist *
7895 copynodelist(struct nodelist *lp)
7897 struct nodelist *start;
7898 struct nodelist **lpp;
7903 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7904 (*lpp)->n = copynode(lp->n);
7906 lpp = &(*lpp)->next;
7913 copynode(union node *n)
7920 funcblock = (char *) funcblock + nodesize[n->type];
7924 new->ncmd.redirect = copynode(n->ncmd.redirect);
7925 new->ncmd.args = copynode(n->ncmd.args);
7926 new->ncmd.assign = copynode(n->ncmd.assign);
7929 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7930 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
7935 new->nredir.redirect = copynode(n->nredir.redirect);
7936 new->nredir.n = copynode(n->nredir.n);
7943 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7944 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7947 new->nif.elsepart = copynode(n->nif.elsepart);
7948 new->nif.ifpart = copynode(n->nif.ifpart);
7949 new->nif.test = copynode(n->nif.test);
7952 new->nfor.var = nodeckstrdup(n->nfor.var);
7953 new->nfor.body = copynode(n->nfor.body);
7954 new->nfor.args = copynode(n->nfor.args);
7957 new->ncase.cases = copynode(n->ncase.cases);
7958 new->ncase.expr = copynode(n->ncase.expr);
7961 new->nclist.body = copynode(n->nclist.body);
7962 new->nclist.pattern = copynode(n->nclist.pattern);
7963 new->nclist.next = copynode(n->nclist.next);
7967 new->narg.backquote = copynodelist(n->narg.backquote);
7968 new->narg.text = nodeckstrdup(n->narg.text);
7969 new->narg.next = copynode(n->narg.next);
7972 #if ENABLE_ASH_BASH_COMPAT
7979 new->nfile.fname = copynode(n->nfile.fname);
7980 new->nfile.fd = n->nfile.fd;
7981 new->nfile.next = copynode(n->nfile.next);
7985 new->ndup.vname = copynode(n->ndup.vname);
7986 new->ndup.dupfd = n->ndup.dupfd;
7987 new->ndup.fd = n->ndup.fd;
7988 new->ndup.next = copynode(n->ndup.next);
7992 new->nhere.doc = copynode(n->nhere.doc);
7993 new->nhere.fd = n->nhere.fd;
7994 new->nhere.next = copynode(n->nhere.next);
7997 new->nnot.com = copynode(n->nnot.com);
8000 new->type = n->type;
8005 * Make a copy of a parse tree.
8007 static struct funcnode *
8008 copyfunc(union node *n)
8013 funcblocksize = offsetof(struct funcnode, n);
8016 blocksize = funcblocksize;
8017 f = ckmalloc(blocksize + funcstringsize);
8018 funcblock = (char *) f + offsetof(struct funcnode, n);
8019 funcstring = (char *) f + blocksize;
8026 * Define a shell function.
8029 defun(char *name, union node *func)
8031 struct cmdentry entry;
8034 entry.cmdtype = CMDFUNCTION;
8035 entry.u.func = copyfunc(func);
8036 addcmdentry(name, &entry);
8040 /* Reasons for skipping commands (see comment on breakcmd routine) */
8041 #define SKIPBREAK (1 << 0)
8042 #define SKIPCONT (1 << 1)
8043 #define SKIPFUNC (1 << 2)
8044 #define SKIPFILE (1 << 3)
8045 #define SKIPEVAL (1 << 4)
8046 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8047 static int skipcount; /* number of levels to skip */
8048 static int funcnest; /* depth of function calls */
8049 static int loopnest; /* current loop nesting level */
8051 /* Forward decl way out to parsing code - dotrap needs it */
8052 static int evalstring(char *s, int mask);
8054 /* Called to execute a trap.
8055 * Single callsite - at the end of evaltree().
8056 * If we return non-zero, exaltree raises EXEXIT exception.
8058 * Perhaps we should avoid entering new trap handlers
8059 * while we are executing a trap handler. [is it a TODO?]
8068 savestatus = exitstatus;
8072 TRACE(("dotrap entered\n"));
8073 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8080 /* non-trapped SIGINT is handled separately by raise_interrupt,
8081 * don't upset it by resetting gotsig[SIGINT-1] */
8082 if (sig == SIGINT && !t)
8085 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8089 want_exexit = evalstring(t, SKIPEVAL);
8090 exitstatus = savestatus;
8092 TRACE(("dotrap returns %d\n", want_exexit));
8097 TRACE(("dotrap returns 0\n"));
8101 /* forward declarations - evaluation is fairly recursive business... */
8102 static void evalloop(union node *, int);
8103 static void evalfor(union node *, int);
8104 static void evalcase(union node *, int);
8105 static void evalsubshell(union node *, int);
8106 static void expredir(union node *);
8107 static void evalpipe(union node *, int);
8108 static void evalcommand(union node *, int);
8109 static int evalbltin(const struct builtincmd *, int, char **);
8110 static void prehash(union node *);
8113 * Evaluate a parse tree. The value is left in the global variable
8117 evaltree(union node *n, int flags)
8119 struct jmploc *volatile savehandler = exception_handler;
8120 struct jmploc jmploc;
8122 void (*evalfn)(union node *, int);
8126 SAVE_INT(int_level);
8129 TRACE(("evaltree(NULL) called\n"));
8132 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8134 exception_handler = &jmploc;
8136 int err = setjmp(jmploc.loc);
8138 /* if it was a signal, check for trap handlers */
8139 if (exception_type == EXSIG) {
8140 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8141 exception_type, err));
8144 /* continue on the way out */
8145 TRACE(("exception %d in evaltree, propagating err=%d\n",
8146 exception_type, err));
8147 exception_handler = savehandler;
8148 longjmp(exception_handler->loc, err);
8155 out1fmt("Node type = %d\n", n->type);
8160 evaltree(n->nnot.com, EV_TESTED);
8161 status = !exitstatus;
8164 expredir(n->nredir.redirect);
8165 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8167 evaltree(n->nredir.n, flags & EV_TESTED);
8168 status = exitstatus;
8170 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8173 evalfn = evalcommand;
8175 if (eflag && !(flags & EV_TESTED))
8187 evalfn = evalsubshell;
8200 #error NAND + 1 != NOR
8202 #if NOR + 1 != NSEMI
8203 #error NOR + 1 != NSEMI
8205 unsigned is_or = n->type - NAND;
8208 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8210 if (!exitstatus == is_or)
8223 evaltree(n->nif.test, EV_TESTED);
8226 if (exitstatus == 0) {
8230 if (n->nif.elsepart) {
8231 n = n->nif.elsepart;
8236 defun(n->narg.text, n->narg.next);
8240 exitstatus = status;
8245 exception_handler = savehandler;
8247 if (checkexit & exitstatus)
8248 evalskip |= SKIPEVAL;
8249 else if (pending_sig && dotrap())
8252 if (flags & EV_EXIT) {
8254 raise_exception(EXEXIT);
8257 RESTORE_INT(int_level);
8258 TRACE(("leaving evaltree (no interrupts)\n"));
8261 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8264 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8267 evalloop(union node *n, int flags)
8277 evaltree(n->nbinary.ch1, EV_TESTED);
8280 if (evalskip == SKIPCONT && --skipcount <= 0) {
8284 if (evalskip == SKIPBREAK && --skipcount <= 0)
8289 if (n->type != NWHILE)
8293 evaltree(n->nbinary.ch2, flags);
8294 status = exitstatus;
8299 exitstatus = status;
8303 evalfor(union node *n, int flags)
8305 struct arglist arglist;
8308 struct stackmark smark;
8310 setstackmark(&smark);
8311 arglist.list = NULL;
8312 arglist.lastp = &arglist.list;
8313 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8314 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8319 *arglist.lastp = NULL;
8324 for (sp = arglist.list; sp; sp = sp->next) {
8325 setvar(n->nfor.var, sp->text, 0);
8326 evaltree(n->nfor.body, flags);
8328 if (evalskip == SKIPCONT && --skipcount <= 0) {
8332 if (evalskip == SKIPBREAK && --skipcount <= 0)
8339 popstackmark(&smark);
8343 evalcase(union node *n, int flags)
8347 struct arglist arglist;
8348 struct stackmark smark;
8350 setstackmark(&smark);
8351 arglist.list = NULL;
8352 arglist.lastp = &arglist.list;
8353 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8355 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8356 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8357 if (casematch(patp, arglist.list->text)) {
8358 if (evalskip == 0) {
8359 evaltree(cp->nclist.body, flags);
8366 popstackmark(&smark);
8370 * Kick off a subshell to evaluate a tree.
8373 evalsubshell(union node *n, int flags)
8376 int backgnd = (n->type == NBACKGND);
8379 expredir(n->nredir.redirect);
8380 if (!backgnd && flags & EV_EXIT && !trap[0])
8383 jp = makejob(/*n,*/ 1);
8384 if (forkshell(jp, n, backgnd) == 0) {
8388 flags &=~ EV_TESTED;
8390 redirect(n->nredir.redirect, 0);
8391 evaltreenr(n->nredir.n, flags);
8396 status = waitforjob(jp);
8397 exitstatus = status;
8402 * Compute the names of the files in a redirection list.
8404 static void fixredir(union node *, const char *, int);
8406 expredir(union node *n)
8410 for (redir = n; redir; redir = redir->nfile.next) {
8414 fn.lastp = &fn.list;
8415 switch (redir->type) {
8419 #if ENABLE_ASH_BASH_COMPAT
8424 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8425 #if ENABLE_ASH_BASH_COMPAT
8428 redir->nfile.expfname = fn.list->text;
8431 case NTOFD: /* >& */
8432 if (redir->ndup.vname) {
8433 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8434 if (fn.list == NULL)
8435 ash_msg_and_raise_error("redir error");
8436 #if ENABLE_ASH_BASH_COMPAT
8437 //FIXME: we used expandarg with different args!
8438 if (!isdigit_str9(fn.list->text)) {
8439 /* >&file, not >&fd */
8440 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8441 ash_msg_and_raise_error("redir error");
8443 goto store_expfname;
8446 fixredir(redir, fn.list->text, 1);
8454 * Evaluate a pipeline. All the processes in the pipeline are children
8455 * of the process creating the pipeline. (This differs from some versions
8456 * of the shell, which make the last process in a pipeline the parent
8460 evalpipe(union node *n, int flags)
8463 struct nodelist *lp;
8468 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8470 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8474 jp = makejob(/*n,*/ pipelen);
8476 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8480 if (pipe(pip) < 0) {
8482 ash_msg_and_raise_error("pipe call failed");
8485 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8498 evaltreenr(lp->n, flags);
8504 /* Don't want to trigger debugging */
8508 if (n->npipe.pipe_backgnd == 0) {
8509 exitstatus = waitforjob(jp);
8510 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8516 * Controls whether the shell is interactive or not.
8519 setinteractive(int on)
8521 static smallint is_interactive;
8523 if (++on == is_interactive)
8525 is_interactive = on;
8529 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8530 if (is_interactive > 1) {
8531 /* Looks like they want an interactive shell */
8532 static smallint did_banner;
8537 "%s built-in shell (ash)\n"
8538 "Enter 'help' for a list of built-in commands."
8553 setinteractive(iflag);
8555 #if ENABLE_FEATURE_EDITING_VI
8557 line_input_state->flags |= VI_MODE;
8559 line_input_state->flags &= ~VI_MODE;
8561 viflag = 0; /* forcibly keep the option off */
8565 static struct localvar *localvars;
8568 * Called after a function returns.
8569 * Interrupts must be off.
8574 struct localvar *lvp;
8577 while ((lvp = localvars) != NULL) {
8578 localvars = lvp->next;
8580 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8581 if (vp == NULL) { /* $- saved */
8582 memcpy(optlist, lvp->text, sizeof(optlist));
8583 free((char*)lvp->text);
8585 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8589 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8590 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8591 free((char*)vp->text);
8592 vp->flags = lvp->flags;
8593 vp->text = lvp->text;
8600 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8602 volatile struct shparam saveparam;
8603 struct localvar *volatile savelocalvars;
8604 struct jmploc *volatile savehandler;
8605 struct jmploc jmploc;
8608 saveparam = shellparam;
8609 savelocalvars = localvars;
8610 e = setjmp(jmploc.loc);
8615 savehandler = exception_handler;
8616 exception_handler = &jmploc;
8618 shellparam.malloced = 0;
8622 shellparam.nparam = argc - 1;
8623 shellparam.p = argv + 1;
8624 #if ENABLE_ASH_GETOPTS
8625 shellparam.optind = 1;
8626 shellparam.optoff = -1;
8628 evaltree(&func->n, flags & EV_TESTED);
8634 localvars = savelocalvars;
8635 freeparam(&shellparam);
8636 shellparam = saveparam;
8637 exception_handler = savehandler;
8639 evalskip &= ~SKIPFUNC;
8643 #if ENABLE_ASH_CMDCMD
8645 parse_command_args(char **argv, const char **path)
8658 if (c == '-' && !*cp) {
8665 *path = bb_default_path;
8668 /* run 'typecmd' for other options */
8679 * Make a variable a local variable. When a variable is made local, it's
8680 * value and flags are saved in a localvar structure. The saved values
8681 * will be restored when the shell function returns. We handle the name
8682 * "-" as a special case.
8687 struct localvar *lvp;
8692 lvp = ckzalloc(sizeof(struct localvar));
8693 if (LONE_DASH(name)) {
8695 p = ckmalloc(sizeof(optlist));
8696 lvp->text = memcpy(p, optlist, sizeof(optlist));
8701 vpp = hashvar(name);
8702 vp = *findvar(vpp, name);
8703 eq = strchr(name, '=');
8706 setvareq(name, VSTRFIXED);
8708 setvar(name, NULL, VSTRFIXED);
8709 vp = *vpp; /* the new variable */
8710 lvp->flags = VUNSET;
8712 lvp->text = vp->text;
8713 lvp->flags = vp->flags;
8714 vp->flags |= VSTRFIXED|VTEXTFIXED;
8720 lvp->next = localvars;
8726 * The "local" command.
8728 static int FAST_FUNC
8729 localcmd(int argc UNUSED_PARAM, char **argv)
8734 while ((name = *argv++) != NULL) {
8740 static int FAST_FUNC
8741 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8746 static int FAST_FUNC
8747 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8752 static int FAST_FUNC
8753 execcmd(int argc UNUSED_PARAM, char **argv)
8756 iflag = 0; /* exit on error */
8759 shellexec(argv + 1, pathval(), 0);
8765 * The return command.
8767 static int FAST_FUNC
8768 returncmd(int argc UNUSED_PARAM, char **argv)
8771 * If called outside a function, do what ksh does;
8772 * skip the rest of the file.
8774 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8775 return argv[1] ? number(argv[1]) : exitstatus;
8778 /* Forward declarations for builtintab[] */
8779 static int breakcmd(int, char **) FAST_FUNC;
8780 static int dotcmd(int, char **) FAST_FUNC;
8781 static int evalcmd(int, char **) FAST_FUNC;
8782 static int exitcmd(int, char **) FAST_FUNC;
8783 static int exportcmd(int, char **) FAST_FUNC;
8784 #if ENABLE_ASH_GETOPTS
8785 static int getoptscmd(int, char **) FAST_FUNC;
8787 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8788 static int helpcmd(int, char **) FAST_FUNC;
8790 #if ENABLE_SH_MATH_SUPPORT
8791 static int letcmd(int, char **) FAST_FUNC;
8793 static int readcmd(int, char **) FAST_FUNC;
8794 static int setcmd(int, char **) FAST_FUNC;
8795 static int shiftcmd(int, char **) FAST_FUNC;
8796 static int timescmd(int, char **) FAST_FUNC;
8797 static int trapcmd(int, char **) FAST_FUNC;
8798 static int umaskcmd(int, char **) FAST_FUNC;
8799 static int unsetcmd(int, char **) FAST_FUNC;
8800 static int ulimitcmd(int, char **) FAST_FUNC;
8802 #define BUILTIN_NOSPEC "0"
8803 #define BUILTIN_SPECIAL "1"
8804 #define BUILTIN_REGULAR "2"
8805 #define BUILTIN_SPEC_REG "3"
8806 #define BUILTIN_ASSIGN "4"
8807 #define BUILTIN_SPEC_ASSG "5"
8808 #define BUILTIN_REG_ASSG "6"
8809 #define BUILTIN_SPEC_REG_ASSG "7"
8811 /* Stubs for calling non-FAST_FUNC's */
8812 #if ENABLE_ASH_BUILTIN_ECHO
8813 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8815 #if ENABLE_ASH_BUILTIN_PRINTF
8816 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8818 #if ENABLE_ASH_BUILTIN_TEST
8819 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8822 /* Keep these in proper order since it is searched via bsearch() */
8823 static const struct builtincmd builtintab[] = {
8824 { BUILTIN_SPEC_REG ".", dotcmd },
8825 { BUILTIN_SPEC_REG ":", truecmd },
8826 #if ENABLE_ASH_BUILTIN_TEST
8827 { BUILTIN_REGULAR "[", testcmd },
8828 #if ENABLE_ASH_BASH_COMPAT
8829 { BUILTIN_REGULAR "[[", testcmd },
8832 #if ENABLE_ASH_ALIAS
8833 { BUILTIN_REG_ASSG "alias", aliascmd },
8836 { BUILTIN_REGULAR "bg", fg_bgcmd },
8838 { BUILTIN_SPEC_REG "break", breakcmd },
8839 { BUILTIN_REGULAR "cd", cdcmd },
8840 { BUILTIN_NOSPEC "chdir", cdcmd },
8841 #if ENABLE_ASH_CMDCMD
8842 { BUILTIN_REGULAR "command", commandcmd },
8844 { BUILTIN_SPEC_REG "continue", breakcmd },
8845 #if ENABLE_ASH_BUILTIN_ECHO
8846 { BUILTIN_REGULAR "echo", echocmd },
8848 { BUILTIN_SPEC_REG "eval", evalcmd },
8849 { BUILTIN_SPEC_REG "exec", execcmd },
8850 { BUILTIN_SPEC_REG "exit", exitcmd },
8851 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8852 { BUILTIN_REGULAR "false", falsecmd },
8854 { BUILTIN_REGULAR "fg", fg_bgcmd },
8856 #if ENABLE_ASH_GETOPTS
8857 { BUILTIN_REGULAR "getopts", getoptscmd },
8859 { BUILTIN_NOSPEC "hash", hashcmd },
8860 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8861 { BUILTIN_NOSPEC "help", helpcmd },
8864 { BUILTIN_REGULAR "jobs", jobscmd },
8865 { BUILTIN_REGULAR "kill", killcmd },
8867 #if ENABLE_SH_MATH_SUPPORT
8868 { BUILTIN_NOSPEC "let", letcmd },
8870 { BUILTIN_ASSIGN "local", localcmd },
8871 #if ENABLE_ASH_BUILTIN_PRINTF
8872 { BUILTIN_REGULAR "printf", printfcmd },
8874 { BUILTIN_NOSPEC "pwd", pwdcmd },
8875 { BUILTIN_REGULAR "read", readcmd },
8876 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8877 { BUILTIN_SPEC_REG "return", returncmd },
8878 { BUILTIN_SPEC_REG "set", setcmd },
8879 { BUILTIN_SPEC_REG "shift", shiftcmd },
8880 { BUILTIN_SPEC_REG "source", dotcmd },
8881 #if ENABLE_ASH_BUILTIN_TEST
8882 { BUILTIN_REGULAR "test", testcmd },
8884 { BUILTIN_SPEC_REG "times", timescmd },
8885 { BUILTIN_SPEC_REG "trap", trapcmd },
8886 { BUILTIN_REGULAR "true", truecmd },
8887 { BUILTIN_NOSPEC "type", typecmd },
8888 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8889 { BUILTIN_REGULAR "umask", umaskcmd },
8890 #if ENABLE_ASH_ALIAS
8891 { BUILTIN_REGULAR "unalias", unaliascmd },
8893 { BUILTIN_SPEC_REG "unset", unsetcmd },
8894 { BUILTIN_REGULAR "wait", waitcmd },
8897 /* Should match the above table! */
8898 #define COMMANDCMD (builtintab + \
8900 1 * ENABLE_ASH_BUILTIN_TEST + \
8901 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8902 1 * ENABLE_ASH_ALIAS + \
8903 1 * ENABLE_ASH_JOB_CONTROL + \
8905 #define EXECCMD (builtintab + \
8907 1 * ENABLE_ASH_BUILTIN_TEST + \
8908 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8909 1 * ENABLE_ASH_ALIAS + \
8910 1 * ENABLE_ASH_JOB_CONTROL + \
8912 1 * ENABLE_ASH_CMDCMD + \
8914 ENABLE_ASH_BUILTIN_ECHO + \
8918 * Search the table of builtin commands.
8920 static struct builtincmd *
8921 find_builtin(const char *name)
8923 struct builtincmd *bp;
8926 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8933 * Execute a simple command.
8936 isassignment(const char *p)
8938 const char *q = endofname(p);
8943 static int FAST_FUNC
8944 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8946 /* Preserve exitstatus of a previous possible redirection
8947 * as POSIX mandates */
8948 return back_exitstatus;
8951 evalcommand(union node *cmd, int flags)
8953 static const struct builtincmd null_bltin = {
8954 "\0\0", bltincmd /* why three NULs? */
8956 struct stackmark smark;
8958 struct arglist arglist;
8959 struct arglist varlist;
8962 const struct strlist *sp;
8963 struct cmdentry cmdentry;
8970 struct builtincmd *bcmd;
8971 smallint cmd_is_exec;
8972 smallint pseudovarflag = 0;
8974 /* First expand the arguments. */
8975 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8976 setstackmark(&smark);
8977 back_exitstatus = 0;
8979 cmdentry.cmdtype = CMDBUILTIN;
8980 cmdentry.u.cmd = &null_bltin;
8981 varlist.lastp = &varlist.list;
8982 *varlist.lastp = NULL;
8983 arglist.lastp = &arglist.list;
8984 *arglist.lastp = NULL;
8987 if (cmd->ncmd.args) {
8988 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8989 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8992 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8993 struct strlist **spp;
8995 spp = arglist.lastp;
8996 if (pseudovarflag && isassignment(argp->narg.text))
8997 expandarg(argp, &arglist, EXP_VARTILDE);
8999 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9001 for (sp = *spp; sp; sp = sp->next)
9005 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9006 for (sp = arglist.list; sp; sp = sp->next) {
9007 TRACE(("evalcommand arg: %s\n", sp->text));
9008 *nargv++ = sp->text;
9013 if (iflag && funcnest == 0 && argc > 0)
9014 lastarg = nargv[-1];
9017 expredir(cmd->ncmd.redirect);
9018 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9021 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9022 struct strlist **spp;
9025 spp = varlist.lastp;
9026 expandarg(argp, &varlist, EXP_VARTILDE);
9029 * Modify the command lookup path, if a PATH= assignment
9033 if (varequal(p, path))
9037 /* Print the command if xflag is set. */
9040 const char *p = " %s";
9043 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9046 for (n = 0; n < 2; n++) {
9048 fdprintf(preverrout_fd, p, sp->text);
9056 safe_write(preverrout_fd, "\n", 1);
9062 /* Now locate the command. */
9064 const char *oldpath;
9065 int cmd_flag = DO_ERR;
9070 find_command(argv[0], &cmdentry, cmd_flag, path);
9071 if (cmdentry.cmdtype == CMDUNKNOWN) {
9077 /* implement bltin and command here */
9078 if (cmdentry.cmdtype != CMDBUILTIN)
9081 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9082 if (cmdentry.u.cmd == EXECCMD)
9084 #if ENABLE_ASH_CMDCMD
9085 if (cmdentry.u.cmd == COMMANDCMD) {
9087 nargv = parse_command_args(argv, &path);
9090 argc -= nargv - argv;
9092 cmd_flag |= DO_NOFUNC;
9100 /* We have a redirection error. */
9102 raise_exception(EXERROR);
9104 exitstatus = status;
9108 /* Execute the command. */
9109 switch (cmdentry.cmdtype) {
9112 #if ENABLE_FEATURE_SH_NOFORK
9113 /* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9114 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
9116 /* find_command() encodes applet_no as (-2 - applet_no) */
9117 int applet_no = (- cmdentry.u.index - 2);
9118 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9119 listsetvar(varlist.list, VEXPORT|VSTACK);
9120 /* run <applet>_main() */
9121 exitstatus = run_nofork_applet(applet_no, argv);
9126 /* Fork off a child process if necessary. */
9127 if (!(flags & EV_EXIT) || trap[0]) {
9129 jp = makejob(/*cmd,*/ 1);
9130 if (forkshell(jp, cmd, FORK_FG) != 0) {
9131 exitstatus = waitforjob(jp);
9133 TRACE(("forked child exited with %d\n", exitstatus));
9138 listsetvar(varlist.list, VEXPORT|VSTACK);
9139 shellexec(argv, path, cmdentry.u.index);
9143 cmdenviron = varlist.list;
9145 struct strlist *list = cmdenviron;
9147 if (spclbltin > 0 || argc == 0) {
9149 if (cmd_is_exec && argc > 1)
9152 listsetvar(list, i);
9154 /* Tight loop with builtins only:
9155 * "while kill -0 $child; do true; done"
9156 * will never exit even if $child died, unless we do this
9157 * to reap the zombie and make kill detect that it's gone: */
9158 dowait(DOWAIT_NONBLOCK, NULL);
9160 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9162 int i = exception_type;
9167 exit_status = 128 + SIGINT;
9169 exit_status = 128 + pending_sig;
9170 exitstatus = exit_status;
9171 if (i == EXINT || spclbltin > 0) {
9173 longjmp(exception_handler->loc, 1);
9180 listsetvar(varlist.list, 0);
9181 /* See above for the rationale */
9182 dowait(DOWAIT_NONBLOCK, NULL);
9183 if (evalfun(cmdentry.u.func, argc, argv, flags))
9189 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9191 /* dsl: I think this is intended to be used to support
9192 * '_' in 'vi' command mode during line editing...
9193 * However I implemented that within libedit itself.
9195 setvar("_", lastarg, 0);
9197 popstackmark(&smark);
9201 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9203 char *volatile savecmdname;
9204 struct jmploc *volatile savehandler;
9205 struct jmploc jmploc;
9208 savecmdname = commandname;
9209 i = setjmp(jmploc.loc);
9212 savehandler = exception_handler;
9213 exception_handler = &jmploc;
9214 commandname = argv[0];
9216 optptr = NULL; /* initialize nextopt */
9217 exitstatus = (*cmd->builtin)(argc, argv);
9218 flush_stdout_stderr();
9220 exitstatus |= ferror(stdout);
9222 commandname = savecmdname;
9223 exception_handler = savehandler;
9229 goodname(const char *p)
9231 return !*endofname(p);
9236 * Search for a command. This is called before we fork so that the
9237 * location of the command will be available in the parent as well as
9238 * the child. The check for "goodname" is an overly conservative
9239 * check that the name will not be subject to expansion.
9242 prehash(union node *n)
9244 struct cmdentry entry;
9246 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9247 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9251 /* ============ Builtin commands
9253 * Builtin commands whose functions are closely tied to evaluation
9254 * are implemented here.
9258 * Handle break and continue commands. Break, continue, and return are
9259 * all handled by setting the evalskip flag. The evaluation routines
9260 * above all check this flag, and if it is set they start skipping
9261 * commands rather than executing them. The variable skipcount is
9262 * the number of loops to break/continue, or the number of function
9263 * levels to return. (The latter is always 1.) It should probably
9264 * be an error to break out of more loops than exist, but it isn't
9265 * in the standard shell so we don't make it one here.
9267 static int FAST_FUNC
9268 breakcmd(int argc UNUSED_PARAM, char **argv)
9270 int n = argv[1] ? number(argv[1]) : 1;
9273 ash_msg_and_raise_error(msg_illnum, argv[1]);
9277 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9284 /* ============ input.c
9286 * This implements the input routines used by the parser.
9290 INPUT_PUSH_FILE = 1,
9291 INPUT_NOFILE_OK = 2,
9294 static smallint checkkwd;
9295 /* values of checkkwd variable */
9296 #define CHKALIAS 0x1
9301 * Push a string back onto the input at this current parsefile level.
9302 * We handle aliases this way.
9304 #if !ENABLE_ASH_ALIAS
9305 #define pushstring(s, ap) pushstring(s)
9308 pushstring(char *s, struct alias *ap)
9315 if (g_parsefile->strpush) {
9316 sp = ckzalloc(sizeof(*sp));
9317 sp->prev = g_parsefile->strpush;
9319 sp = &(g_parsefile->basestrpush);
9321 g_parsefile->strpush = sp;
9322 sp->prev_string = g_parsefile->next_to_pgetc;
9323 sp->prev_left_in_line = g_parsefile->left_in_line;
9324 #if ENABLE_ASH_ALIAS
9327 ap->flag |= ALIASINUSE;
9331 g_parsefile->next_to_pgetc = s;
9332 g_parsefile->left_in_line = len;
9339 struct strpush *sp = g_parsefile->strpush;
9342 #if ENABLE_ASH_ALIAS
9344 if (g_parsefile->next_to_pgetc[-1] == ' '
9345 || g_parsefile->next_to_pgetc[-1] == '\t'
9347 checkkwd |= CHKALIAS;
9349 if (sp->string != sp->ap->val) {
9352 sp->ap->flag &= ~ALIASINUSE;
9353 if (sp->ap->flag & ALIASDEAD) {
9354 unalias(sp->ap->name);
9358 g_parsefile->next_to_pgetc = sp->prev_string;
9359 g_parsefile->left_in_line = sp->prev_left_in_line;
9360 g_parsefile->strpush = sp->prev;
9361 if (sp != &(g_parsefile->basestrpush))
9366 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9367 //it peeks whether it is &>, and then pushes back both chars.
9368 //This function needs to save last *next_to_pgetc to buf[0]
9369 //to make two pungetc() reliable. Currently,
9370 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9375 char *buf = g_parsefile->buf;
9377 g_parsefile->next_to_pgetc = buf;
9378 #if ENABLE_FEATURE_EDITING
9380 if (!iflag || g_parsefile->fd != STDIN_FILENO)
9381 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9383 #if ENABLE_FEATURE_TAB_COMPLETION
9384 line_input_state->path_lookup = pathval();
9386 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9388 /* Ctrl+C pressed */
9397 if (nr < 0 && errno == 0) {
9398 /* Ctrl+D pressed */
9403 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9407 /* nonblock_safe_read() handles this problem */
9409 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9410 int flags = fcntl(0, F_GETFL);
9411 if (flags >= 0 && (flags & O_NONBLOCK)) {
9412 flags &= ~O_NONBLOCK;
9413 if (fcntl(0, F_SETFL, flags) >= 0) {
9414 out2str("sh: turning off NDELAY mode\n");
9425 * Refill the input buffer and return the next input character:
9427 * 1) If a string was pushed back on the input, pop it;
9428 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9429 * or we are reading from a string so we can't refill the buffer,
9431 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9432 * 4) Process input up to the next newline, deleting nul characters.
9434 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9435 #define pgetc_debug(...) ((void)0)
9437 * NB: due to SIT(c) internals (syntax_index_table[] vector),
9438 * pgetc() and related functions must return chars SIGN-EXTENDED into ints,
9439 * not zero-extended. Seems fragile to me. Affects only !USE_SIT_FUNCTION case,
9440 * so we can fix it by ditching !USE_SIT_FUNCTION if Unicode requires that.
9448 while (g_parsefile->strpush) {
9449 #if ENABLE_ASH_ALIAS
9450 if (g_parsefile->left_in_line == -1
9451 && g_parsefile->strpush->ap
9452 && g_parsefile->next_to_pgetc[-1] != ' '
9453 && g_parsefile->next_to_pgetc[-1] != '\t'
9455 pgetc_debug("preadbuffer PEOA");
9460 /* try "pgetc" now: */
9461 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9462 g_parsefile->left_in_line,
9463 g_parsefile->next_to_pgetc,
9464 g_parsefile->next_to_pgetc);
9465 if (--g_parsefile->left_in_line >= 0)
9466 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9468 /* on both branches above g_parsefile->left_in_line < 0.
9469 * "pgetc" needs refilling.
9472 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9473 * pungetc() may increment it a few times.
9474 * Assuming it won't increment it to less than -90.
9476 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9477 pgetc_debug("preadbuffer PEOF1");
9478 /* even in failure keep left_in_line and next_to_pgetc
9479 * in lock step, for correct multi-layer pungetc.
9480 * left_in_line was decremented before preadbuffer(),
9481 * must inc next_to_pgetc: */
9482 g_parsefile->next_to_pgetc++;
9486 more = g_parsefile->left_in_buffer;
9488 flush_stdout_stderr();
9492 /* don't try reading again */
9493 g_parsefile->left_in_line = -99;
9494 pgetc_debug("preadbuffer PEOF2");
9495 g_parsefile->next_to_pgetc++;
9500 /* Find out where's the end of line.
9501 * Set g_parsefile->left_in_line
9502 * and g_parsefile->left_in_buffer acordingly.
9503 * NUL chars are deleted.
9505 q = g_parsefile->next_to_pgetc;
9513 memmove(q, q + 1, more);
9517 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9523 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9524 if (g_parsefile->left_in_line < 0)
9529 g_parsefile->left_in_buffer = more;
9534 out2str(g_parsefile->next_to_pgetc);
9538 pgetc_debug("preadbuffer at %d:%p'%s'",
9539 g_parsefile->left_in_line,
9540 g_parsefile->next_to_pgetc,
9541 g_parsefile->next_to_pgetc);
9542 return signed_char2int(*g_parsefile->next_to_pgetc++);
9545 #define pgetc_as_macro() \
9546 (--g_parsefile->left_in_line >= 0 \
9547 ? signed_char2int(*g_parsefile->next_to_pgetc++) \
9554 pgetc_debug("pgetc_fast at %d:%p'%s'",
9555 g_parsefile->left_in_line,
9556 g_parsefile->next_to_pgetc,
9557 g_parsefile->next_to_pgetc);
9558 return pgetc_as_macro();
9561 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9562 #define pgetc_fast() pgetc()
9564 #define pgetc_fast() pgetc_as_macro()
9568 * Same as pgetc(), but ignores PEOA.
9570 #if ENABLE_ASH_ALIAS
9576 pgetc_debug("pgetc_fast at %d:%p'%s'",
9577 g_parsefile->left_in_line,
9578 g_parsefile->next_to_pgetc,
9579 g_parsefile->next_to_pgetc);
9581 } while (c == PEOA);
9585 #define pgetc2() pgetc()
9589 * Read a line from the script.
9592 pfgets(char *line, int len)
9598 while (--nleft > 0) {
9614 * Undo the last call to pgetc. Only one character may be pushed back.
9615 * PEOF may be pushed back.
9620 g_parsefile->left_in_line++;
9621 g_parsefile->next_to_pgetc--;
9622 pgetc_debug("pushed back to %d:%p'%s'",
9623 g_parsefile->left_in_line,
9624 g_parsefile->next_to_pgetc,
9625 g_parsefile->next_to_pgetc);
9629 * To handle the "." command, a stack of input files is used. Pushfile
9630 * adds a new entry to the stack and popfile restores the previous level.
9635 struct parsefile *pf;
9637 pf = ckzalloc(sizeof(*pf));
9638 pf->prev = g_parsefile;
9640 /*pf->strpush = NULL; - ckzalloc did it */
9641 /*pf->basestrpush.prev = NULL;*/
9648 struct parsefile *pf = g_parsefile;
9656 g_parsefile = pf->prev;
9662 * Return to top level.
9667 while (g_parsefile != &basepf)
9672 * Close the file(s) that the shell is reading commands from. Called
9673 * after a fork is done.
9679 if (g_parsefile->fd > 0) {
9680 close(g_parsefile->fd);
9681 g_parsefile->fd = 0;
9686 * Like setinputfile, but takes an open file descriptor. Call this with
9690 setinputfd(int fd, int push)
9692 close_on_exec_on(fd);
9695 g_parsefile->buf = NULL;
9697 g_parsefile->fd = fd;
9698 if (g_parsefile->buf == NULL)
9699 g_parsefile->buf = ckmalloc(IBUFSIZ);
9700 g_parsefile->left_in_buffer = 0;
9701 g_parsefile->left_in_line = 0;
9702 g_parsefile->linno = 1;
9706 * Set the input to take input from a file. If push is set, push the
9707 * old input onto the stack first.
9710 setinputfile(const char *fname, int flags)
9716 fd = open(fname, O_RDONLY);
9718 if (flags & INPUT_NOFILE_OK)
9720 ash_msg_and_raise_error("can't open '%s'", fname);
9723 fd2 = copyfd(fd, 10);
9726 ash_msg_and_raise_error("out of file descriptors");
9729 setinputfd(fd, flags & INPUT_PUSH_FILE);
9736 * Like setinputfile, but takes input from a string.
9739 setinputstring(char *string)
9743 g_parsefile->next_to_pgetc = string;
9744 g_parsefile->left_in_line = strlen(string);
9745 g_parsefile->buf = NULL;
9746 g_parsefile->linno = 1;
9751 /* ============ mail.c
9753 * Routines to check for mail.
9758 #define MAXMBOXES 10
9760 /* times of mailboxes */
9761 static time_t mailtime[MAXMBOXES];
9762 /* Set if MAIL or MAILPATH is changed. */
9763 static smallint mail_var_path_changed;
9766 * Print appropriate message(s) if mail has arrived.
9767 * If mail_var_path_changed is set,
9768 * then the value of MAIL has mail_var_path_changed,
9769 * so we just update the values.
9778 struct stackmark smark;
9781 setstackmark(&smark);
9782 mpath = mpathset() ? mpathval() : mailval();
9783 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9784 p = path_advance(&mpath, nullstr);
9789 for (q = p; *q; q++)
9795 q[-1] = '\0'; /* delete trailing '/' */
9796 if (stat(p, &statb) < 0) {
9800 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9803 pathopt ? pathopt : "you have mail"
9806 *mtp = statb.st_mtime;
9808 mail_var_path_changed = 0;
9809 popstackmark(&smark);
9812 static void FAST_FUNC
9813 changemail(const char *val UNUSED_PARAM)
9815 mail_var_path_changed = 1;
9818 #endif /* ASH_MAIL */
9821 /* ============ ??? */
9824 * Set the shell parameters.
9827 setparam(char **argv)
9833 for (nparam = 0; argv[nparam]; nparam++)
9835 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9837 *ap++ = ckstrdup(*argv++);
9840 freeparam(&shellparam);
9841 shellparam.malloced = 1;
9842 shellparam.nparam = nparam;
9843 shellparam.p = newparam;
9844 #if ENABLE_ASH_GETOPTS
9845 shellparam.optind = 1;
9846 shellparam.optoff = -1;
9851 * Process shell options. The global variable argptr contains a pointer
9852 * to the argument list; we advance it past the options.
9854 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9855 * For a non-interactive shell, an error condition encountered
9856 * by a special built-in ... shall cause the shell to write a diagnostic message
9857 * to standard error and exit as shown in the following table:
9858 * Error Special Built-In
9860 * Utility syntax error (option or operand error) Shall exit
9862 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9863 * we see that bash does not do that (set "finishes" with error code 1 instead,
9864 * and shell continues), and people rely on this behavior!
9866 * set -o barfoo 2>/dev/null
9869 * Oh well. Let's mimic that.
9872 plus_minus_o(char *name, int val)
9877 for (i = 0; i < NOPTS; i++) {
9878 if (strcmp(name, optnames(i)) == 0) {
9883 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9886 for (i = 0; i < NOPTS; i++) {
9888 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9890 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9896 setoption(int flag, int val)
9900 for (i = 0; i < NOPTS; i++) {
9901 if (optletters(i) == flag) {
9906 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9910 options(int cmdline)
9918 while ((p = *argptr) != NULL) {
9920 if (c != '-' && c != '+')
9923 val = 0; /* val = 0 if c == '+' */
9926 if (p[0] == '\0' || LONE_DASH(p)) {
9928 /* "-" means turn off -x and -v */
9931 /* "--" means reset params */
9932 else if (*argptr == NULL)
9935 break; /* "-" or "--" terminates options */
9938 /* first char was + or - */
9939 while ((c = *p++) != '\0') {
9940 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9941 if (c == 'c' && cmdline) {
9942 minusc = p; /* command is after shell args */
9943 } else if (c == 'o') {
9944 if (plus_minus_o(*argptr, val)) {
9945 /* it already printed err message */
9946 return 1; /* error */
9950 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9952 /* bash does not accept +-login, we also won't */
9953 } else if (cmdline && val && (c == '-')) { /* long options */
9954 if (strcmp(p, "login") == 0)
9966 * The shift builtin command.
9968 static int FAST_FUNC
9969 shiftcmd(int argc UNUSED_PARAM, char **argv)
9976 n = number(argv[1]);
9977 if (n > shellparam.nparam)
9978 n = 0; /* bash compat, was = shellparam.nparam; */
9980 shellparam.nparam -= n;
9981 for (ap1 = shellparam.p; --n >= 0; ap1++) {
9982 if (shellparam.malloced)
9986 while ((*ap2++ = *ap1++) != NULL)
9988 #if ENABLE_ASH_GETOPTS
9989 shellparam.optind = 1;
9990 shellparam.optoff = -1;
9997 * POSIX requires that 'set' (but not export or readonly) output the
9998 * variables in lexicographic order - by the locale's collating order (sigh).
9999 * Maybe we could keep them in an ordered balanced binary tree
10000 * instead of hashed lists.
10001 * For now just roll 'em through qsort for printing...
10004 showvars(const char *sep_prefix, int on, int off)
10007 char **ep, **epend;
10009 ep = listvars(on, off, &epend);
10010 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10012 sep = *sep_prefix ? " " : sep_prefix;
10014 for (; ep < epend; ep++) {
10018 p = strchrnul(*ep, '=');
10021 q = single_quote(++p);
10022 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10028 * The set command builtin.
10030 static int FAST_FUNC
10031 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10036 return showvars(nullstr, 0, VUNSET);
10039 if (!options(0)) { /* if no parse error... */
10042 if (*argptr != NULL) {
10050 #if ENABLE_ASH_RANDOM_SUPPORT
10051 static void FAST_FUNC
10052 change_random(const char *value)
10054 /* Galois LFSR parameter */
10055 /* Taps at 32 31 29 1: */
10056 enum { MASK = 0x8000000b };
10057 /* Another example - taps at 32 31 30 10: */
10058 /* MASK = 0x00400007 */
10060 if (value == NULL) {
10061 /* "get", generate */
10064 /* LCG has period of 2^32 and alternating lowest bit */
10065 random_LCG = 1664525 * random_LCG + 1013904223;
10066 /* Galois LFSR has period of 2^32-1 = 3 * 5 * 17 * 257 * 65537 */
10067 t = (random_galois_LFSR << 1);
10068 if (random_galois_LFSR < 0) /* if we just shifted 1 out of msb... */
10070 random_galois_LFSR = t;
10071 /* Both are weak, combining them gives better randomness
10072 * and ~2^64 period. & 0x7fff is probably bash compat
10073 * for $RANDOM range. Combining with subtraction is
10074 * just for fun. + and ^ would work equally well. */
10075 t = (t - random_LCG) & 0x7fff;
10076 /* set without recursion */
10077 setvar(vrandom.text, utoa(t), VNOFUNC);
10078 vrandom.flags &= ~VNOFUNC;
10081 random_galois_LFSR = random_LCG = strtoul(value, (char **)NULL, 10);
10086 #if ENABLE_ASH_GETOPTS
10088 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10097 if (*param_optind < 1)
10099 optnext = optfirst + *param_optind - 1;
10101 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10104 p = optnext[-1] + *optoff;
10105 if (p == NULL || *p == '\0') {
10106 /* Current word is done, advance */
10108 if (p == NULL || *p != '-' || *++p == '\0') {
10115 if (LONE_DASH(p)) /* check for "--" */
10120 for (q = optstr; *q != c;) {
10122 if (optstr[0] == ':') {
10125 err |= setvarsafe("OPTARG", s, 0);
10127 fprintf(stderr, "Illegal option -%c\n", c);
10128 unsetvar("OPTARG");
10138 if (*p == '\0' && (p = *optnext) == NULL) {
10139 if (optstr[0] == ':') {
10142 err |= setvarsafe("OPTARG", s, 0);
10145 fprintf(stderr, "No arg for -%c option\n", c);
10146 unsetvar("OPTARG");
10154 err |= setvarsafe("OPTARG", p, 0);
10157 err |= setvarsafe("OPTARG", nullstr, 0);
10159 *optoff = p ? p - *(optnext - 1) : -1;
10160 *param_optind = optnext - optfirst + 1;
10161 fmtstr(s, sizeof(s), "%d", *param_optind);
10162 err |= setvarsafe("OPTIND", s, VNOFUNC);
10165 err |= setvarsafe(optvar, s, 0);
10169 flush_stdout_stderr();
10170 raise_exception(EXERROR);
10176 * The getopts builtin. Shellparam.optnext points to the next argument
10177 * to be processed. Shellparam.optptr points to the next character to
10178 * be processed in the current argument. If shellparam.optnext is NULL,
10179 * then it's the first time getopts has been called.
10181 static int FAST_FUNC
10182 getoptscmd(int argc, char **argv)
10187 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10189 optbase = shellparam.p;
10190 if (shellparam.optind > shellparam.nparam + 1) {
10191 shellparam.optind = 1;
10192 shellparam.optoff = -1;
10195 optbase = &argv[3];
10196 if (shellparam.optind > argc - 2) {
10197 shellparam.optind = 1;
10198 shellparam.optoff = -1;
10202 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10203 &shellparam.optoff);
10205 #endif /* ASH_GETOPTS */
10208 /* ============ Shell parser */
10211 struct heredoc *next; /* next here document in list */
10212 union node *here; /* redirection node */
10213 char *eofmark; /* string indicating end of input */
10214 smallint striptabs; /* if set, strip leading tabs */
10217 static smallint tokpushback; /* last token pushed back */
10218 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10219 static smallint quoteflag; /* set if (part of) last token was quoted */
10220 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10221 static struct heredoc *heredoclist; /* list of here documents to read */
10222 static char *wordtext; /* text of last word returned by readtoken */
10223 static struct nodelist *backquotelist;
10224 static union node *redirnode;
10225 static struct heredoc *heredoc;
10228 * Called when an unexpected token is read during the parse. The argument
10229 * is the token that is expected, or -1 if more than one type of token can
10230 * occur at this point.
10232 static void raise_error_unexpected_syntax(int) NORETURN;
10234 raise_error_unexpected_syntax(int token)
10239 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
10241 sprintf(msg + l, " (expecting %s)", tokname(token));
10242 raise_error_syntax(msg);
10246 #define EOFMARKLEN 79
10248 /* parsing is heavily cross-recursive, need these forward decls */
10249 static union node *andor(void);
10250 static union node *pipeline(void);
10251 static union node *parse_command(void);
10252 static void parseheredoc(void);
10253 static char peektoken(void);
10254 static int readtoken(void);
10256 static union node *
10259 union node *n1, *n2, *n3;
10262 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10263 if (nlflag == 2 && peektoken())
10269 if (tok == TBACKGND) {
10270 if (n2->type == NPIPE) {
10271 n2->npipe.pipe_backgnd = 1;
10273 if (n2->type != NREDIR) {
10274 n3 = stzalloc(sizeof(struct nredir));
10276 /*n3->nredir.redirect = NULL; - stzalloc did it */
10279 n2->type = NBACKGND;
10285 n3 = stzalloc(sizeof(struct nbinary));
10287 n3->nbinary.ch1 = n1;
10288 n3->nbinary.ch2 = n2;
10304 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10312 pungetc(); /* push back EOF on input */
10316 raise_error_unexpected_syntax(-1);
10323 static union node *
10326 union node *n1, *n2, *n3;
10334 } else if (t == TOR) {
10340 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10342 n3 = stzalloc(sizeof(struct nbinary));
10344 n3->nbinary.ch1 = n1;
10345 n3->nbinary.ch2 = n2;
10350 static union node *
10353 union node *n1, *n2, *pipenode;
10354 struct nodelist *lp, *prev;
10358 TRACE(("pipeline: entered\n"));
10359 if (readtoken() == TNOT) {
10361 checkkwd = CHKKWD | CHKALIAS;
10364 n1 = parse_command();
10365 if (readtoken() == TPIPE) {
10366 pipenode = stzalloc(sizeof(struct npipe));
10367 pipenode->type = NPIPE;
10368 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10369 lp = stzalloc(sizeof(struct nodelist));
10370 pipenode->npipe.cmdlist = lp;
10374 lp = stzalloc(sizeof(struct nodelist));
10375 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10376 lp->n = parse_command();
10378 } while (readtoken() == TPIPE);
10384 n2 = stzalloc(sizeof(struct nnot));
10392 static union node *
10397 n = stzalloc(sizeof(struct narg));
10399 /*n->narg.next = NULL; - stzalloc did it */
10400 n->narg.text = wordtext;
10401 n->narg.backquote = backquotelist;
10406 fixredir(union node *n, const char *text, int err)
10410 TRACE(("Fix redir %s %d\n", text, err));
10412 n->ndup.vname = NULL;
10414 fd = bb_strtou(text, NULL, 10);
10415 if (!errno && fd >= 0)
10416 n->ndup.dupfd = fd;
10417 else if (LONE_DASH(text))
10418 n->ndup.dupfd = -1;
10421 raise_error_syntax("bad fd number");
10422 n->ndup.vname = makename();
10427 * Returns true if the text contains nothing to expand (no dollar signs
10431 noexpand(const char *text)
10437 while ((c = *p++) != '\0') {
10438 if (c == CTLQUOTEMARK)
10442 else if (SIT((signed char)c, BASESYNTAX) == CCTL)
10451 union node *n = redirnode;
10453 if (readtoken() != TWORD)
10454 raise_error_unexpected_syntax(-1);
10455 if (n->type == NHERE) {
10456 struct heredoc *here = heredoc;
10460 if (quoteflag == 0)
10462 TRACE(("Here document %d\n", n->type));
10463 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10464 raise_error_syntax("illegal eof marker for << redirection");
10465 rmescapes(wordtext, 0);
10466 here->eofmark = wordtext;
10468 if (heredoclist == NULL)
10469 heredoclist = here;
10471 for (p = heredoclist; p->next; p = p->next)
10475 } else if (n->type == NTOFD || n->type == NFROMFD) {
10476 fixredir(n, wordtext, 0);
10478 n->nfile.fname = makename();
10482 static union node *
10485 union node *args, **app;
10486 union node *n = NULL;
10487 union node *vars, **vpp;
10488 union node **rpp, *redir;
10490 #if ENABLE_ASH_BASH_COMPAT
10491 smallint double_brackets_flag = 0;
10501 savecheckkwd = CHKALIAS;
10504 checkkwd = savecheckkwd;
10507 #if ENABLE_ASH_BASH_COMPAT
10508 case TAND: /* "&&" */
10509 case TOR: /* "||" */
10510 if (!double_brackets_flag) {
10514 wordtext = (char *) (t == TAND ? "-a" : "-o");
10517 n = stzalloc(sizeof(struct narg));
10519 /*n->narg.next = NULL; - stzalloc did it */
10520 n->narg.text = wordtext;
10521 #if ENABLE_ASH_BASH_COMPAT
10522 if (strcmp("[[", wordtext) == 0)
10523 double_brackets_flag = 1;
10524 else if (strcmp("]]", wordtext) == 0)
10525 double_brackets_flag = 0;
10527 n->narg.backquote = backquotelist;
10528 if (savecheckkwd && isassignment(wordtext)) {
10530 vpp = &n->narg.next;
10533 app = &n->narg.next;
10538 *rpp = n = redirnode;
10539 rpp = &n->nfile.next;
10540 parsefname(); /* read name of redirection file */
10543 if (args && app == &args->narg.next
10546 struct builtincmd *bcmd;
10549 /* We have a function */
10550 if (readtoken() != TRP)
10551 raise_error_unexpected_syntax(TRP);
10552 name = n->narg.text;
10553 if (!goodname(name)
10554 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10556 raise_error_syntax("bad function name");
10559 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10560 n->narg.next = parse_command();
10573 n = stzalloc(sizeof(struct ncmd));
10575 n->ncmd.args = args;
10576 n->ncmd.assign = vars;
10577 n->ncmd.redirect = redir;
10581 static union node *
10582 parse_command(void)
10584 union node *n1, *n2;
10585 union node *ap, **app;
10586 union node *cp, **cpp;
10587 union node *redir, **rpp;
10594 switch (readtoken()) {
10596 raise_error_unexpected_syntax(-1);
10599 n1 = stzalloc(sizeof(struct nif));
10601 n1->nif.test = list(0);
10602 if (readtoken() != TTHEN)
10603 raise_error_unexpected_syntax(TTHEN);
10604 n1->nif.ifpart = list(0);
10606 while (readtoken() == TELIF) {
10607 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10608 n2 = n2->nif.elsepart;
10610 n2->nif.test = list(0);
10611 if (readtoken() != TTHEN)
10612 raise_error_unexpected_syntax(TTHEN);
10613 n2->nif.ifpart = list(0);
10615 if (lasttoken == TELSE)
10616 n2->nif.elsepart = list(0);
10618 n2->nif.elsepart = NULL;
10626 n1 = stzalloc(sizeof(struct nbinary));
10627 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10628 n1->nbinary.ch1 = list(0);
10631 TRACE(("expecting DO got %s %s\n", tokname(got),
10632 got == TWORD ? wordtext : ""));
10633 raise_error_unexpected_syntax(TDO);
10635 n1->nbinary.ch2 = list(0);
10640 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10641 raise_error_syntax("bad for loop variable");
10642 n1 = stzalloc(sizeof(struct nfor));
10644 n1->nfor.var = wordtext;
10645 checkkwd = CHKKWD | CHKALIAS;
10646 if (readtoken() == TIN) {
10648 while (readtoken() == TWORD) {
10649 n2 = stzalloc(sizeof(struct narg));
10651 /*n2->narg.next = NULL; - stzalloc did it */
10652 n2->narg.text = wordtext;
10653 n2->narg.backquote = backquotelist;
10655 app = &n2->narg.next;
10658 n1->nfor.args = ap;
10659 if (lasttoken != TNL && lasttoken != TSEMI)
10660 raise_error_unexpected_syntax(-1);
10662 n2 = stzalloc(sizeof(struct narg));
10664 /*n2->narg.next = NULL; - stzalloc did it */
10665 n2->narg.text = (char *)dolatstr;
10666 /*n2->narg.backquote = NULL;*/
10667 n1->nfor.args = n2;
10669 * Newline or semicolon here is optional (but note
10670 * that the original Bourne shell only allowed NL).
10672 if (lasttoken != TNL && lasttoken != TSEMI)
10675 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10676 if (readtoken() != TDO)
10677 raise_error_unexpected_syntax(TDO);
10678 n1->nfor.body = list(0);
10682 n1 = stzalloc(sizeof(struct ncase));
10684 if (readtoken() != TWORD)
10685 raise_error_unexpected_syntax(TWORD);
10686 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10688 /*n2->narg.next = NULL; - stzalloc did it */
10689 n2->narg.text = wordtext;
10690 n2->narg.backquote = backquotelist;
10692 checkkwd = CHKKWD | CHKALIAS;
10693 } while (readtoken() == TNL);
10694 if (lasttoken != TIN)
10695 raise_error_unexpected_syntax(TIN);
10696 cpp = &n1->ncase.cases;
10698 checkkwd = CHKNL | CHKKWD;
10700 while (t != TESAC) {
10701 if (lasttoken == TLP)
10703 *cpp = cp = stzalloc(sizeof(struct nclist));
10705 app = &cp->nclist.pattern;
10707 *app = ap = stzalloc(sizeof(struct narg));
10709 /*ap->narg.next = NULL; - stzalloc did it */
10710 ap->narg.text = wordtext;
10711 ap->narg.backquote = backquotelist;
10712 if (readtoken() != TPIPE)
10714 app = &ap->narg.next;
10717 //ap->narg.next = NULL;
10718 if (lasttoken != TRP)
10719 raise_error_unexpected_syntax(TRP);
10720 cp->nclist.body = list(2);
10722 cpp = &cp->nclist.next;
10724 checkkwd = CHKNL | CHKKWD;
10728 raise_error_unexpected_syntax(TENDCASE);
10735 n1 = stzalloc(sizeof(struct nredir));
10736 n1->type = NSUBSHELL;
10737 n1->nredir.n = list(0);
10738 /*n1->nredir.redirect = NULL; - stzalloc did it */
10748 return simplecmd();
10751 if (readtoken() != t)
10752 raise_error_unexpected_syntax(t);
10755 /* Now check for redirection which may follow command */
10756 checkkwd = CHKKWD | CHKALIAS;
10758 while (readtoken() == TREDIR) {
10759 *rpp = n2 = redirnode;
10760 rpp = &n2->nfile.next;
10766 if (n1->type != NSUBSHELL) {
10767 n2 = stzalloc(sizeof(struct nredir));
10772 n1->nredir.redirect = redir;
10777 #if ENABLE_ASH_BASH_COMPAT
10778 static int decode_dollar_squote(void)
10780 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10786 p = strchr(C_escapes, c);
10791 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10795 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10797 } else if (c == 'x') { /* \xHH */
10801 } while (isxdigit(c) && --cnt);
10803 if (cnt == 3) { /* \x but next char is "bad" */
10807 } else { /* simple seq like \\ or \t */
10812 c = bb_process_escape_sequence((void*)&p);
10813 } else { /* unrecognized "\z": print both chars unless ' or " */
10814 if (c != '\'' && c != '"') {
10816 c |= 0x100; /* "please encode \, then me" */
10824 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10825 * is not NULL, read a here document. In the latter case, eofmark is the
10826 * word which marks the end of the document and striptabs is true if
10827 * leading tabs should be stripped from the document. The argument firstc
10828 * is the first character of the input token or document.
10830 * Because C does not have internal subroutines, I have simulated them
10831 * using goto's to implement the subroutine linkage. The following macros
10832 * will run code that appears at the end of readtoken1.
10834 #define CHECKEND() {goto checkend; checkend_return:;}
10835 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10836 #define PARSESUB() {goto parsesub; parsesub_return:;}
10837 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10838 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10839 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10841 readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
10843 /* NB: syntax parameter fits into smallint */
10847 char line[EOFMARKLEN + 1];
10848 struct nodelist *bqlist;
10852 smallint prevsyntax; /* syntax before arithmetic */
10853 #if ENABLE_ASH_EXPAND_PRMT
10854 smallint pssyntax; /* we are expanding a prompt string */
10856 int varnest; /* levels of variables expansion */
10857 int arinest; /* levels of arithmetic expansion */
10858 int parenlevel; /* levels of parens in arithmetic */
10859 int dqvarnest; /* levels of variables expansion within double quotes */
10861 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10864 /* Avoid longjmp clobbering */
10870 (void) &parenlevel;
10873 (void) &prevsyntax;
10876 startlinno = g_parsefile->linno;
10881 #if ENABLE_ASH_EXPAND_PRMT
10882 pssyntax = (syntax == PSSYNTAX);
10886 dblquote = (syntax == DQSYNTAX);
10892 STARTSTACKSTR(out);
10894 /* For each line, until end of word */
10896 CHECKEND(); /* set c to PEOF if at end of here document */
10897 for (;;) { /* until end of line or end of word */
10898 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10899 switch (SIT(c, syntax)) {
10900 case CNL: /* '\n' */
10901 if (syntax == BASESYNTAX)
10902 goto endword; /* exit outer loop */
10904 g_parsefile->linno++;
10908 goto loop; /* continue outer loop */
10913 if (eofmark == NULL || dblquote)
10914 USTPUTC(CTLESC, out);
10915 #if ENABLE_ASH_BASH_COMPAT
10916 if (c == '\\' && bash_dollar_squote) {
10917 c = decode_dollar_squote();
10919 USTPUTC('\\', out);
10920 c = (unsigned char)c;
10926 case CBACK: /* backslash */
10929 USTPUTC(CTLESC, out);
10930 USTPUTC('\\', out);
10932 } else if (c == '\n') {
10936 #if ENABLE_ASH_EXPAND_PRMT
10937 if (c == '$' && pssyntax) {
10938 USTPUTC(CTLESC, out);
10939 USTPUTC('\\', out);
10942 if (dblquote && c != '\\'
10943 && c != '`' && c != '$'
10944 && (c != '"' || eofmark != NULL)
10946 USTPUTC(CTLESC, out);
10947 USTPUTC('\\', out);
10949 if (SIT(c, SQSYNTAX) == CCTL)
10950 USTPUTC(CTLESC, out);
10958 if (eofmark == NULL) {
10959 USTPUTC(CTLQUOTEMARK, out);
10967 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
10968 if (eofmark != NULL && arinest == 0
10973 if (dqvarnest == 0) {
10974 syntax = BASESYNTAX;
10981 case CVAR: /* '$' */
10982 PARSESUB(); /* parse substitution */
10984 case CENDVAR: /* '}' */
10987 if (dqvarnest > 0) {
10990 USTPUTC(CTLENDVAR, out);
10995 #if ENABLE_SH_MATH_SUPPORT
10996 case CLP: /* '(' in arithmetic */
11000 case CRP: /* ')' in arithmetic */
11001 if (parenlevel > 0) {
11005 if (pgetc() == ')') {
11006 if (--arinest == 0) {
11007 USTPUTC(CTLENDARI, out);
11008 syntax = prevsyntax;
11009 dblquote = (syntax == DQSYNTAX);
11014 * unbalanced parens
11015 * (don't 2nd guess - no error)
11023 case CBQUOTE: /* '`' */
11027 goto endword; /* exit outer loop */
11031 if (varnest == 0) {
11032 #if ENABLE_ASH_BASH_COMPAT
11034 if (pgetc() == '>')
11035 c = 0x100 + '>'; /* flag &> */
11039 goto endword; /* exit outer loop */
11041 #if ENABLE_ASH_ALIAS
11051 #if ENABLE_SH_MATH_SUPPORT
11052 if (syntax == ARISYNTAX)
11053 raise_error_syntax("missing '))'");
11055 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11056 raise_error_syntax("unterminated quoted string");
11057 if (varnest != 0) {
11058 startlinno = g_parsefile->linno;
11060 raise_error_syntax("missing '}'");
11062 USTPUTC('\0', out);
11063 len = out - (char *)stackblock();
11064 out = stackblock();
11065 if (eofmark == NULL) {
11066 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11069 if (isdigit_str9(out)) {
11070 PARSEREDIR(); /* passed as params: out, c */
11071 lasttoken = TREDIR;
11074 /* else: non-number X seen, interpret it
11075 * as "NNNX>file" = "NNNX >file" */
11079 quoteflag = quotef;
11080 backquotelist = bqlist;
11081 grabstackblock(len);
11085 /* end of readtoken routine */
11088 * Check to see whether we are at the end of the here document. When this
11089 * is called, c is set to the first character of the next input line. If
11090 * we are at the end of the here document, this routine sets the c to PEOF.
11094 #if ENABLE_ASH_ALIAS
11100 while (c == '\t') {
11104 if (c == *eofmark) {
11105 if (pfgets(line, sizeof(line)) != NULL) {
11109 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11111 if (*p == '\n' && *q == '\0') {
11113 g_parsefile->linno++;
11114 needprompt = doprompt;
11116 pushstring(line, NULL);
11121 goto checkend_return;
11125 * Parse a redirection operator. The variable "out" points to a string
11126 * specifying the fd to be redirected. The variable "c" contains the
11127 * first character of the redirection operator.
11130 /* out is already checked to be a valid number or "" */
11131 int fd = (*out == '\0' ? -1 : atoi(out));
11134 np = stzalloc(sizeof(struct nfile));
11139 np->type = NAPPEND;
11141 np->type = NCLOBBER;
11144 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11150 #if ENABLE_ASH_BASH_COMPAT
11151 else if (c == 0x100 + '>') { /* this flags &> redirection */
11153 pgetc(); /* this is '>', no need to check */
11157 else { /* c == '<' */
11158 /*np->nfile.fd = 0; - stzalloc did it */
11162 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11163 np = stzalloc(sizeof(struct nhere));
11164 /*np->nfile.fd = 0; - stzalloc did it */
11167 heredoc = stzalloc(sizeof(struct heredoc));
11168 heredoc->here = np;
11171 heredoc->striptabs = 1;
11173 /*heredoc->striptabs = 0; - stzalloc did it */
11179 np->type = NFROMFD;
11183 np->type = NFROMTO;
11195 goto parseredir_return;
11199 * Parse a substitution. At this point, we have read the dollar sign
11200 * and nothing else.
11203 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11204 * (assuming ascii char codes, as the original implementation did) */
11205 #define is_special(c) \
11206 (((unsigned)(c) - 33 < 32) \
11207 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11213 static const char types[] ALIGN1 = "}-+?=";
11216 if (c <= PEOA_OR_PEOF
11217 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11219 #if ENABLE_ASH_BASH_COMPAT
11221 bash_dollar_squote = 1;
11226 } else if (c == '(') { /* $(command) or $((arith)) */
11227 if (pgetc() == '(') {
11228 #if ENABLE_SH_MATH_SUPPORT
11231 raise_error_syntax("you disabled math support for $((arith)) syntax");
11238 USTPUTC(CTLVAR, out);
11239 typeloc = out - (char *)stackblock();
11240 USTPUTC(VSNORMAL, out);
11241 subtype = VSNORMAL;
11249 subtype = VSLENGTH;
11253 if (c > PEOA_OR_PEOF && is_name(c)) {
11257 } while (c > PEOA_OR_PEOF && is_in_name(c));
11258 } else if (isdigit(c)) {
11262 } while (isdigit(c));
11263 } else if (is_special(c)) {
11268 raise_error_syntax("bad substitution");
11273 if (subtype == 0) {
11277 #if ENABLE_ASH_BASH_COMPAT
11278 if (c == ':' || c == '$' || isdigit(c)) {
11280 subtype = VSSUBSTR;
11287 p = strchr(types, c);
11290 subtype = p - types + VSNORMAL;
11295 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11303 #if ENABLE_ASH_BASH_COMPAT
11305 subtype = VSREPLACE;
11308 subtype++; /* VSREPLACEALL */
11317 if (dblquote || arinest)
11319 *((char *)stackblock() + typeloc) = subtype | flags;
11320 if (subtype != VSNORMAL) {
11322 if (dblquote || arinest) {
11327 goto parsesub_return;
11331 * Called to parse command substitutions. Newstyle is set if the command
11332 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11333 * list of commands (passed by reference), and savelen is the number of
11334 * characters on the top of the stack which must be preserved.
11337 struct nodelist **nlpp;
11340 char *volatile str;
11341 struct jmploc jmploc;
11342 struct jmploc *volatile savehandler;
11344 smallint saveprompt = 0;
11347 (void) &saveprompt;
11349 savepbq = parsebackquote;
11350 if (setjmp(jmploc.loc)) {
11352 parsebackquote = 0;
11353 exception_handler = savehandler;
11354 longjmp(exception_handler->loc, 1);
11358 savelen = out - (char *)stackblock();
11360 str = ckmalloc(savelen);
11361 memcpy(str, stackblock(), savelen);
11363 savehandler = exception_handler;
11364 exception_handler = &jmploc;
11367 /* We must read until the closing backquote, giving special
11368 treatment to some slashes, and then push the string and
11369 reread it as input, interpreting it normally. */
11376 STARTSTACKSTR(pout);
11389 g_parsefile->linno++;
11393 * If eating a newline, avoid putting
11394 * the newline into the new character
11395 * stream (via the STPUTC after the
11400 if (pc != '\\' && pc != '`' && pc != '$'
11401 && (!dblquote || pc != '"'))
11402 STPUTC('\\', pout);
11403 if (pc > PEOA_OR_PEOF) {
11409 #if ENABLE_ASH_ALIAS
11412 startlinno = g_parsefile->linno;
11413 raise_error_syntax("EOF in backquote substitution");
11416 g_parsefile->linno++;
11417 needprompt = doprompt;
11426 STPUTC('\0', pout);
11427 psavelen = pout - (char *)stackblock();
11428 if (psavelen > 0) {
11429 pstr = grabstackstr(pout);
11430 setinputstring(pstr);
11435 nlpp = &(*nlpp)->next;
11436 *nlpp = stzalloc(sizeof(**nlpp));
11437 /* (*nlpp)->next = NULL; - stzalloc did it */
11438 parsebackquote = oldstyle;
11441 saveprompt = doprompt;
11448 doprompt = saveprompt;
11449 else if (readtoken() != TRP)
11450 raise_error_unexpected_syntax(TRP);
11455 * Start reading from old file again, ignoring any pushed back
11456 * tokens left from the backquote parsing
11461 while (stackblocksize() <= savelen)
11463 STARTSTACKSTR(out);
11465 memcpy(out, str, savelen);
11466 STADJUST(savelen, out);
11472 parsebackquote = savepbq;
11473 exception_handler = savehandler;
11474 if (arinest || dblquote)
11475 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11477 USTPUTC(CTLBACKQ, out);
11479 goto parsebackq_oldreturn;
11480 goto parsebackq_newreturn;
11483 #if ENABLE_SH_MATH_SUPPORT
11485 * Parse an arithmetic expansion (indicate start of one and set state)
11488 if (++arinest == 1) {
11489 prevsyntax = syntax;
11490 syntax = ARISYNTAX;
11491 USTPUTC(CTLARI, out);
11498 * we collapse embedded arithmetic expansion to
11499 * parenthesis, which should be equivalent
11503 goto parsearith_return;
11507 } /* end of readtoken */
11510 * Read the next input token.
11511 * If the token is a word, we set backquotelist to the list of cmds in
11512 * backquotes. We set quoteflag to true if any part of the word was
11514 * If the token is TREDIR, then we set redirnode to a structure containing
11516 * In all cases, the variable startlinno is set to the number of the line
11517 * on which the token starts.
11519 * [Change comment: here documents and internal procedures]
11520 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11521 * word parsing code into a separate routine. In this case, readtoken
11522 * doesn't need to have any internal procedures, but parseword does.
11523 * We could also make parseoperator in essence the main routine, and
11524 * have parseword (readtoken1?) handle both words and redirection.]
11526 #define NEW_xxreadtoken
11527 #ifdef NEW_xxreadtoken
11528 /* singles must be first! */
11529 static const char xxreadtoken_chars[7] ALIGN1 = {
11530 '\n', '(', ')', /* singles */
11531 '&', '|', ';', /* doubles */
11535 #define xxreadtoken_singles 3
11536 #define xxreadtoken_doubles 3
11538 static const char xxreadtoken_tokens[] ALIGN1 = {
11539 TNL, TLP, TRP, /* only single occurrence allowed */
11540 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11541 TEOF, /* corresponds to trailing nul */
11542 TAND, TOR, TENDCASE /* if double occurrence */
11557 startlinno = g_parsefile->linno;
11558 for (;;) { /* until token or start of word found */
11560 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11564 while ((c = pgetc()) != '\n' && c != PEOF)
11567 } else if (c == '\\') {
11568 if (pgetc() != '\n') {
11570 break; /* return readtoken1(...) */
11572 startlinno = ++g_parsefile->linno;
11578 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11581 g_parsefile->linno++;
11582 needprompt = doprompt;
11585 p = strchr(xxreadtoken_chars, c);
11587 break; /* return readtoken1(...) */
11589 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11591 if (cc == c) { /* double occurrence? */
11592 p += xxreadtoken_doubles + 1;
11595 #if ENABLE_ASH_BASH_COMPAT
11596 if (c == '&' && cc == '>') /* &> */
11597 break; /* return readtoken1(...) */
11602 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11607 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11609 #else /* old xxreadtoken */
11610 #define RETURN(token) return lasttoken = token
11623 startlinno = g_parsefile->linno;
11624 for (;;) { /* until token or start of word found */
11627 case ' ': case '\t':
11628 #if ENABLE_ASH_ALIAS
11633 while ((c = pgetc()) != '\n' && c != PEOF)
11638 if (pgetc() == '\n') {
11639 startlinno = ++g_parsefile->linno;
11647 g_parsefile->linno++;
11648 needprompt = doprompt;
11653 if (pgetc() == '&')
11658 if (pgetc() == '|')
11663 if (pgetc() == ';')
11676 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11679 #endif /* old xxreadtoken */
11686 smallint alreadyseen = tokpushback;
11689 #if ENABLE_ASH_ALIAS
11698 if (checkkwd & CHKNL) {
11705 if (t != TWORD || quoteflag) {
11710 * check for keywords
11712 if (checkkwd & CHKKWD) {
11713 const char *const *pp;
11715 pp = findkwd(wordtext);
11717 lasttoken = t = pp - tokname_array;
11718 TRACE(("keyword %s recognized\n", tokname(t)));
11723 if (checkkwd & CHKALIAS) {
11724 #if ENABLE_ASH_ALIAS
11726 ap = lookupalias(wordtext, 1);
11729 pushstring(ap->val, ap);
11739 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11741 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11753 return tokname_array[t][0];
11757 * Read and parse a command. Returns NODE_EOF on end of file.
11758 * (NULL is a valid parse tree indicating a blank line.)
11760 static union node *
11761 parsecmd(int interact)
11766 doprompt = interact;
11768 setprompt(doprompt);
11780 * Input any here documents.
11785 struct heredoc *here;
11788 here = heredoclist;
11789 heredoclist = NULL;
11795 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11796 here->eofmark, here->striptabs);
11797 n = stzalloc(sizeof(struct narg));
11798 n->narg.type = NARG;
11799 /*n->narg.next = NULL; - stzalloc did it */
11800 n->narg.text = wordtext;
11801 n->narg.backquote = backquotelist;
11802 here->here->nhere.doc = n;
11809 * called by editline -- any expansions to the prompt should be added here.
11811 #if ENABLE_ASH_EXPAND_PRMT
11812 static const char *
11813 expandstr(const char *ps)
11817 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11818 * and token processing _can_ alter it (delete NULs etc). */
11819 setinputstring((char *)ps);
11820 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11823 n.narg.type = NARG;
11824 n.narg.next = NULL;
11825 n.narg.text = wordtext;
11826 n.narg.backquote = backquotelist;
11828 expandarg(&n, NULL, 0);
11829 return stackblock();
11834 * Execute a command or commands contained in a string.
11837 evalstring(char *s, int mask)
11840 struct stackmark smark;
11844 setstackmark(&smark);
11847 while ((n = parsecmd(0)) != NODE_EOF) {
11849 popstackmark(&smark);
11862 * The eval command.
11864 static int FAST_FUNC
11865 evalcmd(int argc UNUSED_PARAM, char **argv)
11874 STARTSTACKSTR(concat);
11876 concat = stack_putstr(p, concat);
11880 STPUTC(' ', concat);
11882 STPUTC('\0', concat);
11883 p = grabstackstr(concat);
11885 evalstring(p, ~SKIPEVAL);
11892 * Read and execute commands. "Top" is nonzero for the top level command
11893 * loop; it turns on prompting if the shell is interactive.
11899 struct stackmark smark;
11903 TRACE(("cmdloop(%d) called\n", top));
11907 setstackmark(&smark);
11910 showjobs(stderr, SHOW_CHANGED);
11913 if (iflag && top) {
11915 #if ENABLE_ASH_MAIL
11919 n = parsecmd(inter);
11921 if (DEBUG > 2 && debug && (n != NODE_EOF))
11924 if (n == NODE_EOF) {
11925 if (!top || numeof >= 50)
11927 if (!stoppedjobs()) {
11930 out2str("\nUse \"exit\" to leave shell.\n");
11933 } else if (nflag == 0) {
11934 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11939 popstackmark(&smark);
11944 return skip & SKIPEVAL;
11951 * Take commands from a file. To be compatible we should do a path
11952 * search for the file, which is necessary to find sub-commands.
11955 find_dot_file(char *name)
11958 const char *path = pathval();
11961 /* don't try this for absolute or relative paths */
11962 if (strchr(name, '/'))
11965 /* IIRC standards do not say whether . is to be searched.
11966 * And it is even smaller this way, making it unconditional for now:
11968 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11973 while ((fullname = path_advance(&path, name)) != NULL) {
11975 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11977 * Don't bother freeing here, since it will
11978 * be freed by the caller.
11982 if (fullname != name)
11983 stunalloc(fullname);
11986 /* not found in the PATH */
11987 ash_msg_and_raise_error("%s: not found", name);
11991 static int FAST_FUNC
11992 dotcmd(int argc, char **argv)
11994 struct strlist *sp;
11995 volatile struct shparam saveparam;
11998 for (sp = cmdenviron; sp; sp = sp->next)
11999 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12001 if (argv[1]) { /* That's what SVR2 does */
12002 char *fullname = find_dot_file(argv[1]);
12005 if (argc) { /* argc > 0, argv[0] != NULL */
12006 saveparam = shellparam;
12007 shellparam.malloced = 0;
12008 shellparam.nparam = argc;
12009 shellparam.p = argv;
12012 setinputfile(fullname, INPUT_PUSH_FILE);
12013 commandname = fullname;
12018 freeparam(&shellparam);
12019 shellparam = saveparam;
12021 status = exitstatus;
12026 static int FAST_FUNC
12027 exitcmd(int argc UNUSED_PARAM, char **argv)
12032 exitstatus = number(argv[1]);
12033 raise_exception(EXEXIT);
12038 * Read a file containing shell functions.
12041 readcmdfile(char *name)
12043 setinputfile(name, INPUT_PUSH_FILE);
12049 /* ============ find_command inplementation */
12052 * Resolve a command name. If you change this routine, you may have to
12053 * change the shellexec routine as well.
12056 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12058 struct tblentry *cmdp;
12065 struct builtincmd *bcmd;
12067 /* If name contains a slash, don't use PATH or hash table */
12068 if (strchr(name, '/') != NULL) {
12069 entry->u.index = -1;
12070 if (act & DO_ABS) {
12071 while (stat(name, &statb) < 0) {
12073 if (errno == EINTR)
12076 entry->cmdtype = CMDUNKNOWN;
12080 entry->cmdtype = CMDNORMAL;
12084 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12086 updatetbl = (path == pathval());
12089 if (strstr(path, "%builtin") != NULL)
12090 act |= DO_ALTBLTIN;
12093 /* If name is in the table, check answer will be ok */
12094 cmdp = cmdlookup(name, 0);
12095 if (cmdp != NULL) {
12098 switch (cmdp->cmdtype) {
12116 } else if (cmdp->rehash == 0)
12117 /* if not invalidated by cd, we're done */
12121 /* If %builtin not in path, check for builtin next */
12122 bcmd = find_builtin(name);
12124 if (IS_BUILTIN_REGULAR(bcmd))
12125 goto builtin_success;
12126 if (act & DO_ALTPATH) {
12127 if (!(act & DO_ALTBLTIN))
12128 goto builtin_success;
12129 } else if (builtinloc <= 0) {
12130 goto builtin_success;
12134 #if ENABLE_FEATURE_SH_STANDALONE
12136 int applet_no = find_applet_by_name(name);
12137 if (applet_no >= 0) {
12138 entry->cmdtype = CMDNORMAL;
12139 entry->u.index = -2 - applet_no;
12145 /* We have to search path. */
12146 prev = -1; /* where to start */
12147 if (cmdp && cmdp->rehash) { /* doing a rehash */
12148 if (cmdp->cmdtype == CMDBUILTIN)
12151 prev = cmdp->param.index;
12157 while ((fullname = path_advance(&path, name)) != NULL) {
12158 stunalloc(fullname);
12159 /* NB: code below will still use fullname
12160 * despite it being "unallocated" */
12163 if (prefix(pathopt, "builtin")) {
12165 goto builtin_success;
12168 if ((act & DO_NOFUNC)
12169 || !prefix(pathopt, "func")
12170 ) { /* ignore unimplemented options */
12174 /* if rehash, don't redo absolute path names */
12175 if (fullname[0] == '/' && idx <= prev) {
12178 TRACE(("searchexec \"%s\": no change\n", name));
12181 while (stat(fullname, &statb) < 0) {
12183 if (errno == EINTR)
12186 if (errno != ENOENT && errno != ENOTDIR)
12190 e = EACCES; /* if we fail, this will be the error */
12191 if (!S_ISREG(statb.st_mode))
12193 if (pathopt) { /* this is a %func directory */
12194 stalloc(strlen(fullname) + 1);
12195 /* NB: stalloc will return space pointed by fullname
12196 * (because we don't have any intervening allocations
12197 * between stunalloc above and this stalloc) */
12198 readcmdfile(fullname);
12199 cmdp = cmdlookup(name, 0);
12200 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12201 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12202 stunalloc(fullname);
12205 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12207 entry->cmdtype = CMDNORMAL;
12208 entry->u.index = idx;
12212 cmdp = cmdlookup(name, 1);
12213 cmdp->cmdtype = CMDNORMAL;
12214 cmdp->param.index = idx;
12219 /* We failed. If there was an entry for this command, delete it */
12220 if (cmdp && updatetbl)
12221 delete_cmd_entry();
12223 ash_msg("%s: %s", name, errmsg(e, "not found"));
12224 entry->cmdtype = CMDUNKNOWN;
12229 entry->cmdtype = CMDBUILTIN;
12230 entry->u.cmd = bcmd;
12234 cmdp = cmdlookup(name, 1);
12235 cmdp->cmdtype = CMDBUILTIN;
12236 cmdp->param.cmd = bcmd;
12240 entry->cmdtype = cmdp->cmdtype;
12241 entry->u = cmdp->param;
12245 /* ============ trap.c */
12248 * The trap builtin.
12250 static int FAST_FUNC
12251 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12260 for (signo = 0; signo < NSIG; signo++) {
12261 if (trap[signo] != NULL) {
12262 out1fmt("trap -- %s SIG%s\n",
12263 single_quote(trap[signo]),
12264 get_signame(signo));
12273 signo = get_signum(*ap);
12275 ash_msg_and_raise_error("%s: bad trap", *ap);
12278 if (LONE_DASH(action))
12281 action = ckstrdup(action);
12284 trap[signo] = action;
12294 /* ============ Builtins */
12296 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12298 * Lists available builtins
12300 static int FAST_FUNC
12301 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12307 "Built-in commands:\n"
12308 "------------------\n");
12309 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12310 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12311 builtintab[i].name + 1);
12317 #if ENABLE_FEATURE_SH_STANDALONE
12319 const char *a = applet_names;
12321 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12326 a += strlen(a) + 1;
12331 return EXIT_SUCCESS;
12333 #endif /* FEATURE_SH_EXTRA_QUIET */
12336 * The export and readonly commands.
12338 static int FAST_FUNC
12339 exportcmd(int argc UNUSED_PARAM, char **argv)
12345 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12347 if (nextopt("p") != 'p') {
12352 p = strchr(name, '=');
12356 vp = *findvar(hashvar(name), name);
12362 setvar(name, p, flag);
12363 } while ((name = *++aptr) != NULL);
12367 showvars(argv[0], flag, 0);
12372 * Delete a function if it exists.
12375 unsetfunc(const char *name)
12377 struct tblentry *cmdp;
12379 cmdp = cmdlookup(name, 0);
12380 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12381 delete_cmd_entry();
12385 * The unset builtin command. We unset the function before we unset the
12386 * variable to allow a function to be unset when there is a readonly variable
12387 * with the same name.
12389 static int FAST_FUNC
12390 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12397 while ((i = nextopt("vf")) != '\0') {
12401 for (ap = argptr; *ap; ap++) {
12417 #include <sys/times.h>
12419 static const unsigned char timescmd_str[] ALIGN1 = {
12420 ' ', offsetof(struct tms, tms_utime),
12421 '\n', offsetof(struct tms, tms_stime),
12422 ' ', offsetof(struct tms, tms_cutime),
12423 '\n', offsetof(struct tms, tms_cstime),
12427 static int FAST_FUNC
12428 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12430 long clk_tck, s, t;
12431 const unsigned char *p;
12434 clk_tck = sysconf(_SC_CLK_TCK);
12439 t = *(clock_t *)(((char *) &buf) + p[1]);
12441 out1fmt("%ldm%ld.%.3lds%c",
12443 ((t - s * clk_tck) * 1000) / clk_tck,
12445 } while (*(p += 2));
12450 #if ENABLE_SH_MATH_SUPPORT
12452 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12453 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12455 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12457 static int FAST_FUNC
12458 letcmd(int argc UNUSED_PARAM, char **argv)
12464 ash_msg_and_raise_error("expression expected");
12466 i = ash_arith(*argv);
12471 #endif /* SH_MATH_SUPPORT */
12474 /* ============ miscbltin.c
12476 * Miscellaneous builtins.
12481 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
12482 typedef enum __rlimit_resource rlim_t;
12486 * The read builtin. Options:
12487 * -r Do not interpret '\' specially
12488 * -s Turn off echo (tty only)
12489 * -n NCHARS Read NCHARS max
12490 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12491 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12492 * -u FD Read from given FD instead of fd 0
12493 * This uses unbuffered input, which may be avoidable in some cases.
12494 * TODO: bash also has:
12495 * -a ARRAY Read into array[0],[1],etc
12496 * -d DELIM End on DELIM char, not newline
12497 * -e Use line editing (tty only)
12499 static int FAST_FUNC
12500 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12502 static const char *const arg_REPLY[] = { "REPLY", NULL };
12515 #if ENABLE_ASH_READ_NCHARS
12516 int nchars = 0; /* if != 0, -n is in effect */
12518 struct termios tty, old_tty;
12520 #if ENABLE_ASH_READ_TIMEOUT
12521 unsigned end_ms = 0;
12522 unsigned timeout = 0;
12527 while ((i = nextopt("p:u:r"
12528 IF_ASH_READ_TIMEOUT("t:")
12529 IF_ASH_READ_NCHARS("n:s")
12533 prompt = optionarg;
12535 #if ENABLE_ASH_READ_NCHARS
12537 nchars = bb_strtou(optionarg, NULL, 10);
12538 if (nchars < 0 || errno)
12539 ash_msg_and_raise_error("invalid count");
12540 /* nchars == 0: off (bash 3.2 does this too) */
12546 #if ENABLE_ASH_READ_TIMEOUT
12548 timeout = bb_strtou(optionarg, NULL, 10);
12549 if (errno || timeout > UINT_MAX / 2048)
12550 ash_msg_and_raise_error("invalid timeout");
12552 #if 0 /* even bash have no -t N.NNN support */
12553 ts.tv_sec = bb_strtou(optionarg, &p, 10);
12555 /* EINVAL means number is ok, but not terminated by NUL */
12556 if (*p == '.' && errno == EINVAL) {
12560 ts.tv_usec = bb_strtou(p, &p2, 10);
12562 ash_msg_and_raise_error("invalid timeout");
12564 /* normalize to usec */
12566 ash_msg_and_raise_error("invalid timeout");
12567 while (scale++ < 6)
12570 } else if (ts.tv_sec < 0 || errno) {
12571 ash_msg_and_raise_error("invalid timeout");
12573 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
12574 ash_msg_and_raise_error("invalid timeout");
12583 fd = bb_strtou(optionarg, NULL, 10);
12584 if (fd < 0 || errno)
12585 ash_msg_and_raise_error("invalid file descriptor");
12591 if (prompt && isatty(fd)) {
12596 ap = (char**)arg_REPLY;
12597 ifs = bltinlookup("IFS");
12600 #if ENABLE_ASH_READ_NCHARS
12601 tcgetattr(fd, &tty);
12603 if (nchars || silent) {
12605 tty.c_lflag &= ~ICANON;
12606 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
12609 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12611 /* if tcgetattr failed, tcsetattr will fail too.
12612 * Ignoring, it's harmless. */
12613 tcsetattr(fd, TCSANOW, &tty);
12620 #if ENABLE_ASH_READ_TIMEOUT
12621 if (timeout) /* NB: ensuring end_ms is nonzero */
12622 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12626 const char *is_ifs;
12628 #if ENABLE_ASH_READ_TIMEOUT
12630 struct pollfd pfd[1];
12632 pfd[0].events = POLLIN;
12633 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12634 if ((int)timeout <= 0 /* already late? */
12635 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12636 ) { /* timed out! */
12637 #if ENABLE_ASH_READ_NCHARS
12638 tcsetattr(fd, TCSANOW, &old_tty);
12644 if (nonblock_safe_read(fd, &c, 1) != 1) {
12656 if (!rflag && c == '\\') {
12662 /* $IFS splitting */
12663 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
12664 is_ifs = strchr(ifs, c);
12665 if (startword && is_ifs) {
12668 /* it is a non-space ifs char */
12670 if (startword == 1) /* first one? */
12671 continue; /* yes, it is not next word yet */
12674 if (ap[1] != NULL && is_ifs) {
12677 beg = stackblock();
12678 setvar(*ap, beg, 0);
12680 /* can we skip one non-space ifs char? (2: yes) */
12681 startword = isspace(c) ? 2 : 1;
12688 /* end of do {} while: */
12689 #if ENABLE_ASH_READ_NCHARS
12695 #if ENABLE_ASH_READ_NCHARS
12696 tcsetattr(fd, TCSANOW, &old_tty);
12700 /* Remove trailing space ifs chars */
12701 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
12703 setvar(*ap, stackblock(), 0);
12704 while (*++ap != NULL)
12705 setvar(*ap, nullstr, 0);
12709 static int FAST_FUNC
12710 umaskcmd(int argc UNUSED_PARAM, char **argv)
12712 static const char permuser[3] ALIGN1 = "ugo";
12713 static const char permmode[3] ALIGN1 = "rwx";
12714 static const short permmask[] ALIGN2 = {
12715 S_IRUSR, S_IWUSR, S_IXUSR,
12716 S_IRGRP, S_IWGRP, S_IXGRP,
12717 S_IROTH, S_IWOTH, S_IXOTH
12720 /* TODO: use bb_parse_mode() instead */
12725 int symbolic_mode = 0;
12727 while (nextopt("S") != '\0') {
12738 if (symbolic_mode) {
12742 for (i = 0; i < 3; i++) {
12745 *p++ = permuser[i];
12747 for (j = 0; j < 3; j++) {
12748 if ((mask & permmask[3 * i + j]) == 0) {
12749 *p++ = permmode[j];
12757 out1fmt("%.4o\n", mask);
12760 if (isdigit((unsigned char) *ap)) {
12763 if (*ap >= '8' || *ap < '0')
12764 ash_msg_and_raise_error(msg_illnum, argv[1]);
12765 mask = (mask << 3) + (*ap - '0');
12766 } while (*++ap != '\0');
12769 mask = ~mask & 0777;
12770 if (!bb_parse_mode(ap, &mask)) {
12771 ash_msg_and_raise_error("illegal mode: %s", ap);
12773 umask(~mask & 0777);
12782 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12783 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12784 * ash by J.T. Conklin.
12789 uint8_t cmd; /* RLIMIT_xxx fit into it */
12790 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
12794 static const struct limits limits_tbl[] = {
12796 { RLIMIT_CPU, 0, 't' },
12798 #ifdef RLIMIT_FSIZE
12799 { RLIMIT_FSIZE, 9, 'f' },
12802 { RLIMIT_DATA, 10, 'd' },
12804 #ifdef RLIMIT_STACK
12805 { RLIMIT_STACK, 10, 's' },
12808 { RLIMIT_CORE, 9, 'c' },
12811 { RLIMIT_RSS, 10, 'm' },
12813 #ifdef RLIMIT_MEMLOCK
12814 { RLIMIT_MEMLOCK, 10, 'l' },
12816 #ifdef RLIMIT_NPROC
12817 { RLIMIT_NPROC, 0, 'p' },
12819 #ifdef RLIMIT_NOFILE
12820 { RLIMIT_NOFILE, 0, 'n' },
12823 { RLIMIT_AS, 10, 'v' },
12825 #ifdef RLIMIT_LOCKS
12826 { RLIMIT_LOCKS, 0, 'w' },
12829 static const char limits_name[] =
12831 "time(seconds)" "\0"
12833 #ifdef RLIMIT_FSIZE
12834 "file(blocks)" "\0"
12839 #ifdef RLIMIT_STACK
12843 "coredump(blocks)" "\0"
12848 #ifdef RLIMIT_MEMLOCK
12849 "locked memory(kb)" "\0"
12851 #ifdef RLIMIT_NPROC
12854 #ifdef RLIMIT_NOFILE
12860 #ifdef RLIMIT_LOCKS
12865 enum limtype { SOFT = 0x1, HARD = 0x2 };
12868 printlim(enum limtype how, const struct rlimit *limit,
12869 const struct limits *l)
12873 val = limit->rlim_max;
12875 val = limit->rlim_cur;
12877 if (val == RLIM_INFINITY)
12878 out1fmt("unlimited\n");
12880 val >>= l->factor_shift;
12881 out1fmt("%lld\n", (long long) val);
12885 static int FAST_FUNC
12886 ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12890 enum limtype how = SOFT | HARD;
12891 const struct limits *l;
12894 struct rlimit limit;
12897 while ((optc = nextopt("HSa"
12901 #ifdef RLIMIT_FSIZE
12907 #ifdef RLIMIT_STACK
12916 #ifdef RLIMIT_MEMLOCK
12919 #ifdef RLIMIT_NPROC
12922 #ifdef RLIMIT_NOFILE
12928 #ifdef RLIMIT_LOCKS
12946 for (l = limits_tbl; l->option != what; l++)
12949 set = *argptr ? 1 : 0;
12953 if (all || argptr[1])
12954 ash_msg_and_raise_error("too many arguments");
12955 if (strncmp(p, "unlimited\n", 9) == 0)
12956 val = RLIM_INFINITY;
12960 while ((c = *p++) >= '0' && c <= '9') {
12961 val = (val * 10) + (long)(c - '0');
12962 // val is actually 'unsigned long int' and can't get < 0
12963 if (val < (rlim_t) 0)
12967 ash_msg_and_raise_error("bad number");
12968 val <<= l->factor_shift;
12972 const char *lname = limits_name;
12973 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
12974 getrlimit(l->cmd, &limit);
12975 out1fmt("%-20s ", lname);
12976 lname += strlen(lname) + 1;
12977 printlim(how, &limit, l);
12982 getrlimit(l->cmd, &limit);
12985 limit.rlim_max = val;
12987 limit.rlim_cur = val;
12988 if (setrlimit(l->cmd, &limit) < 0)
12989 ash_msg_and_raise_error("error setting limit (%m)");
12991 printlim(how, &limit, l);
12996 /* ============ main() and helpers */
12999 * Called to exit the shell.
13001 static void exitshell(void) NORETURN;
13009 status = exitstatus;
13010 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13011 if (setjmp(loc.loc)) {
13012 if (exception_type == EXEXIT)
13013 /* dash bug: it just does _exit(exitstatus) here
13014 * but we have to do setjobctl(0) first!
13015 * (bug is still not fixed in dash-0.5.3 - if you run dash
13016 * under Midnight Commander, on exit from dash MC is backgrounded) */
13017 status = exitstatus;
13020 exception_handler = &loc;
13026 flush_stdout_stderr();
13036 /* from input.c: */
13037 basepf.next_to_pgetc = basepf.buf = basebuf;
13040 signal(SIGCHLD, SIG_DFL);
13045 char ppid[sizeof(int)*3 + 2];
13047 struct stat st1, st2;
13050 for (envp = environ; envp && *envp; envp++) {
13051 if (strchr(*envp, '=')) {
13052 setvareq(*envp, VEXPORT|VTEXTFIXED);
13056 sprintf(ppid, "%u", (unsigned) getppid());
13057 setvar("PPID", ppid, 0);
13059 p = lookupvar("PWD");
13061 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13062 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
13069 * Process the shell command line arguments.
13072 procargs(char **argv)
13075 const char *xminusc;
13080 /* if (xargv[0]) - mmm, this is always true! */
13082 for (i = 0; i < NOPTS; i++)
13086 /* it already printed err message */
13087 raise_exception(EXERROR);
13091 if (*xargv == NULL) {
13093 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13096 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13100 for (i = 0; i < NOPTS; i++)
13101 if (optlist[i] == 2)
13106 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13111 } else if (!sflag) {
13112 setinputfile(*xargv, 0);
13115 commandname = arg0;
13118 shellparam.p = xargv;
13119 #if ENABLE_ASH_GETOPTS
13120 shellparam.optind = 1;
13121 shellparam.optoff = -1;
13123 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13125 shellparam.nparam++;
13132 * Read /etc/profile or .profile.
13135 read_profile(const char *name)
13139 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13148 * This routine is called when an error or an interrupt occurs in an
13149 * interactive shell and control is returned to the main command loop.
13157 /* from input.c: */
13158 g_parsefile->left_in_buffer = 0;
13159 g_parsefile->left_in_line = 0; /* clear input buffer */
13161 /* from parser.c: */
13164 /* from redir.c: */
13165 clearredir(/*drop:*/ 0);
13169 static short profile_buf[16384];
13170 extern int etext();
13174 * Main routine. We initialize things, parse the arguments, execute
13175 * profiles if we're a login shell, and then call cmdloop to execute
13176 * commands. The setjmp call sets up the location to jump to when an
13177 * exception occurs. When an exception occurs the variable "state"
13178 * is used to figure out how far we had gotten.
13180 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13181 int ash_main(int argc UNUSED_PARAM, char **argv)
13183 const char *shinit;
13184 volatile smallint state;
13185 struct jmploc jmploc;
13186 struct stackmark smark;
13188 /* Initialize global data */
13192 #if ENABLE_ASH_ALIAS
13198 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13201 #if ENABLE_FEATURE_EDITING
13202 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13205 if (setjmp(jmploc.loc)) {
13211 e = exception_type;
13215 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13218 outcslow('\n', stderr);
13220 popstackmark(&smark);
13221 FORCE_INT_ON; /* enable interrupts */
13230 exception_handler = &jmploc;
13233 TRACE(("Shell args: "));
13234 trace_puts_args(argv);
13236 rootpid = getpid();
13238 #if ENABLE_ASH_RANDOM_SUPPORT
13239 /* Can use monotonic_ns() for better randomness but for now it is
13240 * not used anywhere else in busybox... so avoid bloat */
13241 random_galois_LFSR = random_LCG = rootpid + monotonic_us();
13244 setstackmark(&smark);
13247 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13249 const char *hp = lookupvar("HISTFILE");
13252 hp = lookupvar("HOME");
13254 char *defhp = concat_path_file(hp, ".ash_history");
13255 setvar("HISTFILE", defhp, 0);
13261 if (/* argv[0] && */ argv[0][0] == '-')
13265 read_profile("/etc/profile");
13268 read_profile(".profile");
13274 getuid() == geteuid() && getgid() == getegid() &&
13278 shinit = lookupvar("ENV");
13279 if (shinit != NULL && *shinit != '\0') {
13280 read_profile(shinit);
13286 /* evalstring pushes parsefile stack.
13287 * Ensure we don't falsely claim that 0 (stdin)
13288 * is one of stacked source fds.
13289 * Testcase: ash -c 'exec 1>&0' must not complain. */
13291 g_parsefile->fd = -1;
13292 evalstring(minusc, 0);
13295 if (sflag || minusc == NULL) {
13296 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13298 const char *hp = lookupvar("HISTFILE");
13300 line_input_state->hist_file = hp;
13303 state4: /* XXX ??? - why isn't this before the "if" statement */
13311 extern void _mcleanup(void);
13321 * Copyright (c) 1989, 1991, 1993, 1994
13322 * The Regents of the University of California. All rights reserved.
13324 * This code is derived from software contributed to Berkeley by
13325 * Kenneth Almquist.
13327 * Redistribution and use in source and binary forms, with or without
13328 * modification, are permitted provided that the following conditions
13330 * 1. Redistributions of source code must retain the above copyright
13331 * notice, this list of conditions and the following disclaimer.
13332 * 2. Redistributions in binary form must reproduce the above copyright
13333 * notice, this list of conditions and the following disclaimer in the
13334 * documentation and/or other materials provided with the distribution.
13335 * 3. Neither the name of the University nor the names of its contributors
13336 * may be used to endorse or promote products derived from this software
13337 * without specific prior written permission.
13339 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13340 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13341 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13342 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13343 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13344 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13345 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13346 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13347 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13348 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF