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 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 // disabled by vda: cannot understand how it was supposed to work -
146 // cannot fix bugs. That's why you have to explain your non-trivial designs!
147 // /* do we generate EXSIG events */
148 // int exsig; /* counter */
149 volatile int suppressint; /* counter */
151 // pendingsig -> pending_sig
152 // intpending -> pending_int
153 volatile /*sig_atomic_t*/ smallint intpending; /* 1 = got SIGINT */
154 /* last pending signal */
155 volatile /*sig_atomic_t*/ smallint pendingsig;
156 smallint exception_type; /* kind of exception (0..5) */
158 #define EXINT 0 /* SIGINT received */
159 #define EXERROR 1 /* a generic error */
160 #define EXSHELLPROC 2 /* execute a shell procedure */
161 #define EXEXEC 3 /* command execution failed */
162 #define EXEXIT 4 /* exit the shell */
163 #define EXSIG 5 /* trapped signal in wait(1) */
166 char nullstr[1]; /* zero length string */
169 #define eflag optlist[0]
170 #define fflag optlist[1]
171 #define Iflag optlist[2]
172 #define iflag optlist[3]
173 #define mflag optlist[4]
174 #define nflag optlist[5]
175 #define sflag optlist[6]
176 #define xflag optlist[7]
177 #define vflag optlist[8]
178 #define Cflag optlist[9]
179 #define aflag optlist[10]
180 #define bflag optlist[11]
181 #define uflag optlist[12]
182 #define viflag optlist[13]
184 #define nolog optlist[14]
185 #define debug optlist[15]
188 /* trap handler commands */
190 * Sigmode records the current value of the signal handlers for the various
191 * modes. A value of zero means that the current handler is not known.
192 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
194 char sigmode[NSIG - 1];
195 #define S_DFL 1 /* default signal handling (SIG_DFL) */
196 #define S_CATCH 2 /* signal is caught */
197 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
198 #define S_HARD_IGN 4 /* signal is ignored permenantly */
200 /* indicates specified signal received */
201 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
204 /* Rarely referenced stuff */
205 #if ENABLE_ASH_RANDOM_SUPPORT
206 /* Random number generators */
207 int32_t random_galois_LFSR; /* Galois LFSR (fast but weak). signed! */
208 uint32_t random_LCG; /* LCG (fast but weak) */
210 pid_t backgndpid; /* pid of last background process */
211 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
213 extern struct globals_misc *const ash_ptr_to_globals_misc;
214 #define G_misc (*ash_ptr_to_globals_misc)
215 #define rootpid (G_misc.rootpid )
216 #define shlvl (G_misc.shlvl )
217 #define minusc (G_misc.minusc )
218 #define curdir (G_misc.curdir )
219 #define physdir (G_misc.physdir )
220 #define arg0 (G_misc.arg0 )
221 #define exception_handler (G_misc.exception_handler)
222 #define exception_type (G_misc.exception_type )
223 #define suppressint (G_misc.suppressint )
224 #define intpending (G_misc.intpending )
225 //#define exsig (G_misc.exsig )
226 #define pendingsig (G_misc.pendingsig )
227 #define isloginsh (G_misc.isloginsh )
228 #define nullstr (G_misc.nullstr )
229 #define optlist (G_misc.optlist )
230 #define sigmode (G_misc.sigmode )
231 #define gotsig (G_misc.gotsig )
232 #define trap (G_misc.trap )
233 #define random_galois_LFSR (G_misc.random_galois_LFSR)
234 #define random_LCG (G_misc.random_LCG )
235 #define backgndpid (G_misc.backgndpid )
236 #define job_warning (G_misc.job_warning)
237 #define INIT_G_misc() do { \
238 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
245 /* ============ DEBUG */
247 static void trace_printf(const char *fmt, ...);
248 static void trace_vprintf(const char *fmt, va_list va);
249 # define TRACE(param) trace_printf param
250 # define TRACEV(param) trace_vprintf param
251 # define close(fd) do { \
253 if (close(dfd) < 0) \
254 bb_error_msg("bug on %d: closing %d(0x%x)", \
255 __LINE__, dfd, dfd); \
258 # define TRACE(param)
259 # define TRACEV(param)
263 /* ============ Utility functions */
264 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
266 /* C99 says: "char" declaration may be signed or unsigned by default */
267 #define signed_char2int(sc) ((int)(signed char)(sc))
269 static int isdigit_str9(const char *str)
271 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
272 while (--maxlen && isdigit(*str))
274 return (*str == '\0');
278 /* ============ Interrupts / exceptions */
280 * These macros allow the user to suspend the handling of interrupt signals
281 * over a period of time. This is similar to SIGHOLD or to sigblock, but
282 * much more efficient and portable. (But hacking the kernel is so much
283 * more fun than worrying about efficiency and portability. :-))
285 #define INT_OFF do { \
291 * Called to raise an exception. Since C doesn't include exceptions, we
292 * just do a longjmp to the exception handler. The type of exception is
293 * stored in the global variable "exception_type".
295 static void raise_exception(int) NORETURN;
297 raise_exception(int e)
300 if (exception_handler == NULL)
305 longjmp(exception_handler->loc, 1);
308 #define raise_exception(e) do { \
309 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
310 raise_exception(e); \
315 * Called from trap.c when a SIGINT is received. (If the user specifies
316 * that SIGINT is to be trapped or ignored using the trap builtin, then
317 * this routine is not called.) Suppressint is nonzero when interrupts
318 * are held using the INT_OFF macro. (The test for iflag is just
319 * defensive programming.)
321 static void raise_interrupt(void) NORETURN;
323 raise_interrupt(void)
328 /* Signal is not automatically unmasked after it is raised,
329 * do it ourself - unmask all signals */
330 sigprocmask_allsigs(SIG_UNBLOCK);
331 /* pendingsig = 0; - now done in onsig() */
334 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
335 if (!(rootshell && iflag)) {
336 /* Kill ourself with SIGINT */
337 signal(SIGINT, SIG_DFL);
342 raise_exception(ex_type);
346 #define raise_interrupt() do { \
347 TRACE(("raising interrupt on line %d\n", __LINE__)); \
352 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
356 if (--suppressint == 0 && intpending) {
360 #define INT_ON int_on()
361 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
369 #define FORCE_INT_ON force_int_on()
371 #define SAVE_INT(v) ((v) = suppressint)
373 #define RESTORE_INT(v) do { \
376 if (suppressint == 0 && intpending) \
381 /* ============ Stdout/stderr output */
384 outstr(const char *p, FILE *file)
392 flush_stdout_stderr(void)
409 outcslow(int c, FILE *dest)
417 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
419 out1fmt(const char *fmt, ...)
426 r = vprintf(fmt, ap);
432 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
434 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
441 ret = vsnprintf(outbuf, length, fmt, ap);
448 out1str(const char *p)
454 out2str(const char *p)
461 /* ============ Parser structures */
463 /* control characters in argument strings */
464 #define CTLESC ((unsigned char)'\201') /* escape next character */
465 #define CTLVAR ((unsigned char)'\202') /* variable defn */
466 #define CTLENDVAR ((unsigned char)'\203')
467 #define CTLBACKQ ((unsigned char)'\204')
468 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
469 /* CTLBACKQ | CTLQUOTE == '\205' */
470 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
471 #define CTLENDARI ((unsigned char)'\207')
472 #define CTLQUOTEMARK ((unsigned char)'\210')
474 /* variable substitution byte (follows CTLVAR) */
475 #define VSTYPE 0x0f /* type of variable substitution */
476 #define VSNUL 0x10 /* colon--treat the empty string as unset */
477 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
479 /* values of VSTYPE field */
480 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
481 #define VSMINUS 0x2 /* ${var-text} */
482 #define VSPLUS 0x3 /* ${var+text} */
483 #define VSQUESTION 0x4 /* ${var?message} */
484 #define VSASSIGN 0x5 /* ${var=text} */
485 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
486 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
487 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
488 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
489 #define VSLENGTH 0xa /* ${#var} */
490 #if ENABLE_ASH_BASH_COMPAT
491 #define VSSUBSTR 0xc /* ${var:position:length} */
492 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
493 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
496 static const char dolatstr[] ALIGN1 = {
497 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
517 #if ENABLE_ASH_BASH_COMPAT
534 smallint type; /* Nxxxx */
537 union node *redirect;
542 smallint pipe_backgnd;
543 struct nodelist *cmdlist;
549 union node *redirect;
562 union node *elsepart;
589 struct nodelist *backquote;
592 /* nfile and ndup layout must match!
593 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
594 * that it is actually NTO2 (>&file), and change its type.
611 char *_unused_expfname;
630 struct nredir nredir;
631 struct nbinary nbinary;
635 struct nclist nclist;
644 * NODE_EOF is returned by parsecmd when it encounters an end of file.
645 * It must be distinct from NULL.
647 #define NODE_EOF ((union node *) -1L)
650 struct nodelist *next;
663 freefunc(struct funcnode *f)
665 if (f && --f->count < 0)
670 /* ============ Debugging output */
674 static FILE *tracefile;
677 trace_printf(const char *fmt, ...)
684 fprintf(tracefile, "%u ", (int) time(NULL));
686 fprintf(tracefile, "[%u] ", (int) getpid());
688 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pendingsig, intpending, suppressint);
690 vfprintf(tracefile, fmt, va);
695 trace_vprintf(const char *fmt, va_list va)
700 fprintf(tracefile, "%u ", (int) time(NULL));
702 fprintf(tracefile, "[%u] ", (int) getpid());
704 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pendingsig, intpending, suppressint);
705 vfprintf(tracefile, fmt, va);
709 trace_puts(const char *s)
717 trace_puts_quoted(char *s)
724 putc('"', tracefile);
725 for (p = s; *p; p++) {
727 case '\n': c = 'n'; goto backslash;
728 case '\t': c = 't'; goto backslash;
729 case '\r': c = 'r'; goto backslash;
730 case '"': c = '"'; goto backslash;
731 case '\\': c = '\\'; goto backslash;
732 case CTLESC: c = 'e'; goto backslash;
733 case CTLVAR: c = 'v'; goto backslash;
734 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
735 case CTLBACKQ: c = 'q'; goto backslash;
736 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
738 putc('\\', tracefile);
742 if (*p >= ' ' && *p <= '~')
745 putc('\\', tracefile);
746 putc(*p >> 6 & 03, tracefile);
747 putc(*p >> 3 & 07, tracefile);
748 putc(*p & 07, tracefile);
753 putc('"', tracefile);
757 trace_puts_args(char **ap)
764 trace_puts_quoted(*ap);
766 putc('\n', tracefile);
769 putc(' ', tracefile);
784 /* leave open because libedit might be using it */
787 strcpy(s, "./trace");
789 if (!freopen(s, "a", tracefile)) {
790 fprintf(stderr, "Can't re-open %s\n", s);
795 tracefile = fopen(s, "a");
796 if (tracefile == NULL) {
797 fprintf(stderr, "Can't open %s\n", s);
803 flags = fcntl(fileno(tracefile), F_GETFL);
805 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
807 setlinebuf(tracefile);
808 fputs("\nTracing started.\n", tracefile);
812 indent(int amount, char *pfx, FILE *fp)
816 for (i = 0; i < amount; i++) {
817 if (pfx && i == amount - 1)
823 /* little circular references here... */
824 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
827 sharg(union node *arg, FILE *fp)
830 struct nodelist *bqlist;
833 if (arg->type != NARG) {
834 out1fmt("<node type %d>\n", arg->type);
837 bqlist = arg->narg.backquote;
838 for (p = arg->narg.text; *p; p++) {
847 if (subtype == VSLENGTH)
856 switch (subtype & VSTYPE) {
889 out1fmt("<subtype %d>", subtype);
896 case CTLBACKQ|CTLQUOTE:
899 shtree(bqlist->n, -1, NULL, fp);
910 shcmd(union node *cmd, FILE *fp)
918 for (np = cmd->ncmd.args; np; np = np->narg.next) {
924 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
928 switch (np->nfile.type) {
929 case NTO: s = ">>"+1; dftfd = 1; break;
930 case NCLOBBER: s = ">|"; dftfd = 1; break;
931 case NAPPEND: s = ">>"; dftfd = 1; break;
932 #if ENABLE_ASH_BASH_COMPAT
935 case NTOFD: s = ">&"; dftfd = 1; break;
936 case NFROM: s = "<"; break;
937 case NFROMFD: s = "<&"; break;
938 case NFROMTO: s = "<>"; break;
939 default: s = "*error*"; break;
941 if (np->nfile.fd != dftfd)
942 fprintf(fp, "%d", np->nfile.fd);
944 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
945 fprintf(fp, "%d", np->ndup.dupfd);
947 sharg(np->nfile.fname, fp);
954 shtree(union node *n, int ind, char *pfx, FILE *fp)
962 indent(ind, pfx, fp);
979 shtree(n->nbinary.ch1, ind, NULL, fp);
982 shtree(n->nbinary.ch2, ind, NULL, fp);
990 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
991 shtree(lp->n, 0, NULL, fp);
995 if (n->npipe.pipe_backgnd)
1001 fprintf(fp, "<node type %d>", n->type);
1009 showtree(union node *n)
1011 trace_puts("showtree called\n");
1012 shtree(n, 1, NULL, stderr);
1018 /* ============ Parser data */
1021 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1024 struct strlist *next;
1031 struct strpush *prev; /* preceding string on stack */
1033 int prev_left_in_line;
1034 #if ENABLE_ASH_ALIAS
1035 struct alias *ap; /* if push was associated with an alias */
1037 char *string; /* remember the string since it may change */
1041 struct parsefile *prev; /* preceding file on stack */
1042 int linno; /* current line */
1043 int fd; /* file descriptor (or -1 if string) */
1044 int left_in_line; /* number of chars left in this line */
1045 int left_in_buffer; /* number of chars left in this buffer past the line */
1046 char *next_to_pgetc; /* next char in buffer */
1047 char *buf; /* input buffer */
1048 struct strpush *strpush; /* for pushing strings at this level */
1049 struct strpush basestrpush; /* so pushing one is fast */
1052 static struct parsefile basepf; /* top level input file */
1053 static struct parsefile *g_parsefile = &basepf; /* current input file */
1054 static int startlinno; /* line # where last token started */
1055 static char *commandname; /* currently executing command */
1056 static struct strlist *cmdenviron; /* environment for builtin command */
1057 static uint8_t exitstatus; /* exit status of last command */
1060 /* ============ Message printing */
1063 ash_vmsg(const char *msg, va_list ap)
1065 fprintf(stderr, "%s: ", arg0);
1067 if (strcmp(arg0, commandname))
1068 fprintf(stderr, "%s: ", commandname);
1069 if (!iflag || g_parsefile->fd)
1070 fprintf(stderr, "line %d: ", startlinno);
1072 vfprintf(stderr, msg, ap);
1073 outcslow('\n', stderr);
1077 * Exverror is called to raise the error exception. If the second argument
1078 * is not NULL then error prints an error message using printf style
1079 * formatting. It then raises the error exception.
1081 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1083 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1087 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1089 TRACE(("\") pid=%d\n", getpid()));
1091 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1096 flush_stdout_stderr();
1097 raise_exception(cond);
1101 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1103 ash_msg_and_raise_error(const char *msg, ...)
1108 ash_vmsg_and_raise(EXERROR, msg, ap);
1113 static void raise_error_syntax(const char *) NORETURN;
1115 raise_error_syntax(const char *msg)
1117 ash_msg_and_raise_error("syntax error: %s", msg);
1121 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1123 ash_msg_and_raise(int cond, const char *msg, ...)
1128 ash_vmsg_and_raise(cond, msg, ap);
1134 * error/warning routines for external builtins
1137 ash_msg(const char *fmt, ...)
1147 * Return a string describing an error. The returned string may be a
1148 * pointer to a static buffer that will be overwritten on the next call.
1149 * Action describes the operation that got the error.
1152 errmsg(int e, const char *em)
1154 if (e == ENOENT || e == ENOTDIR) {
1161 /* ============ Memory allocation */
1164 * It appears that grabstackstr() will barf with such alignments
1165 * because stalloc() will return a string allocated in a new stackblock.
1167 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1169 /* Most machines require the value returned from malloc to be aligned
1170 * in some way. The following macro will get this right
1171 * on many machines. */
1172 SHELL_SIZE = sizeof(union {int i; char *cp; double d; }) - 1,
1173 /* Minimum size of a block */
1174 MINSIZE = SHELL_ALIGN(504),
1177 struct stack_block {
1178 struct stack_block *prev;
1179 char space[MINSIZE];
1183 struct stack_block *stackp;
1186 struct stackmark *marknext;
1190 struct globals_memstack {
1191 struct stack_block *g_stackp; // = &stackbase;
1192 struct stackmark *markp;
1193 char *g_stacknxt; // = stackbase.space;
1194 char *sstrend; // = stackbase.space + MINSIZE;
1195 size_t g_stacknleft; // = MINSIZE;
1196 int herefd; // = -1;
1197 struct stack_block stackbase;
1199 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1200 #define G_memstack (*ash_ptr_to_globals_memstack)
1201 #define g_stackp (G_memstack.g_stackp )
1202 #define markp (G_memstack.markp )
1203 #define g_stacknxt (G_memstack.g_stacknxt )
1204 #define sstrend (G_memstack.sstrend )
1205 #define g_stacknleft (G_memstack.g_stacknleft)
1206 #define herefd (G_memstack.herefd )
1207 #define stackbase (G_memstack.stackbase )
1208 #define INIT_G_memstack() do { \
1209 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1211 g_stackp = &stackbase; \
1212 g_stacknxt = stackbase.space; \
1213 g_stacknleft = MINSIZE; \
1214 sstrend = stackbase.space + MINSIZE; \
1218 #define stackblock() ((void *)g_stacknxt)
1219 #define stackblocksize() g_stacknleft
1223 ckrealloc(void * p, size_t nbytes)
1225 p = realloc(p, nbytes);
1227 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1232 ckmalloc(size_t nbytes)
1234 return ckrealloc(NULL, nbytes);
1238 ckzalloc(size_t nbytes)
1240 return memset(ckmalloc(nbytes), 0, nbytes);
1244 * Make a copy of a string in safe storage.
1247 ckstrdup(const char *s)
1249 char *p = strdup(s);
1251 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1256 * Parse trees for commands are allocated in lifo order, so we use a stack
1257 * to make this more efficient, and also to avoid all sorts of exception
1258 * handling code to handle interrupts in the middle of a parse.
1260 * The size 504 was chosen because the Ultrix malloc handles that size
1264 stalloc(size_t nbytes)
1269 aligned = SHELL_ALIGN(nbytes);
1270 if (aligned > g_stacknleft) {
1273 struct stack_block *sp;
1275 blocksize = aligned;
1276 if (blocksize < MINSIZE)
1277 blocksize = MINSIZE;
1278 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1279 if (len < blocksize)
1280 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1283 sp->prev = g_stackp;
1284 g_stacknxt = sp->space;
1285 g_stacknleft = blocksize;
1286 sstrend = g_stacknxt + blocksize;
1291 g_stacknxt += aligned;
1292 g_stacknleft -= aligned;
1297 stzalloc(size_t nbytes)
1299 return memset(stalloc(nbytes), 0, nbytes);
1306 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1307 write(STDERR_FILENO, "stunalloc\n", 10);
1311 g_stacknleft += g_stacknxt - (char *)p;
1316 * Like strdup but works with the ash stack.
1319 ststrdup(const char *p)
1321 size_t len = strlen(p) + 1;
1322 return memcpy(stalloc(len), p, len);
1326 setstackmark(struct stackmark *mark)
1328 mark->stackp = g_stackp;
1329 mark->stacknxt = g_stacknxt;
1330 mark->stacknleft = g_stacknleft;
1331 mark->marknext = markp;
1336 popstackmark(struct stackmark *mark)
1338 struct stack_block *sp;
1344 markp = mark->marknext;
1345 while (g_stackp != mark->stackp) {
1347 g_stackp = sp->prev;
1350 g_stacknxt = mark->stacknxt;
1351 g_stacknleft = mark->stacknleft;
1352 sstrend = mark->stacknxt + mark->stacknleft;
1357 * When the parser reads in a string, it wants to stick the string on the
1358 * stack and only adjust the stack pointer when it knows how big the
1359 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1360 * of space on top of the stack and stackblocklen returns the length of
1361 * this block. Growstackblock will grow this space by at least one byte,
1362 * possibly moving it (like realloc). Grabstackblock actually allocates the
1363 * part of the block that has been used.
1366 growstackblock(void)
1370 newlen = g_stacknleft * 2;
1371 if (newlen < g_stacknleft)
1372 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1376 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1377 struct stack_block *oldstackp;
1378 struct stackmark *xmark;
1379 struct stack_block *sp;
1380 struct stack_block *prevstackp;
1384 oldstackp = g_stackp;
1386 prevstackp = sp->prev;
1387 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1388 sp = ckrealloc(sp, grosslen);
1389 sp->prev = prevstackp;
1391 g_stacknxt = sp->space;
1392 g_stacknleft = newlen;
1393 sstrend = sp->space + newlen;
1396 * Stack marks pointing to the start of the old block
1397 * must be relocated to point to the new block
1400 while (xmark != NULL && xmark->stackp == oldstackp) {
1401 xmark->stackp = g_stackp;
1402 xmark->stacknxt = g_stacknxt;
1403 xmark->stacknleft = g_stacknleft;
1404 xmark = xmark->marknext;
1408 char *oldspace = g_stacknxt;
1409 size_t oldlen = g_stacknleft;
1410 char *p = stalloc(newlen);
1412 /* free the space we just allocated */
1413 g_stacknxt = memcpy(p, oldspace, oldlen);
1414 g_stacknleft += newlen;
1419 grabstackblock(size_t len)
1421 len = SHELL_ALIGN(len);
1423 g_stacknleft -= len;
1427 * The following routines are somewhat easier to use than the above.
1428 * The user declares a variable of type STACKSTR, which may be declared
1429 * to be a register. The macro STARTSTACKSTR initializes things. Then
1430 * the user uses the macro STPUTC to add characters to the string. In
1431 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1432 * grown as necessary. When the user is done, she can just leave the
1433 * string there and refer to it using stackblock(). Or she can allocate
1434 * the space for it using grabstackstr(). If it is necessary to allow
1435 * someone else to use the stack temporarily and then continue to grow
1436 * the string, the user should use grabstack to allocate the space, and
1437 * then call ungrabstr(p) to return to the previous mode of operation.
1439 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1440 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1441 * is space for at least one character.
1446 size_t len = stackblocksize();
1447 if (herefd >= 0 && len >= 1024) {
1448 full_write(herefd, stackblock(), len);
1449 return stackblock();
1452 return (char *)stackblock() + len;
1456 * Called from CHECKSTRSPACE.
1459 makestrspace(size_t newlen, char *p)
1461 size_t len = p - g_stacknxt;
1462 size_t size = stackblocksize();
1467 size = stackblocksize();
1469 if (nleft >= newlen)
1473 return (char *)stackblock() + len;
1477 stack_nputstr(const char *s, size_t n, char *p)
1479 p = makestrspace(n, p);
1480 p = (char *)memcpy(p, s, n) + n;
1485 stack_putstr(const char *s, char *p)
1487 return stack_nputstr(s, strlen(s), p);
1491 _STPUTC(int c, char *p)
1499 #define STARTSTACKSTR(p) ((p) = stackblock())
1500 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1501 #define CHECKSTRSPACE(n, p) do { \
1504 size_t m = sstrend - q; \
1506 (p) = makestrspace(l, q); \
1508 #define USTPUTC(c, p) (*(p)++ = (c))
1509 #define STACKSTRNUL(p) do { \
1510 if ((p) == sstrend) \
1511 (p) = growstackstr(); \
1514 #define STUNPUTC(p) (--(p))
1515 #define STTOPC(p) ((p)[-1])
1516 #define STADJUST(amount, p) ((p) += (amount))
1518 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1519 #define ungrabstackstr(s, p) stunalloc(s)
1520 #define stackstrend() ((void *)sstrend)
1523 /* ============ String helpers */
1526 * prefix -- see if pfx is a prefix of string.
1529 prefix(const char *string, const char *pfx)
1532 if (*pfx++ != *string++)
1535 return (char *) string;
1539 * Check for a valid number. This should be elsewhere.
1542 is_number(const char *p)
1547 } while (*++p != '\0');
1552 * Convert a string of digits to an integer, printing an error message on
1556 number(const char *s)
1559 ash_msg_and_raise_error(illnum, s);
1564 * Produce a possibly single quoted string suitable as input to the shell.
1565 * The return string is allocated on the stack.
1568 single_quote(const char *s)
1578 len = strchrnul(s, '\'') - s;
1580 q = p = makestrspace(len + 3, p);
1583 q = (char *)memcpy(q, s, len) + len;
1589 len = strspn(s, "'");
1593 q = p = makestrspace(len + 3, p);
1596 q = (char *)memcpy(q, s, len) + len;
1605 return stackblock();
1609 /* ============ nextopt */
1611 static char **argptr; /* argument list for builtin commands */
1612 static char *optionarg; /* set by nextopt (like getopt) */
1613 static char *optptr; /* used by nextopt */
1616 * XXX - should get rid of. Have all builtins use getopt(3).
1617 * The library getopt must have the BSD extension static variable
1618 * "optreset", otherwise it can't be used within the shell safely.
1620 * Standard option processing (a la getopt) for builtin routines.
1621 * The only argument that is passed to nextopt is the option string;
1622 * the other arguments are unnecessary. It returns the character,
1623 * or '\0' on end of input.
1626 nextopt(const char *optstring)
1633 if (p == NULL || *p == '\0') {
1634 /* We ate entire "-param", take next one */
1640 if (*++p == '\0') /* just "-" ? */
1643 if (LONE_DASH(p)) /* "--" ? */
1645 /* p => next "-param" */
1647 /* p => some option char in the middle of a "-param" */
1649 for (q = optstring; *q != c;) {
1651 ash_msg_and_raise_error("illegal option -%c", c);
1659 ash_msg_and_raise_error("no arg for -%c option", c);
1669 /* ============ Shell variables */
1672 * The parsefile structure pointed to by the global variable parsefile
1673 * contains information about the current file being read.
1676 int nparam; /* # of positional parameters (without $0) */
1677 #if ENABLE_ASH_GETOPTS
1678 int optind; /* next parameter to be processed by getopts */
1679 int optoff; /* used by getopts */
1681 unsigned char malloced; /* if parameter list dynamically allocated */
1682 char **p; /* parameter list */
1686 * Free the list of positional parameters.
1689 freeparam(volatile struct shparam *param)
1691 if (param->malloced) {
1693 ap = ap1 = param->p;
1700 #if ENABLE_ASH_GETOPTS
1701 static void FAST_FUNC getoptsreset(const char *value);
1705 struct var *next; /* next entry in hash list */
1706 int flags; /* flags are defined above */
1707 const char *text; /* name=value */
1708 void (*func)(const char *) FAST_FUNC; /* function to be called when */
1709 /* the variable gets set/unset */
1713 struct localvar *next; /* next local variable in list */
1714 struct var *vp; /* the variable that was made local */
1715 int flags; /* saved flags */
1716 const char *text; /* saved text */
1720 #define VEXPORT 0x01 /* variable is exported */
1721 #define VREADONLY 0x02 /* variable cannot be modified */
1722 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1723 #define VTEXTFIXED 0x08 /* text is statically allocated */
1724 #define VSTACK 0x10 /* text is allocated on the stack */
1725 #define VUNSET 0x20 /* the variable is not set */
1726 #define VNOFUNC 0x40 /* don't call the callback function */
1727 #define VNOSET 0x80 /* do not set variable - just readonly test */
1728 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1729 #if ENABLE_ASH_RANDOM_SUPPORT
1730 # define VDYNAMIC 0x200 /* dynamic variable */
1736 static const char defifsvar[] ALIGN1 = "IFS= \t\n";
1737 #define defifs (defifsvar + 4)
1739 static const char defifs[] ALIGN1 = " \t\n";
1743 /* Need to be before varinit_data[] */
1744 #if ENABLE_LOCALE_SUPPORT
1745 static void FAST_FUNC
1746 change_lc_all(const char *value)
1748 if (value && *value != '\0')
1749 setlocale(LC_ALL, value);
1751 static void FAST_FUNC
1752 change_lc_ctype(const char *value)
1754 if (value && *value != '\0')
1755 setlocale(LC_CTYPE, value);
1759 static void chkmail(void);
1760 static void changemail(const char *) FAST_FUNC;
1762 static void changepath(const char *) FAST_FUNC;
1763 #if ENABLE_ASH_RANDOM_SUPPORT
1764 static void change_random(const char *) FAST_FUNC;
1767 static const struct {
1770 void (*func)(const char *) FAST_FUNC;
1771 } varinit_data[] = {
1773 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1775 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
1778 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1779 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1781 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1782 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1783 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1784 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1785 #if ENABLE_ASH_GETOPTS
1786 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1788 #if ENABLE_ASH_RANDOM_SUPPORT
1789 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
1791 #if ENABLE_LOCALE_SUPPORT
1792 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1793 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
1795 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1796 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
1802 struct globals_var {
1803 struct shparam shellparam; /* $@ current positional parameters */
1804 struct redirtab *redirlist;
1806 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1807 struct var *vartab[VTABSIZE];
1808 struct var varinit[ARRAY_SIZE(varinit_data)];
1810 extern struct globals_var *const ash_ptr_to_globals_var;
1811 #define G_var (*ash_ptr_to_globals_var)
1812 #define shellparam (G_var.shellparam )
1813 //#define redirlist (G_var.redirlist )
1814 #define g_nullredirs (G_var.g_nullredirs )
1815 #define preverrout_fd (G_var.preverrout_fd)
1816 #define vartab (G_var.vartab )
1817 #define varinit (G_var.varinit )
1818 #define INIT_G_var() do { \
1820 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1822 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1823 varinit[i].flags = varinit_data[i].flags; \
1824 varinit[i].text = varinit_data[i].text; \
1825 varinit[i].func = varinit_data[i].func; \
1829 #define vifs varinit[0]
1831 # define vmail (&vifs)[1]
1832 # define vmpath (&vmail)[1]
1833 # define vpath (&vmpath)[1]
1835 # define vpath (&vifs)[1]
1837 #define vps1 (&vpath)[1]
1838 #define vps2 (&vps1)[1]
1839 #define vps4 (&vps2)[1]
1840 #if ENABLE_ASH_GETOPTS
1841 # define voptind (&vps4)[1]
1842 # if ENABLE_ASH_RANDOM_SUPPORT
1843 # define vrandom (&voptind)[1]
1846 # if ENABLE_ASH_RANDOM_SUPPORT
1847 # define vrandom (&vps4)[1]
1852 * The following macros access the values of the above variables.
1853 * They have to skip over the name. They return the null string
1854 * for unset variables.
1856 #define ifsval() (vifs.text + 4)
1857 #define ifsset() ((vifs.flags & VUNSET) == 0)
1859 # define mailval() (vmail.text + 5)
1860 # define mpathval() (vmpath.text + 9)
1861 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1863 #define pathval() (vpath.text + 5)
1864 #define ps1val() (vps1.text + 4)
1865 #define ps2val() (vps2.text + 4)
1866 #define ps4val() (vps4.text + 4)
1867 #if ENABLE_ASH_GETOPTS
1868 # define optindval() (voptind.text + 7)
1872 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1873 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1875 #if ENABLE_ASH_GETOPTS
1876 static void FAST_FUNC
1877 getoptsreset(const char *value)
1879 shellparam.optind = number(value);
1880 shellparam.optoff = -1;
1885 * Return of a legal variable name (a letter or underscore followed by zero or
1886 * more letters, underscores, and digits).
1889 endofname(const char *name)
1897 if (!is_in_name(*p))
1904 * Compares two strings up to the first = or '\0'. The first
1905 * string must be terminated by '='; the second may be terminated by
1906 * either '=' or '\0'.
1909 varcmp(const char *p, const char *q)
1913 while ((c = *p) == (d = *q)) {
1928 varequal(const char *a, const char *b)
1930 return !varcmp(a, b);
1934 * Find the appropriate entry in the hash table from the name.
1936 static struct var **
1937 hashvar(const char *p)
1941 hashval = ((unsigned char) *p) << 4;
1942 while (*p && *p != '=')
1943 hashval += (unsigned char) *p++;
1944 return &vartab[hashval % VTABSIZE];
1948 vpcmp(const void *a, const void *b)
1950 return varcmp(*(const char **)a, *(const char **)b);
1954 * This routine initializes the builtin variables.
1964 * PS1 depends on uid
1966 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1967 vps1.text = "PS1=\\w \\$ ";
1970 vps1.text = "PS1=# ";
1973 end = vp + ARRAY_SIZE(varinit);
1975 vpp = hashvar(vp->text);
1978 } while (++vp < end);
1981 static struct var **
1982 findvar(struct var **vpp, const char *name)
1984 for (; *vpp; vpp = &(*vpp)->next) {
1985 if (varequal((*vpp)->text, name)) {
1993 * Find the value of a variable. Returns NULL if not set.
1996 lookupvar(const char *name)
2000 v = *findvar(hashvar(name), name);
2002 #if ENABLE_ASH_RANDOM_SUPPORT
2004 * Dynamic variables are implemented roughly the same way they are
2005 * in bash. Namely, they're "special" so long as they aren't unset.
2006 * As soon as they're unset, they're no longer dynamic, and dynamic
2007 * lookup will no longer happen at that point. -- PFM.
2009 if ((v->flags & VDYNAMIC))
2012 if (!(v->flags & VUNSET))
2013 return strchrnul(v->text, '=') + 1;
2019 * Search the environment of a builtin command.
2022 bltinlookup(const char *name)
2026 for (sp = cmdenviron; sp; sp = sp->next) {
2027 if (varequal(sp->text, name))
2028 return strchrnul(sp->text, '=') + 1;
2030 return lookupvar(name);
2034 * Same as setvar except that the variable and value are passed in
2035 * the first argument as name=value. Since the first argument will
2036 * be actually stored in the table, it should not be a string that
2038 * Called with interrupts off.
2041 setvareq(char *s, int flags)
2043 struct var *vp, **vpp;
2046 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2047 vp = *findvar(vpp, s);
2049 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2052 if (flags & VNOSAVE)
2055 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2061 if (vp->func && (flags & VNOFUNC) == 0)
2062 (*vp->func)(strchrnul(s, '=') + 1);
2064 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2065 free((char*)vp->text);
2067 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2072 vp = ckzalloc(sizeof(*vp));
2074 /*vp->func = NULL; - ckzalloc did it */
2077 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2084 * Set the value of a variable. The flags argument is ored with the
2085 * flags of the variable. If val is NULL, the variable is unset.
2088 setvar(const char *name, const char *val, int flags)
2095 q = endofname(name);
2096 p = strchrnul(q, '=');
2098 if (!namelen || p != q)
2099 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2104 vallen = strlen(val);
2107 nameeq = ckmalloc(namelen + vallen + 2);
2108 p = (char *)memcpy(nameeq, name, namelen) + namelen;
2111 p = (char *)memcpy(p, val, vallen) + vallen;
2114 setvareq(nameeq, flags | VNOSAVE);
2118 #if ENABLE_ASH_GETOPTS
2120 * Safe version of setvar, returns 1 on success 0 on failure.
2123 setvarsafe(const char *name, const char *val, int flags)
2126 volatile int saveint;
2127 struct jmploc *volatile savehandler = exception_handler;
2128 struct jmploc jmploc;
2131 if (setjmp(jmploc.loc))
2134 exception_handler = &jmploc;
2135 setvar(name, val, flags);
2138 exception_handler = savehandler;
2139 RESTORE_INT(saveint);
2145 * Unset the specified variable.
2148 unsetvar(const char *s)
2154 vpp = findvar(hashvar(s), s);
2158 int flags = vp->flags;
2161 if (flags & VREADONLY)
2163 #if ENABLE_ASH_RANDOM_SUPPORT
2164 vp->flags &= ~VDYNAMIC;
2168 if ((flags & VSTRFIXED) == 0) {
2170 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2171 free((char*)vp->text);
2177 vp->flags &= ~VEXPORT;
2187 * Process a linked list of variable assignments.
2190 listsetvar(struct strlist *list_set_var, int flags)
2192 struct strlist *lp = list_set_var;
2198 setvareq(lp->text, flags);
2205 * Generate a list of variables satisfying the given conditions.
2208 listvars(int on, int off, char ***end)
2219 for (vp = *vpp; vp; vp = vp->next) {
2220 if ((vp->flags & mask) == on) {
2221 if (ep == stackstrend())
2222 ep = growstackstr();
2223 *ep++ = (char *) vp->text;
2226 } while (++vpp < vartab + VTABSIZE);
2227 if (ep == stackstrend())
2228 ep = growstackstr();
2232 return grabstackstr(ep);
2236 /* ============ Path search helper
2238 * The variable path (passed by reference) should be set to the start
2239 * of the path before the first call; path_advance will update
2240 * this value as it proceeds. Successive calls to path_advance will return
2241 * the possible path expansions in sequence. If an option (indicated by
2242 * a percent sign) appears in the path entry then the global variable
2243 * pathopt will be set to point to it; otherwise pathopt will be set to
2246 static const char *pathopt; /* set by path_advance */
2249 path_advance(const char **path, const char *name)
2259 for (p = start; *p && *p != ':' && *p != '%'; p++)
2261 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2262 while (stackblocksize() < len)
2266 memcpy(q, start, p - start);
2274 while (*p && *p != ':')
2281 return stalloc(len);
2285 /* ============ Prompt */
2287 static smallint doprompt; /* if set, prompt the user */
2288 static smallint needprompt; /* true if interactive and at start of line */
2290 #if ENABLE_FEATURE_EDITING
2291 static line_input_t *line_input_state;
2292 static const char *cmdedit_prompt;
2294 putprompt(const char *s)
2296 if (ENABLE_ASH_EXPAND_PRMT) {
2297 free((char*)cmdedit_prompt);
2298 cmdedit_prompt = ckstrdup(s);
2305 putprompt(const char *s)
2311 #if ENABLE_ASH_EXPAND_PRMT
2312 /* expandstr() needs parsing machinery, so it is far away ahead... */
2313 static const char *expandstr(const char *ps);
2315 #define expandstr(s) s
2319 setprompt(int whichprompt)
2322 #if ENABLE_ASH_EXPAND_PRMT
2323 struct stackmark smark;
2328 switch (whichprompt) {
2338 #if ENABLE_ASH_EXPAND_PRMT
2339 setstackmark(&smark);
2340 stalloc(stackblocksize());
2342 putprompt(expandstr(prompt));
2343 #if ENABLE_ASH_EXPAND_PRMT
2344 popstackmark(&smark);
2349 /* ============ The cd and pwd commands */
2351 #define CD_PHYSICAL 1
2354 static int docd(const char *, int);
2363 while ((i = nextopt("LP"))) {
2365 flags ^= CD_PHYSICAL;
2374 * Update curdir (the name of the current directory) in response to a
2378 updatepwd(const char *dir)
2385 cdcomppath = ststrdup(dir);
2388 if (curdir == nullstr)
2390 new = stack_putstr(curdir, new);
2392 new = makestrspace(strlen(dir) + 2, new);
2393 lim = (char *)stackblock() + 1;
2397 if (new > lim && *lim == '/')
2402 if (dir[1] == '/' && dir[2] != '/') {
2408 p = strtok(cdcomppath, "/");
2412 if (p[1] == '.' && p[2] == '\0') {
2424 new = stack_putstr(p, new);
2432 return stackblock();
2436 * Find out what the current directory is. If we already know the current
2437 * directory, this routine returns immediately.
2442 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2443 return dir ? dir : nullstr;
2447 setpwd(const char *val, int setold)
2451 oldcur = dir = curdir;
2454 setvar("OLDPWD", oldcur, VEXPORT);
2457 if (physdir != nullstr) {
2458 if (physdir != oldcur)
2462 if (oldcur == val || !val) {
2468 dir = ckstrdup(val);
2469 if (oldcur != dir && oldcur != nullstr) {
2474 setvar("PWD", dir, VEXPORT);
2477 static void hashcd(void);
2480 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2481 * know that the current directory has changed.
2484 docd(const char *dest, int flags)
2486 const char *dir = 0;
2489 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2492 if (!(flags & CD_PHYSICAL)) {
2493 dir = updatepwd(dest);
2507 static int FAST_FUNC
2508 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2520 dest = bltinlookup(homestr);
2521 else if (LONE_DASH(dest)) {
2522 dest = bltinlookup("OLDPWD");
2544 path = bltinlookup("CDPATH");
2553 p = path_advance(&path, dest);
2554 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2558 if (!docd(p, flags))
2563 ash_msg_and_raise_error("can't cd to %s", dest);
2566 if (flags & CD_PRINT)
2567 out1fmt(snlfmt, curdir);
2571 static int FAST_FUNC
2572 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2575 const char *dir = curdir;
2579 if (physdir == nullstr)
2583 out1fmt(snlfmt, dir);
2588 /* ============ ... */
2591 #define IBUFSIZ COMMON_BUFSIZE
2592 /* buffer for top level input file */
2593 #define basebuf bb_common_bufsiz1
2595 /* Syntax classes */
2596 #define CWORD 0 /* character is nothing special */
2597 #define CNL 1 /* newline character */
2598 #define CBACK 2 /* a backslash character */
2599 #define CSQUOTE 3 /* single quote */
2600 #define CDQUOTE 4 /* double quote */
2601 #define CENDQUOTE 5 /* a terminating quote */
2602 #define CBQUOTE 6 /* backwards single quote */
2603 #define CVAR 7 /* a dollar sign */
2604 #define CENDVAR 8 /* a '}' character */
2605 #define CLP 9 /* a left paren in arithmetic */
2606 #define CRP 10 /* a right paren in arithmetic */
2607 #define CENDFILE 11 /* end of file */
2608 #define CCTL 12 /* like CWORD, except it must be escaped */
2609 #define CSPCL 13 /* these terminate a word */
2610 #define CIGN 14 /* character should be ignored */
2612 #if ENABLE_ASH_ALIAS
2616 #define PEOA_OR_PEOF PEOA
2620 #define PEOA_OR_PEOF PEOF
2623 /* number syntax index */
2624 #define BASESYNTAX 0 /* not in quotes */
2625 #define DQSYNTAX 1 /* in double quotes */
2626 #define SQSYNTAX 2 /* in single quotes */
2627 #define ARISYNTAX 3 /* in arithmetic */
2628 #define PSSYNTAX 4 /* prompt */
2630 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
2631 #define USE_SIT_FUNCTION
2634 #if ENABLE_SH_MATH_SUPPORT
2635 static const char S_I_T[][4] = {
2636 #if ENABLE_ASH_ALIAS
2637 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
2639 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2640 { CNL, CNL, CNL, CNL }, /* 2, \n */
2641 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2642 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2643 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2644 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2645 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2646 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2647 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2648 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2649 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
2650 #ifndef USE_SIT_FUNCTION
2651 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2652 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2653 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2657 static const char S_I_T[][3] = {
2658 #if ENABLE_ASH_ALIAS
2659 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
2661 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2662 { CNL, CNL, CNL }, /* 2, \n */
2663 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2664 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2665 { CVAR, CVAR, CWORD }, /* 5, $ */
2666 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2667 { CSPCL, CWORD, CWORD }, /* 7, ( */
2668 { CSPCL, CWORD, CWORD }, /* 8, ) */
2669 { CBACK, CBACK, CCTL }, /* 9, \ */
2670 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2671 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
2672 #ifndef USE_SIT_FUNCTION
2673 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2674 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2675 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2678 #endif /* SH_MATH_SUPPORT */
2680 #ifdef USE_SIT_FUNCTION
2683 SIT(int c, int syntax)
2685 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2686 #if ENABLE_ASH_ALIAS
2687 static const char syntax_index_table[] ALIGN1 = {
2688 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2689 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2690 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2694 static const char syntax_index_table[] ALIGN1 = {
2695 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2696 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2697 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2704 if (c == PEOF) { /* 2^8+2 */
2707 #if ENABLE_ASH_ALIAS
2708 if (c == PEOA) { /* 2^8+1 */
2713 if ((unsigned char)c >= (unsigned char)(CTLESC)
2714 && (unsigned char)c <= (unsigned char)(CTLQUOTEMARK)
2718 s = strchrnul(spec_symbls, c);
2722 indx = syntax_index_table[s - spec_symbls];
2724 return S_I_T[indx][syntax];
2727 #else /* !USE_SIT_FUNCTION */
2729 #if ENABLE_ASH_ALIAS
2730 #define CSPCL_CIGN_CIGN_CIGN 0
2731 #define CSPCL_CWORD_CWORD_CWORD 1
2732 #define CNL_CNL_CNL_CNL 2
2733 #define CWORD_CCTL_CCTL_CWORD 3
2734 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2735 #define CVAR_CVAR_CWORD_CVAR 5
2736 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2737 #define CSPCL_CWORD_CWORD_CLP 7
2738 #define CSPCL_CWORD_CWORD_CRP 8
2739 #define CBACK_CBACK_CCTL_CBACK 9
2740 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2741 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2742 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2743 #define CWORD_CWORD_CWORD_CWORD 13
2744 #define CCTL_CCTL_CCTL_CCTL 14
2746 #define CSPCL_CWORD_CWORD_CWORD 0
2747 #define CNL_CNL_CNL_CNL 1
2748 #define CWORD_CCTL_CCTL_CWORD 2
2749 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2750 #define CVAR_CVAR_CWORD_CVAR 4
2751 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2752 #define CSPCL_CWORD_CWORD_CLP 6
2753 #define CSPCL_CWORD_CWORD_CRP 7
2754 #define CBACK_CBACK_CCTL_CBACK 8
2755 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2756 #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2757 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2758 #define CWORD_CWORD_CWORD_CWORD 12
2759 #define CCTL_CCTL_CCTL_CCTL 13
2762 static const char syntax_index_table[258] = {
2763 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2764 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2765 #if ENABLE_ASH_ALIAS
2766 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2768 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2769 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2770 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2771 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2772 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2773 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2774 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2775 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2776 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2777 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2778 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2779 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2780 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2781 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2782 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2793 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2794 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2795 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2796 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2797 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2798 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2799 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2800 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2801 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2802 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2803 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2804 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2805 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2806 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2807 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2808 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2809 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2810 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2811 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2812 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2813 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2814 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2815 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2816 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2817 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2818 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2819 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2820 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2821 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2822 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2823 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2824 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2825 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2826 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2827 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2828 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2829 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2830 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2831 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2832 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2833 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2834 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2835 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2836 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2837 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2838 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2839 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2840 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2841 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2842 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2906 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2907 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2929 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2930 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2931 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2933 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2935 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2936 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2937 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2938 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2939 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2941 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2942 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2943 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2944 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2955 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2956 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2957 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2958 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2959 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2960 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2988 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2989 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2990 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2993 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3006 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3007 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3008 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3009 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3010 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3011 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3012 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3013 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3014 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3015 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3016 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3017 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3018 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3019 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3020 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3021 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3022 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3023 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
3026 #define SIT(c, syntax) (S_I_T[(int)syntax_index_table[(int)(c) + SYNBASE]][syntax])
3028 #endif /* USE_SIT_FUNCTION */
3031 /* ============ Alias handling */
3033 #if ENABLE_ASH_ALIAS
3035 #define ALIASINUSE 1
3046 static struct alias **atab; // [ATABSIZE];
3047 #define INIT_G_alias() do { \
3048 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3052 static struct alias **
3053 __lookupalias(const char *name) {
3054 unsigned int hashval;
3061 ch = (unsigned char)*p;
3065 ch = (unsigned char)*++p;
3067 app = &atab[hashval % ATABSIZE];
3069 for (; *app; app = &(*app)->next) {
3070 if (strcmp(name, (*app)->name) == 0) {
3078 static struct alias *
3079 lookupalias(const char *name, int check)
3081 struct alias *ap = *__lookupalias(name);
3083 if (check && ap && (ap->flag & ALIASINUSE))
3088 static struct alias *
3089 freealias(struct alias *ap)
3093 if (ap->flag & ALIASINUSE) {
3094 ap->flag |= ALIASDEAD;
3106 setalias(const char *name, const char *val)
3108 struct alias *ap, **app;
3110 app = __lookupalias(name);
3114 if (!(ap->flag & ALIASINUSE)) {
3117 ap->val = ckstrdup(val);
3118 ap->flag &= ~ALIASDEAD;
3121 ap = ckzalloc(sizeof(struct alias));
3122 ap->name = ckstrdup(name);
3123 ap->val = ckstrdup(val);
3124 /*ap->flag = 0; - ckzalloc did it */
3125 /*ap->next = NULL;*/
3132 unalias(const char *name)
3136 app = __lookupalias(name);
3140 *app = freealias(*app);
3151 struct alias *ap, **app;
3155 for (i = 0; i < ATABSIZE; i++) {
3157 for (ap = *app; ap; ap = *app) {
3158 *app = freealias(*app);
3168 printalias(const struct alias *ap)
3170 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3174 * TODO - sort output
3176 static int FAST_FUNC
3177 aliascmd(int argc UNUSED_PARAM, char **argv)
3186 for (i = 0; i < ATABSIZE; i++) {
3187 for (ap = atab[i]; ap; ap = ap->next) {
3193 while ((n = *++argv) != NULL) {
3194 v = strchr(n+1, '=');
3195 if (v == NULL) { /* n+1: funny ksh stuff */
3196 ap = *__lookupalias(n);
3198 fprintf(stderr, "%s: %s not found\n", "alias", n);
3211 static int FAST_FUNC
3212 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3216 while ((i = nextopt("a")) != '\0') {
3222 for (i = 0; *argptr; argptr++) {
3223 if (unalias(*argptr)) {
3224 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3232 #endif /* ASH_ALIAS */
3235 /* ============ jobs.c */
3237 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3240 #define FORK_NOJOB 2
3242 /* mode flags for showjob(s) */
3243 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3244 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3245 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3248 * A job structure contains information about a job. A job is either a
3249 * single process or a set of processes contained in a pipeline. In the
3250 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3254 pid_t pid; /* process id */
3255 int status; /* last process status from wait() */
3256 char *cmd; /* text of command being run */
3260 struct procstat ps0; /* status of process */
3261 struct procstat *ps; /* status or processes when more than one */
3263 int stopstatus; /* status of a stopped job */
3266 nprocs: 16, /* number of processes */
3268 #define JOBRUNNING 0 /* at least one proc running */
3269 #define JOBSTOPPED 1 /* all procs are stopped */
3270 #define JOBDONE 2 /* all procs are completed */
3272 sigint: 1, /* job was killed by SIGINT */
3273 jobctl: 1, /* job running under job control */
3275 waited: 1, /* true if this entry has been waited for */
3276 used: 1, /* true if this entry is in used */
3277 changed: 1; /* true if status has changed */
3278 struct job *prev_job; /* previous job */
3281 static struct job *makejob(/*union node *,*/ int);
3283 #define forkshell(job, node, mode) forkshell(job, mode)
3285 static int forkshell(struct job *, union node *, int);
3286 static int waitforjob(struct job *);
3289 enum { doing_jobctl = 0 };
3290 #define setjobctl(on) do {} while (0)
3292 static smallint doing_jobctl; //references:8
3293 static void setjobctl(int);
3300 ignoresig(int signo)
3302 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3303 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3304 /* No, need to do it */
3305 signal(signo, SIG_IGN);
3307 sigmode[signo - 1] = S_HARD_IGN;
3311 * Signal handler. Only one usage site - in setsignal()
3316 gotsig[signo - 1] = 1;
3318 if (/* exsig || */ (signo == SIGINT && !trap[SIGINT])) {
3321 raise_interrupt(); /* does not return */
3330 * Set the signal handler for the specified signal. The routine figures
3331 * out what it should be set to.
3334 setsignal(int signo)
3337 char cur_act, new_act;
3338 struct sigaction act;
3342 if (t != NULL) { /* trap for this sig is set */
3344 if (t[0] == '\0') /* trap is "": ignore this sig */
3348 if (rootshell && new_act == S_DFL) {
3351 if (iflag || minusc || sflag == 0)
3360 * "In all cases, bash ignores SIGQUIT. Non-builtin
3361 * commands run by bash have signal handlers
3362 * set to the values inherited by the shell
3363 * from its parent". */
3379 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3380 //whereas we have to restore it to what shell got on entry
3381 //from the parent. See comment above
3383 t = &sigmode[signo - 1];
3386 /* current setting is not yet known */
3387 if (sigaction(signo, NULL, &act)) {
3388 /* pretend it worked; maybe we should give a warning,
3389 * but other shells don't. We don't alter sigmode,
3390 * so we retry every time.
3391 * btw, in Linux it never fails. --vda */
3394 if (act.sa_handler == SIG_IGN) {
3395 cur_act = S_HARD_IGN;
3397 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3399 cur_act = S_IGN; /* don't hard ignore these */
3403 if (cur_act == S_HARD_IGN || cur_act == new_act)
3406 act.sa_handler = SIG_DFL;
3409 act.sa_handler = onsig;
3410 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3411 sigfillset(&act.sa_mask); /* ditto */
3414 act.sa_handler = SIG_IGN;
3417 sigaction_set(signo, &act);
3422 /* mode flags for set_curjob */
3423 #define CUR_DELETE 2
3424 #define CUR_RUNNING 1
3425 #define CUR_STOPPED 0
3427 /* mode flags for dowait */
3428 #define DOWAIT_NONBLOCK WNOHANG
3429 #define DOWAIT_BLOCK 0
3432 /* pgrp of shell on invocation */
3433 static int initialpgrp; //references:2
3434 static int ttyfd = -1; //5
3437 static struct job *jobtab; //5
3439 static unsigned njobs; //4
3441 static struct job *curjob; //lots
3442 /* number of presumed living untracked jobs */
3443 static int jobless; //4
3446 set_curjob(struct job *jp, unsigned mode)
3449 struct job **jpp, **curp;
3451 /* first remove from list */
3452 jpp = curp = &curjob;
3457 jpp = &jp1->prev_job;
3459 *jpp = jp1->prev_job;
3461 /* Then re-insert in correct position */
3469 /* job being deleted */
3472 /* newly created job or backgrounded job,
3473 put after all stopped jobs. */
3477 if (!jp1 || jp1->state != JOBSTOPPED)
3480 jpp = &jp1->prev_job;
3486 /* newly stopped job - becomes curjob */
3487 jp->prev_job = *jpp;
3495 jobno(const struct job *jp)
3497 return jp - jobtab + 1;
3502 * Convert a job name to a job structure.
3505 #define getjob(name, getctl) getjob(name)
3508 getjob(const char *name, int getctl)
3512 const char *err_msg = "%s: no such job";
3516 char *(*match)(const char *, const char *);
3531 if (c == '+' || c == '%') {
3533 err_msg = "No current job";
3539 err_msg = "No previous job";
3548 // TODO: number() instead? It does error checking...
3551 jp = jobtab + num - 1;
3566 if (match(jp->ps[0].cmd, p)) {
3570 err_msg = "%s: ambiguous";
3580 err_msg = "job %s not created under job control";
3581 if (getctl && jp->jobctl == 0)
3586 ash_msg_and_raise_error(err_msg, name);
3590 * Mark a job structure as unused.
3593 freejob(struct job *jp)
3595 struct procstat *ps;
3599 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3600 if (ps->cmd != nullstr)
3603 if (jp->ps != &jp->ps0)
3606 set_curjob(jp, CUR_DELETE);
3612 xtcsetpgrp(int fd, pid_t pgrp)
3614 if (tcsetpgrp(fd, pgrp))
3615 ash_msg_and_raise_error("can't set tty process group (%m)");
3619 * Turn job control on and off.
3621 * Note: This code assumes that the third arg to ioctl is a character
3622 * pointer, which is true on Berkeley systems but not System V. Since
3623 * System V doesn't have job control yet, this isn't a problem now.
3625 * Called with interrupts off.
3633 if (on == doing_jobctl || rootshell == 0)
3637 ofd = fd = open(_PATH_TTY, O_RDWR);
3639 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3640 * That sometimes helps to acquire controlling tty.
3641 * Obviously, a workaround for bugs when someone
3642 * failed to provide a controlling tty to bash! :) */
3648 fd = fcntl(fd, F_DUPFD, 10);
3653 /* fd is a tty at this point */
3654 close_on_exec_on(fd);
3655 do { /* while we are in the background */
3656 pgrp = tcgetpgrp(fd);
3659 ash_msg("can't access tty; job control turned off");
3663 if (pgrp == getpgrp())
3674 xtcsetpgrp(fd, pgrp);
3676 /* turning job control off */
3679 /* was xtcsetpgrp, but this can make exiting ash
3680 * loop forever if pty is already deleted */
3681 tcsetpgrp(fd, pgrp);
3695 static int FAST_FUNC
3696 killcmd(int argc, char **argv)
3699 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3701 if (argv[i][0] == '%') {
3702 struct job *jp = getjob(argv[i], 0);
3703 unsigned pid = jp->ps[0].pid;
3704 /* Enough space for ' -NNN<nul>' */
3705 argv[i] = alloca(sizeof(int)*3 + 3);
3706 /* kill_main has matching code to expect
3707 * leading space. Needed to not confuse
3708 * negative pids with "kill -SIGNAL_NO" syntax */
3709 sprintf(argv[i], " -%u", pid);
3711 } while (argv[++i]);
3713 return kill_main(argc, argv);
3717 showpipe(struct job *jp, FILE *out)
3719 struct procstat *sp;
3720 struct procstat *spend;
3722 spend = jp->ps + jp->nprocs;
3723 for (sp = jp->ps + 1; sp < spend; sp++)
3724 fprintf(out, " | %s", sp->cmd);
3725 outcslow('\n', out);
3726 flush_stdout_stderr();
3731 restartjob(struct job *jp, int mode)
3733 struct procstat *ps;
3739 if (jp->state == JOBDONE)
3741 jp->state = JOBRUNNING;
3743 if (mode == FORK_FG)
3744 xtcsetpgrp(ttyfd, pgid);
3745 killpg(pgid, SIGCONT);
3749 if (WIFSTOPPED(ps->status)) {
3755 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3760 static int FAST_FUNC
3761 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3768 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3773 jp = getjob(*argv, 1);
3774 if (mode == FORK_BG) {
3775 set_curjob(jp, CUR_RUNNING);
3776 fprintf(out, "[%d] ", jobno(jp));
3778 outstr(jp->ps->cmd, out);
3780 retval = restartjob(jp, mode);
3781 } while (*argv && *++argv);
3787 sprint_status(char *s, int status, int sigonly)
3793 if (!WIFEXITED(status)) {
3795 if (WIFSTOPPED(status))
3796 st = WSTOPSIG(status);
3799 st = WTERMSIG(status);
3801 if (st == SIGINT || st == SIGPIPE)
3804 if (WIFSTOPPED(status))
3809 col = fmtstr(s, 32, strsignal(st));
3810 if (WCOREDUMP(status)) {
3811 col += fmtstr(s + col, 16, " (core dumped)");
3813 } else if (!sigonly) {
3814 st = WEXITSTATUS(status);
3816 col = fmtstr(s, 16, "Done(%d)", st);
3818 col = fmtstr(s, 16, "Done");
3825 dowait(int wait_flags, struct job *job)
3830 struct job *thisjob;
3833 TRACE(("dowait(0x%x) called\n", wait_flags));
3835 /* Do a wait system call. If job control is compiled in, we accept
3836 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3837 * NB: _not_ safe_waitpid, we need to detect EINTR */
3838 pid = waitpid(-1, &status,
3839 (doing_jobctl ? (wait_flags | WUNTRACED) : wait_flags));
3840 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3841 pid, status, errno, strerror(errno)));
3847 for (jp = curjob; jp; jp = jp->prev_job) {
3848 struct procstat *sp;
3849 struct procstat *spend;
3850 if (jp->state == JOBDONE)
3853 spend = jp->ps + jp->nprocs;
3856 if (sp->pid == pid) {
3857 TRACE(("Job %d: changing status of proc %d "
3858 "from 0x%x to 0x%x\n",
3859 jobno(jp), pid, sp->status, status));
3860 sp->status = status;
3863 if (sp->status == -1)
3866 if (state == JOBRUNNING)
3868 if (WIFSTOPPED(sp->status)) {
3869 jp->stopstatus = sp->status;
3873 } while (++sp < spend);
3878 if (!WIFSTOPPED(status))
3884 if (state != JOBRUNNING) {
3885 thisjob->changed = 1;
3887 if (thisjob->state != state) {
3888 TRACE(("Job %d: changing state from %d to %d\n",
3889 jobno(thisjob), thisjob->state, state));
3890 thisjob->state = state;
3892 if (state == JOBSTOPPED) {
3893 set_curjob(thisjob, CUR_STOPPED);
3902 if (thisjob && thisjob == job) {
3906 len = sprint_status(s, status, 1);
3917 blocking_wait_with_raise_on_sig(struct job *job)
3919 pid_t pid = dowait(DOWAIT_BLOCK, job);
3920 if (pid <= 0 && pendingsig)
3921 raise_exception(EXSIG);
3927 showjob(FILE *out, struct job *jp, int mode)
3929 struct procstat *ps;
3930 struct procstat *psend;
3937 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
3938 /* just output process (group) id of pipeline */
3939 fprintf(out, "%d\n", ps->pid);
3943 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3948 else if (curjob && jp == curjob->prev_job)
3951 if (mode & SHOW_PIDS)
3952 col += fmtstr(s + col, 16, "%d ", ps->pid);
3954 psend = ps + jp->nprocs;
3956 if (jp->state == JOBRUNNING) {
3957 strcpy(s + col, "Running");
3958 col += sizeof("Running") - 1;
3960 int status = psend[-1].status;
3961 if (jp->state == JOBSTOPPED)
3962 status = jp->stopstatus;
3963 col += sprint_status(s + col, status, 0);
3965 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
3967 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3968 * or prints several "PID | <cmdN>" lines,
3969 * depending on SHOW_PIDS bit.
3970 * We do not print status of individual processes
3971 * between PID and <cmdN>. bash does it, but not very well:
3972 * first line shows overall job status, not process status,
3973 * making it impossible to know 1st process status.
3977 /* for each process */
3980 if (mode & SHOW_PIDS)
3981 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->pid) - 1;
3983 fprintf(out, "%s%*c", s, 33 - col >= 0 ? 33 - col : 0, ' ');
3986 fprintf(out, "%s", ps->cmd);
3990 outcslow('\n', out);
3994 if (jp->state == JOBDONE) {
3995 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4001 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4002 * statuses have changed since the last call to showjobs.
4005 showjobs(FILE *out, int mode)
4009 TRACE(("showjobs(0x%x) called\n", mode));
4011 /* Handle all finished jobs */
4012 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4015 for (jp = curjob; jp; jp = jp->prev_job) {
4016 if (!(mode & SHOW_CHANGED) || jp->changed) {
4017 showjob(out, jp, mode);
4022 static int FAST_FUNC
4023 jobscmd(int argc UNUSED_PARAM, char **argv)
4028 while ((m = nextopt("lp"))) {
4032 mode |= SHOW_ONLY_PGID;
4038 showjob(stdout, getjob(*argv, 0), mode);
4041 showjobs(stdout, mode);
4048 getstatus(struct job *job)
4053 status = job->ps[job->nprocs - 1].status;
4054 retval = WEXITSTATUS(status);
4055 if (!WIFEXITED(status)) {
4057 retval = WSTOPSIG(status);
4058 if (!WIFSTOPPED(status))
4061 /* XXX: limits number of signals */
4062 retval = WTERMSIG(status);
4064 if (retval == SIGINT)
4070 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4071 jobno(job), job->nprocs, status, retval));
4075 static int FAST_FUNC
4076 waitcmd(int argc UNUSED_PARAM, char **argv)
4085 raise_exception(EXSIG);
4092 /* wait for all jobs */
4096 if (!jp) /* no running procs */
4098 if (jp->state == JOBRUNNING)
4104 * "When bash is waiting for an asynchronous command via
4105 * the wait builtin, the reception of a signal for which a trap
4106 * has been set will cause the wait builtin to return immediately
4107 * with an exit status greater than 128, immediately after which
4108 * the trap is executed."
4109 * Do we do it that way? */
4110 blocking_wait_with_raise_on_sig(NULL);
4116 if (**argv != '%') {
4117 pid_t pid = number(*argv);
4122 if (job->ps[job->nprocs - 1].pid == pid)
4124 job = job->prev_job;
4127 job = getjob(*argv, 0);
4128 /* loop until process terminated or stopped */
4129 while (job->state == JOBRUNNING)
4130 blocking_wait_with_raise_on_sig(NULL);
4132 retval = getstatus(job);
4145 struct job *jp, *jq;
4147 len = njobs * sizeof(*jp);
4149 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4151 offset = (char *)jp - (char *)jq;
4153 /* Relocate pointers */
4156 jq = (struct job *)((char *)jq + l);
4160 #define joff(p) ((struct job *)((char *)(p) + l))
4161 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4162 if (joff(jp)->ps == &jq->ps0)
4163 jmove(joff(jp)->ps);
4164 if (joff(jp)->prev_job)
4165 jmove(joff(jp)->prev_job);
4175 jp = (struct job *)((char *)jp + len);
4179 } while (--jq >= jp);
4184 * Return a new job structure.
4185 * Called with interrupts off.
4188 makejob(/*union node *node,*/ int nprocs)
4193 for (i = njobs, jp = jobtab; ; jp++) {
4200 if (jp->state != JOBDONE || !jp->waited)
4209 memset(jp, 0, sizeof(*jp));
4211 /* jp->jobctl is a bitfield.
4212 * "jp->jobctl |= jobctl" likely to give awful code */
4216 jp->prev_job = curjob;
4221 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4223 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4230 * Return a string identifying a command (to be printed by the
4233 static char *cmdnextc;
4236 cmdputs(const char *s)
4238 static const char vstype[VSTYPE + 1][3] = {
4239 "", "}", "-", "+", "?", "=",
4240 "%", "%%", "#", "##"
4241 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4244 const char *p, *str;
4245 char c, cc[2] = " ";
4250 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4252 while ((c = *p++) != 0) {
4260 if ((subtype & VSTYPE) == VSLENGTH)
4264 if (!(subtype & VSQUOTE) == !(quoted & 1))
4270 str = "\"}" + !(quoted & 1);
4277 case CTLBACKQ+CTLQUOTE:
4280 #if ENABLE_SH_MATH_SUPPORT
4295 if ((subtype & VSTYPE) != VSNORMAL)
4297 str = vstype[subtype & VSTYPE];
4298 if (subtype & VSNUL)
4307 /* These can only happen inside quotes */
4320 while ((c = *str++)) {
4325 USTPUTC('"', nextc);
4331 /* cmdtxt() and cmdlist() call each other */
4332 static void cmdtxt(union node *n);
4335 cmdlist(union node *np, int sep)
4337 for (; np; np = np->narg.next) {
4341 if (sep && np->narg.next)
4347 cmdtxt(union node *n)
4350 struct nodelist *lp;
4361 lp = n->npipe.cmdlist;
4379 cmdtxt(n->nbinary.ch1);
4395 cmdtxt(n->nif.test);
4397 if (n->nif.elsepart) {
4398 cmdtxt(n->nif.ifpart);
4400 n = n->nif.elsepart;
4418 cmdtxt(n->nbinary.ch1);
4428 cmdputs(n->nfor.var);
4430 cmdlist(n->nfor.args, 1);
4435 cmdputs(n->narg.text);
4439 cmdlist(n->ncmd.args, 1);
4440 cmdlist(n->ncmd.redirect, 0);
4453 cmdputs(n->ncase.expr->narg.text);
4455 for (np = n->ncase.cases; np; np = np->nclist.next) {
4456 cmdtxt(np->nclist.pattern);
4458 cmdtxt(np->nclist.body);
4472 #if ENABLE_ASH_BASH_COMPAT
4487 cmdputs(utoa(n->nfile.fd));
4489 if (n->type == NTOFD || n->type == NFROMFD) {
4490 cmdputs(utoa(n->ndup.dupfd));
4499 commandtext(union node *n)
4503 STARTSTACKSTR(cmdnextc);
4505 name = stackblock();
4506 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4507 name, cmdnextc, cmdnextc));
4508 return ckstrdup(name);
4513 * Fork off a subshell. If we are doing job control, give the subshell its
4514 * own process group. Jp is a job structure that the job is to be added to.
4515 * N is the command that will be evaluated by the child. Both jp and n may
4516 * be NULL. The mode parameter can be one of the following:
4517 * FORK_FG - Fork off a foreground process.
4518 * FORK_BG - Fork off a background process.
4519 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4520 * process group even if job control is on.
4522 * When job control is turned off, background processes have their standard
4523 * input redirected to /dev/null (except for the second and later processes
4526 * Called with interrupts off.
4529 * Clear traps on a fork.
4536 for (tp = trap; tp < &trap[NSIG]; tp++) {
4537 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4542 setsignal(tp - trap);
4548 /* Lives far away from here, needed for forkchild */
4549 static void closescript(void);
4551 /* Called after fork(), in child */
4553 # define forkchild(jp, n, mode) forkchild(jp, mode)
4556 forkchild(struct job *jp, union node *n, int mode)
4560 TRACE(("Child shell %d\n", getpid()));
4564 /* man bash: "Non-builtin commands run by bash have signal handlers
4565 * set to the values inherited by the shell from its parent".
4566 * Do we do it correctly? */
4571 /* do job control only in root shell */
4573 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4576 if (jp->nprocs == 0)
4579 pgrp = jp->ps[0].pid;
4580 /* this can fail because we are doing it in the parent also */
4582 if (mode == FORK_FG)
4583 xtcsetpgrp(ttyfd, pgrp);
4588 if (mode == FORK_BG) {
4589 /* man bash: "When job control is not in effect,
4590 * asynchronous commands ignore SIGINT and SIGQUIT" */
4593 if (jp->nprocs == 0) {
4595 if (open(bb_dev_null, O_RDONLY) != 0)
4596 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4600 if (iflag) { /* why if iflag only? */
4605 * "In all cases, bash ignores SIGQUIT. Non-builtin
4606 * commands run by bash have signal handlers
4607 * set to the values inherited by the shell
4609 * Take care of the second rule: */
4613 if (n && n->type == NCMD && strcmp(n->ncmd.args->narg.text, "jobs") == 0) {
4614 TRACE(("Job hack\n"));
4619 for (jp = curjob; jp; jp = jp->prev_job)
4624 /* Called after fork(), in parent */
4626 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4629 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4631 TRACE(("In parent shell: child = %d\n", pid));
4633 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4639 if (mode != FORK_NOJOB && jp->jobctl) {
4642 if (jp->nprocs == 0)
4645 pgrp = jp->ps[0].pid;
4646 /* This can fail because we are doing it in the child also */
4650 if (mode == FORK_BG) {
4651 backgndpid = pid; /* set $! */
4652 set_curjob(jp, CUR_RUNNING);
4655 struct procstat *ps = &jp->ps[jp->nprocs++];
4660 if (doing_jobctl && n)
4661 ps->cmd = commandtext(n);
4667 forkshell(struct job *jp, union node *n, int mode)
4671 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4674 TRACE(("Fork failed, errno=%d", errno));
4677 ash_msg_and_raise_error("can't fork");
4680 forkchild(jp, n, mode);
4682 forkparent(jp, n, mode, pid);
4687 * Wait for job to finish.
4689 * Under job control we have the problem that while a child process
4690 * is running interrupts generated by the user are sent to the child
4691 * but not to the shell. This means that an infinite loop started by
4692 * an interactive user may be hard to kill. With job control turned off,
4693 * an interactive user may place an interactive program inside a loop.
4694 * If the interactive program catches interrupts, the user doesn't want
4695 * these interrupts to also abort the loop. The approach we take here
4696 * is to have the shell ignore interrupt signals while waiting for a
4697 * foreground process to terminate, and then send itself an interrupt
4698 * signal if the child process was terminated by an interrupt signal.
4699 * Unfortunately, some programs want to do a bit of cleanup and then
4700 * exit on interrupt; unless these processes terminate themselves by
4701 * sending a signal to themselves (instead of calling exit) they will
4702 * confuse this approach.
4704 * Called with interrupts off.
4707 waitforjob(struct job *jp)
4711 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4714 while (jp->state == JOBRUNNING) {
4715 /* In non-interactive shells, we _can_ get
4716 * a keyboard signal here and be EINTRed,
4717 * but we just loop back, waiting for command to complete.
4720 * "If bash is waiting for a command to complete and receives
4721 * a signal for which a trap has been set, the trap
4722 * will not be executed until the command completes."
4724 * Reality is that even if trap is not set, bash
4725 * will not act on the signal until command completes.
4726 * Try this. sleep5intoff.c:
4727 * #include <signal.h>
4728 * #include <unistd.h>
4731 * sigemptyset(&set);
4732 * sigaddset(&set, SIGINT);
4733 * sigaddset(&set, SIGQUIT);
4734 * sigprocmask(SIG_BLOCK, &set, NULL);
4738 * $ bash -c './sleep5intoff; echo hi'
4739 * ^C^C^C^C <--- pressing ^C once a second
4741 * $ bash -c './sleep5intoff; echo hi'
4742 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4745 dowait(DOWAIT_BLOCK, jp);
4752 xtcsetpgrp(ttyfd, rootpid);
4754 * This is truly gross.
4755 * If we're doing job control, then we did a TIOCSPGRP which
4756 * caused us (the shell) to no longer be in the controlling
4757 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4758 * intuit from the subprocess exit status whether a SIGINT
4759 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4761 if (jp->sigint) /* TODO: do the same with all signals */
4762 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4764 if (jp->state == JOBDONE)
4771 * return 1 if there are stopped jobs, otherwise 0
4783 if (jp && jp->state == JOBSTOPPED) {
4784 out2str("You have stopped jobs.\n");
4793 /* ============ redir.c
4795 * Code for dealing with input/output redirection.
4798 #define EMPTY -2 /* marks an unused slot in redirtab */
4799 #define CLOSED -3 /* marks a slot of previously-closed fd */
4802 * Open a file in noclobber mode.
4803 * The code was copied from bash.
4806 noclobberopen(const char *fname)
4809 struct stat finfo, finfo2;
4812 * If the file exists and is a regular file, return an error
4815 r = stat(fname, &finfo);
4816 if (r == 0 && S_ISREG(finfo.st_mode)) {
4822 * If the file was not present (r != 0), make sure we open it
4823 * exclusively so that if it is created before we open it, our open
4824 * will fail. Make sure that we do not truncate an existing file.
4825 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4826 * file was not a regular file, we leave O_EXCL off.
4829 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4830 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4832 /* If the open failed, return the file descriptor right away. */
4837 * OK, the open succeeded, but the file may have been changed from a
4838 * non-regular file to a regular file between the stat and the open.
4839 * We are assuming that the O_EXCL open handles the case where FILENAME
4840 * did not exist and is symlinked to an existing file between the stat
4845 * If we can open it and fstat the file descriptor, and neither check
4846 * revealed that it was a regular file, and the file has not been
4847 * replaced, return the file descriptor.
4849 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4850 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4853 /* The file has been replaced. badness. */
4860 * Handle here documents. Normally we fork off a process to write the
4861 * data to a pipe. If the document is short, we can stuff the data in
4862 * the pipe without forking.
4864 /* openhere needs this forward reference */
4865 static void expandhere(union node *arg, int fd);
4867 openhere(union node *redir)
4873 ash_msg_and_raise_error("pipe call failed");
4874 if (redir->type == NHERE) {
4875 len = strlen(redir->nhere.doc->narg.text);
4876 if (len <= PIPE_BUF) {
4877 full_write(pip[1], redir->nhere.doc->narg.text, len);
4881 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4884 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4885 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4886 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4887 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4888 signal(SIGPIPE, SIG_DFL);
4889 if (redir->type == NHERE)
4890 full_write(pip[1], redir->nhere.doc->narg.text, len);
4892 expandhere(redir->nhere.doc, pip[1]);
4893 _exit(EXIT_SUCCESS);
4901 openredirect(union node *redir)
4906 switch (redir->nfile.type) {
4908 fname = redir->nfile.expfname;
4909 f = open(fname, O_RDONLY);
4914 fname = redir->nfile.expfname;
4915 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4920 #if ENABLE_ASH_BASH_COMPAT
4923 /* Take care of noclobber mode. */
4925 fname = redir->nfile.expfname;
4926 f = noclobberopen(fname);
4933 fname = redir->nfile.expfname;
4934 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4939 fname = redir->nfile.expfname;
4940 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4948 /* Fall through to eliminate warning. */
4949 /* Our single caller does this itself */
4956 f = openhere(redir);
4962 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4964 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
4968 * Copy a file descriptor to be >= to. Returns -1
4969 * if the source file descriptor is closed, EMPTY if there are no unused
4970 * file descriptors left.
4972 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
4973 * old code was doing close(to) prior to copyfd() to achieve the same */
4975 COPYFD_EXACT = (int)~(INT_MAX),
4976 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
4979 copyfd(int from, int to)
4983 if (to & COPYFD_EXACT) {
4984 to &= ~COPYFD_EXACT;
4986 newfd = dup2(from, to);
4988 newfd = fcntl(from, F_DUPFD, to);
4991 if (errno == EMFILE)
4993 /* Happens when source fd is not open: try "echo >&99" */
4994 ash_msg_and_raise_error("%d: %m", from);
4999 /* Struct def and variable are moved down to the first usage site */
5004 struct redirtab *next;
5007 struct two_fd_t two_fd[0];
5009 #define redirlist (G_var.redirlist)
5011 static int need_to_remember(struct redirtab *rp, int fd)
5015 if (!rp) /* remembering was not requested */
5018 for (i = 0; i < rp->pair_count; i++) {
5019 if (rp->two_fd[i].orig == fd) {
5020 /* already remembered */
5027 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5028 static int is_hidden_fd(struct redirtab *rp, int fd)
5031 struct parsefile *pf;
5044 fd |= COPYFD_RESTORE;
5045 for (i = 0; i < rp->pair_count; i++) {
5046 if (rp->two_fd[i].copy == fd) {
5054 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5055 * old file descriptors are stashed away so that the redirection can be
5056 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5057 * standard output, and the standard error if it becomes a duplicate of
5058 * stdout, is saved in memory.
5060 /* flags passed to redirect */
5061 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5062 #define REDIR_SAVEFD2 03 /* set preverrout */
5064 redirect(union node *redir, int flags)
5066 struct redirtab *sv;
5071 int copied_fd2 = -1;
5081 if (flags & REDIR_PUSH) {
5082 union node *tmp = redir;
5085 #if ENABLE_ASH_BASH_COMPAT
5086 if (redir->nfile.type == NTO2)
5089 tmp = tmp->nfile.next;
5091 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5092 sv->next = redirlist;
5093 sv->pair_count = sv_pos;
5095 sv->nullredirs = g_nullredirs - 1;
5097 while (sv_pos > 0) {
5099 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5104 fd = redir->nfile.fd;
5105 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5106 int right_fd = redir->ndup.dupfd;
5107 /* redirect from/to same file descriptor? */
5110 /* echo >&10 and 10 is a fd opened to the sh script? */
5111 if (is_hidden_fd(sv, right_fd)) {
5112 errno = EBADF; /* as if it is closed */
5113 ash_msg_and_raise_error("%d: %m", right_fd);
5117 newfd = openredirect(redir); /* always >= 0 */
5119 /* Descriptor wasn't open before redirect.
5120 * Mark it for close in the future */
5121 if (need_to_remember(sv, fd)) {
5122 goto remember_to_close;
5127 #if ENABLE_ASH_BASH_COMPAT
5130 if (need_to_remember(sv, fd)) {
5131 /* Copy old descriptor */
5132 i = fcntl(fd, F_DUPFD, 10);
5133 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5134 * are closed in popredir() in the child, preventing them from leaking
5135 * into child. (popredir() also cleans up the mess in case of failures)
5140 /* Strange error (e.g. "too many files" EMFILE?) */
5144 ash_msg_and_raise_error("%d: %m", fd);
5147 /* EBADF: it is not open - good, remember to close it */
5150 } else { /* fd is open, save its copy */
5151 /* "exec fd>&-" should not close fds
5152 * which point to script file(s).
5153 * Force them to be restored afterwards */
5154 if (is_hidden_fd(sv, fd))
5155 i |= COPYFD_RESTORE;
5159 sv->two_fd[sv_pos].orig = fd;
5160 sv->two_fd[sv_pos].copy = i;
5164 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5165 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5166 /* Don't want to trigger debugging */
5170 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5172 } else if (fd != newfd) { /* move newfd to fd */
5173 copyfd(newfd, fd | COPYFD_EXACT);
5174 #if ENABLE_ASH_BASH_COMPAT
5175 if (!(redir->nfile.type == NTO2 && fd == 2))
5179 #if ENABLE_ASH_BASH_COMPAT
5180 if (redir->nfile.type == NTO2 && fd == 1) {
5181 /* We already redirected it to fd 1, now copy it to 2 */
5187 } while ((redir = redir->nfile.next) != NULL);
5190 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5191 preverrout_fd = copied_fd2;
5195 * Undo the effects of the last redirection.
5198 popredir(int drop, int restore)
5200 struct redirtab *rp;
5203 if (--g_nullredirs >= 0)
5207 for (i = 0; i < rp->pair_count; i++) {
5208 int fd = rp->two_fd[i].orig;
5209 int copy = rp->two_fd[i].copy;
5210 if (copy == CLOSED) {
5215 if (copy != EMPTY) {
5216 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5217 copy &= ~COPYFD_RESTORE;
5219 copyfd(copy, fd | COPYFD_EXACT);
5221 close(copy & ~COPYFD_RESTORE);
5224 redirlist = rp->next;
5225 g_nullredirs = rp->nullredirs;
5231 * Undo all redirections. Called on error or interrupt.
5235 * Discard all saved file descriptors.
5238 clearredir(int drop)
5244 popredir(drop, /*restore:*/ 0);
5249 redirectsafe(union node *redir, int flags)
5252 volatile int saveint;
5253 struct jmploc *volatile savehandler = exception_handler;
5254 struct jmploc jmploc;
5257 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5258 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5260 exception_handler = &jmploc;
5261 redirect(redir, flags);
5263 exception_handler = savehandler;
5264 if (err && exception_type != EXERROR)
5265 longjmp(exception_handler->loc, 1);
5266 RESTORE_INT(saveint);
5271 /* ============ Routines to expand arguments to commands
5273 * We have to deal with backquotes, shell variables, and file metacharacters.
5276 #if ENABLE_SH_MATH_SUPPORT
5278 ash_arith(const char *s)
5280 arith_eval_hooks_t math_hooks;
5284 math_hooks.lookupvar = lookupvar;
5285 math_hooks.setvar = setvar;
5286 math_hooks.endofname = endofname;
5289 result = arith(s, &errcode, &math_hooks);
5292 ash_msg_and_raise_error("exponent less than 0");
5294 ash_msg_and_raise_error("divide by zero");
5296 ash_msg_and_raise_error("expression recursion loop detected");
5297 raise_error_syntax(s);
5308 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5309 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5310 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5311 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5312 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5313 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5314 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5315 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5316 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5320 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5321 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5322 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5323 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5324 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5327 * Structure specifying which parts of the string should be searched
5328 * for IFS characters.
5331 struct ifsregion *next; /* next region in list */
5332 int begoff; /* offset of start of region */
5333 int endoff; /* offset of end of region */
5334 int nulonly; /* search for nul bytes only */
5338 struct strlist *list;
5339 struct strlist **lastp;
5342 /* output of current string */
5343 static char *expdest;
5344 /* list of back quote expressions */
5345 static struct nodelist *argbackq;
5346 /* first struct in list of ifs regions */
5347 static struct ifsregion ifsfirst;
5348 /* last struct in list */
5349 static struct ifsregion *ifslastp;
5350 /* holds expanded arg list */
5351 static struct arglist exparg;
5361 expdest = makestrspace(32, expdest);
5362 len = fmtstr(expdest, 32, arith_t_fmt, num);
5363 STADJUST(len, expdest);
5368 esclen(const char *start, const char *p)
5372 while (p > start && *--p == CTLESC) {
5379 * Remove any CTLESC characters from a string.
5382 rmescapes(char *str, int flag)
5384 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5391 p = strpbrk(str, qchars);
5397 if (flag & RMESCAPE_ALLOC) {
5398 size_t len = p - str;
5399 size_t fulllen = len + strlen(p) + 1;
5401 if (flag & RMESCAPE_GROW) {
5402 r = makestrspace(fulllen, expdest);
5403 } else if (flag & RMESCAPE_HEAP) {
5404 r = ckmalloc(fulllen);
5406 r = stalloc(fulllen);
5410 q = (char *)memcpy(q, str, len) + len;
5413 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5414 globbing = flag & RMESCAPE_GLOB;
5415 notescaped = globbing;
5417 if (*p == CTLQUOTEMARK) {
5418 inquotes = ~inquotes;
5420 notescaped = globbing;
5424 /* naked back slash */
5430 if (notescaped && inquotes && *p != '/') {
5434 notescaped = globbing;
5439 if (flag & RMESCAPE_GROW) {
5441 STADJUST(q - r + 1, expdest);
5445 #define pmatch(a, b) !fnmatch((a), (b), 0)
5448 * Prepare a pattern for a expmeta (internal glob(3)) call.
5450 * Returns an stalloced string.
5453 preglob(const char *pattern, int quoted, int flag)
5455 flag |= RMESCAPE_GLOB;
5457 flag |= RMESCAPE_QUOTED;
5459 return rmescapes((char *)pattern, flag);
5463 * Put a string on the stack.
5466 memtodest(const char *p, size_t len, int syntax, int quotes)
5470 q = makestrspace(quotes ? len * 2 : len, q);
5473 int c = signed_char2int(*p++);
5477 int n = SIT(c, syntax);
5478 if (n == CCTL || n == CBACK)
5488 strtodest(const char *p, int syntax, int quotes)
5490 memtodest(p, strlen(p), syntax, quotes);
5494 * Record the fact that we have to scan this region of the
5495 * string for IFS characters.
5498 recordregion(int start, int end, int nulonly)
5500 struct ifsregion *ifsp;
5502 if (ifslastp == NULL) {
5506 ifsp = ckzalloc(sizeof(*ifsp));
5507 /*ifsp->next = NULL; - ckzalloc did it */
5508 ifslastp->next = ifsp;
5512 ifslastp->begoff = start;
5513 ifslastp->endoff = end;
5514 ifslastp->nulonly = nulonly;
5518 removerecordregions(int endoff)
5520 if (ifslastp == NULL)
5523 if (ifsfirst.endoff > endoff) {
5524 while (ifsfirst.next != NULL) {
5525 struct ifsregion *ifsp;
5527 ifsp = ifsfirst.next->next;
5528 free(ifsfirst.next);
5529 ifsfirst.next = ifsp;
5532 if (ifsfirst.begoff > endoff)
5535 ifslastp = &ifsfirst;
5536 ifsfirst.endoff = endoff;
5541 ifslastp = &ifsfirst;
5542 while (ifslastp->next && ifslastp->next->begoff < endoff)
5543 ifslastp=ifslastp->next;
5544 while (ifslastp->next != NULL) {
5545 struct ifsregion *ifsp;
5547 ifsp = ifslastp->next->next;
5548 free(ifslastp->next);
5549 ifslastp->next = ifsp;
5552 if (ifslastp->endoff > endoff)
5553 ifslastp->endoff = endoff;
5557 exptilde(char *startp, char *p, int flag)
5563 int quotes = flag & (EXP_FULL | EXP_CASE);
5568 while ((c = *++p) != '\0') {
5575 if (flag & EXP_VARTILDE)
5585 if (*name == '\0') {
5586 home = lookupvar(homestr);
5588 pw = getpwnam(name);
5593 if (!home || !*home)
5596 startloc = expdest - (char *)stackblock();
5597 strtodest(home, SQSYNTAX, quotes);
5598 recordregion(startloc, expdest - (char *)stackblock(), 0);
5606 * Execute a command inside back quotes. If it's a builtin command, we
5607 * want to save its output in a block obtained from malloc. Otherwise
5608 * we fork off a subprocess and get the output of the command via a pipe.
5609 * Should be called with interrupts off.
5611 struct backcmd { /* result of evalbackcmd */
5612 int fd; /* file descriptor to read from */
5613 int nleft; /* number of chars in buffer */
5614 char *buf; /* buffer */
5615 struct job *jp; /* job structure for command */
5618 /* These forward decls are needed to use "eval" code for backticks handling: */
5619 static uint8_t back_exitstatus; /* exit status of backquoted command */
5620 #define EV_EXIT 01 /* exit after evaluating tree */
5621 static void evaltree(union node *, int);
5623 static void FAST_FUNC
5624 evalbackcmd(union node *n, struct backcmd *result)
5635 saveherefd = herefd;
5643 ash_msg_and_raise_error("pipe call failed");
5644 jp = makejob(/*n,*/ 1);
5645 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5650 copyfd(pip[1], 1 | COPYFD_EXACT);
5654 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5658 result->fd = pip[0];
5661 herefd = saveherefd;
5663 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5664 result->fd, result->buf, result->nleft, result->jp));
5668 * Expand stuff in backwards quotes.
5671 expbackq(union node *cmd, int quoted, int quotes)
5679 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5680 struct stackmark smark;
5683 setstackmark(&smark);
5685 startloc = dest - (char *)stackblock();
5687 evalbackcmd(cmd, &in);
5688 popstackmark(&smark);
5695 memtodest(p, i, syntax, quotes);
5699 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5700 TRACE(("expbackq: read returns %d\n", i));
5709 back_exitstatus = waitforjob(in.jp);
5713 /* Eat all trailing newlines */
5715 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5720 recordregion(startloc, dest - (char *)stackblock(), 0);
5721 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5722 (dest - (char *)stackblock()) - startloc,
5723 (dest - (char *)stackblock()) - startloc,
5724 stackblock() + startloc));
5727 #if ENABLE_SH_MATH_SUPPORT
5729 * Expand arithmetic expression. Backup to start of expression,
5730 * evaluate, place result in (backed up) result, adjust string position.
5743 * This routine is slightly over-complicated for
5744 * efficiency. Next we scan backwards looking for the
5745 * start of arithmetic.
5747 start = stackblock();
5754 while (*p != CTLARI) {
5758 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5763 esc = esclen(start, p);
5773 removerecordregions(begoff);
5780 rmescapes(p + 2, 0);
5782 len = cvtnum(ash_arith(p + 2));
5785 recordregion(begoff, begoff + len, 0);
5789 /* argstr needs it */
5790 static char *evalvar(char *p, int flag, struct strlist *var_str_list);
5793 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5794 * characters to allow for further processing. Otherwise treat
5795 * $@ like $* since no splitting will be performed.
5797 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5798 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5799 * for correct expansion of "B=$A" word.
5802 argstr(char *p, int flag, struct strlist *var_str_list)
5804 static const char spclchars[] ALIGN1 = {
5812 CTLBACKQ | CTLQUOTE,
5813 #if ENABLE_SH_MATH_SUPPORT
5818 const char *reject = spclchars;
5820 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5821 int breakall = flag & EXP_WORD;
5826 if (!(flag & EXP_VARTILDE)) {
5828 } else if (flag & EXP_VARTILDE2) {
5833 if (flag & EXP_TILDE) {
5839 if (*q == CTLESC && (flag & EXP_QWORD))
5842 p = exptilde(p, q, flag);
5845 startloc = expdest - (char *)stackblock();
5847 length += strcspn(p + length, reject);
5849 if (c && (!(c & 0x80)
5850 #if ENABLE_SH_MATH_SUPPORT
5854 /* c == '=' || c == ':' || c == CTLENDARI */
5859 expdest = stack_nputstr(p, length, expdest);
5860 newloc = expdest - (char *)stackblock();
5861 if (breakall && !inquotes && newloc > startloc) {
5862 recordregion(startloc, newloc, 0);
5873 if (flag & EXP_VARTILDE2) {
5877 flag |= EXP_VARTILDE2;
5882 * sort of a hack - expand tildes in variable
5883 * assignments (after the first '=' and after ':'s).
5892 case CTLENDVAR: /* ??? */
5895 /* "$@" syntax adherence hack */
5898 !memcmp(p, dolatstr, 4) &&
5899 (p[4] == CTLQUOTEMARK || (
5900 p[4] == CTLENDVAR &&
5901 p[5] == CTLQUOTEMARK
5904 p = evalvar(p + 1, flag, /* var_str_list: */ NULL) + 1;
5907 inquotes = !inquotes;
5920 p = evalvar(p, flag, var_str_list);
5924 case CTLBACKQ|CTLQUOTE:
5925 expbackq(argbackq->n, c, quotes);
5926 argbackq = argbackq->next;
5928 #if ENABLE_SH_MATH_SUPPORT
5941 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
5944 // This commented out code was added by James Simmons <jsimmons@infradead.org>
5945 // as part of a larger change when he added support for ${var/a/b}.
5946 // However, it broke # and % operators:
5950 //echo ${var#ab} abcdcd abcdcd
5951 //echo ${var##ab} abcdcd abcdcd
5952 //echo ${var#a*b} abcdcd ababcdcd (!)
5953 //echo ${var##a*b} cdcd cdcd
5954 //echo ${var#?} babcdcd ababcdcd (!)
5955 //echo ${var##?} babcdcd babcdcd
5956 //echo ${var#*} ababcdcd babcdcd (!)
5958 //echo ${var%cd} ababcd ababcd
5959 //echo ${var%%cd} ababcd abab (!)
5960 //echo ${var%c*d} ababcd ababcd
5961 //echo ${var%%c*d} abab ababcdcd (!)
5962 //echo ${var%?} ababcdc ababcdc
5963 //echo ${var%%?} ababcdc ababcdcd (!)
5964 //echo ${var%*} ababcdcd ababcdcd
5967 // Commenting it back out helped. Remove it completely if it really
5970 char *loc, *loc2; //, *full;
5976 int match; // = strlen(str);
5977 const char *s = loc2;
5984 match = pmatch(str, s); // this line was deleted
5986 // // chop off end if its '*'
5987 // full = strrchr(str, '*');
5988 // if (full && full != str)
5991 // // If str starts with '*' replace with s.
5992 // if ((*str == '*') && strlen(s) >= match) {
5993 // full = xstrdup(s);
5994 // strncpy(full+strlen(s)-match+1, str+1, match-1);
5996 // full = xstrndup(str, match);
5997 // match = strncmp(s, full, strlen(full));
6001 if (match) // if (!match)
6003 if (quotes && *loc == CTLESC)
6012 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6019 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6022 const char *s = loc2;
6027 match = pmatch(str, s);
6034 esc = esclen(startp, loc);
6045 static void varunset(const char *, const char *, const char *, int) NORETURN;
6047 varunset(const char *end, const char *var, const char *umsg, int varflags)
6053 msg = "parameter not set";
6055 if (*end == CTLENDVAR) {
6056 if (varflags & VSNUL)
6062 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6065 #if ENABLE_ASH_BASH_COMPAT
6067 parse_sub_pattern(char *arg, int inquotes)
6069 char *idx, *repl = NULL;
6078 /* Only the first '/' seen is our separator */
6085 if (!inquotes && c == '\\' && arg[1] == '\\')
6086 arg++; /* skip both \\, not just first one */
6093 #endif /* ENABLE_ASH_BASH_COMPAT */
6096 subevalvar(char *p, char *str, int strloc, int subtype,
6097 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6099 struct nodelist *saveargbackq = argbackq;
6102 char *rmesc, *rmescend;
6103 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6104 IF_ASH_BASH_COMPAT(char null = '\0';)
6105 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6106 int saveherefd = herefd;
6107 int amount, workloc, resetloc;
6109 char *(*scan)(char*, char*, char*, char*, int, int);
6112 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6114 STPUTC('\0', expdest);
6115 herefd = saveherefd;
6116 argbackq = saveargbackq;
6117 startp = (char *)stackblock() + startloc;
6121 setvar(str, startp, 0);
6122 amount = startp - expdest;
6123 STADJUST(amount, expdest);
6126 #if ENABLE_ASH_BASH_COMPAT
6128 loc = str = stackblock() + strloc;
6129 // TODO: number() instead? It does error checking...
6131 len = str - startp - 1;
6133 /* *loc != '\0', guaranteed by parser */
6137 /* We must adjust the length by the number of escapes we find. */
6138 for (ptr = startp; ptr < (str - 1); ptr++) {
6139 if (*ptr == CTLESC) {
6147 if (*loc++ == ':') {
6148 // TODO: number() instead? It does error checking...
6152 while (*loc && *loc != ':')
6155 // TODO: number() instead? It does error checking...
6158 if (pos >= orig_len) {
6162 if (len > (orig_len - pos))
6163 len = orig_len - pos;
6165 for (str = startp; pos; str++, pos--) {
6166 if (quotes && *str == CTLESC)
6169 for (loc = startp; len; len--) {
6170 if (quotes && *str == CTLESC)
6175 amount = loc - expdest;
6176 STADJUST(amount, expdest);
6181 varunset(p, str, startp, varflags);
6184 resetloc = expdest - (char *)stackblock();
6186 /* We'll comeback here if we grow the stack while handling
6187 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6188 * stack will need rebasing, and we'll need to remove our work
6191 IF_ASH_BASH_COMPAT(restart:)
6193 amount = expdest - ((char *)stackblock() + resetloc);
6194 STADJUST(-amount, expdest);
6195 startp = (char *)stackblock() + startloc;
6198 rmescend = (char *)stackblock() + strloc;
6200 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6201 if (rmesc != startp) {
6203 startp = (char *)stackblock() + startloc;
6207 str = (char *)stackblock() + strloc;
6208 preglob(str, varflags & VSQUOTE, 0);
6209 workloc = expdest - (char *)stackblock();
6211 #if ENABLE_ASH_BASH_COMPAT
6212 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6213 char *idx, *end, *restart_detect;
6216 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6221 /* If there's no pattern to match, return the expansion unmolested */
6229 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6231 /* No match, advance */
6232 restart_detect = stackblock();
6233 STPUTC(*idx, expdest);
6234 if (quotes && *idx == CTLESC) {
6237 STPUTC(*idx, expdest);
6239 if (stackblock() != restart_detect)
6247 if (subtype == VSREPLACEALL) {
6249 if (quotes && *idx == CTLESC)
6258 for (loc = repl; *loc; loc++) {
6259 restart_detect = stackblock();
6260 STPUTC(*loc, expdest);
6261 if (stackblock() != restart_detect)
6266 if (subtype == VSREPLACE) {
6268 restart_detect = stackblock();
6269 STPUTC(*idx, expdest);
6270 if (stackblock() != restart_detect)
6279 /* We've put the replaced text into a buffer at workloc, now
6280 * move it to the right place and adjust the stack.
6282 startp = stackblock() + startloc;
6283 STPUTC('\0', expdest);
6284 memmove(startp, stackblock() + workloc, len);
6285 startp[len++] = '\0';
6286 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6287 STADJUST(-amount, expdest);
6290 #endif /* ENABLE_ASH_BASH_COMPAT */
6292 subtype -= VSTRIMRIGHT;
6294 if (subtype < 0 || subtype > 7)
6297 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6298 zero = subtype >> 1;
6299 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6300 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6302 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6305 memmove(startp, loc, str - loc);
6306 loc = startp + (str - loc) - 1;
6309 amount = loc - expdest;
6310 STADJUST(amount, expdest);
6316 * Add the value of a specialized variable to the stack string.
6319 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6329 int quoted = varflags & VSQUOTE;
6330 int subtype = varflags & VSTYPE;
6331 int quotes = flags & (EXP_FULL | EXP_CASE);
6333 if (quoted && (flags & EXP_FULL))
6334 sep = 1 << CHAR_BIT;
6336 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6345 num = shellparam.nparam;
6355 expdest = makestrspace(NOPTS, expdest);
6356 for (i = NOPTS - 1; i >= 0; i--) {
6358 USTPUTC(optletters(i), expdest);
6368 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
6369 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6375 while ((p = *ap++)) {
6378 partlen = strlen(p);
6381 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6382 memtodest(p, partlen, syntax, quotes);
6388 if (subtype == VSPLUS || subtype == VSLENGTH) {
6409 // TODO: number() instead? It does error checking...
6411 if (num < 0 || num > shellparam.nparam)
6413 p = num ? shellparam.p[num - 1] : arg0;
6416 /* NB: name has form "VAR=..." */
6418 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6419 * which should be considered before we check variables. */
6421 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6425 str = var_str_list->text;
6426 eq = strchr(str, '=');
6427 if (!eq) /* stop at first non-assignment */
6430 if (name_len == (unsigned)(eq - str)
6431 && strncmp(str, name, name_len) == 0) {
6433 /* goto value; - WRONG! */
6434 /* think "A=1 A=2 B=$A" */
6436 var_str_list = var_str_list->next;
6437 } while (var_str_list);
6441 p = lookupvar(name);
6447 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6448 memtodest(p, len, syntax, quotes);
6452 if (subtype == VSPLUS || subtype == VSLENGTH)
6453 STADJUST(-len, expdest);
6458 * Expand a variable, and return a pointer to the next character in the
6462 evalvar(char *p, int flag, struct strlist *var_str_list)
6474 subtype = varflags & VSTYPE;
6475 quoted = varflags & VSQUOTE;
6477 easy = (!quoted || (*var == '@' && shellparam.nparam));
6478 startloc = expdest - (char *)stackblock();
6479 p = strchr(p, '=') + 1;
6482 varlen = varvalue(var, varflags, flag, var_str_list);
6483 if (varflags & VSNUL)
6486 if (subtype == VSPLUS) {
6487 varlen = -1 - varlen;
6491 if (subtype == VSMINUS) {
6495 p, flag | EXP_TILDE |
6496 (quoted ? EXP_QWORD : EXP_WORD),
6506 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6508 if (subevalvar(p, var, /* strloc: */ 0,
6509 subtype, startloc, varflags,
6515 * Remove any recorded regions beyond
6518 removerecordregions(startloc);
6528 if (varlen < 0 && uflag)
6529 varunset(p, var, 0, 0);
6531 if (subtype == VSLENGTH) {
6532 cvtnum(varlen > 0 ? varlen : 0);
6536 if (subtype == VSNORMAL) {
6547 case VSTRIMRIGHTMAX:
6548 #if ENABLE_ASH_BASH_COMPAT
6561 * Terminate the string and start recording the pattern
6564 STPUTC('\0', expdest);
6565 patloc = expdest - (char *)stackblock();
6566 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6568 /* quotes: */ flag & (EXP_FULL | EXP_CASE),
6571 int amount = expdest - (
6572 (char *)stackblock() + patloc - 1
6574 STADJUST(-amount, expdest);
6576 /* Remove any recorded regions beyond start of variable */
6577 removerecordregions(startloc);
6579 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6583 if (subtype != VSNORMAL) { /* skip to end of alternative */
6589 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6591 argbackq = argbackq->next;
6592 } else if (c == CTLVAR) {
6593 if ((*p++ & VSTYPE) != VSNORMAL)
6595 } else if (c == CTLENDVAR) {
6605 * Break the argument string into pieces based upon IFS and add the
6606 * strings to the argument list. The regions of the string to be
6607 * searched for IFS characters have been stored by recordregion.
6610 ifsbreakup(char *string, struct arglist *arglist)
6612 struct ifsregion *ifsp;
6617 const char *ifs, *realifs;
6622 if (ifslastp != NULL) {
6625 realifs = ifsset() ? ifsval() : defifs;
6628 p = string + ifsp->begoff;
6629 nulonly = ifsp->nulonly;
6630 ifs = nulonly ? nullstr : realifs;
6632 while (p < string + ifsp->endoff) {
6636 if (!strchr(ifs, *p)) {
6641 ifsspc = (strchr(defifs, *p) != NULL);
6642 /* Ignore IFS whitespace at start */
6643 if (q == start && ifsspc) {
6649 sp = stzalloc(sizeof(*sp));
6651 *arglist->lastp = sp;
6652 arglist->lastp = &sp->next;
6656 if (p >= string + ifsp->endoff) {
6662 if (strchr(ifs, *p) == NULL) {
6666 if (strchr(defifs, *p) == NULL) {
6681 } while (ifsp != NULL);
6690 sp = stzalloc(sizeof(*sp));
6692 *arglist->lastp = sp;
6693 arglist->lastp = &sp->next;
6699 struct ifsregion *p;
6704 struct ifsregion *ifsp;
6710 ifsfirst.next = NULL;
6715 * Add a file name to the list.
6718 addfname(const char *name)
6722 sp = stzalloc(sizeof(*sp));
6723 sp->text = ststrdup(name);
6725 exparg.lastp = &sp->next;
6728 static char *expdir;
6731 * Do metacharacter (i.e. *, ?, [...]) expansion.
6734 expmeta(char *enddir, char *name)
6749 for (p = name; *p; p++) {
6750 if (*p == '*' || *p == '?')
6752 else if (*p == '[') {
6759 if (*q == '/' || *q == '\0')
6766 } else if (*p == '\\')
6768 else if (*p == '/') {
6775 if (metaflag == 0) { /* we've reached the end of the file name */
6776 if (enddir != expdir)
6784 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6795 } while (p < start);
6797 if (enddir == expdir) {
6799 } else if (enddir == expdir + 1 && *expdir == '/') {
6808 if (enddir != expdir)
6810 if (*endname == 0) {
6822 while (!intpending && (dp = readdir(dirp)) != NULL) {
6823 if (dp->d_name[0] == '.' && !matchdot)
6825 if (pmatch(start, dp->d_name)) {
6827 strcpy(enddir, dp->d_name);
6830 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6833 expmeta(p, endname);
6842 static struct strlist *
6843 msort(struct strlist *list, int len)
6845 struct strlist *p, *q = NULL;
6846 struct strlist **lpp;
6854 for (n = half; --n >= 0;) {
6858 q->next = NULL; /* terminate first half of list */
6859 q = msort(list, half); /* sort first half of list */
6860 p = msort(p, len - half); /* sort second half */
6863 #if ENABLE_LOCALE_SUPPORT
6864 if (strcoll(p->text, q->text) < 0)
6866 if (strcmp(p->text, q->text) < 0)
6890 * Sort the results of file name expansion. It calculates the number of
6891 * strings to sort and then calls msort (short for merge sort) to do the
6894 static struct strlist *
6895 expsort(struct strlist *str)
6901 for (sp = str; sp; sp = sp->next)
6903 return msort(str, len);
6907 expandmeta(struct strlist *str /*, int flag*/)
6909 static const char metachars[] ALIGN1 = {
6912 /* TODO - EXP_REDIR */
6915 struct strlist **savelastp;
6921 if (!strpbrk(str->text, metachars))
6923 savelastp = exparg.lastp;
6926 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6928 int i = strlen(str->text);
6929 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6937 if (exparg.lastp == savelastp) {
6942 *exparg.lastp = str;
6943 rmescapes(str->text, 0);
6944 exparg.lastp = &str->next;
6946 *exparg.lastp = NULL;
6947 *savelastp = sp = expsort(*savelastp);
6948 while (sp->next != NULL)
6950 exparg.lastp = &sp->next;
6957 * Perform variable substitution and command substitution on an argument,
6958 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
6959 * perform splitting and file name expansion. When arglist is NULL, perform
6960 * here document expansion.
6963 expandarg(union node *arg, struct arglist *arglist, int flag)
6968 argbackq = arg->narg.backquote;
6969 STARTSTACKSTR(expdest);
6970 ifsfirst.next = NULL;
6972 argstr(arg->narg.text, flag,
6973 /* var_str_list: */ arglist ? arglist->list : NULL);
6974 p = _STPUTC('\0', expdest);
6976 if (arglist == NULL) {
6977 return; /* here document expanded */
6979 p = grabstackstr(p);
6980 exparg.lastp = &exparg.list;
6984 if (flag & EXP_FULL) {
6985 ifsbreakup(p, &exparg);
6986 *exparg.lastp = NULL;
6987 exparg.lastp = &exparg.list;
6988 expandmeta(exparg.list /*, flag*/);
6990 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
6992 sp = stzalloc(sizeof(*sp));
6995 exparg.lastp = &sp->next;
6999 *exparg.lastp = NULL;
7001 *arglist->lastp = exparg.list;
7002 arglist->lastp = exparg.lastp;
7007 * Expand shell variables and backquotes inside a here document.
7010 expandhere(union node *arg, int fd)
7013 expandarg(arg, (struct arglist *)NULL, 0);
7014 full_write(fd, stackblock(), expdest - (char *)stackblock());
7018 * Returns true if the pattern matches the string.
7021 patmatch(char *pattern, const char *string)
7023 return pmatch(preglob(pattern, 0, 0), string);
7027 * See if a pattern matches in a case statement.
7030 casematch(union node *pattern, char *val)
7032 struct stackmark smark;
7035 setstackmark(&smark);
7036 argbackq = pattern->narg.backquote;
7037 STARTSTACKSTR(expdest);
7039 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7040 /* var_str_list: */ NULL);
7041 STACKSTRNUL(expdest);
7042 result = patmatch(stackblock(), val);
7043 popstackmark(&smark);
7048 /* ============ find_command */
7052 int (*builtin)(int, char **) FAST_FUNC;
7053 /* unsigned flags; */
7055 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7056 /* "regular" builtins always take precedence over commands,
7057 * regardless of PATH=....%builtin... position */
7058 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7059 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7062 smallint cmdtype; /* CMDxxx */
7065 /* index >= 0 for commands without path (slashes) */
7066 /* (TODO: what exactly does the value mean? PATH position?) */
7067 /* index == -1 for commands with slashes */
7068 /* index == (-2 - applet_no) for NOFORK applets */
7069 const struct builtincmd *cmd;
7070 struct funcnode *func;
7073 /* values of cmdtype */
7074 #define CMDUNKNOWN -1 /* no entry in table for command */
7075 #define CMDNORMAL 0 /* command is an executable program */
7076 #define CMDFUNCTION 1 /* command is a shell function */
7077 #define CMDBUILTIN 2 /* command is a shell builtin */
7079 /* action to find_command() */
7080 #define DO_ERR 0x01 /* prints errors */
7081 #define DO_ABS 0x02 /* checks absolute paths */
7082 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7083 #define DO_ALTPATH 0x08 /* using alternate path */
7084 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7086 static void find_command(char *, struct cmdentry *, int, const char *);
7089 /* ============ Hashing commands */
7092 * When commands are first encountered, they are entered in a hash table.
7093 * This ensures that a full path search will not have to be done for them
7094 * on each invocation.
7096 * We should investigate converting to a linear search, even though that
7097 * would make the command name "hash" a misnomer.
7101 struct tblentry *next; /* next entry in hash chain */
7102 union param param; /* definition of builtin function */
7103 smallint cmdtype; /* CMDxxx */
7104 char rehash; /* if set, cd done since entry created */
7105 char cmdname[1]; /* name of command */
7108 static struct tblentry **cmdtable;
7109 #define INIT_G_cmdtable() do { \
7110 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7113 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7117 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7121 #if ENABLE_FEATURE_SH_STANDALONE
7122 if (applet_no >= 0) {
7123 if (APPLET_IS_NOEXEC(applet_no)) {
7126 run_applet_no_and_exit(applet_no, argv);
7128 /* re-exec ourselves with the new arguments */
7129 execve(bb_busybox_exec_path, argv, envp);
7130 /* If they called chroot or otherwise made the binary no longer
7131 * executable, fall through */
7138 execve(cmd, argv, envp);
7139 } while (errno == EINTR);
7141 execve(cmd, argv, envp);
7147 if (errno == ENOEXEC) {
7151 for (ap = argv; *ap; ap++)
7153 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7155 ap[0] = cmd = (char *)DEFAULT_SHELL;
7158 while ((*ap++ = *argv++) != NULL)
7167 * Exec a program. Never returns. If you change this routine, you may
7168 * have to change the find_command routine as well.
7170 static void shellexec(char **, const char *, int) NORETURN;
7172 shellexec(char **argv, const char *path, int idx)
7178 #if ENABLE_FEATURE_SH_STANDALONE
7182 clearredir(/*drop:*/ 1);
7183 envp = listvars(VEXPORT, VUNSET, 0);
7184 if (strchr(argv[0], '/') != NULL
7185 #if ENABLE_FEATURE_SH_STANDALONE
7186 || (applet_no = find_applet_by_name(argv[0])) >= 0
7189 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7193 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7194 if (--idx < 0 && pathopt == NULL) {
7195 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7196 if (errno != ENOENT && errno != ENOTDIR)
7203 /* Map to POSIX errors */
7215 exitstatus = exerrno;
7216 TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
7217 argv[0], e, suppressint));
7218 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7223 printentry(struct tblentry *cmdp)
7229 idx = cmdp->param.index;
7232 name = path_advance(&path, cmdp->cmdname);
7234 } while (--idx >= 0);
7235 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7239 * Clear out command entries. The argument specifies the first entry in
7240 * PATH which has changed.
7243 clearcmdentry(int firstchange)
7245 struct tblentry **tblp;
7246 struct tblentry **pp;
7247 struct tblentry *cmdp;
7250 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7252 while ((cmdp = *pp) != NULL) {
7253 if ((cmdp->cmdtype == CMDNORMAL &&
7254 cmdp->param.index >= firstchange)
7255 || (cmdp->cmdtype == CMDBUILTIN &&
7256 builtinloc >= firstchange)
7269 * Locate a command in the command hash table. If "add" is nonzero,
7270 * add the command to the table if it is not already present. The
7271 * variable "lastcmdentry" is set to point to the address of the link
7272 * pointing to the entry, so that delete_cmd_entry can delete the
7275 * Interrupts must be off if called with add != 0.
7277 static struct tblentry **lastcmdentry;
7279 static struct tblentry *
7280 cmdlookup(const char *name, int add)
7282 unsigned int hashval;
7284 struct tblentry *cmdp;
7285 struct tblentry **pp;
7288 hashval = (unsigned char)*p << 4;
7290 hashval += (unsigned char)*p++;
7292 pp = &cmdtable[hashval % CMDTABLESIZE];
7293 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7294 if (strcmp(cmdp->cmdname, name) == 0)
7298 if (add && cmdp == NULL) {
7299 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7301 /* + 1 - already done because
7302 * tblentry::cmdname is char[1] */);
7303 /*cmdp->next = NULL; - ckzalloc did it */
7304 cmdp->cmdtype = CMDUNKNOWN;
7305 strcpy(cmdp->cmdname, name);
7312 * Delete the command entry returned on the last lookup.
7315 delete_cmd_entry(void)
7317 struct tblentry *cmdp;
7320 cmdp = *lastcmdentry;
7321 *lastcmdentry = cmdp->next;
7322 if (cmdp->cmdtype == CMDFUNCTION)
7323 freefunc(cmdp->param.func);
7329 * Add a new command entry, replacing any existing command entry for
7330 * the same name - except special builtins.
7333 addcmdentry(char *name, struct cmdentry *entry)
7335 struct tblentry *cmdp;
7337 cmdp = cmdlookup(name, 1);
7338 if (cmdp->cmdtype == CMDFUNCTION) {
7339 freefunc(cmdp->param.func);
7341 cmdp->cmdtype = entry->cmdtype;
7342 cmdp->param = entry->u;
7346 static int FAST_FUNC
7347 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7349 struct tblentry **pp;
7350 struct tblentry *cmdp;
7352 struct cmdentry entry;
7355 if (nextopt("r") != '\0') {
7360 if (*argptr == NULL) {
7361 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7362 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7363 if (cmdp->cmdtype == CMDNORMAL)
7371 while ((name = *argptr) != NULL) {
7372 cmdp = cmdlookup(name, 0);
7374 && (cmdp->cmdtype == CMDNORMAL
7375 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7379 find_command(name, &entry, DO_ERR, pathval());
7380 if (entry.cmdtype == CMDUNKNOWN)
7388 * Called when a cd is done. Marks all commands so the next time they
7389 * are executed they will be rehashed.
7394 struct tblentry **pp;
7395 struct tblentry *cmdp;
7397 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7398 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7399 if (cmdp->cmdtype == CMDNORMAL
7400 || (cmdp->cmdtype == CMDBUILTIN
7401 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7411 * Fix command hash table when PATH changed.
7412 * Called before PATH is changed. The argument is the new value of PATH;
7413 * pathval() still returns the old value at this point.
7414 * Called with interrupts off.
7416 static void FAST_FUNC
7417 changepath(const char *new)
7425 firstchange = 9999; /* assume no change */
7431 if ((*old == '\0' && *new == ':')
7432 || (*old == ':' && *new == '\0'))
7434 old = new; /* ignore subsequent differences */
7438 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7444 if (builtinloc < 0 && idx_bltin >= 0)
7445 builtinloc = idx_bltin; /* zap builtins */
7446 if (builtinloc >= 0 && idx_bltin < 0)
7448 clearcmdentry(firstchange);
7449 builtinloc = idx_bltin;
7464 #define TENDBQUOTE 12
7481 typedef smallint token_id_t;
7483 /* first char is indicating which tokens mark the end of a list */
7484 static const char *const tokname_array[] = {
7498 #define KWDOFFSET 13
7499 /* the following are keywords */
7521 static char buf[16];
7524 //if (tok < TSEMI) return tokname_array[tok] + 1;
7525 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7530 sprintf(buf + (tok >= TSEMI), "%s%c",
7531 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7535 /* Wrapper around strcmp for qsort/bsearch/... */
7537 pstrcmp(const void *a, const void *b)
7539 return strcmp((char*) a, (*(char**) b) + 1);
7542 static const char *const *
7543 findkwd(const char *s)
7545 return bsearch(s, tokname_array + KWDOFFSET,
7546 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7547 sizeof(tokname_array[0]), pstrcmp);
7551 * Locate and print what a word is...
7554 describe_command(char *command, int describe_command_verbose)
7556 struct cmdentry entry;
7557 struct tblentry *cmdp;
7558 #if ENABLE_ASH_ALIAS
7559 const struct alias *ap;
7561 const char *path = pathval();
7563 if (describe_command_verbose) {
7567 /* First look at the keywords */
7568 if (findkwd(command)) {
7569 out1str(describe_command_verbose ? " is a shell keyword" : command);
7573 #if ENABLE_ASH_ALIAS
7574 /* Then look at the aliases */
7575 ap = lookupalias(command, 0);
7577 if (!describe_command_verbose) {
7582 out1fmt(" is an alias for %s", ap->val);
7586 /* Then check if it is a tracked alias */
7587 cmdp = cmdlookup(command, 0);
7589 entry.cmdtype = cmdp->cmdtype;
7590 entry.u = cmdp->param;
7592 /* Finally use brute force */
7593 find_command(command, &entry, DO_ABS, path);
7596 switch (entry.cmdtype) {
7598 int j = entry.u.index;
7604 p = path_advance(&path, command);
7608 if (describe_command_verbose) {
7610 (cmdp ? " a tracked alias for" : nullstr), p
7619 if (describe_command_verbose) {
7620 out1str(" is a shell function");
7627 if (describe_command_verbose) {
7628 out1fmt(" is a %sshell builtin",
7629 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7630 "special " : nullstr
7638 if (describe_command_verbose) {
7639 out1str(": not found\n");
7644 outstr("\n", stdout);
7648 static int FAST_FUNC
7649 typecmd(int argc UNUSED_PARAM, char **argv)
7655 /* type -p ... ? (we don't bother checking for 'p') */
7656 if (argv[1] && argv[1][0] == '-') {
7661 err |= describe_command(argv[i++], verbose);
7666 #if ENABLE_ASH_CMDCMD
7667 static int FAST_FUNC
7668 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7676 while ((c = nextopt("pvV")) != '\0')
7678 verify |= VERIFY_VERBOSE;
7680 verify |= VERIFY_BRIEF;
7685 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7686 if (verify && (*argptr != NULL)) {
7687 return describe_command(*argptr, verify - VERIFY_BRIEF);
7695 /* ============ eval.c */
7697 static int funcblocksize; /* size of structures in function */
7698 static int funcstringsize; /* size of strings in node */
7699 static void *funcblock; /* block to allocate function from */
7700 static char *funcstring; /* block to allocate strings from */
7702 /* flags in argument to evaltree */
7703 #define EV_EXIT 01 /* exit after evaluating tree */
7704 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7705 #define EV_BACKCMD 04 /* command executing within back quotes */
7707 static const short nodesize[N_NUMBER] = {
7708 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7709 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7710 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7711 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7712 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7713 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7714 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7715 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7716 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7717 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7718 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7719 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7720 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7721 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7722 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7723 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7724 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7725 #if ENABLE_ASH_BASH_COMPAT
7726 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7728 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7729 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7730 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7731 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7732 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7733 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7734 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7735 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7736 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7739 static void calcsize(union node *n);
7742 sizenodelist(struct nodelist *lp)
7745 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7752 calcsize(union node *n)
7756 funcblocksize += nodesize[n->type];
7759 calcsize(n->ncmd.redirect);
7760 calcsize(n->ncmd.args);
7761 calcsize(n->ncmd.assign);
7764 sizenodelist(n->npipe.cmdlist);
7769 calcsize(n->nredir.redirect);
7770 calcsize(n->nredir.n);
7777 calcsize(n->nbinary.ch2);
7778 calcsize(n->nbinary.ch1);
7781 calcsize(n->nif.elsepart);
7782 calcsize(n->nif.ifpart);
7783 calcsize(n->nif.test);
7786 funcstringsize += strlen(n->nfor.var) + 1;
7787 calcsize(n->nfor.body);
7788 calcsize(n->nfor.args);
7791 calcsize(n->ncase.cases);
7792 calcsize(n->ncase.expr);
7795 calcsize(n->nclist.body);
7796 calcsize(n->nclist.pattern);
7797 calcsize(n->nclist.next);
7801 sizenodelist(n->narg.backquote);
7802 funcstringsize += strlen(n->narg.text) + 1;
7803 calcsize(n->narg.next);
7806 #if ENABLE_ASH_BASH_COMPAT
7813 calcsize(n->nfile.fname);
7814 calcsize(n->nfile.next);
7818 calcsize(n->ndup.vname);
7819 calcsize(n->ndup.next);
7823 calcsize(n->nhere.doc);
7824 calcsize(n->nhere.next);
7827 calcsize(n->nnot.com);
7833 nodeckstrdup(char *s)
7835 char *rtn = funcstring;
7837 strcpy(funcstring, s);
7838 funcstring += strlen(s) + 1;
7842 static union node *copynode(union node *);
7844 static struct nodelist *
7845 copynodelist(struct nodelist *lp)
7847 struct nodelist *start;
7848 struct nodelist **lpp;
7853 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7854 (*lpp)->n = copynode(lp->n);
7856 lpp = &(*lpp)->next;
7863 copynode(union node *n)
7870 funcblock = (char *) funcblock + nodesize[n->type];
7874 new->ncmd.redirect = copynode(n->ncmd.redirect);
7875 new->ncmd.args = copynode(n->ncmd.args);
7876 new->ncmd.assign = copynode(n->ncmd.assign);
7879 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7880 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
7885 new->nredir.redirect = copynode(n->nredir.redirect);
7886 new->nredir.n = copynode(n->nredir.n);
7893 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7894 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7897 new->nif.elsepart = copynode(n->nif.elsepart);
7898 new->nif.ifpart = copynode(n->nif.ifpart);
7899 new->nif.test = copynode(n->nif.test);
7902 new->nfor.var = nodeckstrdup(n->nfor.var);
7903 new->nfor.body = copynode(n->nfor.body);
7904 new->nfor.args = copynode(n->nfor.args);
7907 new->ncase.cases = copynode(n->ncase.cases);
7908 new->ncase.expr = copynode(n->ncase.expr);
7911 new->nclist.body = copynode(n->nclist.body);
7912 new->nclist.pattern = copynode(n->nclist.pattern);
7913 new->nclist.next = copynode(n->nclist.next);
7917 new->narg.backquote = copynodelist(n->narg.backquote);
7918 new->narg.text = nodeckstrdup(n->narg.text);
7919 new->narg.next = copynode(n->narg.next);
7922 #if ENABLE_ASH_BASH_COMPAT
7929 new->nfile.fname = copynode(n->nfile.fname);
7930 new->nfile.fd = n->nfile.fd;
7931 new->nfile.next = copynode(n->nfile.next);
7935 new->ndup.vname = copynode(n->ndup.vname);
7936 new->ndup.dupfd = n->ndup.dupfd;
7937 new->ndup.fd = n->ndup.fd;
7938 new->ndup.next = copynode(n->ndup.next);
7942 new->nhere.doc = copynode(n->nhere.doc);
7943 new->nhere.fd = n->nhere.fd;
7944 new->nhere.next = copynode(n->nhere.next);
7947 new->nnot.com = copynode(n->nnot.com);
7950 new->type = n->type;
7955 * Make a copy of a parse tree.
7957 static struct funcnode *
7958 copyfunc(union node *n)
7963 funcblocksize = offsetof(struct funcnode, n);
7966 blocksize = funcblocksize;
7967 f = ckmalloc(blocksize + funcstringsize);
7968 funcblock = (char *) f + offsetof(struct funcnode, n);
7969 funcstring = (char *) f + blocksize;
7976 * Define a shell function.
7979 defun(char *name, union node *func)
7981 struct cmdentry entry;
7984 entry.cmdtype = CMDFUNCTION;
7985 entry.u.func = copyfunc(func);
7986 addcmdentry(name, &entry);
7990 /* Reasons for skipping commands (see comment on breakcmd routine) */
7991 #define SKIPBREAK (1 << 0)
7992 #define SKIPCONT (1 << 1)
7993 #define SKIPFUNC (1 << 2)
7994 #define SKIPFILE (1 << 3)
7995 #define SKIPEVAL (1 << 4)
7996 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
7997 static int skipcount; /* number of levels to skip */
7998 static int funcnest; /* depth of function calls */
7999 static int loopnest; /* current loop nesting level */
8001 /* Forward decl way out to parsing code - dotrap needs it */
8002 static int evalstring(char *s, int mask);
8004 /* Called to execute a trap.
8005 * Single callsite - at the end of evaltree().
8006 * If we return non-zero, exaltree raises EXEXIT exception.
8008 * Perhaps we should avoid entering new trap handlers
8009 * while we are executing a trap handler. [is it a TODO?]
8018 savestatus = exitstatus;
8022 TRACE(("dotrap entered\n"));
8023 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8030 /* non-trapped SIGINT is handled separately by raise_interrupt,
8031 * don't upset it by resetting gotsig[SIGINT-1] */
8032 if (sig == SIGINT && !t)
8035 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8039 want_exexit = evalstring(t, SKIPEVAL);
8040 exitstatus = savestatus;
8042 TRACE(("dotrap returns %d\n", want_exexit));
8047 TRACE(("dotrap returns 0\n"));
8051 /* forward declarations - evaluation is fairly recursive business... */
8052 static void evalloop(union node *, int);
8053 static void evalfor(union node *, int);
8054 static void evalcase(union node *, int);
8055 static void evalsubshell(union node *, int);
8056 static void expredir(union node *);
8057 static void evalpipe(union node *, int);
8058 static void evalcommand(union node *, int);
8059 static int evalbltin(const struct builtincmd *, int, char **);
8060 static void prehash(union node *);
8063 * Evaluate a parse tree. The value is left in the global variable
8067 evaltree(union node *n, int flags)
8069 struct jmploc *volatile savehandler = exception_handler;
8070 struct jmploc jmploc;
8072 void (*evalfn)(union node *, int);
8076 SAVE_INT(int_level);
8079 TRACE(("evaltree(NULL) called\n"));
8082 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8084 exception_handler = &jmploc;
8086 int err = setjmp(jmploc.loc);
8088 /* if it was a signal, check for trap handlers */
8089 if (exception_type == EXSIG) {
8090 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8091 exception_type, err));
8094 /* continue on the way out */
8095 TRACE(("exception %d in evaltree, propagating err=%d\n",
8096 exception_type, err));
8097 exception_handler = savehandler;
8098 longjmp(exception_handler->loc, err);
8105 out1fmt("Node type = %d\n", n->type);
8110 evaltree(n->nnot.com, EV_TESTED);
8111 status = !exitstatus;
8114 expredir(n->nredir.redirect);
8115 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8117 evaltree(n->nredir.n, flags & EV_TESTED);
8118 status = exitstatus;
8120 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8123 evalfn = evalcommand;
8125 if (eflag && !(flags & EV_TESTED))
8137 evalfn = evalsubshell;
8150 #error NAND + 1 != NOR
8152 #if NOR + 1 != NSEMI
8153 #error NOR + 1 != NSEMI
8155 unsigned is_or = n->type - NAND;
8158 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8160 if (!exitstatus == is_or)
8173 evaltree(n->nif.test, EV_TESTED);
8176 if (exitstatus == 0) {
8180 if (n->nif.elsepart) {
8181 n = n->nif.elsepart;
8186 defun(n->narg.text, n->narg.next);
8190 exitstatus = status;
8195 exception_handler = savehandler;
8197 if (checkexit & exitstatus)
8198 evalskip |= SKIPEVAL;
8199 else if (pendingsig && dotrap())
8202 if (flags & EV_EXIT) {
8204 raise_exception(EXEXIT);
8207 RESTORE_INT(int_level);
8208 TRACE(("leaving evaltree (no interrupts)\n"));
8211 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8214 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8217 evalloop(union node *n, int flags)
8227 evaltree(n->nbinary.ch1, EV_TESTED);
8230 if (evalskip == SKIPCONT && --skipcount <= 0) {
8234 if (evalskip == SKIPBREAK && --skipcount <= 0)
8239 if (n->type != NWHILE)
8243 evaltree(n->nbinary.ch2, flags);
8244 status = exitstatus;
8249 exitstatus = status;
8253 evalfor(union node *n, int flags)
8255 struct arglist arglist;
8258 struct stackmark smark;
8260 setstackmark(&smark);
8261 arglist.list = NULL;
8262 arglist.lastp = &arglist.list;
8263 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8264 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8269 *arglist.lastp = NULL;
8274 for (sp = arglist.list; sp; sp = sp->next) {
8275 setvar(n->nfor.var, sp->text, 0);
8276 evaltree(n->nfor.body, flags);
8278 if (evalskip == SKIPCONT && --skipcount <= 0) {
8282 if (evalskip == SKIPBREAK && --skipcount <= 0)
8289 popstackmark(&smark);
8293 evalcase(union node *n, int flags)
8297 struct arglist arglist;
8298 struct stackmark smark;
8300 setstackmark(&smark);
8301 arglist.list = NULL;
8302 arglist.lastp = &arglist.list;
8303 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8305 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8306 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8307 if (casematch(patp, arglist.list->text)) {
8308 if (evalskip == 0) {
8309 evaltree(cp->nclist.body, flags);
8316 popstackmark(&smark);
8320 * Kick off a subshell to evaluate a tree.
8323 evalsubshell(union node *n, int flags)
8326 int backgnd = (n->type == NBACKGND);
8329 expredir(n->nredir.redirect);
8330 if (!backgnd && flags & EV_EXIT && !trap[0])
8333 jp = makejob(/*n,*/ 1);
8334 if (forkshell(jp, n, backgnd) == 0) {
8338 flags &=~ EV_TESTED;
8340 redirect(n->nredir.redirect, 0);
8341 evaltreenr(n->nredir.n, flags);
8346 status = waitforjob(jp);
8347 exitstatus = status;
8352 * Compute the names of the files in a redirection list.
8354 static void fixredir(union node *, const char *, int);
8356 expredir(union node *n)
8360 for (redir = n; redir; redir = redir->nfile.next) {
8364 fn.lastp = &fn.list;
8365 switch (redir->type) {
8369 #if ENABLE_ASH_BASH_COMPAT
8374 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8375 #if ENABLE_ASH_BASH_COMPAT
8378 redir->nfile.expfname = fn.list->text;
8381 case NTOFD: /* >& */
8382 if (redir->ndup.vname) {
8383 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8384 if (fn.list == NULL)
8385 ash_msg_and_raise_error("redir error");
8386 #if ENABLE_ASH_BASH_COMPAT
8387 //FIXME: we used expandarg with different args!
8388 if (!isdigit_str9(fn.list->text)) {
8389 /* >&file, not >&fd */
8390 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8391 ash_msg_and_raise_error("redir error");
8393 goto store_expfname;
8396 fixredir(redir, fn.list->text, 1);
8404 * Evaluate a pipeline. All the processes in the pipeline are children
8405 * of the process creating the pipeline. (This differs from some versions
8406 * of the shell, which make the last process in a pipeline the parent
8410 evalpipe(union node *n, int flags)
8413 struct nodelist *lp;
8418 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8420 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8424 jp = makejob(/*n,*/ pipelen);
8426 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8430 if (pipe(pip) < 0) {
8432 ash_msg_and_raise_error("pipe call failed");
8435 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8448 evaltreenr(lp->n, flags);
8454 /* Don't want to trigger debugging */
8458 if (n->npipe.pipe_backgnd == 0) {
8459 exitstatus = waitforjob(jp);
8460 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8466 * Controls whether the shell is interactive or not.
8469 setinteractive(int on)
8471 static smallint is_interactive;
8473 if (++on == is_interactive)
8475 is_interactive = on;
8479 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8480 if (is_interactive > 1) {
8481 /* Looks like they want an interactive shell */
8482 static smallint did_banner;
8487 "%s built-in shell (ash)\n"
8488 "Enter 'help' for a list of built-in commands."
8503 setinteractive(iflag);
8505 #if ENABLE_FEATURE_EDITING_VI
8507 line_input_state->flags |= VI_MODE;
8509 line_input_state->flags &= ~VI_MODE;
8511 viflag = 0; /* forcibly keep the option off */
8515 static struct localvar *localvars;
8518 * Called after a function returns.
8519 * Interrupts must be off.
8524 struct localvar *lvp;
8527 while ((lvp = localvars) != NULL) {
8528 localvars = lvp->next;
8530 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8531 if (vp == NULL) { /* $- saved */
8532 memcpy(optlist, lvp->text, sizeof(optlist));
8533 free((char*)lvp->text);
8535 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8539 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8540 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8541 free((char*)vp->text);
8542 vp->flags = lvp->flags;
8543 vp->text = lvp->text;
8550 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8552 volatile struct shparam saveparam;
8553 struct localvar *volatile savelocalvars;
8554 struct jmploc *volatile savehandler;
8555 struct jmploc jmploc;
8558 saveparam = shellparam;
8559 savelocalvars = localvars;
8560 e = setjmp(jmploc.loc);
8565 savehandler = exception_handler;
8566 exception_handler = &jmploc;
8568 shellparam.malloced = 0;
8572 shellparam.nparam = argc - 1;
8573 shellparam.p = argv + 1;
8574 #if ENABLE_ASH_GETOPTS
8575 shellparam.optind = 1;
8576 shellparam.optoff = -1;
8578 evaltree(&func->n, flags & EV_TESTED);
8584 localvars = savelocalvars;
8585 freeparam(&shellparam);
8586 shellparam = saveparam;
8587 exception_handler = savehandler;
8589 evalskip &= ~SKIPFUNC;
8593 #if ENABLE_ASH_CMDCMD
8595 parse_command_args(char **argv, const char **path)
8608 if (c == '-' && !*cp) {
8615 *path = bb_default_path;
8618 /* run 'typecmd' for other options */
8629 * Make a variable a local variable. When a variable is made local, it's
8630 * value and flags are saved in a localvar structure. The saved values
8631 * will be restored when the shell function returns. We handle the name
8632 * "-" as a special case.
8637 struct localvar *lvp;
8642 lvp = ckzalloc(sizeof(struct localvar));
8643 if (LONE_DASH(name)) {
8645 p = ckmalloc(sizeof(optlist));
8646 lvp->text = memcpy(p, optlist, sizeof(optlist));
8651 vpp = hashvar(name);
8652 vp = *findvar(vpp, name);
8653 eq = strchr(name, '=');
8656 setvareq(name, VSTRFIXED);
8658 setvar(name, NULL, VSTRFIXED);
8659 vp = *vpp; /* the new variable */
8660 lvp->flags = VUNSET;
8662 lvp->text = vp->text;
8663 lvp->flags = vp->flags;
8664 vp->flags |= VSTRFIXED|VTEXTFIXED;
8670 lvp->next = localvars;
8676 * The "local" command.
8678 static int FAST_FUNC
8679 localcmd(int argc UNUSED_PARAM, char **argv)
8684 while ((name = *argv++) != NULL) {
8690 static int FAST_FUNC
8691 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8696 static int FAST_FUNC
8697 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8702 static int FAST_FUNC
8703 execcmd(int argc UNUSED_PARAM, char **argv)
8706 iflag = 0; /* exit on error */
8709 shellexec(argv + 1, pathval(), 0);
8715 * The return command.
8717 static int FAST_FUNC
8718 returncmd(int argc UNUSED_PARAM, char **argv)
8721 * If called outside a function, do what ksh does;
8722 * skip the rest of the file.
8724 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8725 return argv[1] ? number(argv[1]) : exitstatus;
8728 /* Forward declarations for builtintab[] */
8729 static int breakcmd(int, char **) FAST_FUNC;
8730 static int dotcmd(int, char **) FAST_FUNC;
8731 static int evalcmd(int, char **) FAST_FUNC;
8732 static int exitcmd(int, char **) FAST_FUNC;
8733 static int exportcmd(int, char **) FAST_FUNC;
8734 #if ENABLE_ASH_GETOPTS
8735 static int getoptscmd(int, char **) FAST_FUNC;
8737 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8738 static int helpcmd(int, char **) FAST_FUNC;
8740 #if ENABLE_SH_MATH_SUPPORT
8741 static int letcmd(int, char **) FAST_FUNC;
8743 static int readcmd(int, char **) FAST_FUNC;
8744 static int setcmd(int, char **) FAST_FUNC;
8745 static int shiftcmd(int, char **) FAST_FUNC;
8746 static int timescmd(int, char **) FAST_FUNC;
8747 static int trapcmd(int, char **) FAST_FUNC;
8748 static int umaskcmd(int, char **) FAST_FUNC;
8749 static int unsetcmd(int, char **) FAST_FUNC;
8750 static int ulimitcmd(int, char **) FAST_FUNC;
8752 #define BUILTIN_NOSPEC "0"
8753 #define BUILTIN_SPECIAL "1"
8754 #define BUILTIN_REGULAR "2"
8755 #define BUILTIN_SPEC_REG "3"
8756 #define BUILTIN_ASSIGN "4"
8757 #define BUILTIN_SPEC_ASSG "5"
8758 #define BUILTIN_REG_ASSG "6"
8759 #define BUILTIN_SPEC_REG_ASSG "7"
8761 /* Stubs for calling non-FAST_FUNC's */
8762 #if ENABLE_ASH_BUILTIN_ECHO
8763 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8765 #if ENABLE_ASH_BUILTIN_PRINTF
8766 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8768 #if ENABLE_ASH_BUILTIN_TEST
8769 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8772 /* Keep these in proper order since it is searched via bsearch() */
8773 static const struct builtincmd builtintab[] = {
8774 { BUILTIN_SPEC_REG ".", dotcmd },
8775 { BUILTIN_SPEC_REG ":", truecmd },
8776 #if ENABLE_ASH_BUILTIN_TEST
8777 { BUILTIN_REGULAR "[", testcmd },
8778 #if ENABLE_ASH_BASH_COMPAT
8779 { BUILTIN_REGULAR "[[", testcmd },
8782 #if ENABLE_ASH_ALIAS
8783 { BUILTIN_REG_ASSG "alias", aliascmd },
8786 { BUILTIN_REGULAR "bg", fg_bgcmd },
8788 { BUILTIN_SPEC_REG "break", breakcmd },
8789 { BUILTIN_REGULAR "cd", cdcmd },
8790 { BUILTIN_NOSPEC "chdir", cdcmd },
8791 #if ENABLE_ASH_CMDCMD
8792 { BUILTIN_REGULAR "command", commandcmd },
8794 { BUILTIN_SPEC_REG "continue", breakcmd },
8795 #if ENABLE_ASH_BUILTIN_ECHO
8796 { BUILTIN_REGULAR "echo", echocmd },
8798 { BUILTIN_SPEC_REG "eval", evalcmd },
8799 { BUILTIN_SPEC_REG "exec", execcmd },
8800 { BUILTIN_SPEC_REG "exit", exitcmd },
8801 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8802 { BUILTIN_REGULAR "false", falsecmd },
8804 { BUILTIN_REGULAR "fg", fg_bgcmd },
8806 #if ENABLE_ASH_GETOPTS
8807 { BUILTIN_REGULAR "getopts", getoptscmd },
8809 { BUILTIN_NOSPEC "hash", hashcmd },
8810 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8811 { BUILTIN_NOSPEC "help", helpcmd },
8814 { BUILTIN_REGULAR "jobs", jobscmd },
8815 { BUILTIN_REGULAR "kill", killcmd },
8817 #if ENABLE_SH_MATH_SUPPORT
8818 { BUILTIN_NOSPEC "let", letcmd },
8820 { BUILTIN_ASSIGN "local", localcmd },
8821 #if ENABLE_ASH_BUILTIN_PRINTF
8822 { BUILTIN_REGULAR "printf", printfcmd },
8824 { BUILTIN_NOSPEC "pwd", pwdcmd },
8825 { BUILTIN_REGULAR "read", readcmd },
8826 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8827 { BUILTIN_SPEC_REG "return", returncmd },
8828 { BUILTIN_SPEC_REG "set", setcmd },
8829 { BUILTIN_SPEC_REG "shift", shiftcmd },
8830 { BUILTIN_SPEC_REG "source", dotcmd },
8831 #if ENABLE_ASH_BUILTIN_TEST
8832 { BUILTIN_REGULAR "test", testcmd },
8834 { BUILTIN_SPEC_REG "times", timescmd },
8835 { BUILTIN_SPEC_REG "trap", trapcmd },
8836 { BUILTIN_REGULAR "true", truecmd },
8837 { BUILTIN_NOSPEC "type", typecmd },
8838 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8839 { BUILTIN_REGULAR "umask", umaskcmd },
8840 #if ENABLE_ASH_ALIAS
8841 { BUILTIN_REGULAR "unalias", unaliascmd },
8843 { BUILTIN_SPEC_REG "unset", unsetcmd },
8844 { BUILTIN_REGULAR "wait", waitcmd },
8847 /* Should match the above table! */
8848 #define COMMANDCMD (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 #define EXECCMD (builtintab + \
8857 1 * ENABLE_ASH_BUILTIN_TEST + \
8858 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8859 1 * ENABLE_ASH_ALIAS + \
8860 1 * ENABLE_ASH_JOB_CONTROL + \
8862 1 * ENABLE_ASH_CMDCMD + \
8864 ENABLE_ASH_BUILTIN_ECHO + \
8868 * Search the table of builtin commands.
8870 static struct builtincmd *
8871 find_builtin(const char *name)
8873 struct builtincmd *bp;
8876 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8883 * Execute a simple command.
8886 isassignment(const char *p)
8888 const char *q = endofname(p);
8893 static int FAST_FUNC
8894 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8896 /* Preserve exitstatus of a previous possible redirection
8897 * as POSIX mandates */
8898 return back_exitstatus;
8901 evalcommand(union node *cmd, int flags)
8903 static const struct builtincmd null_bltin = {
8904 "\0\0", bltincmd /* why three NULs? */
8906 struct stackmark smark;
8908 struct arglist arglist;
8909 struct arglist varlist;
8912 const struct strlist *sp;
8913 struct cmdentry cmdentry;
8920 struct builtincmd *bcmd;
8921 smallint cmd_is_exec;
8922 smallint pseudovarflag = 0;
8924 /* First expand the arguments. */
8925 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8926 setstackmark(&smark);
8927 back_exitstatus = 0;
8929 cmdentry.cmdtype = CMDBUILTIN;
8930 cmdentry.u.cmd = &null_bltin;
8931 varlist.lastp = &varlist.list;
8932 *varlist.lastp = NULL;
8933 arglist.lastp = &arglist.list;
8934 *arglist.lastp = NULL;
8937 if (cmd->ncmd.args) {
8938 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8939 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8942 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8943 struct strlist **spp;
8945 spp = arglist.lastp;
8946 if (pseudovarflag && isassignment(argp->narg.text))
8947 expandarg(argp, &arglist, EXP_VARTILDE);
8949 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8951 for (sp = *spp; sp; sp = sp->next)
8955 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
8956 for (sp = arglist.list; sp; sp = sp->next) {
8957 TRACE(("evalcommand arg: %s\n", sp->text));
8958 *nargv++ = sp->text;
8963 if (iflag && funcnest == 0 && argc > 0)
8964 lastarg = nargv[-1];
8967 expredir(cmd->ncmd.redirect);
8968 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
8971 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
8972 struct strlist **spp;
8975 spp = varlist.lastp;
8976 expandarg(argp, &varlist, EXP_VARTILDE);
8979 * Modify the command lookup path, if a PATH= assignment
8983 if (varequal(p, path))
8987 /* Print the command if xflag is set. */
8990 const char *p = " %s";
8993 fdprintf(preverrout_fd, p, expandstr(ps4val()));
8996 for (n = 0; n < 2; n++) {
8998 fdprintf(preverrout_fd, p, sp->text);
9006 safe_write(preverrout_fd, "\n", 1);
9012 /* Now locate the command. */
9014 const char *oldpath;
9015 int cmd_flag = DO_ERR;
9020 find_command(argv[0], &cmdentry, cmd_flag, path);
9021 if (cmdentry.cmdtype == CMDUNKNOWN) {
9027 /* implement bltin and command here */
9028 if (cmdentry.cmdtype != CMDBUILTIN)
9031 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9032 if (cmdentry.u.cmd == EXECCMD)
9034 #if ENABLE_ASH_CMDCMD
9035 if (cmdentry.u.cmd == COMMANDCMD) {
9037 nargv = parse_command_args(argv, &path);
9040 argc -= nargv - argv;
9042 cmd_flag |= DO_NOFUNC;
9050 /* We have a redirection error. */
9052 raise_exception(EXERROR);
9054 exitstatus = status;
9058 /* Execute the command. */
9059 switch (cmdentry.cmdtype) {
9062 #if ENABLE_FEATURE_SH_NOFORK
9063 /* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9064 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
9066 /* find_command() encodes applet_no as (-2 - applet_no) */
9067 int applet_no = (- cmdentry.u.index - 2);
9068 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9069 listsetvar(varlist.list, VEXPORT|VSTACK);
9070 /* run <applet>_main() */
9071 exitstatus = run_nofork_applet(applet_no, argv);
9076 /* Fork off a child process if necessary. */
9077 if (!(flags & EV_EXIT) || trap[0]) {
9079 jp = makejob(/*cmd,*/ 1);
9080 if (forkshell(jp, cmd, FORK_FG) != 0) {
9081 exitstatus = waitforjob(jp);
9083 TRACE(("forked child exited with %d\n", exitstatus));
9088 listsetvar(varlist.list, VEXPORT|VSTACK);
9089 shellexec(argv, path, cmdentry.u.index);
9093 cmdenviron = varlist.list;
9095 struct strlist *list = cmdenviron;
9097 if (spclbltin > 0 || argc == 0) {
9099 if (cmd_is_exec && argc > 1)
9102 listsetvar(list, i);
9104 /* Tight loop with builtins only:
9105 * "while kill -0 $child; do true; done"
9106 * will never exit even if $child died, unless we do this
9107 * to reap the zombie and make kill detect that it's gone: */
9108 dowait(DOWAIT_NONBLOCK, NULL);
9110 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9112 int i = exception_type;
9117 exit_status = 128 + SIGINT;
9119 exit_status = 128 + pendingsig;
9120 exitstatus = exit_status;
9121 if (i == EXINT || spclbltin > 0) {
9123 longjmp(exception_handler->loc, 1);
9130 listsetvar(varlist.list, 0);
9131 /* See above for the rationale */
9132 dowait(DOWAIT_NONBLOCK, NULL);
9133 if (evalfun(cmdentry.u.func, argc, argv, flags))
9139 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9141 /* dsl: I think this is intended to be used to support
9142 * '_' in 'vi' command mode during line editing...
9143 * However I implemented that within libedit itself.
9145 setvar("_", lastarg, 0);
9147 popstackmark(&smark);
9151 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9153 char *volatile savecmdname;
9154 struct jmploc *volatile savehandler;
9155 struct jmploc jmploc;
9158 savecmdname = commandname;
9159 i = setjmp(jmploc.loc);
9162 savehandler = exception_handler;
9163 exception_handler = &jmploc;
9164 commandname = argv[0];
9166 optptr = NULL; /* initialize nextopt */
9167 exitstatus = (*cmd->builtin)(argc, argv);
9168 flush_stdout_stderr();
9170 exitstatus |= ferror(stdout);
9172 commandname = savecmdname;
9174 exception_handler = savehandler;
9180 goodname(const char *p)
9182 return !*endofname(p);
9187 * Search for a command. This is called before we fork so that the
9188 * location of the command will be available in the parent as well as
9189 * the child. The check for "goodname" is an overly conservative
9190 * check that the name will not be subject to expansion.
9193 prehash(union node *n)
9195 struct cmdentry entry;
9197 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9198 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9202 /* ============ Builtin commands
9204 * Builtin commands whose functions are closely tied to evaluation
9205 * are implemented here.
9209 * Handle break and continue commands. Break, continue, and return are
9210 * all handled by setting the evalskip flag. The evaluation routines
9211 * above all check this flag, and if it is set they start skipping
9212 * commands rather than executing them. The variable skipcount is
9213 * the number of loops to break/continue, or the number of function
9214 * levels to return. (The latter is always 1.) It should probably
9215 * be an error to break out of more loops than exist, but it isn't
9216 * in the standard shell so we don't make it one here.
9218 static int FAST_FUNC
9219 breakcmd(int argc UNUSED_PARAM, char **argv)
9221 int n = argv[1] ? number(argv[1]) : 1;
9224 ash_msg_and_raise_error(illnum, argv[1]);
9228 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9235 /* ============ input.c
9237 * This implements the input routines used by the parser.
9241 INPUT_PUSH_FILE = 1,
9242 INPUT_NOFILE_OK = 2,
9245 static smallint checkkwd;
9246 /* values of checkkwd variable */
9247 #define CHKALIAS 0x1
9252 * Push a string back onto the input at this current parsefile level.
9253 * We handle aliases this way.
9255 #if !ENABLE_ASH_ALIAS
9256 #define pushstring(s, ap) pushstring(s)
9259 pushstring(char *s, struct alias *ap)
9266 if (g_parsefile->strpush) {
9267 sp = ckzalloc(sizeof(*sp));
9268 sp->prev = g_parsefile->strpush;
9270 sp = &(g_parsefile->basestrpush);
9272 g_parsefile->strpush = sp;
9273 sp->prev_string = g_parsefile->next_to_pgetc;
9274 sp->prev_left_in_line = g_parsefile->left_in_line;
9275 #if ENABLE_ASH_ALIAS
9278 ap->flag |= ALIASINUSE;
9282 g_parsefile->next_to_pgetc = s;
9283 g_parsefile->left_in_line = len;
9290 struct strpush *sp = g_parsefile->strpush;
9293 #if ENABLE_ASH_ALIAS
9295 if (g_parsefile->next_to_pgetc[-1] == ' '
9296 || g_parsefile->next_to_pgetc[-1] == '\t'
9298 checkkwd |= CHKALIAS;
9300 if (sp->string != sp->ap->val) {
9303 sp->ap->flag &= ~ALIASINUSE;
9304 if (sp->ap->flag & ALIASDEAD) {
9305 unalias(sp->ap->name);
9309 g_parsefile->next_to_pgetc = sp->prev_string;
9310 g_parsefile->left_in_line = sp->prev_left_in_line;
9311 g_parsefile->strpush = sp->prev;
9312 if (sp != &(g_parsefile->basestrpush))
9317 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9318 //it peeks whether it is &>, and then pushes back both chars.
9319 //This function needs to save last *next_to_pgetc to buf[0]
9320 //to make two pungetc() reliable. Currently,
9321 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9326 char *buf = g_parsefile->buf;
9328 g_parsefile->next_to_pgetc = buf;
9329 #if ENABLE_FEATURE_EDITING
9331 if (!iflag || g_parsefile->fd != STDIN_FILENO)
9332 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9334 #if ENABLE_FEATURE_TAB_COMPLETION
9335 line_input_state->path_lookup = pathval();
9337 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9339 /* Ctrl+C pressed */
9348 if (nr < 0 && errno == 0) {
9349 /* Ctrl+D pressed */
9354 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9358 /* nonblock_safe_read() handles this problem */
9360 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9361 int flags = fcntl(0, F_GETFL);
9362 if (flags >= 0 && (flags & O_NONBLOCK)) {
9363 flags &= ~O_NONBLOCK;
9364 if (fcntl(0, F_SETFL, flags) >= 0) {
9365 out2str("sh: turning off NDELAY mode\n");
9376 * Refill the input buffer and return the next input character:
9378 * 1) If a string was pushed back on the input, pop it;
9379 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9380 * or we are reading from a string so we can't refill the buffer,
9382 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9383 * 4) Process input up to the next newline, deleting nul characters.
9385 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9386 #define pgetc_debug(...) ((void)0)
9388 * NB: due to SIT(c) internals (syntax_index_table[] vector),
9389 * pgetc() and related functions must return chars SIGN-EXTENDED into ints,
9390 * not zero-extended. Seems fragile to me. Affects only !USE_SIT_FUNCTION case,
9391 * so we can fix it by ditching !USE_SIT_FUNCTION if Unicode requires that.
9399 while (g_parsefile->strpush) {
9400 #if ENABLE_ASH_ALIAS
9401 if (g_parsefile->left_in_line == -1
9402 && g_parsefile->strpush->ap
9403 && g_parsefile->next_to_pgetc[-1] != ' '
9404 && g_parsefile->next_to_pgetc[-1] != '\t'
9406 pgetc_debug("preadbuffer PEOA");
9411 /* try "pgetc" now: */
9412 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9413 g_parsefile->left_in_line,
9414 g_parsefile->next_to_pgetc,
9415 g_parsefile->next_to_pgetc);
9416 if (--g_parsefile->left_in_line >= 0)
9417 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9419 /* on both branches above g_parsefile->left_in_line < 0.
9420 * "pgetc" needs refilling.
9423 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9424 * pungetc() may increment it a few times.
9425 * Assuming it won't increment it to less than -90.
9427 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9428 pgetc_debug("preadbuffer PEOF1");
9429 /* even in failure keep left_in_line and next_to_pgetc
9430 * in lock step, for correct multi-layer pungetc.
9431 * left_in_line was decremented before preadbuffer(),
9432 * must inc next_to_pgetc: */
9433 g_parsefile->next_to_pgetc++;
9437 more = g_parsefile->left_in_buffer;
9439 flush_stdout_stderr();
9443 /* don't try reading again */
9444 g_parsefile->left_in_line = -99;
9445 pgetc_debug("preadbuffer PEOF2");
9446 g_parsefile->next_to_pgetc++;
9451 /* Find out where's the end of line.
9452 * Set g_parsefile->left_in_line
9453 * and g_parsefile->left_in_buffer acordingly.
9454 * NUL chars are deleted.
9456 q = g_parsefile->next_to_pgetc;
9464 memmove(q, q + 1, more);
9468 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9474 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9475 if (g_parsefile->left_in_line < 0)
9480 g_parsefile->left_in_buffer = more;
9485 out2str(g_parsefile->next_to_pgetc);
9489 pgetc_debug("preadbuffer at %d:%p'%s'",
9490 g_parsefile->left_in_line,
9491 g_parsefile->next_to_pgetc,
9492 g_parsefile->next_to_pgetc);
9493 return signed_char2int(*g_parsefile->next_to_pgetc++);
9496 #define pgetc_as_macro() \
9497 (--g_parsefile->left_in_line >= 0 \
9498 ? signed_char2int(*g_parsefile->next_to_pgetc++) \
9505 pgetc_debug("pgetc_fast at %d:%p'%s'",
9506 g_parsefile->left_in_line,
9507 g_parsefile->next_to_pgetc,
9508 g_parsefile->next_to_pgetc);
9509 return pgetc_as_macro();
9512 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9513 #define pgetc_fast() pgetc()
9515 #define pgetc_fast() pgetc_as_macro()
9519 * Same as pgetc(), but ignores PEOA.
9521 #if ENABLE_ASH_ALIAS
9527 pgetc_debug("pgetc_fast at %d:%p'%s'",
9528 g_parsefile->left_in_line,
9529 g_parsefile->next_to_pgetc,
9530 g_parsefile->next_to_pgetc);
9532 } while (c == PEOA);
9536 #define pgetc2() pgetc()
9540 * Read a line from the script.
9543 pfgets(char *line, int len)
9549 while (--nleft > 0) {
9565 * Undo the last call to pgetc. Only one character may be pushed back.
9566 * PEOF may be pushed back.
9571 g_parsefile->left_in_line++;
9572 g_parsefile->next_to_pgetc--;
9573 pgetc_debug("pushed back to %d:%p'%s'",
9574 g_parsefile->left_in_line,
9575 g_parsefile->next_to_pgetc,
9576 g_parsefile->next_to_pgetc);
9580 * To handle the "." command, a stack of input files is used. Pushfile
9581 * adds a new entry to the stack and popfile restores the previous level.
9586 struct parsefile *pf;
9588 pf = ckzalloc(sizeof(*pf));
9589 pf->prev = g_parsefile;
9591 /*pf->strpush = NULL; - ckzalloc did it */
9592 /*pf->basestrpush.prev = NULL;*/
9599 struct parsefile *pf = g_parsefile;
9607 g_parsefile = pf->prev;
9613 * Return to top level.
9618 while (g_parsefile != &basepf)
9623 * Close the file(s) that the shell is reading commands from. Called
9624 * after a fork is done.
9630 if (g_parsefile->fd > 0) {
9631 close(g_parsefile->fd);
9632 g_parsefile->fd = 0;
9637 * Like setinputfile, but takes an open file descriptor. Call this with
9641 setinputfd(int fd, int push)
9643 close_on_exec_on(fd);
9646 g_parsefile->buf = NULL;
9648 g_parsefile->fd = fd;
9649 if (g_parsefile->buf == NULL)
9650 g_parsefile->buf = ckmalloc(IBUFSIZ);
9651 g_parsefile->left_in_buffer = 0;
9652 g_parsefile->left_in_line = 0;
9653 g_parsefile->linno = 1;
9657 * Set the input to take input from a file. If push is set, push the
9658 * old input onto the stack first.
9661 setinputfile(const char *fname, int flags)
9667 fd = open(fname, O_RDONLY);
9669 if (flags & INPUT_NOFILE_OK)
9671 ash_msg_and_raise_error("can't open '%s'", fname);
9674 fd2 = copyfd(fd, 10);
9677 ash_msg_and_raise_error("out of file descriptors");
9680 setinputfd(fd, flags & INPUT_PUSH_FILE);
9687 * Like setinputfile, but takes input from a string.
9690 setinputstring(char *string)
9694 g_parsefile->next_to_pgetc = string;
9695 g_parsefile->left_in_line = strlen(string);
9696 g_parsefile->buf = NULL;
9697 g_parsefile->linno = 1;
9702 /* ============ mail.c
9704 * Routines to check for mail.
9709 #define MAXMBOXES 10
9711 /* times of mailboxes */
9712 static time_t mailtime[MAXMBOXES];
9713 /* Set if MAIL or MAILPATH is changed. */
9714 static smallint mail_var_path_changed;
9717 * Print appropriate message(s) if mail has arrived.
9718 * If mail_var_path_changed is set,
9719 * then the value of MAIL has mail_var_path_changed,
9720 * so we just update the values.
9729 struct stackmark smark;
9732 setstackmark(&smark);
9733 mpath = mpathset() ? mpathval() : mailval();
9734 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9735 p = path_advance(&mpath, nullstr);
9740 for (q = p; *q; q++)
9746 q[-1] = '\0'; /* delete trailing '/' */
9747 if (stat(p, &statb) < 0) {
9751 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9754 pathopt ? pathopt : "you have mail"
9757 *mtp = statb.st_mtime;
9759 mail_var_path_changed = 0;
9760 popstackmark(&smark);
9763 static void FAST_FUNC
9764 changemail(const char *val UNUSED_PARAM)
9766 mail_var_path_changed = 1;
9769 #endif /* ASH_MAIL */
9772 /* ============ ??? */
9775 * Set the shell parameters.
9778 setparam(char **argv)
9784 for (nparam = 0; argv[nparam]; nparam++)
9786 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9788 *ap++ = ckstrdup(*argv++);
9791 freeparam(&shellparam);
9792 shellparam.malloced = 1;
9793 shellparam.nparam = nparam;
9794 shellparam.p = newparam;
9795 #if ENABLE_ASH_GETOPTS
9796 shellparam.optind = 1;
9797 shellparam.optoff = -1;
9802 * Process shell options. The global variable argptr contains a pointer
9803 * to the argument list; we advance it past the options.
9805 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9806 * For a non-interactive shell, an error condition encountered
9807 * by a special built-in ... shall cause the shell to write a diagnostic message
9808 * to standard error and exit as shown in the following table:
9809 * Error Special Built-In
9811 * Utility syntax error (option or operand error) Shall exit
9813 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9814 * we see that bash does not do that (set "finishes" with error code 1 instead,
9815 * and shell continues), and people rely on this behavior!
9817 * set -o barfoo 2>/dev/null
9820 * Oh well. Let's mimic that.
9823 plus_minus_o(char *name, int val)
9828 for (i = 0; i < NOPTS; i++) {
9829 if (strcmp(name, optnames(i)) == 0) {
9834 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9837 for (i = 0; i < NOPTS; i++) {
9839 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9841 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9847 setoption(int flag, int val)
9851 for (i = 0; i < NOPTS; i++) {
9852 if (optletters(i) == flag) {
9857 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9861 options(int cmdline)
9869 while ((p = *argptr) != NULL) {
9871 if (c != '-' && c != '+')
9874 val = 0; /* val = 0 if c == '+' */
9877 if (p[0] == '\0' || LONE_DASH(p)) {
9879 /* "-" means turn off -x and -v */
9882 /* "--" means reset params */
9883 else if (*argptr == NULL)
9886 break; /* "-" or "--" terminates options */
9889 /* first char was + or - */
9890 while ((c = *p++) != '\0') {
9891 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9892 if (c == 'c' && cmdline) {
9893 minusc = p; /* command is after shell args */
9894 } else if (c == 'o') {
9895 if (plus_minus_o(*argptr, val)) {
9896 /* it already printed err message */
9897 return 1; /* error */
9901 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9903 /* bash does not accept +-login, we also won't */
9904 } else if (cmdline && val && (c == '-')) { /* long options */
9905 if (strcmp(p, "login") == 0)
9917 * The shift builtin command.
9919 static int FAST_FUNC
9920 shiftcmd(int argc UNUSED_PARAM, char **argv)
9927 n = number(argv[1]);
9928 if (n > shellparam.nparam)
9929 n = 0; /* bash compat, was = shellparam.nparam; */
9931 shellparam.nparam -= n;
9932 for (ap1 = shellparam.p; --n >= 0; ap1++) {
9933 if (shellparam.malloced)
9937 while ((*ap2++ = *ap1++) != NULL)
9939 #if ENABLE_ASH_GETOPTS
9940 shellparam.optind = 1;
9941 shellparam.optoff = -1;
9948 * POSIX requires that 'set' (but not export or readonly) output the
9949 * variables in lexicographic order - by the locale's collating order (sigh).
9950 * Maybe we could keep them in an ordered balanced binary tree
9951 * instead of hashed lists.
9952 * For now just roll 'em through qsort for printing...
9955 showvars(const char *sep_prefix, int on, int off)
9960 ep = listvars(on, off, &epend);
9961 qsort(ep, epend - ep, sizeof(char *), vpcmp);
9963 sep = *sep_prefix ? " " : sep_prefix;
9965 for (; ep < epend; ep++) {
9969 p = strchrnul(*ep, '=');
9972 q = single_quote(++p);
9973 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
9979 * The set command builtin.
9981 static int FAST_FUNC
9982 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9987 return showvars(nullstr, 0, VUNSET);
9990 if (!options(0)) { /* if no parse error... */
9993 if (*argptr != NULL) {
10001 #if ENABLE_ASH_RANDOM_SUPPORT
10002 static void FAST_FUNC
10003 change_random(const char *value)
10005 /* Galois LFSR parameter */
10006 /* Taps at 32 31 29 1: */
10007 enum { MASK = 0x8000000b };
10008 /* Another example - taps at 32 31 30 10: */
10009 /* MASK = 0x00400007 */
10011 if (value == NULL) {
10012 /* "get", generate */
10015 /* LCG has period of 2^32 and alternating lowest bit */
10016 random_LCG = 1664525 * random_LCG + 1013904223;
10017 /* Galois LFSR has period of 2^32-1 = 3 * 5 * 17 * 257 * 65537 */
10018 t = (random_galois_LFSR << 1);
10019 if (random_galois_LFSR < 0) /* if we just shifted 1 out of msb... */
10021 random_galois_LFSR = t;
10022 /* Both are weak, combining them gives better randomness
10023 * and ~2^64 period. & 0x7fff is probably bash compat
10024 * for $RANDOM range. Combining with subtraction is
10025 * just for fun. + and ^ would work equally well. */
10026 t = (t - random_LCG) & 0x7fff;
10027 /* set without recursion */
10028 setvar(vrandom.text, utoa(t), VNOFUNC);
10029 vrandom.flags &= ~VNOFUNC;
10032 random_galois_LFSR = random_LCG = strtoul(value, (char **)NULL, 10);
10037 #if ENABLE_ASH_GETOPTS
10039 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10048 if (*param_optind < 1)
10050 optnext = optfirst + *param_optind - 1;
10052 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10055 p = optnext[-1] + *optoff;
10056 if (p == NULL || *p == '\0') {
10057 /* Current word is done, advance */
10059 if (p == NULL || *p != '-' || *++p == '\0') {
10066 if (LONE_DASH(p)) /* check for "--" */
10071 for (q = optstr; *q != c;) {
10073 if (optstr[0] == ':') {
10076 err |= setvarsafe("OPTARG", s, 0);
10078 fprintf(stderr, "Illegal option -%c\n", c);
10079 unsetvar("OPTARG");
10089 if (*p == '\0' && (p = *optnext) == NULL) {
10090 if (optstr[0] == ':') {
10093 err |= setvarsafe("OPTARG", s, 0);
10096 fprintf(stderr, "No arg for -%c option\n", c);
10097 unsetvar("OPTARG");
10105 err |= setvarsafe("OPTARG", p, 0);
10108 err |= setvarsafe("OPTARG", nullstr, 0);
10110 *optoff = p ? p - *(optnext - 1) : -1;
10111 *param_optind = optnext - optfirst + 1;
10112 fmtstr(s, sizeof(s), "%d", *param_optind);
10113 err |= setvarsafe("OPTIND", s, VNOFUNC);
10116 err |= setvarsafe(optvar, s, 0);
10120 flush_stdout_stderr();
10121 raise_exception(EXERROR);
10127 * The getopts builtin. Shellparam.optnext points to the next argument
10128 * to be processed. Shellparam.optptr points to the next character to
10129 * be processed in the current argument. If shellparam.optnext is NULL,
10130 * then it's the first time getopts has been called.
10132 static int FAST_FUNC
10133 getoptscmd(int argc, char **argv)
10138 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10140 optbase = shellparam.p;
10141 if (shellparam.optind > shellparam.nparam + 1) {
10142 shellparam.optind = 1;
10143 shellparam.optoff = -1;
10146 optbase = &argv[3];
10147 if (shellparam.optind > argc - 2) {
10148 shellparam.optind = 1;
10149 shellparam.optoff = -1;
10153 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10154 &shellparam.optoff);
10156 #endif /* ASH_GETOPTS */
10159 /* ============ Shell parser */
10162 struct heredoc *next; /* next here document in list */
10163 union node *here; /* redirection node */
10164 char *eofmark; /* string indicating end of input */
10165 smallint striptabs; /* if set, strip leading tabs */
10168 static smallint tokpushback; /* last token pushed back */
10169 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10170 static smallint quoteflag; /* set if (part of) last token was quoted */
10171 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10172 static struct heredoc *heredoclist; /* list of here documents to read */
10173 static char *wordtext; /* text of last word returned by readtoken */
10174 static struct nodelist *backquotelist;
10175 static union node *redirnode;
10176 static struct heredoc *heredoc;
10179 * Called when an unexpected token is read during the parse. The argument
10180 * is the token that is expected, or -1 if more than one type of token can
10181 * occur at this point.
10183 static void raise_error_unexpected_syntax(int) NORETURN;
10185 raise_error_unexpected_syntax(int token)
10190 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
10192 sprintf(msg + l, " (expecting %s)", tokname(token));
10193 raise_error_syntax(msg);
10197 #define EOFMARKLEN 79
10199 /* parsing is heavily cross-recursive, need these forward decls */
10200 static union node *andor(void);
10201 static union node *pipeline(void);
10202 static union node *parse_command(void);
10203 static void parseheredoc(void);
10204 static char peektoken(void);
10205 static int readtoken(void);
10207 static union node *
10210 union node *n1, *n2, *n3;
10213 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10214 if (nlflag == 2 && peektoken())
10220 if (tok == TBACKGND) {
10221 if (n2->type == NPIPE) {
10222 n2->npipe.pipe_backgnd = 1;
10224 if (n2->type != NREDIR) {
10225 n3 = stzalloc(sizeof(struct nredir));
10227 /*n3->nredir.redirect = NULL; - stzalloc did it */
10230 n2->type = NBACKGND;
10236 n3 = stzalloc(sizeof(struct nbinary));
10238 n3->nbinary.ch1 = n1;
10239 n3->nbinary.ch2 = n2;
10255 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10263 pungetc(); /* push back EOF on input */
10267 raise_error_unexpected_syntax(-1);
10274 static union node *
10277 union node *n1, *n2, *n3;
10285 } else if (t == TOR) {
10291 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10293 n3 = stzalloc(sizeof(struct nbinary));
10295 n3->nbinary.ch1 = n1;
10296 n3->nbinary.ch2 = n2;
10301 static union node *
10304 union node *n1, *n2, *pipenode;
10305 struct nodelist *lp, *prev;
10309 TRACE(("pipeline: entered\n"));
10310 if (readtoken() == TNOT) {
10312 checkkwd = CHKKWD | CHKALIAS;
10315 n1 = parse_command();
10316 if (readtoken() == TPIPE) {
10317 pipenode = stzalloc(sizeof(struct npipe));
10318 pipenode->type = NPIPE;
10319 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10320 lp = stzalloc(sizeof(struct nodelist));
10321 pipenode->npipe.cmdlist = lp;
10325 lp = stzalloc(sizeof(struct nodelist));
10326 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10327 lp->n = parse_command();
10329 } while (readtoken() == TPIPE);
10335 n2 = stzalloc(sizeof(struct nnot));
10343 static union node *
10348 n = stzalloc(sizeof(struct narg));
10350 /*n->narg.next = NULL; - stzalloc did it */
10351 n->narg.text = wordtext;
10352 n->narg.backquote = backquotelist;
10357 fixredir(union node *n, const char *text, int err)
10361 TRACE(("Fix redir %s %d\n", text, err));
10363 n->ndup.vname = NULL;
10365 fd = bb_strtou(text, NULL, 10);
10366 if (!errno && fd >= 0)
10367 n->ndup.dupfd = fd;
10368 else if (LONE_DASH(text))
10369 n->ndup.dupfd = -1;
10372 raise_error_syntax("bad fd number");
10373 n->ndup.vname = makename();
10378 * Returns true if the text contains nothing to expand (no dollar signs
10382 noexpand(const char *text)
10388 while ((c = *p++) != '\0') {
10389 if (c == CTLQUOTEMARK)
10393 else if (SIT((signed char)c, BASESYNTAX) == CCTL)
10402 union node *n = redirnode;
10404 if (readtoken() != TWORD)
10405 raise_error_unexpected_syntax(-1);
10406 if (n->type == NHERE) {
10407 struct heredoc *here = heredoc;
10411 if (quoteflag == 0)
10413 TRACE(("Here document %d\n", n->type));
10414 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10415 raise_error_syntax("illegal eof marker for << redirection");
10416 rmescapes(wordtext, 0);
10417 here->eofmark = wordtext;
10419 if (heredoclist == NULL)
10420 heredoclist = here;
10422 for (p = heredoclist; p->next; p = p->next)
10426 } else if (n->type == NTOFD || n->type == NFROMFD) {
10427 fixredir(n, wordtext, 0);
10429 n->nfile.fname = makename();
10433 static union node *
10436 union node *args, **app;
10437 union node *n = NULL;
10438 union node *vars, **vpp;
10439 union node **rpp, *redir;
10441 #if ENABLE_ASH_BASH_COMPAT
10442 smallint double_brackets_flag = 0;
10452 savecheckkwd = CHKALIAS;
10455 checkkwd = savecheckkwd;
10458 #if ENABLE_ASH_BASH_COMPAT
10459 case TAND: /* "&&" */
10460 case TOR: /* "||" */
10461 if (!double_brackets_flag) {
10465 wordtext = (char *) (t == TAND ? "-a" : "-o");
10468 n = stzalloc(sizeof(struct narg));
10470 /*n->narg.next = NULL; - stzalloc did it */
10471 n->narg.text = wordtext;
10472 #if ENABLE_ASH_BASH_COMPAT
10473 if (strcmp("[[", wordtext) == 0)
10474 double_brackets_flag = 1;
10475 else if (strcmp("]]", wordtext) == 0)
10476 double_brackets_flag = 0;
10478 n->narg.backquote = backquotelist;
10479 if (savecheckkwd && isassignment(wordtext)) {
10481 vpp = &n->narg.next;
10484 app = &n->narg.next;
10489 *rpp = n = redirnode;
10490 rpp = &n->nfile.next;
10491 parsefname(); /* read name of redirection file */
10494 if (args && app == &args->narg.next
10497 struct builtincmd *bcmd;
10500 /* We have a function */
10501 if (readtoken() != TRP)
10502 raise_error_unexpected_syntax(TRP);
10503 name = n->narg.text;
10504 if (!goodname(name)
10505 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10507 raise_error_syntax("bad function name");
10510 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10511 n->narg.next = parse_command();
10524 n = stzalloc(sizeof(struct ncmd));
10526 n->ncmd.args = args;
10527 n->ncmd.assign = vars;
10528 n->ncmd.redirect = redir;
10532 static union node *
10533 parse_command(void)
10535 union node *n1, *n2;
10536 union node *ap, **app;
10537 union node *cp, **cpp;
10538 union node *redir, **rpp;
10545 switch (readtoken()) {
10547 raise_error_unexpected_syntax(-1);
10550 n1 = stzalloc(sizeof(struct nif));
10552 n1->nif.test = list(0);
10553 if (readtoken() != TTHEN)
10554 raise_error_unexpected_syntax(TTHEN);
10555 n1->nif.ifpart = list(0);
10557 while (readtoken() == TELIF) {
10558 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10559 n2 = n2->nif.elsepart;
10561 n2->nif.test = list(0);
10562 if (readtoken() != TTHEN)
10563 raise_error_unexpected_syntax(TTHEN);
10564 n2->nif.ifpart = list(0);
10566 if (lasttoken == TELSE)
10567 n2->nif.elsepart = list(0);
10569 n2->nif.elsepart = NULL;
10577 n1 = stzalloc(sizeof(struct nbinary));
10578 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10579 n1->nbinary.ch1 = list(0);
10582 TRACE(("expecting DO got %s %s\n", tokname(got),
10583 got == TWORD ? wordtext : ""));
10584 raise_error_unexpected_syntax(TDO);
10586 n1->nbinary.ch2 = list(0);
10591 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10592 raise_error_syntax("bad for loop variable");
10593 n1 = stzalloc(sizeof(struct nfor));
10595 n1->nfor.var = wordtext;
10596 checkkwd = CHKKWD | CHKALIAS;
10597 if (readtoken() == TIN) {
10599 while (readtoken() == TWORD) {
10600 n2 = stzalloc(sizeof(struct narg));
10602 /*n2->narg.next = NULL; - stzalloc did it */
10603 n2->narg.text = wordtext;
10604 n2->narg.backquote = backquotelist;
10606 app = &n2->narg.next;
10609 n1->nfor.args = ap;
10610 if (lasttoken != TNL && lasttoken != TSEMI)
10611 raise_error_unexpected_syntax(-1);
10613 n2 = stzalloc(sizeof(struct narg));
10615 /*n2->narg.next = NULL; - stzalloc did it */
10616 n2->narg.text = (char *)dolatstr;
10617 /*n2->narg.backquote = NULL;*/
10618 n1->nfor.args = n2;
10620 * Newline or semicolon here is optional (but note
10621 * that the original Bourne shell only allowed NL).
10623 if (lasttoken != TNL && lasttoken != TSEMI)
10626 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10627 if (readtoken() != TDO)
10628 raise_error_unexpected_syntax(TDO);
10629 n1->nfor.body = list(0);
10633 n1 = stzalloc(sizeof(struct ncase));
10635 if (readtoken() != TWORD)
10636 raise_error_unexpected_syntax(TWORD);
10637 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10639 /*n2->narg.next = NULL; - stzalloc did it */
10640 n2->narg.text = wordtext;
10641 n2->narg.backquote = backquotelist;
10643 checkkwd = CHKKWD | CHKALIAS;
10644 } while (readtoken() == TNL);
10645 if (lasttoken != TIN)
10646 raise_error_unexpected_syntax(TIN);
10647 cpp = &n1->ncase.cases;
10649 checkkwd = CHKNL | CHKKWD;
10651 while (t != TESAC) {
10652 if (lasttoken == TLP)
10654 *cpp = cp = stzalloc(sizeof(struct nclist));
10656 app = &cp->nclist.pattern;
10658 *app = ap = stzalloc(sizeof(struct narg));
10660 /*ap->narg.next = NULL; - stzalloc did it */
10661 ap->narg.text = wordtext;
10662 ap->narg.backquote = backquotelist;
10663 if (readtoken() != TPIPE)
10665 app = &ap->narg.next;
10668 //ap->narg.next = NULL;
10669 if (lasttoken != TRP)
10670 raise_error_unexpected_syntax(TRP);
10671 cp->nclist.body = list(2);
10673 cpp = &cp->nclist.next;
10675 checkkwd = CHKNL | CHKKWD;
10679 raise_error_unexpected_syntax(TENDCASE);
10686 n1 = stzalloc(sizeof(struct nredir));
10687 n1->type = NSUBSHELL;
10688 n1->nredir.n = list(0);
10689 /*n1->nredir.redirect = NULL; - stzalloc did it */
10699 return simplecmd();
10702 if (readtoken() != t)
10703 raise_error_unexpected_syntax(t);
10706 /* Now check for redirection which may follow command */
10707 checkkwd = CHKKWD | CHKALIAS;
10709 while (readtoken() == TREDIR) {
10710 *rpp = n2 = redirnode;
10711 rpp = &n2->nfile.next;
10717 if (n1->type != NSUBSHELL) {
10718 n2 = stzalloc(sizeof(struct nredir));
10723 n1->nredir.redirect = redir;
10728 #if ENABLE_ASH_BASH_COMPAT
10729 static int decode_dollar_squote(void)
10731 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10737 p = strchr(C_escapes, c);
10742 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10746 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10748 } else if (c == 'x') { /* \xHH */
10752 } while (isxdigit(c) && --cnt);
10754 if (cnt == 3) { /* \x but next char is "bad" */
10758 } else { /* simple seq like \\ or \t */
10763 c = bb_process_escape_sequence((void*)&p);
10764 } else { /* unrecognized "\z": print both chars unless ' or " */
10765 if (c != '\'' && c != '"') {
10767 c |= 0x100; /* "please encode \, then me" */
10775 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10776 * is not NULL, read a here document. In the latter case, eofmark is the
10777 * word which marks the end of the document and striptabs is true if
10778 * leading tabs should be stripped from the document. The argument firstc
10779 * is the first character of the input token or document.
10781 * Because C does not have internal subroutines, I have simulated them
10782 * using goto's to implement the subroutine linkage. The following macros
10783 * will run code that appears at the end of readtoken1.
10785 #define CHECKEND() {goto checkend; checkend_return:;}
10786 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10787 #define PARSESUB() {goto parsesub; parsesub_return:;}
10788 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10789 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10790 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10792 readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
10794 /* NB: syntax parameter fits into smallint */
10798 char line[EOFMARKLEN + 1];
10799 struct nodelist *bqlist;
10803 smallint prevsyntax; /* syntax before arithmetic */
10804 #if ENABLE_ASH_EXPAND_PRMT
10805 smallint pssyntax; /* we are expanding a prompt string */
10807 int varnest; /* levels of variables expansion */
10808 int arinest; /* levels of arithmetic expansion */
10809 int parenlevel; /* levels of parens in arithmetic */
10810 int dqvarnest; /* levels of variables expansion within double quotes */
10812 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10815 /* Avoid longjmp clobbering */
10821 (void) &parenlevel;
10824 (void) &prevsyntax;
10827 startlinno = g_parsefile->linno;
10832 #if ENABLE_ASH_EXPAND_PRMT
10833 pssyntax = (syntax == PSSYNTAX);
10837 dblquote = (syntax == DQSYNTAX);
10843 STARTSTACKSTR(out);
10845 /* For each line, until end of word */
10847 CHECKEND(); /* set c to PEOF if at end of here document */
10848 for (;;) { /* until end of line or end of word */
10849 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10850 switch (SIT(c, syntax)) {
10851 case CNL: /* '\n' */
10852 if (syntax == BASESYNTAX)
10853 goto endword; /* exit outer loop */
10855 g_parsefile->linno++;
10859 goto loop; /* continue outer loop */
10864 if (eofmark == NULL || dblquote)
10865 USTPUTC(CTLESC, out);
10866 #if ENABLE_ASH_BASH_COMPAT
10867 if (c == '\\' && bash_dollar_squote) {
10868 c = decode_dollar_squote();
10870 USTPUTC('\\', out);
10871 c = (unsigned char)c;
10877 case CBACK: /* backslash */
10880 USTPUTC(CTLESC, out);
10881 USTPUTC('\\', out);
10883 } else if (c == '\n') {
10887 #if ENABLE_ASH_EXPAND_PRMT
10888 if (c == '$' && pssyntax) {
10889 USTPUTC(CTLESC, out);
10890 USTPUTC('\\', out);
10893 if (dblquote && c != '\\'
10894 && c != '`' && c != '$'
10895 && (c != '"' || eofmark != NULL)
10897 USTPUTC(CTLESC, out);
10898 USTPUTC('\\', out);
10900 if (SIT(c, SQSYNTAX) == CCTL)
10901 USTPUTC(CTLESC, out);
10909 if (eofmark == NULL) {
10910 USTPUTC(CTLQUOTEMARK, out);
10918 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
10919 if (eofmark != NULL && arinest == 0
10924 if (dqvarnest == 0) {
10925 syntax = BASESYNTAX;
10932 case CVAR: /* '$' */
10933 PARSESUB(); /* parse substitution */
10935 case CENDVAR: /* '}' */
10938 if (dqvarnest > 0) {
10941 USTPUTC(CTLENDVAR, out);
10946 #if ENABLE_SH_MATH_SUPPORT
10947 case CLP: /* '(' in arithmetic */
10951 case CRP: /* ')' in arithmetic */
10952 if (parenlevel > 0) {
10956 if (pgetc() == ')') {
10957 if (--arinest == 0) {
10958 USTPUTC(CTLENDARI, out);
10959 syntax = prevsyntax;
10960 dblquote = (syntax == DQSYNTAX);
10965 * unbalanced parens
10966 * (don't 2nd guess - no error)
10974 case CBQUOTE: /* '`' */
10978 goto endword; /* exit outer loop */
10982 if (varnest == 0) {
10983 #if ENABLE_ASH_BASH_COMPAT
10985 if (pgetc() == '>')
10986 c = 0x100 + '>'; /* flag &> */
10990 goto endword; /* exit outer loop */
10992 #if ENABLE_ASH_ALIAS
11002 #if ENABLE_SH_MATH_SUPPORT
11003 if (syntax == ARISYNTAX)
11004 raise_error_syntax("missing '))'");
11006 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11007 raise_error_syntax("unterminated quoted string");
11008 if (varnest != 0) {
11009 startlinno = g_parsefile->linno;
11011 raise_error_syntax("missing '}'");
11013 USTPUTC('\0', out);
11014 len = out - (char *)stackblock();
11015 out = stackblock();
11016 if (eofmark == NULL) {
11017 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11020 if (isdigit_str9(out)) {
11021 PARSEREDIR(); /* passed as params: out, c */
11022 lasttoken = TREDIR;
11025 /* else: non-number X seen, interpret it
11026 * as "NNNX>file" = "NNNX >file" */
11030 quoteflag = quotef;
11031 backquotelist = bqlist;
11032 grabstackblock(len);
11036 /* end of readtoken routine */
11039 * Check to see whether we are at the end of the here document. When this
11040 * is called, c is set to the first character of the next input line. If
11041 * we are at the end of the here document, this routine sets the c to PEOF.
11045 #if ENABLE_ASH_ALIAS
11051 while (c == '\t') {
11055 if (c == *eofmark) {
11056 if (pfgets(line, sizeof(line)) != NULL) {
11060 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11062 if (*p == '\n' && *q == '\0') {
11064 g_parsefile->linno++;
11065 needprompt = doprompt;
11067 pushstring(line, NULL);
11072 goto checkend_return;
11076 * Parse a redirection operator. The variable "out" points to a string
11077 * specifying the fd to be redirected. The variable "c" contains the
11078 * first character of the redirection operator.
11081 /* out is already checked to be a valid number or "" */
11082 int fd = (*out == '\0' ? -1 : atoi(out));
11085 np = stzalloc(sizeof(struct nfile));
11090 np->type = NAPPEND;
11092 np->type = NCLOBBER;
11095 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11101 #if ENABLE_ASH_BASH_COMPAT
11102 else if (c == 0x100 + '>') { /* this flags &> redirection */
11104 pgetc(); /* this is '>', no need to check */
11108 else { /* c == '<' */
11109 /*np->nfile.fd = 0; - stzalloc did it */
11113 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11114 np = stzalloc(sizeof(struct nhere));
11115 /*np->nfile.fd = 0; - stzalloc did it */
11118 heredoc = stzalloc(sizeof(struct heredoc));
11119 heredoc->here = np;
11122 heredoc->striptabs = 1;
11124 /*heredoc->striptabs = 0; - stzalloc did it */
11130 np->type = NFROMFD;
11134 np->type = NFROMTO;
11146 goto parseredir_return;
11150 * Parse a substitution. At this point, we have read the dollar sign
11151 * and nothing else.
11154 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11155 * (assuming ascii char codes, as the original implementation did) */
11156 #define is_special(c) \
11157 (((unsigned)(c) - 33 < 32) \
11158 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11164 static const char types[] ALIGN1 = "}-+?=";
11167 if (c <= PEOA_OR_PEOF
11168 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11170 #if ENABLE_ASH_BASH_COMPAT
11172 bash_dollar_squote = 1;
11177 } else if (c == '(') { /* $(command) or $((arith)) */
11178 if (pgetc() == '(') {
11179 #if ENABLE_SH_MATH_SUPPORT
11182 raise_error_syntax("you disabled math support for $((arith)) syntax");
11189 USTPUTC(CTLVAR, out);
11190 typeloc = out - (char *)stackblock();
11191 USTPUTC(VSNORMAL, out);
11192 subtype = VSNORMAL;
11200 subtype = VSLENGTH;
11204 if (c > PEOA_OR_PEOF && is_name(c)) {
11208 } while (c > PEOA_OR_PEOF && is_in_name(c));
11209 } else if (isdigit(c)) {
11213 } while (isdigit(c));
11214 } else if (is_special(c)) {
11219 raise_error_syntax("bad substitution");
11224 if (subtype == 0) {
11228 #if ENABLE_ASH_BASH_COMPAT
11229 if (c == ':' || c == '$' || isdigit(c)) {
11231 subtype = VSSUBSTR;
11238 p = strchr(types, c);
11241 subtype = p - types + VSNORMAL;
11246 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11254 #if ENABLE_ASH_BASH_COMPAT
11256 subtype = VSREPLACE;
11259 subtype++; /* VSREPLACEALL */
11268 if (dblquote || arinest)
11270 *((char *)stackblock() + typeloc) = subtype | flags;
11271 if (subtype != VSNORMAL) {
11273 if (dblquote || arinest) {
11278 goto parsesub_return;
11282 * Called to parse command substitutions. Newstyle is set if the command
11283 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11284 * list of commands (passed by reference), and savelen is the number of
11285 * characters on the top of the stack which must be preserved.
11288 struct nodelist **nlpp;
11291 char *volatile str;
11292 struct jmploc jmploc;
11293 struct jmploc *volatile savehandler;
11295 smallint saveprompt = 0;
11298 (void) &saveprompt;
11300 savepbq = parsebackquote;
11301 if (setjmp(jmploc.loc)) {
11303 parsebackquote = 0;
11304 exception_handler = savehandler;
11305 longjmp(exception_handler->loc, 1);
11309 savelen = out - (char *)stackblock();
11311 str = ckmalloc(savelen);
11312 memcpy(str, stackblock(), savelen);
11314 savehandler = exception_handler;
11315 exception_handler = &jmploc;
11318 /* We must read until the closing backquote, giving special
11319 treatment to some slashes, and then push the string and
11320 reread it as input, interpreting it normally. */
11327 STARTSTACKSTR(pout);
11340 g_parsefile->linno++;
11344 * If eating a newline, avoid putting
11345 * the newline into the new character
11346 * stream (via the STPUTC after the
11351 if (pc != '\\' && pc != '`' && pc != '$'
11352 && (!dblquote || pc != '"'))
11353 STPUTC('\\', pout);
11354 if (pc > PEOA_OR_PEOF) {
11360 #if ENABLE_ASH_ALIAS
11363 startlinno = g_parsefile->linno;
11364 raise_error_syntax("EOF in backquote substitution");
11367 g_parsefile->linno++;
11368 needprompt = doprompt;
11377 STPUTC('\0', pout);
11378 psavelen = pout - (char *)stackblock();
11379 if (psavelen > 0) {
11380 pstr = grabstackstr(pout);
11381 setinputstring(pstr);
11386 nlpp = &(*nlpp)->next;
11387 *nlpp = stzalloc(sizeof(**nlpp));
11388 /* (*nlpp)->next = NULL; - stzalloc did it */
11389 parsebackquote = oldstyle;
11392 saveprompt = doprompt;
11399 doprompt = saveprompt;
11400 else if (readtoken() != TRP)
11401 raise_error_unexpected_syntax(TRP);
11406 * Start reading from old file again, ignoring any pushed back
11407 * tokens left from the backquote parsing
11412 while (stackblocksize() <= savelen)
11414 STARTSTACKSTR(out);
11416 memcpy(out, str, savelen);
11417 STADJUST(savelen, out);
11423 parsebackquote = savepbq;
11424 exception_handler = savehandler;
11425 if (arinest || dblquote)
11426 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11428 USTPUTC(CTLBACKQ, out);
11430 goto parsebackq_oldreturn;
11431 goto parsebackq_newreturn;
11434 #if ENABLE_SH_MATH_SUPPORT
11436 * Parse an arithmetic expansion (indicate start of one and set state)
11439 if (++arinest == 1) {
11440 prevsyntax = syntax;
11441 syntax = ARISYNTAX;
11442 USTPUTC(CTLARI, out);
11449 * we collapse embedded arithmetic expansion to
11450 * parenthesis, which should be equivalent
11454 goto parsearith_return;
11458 } /* end of readtoken */
11461 * Read the next input token.
11462 * If the token is a word, we set backquotelist to the list of cmds in
11463 * backquotes. We set quoteflag to true if any part of the word was
11465 * If the token is TREDIR, then we set redirnode to a structure containing
11467 * In all cases, the variable startlinno is set to the number of the line
11468 * on which the token starts.
11470 * [Change comment: here documents and internal procedures]
11471 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11472 * word parsing code into a separate routine. In this case, readtoken
11473 * doesn't need to have any internal procedures, but parseword does.
11474 * We could also make parseoperator in essence the main routine, and
11475 * have parseword (readtoken1?) handle both words and redirection.]
11477 #define NEW_xxreadtoken
11478 #ifdef NEW_xxreadtoken
11479 /* singles must be first! */
11480 static const char xxreadtoken_chars[7] ALIGN1 = {
11481 '\n', '(', ')', /* singles */
11482 '&', '|', ';', /* doubles */
11486 #define xxreadtoken_singles 3
11487 #define xxreadtoken_doubles 3
11489 static const char xxreadtoken_tokens[] ALIGN1 = {
11490 TNL, TLP, TRP, /* only single occurrence allowed */
11491 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11492 TEOF, /* corresponds to trailing nul */
11493 TAND, TOR, TENDCASE /* if double occurrence */
11508 startlinno = g_parsefile->linno;
11509 for (;;) { /* until token or start of word found */
11511 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11515 while ((c = pgetc()) != '\n' && c != PEOF)
11518 } else if (c == '\\') {
11519 if (pgetc() != '\n') {
11521 break; /* return readtoken1(...) */
11523 startlinno = ++g_parsefile->linno;
11529 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11532 g_parsefile->linno++;
11533 needprompt = doprompt;
11536 p = strchr(xxreadtoken_chars, c);
11538 break; /* return readtoken1(...) */
11540 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11542 if (cc == c) { /* double occurrence? */
11543 p += xxreadtoken_doubles + 1;
11546 #if ENABLE_ASH_BASH_COMPAT
11547 if (c == '&' && cc == '>') /* &> */
11548 break; /* return readtoken1(...) */
11553 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11558 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11560 #else /* old xxreadtoken */
11561 #define RETURN(token) return lasttoken = token
11574 startlinno = g_parsefile->linno;
11575 for (;;) { /* until token or start of word found */
11578 case ' ': case '\t':
11579 #if ENABLE_ASH_ALIAS
11584 while ((c = pgetc()) != '\n' && c != PEOF)
11589 if (pgetc() == '\n') {
11590 startlinno = ++g_parsefile->linno;
11598 g_parsefile->linno++;
11599 needprompt = doprompt;
11604 if (pgetc() == '&')
11609 if (pgetc() == '|')
11614 if (pgetc() == ';')
11627 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11630 #endif /* old xxreadtoken */
11637 smallint alreadyseen = tokpushback;
11640 #if ENABLE_ASH_ALIAS
11649 if (checkkwd & CHKNL) {
11656 if (t != TWORD || quoteflag) {
11661 * check for keywords
11663 if (checkkwd & CHKKWD) {
11664 const char *const *pp;
11666 pp = findkwd(wordtext);
11668 lasttoken = t = pp - tokname_array;
11669 TRACE(("keyword %s recognized\n", tokname(t)));
11674 if (checkkwd & CHKALIAS) {
11675 #if ENABLE_ASH_ALIAS
11677 ap = lookupalias(wordtext, 1);
11680 pushstring(ap->val, ap);
11690 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11692 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11704 return tokname_array[t][0];
11708 * Read and parse a command. Returns NODE_EOF on end of file.
11709 * (NULL is a valid parse tree indicating a blank line.)
11711 static union node *
11712 parsecmd(int interact)
11717 doprompt = interact;
11719 setprompt(doprompt);
11731 * Input any here documents.
11736 struct heredoc *here;
11739 here = heredoclist;
11740 heredoclist = NULL;
11746 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11747 here->eofmark, here->striptabs);
11748 n = stzalloc(sizeof(struct narg));
11749 n->narg.type = NARG;
11750 /*n->narg.next = NULL; - stzalloc did it */
11751 n->narg.text = wordtext;
11752 n->narg.backquote = backquotelist;
11753 here->here->nhere.doc = n;
11760 * called by editline -- any expansions to the prompt should be added here.
11762 #if ENABLE_ASH_EXPAND_PRMT
11763 static const char *
11764 expandstr(const char *ps)
11768 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11769 * and token processing _can_ alter it (delete NULs etc). */
11770 setinputstring((char *)ps);
11771 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11774 n.narg.type = NARG;
11775 n.narg.next = NULL;
11776 n.narg.text = wordtext;
11777 n.narg.backquote = backquotelist;
11779 expandarg(&n, NULL, 0);
11780 return stackblock();
11785 * Execute a command or commands contained in a string.
11788 evalstring(char *s, int mask)
11791 struct stackmark smark;
11795 setstackmark(&smark);
11798 while ((n = parsecmd(0)) != NODE_EOF) {
11800 popstackmark(&smark);
11813 * The eval command.
11815 static int FAST_FUNC
11816 evalcmd(int argc UNUSED_PARAM, char **argv)
11825 STARTSTACKSTR(concat);
11827 concat = stack_putstr(p, concat);
11831 STPUTC(' ', concat);
11833 STPUTC('\0', concat);
11834 p = grabstackstr(concat);
11836 evalstring(p, ~SKIPEVAL);
11843 * Read and execute commands. "Top" is nonzero for the top level command
11844 * loop; it turns on prompting if the shell is interactive.
11850 struct stackmark smark;
11854 TRACE(("cmdloop(%d) called\n", top));
11858 setstackmark(&smark);
11861 showjobs(stderr, SHOW_CHANGED);
11864 if (iflag && top) {
11866 #if ENABLE_ASH_MAIL
11870 n = parsecmd(inter);
11872 if (DEBUG > 2 && debug && (n != NODE_EOF))
11875 if (n == NODE_EOF) {
11876 if (!top || numeof >= 50)
11878 if (!stoppedjobs()) {
11881 out2str("\nUse \"exit\" to leave shell.\n");
11884 } else if (nflag == 0) {
11885 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11890 popstackmark(&smark);
11895 return skip & SKIPEVAL;
11902 * Take commands from a file. To be compatible we should do a path
11903 * search for the file, which is necessary to find sub-commands.
11906 find_dot_file(char *name)
11909 const char *path = pathval();
11912 /* don't try this for absolute or relative paths */
11913 if (strchr(name, '/'))
11916 /* IIRC standards do not say whether . is to be searched.
11917 * And it is even smaller this way, making it unconditional for now:
11919 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11924 while ((fullname = path_advance(&path, name)) != NULL) {
11926 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11928 * Don't bother freeing here, since it will
11929 * be freed by the caller.
11933 if (fullname != name)
11934 stunalloc(fullname);
11937 /* not found in the PATH */
11938 ash_msg_and_raise_error("%s: not found", name);
11942 static int FAST_FUNC
11943 dotcmd(int argc, char **argv)
11945 struct strlist *sp;
11946 volatile struct shparam saveparam;
11949 for (sp = cmdenviron; sp; sp = sp->next)
11950 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
11952 if (argv[1]) { /* That's what SVR2 does */
11953 char *fullname = find_dot_file(argv[1]);
11956 if (argc) { /* argc > 0, argv[0] != NULL */
11957 saveparam = shellparam;
11958 shellparam.malloced = 0;
11959 shellparam.nparam = argc;
11960 shellparam.p = argv;
11963 setinputfile(fullname, INPUT_PUSH_FILE);
11964 commandname = fullname;
11969 freeparam(&shellparam);
11970 shellparam = saveparam;
11972 status = exitstatus;
11977 static int FAST_FUNC
11978 exitcmd(int argc UNUSED_PARAM, char **argv)
11983 exitstatus = number(argv[1]);
11984 raise_exception(EXEXIT);
11989 * Read a file containing shell functions.
11992 readcmdfile(char *name)
11994 setinputfile(name, INPUT_PUSH_FILE);
12000 /* ============ find_command inplementation */
12003 * Resolve a command name. If you change this routine, you may have to
12004 * change the shellexec routine as well.
12007 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12009 struct tblentry *cmdp;
12016 struct builtincmd *bcmd;
12018 /* If name contains a slash, don't use PATH or hash table */
12019 if (strchr(name, '/') != NULL) {
12020 entry->u.index = -1;
12021 if (act & DO_ABS) {
12022 while (stat(name, &statb) < 0) {
12024 if (errno == EINTR)
12027 entry->cmdtype = CMDUNKNOWN;
12031 entry->cmdtype = CMDNORMAL;
12035 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12037 updatetbl = (path == pathval());
12040 if (strstr(path, "%builtin") != NULL)
12041 act |= DO_ALTBLTIN;
12044 /* If name is in the table, check answer will be ok */
12045 cmdp = cmdlookup(name, 0);
12046 if (cmdp != NULL) {
12049 switch (cmdp->cmdtype) {
12067 } else if (cmdp->rehash == 0)
12068 /* if not invalidated by cd, we're done */
12072 /* If %builtin not in path, check for builtin next */
12073 bcmd = find_builtin(name);
12075 if (IS_BUILTIN_REGULAR(bcmd))
12076 goto builtin_success;
12077 if (act & DO_ALTPATH) {
12078 if (!(act & DO_ALTBLTIN))
12079 goto builtin_success;
12080 } else if (builtinloc <= 0) {
12081 goto builtin_success;
12085 #if ENABLE_FEATURE_SH_STANDALONE
12087 int applet_no = find_applet_by_name(name);
12088 if (applet_no >= 0) {
12089 entry->cmdtype = CMDNORMAL;
12090 entry->u.index = -2 - applet_no;
12096 /* We have to search path. */
12097 prev = -1; /* where to start */
12098 if (cmdp && cmdp->rehash) { /* doing a rehash */
12099 if (cmdp->cmdtype == CMDBUILTIN)
12102 prev = cmdp->param.index;
12108 while ((fullname = path_advance(&path, name)) != NULL) {
12109 stunalloc(fullname);
12110 /* NB: code below will still use fullname
12111 * despite it being "unallocated" */
12114 if (prefix(pathopt, "builtin")) {
12116 goto builtin_success;
12119 if ((act & DO_NOFUNC)
12120 || !prefix(pathopt, "func")
12121 ) { /* ignore unimplemented options */
12125 /* if rehash, don't redo absolute path names */
12126 if (fullname[0] == '/' && idx <= prev) {
12129 TRACE(("searchexec \"%s\": no change\n", name));
12132 while (stat(fullname, &statb) < 0) {
12134 if (errno == EINTR)
12137 if (errno != ENOENT && errno != ENOTDIR)
12141 e = EACCES; /* if we fail, this will be the error */
12142 if (!S_ISREG(statb.st_mode))
12144 if (pathopt) { /* this is a %func directory */
12145 stalloc(strlen(fullname) + 1);
12146 /* NB: stalloc will return space pointed by fullname
12147 * (because we don't have any intervening allocations
12148 * between stunalloc above and this stalloc) */
12149 readcmdfile(fullname);
12150 cmdp = cmdlookup(name, 0);
12151 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12152 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12153 stunalloc(fullname);
12156 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12158 entry->cmdtype = CMDNORMAL;
12159 entry->u.index = idx;
12163 cmdp = cmdlookup(name, 1);
12164 cmdp->cmdtype = CMDNORMAL;
12165 cmdp->param.index = idx;
12170 /* We failed. If there was an entry for this command, delete it */
12171 if (cmdp && updatetbl)
12172 delete_cmd_entry();
12174 ash_msg("%s: %s", name, errmsg(e, "not found"));
12175 entry->cmdtype = CMDUNKNOWN;
12180 entry->cmdtype = CMDBUILTIN;
12181 entry->u.cmd = bcmd;
12185 cmdp = cmdlookup(name, 1);
12186 cmdp->cmdtype = CMDBUILTIN;
12187 cmdp->param.cmd = bcmd;
12191 entry->cmdtype = cmdp->cmdtype;
12192 entry->u = cmdp->param;
12196 /* ============ trap.c */
12199 * The trap builtin.
12201 static int FAST_FUNC
12202 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12211 for (signo = 0; signo < NSIG; signo++) {
12212 if (trap[signo] != NULL) {
12213 out1fmt("trap -- %s %s\n",
12214 single_quote(trap[signo]),
12215 get_signame(signo));
12224 signo = get_signum(*ap);
12226 ash_msg_and_raise_error("%s: bad trap", *ap);
12229 if (LONE_DASH(action))
12232 action = ckstrdup(action);
12235 trap[signo] = action;
12245 /* ============ Builtins */
12247 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12249 * Lists available builtins
12251 static int FAST_FUNC
12252 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12258 "Built-in commands:\n"
12259 "------------------\n");
12260 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12261 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12262 builtintab[i].name + 1);
12268 #if ENABLE_FEATURE_SH_STANDALONE
12270 const char *a = applet_names;
12272 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12277 a += strlen(a) + 1;
12282 return EXIT_SUCCESS;
12284 #endif /* FEATURE_SH_EXTRA_QUIET */
12287 * The export and readonly commands.
12289 static int FAST_FUNC
12290 exportcmd(int argc UNUSED_PARAM, char **argv)
12296 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12298 if (nextopt("p") != 'p') {
12303 p = strchr(name, '=');
12307 vp = *findvar(hashvar(name), name);
12313 setvar(name, p, flag);
12314 } while ((name = *++aptr) != NULL);
12318 showvars(argv[0], flag, 0);
12323 * Delete a function if it exists.
12326 unsetfunc(const char *name)
12328 struct tblentry *cmdp;
12330 cmdp = cmdlookup(name, 0);
12331 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12332 delete_cmd_entry();
12336 * The unset builtin command. We unset the function before we unset the
12337 * variable to allow a function to be unset when there is a readonly variable
12338 * with the same name.
12340 static int FAST_FUNC
12341 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12348 while ((i = nextopt("vf")) != '\0') {
12352 for (ap = argptr; *ap; ap++) {
12368 #include <sys/times.h>
12370 static const unsigned char timescmd_str[] ALIGN1 = {
12371 ' ', offsetof(struct tms, tms_utime),
12372 '\n', offsetof(struct tms, tms_stime),
12373 ' ', offsetof(struct tms, tms_cutime),
12374 '\n', offsetof(struct tms, tms_cstime),
12378 static int FAST_FUNC
12379 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12381 long clk_tck, s, t;
12382 const unsigned char *p;
12385 clk_tck = sysconf(_SC_CLK_TCK);
12390 t = *(clock_t *)(((char *) &buf) + p[1]);
12392 out1fmt("%ldm%ld.%.3lds%c",
12394 ((t - s * clk_tck) * 1000) / clk_tck,
12396 } while (*(p += 2));
12401 #if ENABLE_SH_MATH_SUPPORT
12403 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12404 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12406 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12408 static int FAST_FUNC
12409 letcmd(int argc UNUSED_PARAM, char **argv)
12415 ash_msg_and_raise_error("expression expected");
12417 i = ash_arith(*argv);
12422 #endif /* SH_MATH_SUPPORT */
12425 /* ============ miscbltin.c
12427 * Miscellaneous builtins.
12432 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
12433 typedef enum __rlimit_resource rlim_t;
12437 * The read builtin. Options:
12438 * -r Do not interpret '\' specially
12439 * -s Turn off echo (tty only)
12440 * -n NCHARS Read NCHARS max
12441 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12442 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12443 * -u FD Read from given FD instead of fd 0
12444 * This uses unbuffered input, which may be avoidable in some cases.
12445 * TODO: bash also has:
12446 * -a ARRAY Read into array[0],[1],etc
12447 * -d DELIM End on DELIM char, not newline
12448 * -e Use line editing (tty only)
12450 static int FAST_FUNC
12451 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12453 static const char *const arg_REPLY[] = { "REPLY", NULL };
12466 #if ENABLE_ASH_READ_NCHARS
12467 int nchars = 0; /* if != 0, -n is in effect */
12469 struct termios tty, old_tty;
12471 #if ENABLE_ASH_READ_TIMEOUT
12472 unsigned end_ms = 0;
12473 unsigned timeout = 0;
12478 while ((i = nextopt("p:u:r"
12479 IF_ASH_READ_TIMEOUT("t:")
12480 IF_ASH_READ_NCHARS("n:s")
12484 prompt = optionarg;
12486 #if ENABLE_ASH_READ_NCHARS
12488 nchars = bb_strtou(optionarg, NULL, 10);
12489 if (nchars < 0 || errno)
12490 ash_msg_and_raise_error("invalid count");
12491 /* nchars == 0: off (bash 3.2 does this too) */
12497 #if ENABLE_ASH_READ_TIMEOUT
12499 timeout = bb_strtou(optionarg, NULL, 10);
12500 if (errno || timeout > UINT_MAX / 2048)
12501 ash_msg_and_raise_error("invalid timeout");
12503 #if 0 /* even bash have no -t N.NNN support */
12504 ts.tv_sec = bb_strtou(optionarg, &p, 10);
12506 /* EINVAL means number is ok, but not terminated by NUL */
12507 if (*p == '.' && errno == EINVAL) {
12511 ts.tv_usec = bb_strtou(p, &p2, 10);
12513 ash_msg_and_raise_error("invalid timeout");
12515 /* normalize to usec */
12517 ash_msg_and_raise_error("invalid timeout");
12518 while (scale++ < 6)
12521 } else if (ts.tv_sec < 0 || errno) {
12522 ash_msg_and_raise_error("invalid timeout");
12524 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
12525 ash_msg_and_raise_error("invalid timeout");
12534 fd = bb_strtou(optionarg, NULL, 10);
12535 if (fd < 0 || errno)
12536 ash_msg_and_raise_error("invalid file descriptor");
12542 if (prompt && isatty(fd)) {
12547 ap = (char**)arg_REPLY;
12548 ifs = bltinlookup("IFS");
12551 #if ENABLE_ASH_READ_NCHARS
12552 tcgetattr(fd, &tty);
12554 if (nchars || silent) {
12556 tty.c_lflag &= ~ICANON;
12557 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
12560 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12562 /* if tcgetattr failed, tcsetattr will fail too.
12563 * Ignoring, it's harmless. */
12564 tcsetattr(fd, TCSANOW, &tty);
12571 #if ENABLE_ASH_READ_TIMEOUT
12572 if (timeout) /* NB: ensuring end_ms is nonzero */
12573 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12577 const char *is_ifs;
12579 #if ENABLE_ASH_READ_TIMEOUT
12581 struct pollfd pfd[1];
12583 pfd[0].events = POLLIN;
12584 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12585 if ((int)timeout <= 0 /* already late? */
12586 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12587 ) { /* timed out! */
12588 #if ENABLE_ASH_READ_NCHARS
12589 tcsetattr(fd, TCSANOW, &old_tty);
12595 if (nonblock_safe_read(fd, &c, 1) != 1) {
12607 if (!rflag && c == '\\') {
12613 /* $IFS splitting */
12614 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
12615 is_ifs = strchr(ifs, c);
12616 if (startword && is_ifs) {
12619 /* it is a non-space ifs char */
12621 if (startword == 1) /* first one? */
12622 continue; /* yes, it is not next word yet */
12625 if (ap[1] != NULL && is_ifs) {
12628 beg = stackblock();
12629 setvar(*ap, beg, 0);
12631 /* can we skip one non-space ifs char? (2: yes) */
12632 startword = isspace(c) ? 2 : 1;
12639 /* end of do {} while: */
12640 #if ENABLE_ASH_READ_NCHARS
12646 #if ENABLE_ASH_READ_NCHARS
12647 tcsetattr(fd, TCSANOW, &old_tty);
12651 /* Remove trailing space ifs chars */
12652 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
12654 setvar(*ap, stackblock(), 0);
12655 while (*++ap != NULL)
12656 setvar(*ap, nullstr, 0);
12660 static int FAST_FUNC
12661 umaskcmd(int argc UNUSED_PARAM, char **argv)
12663 static const char permuser[3] ALIGN1 = "ugo";
12664 static const char permmode[3] ALIGN1 = "rwx";
12665 static const short permmask[] ALIGN2 = {
12666 S_IRUSR, S_IWUSR, S_IXUSR,
12667 S_IRGRP, S_IWGRP, S_IXGRP,
12668 S_IROTH, S_IWOTH, S_IXOTH
12671 /* TODO: use bb_parse_mode() instead */
12676 int symbolic_mode = 0;
12678 while (nextopt("S") != '\0') {
12689 if (symbolic_mode) {
12693 for (i = 0; i < 3; i++) {
12696 *p++ = permuser[i];
12698 for (j = 0; j < 3; j++) {
12699 if ((mask & permmask[3 * i + j]) == 0) {
12700 *p++ = permmode[j];
12708 out1fmt("%.4o\n", mask);
12711 if (isdigit((unsigned char) *ap)) {
12714 if (*ap >= '8' || *ap < '0')
12715 ash_msg_and_raise_error(illnum, argv[1]);
12716 mask = (mask << 3) + (*ap - '0');
12717 } while (*++ap != '\0');
12720 mask = ~mask & 0777;
12721 if (!bb_parse_mode(ap, &mask)) {
12722 ash_msg_and_raise_error("illegal mode: %s", ap);
12724 umask(~mask & 0777);
12733 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12734 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12735 * ash by J.T. Conklin.
12740 uint8_t cmd; /* RLIMIT_xxx fit into it */
12741 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
12745 static const struct limits limits_tbl[] = {
12747 { RLIMIT_CPU, 0, 't' },
12749 #ifdef RLIMIT_FSIZE
12750 { RLIMIT_FSIZE, 9, 'f' },
12753 { RLIMIT_DATA, 10, 'd' },
12755 #ifdef RLIMIT_STACK
12756 { RLIMIT_STACK, 10, 's' },
12759 { RLIMIT_CORE, 9, 'c' },
12762 { RLIMIT_RSS, 10, 'm' },
12764 #ifdef RLIMIT_MEMLOCK
12765 { RLIMIT_MEMLOCK, 10, 'l' },
12767 #ifdef RLIMIT_NPROC
12768 { RLIMIT_NPROC, 0, 'p' },
12770 #ifdef RLIMIT_NOFILE
12771 { RLIMIT_NOFILE, 0, 'n' },
12774 { RLIMIT_AS, 10, 'v' },
12776 #ifdef RLIMIT_LOCKS
12777 { RLIMIT_LOCKS, 0, 'w' },
12780 static const char limits_name[] =
12782 "time(seconds)" "\0"
12784 #ifdef RLIMIT_FSIZE
12785 "file(blocks)" "\0"
12790 #ifdef RLIMIT_STACK
12794 "coredump(blocks)" "\0"
12799 #ifdef RLIMIT_MEMLOCK
12800 "locked memory(kb)" "\0"
12802 #ifdef RLIMIT_NPROC
12805 #ifdef RLIMIT_NOFILE
12811 #ifdef RLIMIT_LOCKS
12816 enum limtype { SOFT = 0x1, HARD = 0x2 };
12819 printlim(enum limtype how, const struct rlimit *limit,
12820 const struct limits *l)
12824 val = limit->rlim_max;
12826 val = limit->rlim_cur;
12828 if (val == RLIM_INFINITY)
12829 out1fmt("unlimited\n");
12831 val >>= l->factor_shift;
12832 out1fmt("%lld\n", (long long) val);
12836 static int FAST_FUNC
12837 ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12841 enum limtype how = SOFT | HARD;
12842 const struct limits *l;
12845 struct rlimit limit;
12848 while ((optc = nextopt("HSa"
12852 #ifdef RLIMIT_FSIZE
12858 #ifdef RLIMIT_STACK
12867 #ifdef RLIMIT_MEMLOCK
12870 #ifdef RLIMIT_NPROC
12873 #ifdef RLIMIT_NOFILE
12879 #ifdef RLIMIT_LOCKS
12897 for (l = limits_tbl; l->option != what; l++)
12900 set = *argptr ? 1 : 0;
12904 if (all || argptr[1])
12905 ash_msg_and_raise_error("too many arguments");
12906 if (strncmp(p, "unlimited\n", 9) == 0)
12907 val = RLIM_INFINITY;
12911 while ((c = *p++) >= '0' && c <= '9') {
12912 val = (val * 10) + (long)(c - '0');
12913 // val is actually 'unsigned long int' and can't get < 0
12914 if (val < (rlim_t) 0)
12918 ash_msg_and_raise_error("bad number");
12919 val <<= l->factor_shift;
12923 const char *lname = limits_name;
12924 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
12925 getrlimit(l->cmd, &limit);
12926 out1fmt("%-20s ", lname);
12927 lname += strlen(lname) + 1;
12928 printlim(how, &limit, l);
12933 getrlimit(l->cmd, &limit);
12936 limit.rlim_max = val;
12938 limit.rlim_cur = val;
12939 if (setrlimit(l->cmd, &limit) < 0)
12940 ash_msg_and_raise_error("error setting limit (%m)");
12942 printlim(how, &limit, l);
12947 /* ============ main() and helpers */
12950 * Called to exit the shell.
12952 static void exitshell(void) NORETURN;
12960 status = exitstatus;
12961 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12962 if (setjmp(loc.loc)) {
12963 if (exception_type == EXEXIT)
12964 /* dash bug: it just does _exit(exitstatus) here
12965 * but we have to do setjobctl(0) first!
12966 * (bug is still not fixed in dash-0.5.3 - if you run dash
12967 * under Midnight Commander, on exit from dash MC is backgrounded) */
12968 status = exitstatus;
12971 exception_handler = &loc;
12977 flush_stdout_stderr();
12987 /* from input.c: */
12988 basepf.next_to_pgetc = basepf.buf = basebuf;
12991 signal(SIGCHLD, SIG_DFL);
12996 char ppid[sizeof(int)*3 + 1];
12998 struct stat st1, st2;
13001 for (envp = environ; envp && *envp; envp++) {
13002 if (strchr(*envp, '=')) {
13003 setvareq(*envp, VEXPORT|VTEXTFIXED);
13007 snprintf(ppid, sizeof(ppid), "%u", (unsigned) getppid());
13008 setvar("PPID", ppid, 0);
13010 p = lookupvar("PWD");
13012 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13013 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
13020 * Process the shell command line arguments.
13023 procargs(char **argv)
13026 const char *xminusc;
13031 /* if (xargv[0]) - mmm, this is always true! */
13033 for (i = 0; i < NOPTS; i++)
13037 /* it already printed err message */
13038 raise_exception(EXERROR);
13042 if (*xargv == NULL) {
13044 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13047 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13051 for (i = 0; i < NOPTS; i++)
13052 if (optlist[i] == 2)
13057 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13062 } else if (!sflag) {
13063 setinputfile(*xargv, 0);
13066 commandname = arg0;
13069 shellparam.p = xargv;
13070 #if ENABLE_ASH_GETOPTS
13071 shellparam.optind = 1;
13072 shellparam.optoff = -1;
13074 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13076 shellparam.nparam++;
13083 * Read /etc/profile or .profile.
13086 read_profile(const char *name)
13090 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13099 * This routine is called when an error or an interrupt occurs in an
13100 * interactive shell and control is returned to the main command loop.
13108 /* from input.c: */
13109 g_parsefile->left_in_buffer = 0;
13110 g_parsefile->left_in_line = 0; /* clear input buffer */
13112 /* from parser.c: */
13115 /* from redir.c: */
13116 clearredir(/*drop:*/ 0);
13120 static short profile_buf[16384];
13121 extern int etext();
13125 * Main routine. We initialize things, parse the arguments, execute
13126 * profiles if we're a login shell, and then call cmdloop to execute
13127 * commands. The setjmp call sets up the location to jump to when an
13128 * exception occurs. When an exception occurs the variable "state"
13129 * is used to figure out how far we had gotten.
13131 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13132 int ash_main(int argc UNUSED_PARAM, char **argv)
13134 const char *shinit;
13135 volatile smallint state;
13136 struct jmploc jmploc;
13137 struct stackmark smark;
13139 /* Initialize global data */
13143 #if ENABLE_ASH_ALIAS
13149 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13152 #if ENABLE_FEATURE_EDITING
13153 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13156 if (setjmp(jmploc.loc)) {
13162 e = exception_type;
13166 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13169 outcslow('\n', stderr);
13171 popstackmark(&smark);
13172 FORCE_INT_ON; /* enable interrupts */
13181 exception_handler = &jmploc;
13184 TRACE(("Shell args: "));
13185 trace_puts_args(argv);
13187 rootpid = getpid();
13189 #if ENABLE_ASH_RANDOM_SUPPORT
13190 /* Can use monotonic_ns() for better randomness but for now it is
13191 * not used anywhere else in busybox... so avoid bloat */
13192 random_galois_LFSR = random_LCG = rootpid + monotonic_us();
13195 setstackmark(&smark);
13198 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13200 const char *hp = lookupvar("HISTFILE");
13203 hp = lookupvar("HOME");
13205 char *defhp = concat_path_file(hp, ".ash_history");
13206 setvar("HISTFILE", defhp, 0);
13212 if (/* argv[0] && */ argv[0][0] == '-')
13216 read_profile("/etc/profile");
13219 read_profile(".profile");
13225 getuid() == geteuid() && getgid() == getegid() &&
13229 shinit = lookupvar("ENV");
13230 if (shinit != NULL && *shinit != '\0') {
13231 read_profile(shinit);
13237 /* evalstring pushes parsefile stack.
13238 * Ensure we don't falsely claim that 0 (stdin)
13239 * is one of stacked source fds.
13240 * Testcase: ash -c 'exec 1>&0' must not complain. */
13242 g_parsefile->fd = -1;
13243 evalstring(minusc, 0);
13246 if (sflag || minusc == NULL) {
13247 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13249 const char *hp = lookupvar("HISTFILE");
13251 line_input_state->hist_file = hp;
13254 state4: /* XXX ??? - why isn't this before the "if" statement */
13262 extern void _mcleanup(void);
13272 * Copyright (c) 1989, 1991, 1993, 1994
13273 * The Regents of the University of California. All rights reserved.
13275 * This code is derived from software contributed to Berkeley by
13276 * Kenneth Almquist.
13278 * Redistribution and use in source and binary forms, with or without
13279 * modification, are permitted provided that the following conditions
13281 * 1. Redistributions of source code must retain the above copyright
13282 * notice, this list of conditions and the following disclaimer.
13283 * 2. Redistributions in binary form must reproduce the above copyright
13284 * notice, this list of conditions and the following disclaimer in the
13285 * documentation and/or other materials provided with the distribution.
13286 * 3. Neither the name of the University nor the names of its contributors
13287 * may be used to endorse or promote products derived from this software
13288 * without specific prior written permission.
13290 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13291 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13292 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13293 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13294 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13295 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13296 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13297 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13298 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13299 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF