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 >= (unsigned char)(CTLESC)
2704 && (unsigned char)c <= (unsigned char)(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? */
4558 /* do job control only in root shell */
4560 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4563 if (jp->nprocs == 0)
4566 pgrp = jp->ps[0].pid;
4567 /* this can fail because we are doing it in the parent also */
4569 if (mode == FORK_FG)
4570 xtcsetpgrp(ttyfd, pgrp);
4575 if (mode == FORK_BG) {
4576 /* man bash: "When job control is not in effect,
4577 * asynchronous commands ignore SIGINT and SIGQUIT" */
4580 if (jp->nprocs == 0) {
4582 if (open(bb_dev_null, O_RDONLY) != 0)
4583 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4587 if (iflag) { /* why if iflag only? */
4592 * "In all cases, bash ignores SIGQUIT. Non-builtin
4593 * commands run by bash have signal handlers
4594 * set to the values inherited by the shell
4596 * Take care of the second rule: */
4600 if (n && n->type == NCMD && strcmp(n->ncmd.args->narg.text, "jobs") == 0) {
4601 TRACE(("Job hack\n"));
4606 for (jp = curjob; jp; jp = jp->prev_job)
4611 /* Called after fork(), in parent */
4613 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4616 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4618 TRACE(("In parent shell: child = %d\n", pid));
4620 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4626 if (mode != FORK_NOJOB && jp->jobctl) {
4629 if (jp->nprocs == 0)
4632 pgrp = jp->ps[0].pid;
4633 /* This can fail because we are doing it in the child also */
4637 if (mode == FORK_BG) {
4638 backgndpid = pid; /* set $! */
4639 set_curjob(jp, CUR_RUNNING);
4642 struct procstat *ps = &jp->ps[jp->nprocs++];
4647 if (doing_jobctl && n)
4648 ps->cmd = commandtext(n);
4654 forkshell(struct job *jp, union node *n, int mode)
4658 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4661 TRACE(("Fork failed, errno=%d", errno));
4664 ash_msg_and_raise_error("can't fork");
4667 forkchild(jp, n, mode);
4669 forkparent(jp, n, mode, pid);
4674 * Wait for job to finish.
4676 * Under job control we have the problem that while a child process
4677 * is running interrupts generated by the user are sent to the child
4678 * but not to the shell. This means that an infinite loop started by
4679 * an interactive user may be hard to kill. With job control turned off,
4680 * an interactive user may place an interactive program inside a loop.
4681 * If the interactive program catches interrupts, the user doesn't want
4682 * these interrupts to also abort the loop. The approach we take here
4683 * is to have the shell ignore interrupt signals while waiting for a
4684 * foreground process to terminate, and then send itself an interrupt
4685 * signal if the child process was terminated by an interrupt signal.
4686 * Unfortunately, some programs want to do a bit of cleanup and then
4687 * exit on interrupt; unless these processes terminate themselves by
4688 * sending a signal to themselves (instead of calling exit) they will
4689 * confuse this approach.
4691 * Called with interrupts off.
4694 waitforjob(struct job *jp)
4698 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4701 while (jp->state == JOBRUNNING) {
4702 /* In non-interactive shells, we _can_ get
4703 * a keyboard signal here and be EINTRed,
4704 * but we just loop back, waiting for command to complete.
4707 * "If bash is waiting for a command to complete and receives
4708 * a signal for which a trap has been set, the trap
4709 * will not be executed until the command completes."
4711 * Reality is that even if trap is not set, bash
4712 * will not act on the signal until command completes.
4713 * Try this. sleep5intoff.c:
4714 * #include <signal.h>
4715 * #include <unistd.h>
4718 * sigemptyset(&set);
4719 * sigaddset(&set, SIGINT);
4720 * sigaddset(&set, SIGQUIT);
4721 * sigprocmask(SIG_BLOCK, &set, NULL);
4725 * $ bash -c './sleep5intoff; echo hi'
4726 * ^C^C^C^C <--- pressing ^C once a second
4728 * $ bash -c './sleep5intoff; echo hi'
4729 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4732 dowait(DOWAIT_BLOCK, jp);
4739 xtcsetpgrp(ttyfd, rootpid);
4741 * This is truly gross.
4742 * If we're doing job control, then we did a TIOCSPGRP which
4743 * caused us (the shell) to no longer be in the controlling
4744 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4745 * intuit from the subprocess exit status whether a SIGINT
4746 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4748 if (jp->sigint) /* TODO: do the same with all signals */
4749 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4751 if (jp->state == JOBDONE)
4758 * return 1 if there are stopped jobs, otherwise 0
4770 if (jp && jp->state == JOBSTOPPED) {
4771 out2str("You have stopped jobs.\n");
4780 /* ============ redir.c
4782 * Code for dealing with input/output redirection.
4785 #define EMPTY -2 /* marks an unused slot in redirtab */
4786 #define CLOSED -3 /* marks a slot of previously-closed fd */
4789 * Open a file in noclobber mode.
4790 * The code was copied from bash.
4793 noclobberopen(const char *fname)
4796 struct stat finfo, finfo2;
4799 * If the file exists and is a regular file, return an error
4802 r = stat(fname, &finfo);
4803 if (r == 0 && S_ISREG(finfo.st_mode)) {
4809 * If the file was not present (r != 0), make sure we open it
4810 * exclusively so that if it is created before we open it, our open
4811 * will fail. Make sure that we do not truncate an existing file.
4812 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4813 * file was not a regular file, we leave O_EXCL off.
4816 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4817 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4819 /* If the open failed, return the file descriptor right away. */
4824 * OK, the open succeeded, but the file may have been changed from a
4825 * non-regular file to a regular file between the stat and the open.
4826 * We are assuming that the O_EXCL open handles the case where FILENAME
4827 * did not exist and is symlinked to an existing file between the stat
4832 * If we can open it and fstat the file descriptor, and neither check
4833 * revealed that it was a regular file, and the file has not been
4834 * replaced, return the file descriptor.
4836 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4837 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4840 /* The file has been replaced. badness. */
4847 * Handle here documents. Normally we fork off a process to write the
4848 * data to a pipe. If the document is short, we can stuff the data in
4849 * the pipe without forking.
4851 /* openhere needs this forward reference */
4852 static void expandhere(union node *arg, int fd);
4854 openhere(union node *redir)
4860 ash_msg_and_raise_error("pipe call failed");
4861 if (redir->type == NHERE) {
4862 len = strlen(redir->nhere.doc->narg.text);
4863 if (len <= PIPE_BUF) {
4864 full_write(pip[1], redir->nhere.doc->narg.text, len);
4868 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4871 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4872 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4873 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4874 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4875 signal(SIGPIPE, SIG_DFL);
4876 if (redir->type == NHERE)
4877 full_write(pip[1], redir->nhere.doc->narg.text, len);
4879 expandhere(redir->nhere.doc, pip[1]);
4880 _exit(EXIT_SUCCESS);
4888 openredirect(union node *redir)
4893 switch (redir->nfile.type) {
4895 fname = redir->nfile.expfname;
4896 f = open(fname, O_RDONLY);
4901 fname = redir->nfile.expfname;
4902 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4907 #if ENABLE_ASH_BASH_COMPAT
4910 /* Take care of noclobber mode. */
4912 fname = redir->nfile.expfname;
4913 f = noclobberopen(fname);
4920 fname = redir->nfile.expfname;
4921 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4926 fname = redir->nfile.expfname;
4927 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4935 /* Fall through to eliminate warning. */
4936 /* Our single caller does this itself */
4943 f = openhere(redir);
4949 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4951 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
4955 * Copy a file descriptor to be >= to. Returns -1
4956 * if the source file descriptor is closed, EMPTY if there are no unused
4957 * file descriptors left.
4959 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
4960 * old code was doing close(to) prior to copyfd() to achieve the same */
4962 COPYFD_EXACT = (int)~(INT_MAX),
4963 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
4966 copyfd(int from, int to)
4970 if (to & COPYFD_EXACT) {
4971 to &= ~COPYFD_EXACT;
4973 newfd = dup2(from, to);
4975 newfd = fcntl(from, F_DUPFD, to);
4978 if (errno == EMFILE)
4980 /* Happens when source fd is not open: try "echo >&99" */
4981 ash_msg_and_raise_error("%d: %m", from);
4986 /* Struct def and variable are moved down to the first usage site */
4991 struct redirtab *next;
4994 struct two_fd_t two_fd[0];
4996 #define redirlist (G_var.redirlist)
4998 static int need_to_remember(struct redirtab *rp, int fd)
5002 if (!rp) /* remembering was not requested */
5005 for (i = 0; i < rp->pair_count; i++) {
5006 if (rp->two_fd[i].orig == fd) {
5007 /* already remembered */
5014 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5015 static int is_hidden_fd(struct redirtab *rp, int fd)
5018 struct parsefile *pf;
5031 fd |= COPYFD_RESTORE;
5032 for (i = 0; i < rp->pair_count; i++) {
5033 if (rp->two_fd[i].copy == fd) {
5041 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5042 * old file descriptors are stashed away so that the redirection can be
5043 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5044 * standard output, and the standard error if it becomes a duplicate of
5045 * stdout, is saved in memory.
5047 /* flags passed to redirect */
5048 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5049 #define REDIR_SAVEFD2 03 /* set preverrout */
5051 redirect(union node *redir, int flags)
5053 struct redirtab *sv;
5058 int copied_fd2 = -1;
5068 if (flags & REDIR_PUSH) {
5069 union node *tmp = redir;
5072 #if ENABLE_ASH_BASH_COMPAT
5073 if (redir->nfile.type == NTO2)
5076 tmp = tmp->nfile.next;
5078 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5079 sv->next = redirlist;
5080 sv->pair_count = sv_pos;
5082 sv->nullredirs = g_nullredirs - 1;
5084 while (sv_pos > 0) {
5086 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5091 fd = redir->nfile.fd;
5092 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5093 int right_fd = redir->ndup.dupfd;
5094 /* redirect from/to same file descriptor? */
5097 /* echo >&10 and 10 is a fd opened to the sh script? */
5098 if (is_hidden_fd(sv, right_fd)) {
5099 errno = EBADF; /* as if it is closed */
5100 ash_msg_and_raise_error("%d: %m", right_fd);
5104 newfd = openredirect(redir); /* always >= 0 */
5106 /* Descriptor wasn't open before redirect.
5107 * Mark it for close in the future */
5108 if (need_to_remember(sv, fd)) {
5109 goto remember_to_close;
5114 #if ENABLE_ASH_BASH_COMPAT
5117 if (need_to_remember(sv, fd)) {
5118 /* Copy old descriptor */
5119 i = fcntl(fd, F_DUPFD, 10);
5120 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5121 * are closed in popredir() in the child, preventing them from leaking
5122 * into child. (popredir() also cleans up the mess in case of failures)
5127 /* Strange error (e.g. "too many files" EMFILE?) */
5131 ash_msg_and_raise_error("%d: %m", fd);
5134 /* EBADF: it is not open - good, remember to close it */
5137 } else { /* fd is open, save its copy */
5138 /* "exec fd>&-" should not close fds
5139 * which point to script file(s).
5140 * Force them to be restored afterwards */
5141 if (is_hidden_fd(sv, fd))
5142 i |= COPYFD_RESTORE;
5146 sv->two_fd[sv_pos].orig = fd;
5147 sv->two_fd[sv_pos].copy = i;
5151 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5152 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5153 /* Don't want to trigger debugging */
5157 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5159 } else if (fd != newfd) { /* move newfd to fd */
5160 copyfd(newfd, fd | COPYFD_EXACT);
5161 #if ENABLE_ASH_BASH_COMPAT
5162 if (!(redir->nfile.type == NTO2 && fd == 2))
5166 #if ENABLE_ASH_BASH_COMPAT
5167 if (redir->nfile.type == NTO2 && fd == 1) {
5168 /* We already redirected it to fd 1, now copy it to 2 */
5174 } while ((redir = redir->nfile.next) != NULL);
5177 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5178 preverrout_fd = copied_fd2;
5182 * Undo the effects of the last redirection.
5185 popredir(int drop, int restore)
5187 struct redirtab *rp;
5190 if (--g_nullredirs >= 0)
5194 for (i = 0; i < rp->pair_count; i++) {
5195 int fd = rp->two_fd[i].orig;
5196 int copy = rp->two_fd[i].copy;
5197 if (copy == CLOSED) {
5202 if (copy != EMPTY) {
5203 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5204 copy &= ~COPYFD_RESTORE;
5206 copyfd(copy, fd | COPYFD_EXACT);
5208 close(copy & ~COPYFD_RESTORE);
5211 redirlist = rp->next;
5212 g_nullredirs = rp->nullredirs;
5218 * Undo all redirections. Called on error or interrupt.
5222 * Discard all saved file descriptors.
5225 clearredir(int drop)
5231 popredir(drop, /*restore:*/ 0);
5236 redirectsafe(union node *redir, int flags)
5239 volatile int saveint;
5240 struct jmploc *volatile savehandler = exception_handler;
5241 struct jmploc jmploc;
5244 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5245 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5247 exception_handler = &jmploc;
5248 redirect(redir, flags);
5250 exception_handler = savehandler;
5251 if (err && exception_type != EXERROR)
5252 longjmp(exception_handler->loc, 1);
5253 RESTORE_INT(saveint);
5258 /* ============ Routines to expand arguments to commands
5260 * We have to deal with backquotes, shell variables, and file metacharacters.
5263 #if ENABLE_SH_MATH_SUPPORT
5265 ash_arith(const char *s)
5267 arith_eval_hooks_t math_hooks;
5271 math_hooks.lookupvar = lookupvar;
5272 math_hooks.setvar = setvar;
5273 math_hooks.endofname = endofname;
5276 result = arith(s, &errcode, &math_hooks);
5279 ash_msg_and_raise_error("exponent less than 0");
5281 ash_msg_and_raise_error("divide by zero");
5283 ash_msg_and_raise_error("expression recursion loop detected");
5284 raise_error_syntax(s);
5295 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5296 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5297 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5298 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5299 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5300 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5301 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5302 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5303 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5307 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5308 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5309 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5310 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5311 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5314 * Structure specifying which parts of the string should be searched
5315 * for IFS characters.
5318 struct ifsregion *next; /* next region in list */
5319 int begoff; /* offset of start of region */
5320 int endoff; /* offset of end of region */
5321 int nulonly; /* search for nul bytes only */
5325 struct strlist *list;
5326 struct strlist **lastp;
5329 /* output of current string */
5330 static char *expdest;
5331 /* list of back quote expressions */
5332 static struct nodelist *argbackq;
5333 /* first struct in list of ifs regions */
5334 static struct ifsregion ifsfirst;
5335 /* last struct in list */
5336 static struct ifsregion *ifslastp;
5337 /* holds expanded arg list */
5338 static struct arglist exparg;
5348 expdest = makestrspace(32, expdest);
5349 len = fmtstr(expdest, 32, arith_t_fmt, num);
5350 STADJUST(len, expdest);
5355 esclen(const char *start, const char *p)
5359 while (p > start && *--p == CTLESC) {
5366 * Remove any CTLESC characters from a string.
5369 rmescapes(char *str, int flag)
5371 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5378 p = strpbrk(str, qchars);
5384 if (flag & RMESCAPE_ALLOC) {
5385 size_t len = p - str;
5386 size_t fulllen = len + strlen(p) + 1;
5388 if (flag & RMESCAPE_GROW) {
5389 r = makestrspace(fulllen, expdest);
5390 } else if (flag & RMESCAPE_HEAP) {
5391 r = ckmalloc(fulllen);
5393 r = stalloc(fulllen);
5397 q = (char *)memcpy(q, str, len) + len;
5400 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5401 globbing = flag & RMESCAPE_GLOB;
5402 notescaped = globbing;
5404 if (*p == CTLQUOTEMARK) {
5405 inquotes = ~inquotes;
5407 notescaped = globbing;
5411 /* naked back slash */
5417 if (notescaped && inquotes && *p != '/') {
5421 notescaped = globbing;
5426 if (flag & RMESCAPE_GROW) {
5428 STADJUST(q - r + 1, expdest);
5432 #define pmatch(a, b) !fnmatch((a), (b), 0)
5435 * Prepare a pattern for a expmeta (internal glob(3)) call.
5437 * Returns an stalloced string.
5440 preglob(const char *pattern, int quoted, int flag)
5442 flag |= RMESCAPE_GLOB;
5444 flag |= RMESCAPE_QUOTED;
5446 return rmescapes((char *)pattern, flag);
5450 * Put a string on the stack.
5453 memtodest(const char *p, size_t len, int syntax, int quotes)
5457 q = makestrspace(quotes ? len * 2 : len, q);
5460 int c = signed_char2int(*p++);
5464 int n = SIT(c, syntax);
5465 if (n == CCTL || n == CBACK)
5475 strtodest(const char *p, int syntax, int quotes)
5477 memtodest(p, strlen(p), syntax, quotes);
5481 * Record the fact that we have to scan this region of the
5482 * string for IFS characters.
5485 recordregion(int start, int end, int nulonly)
5487 struct ifsregion *ifsp;
5489 if (ifslastp == NULL) {
5493 ifsp = ckzalloc(sizeof(*ifsp));
5494 /*ifsp->next = NULL; - ckzalloc did it */
5495 ifslastp->next = ifsp;
5499 ifslastp->begoff = start;
5500 ifslastp->endoff = end;
5501 ifslastp->nulonly = nulonly;
5505 removerecordregions(int endoff)
5507 if (ifslastp == NULL)
5510 if (ifsfirst.endoff > endoff) {
5511 while (ifsfirst.next != NULL) {
5512 struct ifsregion *ifsp;
5514 ifsp = ifsfirst.next->next;
5515 free(ifsfirst.next);
5516 ifsfirst.next = ifsp;
5519 if (ifsfirst.begoff > endoff)
5522 ifslastp = &ifsfirst;
5523 ifsfirst.endoff = endoff;
5528 ifslastp = &ifsfirst;
5529 while (ifslastp->next && ifslastp->next->begoff < endoff)
5530 ifslastp=ifslastp->next;
5531 while (ifslastp->next != NULL) {
5532 struct ifsregion *ifsp;
5534 ifsp = ifslastp->next->next;
5535 free(ifslastp->next);
5536 ifslastp->next = ifsp;
5539 if (ifslastp->endoff > endoff)
5540 ifslastp->endoff = endoff;
5544 exptilde(char *startp, char *p, int flag)
5550 int quotes = flag & (EXP_FULL | EXP_CASE);
5555 while ((c = *++p) != '\0') {
5562 if (flag & EXP_VARTILDE)
5572 if (*name == '\0') {
5573 home = lookupvar(homestr);
5575 pw = getpwnam(name);
5580 if (!home || !*home)
5583 startloc = expdest - (char *)stackblock();
5584 strtodest(home, SQSYNTAX, quotes);
5585 recordregion(startloc, expdest - (char *)stackblock(), 0);
5593 * Execute a command inside back quotes. If it's a builtin command, we
5594 * want to save its output in a block obtained from malloc. Otherwise
5595 * we fork off a subprocess and get the output of the command via a pipe.
5596 * Should be called with interrupts off.
5598 struct backcmd { /* result of evalbackcmd */
5599 int fd; /* file descriptor to read from */
5600 int nleft; /* number of chars in buffer */
5601 char *buf; /* buffer */
5602 struct job *jp; /* job structure for command */
5605 /* These forward decls are needed to use "eval" code for backticks handling: */
5606 static uint8_t back_exitstatus; /* exit status of backquoted command */
5607 #define EV_EXIT 01 /* exit after evaluating tree */
5608 static void evaltree(union node *, int);
5610 static void FAST_FUNC
5611 evalbackcmd(union node *n, struct backcmd *result)
5622 saveherefd = herefd;
5630 ash_msg_and_raise_error("pipe call failed");
5631 jp = makejob(/*n,*/ 1);
5632 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5637 copyfd(pip[1], 1 | COPYFD_EXACT);
5641 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5645 result->fd = pip[0];
5648 herefd = saveherefd;
5650 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5651 result->fd, result->buf, result->nleft, result->jp));
5655 * Expand stuff in backwards quotes.
5658 expbackq(union node *cmd, int quoted, int quotes)
5666 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5667 struct stackmark smark;
5670 setstackmark(&smark);
5672 startloc = dest - (char *)stackblock();
5674 evalbackcmd(cmd, &in);
5675 popstackmark(&smark);
5682 memtodest(p, i, syntax, quotes);
5686 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5687 TRACE(("expbackq: read returns %d\n", i));
5696 back_exitstatus = waitforjob(in.jp);
5700 /* Eat all trailing newlines */
5702 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5707 recordregion(startloc, dest - (char *)stackblock(), 0);
5708 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5709 (dest - (char *)stackblock()) - startloc,
5710 (dest - (char *)stackblock()) - startloc,
5711 stackblock() + startloc));
5714 #if ENABLE_SH_MATH_SUPPORT
5716 * Expand arithmetic expression. Backup to start of expression,
5717 * evaluate, place result in (backed up) result, adjust string position.
5730 * This routine is slightly over-complicated for
5731 * efficiency. Next we scan backwards looking for the
5732 * start of arithmetic.
5734 start = stackblock();
5741 while (*p != CTLARI) {
5745 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5750 esc = esclen(start, p);
5760 removerecordregions(begoff);
5767 rmescapes(p + 2, 0);
5769 len = cvtnum(ash_arith(p + 2));
5772 recordregion(begoff, begoff + len, 0);
5776 /* argstr needs it */
5777 static char *evalvar(char *p, int flag, struct strlist *var_str_list);
5780 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5781 * characters to allow for further processing. Otherwise treat
5782 * $@ like $* since no splitting will be performed.
5784 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5785 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5786 * for correct expansion of "B=$A" word.
5789 argstr(char *p, int flag, struct strlist *var_str_list)
5791 static const char spclchars[] ALIGN1 = {
5799 CTLBACKQ | CTLQUOTE,
5800 #if ENABLE_SH_MATH_SUPPORT
5805 const char *reject = spclchars;
5807 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5808 int breakall = flag & EXP_WORD;
5813 if (!(flag & EXP_VARTILDE)) {
5815 } else if (flag & EXP_VARTILDE2) {
5820 if (flag & EXP_TILDE) {
5826 if (*q == CTLESC && (flag & EXP_QWORD))
5829 p = exptilde(p, q, flag);
5832 startloc = expdest - (char *)stackblock();
5834 length += strcspn(p + length, reject);
5836 if (c && (!(c & 0x80)
5837 #if ENABLE_SH_MATH_SUPPORT
5841 /* c == '=' || c == ':' || c == CTLENDARI */
5846 expdest = stack_nputstr(p, length, expdest);
5847 newloc = expdest - (char *)stackblock();
5848 if (breakall && !inquotes && newloc > startloc) {
5849 recordregion(startloc, newloc, 0);
5860 if (flag & EXP_VARTILDE2) {
5864 flag |= EXP_VARTILDE2;
5869 * sort of a hack - expand tildes in variable
5870 * assignments (after the first '=' and after ':'s).
5879 case CTLENDVAR: /* ??? */
5882 /* "$@" syntax adherence hack */
5885 !memcmp(p, dolatstr, 4) &&
5886 (p[4] == CTLQUOTEMARK || (
5887 p[4] == CTLENDVAR &&
5888 p[5] == CTLQUOTEMARK
5891 p = evalvar(p + 1, flag, /* var_str_list: */ NULL) + 1;
5894 inquotes = !inquotes;
5907 p = evalvar(p, flag, var_str_list);
5911 case CTLBACKQ|CTLQUOTE:
5912 expbackq(argbackq->n, c, quotes);
5913 argbackq = argbackq->next;
5915 #if ENABLE_SH_MATH_SUPPORT
5928 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
5931 // This commented out code was added by James Simmons <jsimmons@infradead.org>
5932 // as part of a larger change when he added support for ${var/a/b}.
5933 // However, it broke # and % operators:
5937 //echo ${var#ab} abcdcd abcdcd
5938 //echo ${var##ab} abcdcd abcdcd
5939 //echo ${var#a*b} abcdcd ababcdcd (!)
5940 //echo ${var##a*b} cdcd cdcd
5941 //echo ${var#?} babcdcd ababcdcd (!)
5942 //echo ${var##?} babcdcd babcdcd
5943 //echo ${var#*} ababcdcd babcdcd (!)
5945 //echo ${var%cd} ababcd ababcd
5946 //echo ${var%%cd} ababcd abab (!)
5947 //echo ${var%c*d} ababcd ababcd
5948 //echo ${var%%c*d} abab ababcdcd (!)
5949 //echo ${var%?} ababcdc ababcdc
5950 //echo ${var%%?} ababcdc ababcdcd (!)
5951 //echo ${var%*} ababcdcd ababcdcd
5954 // Commenting it back out helped. Remove it completely if it really
5957 char *loc, *loc2; //, *full;
5963 int match; // = strlen(str);
5964 const char *s = loc2;
5971 match = pmatch(str, s); // this line was deleted
5973 // // chop off end if its '*'
5974 // full = strrchr(str, '*');
5975 // if (full && full != str)
5978 // // If str starts with '*' replace with s.
5979 // if ((*str == '*') && strlen(s) >= match) {
5980 // full = xstrdup(s);
5981 // strncpy(full+strlen(s)-match+1, str+1, match-1);
5983 // full = xstrndup(str, match);
5984 // match = strncmp(s, full, strlen(full));
5988 if (match) // if (!match)
5990 if (quotes && *loc == CTLESC)
5999 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6006 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6009 const char *s = loc2;
6014 match = pmatch(str, s);
6021 esc = esclen(startp, loc);
6032 static void varunset(const char *, const char *, const char *, int) NORETURN;
6034 varunset(const char *end, const char *var, const char *umsg, int varflags)
6040 msg = "parameter not set";
6042 if (*end == CTLENDVAR) {
6043 if (varflags & VSNUL)
6049 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6052 #if ENABLE_ASH_BASH_COMPAT
6054 parse_sub_pattern(char *arg, int inquotes)
6056 char *idx, *repl = NULL;
6065 /* Only the first '/' seen is our separator */
6072 if (!inquotes && c == '\\' && arg[1] == '\\')
6073 arg++; /* skip both \\, not just first one */
6080 #endif /* ENABLE_ASH_BASH_COMPAT */
6083 subevalvar(char *p, char *str, int strloc, int subtype,
6084 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6086 struct nodelist *saveargbackq = argbackq;
6089 char *rmesc, *rmescend;
6090 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6091 IF_ASH_BASH_COMPAT(char null = '\0';)
6092 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6093 int saveherefd = herefd;
6094 int amount, workloc, resetloc;
6096 char *(*scan)(char*, char*, char*, char*, int, int);
6099 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6101 STPUTC('\0', expdest);
6102 herefd = saveherefd;
6103 argbackq = saveargbackq;
6104 startp = (char *)stackblock() + startloc;
6108 setvar(str, startp, 0);
6109 amount = startp - expdest;
6110 STADJUST(amount, expdest);
6113 #if ENABLE_ASH_BASH_COMPAT
6115 loc = str = stackblock() + strloc;
6116 /* Read POS in ${var:POS:LEN} */
6117 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6118 len = str - startp - 1;
6120 /* *loc != '\0', guaranteed by parser */
6124 /* Adjust the length by the number of escapes */
6125 for (ptr = startp; ptr < (str - 1); ptr++) {
6126 if (*ptr == CTLESC) {
6134 if (*loc++ == ':') {
6138 /* Skip POS in ${var:POS:LEN} */
6140 while (*loc && *loc != ':') {
6142 * bash complains on: var=qwe; echo ${var:1a:123}
6144 ash_msg_and_raise_error(msg_illnum, str);
6148 if (*loc++ == ':') {
6152 if (pos >= orig_len) {
6156 if (len > (orig_len - pos))
6157 len = orig_len - pos;
6159 for (str = startp; pos; str++, pos--) {
6160 if (quotes && *str == CTLESC)
6163 for (loc = startp; len; len--) {
6164 if (quotes && *str == CTLESC)
6169 amount = loc - expdest;
6170 STADJUST(amount, expdest);
6175 varunset(p, str, startp, varflags);
6178 resetloc = expdest - (char *)stackblock();
6180 /* We'll comeback here if we grow the stack while handling
6181 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6182 * stack will need rebasing, and we'll need to remove our work
6185 IF_ASH_BASH_COMPAT(restart:)
6187 amount = expdest - ((char *)stackblock() + resetloc);
6188 STADJUST(-amount, expdest);
6189 startp = (char *)stackblock() + startloc;
6192 rmescend = (char *)stackblock() + strloc;
6194 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6195 if (rmesc != startp) {
6197 startp = (char *)stackblock() + startloc;
6201 str = (char *)stackblock() + strloc;
6202 preglob(str, varflags & VSQUOTE, 0);
6203 workloc = expdest - (char *)stackblock();
6205 #if ENABLE_ASH_BASH_COMPAT
6206 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6207 char *idx, *end, *restart_detect;
6210 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6215 /* If there's no pattern to match, return the expansion unmolested */
6223 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6225 /* No match, advance */
6226 restart_detect = stackblock();
6227 STPUTC(*idx, expdest);
6228 if (quotes && *idx == CTLESC) {
6231 STPUTC(*idx, expdest);
6233 if (stackblock() != restart_detect)
6241 if (subtype == VSREPLACEALL) {
6243 if (quotes && *idx == CTLESC)
6252 for (loc = repl; *loc; loc++) {
6253 restart_detect = stackblock();
6254 STPUTC(*loc, expdest);
6255 if (stackblock() != restart_detect)
6260 if (subtype == VSREPLACE) {
6262 restart_detect = stackblock();
6263 STPUTC(*idx, expdest);
6264 if (stackblock() != restart_detect)
6273 /* We've put the replaced text into a buffer at workloc, now
6274 * move it to the right place and adjust the stack.
6276 startp = stackblock() + startloc;
6277 STPUTC('\0', expdest);
6278 memmove(startp, stackblock() + workloc, len);
6279 startp[len++] = '\0';
6280 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6281 STADJUST(-amount, expdest);
6284 #endif /* ENABLE_ASH_BASH_COMPAT */
6286 subtype -= VSTRIMRIGHT;
6288 if (subtype < 0 || subtype > 7)
6291 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6292 zero = subtype >> 1;
6293 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6294 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6296 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6299 memmove(startp, loc, str - loc);
6300 loc = startp + (str - loc) - 1;
6303 amount = loc - expdest;
6304 STADJUST(amount, expdest);
6310 * Add the value of a specialized variable to the stack string.
6313 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6323 int quoted = varflags & VSQUOTE;
6324 int subtype = varflags & VSTYPE;
6325 int quotes = flags & (EXP_FULL | EXP_CASE);
6327 if (quoted && (flags & EXP_FULL))
6328 sep = 1 << CHAR_BIT;
6330 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6339 num = shellparam.nparam;
6349 expdest = makestrspace(NOPTS, expdest);
6350 for (i = NOPTS - 1; i >= 0; i--) {
6352 USTPUTC(optletters(i), expdest);
6362 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
6363 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6369 while ((p = *ap++) != NULL) {
6372 partlen = strlen(p);
6375 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6376 memtodest(p, partlen, syntax, quotes);
6382 if (subtype == VSPLUS || subtype == VSLENGTH) {
6403 num = atoi(name); /* number(name) fails on ${N#str} etc */
6404 if (num < 0 || num > shellparam.nparam)
6406 p = num ? shellparam.p[num - 1] : arg0;
6409 /* NB: name has form "VAR=..." */
6411 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6412 * which should be considered before we check variables. */
6414 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6418 str = var_str_list->text;
6419 eq = strchr(str, '=');
6420 if (!eq) /* stop at first non-assignment */
6423 if (name_len == (unsigned)(eq - str)
6424 && strncmp(str, name, name_len) == 0) {
6426 /* goto value; - WRONG! */
6427 /* think "A=1 A=2 B=$A" */
6429 var_str_list = var_str_list->next;
6430 } while (var_str_list);
6434 p = lookupvar(name);
6440 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6441 memtodest(p, len, syntax, quotes);
6445 if (subtype == VSPLUS || subtype == VSLENGTH)
6446 STADJUST(-len, expdest);
6451 * Expand a variable, and return a pointer to the next character in the
6455 evalvar(char *p, int flag, struct strlist *var_str_list)
6467 subtype = varflags & VSTYPE;
6468 quoted = varflags & VSQUOTE;
6470 easy = (!quoted || (*var == '@' && shellparam.nparam));
6471 startloc = expdest - (char *)stackblock();
6472 p = strchr(p, '=') + 1;
6475 varlen = varvalue(var, varflags, flag, var_str_list);
6476 if (varflags & VSNUL)
6479 if (subtype == VSPLUS) {
6480 varlen = -1 - varlen;
6484 if (subtype == VSMINUS) {
6488 p, flag | EXP_TILDE |
6489 (quoted ? EXP_QWORD : EXP_WORD),
6499 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6501 if (subevalvar(p, var, /* strloc: */ 0,
6502 subtype, startloc, varflags,
6508 * Remove any recorded regions beyond
6511 removerecordregions(startloc);
6521 if (varlen < 0 && uflag)
6522 varunset(p, var, 0, 0);
6524 if (subtype == VSLENGTH) {
6525 cvtnum(varlen > 0 ? varlen : 0);
6529 if (subtype == VSNORMAL) {
6540 case VSTRIMRIGHTMAX:
6541 #if ENABLE_ASH_BASH_COMPAT
6554 * Terminate the string and start recording the pattern
6557 STPUTC('\0', expdest);
6558 patloc = expdest - (char *)stackblock();
6559 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6561 /* quotes: */ flag & (EXP_FULL | EXP_CASE),
6564 int amount = expdest - (
6565 (char *)stackblock() + patloc - 1
6567 STADJUST(-amount, expdest);
6569 /* Remove any recorded regions beyond start of variable */
6570 removerecordregions(startloc);
6572 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6576 if (subtype != VSNORMAL) { /* skip to end of alternative */
6582 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6584 argbackq = argbackq->next;
6585 } else if (c == CTLVAR) {
6586 if ((*p++ & VSTYPE) != VSNORMAL)
6588 } else if (c == CTLENDVAR) {
6598 * Break the argument string into pieces based upon IFS and add the
6599 * strings to the argument list. The regions of the string to be
6600 * searched for IFS characters have been stored by recordregion.
6603 ifsbreakup(char *string, struct arglist *arglist)
6605 struct ifsregion *ifsp;
6610 const char *ifs, *realifs;
6615 if (ifslastp != NULL) {
6618 realifs = ifsset() ? ifsval() : defifs;
6621 p = string + ifsp->begoff;
6622 nulonly = ifsp->nulonly;
6623 ifs = nulonly ? nullstr : realifs;
6625 while (p < string + ifsp->endoff) {
6629 if (!strchr(ifs, *p)) {
6634 ifsspc = (strchr(defifs, *p) != NULL);
6635 /* Ignore IFS whitespace at start */
6636 if (q == start && ifsspc) {
6642 sp = stzalloc(sizeof(*sp));
6644 *arglist->lastp = sp;
6645 arglist->lastp = &sp->next;
6649 if (p >= string + ifsp->endoff) {
6655 if (strchr(ifs, *p) == NULL) {
6659 if (strchr(defifs, *p) == NULL) {
6674 } while (ifsp != NULL);
6683 sp = stzalloc(sizeof(*sp));
6685 *arglist->lastp = sp;
6686 arglist->lastp = &sp->next;
6692 struct ifsregion *p;
6697 struct ifsregion *ifsp;
6703 ifsfirst.next = NULL;
6708 * Add a file name to the list.
6711 addfname(const char *name)
6715 sp = stzalloc(sizeof(*sp));
6716 sp->text = ststrdup(name);
6718 exparg.lastp = &sp->next;
6721 static char *expdir;
6724 * Do metacharacter (i.e. *, ?, [...]) expansion.
6727 expmeta(char *enddir, char *name)
6742 for (p = name; *p; p++) {
6743 if (*p == '*' || *p == '?')
6745 else if (*p == '[') {
6752 if (*q == '/' || *q == '\0')
6759 } else if (*p == '\\')
6761 else if (*p == '/') {
6768 if (metaflag == 0) { /* we've reached the end of the file name */
6769 if (enddir != expdir)
6777 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6788 } while (p < start);
6790 if (enddir == expdir) {
6792 } else if (enddir == expdir + 1 && *expdir == '/') {
6801 if (enddir != expdir)
6803 if (*endname == 0) {
6815 while (!pending_int && (dp = readdir(dirp)) != NULL) {
6816 if (dp->d_name[0] == '.' && !matchdot)
6818 if (pmatch(start, dp->d_name)) {
6820 strcpy(enddir, dp->d_name);
6823 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6826 expmeta(p, endname);
6835 static struct strlist *
6836 msort(struct strlist *list, int len)
6838 struct strlist *p, *q = NULL;
6839 struct strlist **lpp;
6847 for (n = half; --n >= 0;) {
6851 q->next = NULL; /* terminate first half of list */
6852 q = msort(list, half); /* sort first half of list */
6853 p = msort(p, len - half); /* sort second half */
6856 #if ENABLE_LOCALE_SUPPORT
6857 if (strcoll(p->text, q->text) < 0)
6859 if (strcmp(p->text, q->text) < 0)
6883 * Sort the results of file name expansion. It calculates the number of
6884 * strings to sort and then calls msort (short for merge sort) to do the
6887 static struct strlist *
6888 expsort(struct strlist *str)
6894 for (sp = str; sp; sp = sp->next)
6896 return msort(str, len);
6900 expandmeta(struct strlist *str /*, int flag*/)
6902 static const char metachars[] ALIGN1 = {
6905 /* TODO - EXP_REDIR */
6908 struct strlist **savelastp;
6914 if (!strpbrk(str->text, metachars))
6916 savelastp = exparg.lastp;
6919 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6921 int i = strlen(str->text);
6922 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6930 if (exparg.lastp == savelastp) {
6935 *exparg.lastp = str;
6936 rmescapes(str->text, 0);
6937 exparg.lastp = &str->next;
6939 *exparg.lastp = NULL;
6940 *savelastp = sp = expsort(*savelastp);
6941 while (sp->next != NULL)
6943 exparg.lastp = &sp->next;
6950 * Perform variable substitution and command substitution on an argument,
6951 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
6952 * perform splitting and file name expansion. When arglist is NULL, perform
6953 * here document expansion.
6956 expandarg(union node *arg, struct arglist *arglist, int flag)
6961 argbackq = arg->narg.backquote;
6962 STARTSTACKSTR(expdest);
6963 ifsfirst.next = NULL;
6965 argstr(arg->narg.text, flag,
6966 /* var_str_list: */ arglist ? arglist->list : NULL);
6967 p = _STPUTC('\0', expdest);
6969 if (arglist == NULL) {
6970 return; /* here document expanded */
6972 p = grabstackstr(p);
6973 exparg.lastp = &exparg.list;
6977 if (flag & EXP_FULL) {
6978 ifsbreakup(p, &exparg);
6979 *exparg.lastp = NULL;
6980 exparg.lastp = &exparg.list;
6981 expandmeta(exparg.list /*, flag*/);
6983 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
6985 sp = stzalloc(sizeof(*sp));
6988 exparg.lastp = &sp->next;
6992 *exparg.lastp = NULL;
6994 *arglist->lastp = exparg.list;
6995 arglist->lastp = exparg.lastp;
7000 * Expand shell variables and backquotes inside a here document.
7003 expandhere(union node *arg, int fd)
7006 expandarg(arg, (struct arglist *)NULL, 0);
7007 full_write(fd, stackblock(), expdest - (char *)stackblock());
7011 * Returns true if the pattern matches the string.
7014 patmatch(char *pattern, const char *string)
7016 return pmatch(preglob(pattern, 0, 0), string);
7020 * See if a pattern matches in a case statement.
7023 casematch(union node *pattern, char *val)
7025 struct stackmark smark;
7028 setstackmark(&smark);
7029 argbackq = pattern->narg.backquote;
7030 STARTSTACKSTR(expdest);
7032 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7033 /* var_str_list: */ NULL);
7034 STACKSTRNUL(expdest);
7035 result = patmatch(stackblock(), val);
7036 popstackmark(&smark);
7041 /* ============ find_command */
7045 int (*builtin)(int, char **) FAST_FUNC;
7046 /* unsigned flags; */
7048 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7049 /* "regular" builtins always take precedence over commands,
7050 * regardless of PATH=....%builtin... position */
7051 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7052 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7055 smallint cmdtype; /* CMDxxx */
7058 /* index >= 0 for commands without path (slashes) */
7059 /* (TODO: what exactly does the value mean? PATH position?) */
7060 /* index == -1 for commands with slashes */
7061 /* index == (-2 - applet_no) for NOFORK applets */
7062 const struct builtincmd *cmd;
7063 struct funcnode *func;
7066 /* values of cmdtype */
7067 #define CMDUNKNOWN -1 /* no entry in table for command */
7068 #define CMDNORMAL 0 /* command is an executable program */
7069 #define CMDFUNCTION 1 /* command is a shell function */
7070 #define CMDBUILTIN 2 /* command is a shell builtin */
7072 /* action to find_command() */
7073 #define DO_ERR 0x01 /* prints errors */
7074 #define DO_ABS 0x02 /* checks absolute paths */
7075 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7076 #define DO_ALTPATH 0x08 /* using alternate path */
7077 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7079 static void find_command(char *, struct cmdentry *, int, const char *);
7082 /* ============ Hashing commands */
7085 * When commands are first encountered, they are entered in a hash table.
7086 * This ensures that a full path search will not have to be done for them
7087 * on each invocation.
7089 * We should investigate converting to a linear search, even though that
7090 * would make the command name "hash" a misnomer.
7094 struct tblentry *next; /* next entry in hash chain */
7095 union param param; /* definition of builtin function */
7096 smallint cmdtype; /* CMDxxx */
7097 char rehash; /* if set, cd done since entry created */
7098 char cmdname[1]; /* name of command */
7101 static struct tblentry **cmdtable;
7102 #define INIT_G_cmdtable() do { \
7103 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7106 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7110 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7114 #if ENABLE_FEATURE_SH_STANDALONE
7115 if (applet_no >= 0) {
7116 if (APPLET_IS_NOEXEC(applet_no)) {
7119 run_applet_no_and_exit(applet_no, argv);
7121 /* re-exec ourselves with the new arguments */
7122 execve(bb_busybox_exec_path, argv, envp);
7123 /* If they called chroot or otherwise made the binary no longer
7124 * executable, fall through */
7131 execve(cmd, argv, envp);
7132 } while (errno == EINTR);
7134 execve(cmd, argv, envp);
7140 if (errno == ENOEXEC) {
7144 for (ap = argv; *ap; ap++)
7146 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7148 ap[0] = cmd = (char *)DEFAULT_SHELL;
7151 while ((*ap++ = *argv++) != NULL)
7160 * Exec a program. Never returns. If you change this routine, you may
7161 * have to change the find_command routine as well.
7163 static void shellexec(char **, const char *, int) NORETURN;
7165 shellexec(char **argv, const char *path, int idx)
7171 #if ENABLE_FEATURE_SH_STANDALONE
7175 clearredir(/*drop:*/ 1);
7176 envp = listvars(VEXPORT, VUNSET, 0);
7177 if (strchr(argv[0], '/') != NULL
7178 #if ENABLE_FEATURE_SH_STANDALONE
7179 || (applet_no = find_applet_by_name(argv[0])) >= 0
7182 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7186 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7187 if (--idx < 0 && pathopt == NULL) {
7188 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7189 if (errno != ENOENT && errno != ENOTDIR)
7196 /* Map to POSIX errors */
7208 exitstatus = exerrno;
7209 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7210 argv[0], e, suppress_int));
7211 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7216 printentry(struct tblentry *cmdp)
7222 idx = cmdp->param.index;
7225 name = path_advance(&path, cmdp->cmdname);
7227 } while (--idx >= 0);
7228 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7232 * Clear out command entries. The argument specifies the first entry in
7233 * PATH which has changed.
7236 clearcmdentry(int firstchange)
7238 struct tblentry **tblp;
7239 struct tblentry **pp;
7240 struct tblentry *cmdp;
7243 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7245 while ((cmdp = *pp) != NULL) {
7246 if ((cmdp->cmdtype == CMDNORMAL &&
7247 cmdp->param.index >= firstchange)
7248 || (cmdp->cmdtype == CMDBUILTIN &&
7249 builtinloc >= firstchange)
7262 * Locate a command in the command hash table. If "add" is nonzero,
7263 * add the command to the table if it is not already present. The
7264 * variable "lastcmdentry" is set to point to the address of the link
7265 * pointing to the entry, so that delete_cmd_entry can delete the
7268 * Interrupts must be off if called with add != 0.
7270 static struct tblentry **lastcmdentry;
7272 static struct tblentry *
7273 cmdlookup(const char *name, int add)
7275 unsigned int hashval;
7277 struct tblentry *cmdp;
7278 struct tblentry **pp;
7281 hashval = (unsigned char)*p << 4;
7283 hashval += (unsigned char)*p++;
7285 pp = &cmdtable[hashval % CMDTABLESIZE];
7286 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7287 if (strcmp(cmdp->cmdname, name) == 0)
7291 if (add && cmdp == NULL) {
7292 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7294 /* + 1 - already done because
7295 * tblentry::cmdname is char[1] */);
7296 /*cmdp->next = NULL; - ckzalloc did it */
7297 cmdp->cmdtype = CMDUNKNOWN;
7298 strcpy(cmdp->cmdname, name);
7305 * Delete the command entry returned on the last lookup.
7308 delete_cmd_entry(void)
7310 struct tblentry *cmdp;
7313 cmdp = *lastcmdentry;
7314 *lastcmdentry = cmdp->next;
7315 if (cmdp->cmdtype == CMDFUNCTION)
7316 freefunc(cmdp->param.func);
7322 * Add a new command entry, replacing any existing command entry for
7323 * the same name - except special builtins.
7326 addcmdentry(char *name, struct cmdentry *entry)
7328 struct tblentry *cmdp;
7330 cmdp = cmdlookup(name, 1);
7331 if (cmdp->cmdtype == CMDFUNCTION) {
7332 freefunc(cmdp->param.func);
7334 cmdp->cmdtype = entry->cmdtype;
7335 cmdp->param = entry->u;
7339 static int FAST_FUNC
7340 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7342 struct tblentry **pp;
7343 struct tblentry *cmdp;
7345 struct cmdentry entry;
7348 if (nextopt("r") != '\0') {
7353 if (*argptr == NULL) {
7354 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7355 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7356 if (cmdp->cmdtype == CMDNORMAL)
7364 while ((name = *argptr) != NULL) {
7365 cmdp = cmdlookup(name, 0);
7367 && (cmdp->cmdtype == CMDNORMAL
7368 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7372 find_command(name, &entry, DO_ERR, pathval());
7373 if (entry.cmdtype == CMDUNKNOWN)
7381 * Called when a cd is done. Marks all commands so the next time they
7382 * are executed they will be rehashed.
7387 struct tblentry **pp;
7388 struct tblentry *cmdp;
7390 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7391 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7392 if (cmdp->cmdtype == CMDNORMAL
7393 || (cmdp->cmdtype == CMDBUILTIN
7394 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7404 * Fix command hash table when PATH changed.
7405 * Called before PATH is changed. The argument is the new value of PATH;
7406 * pathval() still returns the old value at this point.
7407 * Called with interrupts off.
7409 static void FAST_FUNC
7410 changepath(const char *new)
7418 firstchange = 9999; /* assume no change */
7424 if ((*old == '\0' && *new == ':')
7425 || (*old == ':' && *new == '\0'))
7427 old = new; /* ignore subsequent differences */
7431 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7437 if (builtinloc < 0 && idx_bltin >= 0)
7438 builtinloc = idx_bltin; /* zap builtins */
7439 if (builtinloc >= 0 && idx_bltin < 0)
7441 clearcmdentry(firstchange);
7442 builtinloc = idx_bltin;
7457 #define TENDBQUOTE 12
7474 typedef smallint token_id_t;
7476 /* first char is indicating which tokens mark the end of a list */
7477 static const char *const tokname_array[] = {
7491 #define KWDOFFSET 13
7492 /* the following are keywords */
7514 static char buf[16];
7517 //if (tok < TSEMI) return tokname_array[tok] + 1;
7518 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7523 sprintf(buf + (tok >= TSEMI), "%s%c",
7524 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7528 /* Wrapper around strcmp for qsort/bsearch/... */
7530 pstrcmp(const void *a, const void *b)
7532 return strcmp((char*) a, (*(char**) b) + 1);
7535 static const char *const *
7536 findkwd(const char *s)
7538 return bsearch(s, tokname_array + KWDOFFSET,
7539 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7540 sizeof(tokname_array[0]), pstrcmp);
7544 * Locate and print what a word is...
7547 describe_command(char *command, int describe_command_verbose)
7549 struct cmdentry entry;
7550 struct tblentry *cmdp;
7551 #if ENABLE_ASH_ALIAS
7552 const struct alias *ap;
7554 const char *path = pathval();
7556 if (describe_command_verbose) {
7560 /* First look at the keywords */
7561 if (findkwd(command)) {
7562 out1str(describe_command_verbose ? " is a shell keyword" : command);
7566 #if ENABLE_ASH_ALIAS
7567 /* Then look at the aliases */
7568 ap = lookupalias(command, 0);
7570 if (!describe_command_verbose) {
7575 out1fmt(" is an alias for %s", ap->val);
7579 /* Then check if it is a tracked alias */
7580 cmdp = cmdlookup(command, 0);
7582 entry.cmdtype = cmdp->cmdtype;
7583 entry.u = cmdp->param;
7585 /* Finally use brute force */
7586 find_command(command, &entry, DO_ABS, path);
7589 switch (entry.cmdtype) {
7591 int j = entry.u.index;
7597 p = path_advance(&path, command);
7601 if (describe_command_verbose) {
7603 (cmdp ? " a tracked alias for" : nullstr), p
7612 if (describe_command_verbose) {
7613 out1str(" is a shell function");
7620 if (describe_command_verbose) {
7621 out1fmt(" is a %sshell builtin",
7622 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7623 "special " : nullstr
7631 if (describe_command_verbose) {
7632 out1str(": not found\n");
7637 outstr("\n", stdout);
7641 static int FAST_FUNC
7642 typecmd(int argc UNUSED_PARAM, char **argv)
7648 /* type -p ... ? (we don't bother checking for 'p') */
7649 if (argv[1] && argv[1][0] == '-') {
7654 err |= describe_command(argv[i++], verbose);
7659 #if ENABLE_ASH_CMDCMD
7660 static int FAST_FUNC
7661 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7669 while ((c = nextopt("pvV")) != '\0')
7671 verify |= VERIFY_VERBOSE;
7673 verify |= VERIFY_BRIEF;
7678 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7679 if (verify && (*argptr != NULL)) {
7680 return describe_command(*argptr, verify - VERIFY_BRIEF);
7688 /* ============ eval.c */
7690 static int funcblocksize; /* size of structures in function */
7691 static int funcstringsize; /* size of strings in node */
7692 static void *funcblock; /* block to allocate function from */
7693 static char *funcstring; /* block to allocate strings from */
7695 /* flags in argument to evaltree */
7696 #define EV_EXIT 01 /* exit after evaluating tree */
7697 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7698 #define EV_BACKCMD 04 /* command executing within back quotes */
7700 static const short nodesize[N_NUMBER] = {
7701 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7702 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7703 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7704 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7705 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7706 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7707 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7708 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7709 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7710 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7711 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7712 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7713 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7714 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7715 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7716 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7717 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7718 #if ENABLE_ASH_BASH_COMPAT
7719 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7721 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7722 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7723 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7724 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7725 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7726 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7727 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7728 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7729 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7732 static void calcsize(union node *n);
7735 sizenodelist(struct nodelist *lp)
7738 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7745 calcsize(union node *n)
7749 funcblocksize += nodesize[n->type];
7752 calcsize(n->ncmd.redirect);
7753 calcsize(n->ncmd.args);
7754 calcsize(n->ncmd.assign);
7757 sizenodelist(n->npipe.cmdlist);
7762 calcsize(n->nredir.redirect);
7763 calcsize(n->nredir.n);
7770 calcsize(n->nbinary.ch2);
7771 calcsize(n->nbinary.ch1);
7774 calcsize(n->nif.elsepart);
7775 calcsize(n->nif.ifpart);
7776 calcsize(n->nif.test);
7779 funcstringsize += strlen(n->nfor.var) + 1;
7780 calcsize(n->nfor.body);
7781 calcsize(n->nfor.args);
7784 calcsize(n->ncase.cases);
7785 calcsize(n->ncase.expr);
7788 calcsize(n->nclist.body);
7789 calcsize(n->nclist.pattern);
7790 calcsize(n->nclist.next);
7794 sizenodelist(n->narg.backquote);
7795 funcstringsize += strlen(n->narg.text) + 1;
7796 calcsize(n->narg.next);
7799 #if ENABLE_ASH_BASH_COMPAT
7806 calcsize(n->nfile.fname);
7807 calcsize(n->nfile.next);
7811 calcsize(n->ndup.vname);
7812 calcsize(n->ndup.next);
7816 calcsize(n->nhere.doc);
7817 calcsize(n->nhere.next);
7820 calcsize(n->nnot.com);
7826 nodeckstrdup(char *s)
7828 char *rtn = funcstring;
7830 strcpy(funcstring, s);
7831 funcstring += strlen(s) + 1;
7835 static union node *copynode(union node *);
7837 static struct nodelist *
7838 copynodelist(struct nodelist *lp)
7840 struct nodelist *start;
7841 struct nodelist **lpp;
7846 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7847 (*lpp)->n = copynode(lp->n);
7849 lpp = &(*lpp)->next;
7856 copynode(union node *n)
7863 funcblock = (char *) funcblock + nodesize[n->type];
7867 new->ncmd.redirect = copynode(n->ncmd.redirect);
7868 new->ncmd.args = copynode(n->ncmd.args);
7869 new->ncmd.assign = copynode(n->ncmd.assign);
7872 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7873 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
7878 new->nredir.redirect = copynode(n->nredir.redirect);
7879 new->nredir.n = copynode(n->nredir.n);
7886 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7887 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7890 new->nif.elsepart = copynode(n->nif.elsepart);
7891 new->nif.ifpart = copynode(n->nif.ifpart);
7892 new->nif.test = copynode(n->nif.test);
7895 new->nfor.var = nodeckstrdup(n->nfor.var);
7896 new->nfor.body = copynode(n->nfor.body);
7897 new->nfor.args = copynode(n->nfor.args);
7900 new->ncase.cases = copynode(n->ncase.cases);
7901 new->ncase.expr = copynode(n->ncase.expr);
7904 new->nclist.body = copynode(n->nclist.body);
7905 new->nclist.pattern = copynode(n->nclist.pattern);
7906 new->nclist.next = copynode(n->nclist.next);
7910 new->narg.backquote = copynodelist(n->narg.backquote);
7911 new->narg.text = nodeckstrdup(n->narg.text);
7912 new->narg.next = copynode(n->narg.next);
7915 #if ENABLE_ASH_BASH_COMPAT
7922 new->nfile.fname = copynode(n->nfile.fname);
7923 new->nfile.fd = n->nfile.fd;
7924 new->nfile.next = copynode(n->nfile.next);
7928 new->ndup.vname = copynode(n->ndup.vname);
7929 new->ndup.dupfd = n->ndup.dupfd;
7930 new->ndup.fd = n->ndup.fd;
7931 new->ndup.next = copynode(n->ndup.next);
7935 new->nhere.doc = copynode(n->nhere.doc);
7936 new->nhere.fd = n->nhere.fd;
7937 new->nhere.next = copynode(n->nhere.next);
7940 new->nnot.com = copynode(n->nnot.com);
7943 new->type = n->type;
7948 * Make a copy of a parse tree.
7950 static struct funcnode *
7951 copyfunc(union node *n)
7956 funcblocksize = offsetof(struct funcnode, n);
7959 blocksize = funcblocksize;
7960 f = ckmalloc(blocksize + funcstringsize);
7961 funcblock = (char *) f + offsetof(struct funcnode, n);
7962 funcstring = (char *) f + blocksize;
7969 * Define a shell function.
7972 defun(char *name, union node *func)
7974 struct cmdentry entry;
7977 entry.cmdtype = CMDFUNCTION;
7978 entry.u.func = copyfunc(func);
7979 addcmdentry(name, &entry);
7983 /* Reasons for skipping commands (see comment on breakcmd routine) */
7984 #define SKIPBREAK (1 << 0)
7985 #define SKIPCONT (1 << 1)
7986 #define SKIPFUNC (1 << 2)
7987 #define SKIPFILE (1 << 3)
7988 #define SKIPEVAL (1 << 4)
7989 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
7990 static int skipcount; /* number of levels to skip */
7991 static int funcnest; /* depth of function calls */
7992 static int loopnest; /* current loop nesting level */
7994 /* Forward decl way out to parsing code - dotrap needs it */
7995 static int evalstring(char *s, int mask);
7997 /* Called to execute a trap.
7998 * Single callsite - at the end of evaltree().
7999 * If we return non-zero, exaltree raises EXEXIT exception.
8001 * Perhaps we should avoid entering new trap handlers
8002 * while we are executing a trap handler. [is it a TODO?]
8011 savestatus = exitstatus;
8015 TRACE(("dotrap entered\n"));
8016 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8023 /* non-trapped SIGINT is handled separately by raise_interrupt,
8024 * don't upset it by resetting gotsig[SIGINT-1] */
8025 if (sig == SIGINT && !t)
8028 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8032 want_exexit = evalstring(t, SKIPEVAL);
8033 exitstatus = savestatus;
8035 TRACE(("dotrap returns %d\n", want_exexit));
8040 TRACE(("dotrap returns 0\n"));
8044 /* forward declarations - evaluation is fairly recursive business... */
8045 static void evalloop(union node *, int);
8046 static void evalfor(union node *, int);
8047 static void evalcase(union node *, int);
8048 static void evalsubshell(union node *, int);
8049 static void expredir(union node *);
8050 static void evalpipe(union node *, int);
8051 static void evalcommand(union node *, int);
8052 static int evalbltin(const struct builtincmd *, int, char **);
8053 static void prehash(union node *);
8056 * Evaluate a parse tree. The value is left in the global variable
8060 evaltree(union node *n, int flags)
8062 struct jmploc *volatile savehandler = exception_handler;
8063 struct jmploc jmploc;
8065 void (*evalfn)(union node *, int);
8069 SAVE_INT(int_level);
8072 TRACE(("evaltree(NULL) called\n"));
8075 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8077 exception_handler = &jmploc;
8079 int err = setjmp(jmploc.loc);
8081 /* if it was a signal, check for trap handlers */
8082 if (exception_type == EXSIG) {
8083 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8084 exception_type, err));
8087 /* continue on the way out */
8088 TRACE(("exception %d in evaltree, propagating err=%d\n",
8089 exception_type, err));
8090 exception_handler = savehandler;
8091 longjmp(exception_handler->loc, err);
8098 out1fmt("Node type = %d\n", n->type);
8103 evaltree(n->nnot.com, EV_TESTED);
8104 status = !exitstatus;
8107 expredir(n->nredir.redirect);
8108 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8110 evaltree(n->nredir.n, flags & EV_TESTED);
8111 status = exitstatus;
8113 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8116 evalfn = evalcommand;
8118 if (eflag && !(flags & EV_TESTED))
8130 evalfn = evalsubshell;
8143 #error NAND + 1 != NOR
8145 #if NOR + 1 != NSEMI
8146 #error NOR + 1 != NSEMI
8148 unsigned is_or = n->type - NAND;
8151 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8153 if (!exitstatus == is_or)
8166 evaltree(n->nif.test, EV_TESTED);
8169 if (exitstatus == 0) {
8173 if (n->nif.elsepart) {
8174 n = n->nif.elsepart;
8179 defun(n->narg.text, n->narg.next);
8183 exitstatus = status;
8188 exception_handler = savehandler;
8190 if (checkexit & exitstatus)
8191 evalskip |= SKIPEVAL;
8192 else if (pending_sig && dotrap())
8195 if (flags & EV_EXIT) {
8197 raise_exception(EXEXIT);
8200 RESTORE_INT(int_level);
8201 TRACE(("leaving evaltree (no interrupts)\n"));
8204 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8207 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8210 evalloop(union node *n, int flags)
8220 evaltree(n->nbinary.ch1, EV_TESTED);
8223 if (evalskip == SKIPCONT && --skipcount <= 0) {
8227 if (evalskip == SKIPBREAK && --skipcount <= 0)
8232 if (n->type != NWHILE)
8236 evaltree(n->nbinary.ch2, flags);
8237 status = exitstatus;
8242 exitstatus = status;
8246 evalfor(union node *n, int flags)
8248 struct arglist arglist;
8251 struct stackmark smark;
8253 setstackmark(&smark);
8254 arglist.list = NULL;
8255 arglist.lastp = &arglist.list;
8256 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8257 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8262 *arglist.lastp = NULL;
8267 for (sp = arglist.list; sp; sp = sp->next) {
8268 setvar(n->nfor.var, sp->text, 0);
8269 evaltree(n->nfor.body, flags);
8271 if (evalskip == SKIPCONT && --skipcount <= 0) {
8275 if (evalskip == SKIPBREAK && --skipcount <= 0)
8282 popstackmark(&smark);
8286 evalcase(union node *n, int flags)
8290 struct arglist arglist;
8291 struct stackmark smark;
8293 setstackmark(&smark);
8294 arglist.list = NULL;
8295 arglist.lastp = &arglist.list;
8296 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8298 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8299 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8300 if (casematch(patp, arglist.list->text)) {
8301 if (evalskip == 0) {
8302 evaltree(cp->nclist.body, flags);
8309 popstackmark(&smark);
8313 * Kick off a subshell to evaluate a tree.
8316 evalsubshell(union node *n, int flags)
8319 int backgnd = (n->type == NBACKGND);
8322 expredir(n->nredir.redirect);
8323 if (!backgnd && flags & EV_EXIT && !trap[0])
8326 jp = makejob(/*n,*/ 1);
8327 if (forkshell(jp, n, backgnd) == 0) {
8331 flags &=~ EV_TESTED;
8333 redirect(n->nredir.redirect, 0);
8334 evaltreenr(n->nredir.n, flags);
8339 status = waitforjob(jp);
8340 exitstatus = status;
8345 * Compute the names of the files in a redirection list.
8347 static void fixredir(union node *, const char *, int);
8349 expredir(union node *n)
8353 for (redir = n; redir; redir = redir->nfile.next) {
8357 fn.lastp = &fn.list;
8358 switch (redir->type) {
8362 #if ENABLE_ASH_BASH_COMPAT
8367 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8368 #if ENABLE_ASH_BASH_COMPAT
8371 redir->nfile.expfname = fn.list->text;
8374 case NTOFD: /* >& */
8375 if (redir->ndup.vname) {
8376 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8377 if (fn.list == NULL)
8378 ash_msg_and_raise_error("redir error");
8379 #if ENABLE_ASH_BASH_COMPAT
8380 //FIXME: we used expandarg with different args!
8381 if (!isdigit_str9(fn.list->text)) {
8382 /* >&file, not >&fd */
8383 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8384 ash_msg_and_raise_error("redir error");
8386 goto store_expfname;
8389 fixredir(redir, fn.list->text, 1);
8397 * Evaluate a pipeline. All the processes in the pipeline are children
8398 * of the process creating the pipeline. (This differs from some versions
8399 * of the shell, which make the last process in a pipeline the parent
8403 evalpipe(union node *n, int flags)
8406 struct nodelist *lp;
8411 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8413 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8417 jp = makejob(/*n,*/ pipelen);
8419 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8423 if (pipe(pip) < 0) {
8425 ash_msg_and_raise_error("pipe call failed");
8428 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8441 evaltreenr(lp->n, flags);
8447 /* Don't want to trigger debugging */
8451 if (n->npipe.pipe_backgnd == 0) {
8452 exitstatus = waitforjob(jp);
8453 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8459 * Controls whether the shell is interactive or not.
8462 setinteractive(int on)
8464 static smallint is_interactive;
8466 if (++on == is_interactive)
8468 is_interactive = on;
8472 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8473 if (is_interactive > 1) {
8474 /* Looks like they want an interactive shell */
8475 static smallint did_banner;
8480 "%s built-in shell (ash)\n"
8481 "Enter 'help' for a list of built-in commands."
8496 setinteractive(iflag);
8498 #if ENABLE_FEATURE_EDITING_VI
8500 line_input_state->flags |= VI_MODE;
8502 line_input_state->flags &= ~VI_MODE;
8504 viflag = 0; /* forcibly keep the option off */
8508 static struct localvar *localvars;
8511 * Called after a function returns.
8512 * Interrupts must be off.
8517 struct localvar *lvp;
8520 while ((lvp = localvars) != NULL) {
8521 localvars = lvp->next;
8523 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8524 if (vp == NULL) { /* $- saved */
8525 memcpy(optlist, lvp->text, sizeof(optlist));
8526 free((char*)lvp->text);
8528 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8532 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8533 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8534 free((char*)vp->text);
8535 vp->flags = lvp->flags;
8536 vp->text = lvp->text;
8543 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8545 volatile struct shparam saveparam;
8546 struct localvar *volatile savelocalvars;
8547 struct jmploc *volatile savehandler;
8548 struct jmploc jmploc;
8551 saveparam = shellparam;
8552 savelocalvars = localvars;
8553 e = setjmp(jmploc.loc);
8558 savehandler = exception_handler;
8559 exception_handler = &jmploc;
8561 shellparam.malloced = 0;
8565 shellparam.nparam = argc - 1;
8566 shellparam.p = argv + 1;
8567 #if ENABLE_ASH_GETOPTS
8568 shellparam.optind = 1;
8569 shellparam.optoff = -1;
8571 evaltree(&func->n, flags & EV_TESTED);
8577 localvars = savelocalvars;
8578 freeparam(&shellparam);
8579 shellparam = saveparam;
8580 exception_handler = savehandler;
8582 evalskip &= ~SKIPFUNC;
8586 #if ENABLE_ASH_CMDCMD
8588 parse_command_args(char **argv, const char **path)
8601 if (c == '-' && !*cp) {
8608 *path = bb_default_path;
8611 /* run 'typecmd' for other options */
8622 * Make a variable a local variable. When a variable is made local, it's
8623 * value and flags are saved in a localvar structure. The saved values
8624 * will be restored when the shell function returns. We handle the name
8625 * "-" as a special case.
8630 struct localvar *lvp;
8635 lvp = ckzalloc(sizeof(struct localvar));
8636 if (LONE_DASH(name)) {
8638 p = ckmalloc(sizeof(optlist));
8639 lvp->text = memcpy(p, optlist, sizeof(optlist));
8644 vpp = hashvar(name);
8645 vp = *findvar(vpp, name);
8646 eq = strchr(name, '=');
8649 setvareq(name, VSTRFIXED);
8651 setvar(name, NULL, VSTRFIXED);
8652 vp = *vpp; /* the new variable */
8653 lvp->flags = VUNSET;
8655 lvp->text = vp->text;
8656 lvp->flags = vp->flags;
8657 vp->flags |= VSTRFIXED|VTEXTFIXED;
8663 lvp->next = localvars;
8669 * The "local" command.
8671 static int FAST_FUNC
8672 localcmd(int argc UNUSED_PARAM, char **argv)
8677 while ((name = *argv++) != NULL) {
8683 static int FAST_FUNC
8684 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8689 static int FAST_FUNC
8690 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8695 static int FAST_FUNC
8696 execcmd(int argc UNUSED_PARAM, char **argv)
8699 iflag = 0; /* exit on error */
8702 shellexec(argv + 1, pathval(), 0);
8708 * The return command.
8710 static int FAST_FUNC
8711 returncmd(int argc UNUSED_PARAM, char **argv)
8714 * If called outside a function, do what ksh does;
8715 * skip the rest of the file.
8717 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8718 return argv[1] ? number(argv[1]) : exitstatus;
8721 /* Forward declarations for builtintab[] */
8722 static int breakcmd(int, char **) FAST_FUNC;
8723 static int dotcmd(int, char **) FAST_FUNC;
8724 static int evalcmd(int, char **) FAST_FUNC;
8725 static int exitcmd(int, char **) FAST_FUNC;
8726 static int exportcmd(int, char **) FAST_FUNC;
8727 #if ENABLE_ASH_GETOPTS
8728 static int getoptscmd(int, char **) FAST_FUNC;
8730 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8731 static int helpcmd(int, char **) FAST_FUNC;
8733 #if ENABLE_SH_MATH_SUPPORT
8734 static int letcmd(int, char **) FAST_FUNC;
8736 static int readcmd(int, char **) FAST_FUNC;
8737 static int setcmd(int, char **) FAST_FUNC;
8738 static int shiftcmd(int, char **) FAST_FUNC;
8739 static int timescmd(int, char **) FAST_FUNC;
8740 static int trapcmd(int, char **) FAST_FUNC;
8741 static int umaskcmd(int, char **) FAST_FUNC;
8742 static int unsetcmd(int, char **) FAST_FUNC;
8743 static int ulimitcmd(int, char **) FAST_FUNC;
8745 #define BUILTIN_NOSPEC "0"
8746 #define BUILTIN_SPECIAL "1"
8747 #define BUILTIN_REGULAR "2"
8748 #define BUILTIN_SPEC_REG "3"
8749 #define BUILTIN_ASSIGN "4"
8750 #define BUILTIN_SPEC_ASSG "5"
8751 #define BUILTIN_REG_ASSG "6"
8752 #define BUILTIN_SPEC_REG_ASSG "7"
8754 /* Stubs for calling non-FAST_FUNC's */
8755 #if ENABLE_ASH_BUILTIN_ECHO
8756 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8758 #if ENABLE_ASH_BUILTIN_PRINTF
8759 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8761 #if ENABLE_ASH_BUILTIN_TEST
8762 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8765 /* Keep these in proper order since it is searched via bsearch() */
8766 static const struct builtincmd builtintab[] = {
8767 { BUILTIN_SPEC_REG ".", dotcmd },
8768 { BUILTIN_SPEC_REG ":", truecmd },
8769 #if ENABLE_ASH_BUILTIN_TEST
8770 { BUILTIN_REGULAR "[", testcmd },
8771 #if ENABLE_ASH_BASH_COMPAT
8772 { BUILTIN_REGULAR "[[", testcmd },
8775 #if ENABLE_ASH_ALIAS
8776 { BUILTIN_REG_ASSG "alias", aliascmd },
8779 { BUILTIN_REGULAR "bg", fg_bgcmd },
8781 { BUILTIN_SPEC_REG "break", breakcmd },
8782 { BUILTIN_REGULAR "cd", cdcmd },
8783 { BUILTIN_NOSPEC "chdir", cdcmd },
8784 #if ENABLE_ASH_CMDCMD
8785 { BUILTIN_REGULAR "command", commandcmd },
8787 { BUILTIN_SPEC_REG "continue", breakcmd },
8788 #if ENABLE_ASH_BUILTIN_ECHO
8789 { BUILTIN_REGULAR "echo", echocmd },
8791 { BUILTIN_SPEC_REG "eval", evalcmd },
8792 { BUILTIN_SPEC_REG "exec", execcmd },
8793 { BUILTIN_SPEC_REG "exit", exitcmd },
8794 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8795 { BUILTIN_REGULAR "false", falsecmd },
8797 { BUILTIN_REGULAR "fg", fg_bgcmd },
8799 #if ENABLE_ASH_GETOPTS
8800 { BUILTIN_REGULAR "getopts", getoptscmd },
8802 { BUILTIN_NOSPEC "hash", hashcmd },
8803 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8804 { BUILTIN_NOSPEC "help", helpcmd },
8807 { BUILTIN_REGULAR "jobs", jobscmd },
8808 { BUILTIN_REGULAR "kill", killcmd },
8810 #if ENABLE_SH_MATH_SUPPORT
8811 { BUILTIN_NOSPEC "let", letcmd },
8813 { BUILTIN_ASSIGN "local", localcmd },
8814 #if ENABLE_ASH_BUILTIN_PRINTF
8815 { BUILTIN_REGULAR "printf", printfcmd },
8817 { BUILTIN_NOSPEC "pwd", pwdcmd },
8818 { BUILTIN_REGULAR "read", readcmd },
8819 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8820 { BUILTIN_SPEC_REG "return", returncmd },
8821 { BUILTIN_SPEC_REG "set", setcmd },
8822 { BUILTIN_SPEC_REG "shift", shiftcmd },
8823 { BUILTIN_SPEC_REG "source", dotcmd },
8824 #if ENABLE_ASH_BUILTIN_TEST
8825 { BUILTIN_REGULAR "test", testcmd },
8827 { BUILTIN_SPEC_REG "times", timescmd },
8828 { BUILTIN_SPEC_REG "trap", trapcmd },
8829 { BUILTIN_REGULAR "true", truecmd },
8830 { BUILTIN_NOSPEC "type", typecmd },
8831 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8832 { BUILTIN_REGULAR "umask", umaskcmd },
8833 #if ENABLE_ASH_ALIAS
8834 { BUILTIN_REGULAR "unalias", unaliascmd },
8836 { BUILTIN_SPEC_REG "unset", unsetcmd },
8837 { BUILTIN_REGULAR "wait", waitcmd },
8840 /* Should match the above table! */
8841 #define COMMANDCMD (builtintab + \
8843 1 * ENABLE_ASH_BUILTIN_TEST + \
8844 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8845 1 * ENABLE_ASH_ALIAS + \
8846 1 * ENABLE_ASH_JOB_CONTROL + \
8848 #define EXECCMD (builtintab + \
8850 1 * ENABLE_ASH_BUILTIN_TEST + \
8851 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8852 1 * ENABLE_ASH_ALIAS + \
8853 1 * ENABLE_ASH_JOB_CONTROL + \
8855 1 * ENABLE_ASH_CMDCMD + \
8857 ENABLE_ASH_BUILTIN_ECHO + \
8861 * Search the table of builtin commands.
8863 static struct builtincmd *
8864 find_builtin(const char *name)
8866 struct builtincmd *bp;
8869 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8876 * Execute a simple command.
8879 isassignment(const char *p)
8881 const char *q = endofname(p);
8886 static int FAST_FUNC
8887 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8889 /* Preserve exitstatus of a previous possible redirection
8890 * as POSIX mandates */
8891 return back_exitstatus;
8894 evalcommand(union node *cmd, int flags)
8896 static const struct builtincmd null_bltin = {
8897 "\0\0", bltincmd /* why three NULs? */
8899 struct stackmark smark;
8901 struct arglist arglist;
8902 struct arglist varlist;
8905 const struct strlist *sp;
8906 struct cmdentry cmdentry;
8913 struct builtincmd *bcmd;
8914 smallint cmd_is_exec;
8915 smallint pseudovarflag = 0;
8917 /* First expand the arguments. */
8918 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8919 setstackmark(&smark);
8920 back_exitstatus = 0;
8922 cmdentry.cmdtype = CMDBUILTIN;
8923 cmdentry.u.cmd = &null_bltin;
8924 varlist.lastp = &varlist.list;
8925 *varlist.lastp = NULL;
8926 arglist.lastp = &arglist.list;
8927 *arglist.lastp = NULL;
8930 if (cmd->ncmd.args) {
8931 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8932 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8935 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8936 struct strlist **spp;
8938 spp = arglist.lastp;
8939 if (pseudovarflag && isassignment(argp->narg.text))
8940 expandarg(argp, &arglist, EXP_VARTILDE);
8942 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8944 for (sp = *spp; sp; sp = sp->next)
8948 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
8949 for (sp = arglist.list; sp; sp = sp->next) {
8950 TRACE(("evalcommand arg: %s\n", sp->text));
8951 *nargv++ = sp->text;
8956 if (iflag && funcnest == 0 && argc > 0)
8957 lastarg = nargv[-1];
8960 expredir(cmd->ncmd.redirect);
8961 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
8964 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
8965 struct strlist **spp;
8968 spp = varlist.lastp;
8969 expandarg(argp, &varlist, EXP_VARTILDE);
8972 * Modify the command lookup path, if a PATH= assignment
8976 if (varequal(p, path))
8980 /* Print the command if xflag is set. */
8983 const char *p = " %s";
8986 fdprintf(preverrout_fd, p, expandstr(ps4val()));
8989 for (n = 0; n < 2; n++) {
8991 fdprintf(preverrout_fd, p, sp->text);
8999 safe_write(preverrout_fd, "\n", 1);
9005 /* Now locate the command. */
9007 const char *oldpath;
9008 int cmd_flag = DO_ERR;
9013 find_command(argv[0], &cmdentry, cmd_flag, path);
9014 if (cmdentry.cmdtype == CMDUNKNOWN) {
9020 /* implement bltin and command here */
9021 if (cmdentry.cmdtype != CMDBUILTIN)
9024 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9025 if (cmdentry.u.cmd == EXECCMD)
9027 #if ENABLE_ASH_CMDCMD
9028 if (cmdentry.u.cmd == COMMANDCMD) {
9030 nargv = parse_command_args(argv, &path);
9033 argc -= nargv - argv;
9035 cmd_flag |= DO_NOFUNC;
9043 /* We have a redirection error. */
9045 raise_exception(EXERROR);
9047 exitstatus = status;
9051 /* Execute the command. */
9052 switch (cmdentry.cmdtype) {
9055 #if ENABLE_FEATURE_SH_NOFORK
9056 /* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9057 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
9059 /* find_command() encodes applet_no as (-2 - applet_no) */
9060 int applet_no = (- cmdentry.u.index - 2);
9061 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9062 listsetvar(varlist.list, VEXPORT|VSTACK);
9063 /* run <applet>_main() */
9064 exitstatus = run_nofork_applet(applet_no, argv);
9069 /* Fork off a child process if necessary. */
9070 if (!(flags & EV_EXIT) || trap[0]) {
9072 jp = makejob(/*cmd,*/ 1);
9073 if (forkshell(jp, cmd, FORK_FG) != 0) {
9074 exitstatus = waitforjob(jp);
9076 TRACE(("forked child exited with %d\n", exitstatus));
9081 listsetvar(varlist.list, VEXPORT|VSTACK);
9082 shellexec(argv, path, cmdentry.u.index);
9086 cmdenviron = varlist.list;
9088 struct strlist *list = cmdenviron;
9090 if (spclbltin > 0 || argc == 0) {
9092 if (cmd_is_exec && argc > 1)
9095 listsetvar(list, i);
9097 /* Tight loop with builtins only:
9098 * "while kill -0 $child; do true; done"
9099 * will never exit even if $child died, unless we do this
9100 * to reap the zombie and make kill detect that it's gone: */
9101 dowait(DOWAIT_NONBLOCK, NULL);
9103 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9105 int i = exception_type;
9110 exit_status = 128 + SIGINT;
9112 exit_status = 128 + pending_sig;
9113 exitstatus = exit_status;
9114 if (i == EXINT || spclbltin > 0) {
9116 longjmp(exception_handler->loc, 1);
9123 listsetvar(varlist.list, 0);
9124 /* See above for the rationale */
9125 dowait(DOWAIT_NONBLOCK, NULL);
9126 if (evalfun(cmdentry.u.func, argc, argv, flags))
9132 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9134 /* dsl: I think this is intended to be used to support
9135 * '_' in 'vi' command mode during line editing...
9136 * However I implemented that within libedit itself.
9138 setvar("_", lastarg, 0);
9140 popstackmark(&smark);
9144 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9146 char *volatile savecmdname;
9147 struct jmploc *volatile savehandler;
9148 struct jmploc jmploc;
9151 savecmdname = commandname;
9152 i = setjmp(jmploc.loc);
9155 savehandler = exception_handler;
9156 exception_handler = &jmploc;
9157 commandname = argv[0];
9159 optptr = NULL; /* initialize nextopt */
9160 exitstatus = (*cmd->builtin)(argc, argv);
9161 flush_stdout_stderr();
9163 exitstatus |= ferror(stdout);
9165 commandname = savecmdname;
9166 exception_handler = savehandler;
9172 goodname(const char *p)
9174 return !*endofname(p);
9179 * Search for a command. This is called before we fork so that the
9180 * location of the command will be available in the parent as well as
9181 * the child. The check for "goodname" is an overly conservative
9182 * check that the name will not be subject to expansion.
9185 prehash(union node *n)
9187 struct cmdentry entry;
9189 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9190 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9194 /* ============ Builtin commands
9196 * Builtin commands whose functions are closely tied to evaluation
9197 * are implemented here.
9201 * Handle break and continue commands. Break, continue, and return are
9202 * all handled by setting the evalskip flag. The evaluation routines
9203 * above all check this flag, and if it is set they start skipping
9204 * commands rather than executing them. The variable skipcount is
9205 * the number of loops to break/continue, or the number of function
9206 * levels to return. (The latter is always 1.) It should probably
9207 * be an error to break out of more loops than exist, but it isn't
9208 * in the standard shell so we don't make it one here.
9210 static int FAST_FUNC
9211 breakcmd(int argc UNUSED_PARAM, char **argv)
9213 int n = argv[1] ? number(argv[1]) : 1;
9216 ash_msg_and_raise_error(msg_illnum, argv[1]);
9220 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9227 /* ============ input.c
9229 * This implements the input routines used by the parser.
9233 INPUT_PUSH_FILE = 1,
9234 INPUT_NOFILE_OK = 2,
9237 static smallint checkkwd;
9238 /* values of checkkwd variable */
9239 #define CHKALIAS 0x1
9244 * Push a string back onto the input at this current parsefile level.
9245 * We handle aliases this way.
9247 #if !ENABLE_ASH_ALIAS
9248 #define pushstring(s, ap) pushstring(s)
9251 pushstring(char *s, struct alias *ap)
9258 if (g_parsefile->strpush) {
9259 sp = ckzalloc(sizeof(*sp));
9260 sp->prev = g_parsefile->strpush;
9262 sp = &(g_parsefile->basestrpush);
9264 g_parsefile->strpush = sp;
9265 sp->prev_string = g_parsefile->next_to_pgetc;
9266 sp->prev_left_in_line = g_parsefile->left_in_line;
9267 #if ENABLE_ASH_ALIAS
9270 ap->flag |= ALIASINUSE;
9274 g_parsefile->next_to_pgetc = s;
9275 g_parsefile->left_in_line = len;
9282 struct strpush *sp = g_parsefile->strpush;
9285 #if ENABLE_ASH_ALIAS
9287 if (g_parsefile->next_to_pgetc[-1] == ' '
9288 || g_parsefile->next_to_pgetc[-1] == '\t'
9290 checkkwd |= CHKALIAS;
9292 if (sp->string != sp->ap->val) {
9295 sp->ap->flag &= ~ALIASINUSE;
9296 if (sp->ap->flag & ALIASDEAD) {
9297 unalias(sp->ap->name);
9301 g_parsefile->next_to_pgetc = sp->prev_string;
9302 g_parsefile->left_in_line = sp->prev_left_in_line;
9303 g_parsefile->strpush = sp->prev;
9304 if (sp != &(g_parsefile->basestrpush))
9309 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9310 //it peeks whether it is &>, and then pushes back both chars.
9311 //This function needs to save last *next_to_pgetc to buf[0]
9312 //to make two pungetc() reliable. Currently,
9313 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9318 char *buf = g_parsefile->buf;
9320 g_parsefile->next_to_pgetc = buf;
9321 #if ENABLE_FEATURE_EDITING
9323 if (!iflag || g_parsefile->fd != STDIN_FILENO)
9324 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9326 #if ENABLE_FEATURE_TAB_COMPLETION
9327 line_input_state->path_lookup = pathval();
9329 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9331 /* Ctrl+C pressed */
9340 if (nr < 0 && errno == 0) {
9341 /* Ctrl+D pressed */
9346 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9350 /* nonblock_safe_read() handles this problem */
9352 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9353 int flags = fcntl(0, F_GETFL);
9354 if (flags >= 0 && (flags & O_NONBLOCK)) {
9355 flags &= ~O_NONBLOCK;
9356 if (fcntl(0, F_SETFL, flags) >= 0) {
9357 out2str("sh: turning off NDELAY mode\n");
9368 * Refill the input buffer and return the next input character:
9370 * 1) If a string was pushed back on the input, pop it;
9371 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9372 * or we are reading from a string so we can't refill the buffer,
9374 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9375 * 4) Process input up to the next newline, deleting nul characters.
9377 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9378 #define pgetc_debug(...) ((void)0)
9380 * NB: due to SIT(c) internals (syntax_index_table[] vector),
9381 * pgetc() and related functions must return chars SIGN-EXTENDED into ints,
9382 * not zero-extended. Seems fragile to me. Affects only !USE_SIT_FUNCTION case,
9383 * so we can fix it by ditching !USE_SIT_FUNCTION if Unicode requires that.
9391 while (g_parsefile->strpush) {
9392 #if ENABLE_ASH_ALIAS
9393 if (g_parsefile->left_in_line == -1
9394 && g_parsefile->strpush->ap
9395 && g_parsefile->next_to_pgetc[-1] != ' '
9396 && g_parsefile->next_to_pgetc[-1] != '\t'
9398 pgetc_debug("preadbuffer PEOA");
9403 /* try "pgetc" now: */
9404 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9405 g_parsefile->left_in_line,
9406 g_parsefile->next_to_pgetc,
9407 g_parsefile->next_to_pgetc);
9408 if (--g_parsefile->left_in_line >= 0)
9409 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9411 /* on both branches above g_parsefile->left_in_line < 0.
9412 * "pgetc" needs refilling.
9415 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9416 * pungetc() may increment it a few times.
9417 * Assuming it won't increment it to less than -90.
9419 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9420 pgetc_debug("preadbuffer PEOF1");
9421 /* even in failure keep left_in_line and next_to_pgetc
9422 * in lock step, for correct multi-layer pungetc.
9423 * left_in_line was decremented before preadbuffer(),
9424 * must inc next_to_pgetc: */
9425 g_parsefile->next_to_pgetc++;
9429 more = g_parsefile->left_in_buffer;
9431 flush_stdout_stderr();
9435 /* don't try reading again */
9436 g_parsefile->left_in_line = -99;
9437 pgetc_debug("preadbuffer PEOF2");
9438 g_parsefile->next_to_pgetc++;
9443 /* Find out where's the end of line.
9444 * Set g_parsefile->left_in_line
9445 * and g_parsefile->left_in_buffer acordingly.
9446 * NUL chars are deleted.
9448 q = g_parsefile->next_to_pgetc;
9456 memmove(q, q + 1, more);
9460 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9466 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9467 if (g_parsefile->left_in_line < 0)
9472 g_parsefile->left_in_buffer = more;
9477 out2str(g_parsefile->next_to_pgetc);
9481 pgetc_debug("preadbuffer at %d:%p'%s'",
9482 g_parsefile->left_in_line,
9483 g_parsefile->next_to_pgetc,
9484 g_parsefile->next_to_pgetc);
9485 return signed_char2int(*g_parsefile->next_to_pgetc++);
9488 #define pgetc_as_macro() \
9489 (--g_parsefile->left_in_line >= 0 \
9490 ? signed_char2int(*g_parsefile->next_to_pgetc++) \
9497 pgetc_debug("pgetc_fast at %d:%p'%s'",
9498 g_parsefile->left_in_line,
9499 g_parsefile->next_to_pgetc,
9500 g_parsefile->next_to_pgetc);
9501 return pgetc_as_macro();
9504 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9505 #define pgetc_fast() pgetc()
9507 #define pgetc_fast() pgetc_as_macro()
9511 * Same as pgetc(), but ignores PEOA.
9513 #if ENABLE_ASH_ALIAS
9519 pgetc_debug("pgetc_fast at %d:%p'%s'",
9520 g_parsefile->left_in_line,
9521 g_parsefile->next_to_pgetc,
9522 g_parsefile->next_to_pgetc);
9524 } while (c == PEOA);
9528 #define pgetc2() pgetc()
9532 * Read a line from the script.
9535 pfgets(char *line, int len)
9541 while (--nleft > 0) {
9557 * Undo the last call to pgetc. Only one character may be pushed back.
9558 * PEOF may be pushed back.
9563 g_parsefile->left_in_line++;
9564 g_parsefile->next_to_pgetc--;
9565 pgetc_debug("pushed back to %d:%p'%s'",
9566 g_parsefile->left_in_line,
9567 g_parsefile->next_to_pgetc,
9568 g_parsefile->next_to_pgetc);
9572 * To handle the "." command, a stack of input files is used. Pushfile
9573 * adds a new entry to the stack and popfile restores the previous level.
9578 struct parsefile *pf;
9580 pf = ckzalloc(sizeof(*pf));
9581 pf->prev = g_parsefile;
9583 /*pf->strpush = NULL; - ckzalloc did it */
9584 /*pf->basestrpush.prev = NULL;*/
9591 struct parsefile *pf = g_parsefile;
9599 g_parsefile = pf->prev;
9605 * Return to top level.
9610 while (g_parsefile != &basepf)
9615 * Close the file(s) that the shell is reading commands from. Called
9616 * after a fork is done.
9622 if (g_parsefile->fd > 0) {
9623 close(g_parsefile->fd);
9624 g_parsefile->fd = 0;
9629 * Like setinputfile, but takes an open file descriptor. Call this with
9633 setinputfd(int fd, int push)
9635 close_on_exec_on(fd);
9638 g_parsefile->buf = NULL;
9640 g_parsefile->fd = fd;
9641 if (g_parsefile->buf == NULL)
9642 g_parsefile->buf = ckmalloc(IBUFSIZ);
9643 g_parsefile->left_in_buffer = 0;
9644 g_parsefile->left_in_line = 0;
9645 g_parsefile->linno = 1;
9649 * Set the input to take input from a file. If push is set, push the
9650 * old input onto the stack first.
9653 setinputfile(const char *fname, int flags)
9659 fd = open(fname, O_RDONLY);
9661 if (flags & INPUT_NOFILE_OK)
9663 ash_msg_and_raise_error("can't open '%s'", fname);
9666 fd2 = copyfd(fd, 10);
9669 ash_msg_and_raise_error("out of file descriptors");
9672 setinputfd(fd, flags & INPUT_PUSH_FILE);
9679 * Like setinputfile, but takes input from a string.
9682 setinputstring(char *string)
9686 g_parsefile->next_to_pgetc = string;
9687 g_parsefile->left_in_line = strlen(string);
9688 g_parsefile->buf = NULL;
9689 g_parsefile->linno = 1;
9694 /* ============ mail.c
9696 * Routines to check for mail.
9701 #define MAXMBOXES 10
9703 /* times of mailboxes */
9704 static time_t mailtime[MAXMBOXES];
9705 /* Set if MAIL or MAILPATH is changed. */
9706 static smallint mail_var_path_changed;
9709 * Print appropriate message(s) if mail has arrived.
9710 * If mail_var_path_changed is set,
9711 * then the value of MAIL has mail_var_path_changed,
9712 * so we just update the values.
9721 struct stackmark smark;
9724 setstackmark(&smark);
9725 mpath = mpathset() ? mpathval() : mailval();
9726 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9727 p = path_advance(&mpath, nullstr);
9732 for (q = p; *q; q++)
9738 q[-1] = '\0'; /* delete trailing '/' */
9739 if (stat(p, &statb) < 0) {
9743 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9746 pathopt ? pathopt : "you have mail"
9749 *mtp = statb.st_mtime;
9751 mail_var_path_changed = 0;
9752 popstackmark(&smark);
9755 static void FAST_FUNC
9756 changemail(const char *val UNUSED_PARAM)
9758 mail_var_path_changed = 1;
9761 #endif /* ASH_MAIL */
9764 /* ============ ??? */
9767 * Set the shell parameters.
9770 setparam(char **argv)
9776 for (nparam = 0; argv[nparam]; nparam++)
9778 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9780 *ap++ = ckstrdup(*argv++);
9783 freeparam(&shellparam);
9784 shellparam.malloced = 1;
9785 shellparam.nparam = nparam;
9786 shellparam.p = newparam;
9787 #if ENABLE_ASH_GETOPTS
9788 shellparam.optind = 1;
9789 shellparam.optoff = -1;
9794 * Process shell options. The global variable argptr contains a pointer
9795 * to the argument list; we advance it past the options.
9797 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9798 * For a non-interactive shell, an error condition encountered
9799 * by a special built-in ... shall cause the shell to write a diagnostic message
9800 * to standard error and exit as shown in the following table:
9801 * Error Special Built-In
9803 * Utility syntax error (option or operand error) Shall exit
9805 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9806 * we see that bash does not do that (set "finishes" with error code 1 instead,
9807 * and shell continues), and people rely on this behavior!
9809 * set -o barfoo 2>/dev/null
9812 * Oh well. Let's mimic that.
9815 plus_minus_o(char *name, int val)
9820 for (i = 0; i < NOPTS; i++) {
9821 if (strcmp(name, optnames(i)) == 0) {
9826 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9829 for (i = 0; i < NOPTS; i++) {
9831 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9833 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9839 setoption(int flag, int val)
9843 for (i = 0; i < NOPTS; i++) {
9844 if (optletters(i) == flag) {
9849 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9853 options(int cmdline)
9861 while ((p = *argptr) != NULL) {
9863 if (c != '-' && c != '+')
9866 val = 0; /* val = 0 if c == '+' */
9869 if (p[0] == '\0' || LONE_DASH(p)) {
9871 /* "-" means turn off -x and -v */
9874 /* "--" means reset params */
9875 else if (*argptr == NULL)
9878 break; /* "-" or "--" terminates options */
9881 /* first char was + or - */
9882 while ((c = *p++) != '\0') {
9883 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9884 if (c == 'c' && cmdline) {
9885 minusc = p; /* command is after shell args */
9886 } else if (c == 'o') {
9887 if (plus_minus_o(*argptr, val)) {
9888 /* it already printed err message */
9889 return 1; /* error */
9893 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9895 /* bash does not accept +-login, we also won't */
9896 } else if (cmdline && val && (c == '-')) { /* long options */
9897 if (strcmp(p, "login") == 0)
9909 * The shift builtin command.
9911 static int FAST_FUNC
9912 shiftcmd(int argc UNUSED_PARAM, char **argv)
9919 n = number(argv[1]);
9920 if (n > shellparam.nparam)
9921 n = 0; /* bash compat, was = shellparam.nparam; */
9923 shellparam.nparam -= n;
9924 for (ap1 = shellparam.p; --n >= 0; ap1++) {
9925 if (shellparam.malloced)
9929 while ((*ap2++ = *ap1++) != NULL)
9931 #if ENABLE_ASH_GETOPTS
9932 shellparam.optind = 1;
9933 shellparam.optoff = -1;
9940 * POSIX requires that 'set' (but not export or readonly) output the
9941 * variables in lexicographic order - by the locale's collating order (sigh).
9942 * Maybe we could keep them in an ordered balanced binary tree
9943 * instead of hashed lists.
9944 * For now just roll 'em through qsort for printing...
9947 showvars(const char *sep_prefix, int on, int off)
9952 ep = listvars(on, off, &epend);
9953 qsort(ep, epend - ep, sizeof(char *), vpcmp);
9955 sep = *sep_prefix ? " " : sep_prefix;
9957 for (; ep < epend; ep++) {
9961 p = strchrnul(*ep, '=');
9964 q = single_quote(++p);
9965 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
9971 * The set command builtin.
9973 static int FAST_FUNC
9974 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9979 return showvars(nullstr, 0, VUNSET);
9982 if (!options(0)) { /* if no parse error... */
9985 if (*argptr != NULL) {
9993 #if ENABLE_ASH_RANDOM_SUPPORT
9994 static void FAST_FUNC
9995 change_random(const char *value)
9997 /* Galois LFSR parameter */
9998 /* Taps at 32 31 29 1: */
9999 enum { MASK = 0x8000000b };
10000 /* Another example - taps at 32 31 30 10: */
10001 /* MASK = 0x00400007 */
10003 if (value == NULL) {
10004 /* "get", generate */
10007 /* LCG has period of 2^32 and alternating lowest bit */
10008 random_LCG = 1664525 * random_LCG + 1013904223;
10009 /* Galois LFSR has period of 2^32-1 = 3 * 5 * 17 * 257 * 65537 */
10010 t = (random_galois_LFSR << 1);
10011 if (random_galois_LFSR < 0) /* if we just shifted 1 out of msb... */
10013 random_galois_LFSR = t;
10014 /* Both are weak, combining them gives better randomness
10015 * and ~2^64 period. & 0x7fff is probably bash compat
10016 * for $RANDOM range. Combining with subtraction is
10017 * just for fun. + and ^ would work equally well. */
10018 t = (t - random_LCG) & 0x7fff;
10019 /* set without recursion */
10020 setvar(vrandom.text, utoa(t), VNOFUNC);
10021 vrandom.flags &= ~VNOFUNC;
10024 random_galois_LFSR = random_LCG = strtoul(value, (char **)NULL, 10);
10029 #if ENABLE_ASH_GETOPTS
10031 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10040 if (*param_optind < 1)
10042 optnext = optfirst + *param_optind - 1;
10044 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10047 p = optnext[-1] + *optoff;
10048 if (p == NULL || *p == '\0') {
10049 /* Current word is done, advance */
10051 if (p == NULL || *p != '-' || *++p == '\0') {
10058 if (LONE_DASH(p)) /* check for "--" */
10063 for (q = optstr; *q != c;) {
10065 if (optstr[0] == ':') {
10068 err |= setvarsafe("OPTARG", s, 0);
10070 fprintf(stderr, "Illegal option -%c\n", c);
10071 unsetvar("OPTARG");
10081 if (*p == '\0' && (p = *optnext) == NULL) {
10082 if (optstr[0] == ':') {
10085 err |= setvarsafe("OPTARG", s, 0);
10088 fprintf(stderr, "No arg for -%c option\n", c);
10089 unsetvar("OPTARG");
10097 err |= setvarsafe("OPTARG", p, 0);
10100 err |= setvarsafe("OPTARG", nullstr, 0);
10102 *optoff = p ? p - *(optnext - 1) : -1;
10103 *param_optind = optnext - optfirst + 1;
10104 fmtstr(s, sizeof(s), "%d", *param_optind);
10105 err |= setvarsafe("OPTIND", s, VNOFUNC);
10108 err |= setvarsafe(optvar, s, 0);
10112 flush_stdout_stderr();
10113 raise_exception(EXERROR);
10119 * The getopts builtin. Shellparam.optnext points to the next argument
10120 * to be processed. Shellparam.optptr points to the next character to
10121 * be processed in the current argument. If shellparam.optnext is NULL,
10122 * then it's the first time getopts has been called.
10124 static int FAST_FUNC
10125 getoptscmd(int argc, char **argv)
10130 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10132 optbase = shellparam.p;
10133 if (shellparam.optind > shellparam.nparam + 1) {
10134 shellparam.optind = 1;
10135 shellparam.optoff = -1;
10138 optbase = &argv[3];
10139 if (shellparam.optind > argc - 2) {
10140 shellparam.optind = 1;
10141 shellparam.optoff = -1;
10145 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10146 &shellparam.optoff);
10148 #endif /* ASH_GETOPTS */
10151 /* ============ Shell parser */
10154 struct heredoc *next; /* next here document in list */
10155 union node *here; /* redirection node */
10156 char *eofmark; /* string indicating end of input */
10157 smallint striptabs; /* if set, strip leading tabs */
10160 static smallint tokpushback; /* last token pushed back */
10161 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10162 static smallint quoteflag; /* set if (part of) last token was quoted */
10163 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10164 static struct heredoc *heredoclist; /* list of here documents to read */
10165 static char *wordtext; /* text of last word returned by readtoken */
10166 static struct nodelist *backquotelist;
10167 static union node *redirnode;
10168 static struct heredoc *heredoc;
10171 * Called when an unexpected token is read during the parse. The argument
10172 * is the token that is expected, or -1 if more than one type of token can
10173 * occur at this point.
10175 static void raise_error_unexpected_syntax(int) NORETURN;
10177 raise_error_unexpected_syntax(int token)
10182 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
10184 sprintf(msg + l, " (expecting %s)", tokname(token));
10185 raise_error_syntax(msg);
10189 #define EOFMARKLEN 79
10191 /* parsing is heavily cross-recursive, need these forward decls */
10192 static union node *andor(void);
10193 static union node *pipeline(void);
10194 static union node *parse_command(void);
10195 static void parseheredoc(void);
10196 static char peektoken(void);
10197 static int readtoken(void);
10199 static union node *
10202 union node *n1, *n2, *n3;
10205 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10206 if (nlflag == 2 && peektoken())
10212 if (tok == TBACKGND) {
10213 if (n2->type == NPIPE) {
10214 n2->npipe.pipe_backgnd = 1;
10216 if (n2->type != NREDIR) {
10217 n3 = stzalloc(sizeof(struct nredir));
10219 /*n3->nredir.redirect = NULL; - stzalloc did it */
10222 n2->type = NBACKGND;
10228 n3 = stzalloc(sizeof(struct nbinary));
10230 n3->nbinary.ch1 = n1;
10231 n3->nbinary.ch2 = n2;
10247 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10255 pungetc(); /* push back EOF on input */
10259 raise_error_unexpected_syntax(-1);
10266 static union node *
10269 union node *n1, *n2, *n3;
10277 } else if (t == TOR) {
10283 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10285 n3 = stzalloc(sizeof(struct nbinary));
10287 n3->nbinary.ch1 = n1;
10288 n3->nbinary.ch2 = n2;
10293 static union node *
10296 union node *n1, *n2, *pipenode;
10297 struct nodelist *lp, *prev;
10301 TRACE(("pipeline: entered\n"));
10302 if (readtoken() == TNOT) {
10304 checkkwd = CHKKWD | CHKALIAS;
10307 n1 = parse_command();
10308 if (readtoken() == TPIPE) {
10309 pipenode = stzalloc(sizeof(struct npipe));
10310 pipenode->type = NPIPE;
10311 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10312 lp = stzalloc(sizeof(struct nodelist));
10313 pipenode->npipe.cmdlist = lp;
10317 lp = stzalloc(sizeof(struct nodelist));
10318 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10319 lp->n = parse_command();
10321 } while (readtoken() == TPIPE);
10327 n2 = stzalloc(sizeof(struct nnot));
10335 static union node *
10340 n = stzalloc(sizeof(struct narg));
10342 /*n->narg.next = NULL; - stzalloc did it */
10343 n->narg.text = wordtext;
10344 n->narg.backquote = backquotelist;
10349 fixredir(union node *n, const char *text, int err)
10353 TRACE(("Fix redir %s %d\n", text, err));
10355 n->ndup.vname = NULL;
10357 fd = bb_strtou(text, NULL, 10);
10358 if (!errno && fd >= 0)
10359 n->ndup.dupfd = fd;
10360 else if (LONE_DASH(text))
10361 n->ndup.dupfd = -1;
10364 raise_error_syntax("bad fd number");
10365 n->ndup.vname = makename();
10370 * Returns true if the text contains nothing to expand (no dollar signs
10374 noexpand(const char *text)
10380 while ((c = *p++) != '\0') {
10381 if (c == CTLQUOTEMARK)
10385 else if (SIT((signed char)c, BASESYNTAX) == CCTL)
10394 union node *n = redirnode;
10396 if (readtoken() != TWORD)
10397 raise_error_unexpected_syntax(-1);
10398 if (n->type == NHERE) {
10399 struct heredoc *here = heredoc;
10403 if (quoteflag == 0)
10405 TRACE(("Here document %d\n", n->type));
10406 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10407 raise_error_syntax("illegal eof marker for << redirection");
10408 rmescapes(wordtext, 0);
10409 here->eofmark = wordtext;
10411 if (heredoclist == NULL)
10412 heredoclist = here;
10414 for (p = heredoclist; p->next; p = p->next)
10418 } else if (n->type == NTOFD || n->type == NFROMFD) {
10419 fixredir(n, wordtext, 0);
10421 n->nfile.fname = makename();
10425 static union node *
10428 union node *args, **app;
10429 union node *n = NULL;
10430 union node *vars, **vpp;
10431 union node **rpp, *redir;
10433 #if ENABLE_ASH_BASH_COMPAT
10434 smallint double_brackets_flag = 0;
10444 savecheckkwd = CHKALIAS;
10447 checkkwd = savecheckkwd;
10450 #if ENABLE_ASH_BASH_COMPAT
10451 case TAND: /* "&&" */
10452 case TOR: /* "||" */
10453 if (!double_brackets_flag) {
10457 wordtext = (char *) (t == TAND ? "-a" : "-o");
10460 n = stzalloc(sizeof(struct narg));
10462 /*n->narg.next = NULL; - stzalloc did it */
10463 n->narg.text = wordtext;
10464 #if ENABLE_ASH_BASH_COMPAT
10465 if (strcmp("[[", wordtext) == 0)
10466 double_brackets_flag = 1;
10467 else if (strcmp("]]", wordtext) == 0)
10468 double_brackets_flag = 0;
10470 n->narg.backquote = backquotelist;
10471 if (savecheckkwd && isassignment(wordtext)) {
10473 vpp = &n->narg.next;
10476 app = &n->narg.next;
10481 *rpp = n = redirnode;
10482 rpp = &n->nfile.next;
10483 parsefname(); /* read name of redirection file */
10486 if (args && app == &args->narg.next
10489 struct builtincmd *bcmd;
10492 /* We have a function */
10493 if (readtoken() != TRP)
10494 raise_error_unexpected_syntax(TRP);
10495 name = n->narg.text;
10496 if (!goodname(name)
10497 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10499 raise_error_syntax("bad function name");
10502 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10503 n->narg.next = parse_command();
10516 n = stzalloc(sizeof(struct ncmd));
10518 n->ncmd.args = args;
10519 n->ncmd.assign = vars;
10520 n->ncmd.redirect = redir;
10524 static union node *
10525 parse_command(void)
10527 union node *n1, *n2;
10528 union node *ap, **app;
10529 union node *cp, **cpp;
10530 union node *redir, **rpp;
10537 switch (readtoken()) {
10539 raise_error_unexpected_syntax(-1);
10542 n1 = stzalloc(sizeof(struct nif));
10544 n1->nif.test = list(0);
10545 if (readtoken() != TTHEN)
10546 raise_error_unexpected_syntax(TTHEN);
10547 n1->nif.ifpart = list(0);
10549 while (readtoken() == TELIF) {
10550 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10551 n2 = n2->nif.elsepart;
10553 n2->nif.test = list(0);
10554 if (readtoken() != TTHEN)
10555 raise_error_unexpected_syntax(TTHEN);
10556 n2->nif.ifpart = list(0);
10558 if (lasttoken == TELSE)
10559 n2->nif.elsepart = list(0);
10561 n2->nif.elsepart = NULL;
10569 n1 = stzalloc(sizeof(struct nbinary));
10570 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10571 n1->nbinary.ch1 = list(0);
10574 TRACE(("expecting DO got %s %s\n", tokname(got),
10575 got == TWORD ? wordtext : ""));
10576 raise_error_unexpected_syntax(TDO);
10578 n1->nbinary.ch2 = list(0);
10583 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10584 raise_error_syntax("bad for loop variable");
10585 n1 = stzalloc(sizeof(struct nfor));
10587 n1->nfor.var = wordtext;
10588 checkkwd = CHKKWD | CHKALIAS;
10589 if (readtoken() == TIN) {
10591 while (readtoken() == TWORD) {
10592 n2 = stzalloc(sizeof(struct narg));
10594 /*n2->narg.next = NULL; - stzalloc did it */
10595 n2->narg.text = wordtext;
10596 n2->narg.backquote = backquotelist;
10598 app = &n2->narg.next;
10601 n1->nfor.args = ap;
10602 if (lasttoken != TNL && lasttoken != TSEMI)
10603 raise_error_unexpected_syntax(-1);
10605 n2 = stzalloc(sizeof(struct narg));
10607 /*n2->narg.next = NULL; - stzalloc did it */
10608 n2->narg.text = (char *)dolatstr;
10609 /*n2->narg.backquote = NULL;*/
10610 n1->nfor.args = n2;
10612 * Newline or semicolon here is optional (but note
10613 * that the original Bourne shell only allowed NL).
10615 if (lasttoken != TNL && lasttoken != TSEMI)
10618 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10619 if (readtoken() != TDO)
10620 raise_error_unexpected_syntax(TDO);
10621 n1->nfor.body = list(0);
10625 n1 = stzalloc(sizeof(struct ncase));
10627 if (readtoken() != TWORD)
10628 raise_error_unexpected_syntax(TWORD);
10629 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10631 /*n2->narg.next = NULL; - stzalloc did it */
10632 n2->narg.text = wordtext;
10633 n2->narg.backquote = backquotelist;
10635 checkkwd = CHKKWD | CHKALIAS;
10636 } while (readtoken() == TNL);
10637 if (lasttoken != TIN)
10638 raise_error_unexpected_syntax(TIN);
10639 cpp = &n1->ncase.cases;
10641 checkkwd = CHKNL | CHKKWD;
10643 while (t != TESAC) {
10644 if (lasttoken == TLP)
10646 *cpp = cp = stzalloc(sizeof(struct nclist));
10648 app = &cp->nclist.pattern;
10650 *app = ap = stzalloc(sizeof(struct narg));
10652 /*ap->narg.next = NULL; - stzalloc did it */
10653 ap->narg.text = wordtext;
10654 ap->narg.backquote = backquotelist;
10655 if (readtoken() != TPIPE)
10657 app = &ap->narg.next;
10660 //ap->narg.next = NULL;
10661 if (lasttoken != TRP)
10662 raise_error_unexpected_syntax(TRP);
10663 cp->nclist.body = list(2);
10665 cpp = &cp->nclist.next;
10667 checkkwd = CHKNL | CHKKWD;
10671 raise_error_unexpected_syntax(TENDCASE);
10678 n1 = stzalloc(sizeof(struct nredir));
10679 n1->type = NSUBSHELL;
10680 n1->nredir.n = list(0);
10681 /*n1->nredir.redirect = NULL; - stzalloc did it */
10691 return simplecmd();
10694 if (readtoken() != t)
10695 raise_error_unexpected_syntax(t);
10698 /* Now check for redirection which may follow command */
10699 checkkwd = CHKKWD | CHKALIAS;
10701 while (readtoken() == TREDIR) {
10702 *rpp = n2 = redirnode;
10703 rpp = &n2->nfile.next;
10709 if (n1->type != NSUBSHELL) {
10710 n2 = stzalloc(sizeof(struct nredir));
10715 n1->nredir.redirect = redir;
10720 #if ENABLE_ASH_BASH_COMPAT
10721 static int decode_dollar_squote(void)
10723 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10729 p = strchr(C_escapes, c);
10734 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10738 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10740 } else if (c == 'x') { /* \xHH */
10744 } while (isxdigit(c) && --cnt);
10746 if (cnt == 3) { /* \x but next char is "bad" */
10750 } else { /* simple seq like \\ or \t */
10755 c = bb_process_escape_sequence((void*)&p);
10756 } else { /* unrecognized "\z": print both chars unless ' or " */
10757 if (c != '\'' && c != '"') {
10759 c |= 0x100; /* "please encode \, then me" */
10767 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10768 * is not NULL, read a here document. In the latter case, eofmark is the
10769 * word which marks the end of the document and striptabs is true if
10770 * leading tabs should be stripped from the document. The argument firstc
10771 * is the first character of the input token or document.
10773 * Because C does not have internal subroutines, I have simulated them
10774 * using goto's to implement the subroutine linkage. The following macros
10775 * will run code that appears at the end of readtoken1.
10777 #define CHECKEND() {goto checkend; checkend_return:;}
10778 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10779 #define PARSESUB() {goto parsesub; parsesub_return:;}
10780 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10781 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10782 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10784 readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
10786 /* NB: syntax parameter fits into smallint */
10790 char line[EOFMARKLEN + 1];
10791 struct nodelist *bqlist;
10795 smallint prevsyntax; /* syntax before arithmetic */
10796 #if ENABLE_ASH_EXPAND_PRMT
10797 smallint pssyntax; /* we are expanding a prompt string */
10799 int varnest; /* levels of variables expansion */
10800 int arinest; /* levels of arithmetic expansion */
10801 int parenlevel; /* levels of parens in arithmetic */
10802 int dqvarnest; /* levels of variables expansion within double quotes */
10804 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10807 /* Avoid longjmp clobbering */
10813 (void) &parenlevel;
10816 (void) &prevsyntax;
10819 startlinno = g_parsefile->linno;
10824 #if ENABLE_ASH_EXPAND_PRMT
10825 pssyntax = (syntax == PSSYNTAX);
10829 dblquote = (syntax == DQSYNTAX);
10835 STARTSTACKSTR(out);
10837 /* For each line, until end of word */
10839 CHECKEND(); /* set c to PEOF if at end of here document */
10840 for (;;) { /* until end of line or end of word */
10841 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10842 switch (SIT(c, syntax)) {
10843 case CNL: /* '\n' */
10844 if (syntax == BASESYNTAX)
10845 goto endword; /* exit outer loop */
10847 g_parsefile->linno++;
10851 goto loop; /* continue outer loop */
10856 if (eofmark == NULL || dblquote)
10857 USTPUTC(CTLESC, out);
10858 #if ENABLE_ASH_BASH_COMPAT
10859 if (c == '\\' && bash_dollar_squote) {
10860 c = decode_dollar_squote();
10862 USTPUTC('\\', out);
10863 c = (unsigned char)c;
10869 case CBACK: /* backslash */
10872 USTPUTC(CTLESC, out);
10873 USTPUTC('\\', out);
10875 } else if (c == '\n') {
10879 #if ENABLE_ASH_EXPAND_PRMT
10880 if (c == '$' && pssyntax) {
10881 USTPUTC(CTLESC, out);
10882 USTPUTC('\\', out);
10885 if (dblquote && c != '\\'
10886 && c != '`' && c != '$'
10887 && (c != '"' || eofmark != NULL)
10889 USTPUTC(CTLESC, out);
10890 USTPUTC('\\', out);
10892 if (SIT(c, SQSYNTAX) == CCTL)
10893 USTPUTC(CTLESC, out);
10901 if (eofmark == NULL) {
10902 USTPUTC(CTLQUOTEMARK, out);
10910 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
10911 if (eofmark != NULL && arinest == 0
10916 if (dqvarnest == 0) {
10917 syntax = BASESYNTAX;
10924 case CVAR: /* '$' */
10925 PARSESUB(); /* parse substitution */
10927 case CENDVAR: /* '}' */
10930 if (dqvarnest > 0) {
10933 USTPUTC(CTLENDVAR, out);
10938 #if ENABLE_SH_MATH_SUPPORT
10939 case CLP: /* '(' in arithmetic */
10943 case CRP: /* ')' in arithmetic */
10944 if (parenlevel > 0) {
10948 if (pgetc() == ')') {
10949 if (--arinest == 0) {
10950 USTPUTC(CTLENDARI, out);
10951 syntax = prevsyntax;
10952 dblquote = (syntax == DQSYNTAX);
10957 * unbalanced parens
10958 * (don't 2nd guess - no error)
10966 case CBQUOTE: /* '`' */
10970 goto endword; /* exit outer loop */
10974 if (varnest == 0) {
10975 #if ENABLE_ASH_BASH_COMPAT
10977 if (pgetc() == '>')
10978 c = 0x100 + '>'; /* flag &> */
10982 goto endword; /* exit outer loop */
10984 #if ENABLE_ASH_ALIAS
10994 #if ENABLE_SH_MATH_SUPPORT
10995 if (syntax == ARISYNTAX)
10996 raise_error_syntax("missing '))'");
10998 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
10999 raise_error_syntax("unterminated quoted string");
11000 if (varnest != 0) {
11001 startlinno = g_parsefile->linno;
11003 raise_error_syntax("missing '}'");
11005 USTPUTC('\0', out);
11006 len = out - (char *)stackblock();
11007 out = stackblock();
11008 if (eofmark == NULL) {
11009 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11012 if (isdigit_str9(out)) {
11013 PARSEREDIR(); /* passed as params: out, c */
11014 lasttoken = TREDIR;
11017 /* else: non-number X seen, interpret it
11018 * as "NNNX>file" = "NNNX >file" */
11022 quoteflag = quotef;
11023 backquotelist = bqlist;
11024 grabstackblock(len);
11028 /* end of readtoken routine */
11031 * Check to see whether we are at the end of the here document. When this
11032 * is called, c is set to the first character of the next input line. If
11033 * we are at the end of the here document, this routine sets the c to PEOF.
11037 #if ENABLE_ASH_ALIAS
11043 while (c == '\t') {
11047 if (c == *eofmark) {
11048 if (pfgets(line, sizeof(line)) != NULL) {
11052 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11054 if (*p == '\n' && *q == '\0') {
11056 g_parsefile->linno++;
11057 needprompt = doprompt;
11059 pushstring(line, NULL);
11064 goto checkend_return;
11068 * Parse a redirection operator. The variable "out" points to a string
11069 * specifying the fd to be redirected. The variable "c" contains the
11070 * first character of the redirection operator.
11073 /* out is already checked to be a valid number or "" */
11074 int fd = (*out == '\0' ? -1 : atoi(out));
11077 np = stzalloc(sizeof(struct nfile));
11082 np->type = NAPPEND;
11084 np->type = NCLOBBER;
11087 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11093 #if ENABLE_ASH_BASH_COMPAT
11094 else if (c == 0x100 + '>') { /* this flags &> redirection */
11096 pgetc(); /* this is '>', no need to check */
11100 else { /* c == '<' */
11101 /*np->nfile.fd = 0; - stzalloc did it */
11105 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11106 np = stzalloc(sizeof(struct nhere));
11107 /*np->nfile.fd = 0; - stzalloc did it */
11110 heredoc = stzalloc(sizeof(struct heredoc));
11111 heredoc->here = np;
11114 heredoc->striptabs = 1;
11116 /*heredoc->striptabs = 0; - stzalloc did it */
11122 np->type = NFROMFD;
11126 np->type = NFROMTO;
11138 goto parseredir_return;
11142 * Parse a substitution. At this point, we have read the dollar sign
11143 * and nothing else.
11146 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11147 * (assuming ascii char codes, as the original implementation did) */
11148 #define is_special(c) \
11149 (((unsigned)(c) - 33 < 32) \
11150 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11156 static const char types[] ALIGN1 = "}-+?=";
11159 if (c <= PEOA_OR_PEOF
11160 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11162 #if ENABLE_ASH_BASH_COMPAT
11164 bash_dollar_squote = 1;
11169 } else if (c == '(') { /* $(command) or $((arith)) */
11170 if (pgetc() == '(') {
11171 #if ENABLE_SH_MATH_SUPPORT
11174 raise_error_syntax("you disabled math support for $((arith)) syntax");
11181 USTPUTC(CTLVAR, out);
11182 typeloc = out - (char *)stackblock();
11183 USTPUTC(VSNORMAL, out);
11184 subtype = VSNORMAL;
11192 subtype = VSLENGTH;
11196 if (c > PEOA_OR_PEOF && is_name(c)) {
11200 } while (c > PEOA_OR_PEOF && is_in_name(c));
11201 } else if (isdigit(c)) {
11205 } while (isdigit(c));
11206 } else if (is_special(c)) {
11211 raise_error_syntax("bad substitution");
11216 if (subtype == 0) {
11220 #if ENABLE_ASH_BASH_COMPAT
11221 if (c == ':' || c == '$' || isdigit(c)) {
11223 subtype = VSSUBSTR;
11230 p = strchr(types, c);
11233 subtype = p - types + VSNORMAL;
11238 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11246 #if ENABLE_ASH_BASH_COMPAT
11248 subtype = VSREPLACE;
11251 subtype++; /* VSREPLACEALL */
11260 if (dblquote || arinest)
11262 *((char *)stackblock() + typeloc) = subtype | flags;
11263 if (subtype != VSNORMAL) {
11265 if (dblquote || arinest) {
11270 goto parsesub_return;
11274 * Called to parse command substitutions. Newstyle is set if the command
11275 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11276 * list of commands (passed by reference), and savelen is the number of
11277 * characters on the top of the stack which must be preserved.
11280 struct nodelist **nlpp;
11283 char *volatile str;
11284 struct jmploc jmploc;
11285 struct jmploc *volatile savehandler;
11287 smallint saveprompt = 0;
11290 (void) &saveprompt;
11292 savepbq = parsebackquote;
11293 if (setjmp(jmploc.loc)) {
11295 parsebackquote = 0;
11296 exception_handler = savehandler;
11297 longjmp(exception_handler->loc, 1);
11301 savelen = out - (char *)stackblock();
11303 str = ckmalloc(savelen);
11304 memcpy(str, stackblock(), savelen);
11306 savehandler = exception_handler;
11307 exception_handler = &jmploc;
11310 /* We must read until the closing backquote, giving special
11311 treatment to some slashes, and then push the string and
11312 reread it as input, interpreting it normally. */
11319 STARTSTACKSTR(pout);
11332 g_parsefile->linno++;
11336 * If eating a newline, avoid putting
11337 * the newline into the new character
11338 * stream (via the STPUTC after the
11343 if (pc != '\\' && pc != '`' && pc != '$'
11344 && (!dblquote || pc != '"'))
11345 STPUTC('\\', pout);
11346 if (pc > PEOA_OR_PEOF) {
11352 #if ENABLE_ASH_ALIAS
11355 startlinno = g_parsefile->linno;
11356 raise_error_syntax("EOF in backquote substitution");
11359 g_parsefile->linno++;
11360 needprompt = doprompt;
11369 STPUTC('\0', pout);
11370 psavelen = pout - (char *)stackblock();
11371 if (psavelen > 0) {
11372 pstr = grabstackstr(pout);
11373 setinputstring(pstr);
11378 nlpp = &(*nlpp)->next;
11379 *nlpp = stzalloc(sizeof(**nlpp));
11380 /* (*nlpp)->next = NULL; - stzalloc did it */
11381 parsebackquote = oldstyle;
11384 saveprompt = doprompt;
11391 doprompt = saveprompt;
11392 else if (readtoken() != TRP)
11393 raise_error_unexpected_syntax(TRP);
11398 * Start reading from old file again, ignoring any pushed back
11399 * tokens left from the backquote parsing
11404 while (stackblocksize() <= savelen)
11406 STARTSTACKSTR(out);
11408 memcpy(out, str, savelen);
11409 STADJUST(savelen, out);
11415 parsebackquote = savepbq;
11416 exception_handler = savehandler;
11417 if (arinest || dblquote)
11418 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11420 USTPUTC(CTLBACKQ, out);
11422 goto parsebackq_oldreturn;
11423 goto parsebackq_newreturn;
11426 #if ENABLE_SH_MATH_SUPPORT
11428 * Parse an arithmetic expansion (indicate start of one and set state)
11431 if (++arinest == 1) {
11432 prevsyntax = syntax;
11433 syntax = ARISYNTAX;
11434 USTPUTC(CTLARI, out);
11441 * we collapse embedded arithmetic expansion to
11442 * parenthesis, which should be equivalent
11446 goto parsearith_return;
11450 } /* end of readtoken */
11453 * Read the next input token.
11454 * If the token is a word, we set backquotelist to the list of cmds in
11455 * backquotes. We set quoteflag to true if any part of the word was
11457 * If the token is TREDIR, then we set redirnode to a structure containing
11459 * In all cases, the variable startlinno is set to the number of the line
11460 * on which the token starts.
11462 * [Change comment: here documents and internal procedures]
11463 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11464 * word parsing code into a separate routine. In this case, readtoken
11465 * doesn't need to have any internal procedures, but parseword does.
11466 * We could also make parseoperator in essence the main routine, and
11467 * have parseword (readtoken1?) handle both words and redirection.]
11469 #define NEW_xxreadtoken
11470 #ifdef NEW_xxreadtoken
11471 /* singles must be first! */
11472 static const char xxreadtoken_chars[7] ALIGN1 = {
11473 '\n', '(', ')', /* singles */
11474 '&', '|', ';', /* doubles */
11478 #define xxreadtoken_singles 3
11479 #define xxreadtoken_doubles 3
11481 static const char xxreadtoken_tokens[] ALIGN1 = {
11482 TNL, TLP, TRP, /* only single occurrence allowed */
11483 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11484 TEOF, /* corresponds to trailing nul */
11485 TAND, TOR, TENDCASE /* if double occurrence */
11500 startlinno = g_parsefile->linno;
11501 for (;;) { /* until token or start of word found */
11503 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11507 while ((c = pgetc()) != '\n' && c != PEOF)
11510 } else if (c == '\\') {
11511 if (pgetc() != '\n') {
11513 break; /* return readtoken1(...) */
11515 startlinno = ++g_parsefile->linno;
11521 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11524 g_parsefile->linno++;
11525 needprompt = doprompt;
11528 p = strchr(xxreadtoken_chars, c);
11530 break; /* return readtoken1(...) */
11532 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11534 if (cc == c) { /* double occurrence? */
11535 p += xxreadtoken_doubles + 1;
11538 #if ENABLE_ASH_BASH_COMPAT
11539 if (c == '&' && cc == '>') /* &> */
11540 break; /* return readtoken1(...) */
11545 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11550 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11552 #else /* old xxreadtoken */
11553 #define RETURN(token) return lasttoken = token
11566 startlinno = g_parsefile->linno;
11567 for (;;) { /* until token or start of word found */
11570 case ' ': case '\t':
11571 #if ENABLE_ASH_ALIAS
11576 while ((c = pgetc()) != '\n' && c != PEOF)
11581 if (pgetc() == '\n') {
11582 startlinno = ++g_parsefile->linno;
11590 g_parsefile->linno++;
11591 needprompt = doprompt;
11596 if (pgetc() == '&')
11601 if (pgetc() == '|')
11606 if (pgetc() == ';')
11619 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11622 #endif /* old xxreadtoken */
11629 smallint alreadyseen = tokpushback;
11632 #if ENABLE_ASH_ALIAS
11641 if (checkkwd & CHKNL) {
11648 if (t != TWORD || quoteflag) {
11653 * check for keywords
11655 if (checkkwd & CHKKWD) {
11656 const char *const *pp;
11658 pp = findkwd(wordtext);
11660 lasttoken = t = pp - tokname_array;
11661 TRACE(("keyword %s recognized\n", tokname(t)));
11666 if (checkkwd & CHKALIAS) {
11667 #if ENABLE_ASH_ALIAS
11669 ap = lookupalias(wordtext, 1);
11672 pushstring(ap->val, ap);
11682 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11684 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11696 return tokname_array[t][0];
11700 * Read and parse a command. Returns NODE_EOF on end of file.
11701 * (NULL is a valid parse tree indicating a blank line.)
11703 static union node *
11704 parsecmd(int interact)
11709 doprompt = interact;
11711 setprompt(doprompt);
11723 * Input any here documents.
11728 struct heredoc *here;
11731 here = heredoclist;
11732 heredoclist = NULL;
11738 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11739 here->eofmark, here->striptabs);
11740 n = stzalloc(sizeof(struct narg));
11741 n->narg.type = NARG;
11742 /*n->narg.next = NULL; - stzalloc did it */
11743 n->narg.text = wordtext;
11744 n->narg.backquote = backquotelist;
11745 here->here->nhere.doc = n;
11752 * called by editline -- any expansions to the prompt should be added here.
11754 #if ENABLE_ASH_EXPAND_PRMT
11755 static const char *
11756 expandstr(const char *ps)
11760 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11761 * and token processing _can_ alter it (delete NULs etc). */
11762 setinputstring((char *)ps);
11763 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11766 n.narg.type = NARG;
11767 n.narg.next = NULL;
11768 n.narg.text = wordtext;
11769 n.narg.backquote = backquotelist;
11771 expandarg(&n, NULL, 0);
11772 return stackblock();
11777 * Execute a command or commands contained in a string.
11780 evalstring(char *s, int mask)
11783 struct stackmark smark;
11787 setstackmark(&smark);
11790 while ((n = parsecmd(0)) != NODE_EOF) {
11792 popstackmark(&smark);
11805 * The eval command.
11807 static int FAST_FUNC
11808 evalcmd(int argc UNUSED_PARAM, char **argv)
11817 STARTSTACKSTR(concat);
11819 concat = stack_putstr(p, concat);
11823 STPUTC(' ', concat);
11825 STPUTC('\0', concat);
11826 p = grabstackstr(concat);
11828 evalstring(p, ~SKIPEVAL);
11835 * Read and execute commands. "Top" is nonzero for the top level command
11836 * loop; it turns on prompting if the shell is interactive.
11842 struct stackmark smark;
11846 TRACE(("cmdloop(%d) called\n", top));
11850 setstackmark(&smark);
11853 showjobs(stderr, SHOW_CHANGED);
11856 if (iflag && top) {
11858 #if ENABLE_ASH_MAIL
11862 n = parsecmd(inter);
11864 if (DEBUG > 2 && debug && (n != NODE_EOF))
11867 if (n == NODE_EOF) {
11868 if (!top || numeof >= 50)
11870 if (!stoppedjobs()) {
11873 out2str("\nUse \"exit\" to leave shell.\n");
11876 } else if (nflag == 0) {
11877 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11882 popstackmark(&smark);
11887 return skip & SKIPEVAL;
11894 * Take commands from a file. To be compatible we should do a path
11895 * search for the file, which is necessary to find sub-commands.
11898 find_dot_file(char *name)
11901 const char *path = pathval();
11904 /* don't try this for absolute or relative paths */
11905 if (strchr(name, '/'))
11908 /* IIRC standards do not say whether . is to be searched.
11909 * And it is even smaller this way, making it unconditional for now:
11911 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11916 while ((fullname = path_advance(&path, name)) != NULL) {
11918 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11920 * Don't bother freeing here, since it will
11921 * be freed by the caller.
11925 if (fullname != name)
11926 stunalloc(fullname);
11929 /* not found in the PATH */
11930 ash_msg_and_raise_error("%s: not found", name);
11934 static int FAST_FUNC
11935 dotcmd(int argc, char **argv)
11937 struct strlist *sp;
11938 volatile struct shparam saveparam;
11941 for (sp = cmdenviron; sp; sp = sp->next)
11942 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
11944 if (argv[1]) { /* That's what SVR2 does */
11945 char *fullname = find_dot_file(argv[1]);
11948 if (argc) { /* argc > 0, argv[0] != NULL */
11949 saveparam = shellparam;
11950 shellparam.malloced = 0;
11951 shellparam.nparam = argc;
11952 shellparam.p = argv;
11955 setinputfile(fullname, INPUT_PUSH_FILE);
11956 commandname = fullname;
11961 freeparam(&shellparam);
11962 shellparam = saveparam;
11964 status = exitstatus;
11969 static int FAST_FUNC
11970 exitcmd(int argc UNUSED_PARAM, char **argv)
11975 exitstatus = number(argv[1]);
11976 raise_exception(EXEXIT);
11981 * Read a file containing shell functions.
11984 readcmdfile(char *name)
11986 setinputfile(name, INPUT_PUSH_FILE);
11992 /* ============ find_command inplementation */
11995 * Resolve a command name. If you change this routine, you may have to
11996 * change the shellexec routine as well.
11999 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12001 struct tblentry *cmdp;
12008 struct builtincmd *bcmd;
12010 /* If name contains a slash, don't use PATH or hash table */
12011 if (strchr(name, '/') != NULL) {
12012 entry->u.index = -1;
12013 if (act & DO_ABS) {
12014 while (stat(name, &statb) < 0) {
12016 if (errno == EINTR)
12019 entry->cmdtype = CMDUNKNOWN;
12023 entry->cmdtype = CMDNORMAL;
12027 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12029 updatetbl = (path == pathval());
12032 if (strstr(path, "%builtin") != NULL)
12033 act |= DO_ALTBLTIN;
12036 /* If name is in the table, check answer will be ok */
12037 cmdp = cmdlookup(name, 0);
12038 if (cmdp != NULL) {
12041 switch (cmdp->cmdtype) {
12059 } else if (cmdp->rehash == 0)
12060 /* if not invalidated by cd, we're done */
12064 /* If %builtin not in path, check for builtin next */
12065 bcmd = find_builtin(name);
12067 if (IS_BUILTIN_REGULAR(bcmd))
12068 goto builtin_success;
12069 if (act & DO_ALTPATH) {
12070 if (!(act & DO_ALTBLTIN))
12071 goto builtin_success;
12072 } else if (builtinloc <= 0) {
12073 goto builtin_success;
12077 #if ENABLE_FEATURE_SH_STANDALONE
12079 int applet_no = find_applet_by_name(name);
12080 if (applet_no >= 0) {
12081 entry->cmdtype = CMDNORMAL;
12082 entry->u.index = -2 - applet_no;
12088 /* We have to search path. */
12089 prev = -1; /* where to start */
12090 if (cmdp && cmdp->rehash) { /* doing a rehash */
12091 if (cmdp->cmdtype == CMDBUILTIN)
12094 prev = cmdp->param.index;
12100 while ((fullname = path_advance(&path, name)) != NULL) {
12101 stunalloc(fullname);
12102 /* NB: code below will still use fullname
12103 * despite it being "unallocated" */
12106 if (prefix(pathopt, "builtin")) {
12108 goto builtin_success;
12111 if ((act & DO_NOFUNC)
12112 || !prefix(pathopt, "func")
12113 ) { /* ignore unimplemented options */
12117 /* if rehash, don't redo absolute path names */
12118 if (fullname[0] == '/' && idx <= prev) {
12121 TRACE(("searchexec \"%s\": no change\n", name));
12124 while (stat(fullname, &statb) < 0) {
12126 if (errno == EINTR)
12129 if (errno != ENOENT && errno != ENOTDIR)
12133 e = EACCES; /* if we fail, this will be the error */
12134 if (!S_ISREG(statb.st_mode))
12136 if (pathopt) { /* this is a %func directory */
12137 stalloc(strlen(fullname) + 1);
12138 /* NB: stalloc will return space pointed by fullname
12139 * (because we don't have any intervening allocations
12140 * between stunalloc above and this stalloc) */
12141 readcmdfile(fullname);
12142 cmdp = cmdlookup(name, 0);
12143 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12144 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12145 stunalloc(fullname);
12148 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12150 entry->cmdtype = CMDNORMAL;
12151 entry->u.index = idx;
12155 cmdp = cmdlookup(name, 1);
12156 cmdp->cmdtype = CMDNORMAL;
12157 cmdp->param.index = idx;
12162 /* We failed. If there was an entry for this command, delete it */
12163 if (cmdp && updatetbl)
12164 delete_cmd_entry();
12166 ash_msg("%s: %s", name, errmsg(e, "not found"));
12167 entry->cmdtype = CMDUNKNOWN;
12172 entry->cmdtype = CMDBUILTIN;
12173 entry->u.cmd = bcmd;
12177 cmdp = cmdlookup(name, 1);
12178 cmdp->cmdtype = CMDBUILTIN;
12179 cmdp->param.cmd = bcmd;
12183 entry->cmdtype = cmdp->cmdtype;
12184 entry->u = cmdp->param;
12188 /* ============ trap.c */
12191 * The trap builtin.
12193 static int FAST_FUNC
12194 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12203 for (signo = 0; signo < NSIG; signo++) {
12204 if (trap[signo] != NULL) {
12205 out1fmt("trap -- %s %s\n",
12206 single_quote(trap[signo]),
12207 get_signame(signo));
12216 signo = get_signum(*ap);
12218 ash_msg_and_raise_error("%s: bad trap", *ap);
12221 if (LONE_DASH(action))
12224 action = ckstrdup(action);
12227 trap[signo] = action;
12237 /* ============ Builtins */
12239 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12241 * Lists available builtins
12243 static int FAST_FUNC
12244 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12250 "Built-in commands:\n"
12251 "------------------\n");
12252 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12253 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12254 builtintab[i].name + 1);
12260 #if ENABLE_FEATURE_SH_STANDALONE
12262 const char *a = applet_names;
12264 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12269 a += strlen(a) + 1;
12274 return EXIT_SUCCESS;
12276 #endif /* FEATURE_SH_EXTRA_QUIET */
12279 * The export and readonly commands.
12281 static int FAST_FUNC
12282 exportcmd(int argc UNUSED_PARAM, char **argv)
12288 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12290 if (nextopt("p") != 'p') {
12295 p = strchr(name, '=');
12299 vp = *findvar(hashvar(name), name);
12305 setvar(name, p, flag);
12306 } while ((name = *++aptr) != NULL);
12310 showvars(argv[0], flag, 0);
12315 * Delete a function if it exists.
12318 unsetfunc(const char *name)
12320 struct tblentry *cmdp;
12322 cmdp = cmdlookup(name, 0);
12323 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12324 delete_cmd_entry();
12328 * The unset builtin command. We unset the function before we unset the
12329 * variable to allow a function to be unset when there is a readonly variable
12330 * with the same name.
12332 static int FAST_FUNC
12333 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12340 while ((i = nextopt("vf")) != '\0') {
12344 for (ap = argptr; *ap; ap++) {
12360 #include <sys/times.h>
12362 static const unsigned char timescmd_str[] ALIGN1 = {
12363 ' ', offsetof(struct tms, tms_utime),
12364 '\n', offsetof(struct tms, tms_stime),
12365 ' ', offsetof(struct tms, tms_cutime),
12366 '\n', offsetof(struct tms, tms_cstime),
12370 static int FAST_FUNC
12371 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12373 long clk_tck, s, t;
12374 const unsigned char *p;
12377 clk_tck = sysconf(_SC_CLK_TCK);
12382 t = *(clock_t *)(((char *) &buf) + p[1]);
12384 out1fmt("%ldm%ld.%.3lds%c",
12386 ((t - s * clk_tck) * 1000) / clk_tck,
12388 } while (*(p += 2));
12393 #if ENABLE_SH_MATH_SUPPORT
12395 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12396 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12398 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12400 static int FAST_FUNC
12401 letcmd(int argc UNUSED_PARAM, char **argv)
12407 ash_msg_and_raise_error("expression expected");
12409 i = ash_arith(*argv);
12414 #endif /* SH_MATH_SUPPORT */
12417 /* ============ miscbltin.c
12419 * Miscellaneous builtins.
12424 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
12425 typedef enum __rlimit_resource rlim_t;
12429 * The read builtin. Options:
12430 * -r Do not interpret '\' specially
12431 * -s Turn off echo (tty only)
12432 * -n NCHARS Read NCHARS max
12433 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12434 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12435 * -u FD Read from given FD instead of fd 0
12436 * This uses unbuffered input, which may be avoidable in some cases.
12437 * TODO: bash also has:
12438 * -a ARRAY Read into array[0],[1],etc
12439 * -d DELIM End on DELIM char, not newline
12440 * -e Use line editing (tty only)
12442 static int FAST_FUNC
12443 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12445 static const char *const arg_REPLY[] = { "REPLY", NULL };
12458 #if ENABLE_ASH_READ_NCHARS
12459 int nchars = 0; /* if != 0, -n is in effect */
12461 struct termios tty, old_tty;
12463 #if ENABLE_ASH_READ_TIMEOUT
12464 unsigned end_ms = 0;
12465 unsigned timeout = 0;
12470 while ((i = nextopt("p:u:r"
12471 IF_ASH_READ_TIMEOUT("t:")
12472 IF_ASH_READ_NCHARS("n:s")
12476 prompt = optionarg;
12478 #if ENABLE_ASH_READ_NCHARS
12480 nchars = bb_strtou(optionarg, NULL, 10);
12481 if (nchars < 0 || errno)
12482 ash_msg_and_raise_error("invalid count");
12483 /* nchars == 0: off (bash 3.2 does this too) */
12489 #if ENABLE_ASH_READ_TIMEOUT
12491 timeout = bb_strtou(optionarg, NULL, 10);
12492 if (errno || timeout > UINT_MAX / 2048)
12493 ash_msg_and_raise_error("invalid timeout");
12495 #if 0 /* even bash have no -t N.NNN support */
12496 ts.tv_sec = bb_strtou(optionarg, &p, 10);
12498 /* EINVAL means number is ok, but not terminated by NUL */
12499 if (*p == '.' && errno == EINVAL) {
12503 ts.tv_usec = bb_strtou(p, &p2, 10);
12505 ash_msg_and_raise_error("invalid timeout");
12507 /* normalize to usec */
12509 ash_msg_and_raise_error("invalid timeout");
12510 while (scale++ < 6)
12513 } else if (ts.tv_sec < 0 || errno) {
12514 ash_msg_and_raise_error("invalid timeout");
12516 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
12517 ash_msg_and_raise_error("invalid timeout");
12526 fd = bb_strtou(optionarg, NULL, 10);
12527 if (fd < 0 || errno)
12528 ash_msg_and_raise_error("invalid file descriptor");
12534 if (prompt && isatty(fd)) {
12539 ap = (char**)arg_REPLY;
12540 ifs = bltinlookup("IFS");
12543 #if ENABLE_ASH_READ_NCHARS
12544 tcgetattr(fd, &tty);
12546 if (nchars || silent) {
12548 tty.c_lflag &= ~ICANON;
12549 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
12552 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12554 /* if tcgetattr failed, tcsetattr will fail too.
12555 * Ignoring, it's harmless. */
12556 tcsetattr(fd, TCSANOW, &tty);
12563 #if ENABLE_ASH_READ_TIMEOUT
12564 if (timeout) /* NB: ensuring end_ms is nonzero */
12565 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12569 const char *is_ifs;
12571 #if ENABLE_ASH_READ_TIMEOUT
12573 struct pollfd pfd[1];
12575 pfd[0].events = POLLIN;
12576 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12577 if ((int)timeout <= 0 /* already late? */
12578 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12579 ) { /* timed out! */
12580 #if ENABLE_ASH_READ_NCHARS
12581 tcsetattr(fd, TCSANOW, &old_tty);
12587 if (nonblock_safe_read(fd, &c, 1) != 1) {
12599 if (!rflag && c == '\\') {
12605 /* $IFS splitting */
12606 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
12607 is_ifs = strchr(ifs, c);
12608 if (startword && is_ifs) {
12611 /* it is a non-space ifs char */
12613 if (startword == 1) /* first one? */
12614 continue; /* yes, it is not next word yet */
12617 if (ap[1] != NULL && is_ifs) {
12620 beg = stackblock();
12621 setvar(*ap, beg, 0);
12623 /* can we skip one non-space ifs char? (2: yes) */
12624 startword = isspace(c) ? 2 : 1;
12631 /* end of do {} while: */
12632 #if ENABLE_ASH_READ_NCHARS
12638 #if ENABLE_ASH_READ_NCHARS
12639 tcsetattr(fd, TCSANOW, &old_tty);
12643 /* Remove trailing space ifs chars */
12644 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
12646 setvar(*ap, stackblock(), 0);
12647 while (*++ap != NULL)
12648 setvar(*ap, nullstr, 0);
12652 static int FAST_FUNC
12653 umaskcmd(int argc UNUSED_PARAM, char **argv)
12655 static const char permuser[3] ALIGN1 = "ugo";
12656 static const char permmode[3] ALIGN1 = "rwx";
12657 static const short permmask[] ALIGN2 = {
12658 S_IRUSR, S_IWUSR, S_IXUSR,
12659 S_IRGRP, S_IWGRP, S_IXGRP,
12660 S_IROTH, S_IWOTH, S_IXOTH
12663 /* TODO: use bb_parse_mode() instead */
12668 int symbolic_mode = 0;
12670 while (nextopt("S") != '\0') {
12681 if (symbolic_mode) {
12685 for (i = 0; i < 3; i++) {
12688 *p++ = permuser[i];
12690 for (j = 0; j < 3; j++) {
12691 if ((mask & permmask[3 * i + j]) == 0) {
12692 *p++ = permmode[j];
12700 out1fmt("%.4o\n", mask);
12703 if (isdigit((unsigned char) *ap)) {
12706 if (*ap >= '8' || *ap < '0')
12707 ash_msg_and_raise_error(msg_illnum, argv[1]);
12708 mask = (mask << 3) + (*ap - '0');
12709 } while (*++ap != '\0');
12712 mask = ~mask & 0777;
12713 if (!bb_parse_mode(ap, &mask)) {
12714 ash_msg_and_raise_error("illegal mode: %s", ap);
12716 umask(~mask & 0777);
12725 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12726 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12727 * ash by J.T. Conklin.
12732 uint8_t cmd; /* RLIMIT_xxx fit into it */
12733 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
12737 static const struct limits limits_tbl[] = {
12739 { RLIMIT_CPU, 0, 't' },
12741 #ifdef RLIMIT_FSIZE
12742 { RLIMIT_FSIZE, 9, 'f' },
12745 { RLIMIT_DATA, 10, 'd' },
12747 #ifdef RLIMIT_STACK
12748 { RLIMIT_STACK, 10, 's' },
12751 { RLIMIT_CORE, 9, 'c' },
12754 { RLIMIT_RSS, 10, 'm' },
12756 #ifdef RLIMIT_MEMLOCK
12757 { RLIMIT_MEMLOCK, 10, 'l' },
12759 #ifdef RLIMIT_NPROC
12760 { RLIMIT_NPROC, 0, 'p' },
12762 #ifdef RLIMIT_NOFILE
12763 { RLIMIT_NOFILE, 0, 'n' },
12766 { RLIMIT_AS, 10, 'v' },
12768 #ifdef RLIMIT_LOCKS
12769 { RLIMIT_LOCKS, 0, 'w' },
12772 static const char limits_name[] =
12774 "time(seconds)" "\0"
12776 #ifdef RLIMIT_FSIZE
12777 "file(blocks)" "\0"
12782 #ifdef RLIMIT_STACK
12786 "coredump(blocks)" "\0"
12791 #ifdef RLIMIT_MEMLOCK
12792 "locked memory(kb)" "\0"
12794 #ifdef RLIMIT_NPROC
12797 #ifdef RLIMIT_NOFILE
12803 #ifdef RLIMIT_LOCKS
12808 enum limtype { SOFT = 0x1, HARD = 0x2 };
12811 printlim(enum limtype how, const struct rlimit *limit,
12812 const struct limits *l)
12816 val = limit->rlim_max;
12818 val = limit->rlim_cur;
12820 if (val == RLIM_INFINITY)
12821 out1fmt("unlimited\n");
12823 val >>= l->factor_shift;
12824 out1fmt("%lld\n", (long long) val);
12828 static int FAST_FUNC
12829 ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12833 enum limtype how = SOFT | HARD;
12834 const struct limits *l;
12837 struct rlimit limit;
12840 while ((optc = nextopt("HSa"
12844 #ifdef RLIMIT_FSIZE
12850 #ifdef RLIMIT_STACK
12859 #ifdef RLIMIT_MEMLOCK
12862 #ifdef RLIMIT_NPROC
12865 #ifdef RLIMIT_NOFILE
12871 #ifdef RLIMIT_LOCKS
12889 for (l = limits_tbl; l->option != what; l++)
12892 set = *argptr ? 1 : 0;
12896 if (all || argptr[1])
12897 ash_msg_and_raise_error("too many arguments");
12898 if (strncmp(p, "unlimited\n", 9) == 0)
12899 val = RLIM_INFINITY;
12903 while ((c = *p++) >= '0' && c <= '9') {
12904 val = (val * 10) + (long)(c - '0');
12905 // val is actually 'unsigned long int' and can't get < 0
12906 if (val < (rlim_t) 0)
12910 ash_msg_and_raise_error("bad number");
12911 val <<= l->factor_shift;
12915 const char *lname = limits_name;
12916 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
12917 getrlimit(l->cmd, &limit);
12918 out1fmt("%-20s ", lname);
12919 lname += strlen(lname) + 1;
12920 printlim(how, &limit, l);
12925 getrlimit(l->cmd, &limit);
12928 limit.rlim_max = val;
12930 limit.rlim_cur = val;
12931 if (setrlimit(l->cmd, &limit) < 0)
12932 ash_msg_and_raise_error("error setting limit (%m)");
12934 printlim(how, &limit, l);
12939 /* ============ main() and helpers */
12942 * Called to exit the shell.
12944 static void exitshell(void) NORETURN;
12952 status = exitstatus;
12953 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12954 if (setjmp(loc.loc)) {
12955 if (exception_type == EXEXIT)
12956 /* dash bug: it just does _exit(exitstatus) here
12957 * but we have to do setjobctl(0) first!
12958 * (bug is still not fixed in dash-0.5.3 - if you run dash
12959 * under Midnight Commander, on exit from dash MC is backgrounded) */
12960 status = exitstatus;
12963 exception_handler = &loc;
12969 flush_stdout_stderr();
12979 /* from input.c: */
12980 basepf.next_to_pgetc = basepf.buf = basebuf;
12983 signal(SIGCHLD, SIG_DFL);
12988 char ppid[sizeof(int)*3 + 2];
12990 struct stat st1, st2;
12993 for (envp = environ; envp && *envp; envp++) {
12994 if (strchr(*envp, '=')) {
12995 setvareq(*envp, VEXPORT|VTEXTFIXED);
12999 sprintf(ppid, "%u", (unsigned) getppid());
13000 setvar("PPID", ppid, 0);
13002 p = lookupvar("PWD");
13004 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13005 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
13012 * Process the shell command line arguments.
13015 procargs(char **argv)
13018 const char *xminusc;
13023 /* if (xargv[0]) - mmm, this is always true! */
13025 for (i = 0; i < NOPTS; i++)
13029 /* it already printed err message */
13030 raise_exception(EXERROR);
13034 if (*xargv == NULL) {
13036 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13039 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13043 for (i = 0; i < NOPTS; i++)
13044 if (optlist[i] == 2)
13049 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13054 } else if (!sflag) {
13055 setinputfile(*xargv, 0);
13058 commandname = arg0;
13061 shellparam.p = xargv;
13062 #if ENABLE_ASH_GETOPTS
13063 shellparam.optind = 1;
13064 shellparam.optoff = -1;
13066 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13068 shellparam.nparam++;
13075 * Read /etc/profile or .profile.
13078 read_profile(const char *name)
13082 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13091 * This routine is called when an error or an interrupt occurs in an
13092 * interactive shell and control is returned to the main command loop.
13100 /* from input.c: */
13101 g_parsefile->left_in_buffer = 0;
13102 g_parsefile->left_in_line = 0; /* clear input buffer */
13104 /* from parser.c: */
13107 /* from redir.c: */
13108 clearredir(/*drop:*/ 0);
13112 static short profile_buf[16384];
13113 extern int etext();
13117 * Main routine. We initialize things, parse the arguments, execute
13118 * profiles if we're a login shell, and then call cmdloop to execute
13119 * commands. The setjmp call sets up the location to jump to when an
13120 * exception occurs. When an exception occurs the variable "state"
13121 * is used to figure out how far we had gotten.
13123 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13124 int ash_main(int argc UNUSED_PARAM, char **argv)
13126 const char *shinit;
13127 volatile smallint state;
13128 struct jmploc jmploc;
13129 struct stackmark smark;
13131 /* Initialize global data */
13135 #if ENABLE_ASH_ALIAS
13141 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13144 #if ENABLE_FEATURE_EDITING
13145 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13148 if (setjmp(jmploc.loc)) {
13154 e = exception_type;
13158 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13161 outcslow('\n', stderr);
13163 popstackmark(&smark);
13164 FORCE_INT_ON; /* enable interrupts */
13173 exception_handler = &jmploc;
13176 TRACE(("Shell args: "));
13177 trace_puts_args(argv);
13179 rootpid = getpid();
13181 #if ENABLE_ASH_RANDOM_SUPPORT
13182 /* Can use monotonic_ns() for better randomness but for now it is
13183 * not used anywhere else in busybox... so avoid bloat */
13184 random_galois_LFSR = random_LCG = rootpid + monotonic_us();
13187 setstackmark(&smark);
13190 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13192 const char *hp = lookupvar("HISTFILE");
13195 hp = lookupvar("HOME");
13197 char *defhp = concat_path_file(hp, ".ash_history");
13198 setvar("HISTFILE", defhp, 0);
13204 if (/* argv[0] && */ argv[0][0] == '-')
13208 read_profile("/etc/profile");
13211 read_profile(".profile");
13217 getuid() == geteuid() && getgid() == getegid() &&
13221 shinit = lookupvar("ENV");
13222 if (shinit != NULL && *shinit != '\0') {
13223 read_profile(shinit);
13229 /* evalstring pushes parsefile stack.
13230 * Ensure we don't falsely claim that 0 (stdin)
13231 * is one of stacked source fds.
13232 * Testcase: ash -c 'exec 1>&0' must not complain. */
13234 g_parsefile->fd = -1;
13235 evalstring(minusc, 0);
13238 if (sflag || minusc == NULL) {
13239 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13241 const char *hp = lookupvar("HISTFILE");
13243 line_input_state->hist_file = hp;
13246 state4: /* XXX ??? - why isn't this before the "if" statement */
13254 extern void _mcleanup(void);
13264 * Copyright (c) 1989, 1991, 1993, 1994
13265 * The Regents of the University of California. All rights reserved.
13267 * This code is derived from software contributed to Berkeley by
13268 * Kenneth Almquist.
13270 * Redistribution and use in source and binary forms, with or without
13271 * modification, are permitted provided that the following conditions
13273 * 1. Redistributions of source code must retain the above copyright
13274 * notice, this list of conditions and the following disclaimer.
13275 * 2. Redistributions in binary form must reproduce the above copyright
13276 * notice, this list of conditions and the following disclaimer in the
13277 * documentation and/or other materials provided with the distribution.
13278 * 3. Neither the name of the University nor the names of its contributors
13279 * may be used to endorse or promote products derived from this software
13280 * without specific prior written permission.
13282 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13283 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13284 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13285 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13286 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13287 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13288 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13289 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13290 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13291 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF