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 USE_FEATURE_SH_STANDALONE
60 #undef SKIP_FEATURE_SH_STANDALONE(...)
61 #define ENABLE_FEATURE_SH_STANDALONE 0
62 #define USE_FEATURE_SH_STANDALONE(...)
63 #define SKIP_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 #if ENABLE_SH_MATH_SUPPORT
189 arith_eval_hooks_t math_hooks;
192 /* trap handler commands */
194 * Sigmode records the current value of the signal handlers for the various
195 * modes. A value of zero means that the current handler is not known.
196 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
198 char sigmode[NSIG - 1];
199 #define S_DFL 1 /* default signal handling (SIG_DFL) */
200 #define S_CATCH 2 /* signal is caught */
201 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
202 #define S_HARD_IGN 4 /* signal is ignored permenantly */
204 /* indicates specified signal received */
205 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
208 /* Rarely referenced stuff */
209 #if ENABLE_ASH_RANDOM_SUPPORT
210 /* Random number generators */
211 int32_t random_galois_LFSR; /* Galois LFSR (fast but weak). signed! */
212 uint32_t random_LCG; /* LCG (fast but weak) */
214 pid_t backgndpid; /* pid of last background process */
215 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
217 extern struct globals_misc *const ash_ptr_to_globals_misc;
218 #define G_misc (*ash_ptr_to_globals_misc)
219 #define rootpid (G_misc.rootpid )
220 #define shlvl (G_misc.shlvl )
221 #define minusc (G_misc.minusc )
222 #define curdir (G_misc.curdir )
223 #define physdir (G_misc.physdir )
224 #define arg0 (G_misc.arg0 )
225 #define exception_handler (G_misc.exception_handler)
226 #define exception_type (G_misc.exception_type )
227 #define suppressint (G_misc.suppressint )
228 #define intpending (G_misc.intpending )
229 //#define exsig (G_misc.exsig )
230 #define pendingsig (G_misc.pendingsig )
231 #define isloginsh (G_misc.isloginsh )
232 #define nullstr (G_misc.nullstr )
233 #define optlist (G_misc.optlist )
234 #define sigmode (G_misc.sigmode )
235 #define gotsig (G_misc.gotsig )
236 #define trap (G_misc.trap )
237 #define random_galois_LFSR (G_misc.random_galois_LFSR)
238 #define random_LCG (G_misc.random_LCG )
239 #define backgndpid (G_misc.backgndpid )
240 #define job_warning (G_misc.job_warning)
241 #define math_hooks (G_misc.math_hooks )
242 #define INIT_G_misc() do { \
243 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
250 /* ============ DEBUG */
252 static void trace_printf(const char *fmt, ...);
253 static void trace_vprintf(const char *fmt, va_list va);
254 # define TRACE(param) trace_printf param
255 # define TRACEV(param) trace_vprintf param
256 # define close(fd) do { \
258 if (close(dfd) < 0) \
259 bb_error_msg("bug on %d: closing %d(%x)", \
260 __LINE__, dfd, dfd); \
263 # define TRACE(param)
264 # define TRACEV(param)
268 /* ============ Utility functions */
269 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
271 /* C99 say: "char" declaration may be signed or unsigned by default */
272 #define signed_char2int(sc) ((int)(signed char)(sc))
274 static int isdigit_str9(const char *str)
276 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
277 while (--maxlen && isdigit(*str))
279 return (*str == '\0');
283 /* ============ Interrupts / exceptions */
285 * These macros allow the user to suspend the handling of interrupt signals
286 * over a period of time. This is similar to SIGHOLD or to sigblock, but
287 * much more efficient and portable. (But hacking the kernel is so much
288 * more fun than worrying about efficiency and portability. :-))
290 #define INT_OFF do { \
296 * Called to raise an exception. Since C doesn't include exceptions, we
297 * just do a longjmp to the exception handler. The type of exception is
298 * stored in the global variable "exception_type".
300 static void raise_exception(int) NORETURN;
302 raise_exception(int e)
305 if (exception_handler == NULL)
310 longjmp(exception_handler->loc, 1);
313 #define raise_exception(e) do { \
314 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
315 raise_exception(e); \
320 * Called from trap.c when a SIGINT is received. (If the user specifies
321 * that SIGINT is to be trapped or ignored using the trap builtin, then
322 * this routine is not called.) Suppressint is nonzero when interrupts
323 * are held using the INT_OFF macro. (The test for iflag is just
324 * defensive programming.)
326 static void raise_interrupt(void) NORETURN;
328 raise_interrupt(void)
333 /* Signal is not automatically unmasked after it is raised,
334 * do it ourself - unmask all signals */
335 sigprocmask_allsigs(SIG_UNBLOCK);
336 /* pendingsig = 0; - now done in onsig() */
339 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
340 if (!(rootshell && iflag)) {
341 /* Kill ourself with SIGINT */
342 signal(SIGINT, SIG_DFL);
347 raise_exception(ex_type);
351 #define raise_interrupt() do { \
352 TRACE(("raising interrupt on line %d\n", __LINE__)); \
357 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
361 if (--suppressint == 0 && intpending) {
365 #define INT_ON int_on()
373 #define FORCE_INT_ON force_int_on()
375 #else /* !ASH_OPTIMIZE_FOR_SIZE */
377 #define INT_ON do { \
379 if (--suppressint == 0 && intpending) \
382 #define FORCE_INT_ON do { \
388 #endif /* !ASH_OPTIMIZE_FOR_SIZE */
390 #define SAVE_INT(v) ((v) = suppressint)
392 #define RESTORE_INT(v) do { \
395 if (suppressint == 0 && intpending) \
400 /* ============ Stdout/stderr output */
403 outstr(const char *p, FILE *file)
411 flush_stdout_stderr(void)
428 outcslow(int c, FILE *dest)
436 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
438 out1fmt(const char *fmt, ...)
445 r = vprintf(fmt, ap);
451 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
453 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
460 ret = vsnprintf(outbuf, length, fmt, ap);
467 out1str(const char *p)
473 out2str(const char *p)
480 /* ============ Parser structures */
482 /* control characters in argument strings */
483 #define CTLESC '\201' /* escape next character */
484 #define CTLVAR '\202' /* variable defn */
485 #define CTLENDVAR '\203'
486 #define CTLBACKQ '\204'
487 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
488 /* CTLBACKQ | CTLQUOTE == '\205' */
489 #define CTLARI '\206' /* arithmetic expression */
490 #define CTLENDARI '\207'
491 #define CTLQUOTEMARK '\210'
493 /* variable substitution byte (follows CTLVAR) */
494 #define VSTYPE 0x0f /* type of variable substitution */
495 #define VSNUL 0x10 /* colon--treat the empty string as unset */
496 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
498 /* values of VSTYPE field */
499 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
500 #define VSMINUS 0x2 /* ${var-text} */
501 #define VSPLUS 0x3 /* ${var+text} */
502 #define VSQUESTION 0x4 /* ${var?message} */
503 #define VSASSIGN 0x5 /* ${var=text} */
504 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
505 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
506 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
507 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
508 #define VSLENGTH 0xa /* ${#var} */
509 #if ENABLE_ASH_BASH_COMPAT
510 #define VSSUBSTR 0xc /* ${var:position:length} */
511 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
512 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
515 static const char dolatstr[] ALIGN1 = {
516 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
536 #if ENABLE_ASH_BASH_COMPAT
553 smallint type; /* Nxxxx */
556 union node *redirect;
561 smallint pipe_backgnd;
562 struct nodelist *cmdlist;
568 union node *redirect;
581 union node *elsepart;
608 struct nodelist *backquote;
611 /* nfile and ndup layout must match!
612 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
613 * that it is actually NTO2 (>&file), and change its type.
630 char *_unused_expfname;
649 struct nredir nredir;
650 struct nbinary nbinary;
654 struct nclist nclist;
663 struct nodelist *next;
676 freefunc(struct funcnode *f)
678 if (f && --f->count < 0)
683 /* ============ Debugging output */
687 static FILE *tracefile;
690 trace_printf(const char *fmt, ...)
697 fprintf(tracefile, "%u ", (int) time(NULL));
699 fprintf(tracefile, "[%u] ", (int) getpid());
701 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pendingsig, intpending, suppressint);
703 vfprintf(tracefile, fmt, va);
708 trace_vprintf(const char *fmt, va_list va)
713 fprintf(tracefile, "%u ", (int) time(NULL));
715 fprintf(tracefile, "[%u] ", (int) getpid());
717 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pendingsig, intpending, suppressint);
718 vfprintf(tracefile, fmt, va);
722 trace_puts(const char *s)
730 trace_puts_quoted(char *s)
737 putc('"', tracefile);
738 for (p = s; *p; p++) {
740 case '\n': c = 'n'; goto backslash;
741 case '\t': c = 't'; goto backslash;
742 case '\r': c = 'r'; goto backslash;
743 case '"': c = '"'; goto backslash;
744 case '\\': c = '\\'; goto backslash;
745 case CTLESC: c = 'e'; goto backslash;
746 case CTLVAR: c = 'v'; goto backslash;
747 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
748 case CTLBACKQ: c = 'q'; goto backslash;
749 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
751 putc('\\', tracefile);
755 if (*p >= ' ' && *p <= '~')
758 putc('\\', tracefile);
759 putc(*p >> 6 & 03, tracefile);
760 putc(*p >> 3 & 07, tracefile);
761 putc(*p & 07, tracefile);
766 putc('"', tracefile);
770 trace_puts_args(char **ap)
777 trace_puts_quoted(*ap);
779 putc('\n', tracefile);
782 putc(' ', tracefile);
797 /* leave open because libedit might be using it */
800 strcpy(s, "./trace");
802 if (!freopen(s, "a", tracefile)) {
803 fprintf(stderr, "Can't re-open %s\n", s);
808 tracefile = fopen(s, "a");
809 if (tracefile == NULL) {
810 fprintf(stderr, "Can't open %s\n", s);
816 flags = fcntl(fileno(tracefile), F_GETFL);
818 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
820 setlinebuf(tracefile);
821 fputs("\nTracing started.\n", tracefile);
825 indent(int amount, char *pfx, FILE *fp)
829 for (i = 0; i < amount; i++) {
830 if (pfx && i == amount - 1)
836 /* little circular references here... */
837 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
840 sharg(union node *arg, FILE *fp)
843 struct nodelist *bqlist;
846 if (arg->type != NARG) {
847 out1fmt("<node type %d>\n", arg->type);
850 bqlist = arg->narg.backquote;
851 for (p = arg->narg.text; *p; p++) {
860 if (subtype == VSLENGTH)
869 switch (subtype & VSTYPE) {
902 out1fmt("<subtype %d>", subtype);
909 case CTLBACKQ|CTLQUOTE:
912 shtree(bqlist->n, -1, NULL, fp);
923 shcmd(union node *cmd, FILE *fp)
931 for (np = cmd->ncmd.args; np; np = np->narg.next) {
937 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
941 switch (np->nfile.type) {
942 case NTO: s = ">>"+1; dftfd = 1; break;
943 case NCLOBBER: s = ">|"; dftfd = 1; break;
944 case NAPPEND: s = ">>"; dftfd = 1; break;
945 #if ENABLE_ASH_BASH_COMPAT
948 case NTOFD: s = ">&"; dftfd = 1; break;
949 case NFROM: s = "<"; break;
950 case NFROMFD: s = "<&"; break;
951 case NFROMTO: s = "<>"; break;
952 default: s = "*error*"; break;
954 if (np->nfile.fd != dftfd)
955 fprintf(fp, "%d", np->nfile.fd);
957 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
958 fprintf(fp, "%d", np->ndup.dupfd);
960 sharg(np->nfile.fname, fp);
967 shtree(union node *n, int ind, char *pfx, FILE *fp)
975 indent(ind, pfx, fp);
986 shtree(n->nbinary.ch1, ind, NULL, fp);
989 shtree(n->nbinary.ch2, ind, NULL, fp);
997 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1002 if (n->npipe.pipe_backgnd)
1008 fprintf(fp, "<node type %d>", n->type);
1016 showtree(union node *n)
1018 trace_puts("showtree called\n");
1019 shtree(n, 1, NULL, stdout);
1025 /* ============ Parser data */
1028 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1031 struct strlist *next;
1038 struct strpush *prev; /* preceding string on stack */
1040 int prev_left_in_line;
1041 #if ENABLE_ASH_ALIAS
1042 struct alias *ap; /* if push was associated with an alias */
1044 char *string; /* remember the string since it may change */
1048 struct parsefile *prev; /* preceding file on stack */
1049 int linno; /* current line */
1050 int fd; /* file descriptor (or -1 if string) */
1051 int left_in_line; /* number of chars left in this line */
1052 int left_in_buffer; /* number of chars left in this buffer past the line */
1053 char *next_to_pgetc; /* next char in buffer */
1054 char *buf; /* input buffer */
1055 struct strpush *strpush; /* for pushing strings at this level */
1056 struct strpush basestrpush; /* so pushing one is fast */
1059 static struct parsefile basepf; /* top level input file */
1060 static struct parsefile *g_parsefile = &basepf; /* current input file */
1061 static int startlinno; /* line # where last token started */
1062 static char *commandname; /* currently executing command */
1063 static struct strlist *cmdenviron; /* environment for builtin command */
1064 static uint8_t exitstatus; /* exit status of last command */
1067 /* ============ Message printing */
1070 ash_vmsg(const char *msg, va_list ap)
1072 fprintf(stderr, "%s: ", arg0);
1074 if (strcmp(arg0, commandname))
1075 fprintf(stderr, "%s: ", commandname);
1076 if (!iflag || g_parsefile->fd)
1077 fprintf(stderr, "line %d: ", startlinno);
1079 vfprintf(stderr, msg, ap);
1080 outcslow('\n', stderr);
1084 * Exverror is called to raise the error exception. If the second argument
1085 * is not NULL then error prints an error message using printf style
1086 * formatting. It then raises the error exception.
1088 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1090 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1094 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1096 TRACE(("\") pid=%d\n", getpid()));
1098 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1103 flush_stdout_stderr();
1104 raise_exception(cond);
1108 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1110 ash_msg_and_raise_error(const char *msg, ...)
1115 ash_vmsg_and_raise(EXERROR, msg, ap);
1120 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1122 ash_msg_and_raise(int cond, const char *msg, ...)
1127 ash_vmsg_and_raise(cond, msg, ap);
1133 * error/warning routines for external builtins
1136 ash_msg(const char *fmt, ...)
1146 * Return a string describing an error. The returned string may be a
1147 * pointer to a static buffer that will be overwritten on the next call.
1148 * Action describes the operation that got the error.
1151 errmsg(int e, const char *em)
1153 if (e == ENOENT || e == ENOTDIR) {
1160 /* ============ Memory allocation */
1163 * It appears that grabstackstr() will barf with such alignments
1164 * because stalloc() will return a string allocated in a new stackblock.
1166 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1168 /* Most machines require the value returned from malloc to be aligned
1169 * in some way. The following macro will get this right
1170 * on many machines. */
1171 SHELL_SIZE = sizeof(union {int i; char *cp; double d; }) - 1,
1172 /* Minimum size of a block */
1173 MINSIZE = SHELL_ALIGN(504),
1176 struct stack_block {
1177 struct stack_block *prev;
1178 char space[MINSIZE];
1182 struct stack_block *stackp;
1185 struct stackmark *marknext;
1189 struct globals_memstack {
1190 struct stack_block *g_stackp; // = &stackbase;
1191 struct stackmark *markp;
1192 char *g_stacknxt; // = stackbase.space;
1193 char *sstrend; // = stackbase.space + MINSIZE;
1194 size_t g_stacknleft; // = MINSIZE;
1195 int herefd; // = -1;
1196 struct stack_block stackbase;
1198 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1199 #define G_memstack (*ash_ptr_to_globals_memstack)
1200 #define g_stackp (G_memstack.g_stackp )
1201 #define markp (G_memstack.markp )
1202 #define g_stacknxt (G_memstack.g_stacknxt )
1203 #define sstrend (G_memstack.sstrend )
1204 #define g_stacknleft (G_memstack.g_stacknleft)
1205 #define herefd (G_memstack.herefd )
1206 #define stackbase (G_memstack.stackbase )
1207 #define INIT_G_memstack() do { \
1208 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1210 g_stackp = &stackbase; \
1211 g_stacknxt = stackbase.space; \
1212 g_stacknleft = MINSIZE; \
1213 sstrend = stackbase.space + MINSIZE; \
1217 #define stackblock() ((void *)g_stacknxt)
1218 #define stackblocksize() g_stacknleft
1222 ckrealloc(void * p, size_t nbytes)
1224 p = realloc(p, nbytes);
1226 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1231 ckmalloc(size_t nbytes)
1233 return ckrealloc(NULL, nbytes);
1237 ckzalloc(size_t nbytes)
1239 return memset(ckmalloc(nbytes), 0, nbytes);
1243 * Make a copy of a string in safe storage.
1246 ckstrdup(const char *s)
1248 char *p = strdup(s);
1250 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1255 * Parse trees for commands are allocated in lifo order, so we use a stack
1256 * to make this more efficient, and also to avoid all sorts of exception
1257 * handling code to handle interrupts in the middle of a parse.
1259 * The size 504 was chosen because the Ultrix malloc handles that size
1263 stalloc(size_t nbytes)
1268 aligned = SHELL_ALIGN(nbytes);
1269 if (aligned > g_stacknleft) {
1272 struct stack_block *sp;
1274 blocksize = aligned;
1275 if (blocksize < MINSIZE)
1276 blocksize = MINSIZE;
1277 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1278 if (len < blocksize)
1279 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1282 sp->prev = g_stackp;
1283 g_stacknxt = sp->space;
1284 g_stacknleft = blocksize;
1285 sstrend = g_stacknxt + blocksize;
1290 g_stacknxt += aligned;
1291 g_stacknleft -= aligned;
1296 stzalloc(size_t nbytes)
1298 return memset(stalloc(nbytes), 0, nbytes);
1305 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1306 write(STDERR_FILENO, "stunalloc\n", 10);
1310 g_stacknleft += g_stacknxt - (char *)p;
1315 * Like strdup but works with the ash stack.
1318 ststrdup(const char *p)
1320 size_t len = strlen(p) + 1;
1321 return memcpy(stalloc(len), p, len);
1325 setstackmark(struct stackmark *mark)
1327 mark->stackp = g_stackp;
1328 mark->stacknxt = g_stacknxt;
1329 mark->stacknleft = g_stacknleft;
1330 mark->marknext = markp;
1335 popstackmark(struct stackmark *mark)
1337 struct stack_block *sp;
1343 markp = mark->marknext;
1344 while (g_stackp != mark->stackp) {
1346 g_stackp = sp->prev;
1349 g_stacknxt = mark->stacknxt;
1350 g_stacknleft = mark->stacknleft;
1351 sstrend = mark->stacknxt + mark->stacknleft;
1356 * When the parser reads in a string, it wants to stick the string on the
1357 * stack and only adjust the stack pointer when it knows how big the
1358 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1359 * of space on top of the stack and stackblocklen returns the length of
1360 * this block. Growstackblock will grow this space by at least one byte,
1361 * possibly moving it (like realloc). Grabstackblock actually allocates the
1362 * part of the block that has been used.
1365 growstackblock(void)
1369 newlen = g_stacknleft * 2;
1370 if (newlen < g_stacknleft)
1371 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1375 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1376 struct stack_block *oldstackp;
1377 struct stackmark *xmark;
1378 struct stack_block *sp;
1379 struct stack_block *prevstackp;
1383 oldstackp = g_stackp;
1385 prevstackp = sp->prev;
1386 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1387 sp = ckrealloc(sp, grosslen);
1388 sp->prev = prevstackp;
1390 g_stacknxt = sp->space;
1391 g_stacknleft = newlen;
1392 sstrend = sp->space + newlen;
1395 * Stack marks pointing to the start of the old block
1396 * must be relocated to point to the new block
1399 while (xmark != NULL && xmark->stackp == oldstackp) {
1400 xmark->stackp = g_stackp;
1401 xmark->stacknxt = g_stacknxt;
1402 xmark->stacknleft = g_stacknleft;
1403 xmark = xmark->marknext;
1407 char *oldspace = g_stacknxt;
1408 size_t oldlen = g_stacknleft;
1409 char *p = stalloc(newlen);
1411 /* free the space we just allocated */
1412 g_stacknxt = memcpy(p, oldspace, oldlen);
1413 g_stacknleft += newlen;
1418 grabstackblock(size_t len)
1420 len = SHELL_ALIGN(len);
1422 g_stacknleft -= len;
1426 * The following routines are somewhat easier to use than the above.
1427 * The user declares a variable of type STACKSTR, which may be declared
1428 * to be a register. The macro STARTSTACKSTR initializes things. Then
1429 * the user uses the macro STPUTC to add characters to the string. In
1430 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1431 * grown as necessary. When the user is done, she can just leave the
1432 * string there and refer to it using stackblock(). Or she can allocate
1433 * the space for it using grabstackstr(). If it is necessary to allow
1434 * someone else to use the stack temporarily and then continue to grow
1435 * the string, the user should use grabstack to allocate the space, and
1436 * then call ungrabstr(p) to return to the previous mode of operation.
1438 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1439 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1440 * is space for at least one character.
1445 size_t len = stackblocksize();
1446 if (herefd >= 0 && len >= 1024) {
1447 full_write(herefd, stackblock(), len);
1448 return stackblock();
1451 return (char *)stackblock() + len;
1455 * Called from CHECKSTRSPACE.
1458 makestrspace(size_t newlen, char *p)
1460 size_t len = p - g_stacknxt;
1461 size_t size = stackblocksize();
1466 size = stackblocksize();
1468 if (nleft >= newlen)
1472 return (char *)stackblock() + len;
1476 stack_nputstr(const char *s, size_t n, char *p)
1478 p = makestrspace(n, p);
1479 p = (char *)memcpy(p, s, n) + n;
1484 stack_putstr(const char *s, char *p)
1486 return stack_nputstr(s, strlen(s), p);
1490 _STPUTC(int c, char *p)
1498 #define STARTSTACKSTR(p) ((p) = stackblock())
1499 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1500 #define CHECKSTRSPACE(n, p) do { \
1503 size_t m = sstrend - q; \
1505 (p) = makestrspace(l, q); \
1507 #define USTPUTC(c, p) (*(p)++ = (c))
1508 #define STACKSTRNUL(p) do { \
1509 if ((p) == sstrend) \
1510 (p) = growstackstr(); \
1513 #define STUNPUTC(p) (--(p))
1514 #define STTOPC(p) ((p)[-1])
1515 #define STADJUST(amount, p) ((p) += (amount))
1517 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1518 #define ungrabstackstr(s, p) stunalloc(s)
1519 #define stackstrend() ((void *)sstrend)
1522 /* ============ String helpers */
1525 * prefix -- see if pfx is a prefix of string.
1528 prefix(const char *string, const char *pfx)
1531 if (*pfx++ != *string++)
1534 return (char *) string;
1538 * Check for a valid number. This should be elsewhere.
1541 is_number(const char *p)
1546 } while (*++p != '\0');
1551 * Convert a string of digits to an integer, printing an error message on
1555 number(const char *s)
1558 ash_msg_and_raise_error(illnum, s);
1563 * Produce a possibly single quoted string suitable as input to the shell.
1564 * The return string is allocated on the stack.
1567 single_quote(const char *s)
1577 len = strchrnul(s, '\'') - s;
1579 q = p = makestrspace(len + 3, p);
1582 q = (char *)memcpy(q, s, len) + len;
1588 len = strspn(s, "'");
1592 q = p = makestrspace(len + 3, p);
1595 q = (char *)memcpy(q, s, len) + len;
1604 return stackblock();
1608 /* ============ nextopt */
1610 static char **argptr; /* argument list for builtin commands */
1611 static char *optionarg; /* set by nextopt (like getopt) */
1612 static char *optptr; /* used by nextopt */
1615 * XXX - should get rid of. Have all builtins use getopt(3).
1616 * The library getopt must have the BSD extension static variable
1617 * "optreset", otherwise it can't be used within the shell safely.
1619 * Standard option processing (a la getopt) for builtin routines.
1620 * The only argument that is passed to nextopt is the option string;
1621 * the other arguments are unnecessary. It returns the character,
1622 * or '\0' on end of input.
1625 nextopt(const char *optstring)
1632 if (p == NULL || *p == '\0') {
1633 /* We ate entire "-param", take next one */
1639 if (*++p == '\0') /* just "-" ? */
1642 if (LONE_DASH(p)) /* "--" ? */
1644 /* p => next "-param" */
1646 /* p => some option char in the middle of a "-param" */
1648 for (q = optstring; *q != c;) {
1650 ash_msg_and_raise_error("illegal option -%c", c);
1658 ash_msg_and_raise_error("no arg for -%c option", c);
1668 /* ============ Shell variables */
1671 * The parsefile structure pointed to by the global variable parsefile
1672 * contains information about the current file being read.
1675 int nparam; /* # of positional parameters (without $0) */
1676 #if ENABLE_ASH_GETOPTS
1677 int optind; /* next parameter to be processed by getopts */
1678 int optoff; /* used by getopts */
1680 unsigned char malloced; /* if parameter list dynamically allocated */
1681 char **p; /* parameter list */
1685 * Free the list of positional parameters.
1688 freeparam(volatile struct shparam *param)
1690 if (param->malloced) {
1692 ap = ap1 = param->p;
1699 #if ENABLE_ASH_GETOPTS
1700 static void getoptsreset(const char *value);
1704 struct var *next; /* next entry in hash list */
1705 int flags; /* flags are defined above */
1706 const char *text; /* name=value */
1707 void (*func)(const char *); /* function to be called when */
1708 /* the variable gets set/unset */
1712 struct localvar *next; /* next local variable in list */
1713 struct var *vp; /* the variable that was made local */
1714 int flags; /* saved flags */
1715 const char *text; /* saved text */
1719 #define VEXPORT 0x01 /* variable is exported */
1720 #define VREADONLY 0x02 /* variable cannot be modified */
1721 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1722 #define VTEXTFIXED 0x08 /* text is statically allocated */
1723 #define VSTACK 0x10 /* text is allocated on the stack */
1724 #define VUNSET 0x20 /* the variable is not set */
1725 #define VNOFUNC 0x40 /* don't call the callback function */
1726 #define VNOSET 0x80 /* do not set variable - just readonly test */
1727 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1728 #if ENABLE_ASH_RANDOM_SUPPORT
1729 # define VDYNAMIC 0x200 /* dynamic variable */
1735 static const char defifsvar[] ALIGN1 = "IFS= \t\n";
1736 #define defifs (defifsvar + 4)
1738 static const char defifs[] ALIGN1 = " \t\n";
1742 /* Need to be before varinit_data[] */
1743 #if ENABLE_LOCALE_SUPPORT
1745 change_lc_all(const char *value)
1747 if (value && *value != '\0')
1748 setlocale(LC_ALL, value);
1751 change_lc_ctype(const char *value)
1753 if (value && *value != '\0')
1754 setlocale(LC_CTYPE, value);
1758 static void chkmail(void);
1759 static void changemail(const char *);
1761 static void changepath(const char *);
1762 #if ENABLE_ASH_RANDOM_SUPPORT
1763 static void change_random(const char *);
1766 static const struct {
1769 void (*func)(const char *);
1770 } varinit_data[] = {
1772 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1774 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
1777 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1778 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1780 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1781 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1782 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1783 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1784 #if ENABLE_ASH_GETOPTS
1785 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1787 #if ENABLE_ASH_RANDOM_SUPPORT
1788 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
1790 #if ENABLE_LOCALE_SUPPORT
1791 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1792 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
1794 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1795 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
1801 struct globals_var {
1802 struct shparam shellparam; /* $@ current positional parameters */
1803 struct redirtab *redirlist;
1805 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1806 struct var *vartab[VTABSIZE];
1807 struct var varinit[ARRAY_SIZE(varinit_data)];
1809 extern struct globals_var *const ash_ptr_to_globals_var;
1810 #define G_var (*ash_ptr_to_globals_var)
1811 #define shellparam (G_var.shellparam )
1812 //#define redirlist (G_var.redirlist )
1813 #define g_nullredirs (G_var.g_nullredirs )
1814 #define preverrout_fd (G_var.preverrout_fd)
1815 #define vartab (G_var.vartab )
1816 #define varinit (G_var.varinit )
1817 #define INIT_G_var() do { \
1819 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1821 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1822 varinit[i].flags = varinit_data[i].flags; \
1823 varinit[i].text = varinit_data[i].text; \
1824 varinit[i].func = varinit_data[i].func; \
1828 #define vifs varinit[0]
1830 # define vmail (&vifs)[1]
1831 # define vmpath (&vmail)[1]
1832 # define vpath (&vmpath)[1]
1834 # define vpath (&vifs)[1]
1836 #define vps1 (&vpath)[1]
1837 #define vps2 (&vps1)[1]
1838 #define vps4 (&vps2)[1]
1839 #if ENABLE_ASH_GETOPTS
1840 # define voptind (&vps4)[1]
1841 # if ENABLE_ASH_RANDOM_SUPPORT
1842 # define vrandom (&voptind)[1]
1845 # if ENABLE_ASH_RANDOM_SUPPORT
1846 # define vrandom (&vps4)[1]
1851 * The following macros access the values of the above variables.
1852 * They have to skip over the name. They return the null string
1853 * for unset variables.
1855 #define ifsval() (vifs.text + 4)
1856 #define ifsset() ((vifs.flags & VUNSET) == 0)
1858 # define mailval() (vmail.text + 5)
1859 # define mpathval() (vmpath.text + 9)
1860 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1862 #define pathval() (vpath.text + 5)
1863 #define ps1val() (vps1.text + 4)
1864 #define ps2val() (vps2.text + 4)
1865 #define ps4val() (vps4.text + 4)
1866 #if ENABLE_ASH_GETOPTS
1867 # define optindval() (voptind.text + 7)
1871 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1872 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1874 #if ENABLE_ASH_GETOPTS
1876 getoptsreset(const char *value)
1878 shellparam.optind = number(value);
1879 shellparam.optoff = -1;
1884 * Return of a legal variable name (a letter or underscore followed by zero or
1885 * more letters, underscores, and digits).
1888 endofname(const char *name)
1896 if (!is_in_name(*p))
1903 * Compares two strings up to the first = or '\0'. The first
1904 * string must be terminated by '='; the second may be terminated by
1905 * either '=' or '\0'.
1908 varcmp(const char *p, const char *q)
1912 while ((c = *p) == (d = *q)) {
1927 varequal(const char *a, const char *b)
1929 return !varcmp(a, b);
1933 * Find the appropriate entry in the hash table from the name.
1935 static struct var **
1936 hashvar(const char *p)
1940 hashval = ((unsigned char) *p) << 4;
1941 while (*p && *p != '=')
1942 hashval += (unsigned char) *p++;
1943 return &vartab[hashval % VTABSIZE];
1947 vpcmp(const void *a, const void *b)
1949 return varcmp(*(const char **)a, *(const char **)b);
1953 * This routine initializes the builtin variables.
1963 * PS1 depends on uid
1965 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1966 vps1.text = "PS1=\\w \\$ ";
1969 vps1.text = "PS1=# ";
1972 end = vp + ARRAY_SIZE(varinit);
1974 vpp = hashvar(vp->text);
1977 } while (++vp < end);
1980 static struct var **
1981 findvar(struct var **vpp, const char *name)
1983 for (; *vpp; vpp = &(*vpp)->next) {
1984 if (varequal((*vpp)->text, name)) {
1992 * Find the value of a variable. Returns NULL if not set.
1995 lookupvar(const char *name)
1999 v = *findvar(hashvar(name), name);
2001 #if ENABLE_ASH_RANDOM_SUPPORT
2003 * Dynamic variables are implemented roughly the same way they are
2004 * in bash. Namely, they're "special" so long as they aren't unset.
2005 * As soon as they're unset, they're no longer dynamic, and dynamic
2006 * lookup will no longer happen at that point. -- PFM.
2008 if ((v->flags & VDYNAMIC))
2011 if (!(v->flags & VUNSET))
2012 return strchrnul(v->text, '=') + 1;
2018 * Search the environment of a builtin command.
2021 bltinlookup(const char *name)
2025 for (sp = cmdenviron; sp; sp = sp->next) {
2026 if (varequal(sp->text, name))
2027 return strchrnul(sp->text, '=') + 1;
2029 return lookupvar(name);
2033 * Same as setvar except that the variable and value are passed in
2034 * the first argument as name=value. Since the first argument will
2035 * be actually stored in the table, it should not be a string that
2037 * Called with interrupts off.
2040 setvareq(char *s, int flags)
2042 struct var *vp, **vpp;
2045 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2046 vp = *findvar(vpp, s);
2048 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2051 if (flags & VNOSAVE)
2054 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2060 if (vp->func && (flags & VNOFUNC) == 0)
2061 (*vp->func)(strchrnul(s, '=') + 1);
2063 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2064 free((char*)vp->text);
2066 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2071 vp = ckzalloc(sizeof(*vp));
2073 /*vp->func = NULL; - ckzalloc did it */
2076 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2083 * Set the value of a variable. The flags argument is ored with the
2084 * flags of the variable. If val is NULL, the variable is unset.
2087 setvar(const char *name, const char *val, int flags)
2094 q = endofname(name);
2095 p = strchrnul(q, '=');
2097 if (!namelen || p != q)
2098 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2103 vallen = strlen(val);
2106 nameeq = ckmalloc(namelen + vallen + 2);
2107 p = (char *)memcpy(nameeq, name, namelen) + namelen;
2110 p = (char *)memcpy(p, val, vallen) + vallen;
2113 setvareq(nameeq, flags | VNOSAVE);
2117 #if ENABLE_ASH_GETOPTS
2119 * Safe version of setvar, returns 1 on success 0 on failure.
2122 setvarsafe(const char *name, const char *val, int flags)
2125 volatile int saveint;
2126 struct jmploc *volatile savehandler = exception_handler;
2127 struct jmploc jmploc;
2130 if (setjmp(jmploc.loc))
2133 exception_handler = &jmploc;
2134 setvar(name, val, flags);
2137 exception_handler = savehandler;
2138 RESTORE_INT(saveint);
2144 * Unset the specified variable.
2147 unsetvar(const char *s)
2153 vpp = findvar(hashvar(s), s);
2157 int flags = vp->flags;
2160 if (flags & VREADONLY)
2162 #if ENABLE_ASH_RANDOM_SUPPORT
2163 vp->flags &= ~VDYNAMIC;
2167 if ((flags & VSTRFIXED) == 0) {
2169 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2170 free((char*)vp->text);
2176 vp->flags &= ~VEXPORT;
2186 * Process a linked list of variable assignments.
2189 listsetvar(struct strlist *list_set_var, int flags)
2191 struct strlist *lp = list_set_var;
2197 setvareq(lp->text, flags);
2204 * Generate a list of variables satisfying the given conditions.
2207 listvars(int on, int off, char ***end)
2218 for (vp = *vpp; vp; vp = vp->next) {
2219 if ((vp->flags & mask) == on) {
2220 if (ep == stackstrend())
2221 ep = growstackstr();
2222 *ep++ = (char *) vp->text;
2225 } while (++vpp < vartab + VTABSIZE);
2226 if (ep == stackstrend())
2227 ep = growstackstr();
2231 return grabstackstr(ep);
2235 /* ============ Path search helper
2237 * The variable path (passed by reference) should be set to the start
2238 * of the path before the first call; padvance will update
2239 * this value as it proceeds. Successive calls to padvance will return
2240 * the possible path expansions in sequence. If an option (indicated by
2241 * a percent sign) appears in the path entry then the global variable
2242 * pathopt will be set to point to it; otherwise pathopt will be set to
2245 static const char *pathopt; /* set by padvance */
2248 padvance(const char **path, const char *name)
2258 for (p = start; *p && *p != ':' && *p != '%'; p++)
2260 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2261 while (stackblocksize() < len)
2265 memcpy(q, start, p - start);
2273 while (*p && *p != ':')
2280 return stalloc(len);
2284 /* ============ Prompt */
2286 static smallint doprompt; /* if set, prompt the user */
2287 static smallint needprompt; /* true if interactive and at start of line */
2289 #if ENABLE_FEATURE_EDITING
2290 static line_input_t *line_input_state;
2291 static const char *cmdedit_prompt;
2293 putprompt(const char *s)
2295 if (ENABLE_ASH_EXPAND_PRMT) {
2296 free((char*)cmdedit_prompt);
2297 cmdedit_prompt = ckstrdup(s);
2304 putprompt(const char *s)
2310 #if ENABLE_ASH_EXPAND_PRMT
2311 /* expandstr() needs parsing machinery, so it is far away ahead... */
2312 static const char *expandstr(const char *ps);
2314 #define expandstr(s) s
2318 setprompt(int whichprompt)
2321 #if ENABLE_ASH_EXPAND_PRMT
2322 struct stackmark smark;
2327 switch (whichprompt) {
2337 #if ENABLE_ASH_EXPAND_PRMT
2338 setstackmark(&smark);
2339 stalloc(stackblocksize());
2341 putprompt(expandstr(prompt));
2342 #if ENABLE_ASH_EXPAND_PRMT
2343 popstackmark(&smark);
2348 /* ============ The cd and pwd commands */
2350 #define CD_PHYSICAL 1
2353 static int docd(const char *, int);
2362 while ((i = nextopt("LP"))) {
2364 flags ^= CD_PHYSICAL;
2373 * Update curdir (the name of the current directory) in response to a
2377 updatepwd(const char *dir)
2384 cdcomppath = ststrdup(dir);
2387 if (curdir == nullstr)
2389 new = stack_putstr(curdir, new);
2391 new = makestrspace(strlen(dir) + 2, new);
2392 lim = (char *)stackblock() + 1;
2396 if (new > lim && *lim == '/')
2401 if (dir[1] == '/' && dir[2] != '/') {
2407 p = strtok(cdcomppath, "/");
2411 if (p[1] == '.' && p[2] == '\0') {
2423 new = stack_putstr(p, new);
2431 return stackblock();
2435 * Find out what the current directory is. If we already know the current
2436 * directory, this routine returns immediately.
2441 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2442 return dir ? dir : nullstr;
2446 setpwd(const char *val, int setold)
2450 oldcur = dir = curdir;
2453 setvar("OLDPWD", oldcur, VEXPORT);
2456 if (physdir != nullstr) {
2457 if (physdir != oldcur)
2461 if (oldcur == val || !val) {
2467 dir = ckstrdup(val);
2468 if (oldcur != dir && oldcur != nullstr) {
2473 setvar("PWD", dir, VEXPORT);
2476 static void hashcd(void);
2479 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2480 * know that the current directory has changed.
2483 docd(const char *dest, int flags)
2485 const char *dir = 0;
2488 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2491 if (!(flags & CD_PHYSICAL)) {
2492 dir = updatepwd(dest);
2507 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2519 dest = bltinlookup(homestr);
2520 else if (LONE_DASH(dest)) {
2521 dest = bltinlookup("OLDPWD");
2543 path = bltinlookup("CDPATH");
2552 p = padvance(&path, dest);
2553 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2557 if (!docd(p, flags))
2562 ash_msg_and_raise_error("can't cd to %s", dest);
2565 if (flags & CD_PRINT)
2566 out1fmt(snlfmt, curdir);
2571 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2574 const char *dir = curdir;
2578 if (physdir == nullstr)
2582 out1fmt(snlfmt, dir);
2587 /* ============ ... */
2590 #define IBUFSIZ COMMON_BUFSIZE
2591 /* buffer for top level input file */
2592 #define basebuf bb_common_bufsiz1
2594 /* Syntax classes */
2595 #define CWORD 0 /* character is nothing special */
2596 #define CNL 1 /* newline character */
2597 #define CBACK 2 /* a backslash character */
2598 #define CSQUOTE 3 /* single quote */
2599 #define CDQUOTE 4 /* double quote */
2600 #define CENDQUOTE 5 /* a terminating quote */
2601 #define CBQUOTE 6 /* backwards single quote */
2602 #define CVAR 7 /* a dollar sign */
2603 #define CENDVAR 8 /* a '}' character */
2604 #define CLP 9 /* a left paren in arithmetic */
2605 #define CRP 10 /* a right paren in arithmetic */
2606 #define CENDFILE 11 /* end of file */
2607 #define CCTL 12 /* like CWORD, except it must be escaped */
2608 #define CSPCL 13 /* these terminate a word */
2609 #define CIGN 14 /* character should be ignored */
2611 #if ENABLE_ASH_ALIAS
2615 #define PEOA_OR_PEOF PEOA
2619 #define PEOA_OR_PEOF PEOF
2622 /* number syntax index */
2623 #define BASESYNTAX 0 /* not in quotes */
2624 #define DQSYNTAX 1 /* in double quotes */
2625 #define SQSYNTAX 2 /* in single quotes */
2626 #define ARISYNTAX 3 /* in arithmetic */
2627 #define PSSYNTAX 4 /* prompt */
2629 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
2630 #define USE_SIT_FUNCTION
2633 #if ENABLE_SH_MATH_SUPPORT
2634 static const char S_I_T[][4] = {
2635 #if ENABLE_ASH_ALIAS
2636 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
2638 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2639 { CNL, CNL, CNL, CNL }, /* 2, \n */
2640 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2641 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2642 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2643 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2644 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2645 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2646 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2647 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2648 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
2649 #ifndef USE_SIT_FUNCTION
2650 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2651 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2652 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2656 static const char S_I_T[][3] = {
2657 #if ENABLE_ASH_ALIAS
2658 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
2660 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2661 { CNL, CNL, CNL }, /* 2, \n */
2662 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2663 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2664 { CVAR, CVAR, CWORD }, /* 5, $ */
2665 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2666 { CSPCL, CWORD, CWORD }, /* 7, ( */
2667 { CSPCL, CWORD, CWORD }, /* 8, ) */
2668 { CBACK, CBACK, CCTL }, /* 9, \ */
2669 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2670 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
2671 #ifndef USE_SIT_FUNCTION
2672 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2673 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2674 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2677 #endif /* SH_MATH_SUPPORT */
2679 #ifdef USE_SIT_FUNCTION
2682 SIT(int c, int syntax)
2684 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2685 #if ENABLE_ASH_ALIAS
2686 static const char syntax_index_table[] ALIGN1 = {
2687 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2688 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2689 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2693 static const char syntax_index_table[] ALIGN1 = {
2694 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2695 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2696 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2703 if (c == PEOF) /* 2^8+2 */
2705 #if ENABLE_ASH_ALIAS
2706 if (c == PEOA) /* 2^8+1 */
2711 if ((unsigned char)c >= (unsigned char)(CTLESC)
2712 && (unsigned char)c <= (unsigned char)(CTLQUOTEMARK)
2716 s = strchrnul(spec_symbls, c);
2719 indx = syntax_index_table[s - spec_symbls];
2720 return S_I_T[indx][syntax];
2723 #else /* !USE_SIT_FUNCTION */
2725 #if ENABLE_ASH_ALIAS
2726 #define CSPCL_CIGN_CIGN_CIGN 0
2727 #define CSPCL_CWORD_CWORD_CWORD 1
2728 #define CNL_CNL_CNL_CNL 2
2729 #define CWORD_CCTL_CCTL_CWORD 3
2730 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2731 #define CVAR_CVAR_CWORD_CVAR 5
2732 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2733 #define CSPCL_CWORD_CWORD_CLP 7
2734 #define CSPCL_CWORD_CWORD_CRP 8
2735 #define CBACK_CBACK_CCTL_CBACK 9
2736 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2737 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2738 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2739 #define CWORD_CWORD_CWORD_CWORD 13
2740 #define CCTL_CCTL_CCTL_CCTL 14
2742 #define CSPCL_CWORD_CWORD_CWORD 0
2743 #define CNL_CNL_CNL_CNL 1
2744 #define CWORD_CCTL_CCTL_CWORD 2
2745 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2746 #define CVAR_CVAR_CWORD_CVAR 4
2747 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2748 #define CSPCL_CWORD_CWORD_CLP 6
2749 #define CSPCL_CWORD_CWORD_CRP 7
2750 #define CBACK_CBACK_CCTL_CBACK 8
2751 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2752 #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2753 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2754 #define CWORD_CWORD_CWORD_CWORD 12
2755 #define CCTL_CCTL_CCTL_CCTL 13
2758 static const char syntax_index_table[258] = {
2759 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2760 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2761 #if ENABLE_ASH_ALIAS
2762 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2764 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2765 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2766 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2767 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2768 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2769 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2770 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2771 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2772 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2773 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2774 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2775 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2776 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2777 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2778 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2779 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2780 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2781 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2782 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2793 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2794 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2795 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2796 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2797 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2798 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2799 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2800 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2801 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2802 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2803 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2804 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2805 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2806 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2807 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2808 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2809 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2810 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2811 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2812 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2813 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2814 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2815 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2816 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2817 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2818 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2819 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2820 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2821 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2822 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2823 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2824 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2825 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2826 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2827 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2828 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2829 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2830 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2831 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2832 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2833 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2834 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2835 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2836 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2837 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2838 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2839 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2840 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2841 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2842 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2902 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2903 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2925 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2926 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2927 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2929 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2931 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2932 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2933 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2934 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2935 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2937 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2938 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2939 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2940 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2951 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2952 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2953 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2954 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2955 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2956 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2984 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2985 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2986 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2989 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3006 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3007 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3008 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3009 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3010 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3011 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3012 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3013 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3014 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3015 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3016 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3017 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3018 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3019 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
3022 #define SIT(c, syntax) (S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax])
3024 #endif /* USE_SIT_FUNCTION */
3027 /* ============ Alias handling */
3029 #if ENABLE_ASH_ALIAS
3031 #define ALIASINUSE 1
3042 static struct alias **atab; // [ATABSIZE];
3043 #define INIT_G_alias() do { \
3044 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3048 static struct alias **
3049 __lookupalias(const char *name) {
3050 unsigned int hashval;
3057 ch = (unsigned char)*p;
3061 ch = (unsigned char)*++p;
3063 app = &atab[hashval % ATABSIZE];
3065 for (; *app; app = &(*app)->next) {
3066 if (strcmp(name, (*app)->name) == 0) {
3074 static struct alias *
3075 lookupalias(const char *name, int check)
3077 struct alias *ap = *__lookupalias(name);
3079 if (check && ap && (ap->flag & ALIASINUSE))
3084 static struct alias *
3085 freealias(struct alias *ap)
3089 if (ap->flag & ALIASINUSE) {
3090 ap->flag |= ALIASDEAD;
3102 setalias(const char *name, const char *val)
3104 struct alias *ap, **app;
3106 app = __lookupalias(name);
3110 if (!(ap->flag & ALIASINUSE)) {
3113 ap->val = ckstrdup(val);
3114 ap->flag &= ~ALIASDEAD;
3117 ap = ckzalloc(sizeof(struct alias));
3118 ap->name = ckstrdup(name);
3119 ap->val = ckstrdup(val);
3120 /*ap->flag = 0; - ckzalloc did it */
3121 /*ap->next = NULL;*/
3128 unalias(const char *name)
3132 app = __lookupalias(name);
3136 *app = freealias(*app);
3147 struct alias *ap, **app;
3151 for (i = 0; i < ATABSIZE; i++) {
3153 for (ap = *app; ap; ap = *app) {
3154 *app = freealias(*app);
3164 printalias(const struct alias *ap)
3166 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3170 * TODO - sort output
3173 aliascmd(int argc UNUSED_PARAM, char **argv)
3182 for (i = 0; i < ATABSIZE; i++) {
3183 for (ap = atab[i]; ap; ap = ap->next) {
3189 while ((n = *++argv) != NULL) {
3190 v = strchr(n+1, '=');
3191 if (v == NULL) { /* n+1: funny ksh stuff */
3192 ap = *__lookupalias(n);
3194 fprintf(stderr, "%s: %s not found\n", "alias", n);
3208 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3212 while ((i = nextopt("a")) != '\0') {
3218 for (i = 0; *argptr; argptr++) {
3219 if (unalias(*argptr)) {
3220 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3228 #endif /* ASH_ALIAS */
3231 /* ============ jobs.c */
3233 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3236 #define FORK_NOJOB 2
3238 /* mode flags for showjob(s) */
3239 #define SHOW_PGID 0x01 /* only show pgid - for jobs -p */
3240 #define SHOW_PID 0x04 /* include process pid */
3241 #define SHOW_CHANGED 0x08 /* only jobs whose state has changed */
3244 * A job structure contains information about a job. A job is either a
3245 * single process or a set of processes contained in a pipeline. In the
3246 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3251 pid_t pid; /* process id */
3252 int status; /* last process status from wait() */
3253 char *cmd; /* text of command being run */
3257 struct procstat ps0; /* status of process */
3258 struct procstat *ps; /* status or processes when more than one */
3260 int stopstatus; /* status of a stopped job */
3263 nprocs: 16, /* number of processes */
3265 #define JOBRUNNING 0 /* at least one proc running */
3266 #define JOBSTOPPED 1 /* all procs are stopped */
3267 #define JOBDONE 2 /* all procs are completed */
3269 sigint: 1, /* job was killed by SIGINT */
3270 jobctl: 1, /* job running under job control */
3272 waited: 1, /* true if this entry has been waited for */
3273 used: 1, /* true if this entry is in used */
3274 changed: 1; /* true if status has changed */
3275 struct job *prev_job; /* previous job */
3278 static struct job *makejob(/*union node *,*/ int);
3280 #define forkshell(job, node, mode) forkshell(job, mode)
3282 static int forkshell(struct job *, union node *, int);
3283 static int waitforjob(struct job *);
3286 enum { doing_jobctl = 0 };
3287 #define setjobctl(on) do {} while (0)
3289 static smallint doing_jobctl; //references:8
3290 static void setjobctl(int);
3297 ignoresig(int signo)
3299 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3300 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3301 /* No, need to do it */
3302 signal(signo, SIG_IGN);
3304 sigmode[signo - 1] = S_HARD_IGN;
3308 * Signal handler. Only one usage site - in setsignal()
3313 gotsig[signo - 1] = 1;
3315 if (/* exsig || */ (signo == SIGINT && !trap[SIGINT])) {
3318 raise_interrupt(); /* does not return */
3327 * Set the signal handler for the specified signal. The routine figures
3328 * out what it should be set to.
3331 setsignal(int signo)
3334 char cur_act, new_act;
3335 struct sigaction act;
3339 if (t != NULL) { /* trap for this sig is set */
3341 if (t[0] == '\0') /* trap is "": ignore this sig */
3345 if (rootshell && new_act == S_DFL) {
3348 if (iflag || minusc || sflag == 0)
3357 * "In all cases, bash ignores SIGQUIT. Non-builtin
3358 * commands run by bash have signal handlers
3359 * set to the values inherited by the shell
3360 * from its parent". */
3376 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3377 //whereas we have to restore it to what shell got on entry
3378 //from the parent. See comment above
3380 t = &sigmode[signo - 1];
3383 /* current setting is not yet known */
3384 if (sigaction(signo, NULL, &act)) {
3385 /* pretend it worked; maybe we should give a warning,
3386 * but other shells don't. We don't alter sigmode,
3387 * so we retry every time.
3388 * btw, in Linux it never fails. --vda */
3391 if (act.sa_handler == SIG_IGN) {
3392 cur_act = S_HARD_IGN;
3394 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3396 cur_act = S_IGN; /* don't hard ignore these */
3400 if (cur_act == S_HARD_IGN || cur_act == new_act)
3403 act.sa_handler = SIG_DFL;
3406 act.sa_handler = onsig;
3407 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3408 sigfillset(&act.sa_mask); /* ditto */
3411 act.sa_handler = SIG_IGN;
3414 sigaction_set(signo, &act);
3419 /* mode flags for set_curjob */
3420 #define CUR_DELETE 2
3421 #define CUR_RUNNING 1
3422 #define CUR_STOPPED 0
3424 /* mode flags for dowait */
3425 #define DOWAIT_NONBLOCK WNOHANG
3426 #define DOWAIT_BLOCK 0
3429 /* pgrp of shell on invocation */
3430 static int initialpgrp; //references:2
3431 static int ttyfd = -1; //5
3434 static struct job *jobtab; //5
3436 static unsigned njobs; //4
3438 static struct job *curjob; //lots
3439 /* number of presumed living untracked jobs */
3440 static int jobless; //4
3443 set_curjob(struct job *jp, unsigned mode)
3446 struct job **jpp, **curp;
3448 /* first remove from list */
3449 jpp = curp = &curjob;
3454 jpp = &jp1->prev_job;
3456 *jpp = jp1->prev_job;
3458 /* Then re-insert in correct position */
3466 /* job being deleted */
3469 /* newly created job or backgrounded job,
3470 put after all stopped jobs. */
3474 if (!jp1 || jp1->state != JOBSTOPPED)
3477 jpp = &jp1->prev_job;
3483 /* newly stopped job - becomes curjob */
3484 jp->prev_job = *jpp;
3492 jobno(const struct job *jp)
3494 return jp - jobtab + 1;
3499 * Convert a job name to a job structure.
3502 #define getjob(name, getctl) getjob(name)
3505 getjob(const char *name, int getctl)
3509 const char *err_msg = "No such job: %s";
3513 char *(*match)(const char *, const char *);
3528 if (c == '+' || c == '%') {
3530 err_msg = "No current job";
3536 err_msg = "No previous job";
3545 // TODO: number() instead? It does error checking...
3548 jp = jobtab + num - 1;
3565 if (match(jp->ps[0].cmd, p)) {
3569 err_msg = "%s: ambiguous";
3576 err_msg = "job %s not created under job control";
3577 if (getctl && jp->jobctl == 0)
3582 ash_msg_and_raise_error(err_msg, name);
3586 * Mark a job structure as unused.
3589 freejob(struct job *jp)
3591 struct procstat *ps;
3595 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3596 if (ps->cmd != nullstr)
3599 if (jp->ps != &jp->ps0)
3602 set_curjob(jp, CUR_DELETE);
3608 xtcsetpgrp(int fd, pid_t pgrp)
3610 if (tcsetpgrp(fd, pgrp))
3611 ash_msg_and_raise_error("can't set tty process group (%m)");
3615 * Turn job control on and off.
3617 * Note: This code assumes that the third arg to ioctl is a character
3618 * pointer, which is true on Berkeley systems but not System V. Since
3619 * System V doesn't have job control yet, this isn't a problem now.
3621 * Called with interrupts off.
3629 if (on == doing_jobctl || rootshell == 0)
3633 ofd = fd = open(_PATH_TTY, O_RDWR);
3635 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3636 * That sometimes helps to acquire controlling tty.
3637 * Obviously, a workaround for bugs when someone
3638 * failed to provide a controlling tty to bash! :) */
3644 fd = fcntl(fd, F_DUPFD, 10);
3649 /* fd is a tty at this point */
3650 close_on_exec_on(fd);
3651 do { /* while we are in the background */
3652 pgrp = tcgetpgrp(fd);
3655 ash_msg("can't access tty; job control turned off");
3659 if (pgrp == getpgrp())
3670 xtcsetpgrp(fd, pgrp);
3672 /* turning job control off */
3675 /* was xtcsetpgrp, but this can make exiting ash
3676 * loop forever if pty is already deleted */
3677 tcsetpgrp(fd, pgrp);
3692 killcmd(int argc, char **argv)
3695 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3697 if (argv[i][0] == '%') {
3698 struct job *jp = getjob(argv[i], 0);
3699 unsigned pid = jp->ps[0].pid;
3700 /* Enough space for ' -NNN<nul>' */
3701 argv[i] = alloca(sizeof(int)*3 + 3);
3702 /* kill_main has matching code to expect
3703 * leading space. Needed to not confuse
3704 * negative pids with "kill -SIGNAL_NO" syntax */
3705 sprintf(argv[i], " -%u", pid);
3707 } while (argv[++i]);
3709 return kill_main(argc, argv);
3713 showpipe(struct job *jp, FILE *out)
3715 struct procstat *sp;
3716 struct procstat *spend;
3718 spend = jp->ps + jp->nprocs;
3719 for (sp = jp->ps + 1; sp < spend; sp++)
3720 fprintf(out, " | %s", sp->cmd);
3721 outcslow('\n', out);
3722 flush_stdout_stderr();
3727 restartjob(struct job *jp, int mode)
3729 struct procstat *ps;
3735 if (jp->state == JOBDONE)
3737 jp->state = JOBRUNNING;
3739 if (mode == FORK_FG)
3740 xtcsetpgrp(ttyfd, pgid);
3741 killpg(pgid, SIGCONT);
3745 if (WIFSTOPPED(ps->status)) {
3751 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3757 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3764 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3769 jp = getjob(*argv, 1);
3770 if (mode == FORK_BG) {
3771 set_curjob(jp, CUR_RUNNING);
3772 fprintf(out, "[%d] ", jobno(jp));
3774 outstr(jp->ps->cmd, out);
3776 retval = restartjob(jp, mode);
3777 } while (*argv && *++argv);
3783 sprint_status(char *s, int status, int sigonly)
3789 if (!WIFEXITED(status)) {
3791 if (WIFSTOPPED(status))
3792 st = WSTOPSIG(status);
3795 st = WTERMSIG(status);
3797 if (st == SIGINT || st == SIGPIPE)
3800 if (WIFSTOPPED(status))
3805 col = fmtstr(s, 32, strsignal(st));
3806 if (WCOREDUMP(status)) {
3807 col += fmtstr(s + col, 16, " (core dumped)");
3809 } else if (!sigonly) {
3810 st = WEXITSTATUS(status);
3812 col = fmtstr(s, 16, "Done(%d)", st);
3814 col = fmtstr(s, 16, "Done");
3821 dowait(int wait_flags, struct job *job)
3826 struct job *thisjob;
3829 TRACE(("dowait(0x%x) called\n", wait_flags));
3831 /* Do a wait system call. If job control is compiled in, we accept
3832 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3833 * NB: _not_ safe_waitpid, we need to detect EINTR */
3834 pid = waitpid(-1, &status,
3835 (doing_jobctl ? (wait_flags | WUNTRACED) : wait_flags));
3836 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3837 pid, status, errno, strerror(errno)));
3843 for (jp = curjob; jp; jp = jp->prev_job) {
3844 struct procstat *sp;
3845 struct procstat *spend;
3846 if (jp->state == JOBDONE)
3849 spend = jp->ps + jp->nprocs;
3852 if (sp->pid == pid) {
3853 TRACE(("Job %d: changing status of proc %d "
3854 "from 0x%x to 0x%x\n",
3855 jobno(jp), pid, sp->status, status));
3856 sp->status = status;
3859 if (sp->status == -1)
3862 if (state == JOBRUNNING)
3864 if (WIFSTOPPED(sp->status)) {
3865 jp->stopstatus = sp->status;
3869 } while (++sp < spend);
3874 if (!WIFSTOPPED(status))
3880 if (state != JOBRUNNING) {
3881 thisjob->changed = 1;
3883 if (thisjob->state != state) {
3884 TRACE(("Job %d: changing state from %d to %d\n",
3885 jobno(thisjob), thisjob->state, state));
3886 thisjob->state = state;
3888 if (state == JOBSTOPPED) {
3889 set_curjob(thisjob, CUR_STOPPED);
3898 if (thisjob && thisjob == job) {
3902 len = sprint_status(s, status, 1);
3913 blocking_wait_with_raise_on_sig(struct job *job)
3915 pid_t pid = dowait(DOWAIT_BLOCK, job);
3916 if (pid <= 0 && pendingsig)
3917 raise_exception(EXSIG);
3923 showjob(FILE *out, struct job *jp, int mode)
3925 struct procstat *ps;
3926 struct procstat *psend;
3933 if (mode & SHOW_PGID) {
3934 /* just output process (group) id of pipeline */
3935 fprintf(out, "%d\n", ps->pid);
3939 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3944 else if (curjob && jp == curjob->prev_job)
3947 if (mode & SHOW_PID)
3948 col += fmtstr(s + col, 16, "%d ", ps->pid);
3950 psend = ps + jp->nprocs;
3952 if (jp->state == JOBRUNNING) {
3953 strcpy(s + col, "Running");
3954 col += sizeof("Running") - 1;
3956 int status = psend[-1].status;
3957 if (jp->state == JOBSTOPPED)
3958 status = jp->stopstatus;
3959 col += sprint_status(s + col, status, 0);
3965 /* for each process */
3966 col = fmtstr(s, 48, " |\n%*c%d ", indent_col, ' ', ps->pid) - 3;
3968 fprintf(out, "%s%*c%s",
3969 s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
3971 if (!(mode & SHOW_PID)) {
3975 if (++ps == psend) {
3976 outcslow('\n', out);
3983 if (jp->state == JOBDONE) {
3984 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3990 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3991 * statuses have changed since the last call to showjobs.
3994 showjobs(FILE *out, int mode)
3998 TRACE(("showjobs(%x) called\n", mode));
4000 /* Handle all finished jobs */
4001 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4004 for (jp = curjob; jp; jp = jp->prev_job) {
4005 if (!(mode & SHOW_CHANGED) || jp->changed) {
4006 showjob(out, jp, mode);
4012 jobscmd(int argc UNUSED_PARAM, char **argv)
4017 while ((m = nextopt("lp"))) {
4027 showjob(stdout, getjob(*argv,0), mode);
4030 showjobs(stdout, mode);
4037 getstatus(struct job *job)
4042 status = job->ps[job->nprocs - 1].status;
4043 retval = WEXITSTATUS(status);
4044 if (!WIFEXITED(status)) {
4046 retval = WSTOPSIG(status);
4047 if (!WIFSTOPPED(status))
4050 /* XXX: limits number of signals */
4051 retval = WTERMSIG(status);
4053 if (retval == SIGINT)
4059 TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
4060 jobno(job), job->nprocs, status, retval));
4065 waitcmd(int argc UNUSED_PARAM, char **argv)
4074 raise_exception(EXSIG);
4081 /* wait for all jobs */
4085 if (!jp) /* no running procs */
4087 if (jp->state == JOBRUNNING)
4093 * "When bash is waiting for an asynchronous command via
4094 * the wait builtin, the reception of a signal for which a trap
4095 * has been set will cause the wait builtin to return immediately
4096 * with an exit status greater than 128, immediately after which
4097 * the trap is executed."
4098 * Do we do it that way? */
4099 blocking_wait_with_raise_on_sig(NULL);
4105 if (**argv != '%') {
4106 pid_t pid = number(*argv);
4111 if (job->ps[job->nprocs - 1].pid == pid)
4113 job = job->prev_job;
4116 job = getjob(*argv, 0);
4117 /* loop until process terminated or stopped */
4118 while (job->state == JOBRUNNING)
4119 blocking_wait_with_raise_on_sig(NULL);
4121 retval = getstatus(job);
4134 struct job *jp, *jq;
4136 len = njobs * sizeof(*jp);
4138 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4140 offset = (char *)jp - (char *)jq;
4142 /* Relocate pointers */
4145 jq = (struct job *)((char *)jq + l);
4149 #define joff(p) ((struct job *)((char *)(p) + l))
4150 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4151 if (joff(jp)->ps == &jq->ps0)
4152 jmove(joff(jp)->ps);
4153 if (joff(jp)->prev_job)
4154 jmove(joff(jp)->prev_job);
4164 jp = (struct job *)((char *)jp + len);
4168 } while (--jq >= jp);
4173 * Return a new job structure.
4174 * Called with interrupts off.
4177 makejob(/*union node *node,*/ int nprocs)
4182 for (i = njobs, jp = jobtab; ; jp++) {
4189 if (jp->state != JOBDONE || !jp->waited)
4198 memset(jp, 0, sizeof(*jp));
4200 /* jp->jobctl is a bitfield.
4201 * "jp->jobctl |= jobctl" likely to give awful code */
4205 jp->prev_job = curjob;
4210 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4212 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4219 * Return a string identifying a command (to be printed by the
4222 static char *cmdnextc;
4225 cmdputs(const char *s)
4227 static const char vstype[VSTYPE + 1][3] = {
4228 "", "}", "-", "+", "?", "=",
4229 "%", "%%", "#", "##"
4230 USE_ASH_BASH_COMPAT(, ":", "/", "//")
4233 const char *p, *str;
4234 char c, cc[2] = " ";
4239 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4241 while ((c = *p++) != 0) {
4249 if ((subtype & VSTYPE) == VSLENGTH)
4253 if (!(subtype & VSQUOTE) == !(quoted & 1))
4259 str = "\"}" + !(quoted & 1);
4266 case CTLBACKQ+CTLQUOTE:
4269 #if ENABLE_SH_MATH_SUPPORT
4284 if ((subtype & VSTYPE) != VSNORMAL)
4286 str = vstype[subtype & VSTYPE];
4287 if (subtype & VSNUL)
4296 /* These can only happen inside quotes */
4309 while ((c = *str++)) {
4314 USTPUTC('"', nextc);
4320 /* cmdtxt() and cmdlist() call each other */
4321 static void cmdtxt(union node *n);
4324 cmdlist(union node *np, int sep)
4326 for (; np; np = np->narg.next) {
4330 if (sep && np->narg.next)
4336 cmdtxt(union node *n)
4339 struct nodelist *lp;
4350 lp = n->npipe.cmdlist;
4368 cmdtxt(n->nbinary.ch1);
4384 cmdtxt(n->nif.test);
4387 if (n->nif.elsepart) {
4390 n = n->nif.elsepart;
4406 cmdtxt(n->nbinary.ch1);
4416 cmdputs(n->nfor.var);
4418 cmdlist(n->nfor.args, 1);
4423 cmdputs(n->narg.text);
4427 cmdlist(n->ncmd.args, 1);
4428 cmdlist(n->ncmd.redirect, 0);
4441 cmdputs(n->ncase.expr->narg.text);
4443 for (np = n->ncase.cases; np; np = np->nclist.next) {
4444 cmdtxt(np->nclist.pattern);
4446 cmdtxt(np->nclist.body);
4460 #if ENABLE_ASH_BASH_COMPAT
4475 cmdputs(utoa(n->nfile.fd));
4477 if (n->type == NTOFD || n->type == NFROMFD) {
4478 cmdputs(utoa(n->ndup.dupfd));
4487 commandtext(union node *n)
4491 STARTSTACKSTR(cmdnextc);
4493 name = stackblock();
4494 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4495 name, cmdnextc, cmdnextc));
4496 return ckstrdup(name);
4501 * Fork off a subshell. If we are doing job control, give the subshell its
4502 * own process group. Jp is a job structure that the job is to be added to.
4503 * N is the command that will be evaluated by the child. Both jp and n may
4504 * be NULL. The mode parameter can be one of the following:
4505 * FORK_FG - Fork off a foreground process.
4506 * FORK_BG - Fork off a background process.
4507 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4508 * process group even if job control is on.
4510 * When job control is turned off, background processes have their standard
4511 * input redirected to /dev/null (except for the second and later processes
4514 * Called with interrupts off.
4517 * Clear traps on a fork.
4524 for (tp = trap; tp < &trap[NSIG]; tp++) {
4525 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4530 setsignal(tp - trap);
4536 /* Lives far away from here, needed for forkchild */
4537 static void closescript(void);
4539 /* Called after fork(), in child */
4541 forkchild(struct job *jp, /*union node *n,*/ int mode)
4545 TRACE(("Child shell %d\n", getpid()));
4549 /* man bash: "Non-builtin commands run by bash have signal handlers
4550 * set to the values inherited by the shell from its parent".
4551 * Do we do it correctly? */
4556 /* do job control only in root shell */
4558 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4561 if (jp->nprocs == 0)
4564 pgrp = jp->ps[0].pid;
4565 /* this can fail because we are doing it in the parent also */
4567 if (mode == FORK_FG)
4568 xtcsetpgrp(ttyfd, pgrp);
4573 if (mode == FORK_BG) {
4574 /* man bash: "When job control is not in effect,
4575 * asynchronous commands ignore SIGINT and SIGQUIT" */
4578 if (jp->nprocs == 0) {
4580 if (open(bb_dev_null, O_RDONLY) != 0)
4581 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4585 if (iflag) { /* why if iflag only? */
4590 * "In all cases, bash ignores SIGQUIT. Non-builtin
4591 * commands run by bash have signal handlers
4592 * set to the values inherited by the shell
4594 * Take care of the second rule: */
4597 for (jp = curjob; jp; jp = jp->prev_job)
4602 /* Called after fork(), in parent */
4604 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4607 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4609 TRACE(("In parent shell: child = %d\n", pid));
4611 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4617 if (mode != FORK_NOJOB && jp->jobctl) {
4620 if (jp->nprocs == 0)
4623 pgrp = jp->ps[0].pid;
4624 /* This can fail because we are doing it in the child also */
4628 if (mode == FORK_BG) {
4629 backgndpid = pid; /* set $! */
4630 set_curjob(jp, CUR_RUNNING);
4633 struct procstat *ps = &jp->ps[jp->nprocs++];
4638 if (doing_jobctl && n)
4639 ps->cmd = commandtext(n);
4645 forkshell(struct job *jp, union node *n, int mode)
4649 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4652 TRACE(("Fork failed, errno=%d", errno));
4655 ash_msg_and_raise_error("can't fork");
4658 forkchild(jp, /*n,*/ mode);
4660 forkparent(jp, n, mode, pid);
4665 * Wait for job to finish.
4667 * Under job control we have the problem that while a child process
4668 * is running interrupts generated by the user are sent to the child
4669 * but not to the shell. This means that an infinite loop started by
4670 * an interactive user may be hard to kill. With job control turned off,
4671 * an interactive user may place an interactive program inside a loop.
4672 * If the interactive program catches interrupts, the user doesn't want
4673 * these interrupts to also abort the loop. The approach we take here
4674 * is to have the shell ignore interrupt signals while waiting for a
4675 * foreground process to terminate, and then send itself an interrupt
4676 * signal if the child process was terminated by an interrupt signal.
4677 * Unfortunately, some programs want to do a bit of cleanup and then
4678 * exit on interrupt; unless these processes terminate themselves by
4679 * sending a signal to themselves (instead of calling exit) they will
4680 * confuse this approach.
4682 * Called with interrupts off.
4685 waitforjob(struct job *jp)
4689 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4692 while (jp->state == JOBRUNNING) {
4693 /* In non-interactive shells, we _can_ get
4694 * a keyboard signal here and be EINTRed,
4695 * but we just loop back, waiting for command to complete.
4698 * "If bash is waiting for a command to complete and receives
4699 * a signal for which a trap has been set, the trap
4700 * will not be executed until the command completes."
4702 * Reality is that even if trap is not set, bash
4703 * will not act on the signal until command completes.
4704 * Try this. sleep5intoff.c:
4705 * #include <signal.h>
4706 * #include <unistd.h>
4709 * sigemptyset(&set);
4710 * sigaddset(&set, SIGINT);
4711 * sigaddset(&set, SIGQUIT);
4712 * sigprocmask(SIG_BLOCK, &set, NULL);
4716 * $ bash -c './sleep5intoff; echo hi'
4717 * ^C^C^C^C <--- pressing ^C once a second
4719 * $ bash -c './sleep5intoff; echo hi'
4720 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4723 dowait(DOWAIT_BLOCK, jp);
4730 xtcsetpgrp(ttyfd, rootpid);
4732 * This is truly gross.
4733 * If we're doing job control, then we did a TIOCSPGRP which
4734 * caused us (the shell) to no longer be in the controlling
4735 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4736 * intuit from the subprocess exit status whether a SIGINT
4737 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4739 if (jp->sigint) /* TODO: do the same with all signals */
4740 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4742 if (jp->state == JOBDONE)
4749 * return 1 if there are stopped jobs, otherwise 0
4761 if (jp && jp->state == JOBSTOPPED) {
4762 out2str("You have stopped jobs.\n");
4771 /* ============ redir.c
4773 * Code for dealing with input/output redirection.
4776 #define EMPTY -2 /* marks an unused slot in redirtab */
4777 #define CLOSED -3 /* marks a slot of previously-closed fd */
4780 * Open a file in noclobber mode.
4781 * The code was copied from bash.
4784 noclobberopen(const char *fname)
4787 struct stat finfo, finfo2;
4790 * If the file exists and is a regular file, return an error
4793 r = stat(fname, &finfo);
4794 if (r == 0 && S_ISREG(finfo.st_mode)) {
4800 * If the file was not present (r != 0), make sure we open it
4801 * exclusively so that if it is created before we open it, our open
4802 * will fail. Make sure that we do not truncate an existing file.
4803 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4804 * file was not a regular file, we leave O_EXCL off.
4807 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4808 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4810 /* If the open failed, return the file descriptor right away. */
4815 * OK, the open succeeded, but the file may have been changed from a
4816 * non-regular file to a regular file between the stat and the open.
4817 * We are assuming that the O_EXCL open handles the case where FILENAME
4818 * did not exist and is symlinked to an existing file between the stat
4823 * If we can open it and fstat the file descriptor, and neither check
4824 * revealed that it was a regular file, and the file has not been
4825 * replaced, return the file descriptor.
4827 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4828 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4831 /* The file has been replaced. badness. */
4838 * Handle here documents. Normally we fork off a process to write the
4839 * data to a pipe. If the document is short, we can stuff the data in
4840 * the pipe without forking.
4842 /* openhere needs this forward reference */
4843 static void expandhere(union node *arg, int fd);
4845 openhere(union node *redir)
4851 ash_msg_and_raise_error("pipe call failed");
4852 if (redir->type == NHERE) {
4853 len = strlen(redir->nhere.doc->narg.text);
4854 if (len <= PIPE_BUF) {
4855 full_write(pip[1], redir->nhere.doc->narg.text, len);
4859 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4862 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4863 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4864 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4865 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4866 signal(SIGPIPE, SIG_DFL);
4867 if (redir->type == NHERE)
4868 full_write(pip[1], redir->nhere.doc->narg.text, len);
4870 expandhere(redir->nhere.doc, pip[1]);
4871 _exit(EXIT_SUCCESS);
4879 openredirect(union node *redir)
4884 switch (redir->nfile.type) {
4886 fname = redir->nfile.expfname;
4887 f = open(fname, O_RDONLY);
4892 fname = redir->nfile.expfname;
4893 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4898 #if ENABLE_ASH_BASH_COMPAT
4901 /* Take care of noclobber mode. */
4903 fname = redir->nfile.expfname;
4904 f = noclobberopen(fname);
4911 fname = redir->nfile.expfname;
4912 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4917 fname = redir->nfile.expfname;
4918 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4926 /* Fall through to eliminate warning. */
4927 /* Our single caller does this itself */
4934 f = openhere(redir);
4940 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4942 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
4946 * Copy a file descriptor to be >= to. Returns -1
4947 * if the source file descriptor is closed, EMPTY if there are no unused
4948 * file descriptors left.
4950 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
4951 * old code was doing close(to) prior to copyfd() to achieve the same */
4953 COPYFD_EXACT = (int)~(INT_MAX),
4954 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
4957 copyfd(int from, int to)
4961 if (to & COPYFD_EXACT) {
4962 to &= ~COPYFD_EXACT;
4964 newfd = dup2(from, to);
4966 newfd = fcntl(from, F_DUPFD, to);
4969 if (errno == EMFILE)
4971 /* Happens when source fd is not open: try "echo >&99" */
4972 ash_msg_and_raise_error("%d: %m", from);
4977 /* Struct def and variable are moved down to the first usage site */
4982 struct redirtab *next;
4985 struct two_fd_t two_fd[0];
4987 #define redirlist (G_var.redirlist)
4989 static int need_to_remember(struct redirtab *rp, int fd)
4993 if (!rp) /* remembering was not requested */
4996 for (i = 0; i < rp->pair_count; i++) {
4997 if (rp->two_fd[i].orig == fd) {
4998 /* already remembered */
5005 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5006 static int is_hidden_fd(struct redirtab *rp, int fd)
5009 struct parsefile *pf;
5022 fd |= COPYFD_RESTORE;
5023 for (i = 0; i < rp->pair_count; i++) {
5024 if (rp->two_fd[i].copy == fd) {
5032 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5033 * old file descriptors are stashed away so that the redirection can be
5034 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5035 * standard output, and the standard error if it becomes a duplicate of
5036 * stdout, is saved in memory.
5038 /* flags passed to redirect */
5039 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5040 #define REDIR_SAVEFD2 03 /* set preverrout */
5042 redirect(union node *redir, int flags)
5044 struct redirtab *sv;
5049 int copied_fd2 = -1;
5059 if (flags & REDIR_PUSH) {
5060 union node *tmp = redir;
5063 #if ENABLE_ASH_BASH_COMPAT
5064 if (redir->nfile.type == NTO2)
5067 tmp = tmp->nfile.next;
5069 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5070 sv->next = redirlist;
5071 sv->pair_count = sv_pos;
5073 sv->nullredirs = g_nullredirs - 1;
5075 while (sv_pos > 0) {
5077 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5082 fd = redir->nfile.fd;
5083 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5084 int right_fd = redir->ndup.dupfd;
5085 /* redirect from/to same file descriptor? */
5088 /* echo >&10 and 10 is a fd opened to the sh script? */
5089 if (is_hidden_fd(sv, right_fd)) {
5090 errno = EBADF; /* as if it is closed */
5091 ash_msg_and_raise_error("%d: %m", right_fd);
5095 newfd = openredirect(redir); /* always >= 0 */
5097 /* Descriptor wasn't open before redirect.
5098 * Mark it for close in the future */
5099 if (need_to_remember(sv, fd)) {
5100 goto remember_to_close;
5105 #if ENABLE_ASH_BASH_COMPAT
5108 if (need_to_remember(sv, fd)) {
5109 /* Copy old descriptor */
5110 i = fcntl(fd, F_DUPFD, 10);
5111 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5112 * are closed in popredir() in the child, preventing them from leaking
5113 * into child. (popredir() also cleans up the mess in case of failures)
5118 /* Strange error (e.g. "too many files" EMFILE?) */
5122 ash_msg_and_raise_error("%d: %m", fd);
5125 /* EBADF: it is not open - good, remember to close it */
5128 } else { /* fd is open, save its copy */
5129 /* "exec fd>&-" should not close fds
5130 * which point to script file(s).
5131 * Force them to be restored afterwards */
5132 if (is_hidden_fd(sv, fd))
5133 i |= COPYFD_RESTORE;
5137 sv->two_fd[sv_pos].orig = fd;
5138 sv->two_fd[sv_pos].copy = i;
5142 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5143 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5144 /* Don't want to trigger debugging */
5148 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5150 } else if (fd != newfd) { /* move newfd to fd */
5151 copyfd(newfd, fd | COPYFD_EXACT);
5152 #if ENABLE_ASH_BASH_COMPAT
5153 if (!(redir->nfile.type == NTO2 && fd == 2))
5157 #if ENABLE_ASH_BASH_COMPAT
5158 if (redir->nfile.type == NTO2 && fd == 1) {
5159 /* We already redirected it to fd 1, now copy it to 2 */
5165 } while ((redir = redir->nfile.next) != NULL);
5168 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5169 preverrout_fd = copied_fd2;
5173 * Undo the effects of the last redirection.
5176 popredir(int drop, int restore)
5178 struct redirtab *rp;
5181 if (--g_nullredirs >= 0)
5185 for (i = 0; i < rp->pair_count; i++) {
5186 int fd = rp->two_fd[i].orig;
5187 int copy = rp->two_fd[i].copy;
5188 if (copy == CLOSED) {
5193 if (copy != EMPTY) {
5194 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5195 copy &= ~COPYFD_RESTORE;
5197 copyfd(copy, fd | COPYFD_EXACT);
5199 close(copy & ~COPYFD_RESTORE);
5202 redirlist = rp->next;
5203 g_nullredirs = rp->nullredirs;
5209 * Undo all redirections. Called on error or interrupt.
5213 * Discard all saved file descriptors.
5216 clearredir(int drop)
5222 popredir(drop, /*restore:*/ 0);
5227 redirectsafe(union node *redir, int flags)
5230 volatile int saveint;
5231 struct jmploc *volatile savehandler = exception_handler;
5232 struct jmploc jmploc;
5235 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5236 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5238 exception_handler = &jmploc;
5239 redirect(redir, flags);
5241 exception_handler = savehandler;
5242 if (err && exception_type != EXERROR)
5243 longjmp(exception_handler->loc, 1);
5244 RESTORE_INT(saveint);
5249 /* ============ Routines to expand arguments to commands
5251 * We have to deal with backquotes, shell variables, and file metacharacters.
5254 #if ENABLE_SH_MATH_SUPPORT
5255 static arith_t dash_arith(const char *);
5261 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5262 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5263 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5264 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5265 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5266 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5267 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5268 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5269 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5273 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5274 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5275 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5276 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5277 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5280 * Structure specifying which parts of the string should be searched
5281 * for IFS characters.
5284 struct ifsregion *next; /* next region in list */
5285 int begoff; /* offset of start of region */
5286 int endoff; /* offset of end of region */
5287 int nulonly; /* search for nul bytes only */
5291 struct strlist *list;
5292 struct strlist **lastp;
5295 /* output of current string */
5296 static char *expdest;
5297 /* list of back quote expressions */
5298 static struct nodelist *argbackq;
5299 /* first struct in list of ifs regions */
5300 static struct ifsregion ifsfirst;
5301 /* last struct in list */
5302 static struct ifsregion *ifslastp;
5303 /* holds expanded arg list */
5304 static struct arglist exparg;
5314 expdest = makestrspace(32, expdest);
5315 len = fmtstr(expdest, 32, arith_t_fmt, num);
5316 STADJUST(len, expdest);
5321 esclen(const char *start, const char *p)
5325 while (p > start && *--p == CTLESC) {
5332 * Remove any CTLESC characters from a string.
5335 _rmescapes(char *str, int flag)
5337 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5344 p = strpbrk(str, qchars);
5350 if (flag & RMESCAPE_ALLOC) {
5351 size_t len = p - str;
5352 size_t fulllen = len + strlen(p) + 1;
5354 if (flag & RMESCAPE_GROW) {
5355 r = makestrspace(fulllen, expdest);
5356 } else if (flag & RMESCAPE_HEAP) {
5357 r = ckmalloc(fulllen);
5359 r = stalloc(fulllen);
5363 q = (char *)memcpy(q, str, len) + len;
5366 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5367 globbing = flag & RMESCAPE_GLOB;
5368 notescaped = globbing;
5370 if (*p == CTLQUOTEMARK) {
5371 inquotes = ~inquotes;
5373 notescaped = globbing;
5377 /* naked back slash */
5383 if (notescaped && inquotes && *p != '/') {
5387 notescaped = globbing;
5392 if (flag & RMESCAPE_GROW) {
5394 STADJUST(q - r + 1, expdest);
5398 #define rmescapes(p) _rmescapes((p), 0)
5400 #define pmatch(a, b) !fnmatch((a), (b), 0)
5403 * Prepare a pattern for a expmeta (internal glob(3)) call.
5405 * Returns an stalloced string.
5408 preglob(const char *pattern, int quoted, int flag)
5410 flag |= RMESCAPE_GLOB;
5412 flag |= RMESCAPE_QUOTED;
5414 return _rmescapes((char *)pattern, flag);
5418 * Put a string on the stack.
5421 memtodest(const char *p, size_t len, int syntax, int quotes)
5425 q = makestrspace(len * 2, q);
5428 int c = signed_char2int(*p++);
5431 if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
5440 strtodest(const char *p, int syntax, int quotes)
5442 memtodest(p, strlen(p), syntax, quotes);
5446 * Record the fact that we have to scan this region of the
5447 * string for IFS characters.
5450 recordregion(int start, int end, int nulonly)
5452 struct ifsregion *ifsp;
5454 if (ifslastp == NULL) {
5458 ifsp = ckzalloc(sizeof(*ifsp));
5459 /*ifsp->next = NULL; - ckzalloc did it */
5460 ifslastp->next = ifsp;
5464 ifslastp->begoff = start;
5465 ifslastp->endoff = end;
5466 ifslastp->nulonly = nulonly;
5470 removerecordregions(int endoff)
5472 if (ifslastp == NULL)
5475 if (ifsfirst.endoff > endoff) {
5476 while (ifsfirst.next != NULL) {
5477 struct ifsregion *ifsp;
5479 ifsp = ifsfirst.next->next;
5480 free(ifsfirst.next);
5481 ifsfirst.next = ifsp;
5484 if (ifsfirst.begoff > endoff)
5487 ifslastp = &ifsfirst;
5488 ifsfirst.endoff = endoff;
5493 ifslastp = &ifsfirst;
5494 while (ifslastp->next && ifslastp->next->begoff < endoff)
5495 ifslastp=ifslastp->next;
5496 while (ifslastp->next != NULL) {
5497 struct ifsregion *ifsp;
5499 ifsp = ifslastp->next->next;
5500 free(ifslastp->next);
5501 ifslastp->next = ifsp;
5504 if (ifslastp->endoff > endoff)
5505 ifslastp->endoff = endoff;
5509 exptilde(char *startp, char *p, int flag)
5515 int quotes = flag & (EXP_FULL | EXP_CASE);
5520 while ((c = *++p) != '\0') {
5527 if (flag & EXP_VARTILDE)
5537 if (*name == '\0') {
5538 home = lookupvar(homestr);
5540 pw = getpwnam(name);
5545 if (!home || !*home)
5548 startloc = expdest - (char *)stackblock();
5549 strtodest(home, SQSYNTAX, quotes);
5550 recordregion(startloc, expdest - (char *)stackblock(), 0);
5558 * Execute a command inside back quotes. If it's a builtin command, we
5559 * want to save its output in a block obtained from malloc. Otherwise
5560 * we fork off a subprocess and get the output of the command via a pipe.
5561 * Should be called with interrupts off.
5563 struct backcmd { /* result of evalbackcmd */
5564 int fd; /* file descriptor to read from */
5565 int nleft; /* number of chars in buffer */
5566 char *buf; /* buffer */
5567 struct job *jp; /* job structure for command */
5570 /* These forward decls are needed to use "eval" code for backticks handling: */
5571 static uint8_t back_exitstatus; /* exit status of backquoted command */
5572 #define EV_EXIT 01 /* exit after evaluating tree */
5573 static void evaltree(union node *, int);
5576 evalbackcmd(union node *n, struct backcmd *result)
5587 saveherefd = herefd;
5595 ash_msg_and_raise_error("pipe call failed");
5596 jp = makejob(/*n,*/ 1);
5597 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5602 copyfd(pip[1], 1 | COPYFD_EXACT);
5606 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5610 result->fd = pip[0];
5613 herefd = saveherefd;
5615 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5616 result->fd, result->buf, result->nleft, result->jp));
5620 * Expand stuff in backwards quotes.
5623 expbackq(union node *cmd, int quoted, int quotes)
5631 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5632 struct stackmark smark;
5635 setstackmark(&smark);
5637 startloc = dest - (char *)stackblock();
5639 evalbackcmd(cmd, &in);
5640 popstackmark(&smark);
5647 memtodest(p, i, syntax, quotes);
5651 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5652 TRACE(("expbackq: read returns %d\n", i));
5661 back_exitstatus = waitforjob(in.jp);
5665 /* Eat all trailing newlines */
5667 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5672 recordregion(startloc, dest - (char *)stackblock(), 0);
5673 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5674 (dest - (char *)stackblock()) - startloc,
5675 (dest - (char *)stackblock()) - startloc,
5676 stackblock() + startloc));
5679 #if ENABLE_SH_MATH_SUPPORT
5681 * Expand arithmetic expression. Backup to start of expression,
5682 * evaluate, place result in (backed up) result, adjust string position.
5695 * This routine is slightly over-complicated for
5696 * efficiency. Next we scan backwards looking for the
5697 * start of arithmetic.
5699 start = stackblock();
5706 while (*p != CTLARI) {
5710 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5715 esc = esclen(start, p);
5725 removerecordregions(begoff);
5734 len = cvtnum(dash_arith(p + 2));
5737 recordregion(begoff, begoff + len, 0);
5741 /* argstr needs it */
5742 static char *evalvar(char *p, int flag, struct strlist *var_str_list);
5745 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5746 * characters to allow for further processing. Otherwise treat
5747 * $@ like $* since no splitting will be performed.
5749 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5750 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5751 * for correct expansion of "B=$A" word.
5754 argstr(char *p, int flag, struct strlist *var_str_list)
5756 static const char spclchars[] ALIGN1 = {
5764 CTLBACKQ | CTLQUOTE,
5765 #if ENABLE_SH_MATH_SUPPORT
5770 const char *reject = spclchars;
5772 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
5773 int breakall = flag & EXP_WORD;
5778 if (!(flag & EXP_VARTILDE)) {
5780 } else if (flag & EXP_VARTILDE2) {
5785 if (flag & EXP_TILDE) {
5791 if (*q == CTLESC && (flag & EXP_QWORD))
5794 p = exptilde(p, q, flag);
5797 startloc = expdest - (char *)stackblock();
5799 length += strcspn(p + length, reject);
5801 if (c && (!(c & 0x80)
5802 #if ENABLE_SH_MATH_SUPPORT
5806 /* c == '=' || c == ':' || c == CTLENDARI */
5811 expdest = stack_nputstr(p, length, expdest);
5812 newloc = expdest - (char *)stackblock();
5813 if (breakall && !inquotes && newloc > startloc) {
5814 recordregion(startloc, newloc, 0);
5825 if (flag & EXP_VARTILDE2) {
5829 flag |= EXP_VARTILDE2;
5834 * sort of a hack - expand tildes in variable
5835 * assignments (after the first '=' and after ':'s).
5844 case CTLENDVAR: /* ??? */
5847 /* "$@" syntax adherence hack */
5850 !memcmp(p, dolatstr, 4) &&
5851 (p[4] == CTLQUOTEMARK || (
5852 p[4] == CTLENDVAR &&
5853 p[5] == CTLQUOTEMARK
5856 p = evalvar(p + 1, flag, /* var_str_list: */ NULL) + 1;
5859 inquotes = !inquotes;
5872 p = evalvar(p, flag, var_str_list);
5876 case CTLBACKQ|CTLQUOTE:
5877 expbackq(argbackq->n, c, quotes);
5878 argbackq = argbackq->next;
5880 #if ENABLE_SH_MATH_SUPPORT
5893 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
5896 // This commented out code was added by James Simmons <jsimmons@infradead.org>
5897 // as part of a larger change when he added support for ${var/a/b}.
5898 // However, it broke # and % operators:
5902 //echo ${var#ab} abcdcd abcdcd
5903 //echo ${var##ab} abcdcd abcdcd
5904 //echo ${var#a*b} abcdcd ababcdcd (!)
5905 //echo ${var##a*b} cdcd cdcd
5906 //echo ${var#?} babcdcd ababcdcd (!)
5907 //echo ${var##?} babcdcd babcdcd
5908 //echo ${var#*} ababcdcd babcdcd (!)
5910 //echo ${var%cd} ababcd ababcd
5911 //echo ${var%%cd} ababcd abab (!)
5912 //echo ${var%c*d} ababcd ababcd
5913 //echo ${var%%c*d} abab ababcdcd (!)
5914 //echo ${var%?} ababcdc ababcdc
5915 //echo ${var%%?} ababcdc ababcdcd (!)
5916 //echo ${var%*} ababcdcd ababcdcd
5919 // Commenting it back out helped. Remove it completely if it really
5922 char *loc, *loc2; //, *full;
5928 int match; // = strlen(str);
5929 const char *s = loc2;
5936 match = pmatch(str, s); // this line was deleted
5938 // // chop off end if its '*'
5939 // full = strrchr(str, '*');
5940 // if (full && full != str)
5943 // // If str starts with '*' replace with s.
5944 // if ((*str == '*') && strlen(s) >= match) {
5945 // full = xstrdup(s);
5946 // strncpy(full+strlen(s)-match+1, str+1, match-1);
5948 // full = xstrndup(str, match);
5949 // match = strncmp(s, full, strlen(full));
5953 if (match) // if (!match)
5955 if (quotes && *loc == CTLESC)
5964 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5971 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
5974 const char *s = loc2;
5979 match = pmatch(str, s);
5986 esc = esclen(startp, loc);
5997 static void varunset(const char *, const char *, const char *, int) NORETURN;
5999 varunset(const char *end, const char *var, const char *umsg, int varflags)
6005 msg = "parameter not set";
6007 if (*end == CTLENDVAR) {
6008 if (varflags & VSNUL)
6014 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6017 #if ENABLE_ASH_BASH_COMPAT
6019 parse_sub_pattern(char *arg, int inquotes)
6021 char *idx, *repl = NULL;
6030 /* Only the first '/' seen is our separator */
6037 if (!inquotes && c == '\\' && arg[1] == '\\')
6038 arg++; /* skip both \\, not just first one */
6045 #endif /* ENABLE_ASH_BASH_COMPAT */
6048 subevalvar(char *p, char *str, int strloc, int subtype,
6049 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6051 struct nodelist *saveargbackq = argbackq;
6054 char *rmesc, *rmescend;
6055 USE_ASH_BASH_COMPAT(char *repl = NULL;)
6056 USE_ASH_BASH_COMPAT(char null = '\0';)
6057 USE_ASH_BASH_COMPAT(int pos, len, orig_len;)
6058 int saveherefd = herefd;
6059 int amount, workloc, resetloc;
6061 char *(*scan)(char*, char*, char*, char*, int, int);
6064 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6066 STPUTC('\0', expdest);
6067 herefd = saveherefd;
6068 argbackq = saveargbackq;
6069 startp = (char *)stackblock() + startloc;
6073 setvar(str, startp, 0);
6074 amount = startp - expdest;
6075 STADJUST(amount, expdest);
6078 #if ENABLE_ASH_BASH_COMPAT
6080 loc = str = stackblock() + strloc;
6081 // TODO: number() instead? It does error checking...
6083 len = str - startp - 1;
6085 /* *loc != '\0', guaranteed by parser */
6089 /* We must adjust the length by the number of escapes we find. */
6090 for (ptr = startp; ptr < (str - 1); ptr++) {
6091 if (*ptr == CTLESC) {
6099 if (*loc++ == ':') {
6100 // TODO: number() instead? It does error checking...
6104 while (*loc && *loc != ':')
6107 // TODO: number() instead? It does error checking...
6110 if (pos >= orig_len) {
6114 if (len > (orig_len - pos))
6115 len = orig_len - pos;
6117 for (str = startp; pos; str++, pos--) {
6118 if (quotes && *str == CTLESC)
6121 for (loc = startp; len; len--) {
6122 if (quotes && *str == CTLESC)
6127 amount = loc - expdest;
6128 STADJUST(amount, expdest);
6133 varunset(p, str, startp, varflags);
6136 resetloc = expdest - (char *)stackblock();
6138 /* We'll comeback here if we grow the stack while handling
6139 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6140 * stack will need rebasing, and we'll need to remove our work
6143 USE_ASH_BASH_COMPAT(restart:)
6145 amount = expdest - ((char *)stackblock() + resetloc);
6146 STADJUST(-amount, expdest);
6147 startp = (char *)stackblock() + startloc;
6150 rmescend = (char *)stackblock() + strloc;
6152 rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6153 if (rmesc != startp) {
6155 startp = (char *)stackblock() + startloc;
6159 str = (char *)stackblock() + strloc;
6160 preglob(str, varflags & VSQUOTE, 0);
6161 workloc = expdest - (char *)stackblock();
6163 #if ENABLE_ASH_BASH_COMPAT
6164 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6165 char *idx, *end, *restart_detect;
6168 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6173 /* If there's no pattern to match, return the expansion unmolested */
6181 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6183 /* No match, advance */
6184 restart_detect = stackblock();
6185 STPUTC(*idx, expdest);
6186 if (quotes && *idx == CTLESC) {
6189 STPUTC(*idx, expdest);
6191 if (stackblock() != restart_detect)
6199 if (subtype == VSREPLACEALL) {
6201 if (quotes && *idx == CTLESC)
6210 for (loc = repl; *loc; loc++) {
6211 restart_detect = stackblock();
6212 STPUTC(*loc, expdest);
6213 if (stackblock() != restart_detect)
6218 if (subtype == VSREPLACE) {
6220 restart_detect = stackblock();
6221 STPUTC(*idx, expdest);
6222 if (stackblock() != restart_detect)
6231 /* We've put the replaced text into a buffer at workloc, now
6232 * move it to the right place and adjust the stack.
6234 startp = stackblock() + startloc;
6235 STPUTC('\0', expdest);
6236 memmove(startp, stackblock() + workloc, len);
6237 startp[len++] = '\0';
6238 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6239 STADJUST(-amount, expdest);
6242 #endif /* ENABLE_ASH_BASH_COMPAT */
6244 subtype -= VSTRIMRIGHT;
6246 if (subtype < 0 || subtype > 7)
6249 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6250 zero = subtype >> 1;
6251 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6252 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6254 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6257 memmove(startp, loc, str - loc);
6258 loc = startp + (str - loc) - 1;
6261 amount = loc - expdest;
6262 STADJUST(amount, expdest);
6268 * Add the value of a specialized variable to the stack string.
6271 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6281 int quoted = varflags & VSQUOTE;
6282 int subtype = varflags & VSTYPE;
6283 int quotes = flags & (EXP_FULL | EXP_CASE);
6285 if (quoted && (flags & EXP_FULL))
6286 sep = 1 << CHAR_BIT;
6288 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6297 num = shellparam.nparam;
6307 expdest = makestrspace(NOPTS, expdest);
6308 for (i = NOPTS - 1; i >= 0; i--) {
6310 USTPUTC(optletters(i), expdest);
6320 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
6321 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6327 while ((p = *ap++)) {
6330 partlen = strlen(p);
6333 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6334 memtodest(p, partlen, syntax, quotes);
6340 if (subtype == VSPLUS || subtype == VSLENGTH) {
6361 // TODO: number() instead? It does error checking...
6363 if (num < 0 || num > shellparam.nparam)
6365 p = num ? shellparam.p[num - 1] : arg0;
6368 /* NB: name has form "VAR=..." */
6370 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6371 * which should be considered before we check variables. */
6373 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6377 str = var_str_list->text;
6378 eq = strchr(str, '=');
6379 if (!eq) /* stop at first non-assignment */
6382 if (name_len == (unsigned)(eq - str)
6383 && strncmp(str, name, name_len) == 0) {
6385 /* goto value; - WRONG! */
6386 /* think "A=1 A=2 B=$A" */
6388 var_str_list = var_str_list->next;
6389 } while (var_str_list);
6393 p = lookupvar(name);
6399 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6400 memtodest(p, len, syntax, quotes);
6404 if (subtype == VSPLUS || subtype == VSLENGTH)
6405 STADJUST(-len, expdest);
6410 * Expand a variable, and return a pointer to the next character in the
6414 evalvar(char *p, int flag, struct strlist *var_str_list)
6426 subtype = varflags & VSTYPE;
6427 quoted = varflags & VSQUOTE;
6429 easy = (!quoted || (*var == '@' && shellparam.nparam));
6430 startloc = expdest - (char *)stackblock();
6431 p = strchr(p, '=') + 1;
6434 varlen = varvalue(var, varflags, flag, var_str_list);
6435 if (varflags & VSNUL)
6438 if (subtype == VSPLUS) {
6439 varlen = -1 - varlen;
6443 if (subtype == VSMINUS) {
6447 p, flag | EXP_TILDE |
6448 (quoted ? EXP_QWORD : EXP_WORD),
6458 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6460 if (subevalvar(p, var, /* strloc: */ 0,
6461 subtype, startloc, varflags,
6467 * Remove any recorded regions beyond
6470 removerecordregions(startloc);
6480 if (varlen < 0 && uflag)
6481 varunset(p, var, 0, 0);
6483 if (subtype == VSLENGTH) {
6484 cvtnum(varlen > 0 ? varlen : 0);
6488 if (subtype == VSNORMAL) {
6499 case VSTRIMRIGHTMAX:
6500 #if ENABLE_ASH_BASH_COMPAT
6513 * Terminate the string and start recording the pattern
6516 STPUTC('\0', expdest);
6517 patloc = expdest - (char *)stackblock();
6518 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6520 /* quotes: */ flag & (EXP_FULL | EXP_CASE),
6523 int amount = expdest - (
6524 (char *)stackblock() + patloc - 1
6526 STADJUST(-amount, expdest);
6528 /* Remove any recorded regions beyond start of variable */
6529 removerecordregions(startloc);
6531 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6535 if (subtype != VSNORMAL) { /* skip to end of alternative */
6541 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6543 argbackq = argbackq->next;
6544 } else if (c == CTLVAR) {
6545 if ((*p++ & VSTYPE) != VSNORMAL)
6547 } else if (c == CTLENDVAR) {
6557 * Break the argument string into pieces based upon IFS and add the
6558 * strings to the argument list. The regions of the string to be
6559 * searched for IFS characters have been stored by recordregion.
6562 ifsbreakup(char *string, struct arglist *arglist)
6564 struct ifsregion *ifsp;
6569 const char *ifs, *realifs;
6574 if (ifslastp != NULL) {
6577 realifs = ifsset() ? ifsval() : defifs;
6580 p = string + ifsp->begoff;
6581 nulonly = ifsp->nulonly;
6582 ifs = nulonly ? nullstr : realifs;
6584 while (p < string + ifsp->endoff) {
6588 if (!strchr(ifs, *p)) {
6593 ifsspc = (strchr(defifs, *p) != NULL);
6594 /* Ignore IFS whitespace at start */
6595 if (q == start && ifsspc) {
6601 sp = stzalloc(sizeof(*sp));
6603 *arglist->lastp = sp;
6604 arglist->lastp = &sp->next;
6608 if (p >= string + ifsp->endoff) {
6614 if (strchr(ifs, *p) == NULL) {
6618 if (strchr(defifs, *p) == NULL) {
6633 } while (ifsp != NULL);
6642 sp = stzalloc(sizeof(*sp));
6644 *arglist->lastp = sp;
6645 arglist->lastp = &sp->next;
6651 struct ifsregion *p;
6656 struct ifsregion *ifsp;
6662 ifsfirst.next = NULL;
6667 * Add a file name to the list.
6670 addfname(const char *name)
6674 sp = stzalloc(sizeof(*sp));
6675 sp->text = ststrdup(name);
6677 exparg.lastp = &sp->next;
6680 static char *expdir;
6683 * Do metacharacter (i.e. *, ?, [...]) expansion.
6686 expmeta(char *enddir, char *name)
6701 for (p = name; *p; p++) {
6702 if (*p == '*' || *p == '?')
6704 else if (*p == '[') {
6711 if (*q == '/' || *q == '\0')
6718 } else if (*p == '\\')
6720 else if (*p == '/') {
6727 if (metaflag == 0) { /* we've reached the end of the file name */
6728 if (enddir != expdir)
6736 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6747 } while (p < start);
6749 if (enddir == expdir) {
6751 } else if (enddir == expdir + 1 && *expdir == '/') {
6760 if (enddir != expdir)
6762 if (*endname == 0) {
6774 while (!intpending && (dp = readdir(dirp)) != NULL) {
6775 if (dp->d_name[0] == '.' && !matchdot)
6777 if (pmatch(start, dp->d_name)) {
6779 strcpy(enddir, dp->d_name);
6782 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6785 expmeta(p, endname);
6794 static struct strlist *
6795 msort(struct strlist *list, int len)
6797 struct strlist *p, *q = NULL;
6798 struct strlist **lpp;
6806 for (n = half; --n >= 0;) {
6810 q->next = NULL; /* terminate first half of list */
6811 q = msort(list, half); /* sort first half of list */
6812 p = msort(p, len - half); /* sort second half */
6815 #if ENABLE_LOCALE_SUPPORT
6816 if (strcoll(p->text, q->text) < 0)
6818 if (strcmp(p->text, q->text) < 0)
6842 * Sort the results of file name expansion. It calculates the number of
6843 * strings to sort and then calls msort (short for merge sort) to do the
6846 static struct strlist *
6847 expsort(struct strlist *str)
6853 for (sp = str; sp; sp = sp->next)
6855 return msort(str, len);
6859 expandmeta(struct strlist *str /*, int flag*/)
6861 static const char metachars[] ALIGN1 = {
6864 /* TODO - EXP_REDIR */
6867 struct strlist **savelastp;
6873 if (!strpbrk(str->text, metachars))
6875 savelastp = exparg.lastp;
6878 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6880 int i = strlen(str->text);
6881 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6889 if (exparg.lastp == savelastp) {
6894 *exparg.lastp = str;
6895 rmescapes(str->text);
6896 exparg.lastp = &str->next;
6898 *exparg.lastp = NULL;
6899 *savelastp = sp = expsort(*savelastp);
6900 while (sp->next != NULL)
6902 exparg.lastp = &sp->next;
6909 * Perform variable substitution and command substitution on an argument,
6910 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
6911 * perform splitting and file name expansion. When arglist is NULL, perform
6912 * here document expansion.
6915 expandarg(union node *arg, struct arglist *arglist, int flag)
6920 argbackq = arg->narg.backquote;
6921 STARTSTACKSTR(expdest);
6922 ifsfirst.next = NULL;
6924 argstr(arg->narg.text, flag,
6925 /* var_str_list: */ arglist ? arglist->list : NULL);
6926 p = _STPUTC('\0', expdest);
6928 if (arglist == NULL) {
6929 return; /* here document expanded */
6931 p = grabstackstr(p);
6932 exparg.lastp = &exparg.list;
6936 if (flag & EXP_FULL) {
6937 ifsbreakup(p, &exparg);
6938 *exparg.lastp = NULL;
6939 exparg.lastp = &exparg.list;
6940 expandmeta(exparg.list /*, flag*/);
6942 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
6944 sp = stzalloc(sizeof(*sp));
6947 exparg.lastp = &sp->next;
6951 *exparg.lastp = NULL;
6953 *arglist->lastp = exparg.list;
6954 arglist->lastp = exparg.lastp;
6959 * Expand shell variables and backquotes inside a here document.
6962 expandhere(union node *arg, int fd)
6965 expandarg(arg, (struct arglist *)NULL, 0);
6966 full_write(fd, stackblock(), expdest - (char *)stackblock());
6970 * Returns true if the pattern matches the string.
6973 patmatch(char *pattern, const char *string)
6975 return pmatch(preglob(pattern, 0, 0), string);
6979 * See if a pattern matches in a case statement.
6982 casematch(union node *pattern, char *val)
6984 struct stackmark smark;
6987 setstackmark(&smark);
6988 argbackq = pattern->narg.backquote;
6989 STARTSTACKSTR(expdest);
6991 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
6992 /* var_str_list: */ NULL);
6993 STACKSTRNUL(expdest);
6994 result = patmatch(stackblock(), val);
6995 popstackmark(&smark);
7000 /* ============ find_command */
7004 int (*builtin)(int, char **);
7005 /* unsigned flags; */
7007 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7008 /* "regular" builtins always take precedence over commands,
7009 * regardless of PATH=....%builtin... position */
7010 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7011 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7014 smallint cmdtype; /* CMDxxx */
7017 /* index >= 0 for commands without path (slashes) */
7018 /* (TODO: what exactly does the value mean? PATH position?) */
7019 /* index == -1 for commands with slashes */
7020 /* index == (-2 - applet_no) for NOFORK applets */
7021 const struct builtincmd *cmd;
7022 struct funcnode *func;
7025 /* values of cmdtype */
7026 #define CMDUNKNOWN -1 /* no entry in table for command */
7027 #define CMDNORMAL 0 /* command is an executable program */
7028 #define CMDFUNCTION 1 /* command is a shell function */
7029 #define CMDBUILTIN 2 /* command is a shell builtin */
7031 /* action to find_command() */
7032 #define DO_ERR 0x01 /* prints errors */
7033 #define DO_ABS 0x02 /* checks absolute paths */
7034 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7035 #define DO_ALTPATH 0x08 /* using alternate path */
7036 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7038 static void find_command(char *, struct cmdentry *, int, const char *);
7041 /* ============ Hashing commands */
7044 * When commands are first encountered, they are entered in a hash table.
7045 * This ensures that a full path search will not have to be done for them
7046 * on each invocation.
7048 * We should investigate converting to a linear search, even though that
7049 * would make the command name "hash" a misnomer.
7053 struct tblentry *next; /* next entry in hash chain */
7054 union param param; /* definition of builtin function */
7055 smallint cmdtype; /* CMDxxx */
7056 char rehash; /* if set, cd done since entry created */
7057 char cmdname[1]; /* name of command */
7060 static struct tblentry **cmdtable;
7061 #define INIT_G_cmdtable() do { \
7062 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7065 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7069 tryexec(USE_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7073 #if ENABLE_FEATURE_SH_STANDALONE
7074 if (applet_no >= 0) {
7075 if (APPLET_IS_NOEXEC(applet_no)) {
7078 run_applet_no_and_exit(applet_no, argv);
7080 /* re-exec ourselves with the new arguments */
7081 execve(bb_busybox_exec_path, argv, envp);
7082 /* If they called chroot or otherwise made the binary no longer
7083 * executable, fall through */
7090 execve(cmd, argv, envp);
7091 } while (errno == EINTR);
7093 execve(cmd, argv, envp);
7099 if (errno == ENOEXEC) {
7103 for (ap = argv; *ap; ap++)
7105 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7107 ap[0] = cmd = (char *)DEFAULT_SHELL;
7110 while ((*ap++ = *argv++) != NULL)
7119 * Exec a program. Never returns. If you change this routine, you may
7120 * have to change the find_command routine as well.
7122 static void shellexec(char **, const char *, int) NORETURN;
7124 shellexec(char **argv, const char *path, int idx)
7130 #if ENABLE_FEATURE_SH_STANDALONE
7134 clearredir(/*drop:*/ 1);
7135 envp = listvars(VEXPORT, VUNSET, 0);
7136 if (strchr(argv[0], '/') != NULL
7137 #if ENABLE_FEATURE_SH_STANDALONE
7138 || (applet_no = find_applet_by_name(argv[0])) >= 0
7141 tryexec(USE_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7145 while ((cmdname = padvance(&path, argv[0])) != NULL) {
7146 if (--idx < 0 && pathopt == NULL) {
7147 tryexec(USE_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7148 if (errno != ENOENT && errno != ENOTDIR)
7155 /* Map to POSIX errors */
7167 exitstatus = exerrno;
7168 TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
7169 argv[0], e, suppressint));
7170 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7175 printentry(struct tblentry *cmdp)
7181 idx = cmdp->param.index;
7184 name = padvance(&path, cmdp->cmdname);
7186 } while (--idx >= 0);
7187 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7191 * Clear out command entries. The argument specifies the first entry in
7192 * PATH which has changed.
7195 clearcmdentry(int firstchange)
7197 struct tblentry **tblp;
7198 struct tblentry **pp;
7199 struct tblentry *cmdp;
7202 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7204 while ((cmdp = *pp) != NULL) {
7205 if ((cmdp->cmdtype == CMDNORMAL &&
7206 cmdp->param.index >= firstchange)
7207 || (cmdp->cmdtype == CMDBUILTIN &&
7208 builtinloc >= firstchange)
7221 * Locate a command in the command hash table. If "add" is nonzero,
7222 * add the command to the table if it is not already present. The
7223 * variable "lastcmdentry" is set to point to the address of the link
7224 * pointing to the entry, so that delete_cmd_entry can delete the
7227 * Interrupts must be off if called with add != 0.
7229 static struct tblentry **lastcmdentry;
7231 static struct tblentry *
7232 cmdlookup(const char *name, int add)
7234 unsigned int hashval;
7236 struct tblentry *cmdp;
7237 struct tblentry **pp;
7240 hashval = (unsigned char)*p << 4;
7242 hashval += (unsigned char)*p++;
7244 pp = &cmdtable[hashval % CMDTABLESIZE];
7245 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7246 if (strcmp(cmdp->cmdname, name) == 0)
7250 if (add && cmdp == NULL) {
7251 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7253 /* + 1 - already done because
7254 * tblentry::cmdname is char[1] */);
7255 /*cmdp->next = NULL; - ckzalloc did it */
7256 cmdp->cmdtype = CMDUNKNOWN;
7257 strcpy(cmdp->cmdname, name);
7264 * Delete the command entry returned on the last lookup.
7267 delete_cmd_entry(void)
7269 struct tblentry *cmdp;
7272 cmdp = *lastcmdentry;
7273 *lastcmdentry = cmdp->next;
7274 if (cmdp->cmdtype == CMDFUNCTION)
7275 freefunc(cmdp->param.func);
7281 * Add a new command entry, replacing any existing command entry for
7282 * the same name - except special builtins.
7285 addcmdentry(char *name, struct cmdentry *entry)
7287 struct tblentry *cmdp;
7289 cmdp = cmdlookup(name, 1);
7290 if (cmdp->cmdtype == CMDFUNCTION) {
7291 freefunc(cmdp->param.func);
7293 cmdp->cmdtype = entry->cmdtype;
7294 cmdp->param = entry->u;
7299 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7301 struct tblentry **pp;
7302 struct tblentry *cmdp;
7304 struct cmdentry entry;
7307 if (nextopt("r") != '\0') {
7312 if (*argptr == NULL) {
7313 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7314 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7315 if (cmdp->cmdtype == CMDNORMAL)
7323 while ((name = *argptr) != NULL) {
7324 cmdp = cmdlookup(name, 0);
7326 && (cmdp->cmdtype == CMDNORMAL
7327 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7331 find_command(name, &entry, DO_ERR, pathval());
7332 if (entry.cmdtype == CMDUNKNOWN)
7340 * Called when a cd is done. Marks all commands so the next time they
7341 * are executed they will be rehashed.
7346 struct tblentry **pp;
7347 struct tblentry *cmdp;
7349 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7350 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7351 if (cmdp->cmdtype == CMDNORMAL
7352 || (cmdp->cmdtype == CMDBUILTIN
7353 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7363 * Fix command hash table when PATH changed.
7364 * Called before PATH is changed. The argument is the new value of PATH;
7365 * pathval() still returns the old value at this point.
7366 * Called with interrupts off.
7369 changepath(const char *new)
7377 firstchange = 9999; /* assume no change */
7383 if ((*old == '\0' && *new == ':')
7384 || (*old == ':' && *new == '\0'))
7386 old = new; /* ignore subsequent differences */
7390 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7396 if (builtinloc < 0 && idx_bltin >= 0)
7397 builtinloc = idx_bltin; /* zap builtins */
7398 if (builtinloc >= 0 && idx_bltin < 0)
7400 clearcmdentry(firstchange);
7401 builtinloc = idx_bltin;
7416 #define TENDBQUOTE 12
7433 typedef smallint token_id_t;
7435 /* first char is indicating which tokens mark the end of a list */
7436 static const char *const tokname_array[] = {
7450 #define KWDOFFSET 13
7451 /* the following are keywords */
7473 static char buf[16];
7476 //if (tok < TSEMI) return tokname_array[tok] + 1;
7477 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7482 sprintf(buf + (tok >= TSEMI), "%s%c",
7483 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7487 /* Wrapper around strcmp for qsort/bsearch/... */
7489 pstrcmp(const void *a, const void *b)
7491 return strcmp((char*) a, (*(char**) b) + 1);
7494 static const char *const *
7495 findkwd(const char *s)
7497 return bsearch(s, tokname_array + KWDOFFSET,
7498 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7499 sizeof(tokname_array[0]), pstrcmp);
7503 * Locate and print what a word is...
7506 describe_command(char *command, int describe_command_verbose)
7508 struct cmdentry entry;
7509 struct tblentry *cmdp;
7510 #if ENABLE_ASH_ALIAS
7511 const struct alias *ap;
7513 const char *path = pathval();
7515 if (describe_command_verbose) {
7519 /* First look at the keywords */
7520 if (findkwd(command)) {
7521 out1str(describe_command_verbose ? " is a shell keyword" : command);
7525 #if ENABLE_ASH_ALIAS
7526 /* Then look at the aliases */
7527 ap = lookupalias(command, 0);
7529 if (!describe_command_verbose) {
7534 out1fmt(" is an alias for %s", ap->val);
7538 /* Then check if it is a tracked alias */
7539 cmdp = cmdlookup(command, 0);
7541 entry.cmdtype = cmdp->cmdtype;
7542 entry.u = cmdp->param;
7544 /* Finally use brute force */
7545 find_command(command, &entry, DO_ABS, path);
7548 switch (entry.cmdtype) {
7550 int j = entry.u.index;
7556 p = padvance(&path, command);
7560 if (describe_command_verbose) {
7562 (cmdp ? " a tracked alias for" : nullstr), p
7571 if (describe_command_verbose) {
7572 out1str(" is a shell function");
7579 if (describe_command_verbose) {
7580 out1fmt(" is a %sshell builtin",
7581 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7582 "special " : nullstr
7590 if (describe_command_verbose) {
7591 out1str(": not found\n");
7596 outstr("\n", stdout);
7601 typecmd(int argc UNUSED_PARAM, char **argv)
7607 /* type -p ... ? (we don't bother checking for 'p') */
7608 if (argv[1] && argv[1][0] == '-') {
7613 err |= describe_command(argv[i++], verbose);
7618 #if ENABLE_ASH_CMDCMD
7620 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7628 while ((c = nextopt("pvV")) != '\0')
7630 verify |= VERIFY_VERBOSE;
7632 verify |= VERIFY_BRIEF;
7637 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7638 if (verify && (*argptr != NULL)) {
7639 return describe_command(*argptr, verify - VERIFY_BRIEF);
7647 /* ============ eval.c */
7649 static int funcblocksize; /* size of structures in function */
7650 static int funcstringsize; /* size of strings in node */
7651 static void *funcblock; /* block to allocate function from */
7652 static char *funcstring; /* block to allocate strings from */
7654 /* flags in argument to evaltree */
7655 #define EV_EXIT 01 /* exit after evaluating tree */
7656 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7657 #define EV_BACKCMD 04 /* command executing within back quotes */
7659 static const short nodesize[N_NUMBER] = {
7660 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7661 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7662 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7663 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7664 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7665 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7666 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7667 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7668 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7669 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7670 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7671 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7672 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7673 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7674 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7675 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7676 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7677 #if ENABLE_ASH_BASH_COMPAT
7678 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7680 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7681 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7682 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7683 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7684 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7685 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7686 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7687 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7688 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7691 static void calcsize(union node *n);
7694 sizenodelist(struct nodelist *lp)
7697 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7704 calcsize(union node *n)
7708 funcblocksize += nodesize[n->type];
7711 calcsize(n->ncmd.redirect);
7712 calcsize(n->ncmd.args);
7713 calcsize(n->ncmd.assign);
7716 sizenodelist(n->npipe.cmdlist);
7721 calcsize(n->nredir.redirect);
7722 calcsize(n->nredir.n);
7729 calcsize(n->nbinary.ch2);
7730 calcsize(n->nbinary.ch1);
7733 calcsize(n->nif.elsepart);
7734 calcsize(n->nif.ifpart);
7735 calcsize(n->nif.test);
7738 funcstringsize += strlen(n->nfor.var) + 1;
7739 calcsize(n->nfor.body);
7740 calcsize(n->nfor.args);
7743 calcsize(n->ncase.cases);
7744 calcsize(n->ncase.expr);
7747 calcsize(n->nclist.body);
7748 calcsize(n->nclist.pattern);
7749 calcsize(n->nclist.next);
7753 sizenodelist(n->narg.backquote);
7754 funcstringsize += strlen(n->narg.text) + 1;
7755 calcsize(n->narg.next);
7758 #if ENABLE_ASH_BASH_COMPAT
7765 calcsize(n->nfile.fname);
7766 calcsize(n->nfile.next);
7770 calcsize(n->ndup.vname);
7771 calcsize(n->ndup.next);
7775 calcsize(n->nhere.doc);
7776 calcsize(n->nhere.next);
7779 calcsize(n->nnot.com);
7785 nodeckstrdup(char *s)
7787 char *rtn = funcstring;
7789 strcpy(funcstring, s);
7790 funcstring += strlen(s) + 1;
7794 static union node *copynode(union node *);
7796 static struct nodelist *
7797 copynodelist(struct nodelist *lp)
7799 struct nodelist *start;
7800 struct nodelist **lpp;
7805 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7806 (*lpp)->n = copynode(lp->n);
7808 lpp = &(*lpp)->next;
7815 copynode(union node *n)
7822 funcblock = (char *) funcblock + nodesize[n->type];
7826 new->ncmd.redirect = copynode(n->ncmd.redirect);
7827 new->ncmd.args = copynode(n->ncmd.args);
7828 new->ncmd.assign = copynode(n->ncmd.assign);
7831 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7832 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
7837 new->nredir.redirect = copynode(n->nredir.redirect);
7838 new->nredir.n = copynode(n->nredir.n);
7845 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7846 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7849 new->nif.elsepart = copynode(n->nif.elsepart);
7850 new->nif.ifpart = copynode(n->nif.ifpart);
7851 new->nif.test = copynode(n->nif.test);
7854 new->nfor.var = nodeckstrdup(n->nfor.var);
7855 new->nfor.body = copynode(n->nfor.body);
7856 new->nfor.args = copynode(n->nfor.args);
7859 new->ncase.cases = copynode(n->ncase.cases);
7860 new->ncase.expr = copynode(n->ncase.expr);
7863 new->nclist.body = copynode(n->nclist.body);
7864 new->nclist.pattern = copynode(n->nclist.pattern);
7865 new->nclist.next = copynode(n->nclist.next);
7869 new->narg.backquote = copynodelist(n->narg.backquote);
7870 new->narg.text = nodeckstrdup(n->narg.text);
7871 new->narg.next = copynode(n->narg.next);
7874 #if ENABLE_ASH_BASH_COMPAT
7881 new->nfile.fname = copynode(n->nfile.fname);
7882 new->nfile.fd = n->nfile.fd;
7883 new->nfile.next = copynode(n->nfile.next);
7887 new->ndup.vname = copynode(n->ndup.vname);
7888 new->ndup.dupfd = n->ndup.dupfd;
7889 new->ndup.fd = n->ndup.fd;
7890 new->ndup.next = copynode(n->ndup.next);
7894 new->nhere.doc = copynode(n->nhere.doc);
7895 new->nhere.fd = n->nhere.fd;
7896 new->nhere.next = copynode(n->nhere.next);
7899 new->nnot.com = copynode(n->nnot.com);
7902 new->type = n->type;
7907 * Make a copy of a parse tree.
7909 static struct funcnode *
7910 copyfunc(union node *n)
7915 funcblocksize = offsetof(struct funcnode, n);
7918 blocksize = funcblocksize;
7919 f = ckmalloc(blocksize + funcstringsize);
7920 funcblock = (char *) f + offsetof(struct funcnode, n);
7921 funcstring = (char *) f + blocksize;
7928 * Define a shell function.
7931 defun(char *name, union node *func)
7933 struct cmdentry entry;
7936 entry.cmdtype = CMDFUNCTION;
7937 entry.u.func = copyfunc(func);
7938 addcmdentry(name, &entry);
7942 /* Reasons for skipping commands (see comment on breakcmd routine) */
7943 #define SKIPBREAK (1 << 0)
7944 #define SKIPCONT (1 << 1)
7945 #define SKIPFUNC (1 << 2)
7946 #define SKIPFILE (1 << 3)
7947 #define SKIPEVAL (1 << 4)
7948 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
7949 static int skipcount; /* number of levels to skip */
7950 static int funcnest; /* depth of function calls */
7951 static int loopnest; /* current loop nesting level */
7953 /* Forward decl way out to parsing code - dotrap needs it */
7954 static int evalstring(char *s, int mask);
7956 /* Called to execute a trap.
7957 * Single callsite - at the end of evaltree().
7958 * If we return non-zero, exaltree raises EXEXIT exception.
7960 * Perhaps we should avoid entering new trap handlers
7961 * while we are executing a trap handler. [is it a TODO?]
7970 savestatus = exitstatus;
7974 TRACE(("dotrap entered\n"));
7975 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
7982 /* non-trapped SIGINT is handled separately by raise_interrupt,
7983 * don't upset it by resetting gotsig[SIGINT-1] */
7984 if (sig == SIGINT && !t)
7987 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
7991 want_exexit = evalstring(t, SKIPEVAL);
7992 exitstatus = savestatus;
7994 TRACE(("dotrap returns %d\n", want_exexit));
7999 TRACE(("dotrap returns 0\n"));
8003 /* forward declarations - evaluation is fairly recursive business... */
8004 static void evalloop(union node *, int);
8005 static void evalfor(union node *, int);
8006 static void evalcase(union node *, int);
8007 static void evalsubshell(union node *, int);
8008 static void expredir(union node *);
8009 static void evalpipe(union node *, int);
8010 static void evalcommand(union node *, int);
8011 static int evalbltin(const struct builtincmd *, int, char **);
8012 static void prehash(union node *);
8015 * Evaluate a parse tree. The value is left in the global variable
8019 evaltree(union node *n, int flags)
8021 struct jmploc *volatile savehandler = exception_handler;
8022 struct jmploc jmploc;
8024 void (*evalfn)(union node *, int);
8028 SAVE_INT(int_level);
8031 TRACE(("evaltree(NULL) called\n"));
8034 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8036 exception_handler = &jmploc;
8038 int err = setjmp(jmploc.loc);
8040 /* if it was a signal, check for trap handlers */
8041 if (exception_type == EXSIG) {
8042 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8043 exception_type, err));
8046 /* continue on the way out */
8047 TRACE(("exception %d in evaltree, propagating err=%d\n",
8048 exception_type, err));
8049 exception_handler = savehandler;
8050 longjmp(exception_handler->loc, err);
8057 out1fmt("Node type = %d\n", n->type);
8062 evaltree(n->nnot.com, EV_TESTED);
8063 status = !exitstatus;
8066 expredir(n->nredir.redirect);
8067 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8069 evaltree(n->nredir.n, flags & EV_TESTED);
8070 status = exitstatus;
8072 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8075 evalfn = evalcommand;
8077 if (eflag && !(flags & EV_TESTED))
8089 evalfn = evalsubshell;
8102 #error NAND + 1 != NOR
8104 #if NOR + 1 != NSEMI
8105 #error NOR + 1 != NSEMI
8107 unsigned is_or = n->type - NAND;
8110 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8112 if (!exitstatus == is_or)
8125 evaltree(n->nif.test, EV_TESTED);
8128 if (exitstatus == 0) {
8132 if (n->nif.elsepart) {
8133 n = n->nif.elsepart;
8138 defun(n->narg.text, n->narg.next);
8142 exitstatus = status;
8147 exception_handler = savehandler;
8149 if (checkexit & exitstatus)
8150 evalskip |= SKIPEVAL;
8151 else if (pendingsig && dotrap())
8154 if (flags & EV_EXIT) {
8156 raise_exception(EXEXIT);
8159 RESTORE_INT(int_level);
8160 TRACE(("leaving evaltree (no interrupts)\n"));
8163 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8166 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8169 evalloop(union node *n, int flags)
8179 evaltree(n->nbinary.ch1, EV_TESTED);
8182 if (evalskip == SKIPCONT && --skipcount <= 0) {
8186 if (evalskip == SKIPBREAK && --skipcount <= 0)
8191 if (n->type != NWHILE)
8195 evaltree(n->nbinary.ch2, flags);
8196 status = exitstatus;
8201 exitstatus = status;
8205 evalfor(union node *n, int flags)
8207 struct arglist arglist;
8210 struct stackmark smark;
8212 setstackmark(&smark);
8213 arglist.list = NULL;
8214 arglist.lastp = &arglist.list;
8215 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8216 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8221 *arglist.lastp = NULL;
8226 for (sp = arglist.list; sp; sp = sp->next) {
8227 setvar(n->nfor.var, sp->text, 0);
8228 evaltree(n->nfor.body, flags);
8230 if (evalskip == SKIPCONT && --skipcount <= 0) {
8234 if (evalskip == SKIPBREAK && --skipcount <= 0)
8241 popstackmark(&smark);
8245 evalcase(union node *n, int flags)
8249 struct arglist arglist;
8250 struct stackmark smark;
8252 setstackmark(&smark);
8253 arglist.list = NULL;
8254 arglist.lastp = &arglist.list;
8255 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8257 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8258 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8259 if (casematch(patp, arglist.list->text)) {
8260 if (evalskip == 0) {
8261 evaltree(cp->nclist.body, flags);
8268 popstackmark(&smark);
8272 * Kick off a subshell to evaluate a tree.
8275 evalsubshell(union node *n, int flags)
8278 int backgnd = (n->type == NBACKGND);
8281 expredir(n->nredir.redirect);
8282 if (!backgnd && flags & EV_EXIT && !trap[0])
8285 jp = makejob(/*n,*/ 1);
8286 if (forkshell(jp, n, backgnd) == 0) {
8290 flags &=~ EV_TESTED;
8292 redirect(n->nredir.redirect, 0);
8293 evaltreenr(n->nredir.n, flags);
8298 status = waitforjob(jp);
8299 exitstatus = status;
8304 * Compute the names of the files in a redirection list.
8306 static void fixredir(union node *, const char *, int);
8308 expredir(union node *n)
8312 for (redir = n; redir; redir = redir->nfile.next) {
8316 fn.lastp = &fn.list;
8317 switch (redir->type) {
8321 #if ENABLE_ASH_BASH_COMPAT
8326 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8327 #if ENABLE_ASH_BASH_COMPAT
8330 redir->nfile.expfname = fn.list->text;
8333 case NTOFD: /* >& */
8334 if (redir->ndup.vname) {
8335 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8336 if (fn.list == NULL)
8337 ash_msg_and_raise_error("redir error");
8338 #if ENABLE_ASH_BASH_COMPAT
8339 //FIXME: we used expandarg with different args!
8340 if (!isdigit_str9(fn.list->text)) {
8341 /* >&file, not >&fd */
8342 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8343 ash_msg_and_raise_error("redir error");
8345 goto store_expfname;
8348 fixredir(redir, fn.list->text, 1);
8356 * Evaluate a pipeline. All the processes in the pipeline are children
8357 * of the process creating the pipeline. (This differs from some versions
8358 * of the shell, which make the last process in a pipeline the parent
8362 evalpipe(union node *n, int flags)
8365 struct nodelist *lp;
8370 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8372 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8376 jp = makejob(/*n,*/ pipelen);
8378 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8382 if (pipe(pip) < 0) {
8384 ash_msg_and_raise_error("pipe call failed");
8387 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8400 evaltreenr(lp->n, flags);
8406 /* Don't want to trigger debugging */
8410 if (n->npipe.pipe_backgnd == 0) {
8411 exitstatus = waitforjob(jp);
8412 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8418 * Controls whether the shell is interactive or not.
8421 setinteractive(int on)
8423 static smallint is_interactive;
8425 if (++on == is_interactive)
8427 is_interactive = on;
8431 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8432 if (is_interactive > 1) {
8433 /* Looks like they want an interactive shell */
8434 static smallint did_banner;
8439 "%s built-in shell (ash)\n"
8440 "Enter 'help' for a list of built-in commands."
8455 setinteractive(iflag);
8457 #if ENABLE_FEATURE_EDITING_VI
8459 line_input_state->flags |= VI_MODE;
8461 line_input_state->flags &= ~VI_MODE;
8463 viflag = 0; /* forcibly keep the option off */
8467 static struct localvar *localvars;
8470 * Called after a function returns.
8471 * Interrupts must be off.
8476 struct localvar *lvp;
8479 while ((lvp = localvars) != NULL) {
8480 localvars = lvp->next;
8482 TRACE(("poplocalvar %s", vp ? vp->text : "-"));
8483 if (vp == NULL) { /* $- saved */
8484 memcpy(optlist, lvp->text, sizeof(optlist));
8485 free((char*)lvp->text);
8487 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8491 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8492 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8493 free((char*)vp->text);
8494 vp->flags = lvp->flags;
8495 vp->text = lvp->text;
8502 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8504 volatile struct shparam saveparam;
8505 struct localvar *volatile savelocalvars;
8506 struct jmploc *volatile savehandler;
8507 struct jmploc jmploc;
8510 saveparam = shellparam;
8511 savelocalvars = localvars;
8512 e = setjmp(jmploc.loc);
8517 savehandler = exception_handler;
8518 exception_handler = &jmploc;
8520 shellparam.malloced = 0;
8524 shellparam.nparam = argc - 1;
8525 shellparam.p = argv + 1;
8526 #if ENABLE_ASH_GETOPTS
8527 shellparam.optind = 1;
8528 shellparam.optoff = -1;
8530 evaltree(&func->n, flags & EV_TESTED);
8536 localvars = savelocalvars;
8537 freeparam(&shellparam);
8538 shellparam = saveparam;
8539 exception_handler = savehandler;
8541 evalskip &= ~SKIPFUNC;
8545 #if ENABLE_ASH_CMDCMD
8547 parse_command_args(char **argv, const char **path)
8560 if (c == '-' && !*cp) {
8567 *path = bb_default_path;
8570 /* run 'typecmd' for other options */
8581 * Make a variable a local variable. When a variable is made local, it's
8582 * value and flags are saved in a localvar structure. The saved values
8583 * will be restored when the shell function returns. We handle the name
8584 * "-" as a special case.
8589 struct localvar *lvp;
8594 lvp = ckzalloc(sizeof(struct localvar));
8595 if (LONE_DASH(name)) {
8597 p = ckmalloc(sizeof(optlist));
8598 lvp->text = memcpy(p, optlist, sizeof(optlist));
8603 vpp = hashvar(name);
8604 vp = *findvar(vpp, name);
8605 eq = strchr(name, '=');
8608 setvareq(name, VSTRFIXED);
8610 setvar(name, NULL, VSTRFIXED);
8611 vp = *vpp; /* the new variable */
8612 lvp->flags = VUNSET;
8614 lvp->text = vp->text;
8615 lvp->flags = vp->flags;
8616 vp->flags |= VSTRFIXED|VTEXTFIXED;
8622 lvp->next = localvars;
8628 * The "local" command.
8631 localcmd(int argc UNUSED_PARAM, char **argv)
8636 while ((name = *argv++) != NULL) {
8643 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8649 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8655 execcmd(int argc UNUSED_PARAM, char **argv)
8658 iflag = 0; /* exit on error */
8661 shellexec(argv + 1, pathval(), 0);
8667 * The return command.
8670 returncmd(int argc UNUSED_PARAM, char **argv)
8673 * If called outside a function, do what ksh does;
8674 * skip the rest of the file.
8676 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8677 return argv[1] ? number(argv[1]) : exitstatus;
8680 /* Forward declarations for builtintab[] */
8681 static int breakcmd(int, char **);
8682 static int dotcmd(int, char **);
8683 static int evalcmd(int, char **);
8684 static int exitcmd(int, char **);
8685 static int exportcmd(int, char **);
8686 #if ENABLE_ASH_GETOPTS
8687 static int getoptscmd(int, char **);
8689 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8690 static int helpcmd(int, char **);
8692 #if ENABLE_SH_MATH_SUPPORT
8693 static int letcmd(int, char **);
8695 static int readcmd(int, char **);
8696 static int setcmd(int, char **);
8697 static int shiftcmd(int, char **);
8698 static int timescmd(int, char **);
8699 static int trapcmd(int, char **);
8700 static int umaskcmd(int, char **);
8701 static int unsetcmd(int, char **);
8702 static int ulimitcmd(int, char **);
8704 #define BUILTIN_NOSPEC "0"
8705 #define BUILTIN_SPECIAL "1"
8706 #define BUILTIN_REGULAR "2"
8707 #define BUILTIN_SPEC_REG "3"
8708 #define BUILTIN_ASSIGN "4"
8709 #define BUILTIN_SPEC_ASSG "5"
8710 #define BUILTIN_REG_ASSG "6"
8711 #define BUILTIN_SPEC_REG_ASSG "7"
8713 /* We do not handle [[ expr ]] bashism bash-compatibly,
8714 * we make it a synonym of [ expr ].
8715 * Basically, word splitting and pathname expansion should NOT be performed
8717 * no word splitting: a="a b"; [[ $a = "a b" ]]; echo $? should print "0"
8718 * no pathname expansion: [[ /bin/m* = "/bin/m*" ]]; echo $? should print "0"
8719 * Additional operators:
8720 * || and && should work as -o and -a
8722 * Apart from the above, [[ expr ]] should work as [ expr ]
8725 #define echocmd echo_main
8726 #define printfcmd printf_main
8727 #define testcmd test_main
8729 /* Keep these in proper order since it is searched via bsearch() */
8730 static const struct builtincmd builtintab[] = {
8731 { BUILTIN_SPEC_REG ".", dotcmd },
8732 { BUILTIN_SPEC_REG ":", truecmd },
8733 #if ENABLE_ASH_BUILTIN_TEST
8734 { BUILTIN_REGULAR "[", testcmd },
8735 #if ENABLE_ASH_BASH_COMPAT
8736 { BUILTIN_REGULAR "[[", testcmd },
8739 #if ENABLE_ASH_ALIAS
8740 { BUILTIN_REG_ASSG "alias", aliascmd },
8743 { BUILTIN_REGULAR "bg", fg_bgcmd },
8745 { BUILTIN_SPEC_REG "break", breakcmd },
8746 { BUILTIN_REGULAR "cd", cdcmd },
8747 { BUILTIN_NOSPEC "chdir", cdcmd },
8748 #if ENABLE_ASH_CMDCMD
8749 { BUILTIN_REGULAR "command", commandcmd },
8751 { BUILTIN_SPEC_REG "continue", breakcmd },
8752 #if ENABLE_ASH_BUILTIN_ECHO
8753 { BUILTIN_REGULAR "echo", echocmd },
8755 { BUILTIN_SPEC_REG "eval", evalcmd },
8756 { BUILTIN_SPEC_REG "exec", execcmd },
8757 { BUILTIN_SPEC_REG "exit", exitcmd },
8758 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8759 { BUILTIN_REGULAR "false", falsecmd },
8761 { BUILTIN_REGULAR "fg", fg_bgcmd },
8763 #if ENABLE_ASH_GETOPTS
8764 { BUILTIN_REGULAR "getopts", getoptscmd },
8766 { BUILTIN_NOSPEC "hash", hashcmd },
8767 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8768 { BUILTIN_NOSPEC "help", helpcmd },
8771 { BUILTIN_REGULAR "jobs", jobscmd },
8772 { BUILTIN_REGULAR "kill", killcmd },
8774 #if ENABLE_SH_MATH_SUPPORT
8775 { BUILTIN_NOSPEC "let", letcmd },
8777 { BUILTIN_ASSIGN "local", localcmd },
8778 #if ENABLE_ASH_BUILTIN_PRINTF
8779 { BUILTIN_REGULAR "printf", printfcmd },
8781 { BUILTIN_NOSPEC "pwd", pwdcmd },
8782 { BUILTIN_REGULAR "read", readcmd },
8783 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8784 { BUILTIN_SPEC_REG "return", returncmd },
8785 { BUILTIN_SPEC_REG "set", setcmd },
8786 { BUILTIN_SPEC_REG "shift", shiftcmd },
8787 { BUILTIN_SPEC_REG "source", dotcmd },
8788 #if ENABLE_ASH_BUILTIN_TEST
8789 { BUILTIN_REGULAR "test", testcmd },
8791 { BUILTIN_SPEC_REG "times", timescmd },
8792 { BUILTIN_SPEC_REG "trap", trapcmd },
8793 { BUILTIN_REGULAR "true", truecmd },
8794 { BUILTIN_NOSPEC "type", typecmd },
8795 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8796 { BUILTIN_REGULAR "umask", umaskcmd },
8797 #if ENABLE_ASH_ALIAS
8798 { BUILTIN_REGULAR "unalias", unaliascmd },
8800 { BUILTIN_SPEC_REG "unset", unsetcmd },
8801 { BUILTIN_REGULAR "wait", waitcmd },
8804 /* Should match the above table! */
8805 #define COMMANDCMD (builtintab + \
8807 1 * ENABLE_ASH_BUILTIN_TEST + \
8808 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8809 1 * ENABLE_ASH_ALIAS + \
8810 1 * ENABLE_ASH_JOB_CONTROL + \
8812 #define EXECCMD (builtintab + \
8814 1 * ENABLE_ASH_BUILTIN_TEST + \
8815 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8816 1 * ENABLE_ASH_ALIAS + \
8817 1 * ENABLE_ASH_JOB_CONTROL + \
8819 1 * ENABLE_ASH_CMDCMD + \
8821 ENABLE_ASH_BUILTIN_ECHO + \
8825 * Search the table of builtin commands.
8827 static struct builtincmd *
8828 find_builtin(const char *name)
8830 struct builtincmd *bp;
8833 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8840 * Execute a simple command.
8843 isassignment(const char *p)
8845 const char *q = endofname(p);
8851 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8853 /* Preserve exitstatus of a previous possible redirection
8854 * as POSIX mandates */
8855 return back_exitstatus;
8858 evalcommand(union node *cmd, int flags)
8860 static const struct builtincmd null_bltin = {
8861 "\0\0", bltincmd /* why three NULs? */
8863 struct stackmark smark;
8865 struct arglist arglist;
8866 struct arglist varlist;
8869 const struct strlist *sp;
8870 struct cmdentry cmdentry;
8877 struct builtincmd *bcmd;
8878 smallint cmd_is_exec;
8879 smallint pseudovarflag = 0;
8881 /* First expand the arguments. */
8882 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8883 setstackmark(&smark);
8884 back_exitstatus = 0;
8886 cmdentry.cmdtype = CMDBUILTIN;
8887 cmdentry.u.cmd = &null_bltin;
8888 varlist.lastp = &varlist.list;
8889 *varlist.lastp = NULL;
8890 arglist.lastp = &arglist.list;
8891 *arglist.lastp = NULL;
8894 if (cmd->ncmd.args) {
8895 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8896 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8899 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8900 struct strlist **spp;
8902 spp = arglist.lastp;
8903 if (pseudovarflag && isassignment(argp->narg.text))
8904 expandarg(argp, &arglist, EXP_VARTILDE);
8906 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8908 for (sp = *spp; sp; sp = sp->next)
8912 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
8913 for (sp = arglist.list; sp; sp = sp->next) {
8914 TRACE(("evalcommand arg: %s\n", sp->text));
8915 *nargv++ = sp->text;
8920 if (iflag && funcnest == 0 && argc > 0)
8921 lastarg = nargv[-1];
8924 expredir(cmd->ncmd.redirect);
8925 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
8928 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
8929 struct strlist **spp;
8932 spp = varlist.lastp;
8933 expandarg(argp, &varlist, EXP_VARTILDE);
8936 * Modify the command lookup path, if a PATH= assignment
8940 if (varequal(p, path))
8944 /* Print the command if xflag is set. */
8947 const char *p = " %s";
8950 fdprintf(preverrout_fd, p, expandstr(ps4val()));
8953 for (n = 0; n < 2; n++) {
8955 fdprintf(preverrout_fd, p, sp->text);
8963 safe_write(preverrout_fd, "\n", 1);
8969 /* Now locate the command. */
8971 const char *oldpath;
8972 int cmd_flag = DO_ERR;
8977 find_command(argv[0], &cmdentry, cmd_flag, path);
8978 if (cmdentry.cmdtype == CMDUNKNOWN) {
8984 /* implement bltin and command here */
8985 if (cmdentry.cmdtype != CMDBUILTIN)
8988 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
8989 if (cmdentry.u.cmd == EXECCMD)
8991 #if ENABLE_ASH_CMDCMD
8992 if (cmdentry.u.cmd == COMMANDCMD) {
8994 nargv = parse_command_args(argv, &path);
8997 argc -= nargv - argv;
8999 cmd_flag |= DO_NOFUNC;
9007 /* We have a redirection error. */
9009 raise_exception(EXERROR);
9011 exitstatus = status;
9015 /* Execute the command. */
9016 switch (cmdentry.cmdtype) {
9019 #if ENABLE_FEATURE_SH_NOFORK
9020 /* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9021 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
9023 /* find_command() encodes applet_no as (-2 - applet_no) */
9024 int applet_no = (- cmdentry.u.index - 2);
9025 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9026 listsetvar(varlist.list, VEXPORT|VSTACK);
9027 /* run <applet>_main() */
9028 exitstatus = run_nofork_applet(applet_no, argv);
9033 /* Fork off a child process if necessary. */
9034 if (!(flags & EV_EXIT) || trap[0]) {
9036 jp = makejob(/*cmd,*/ 1);
9037 if (forkshell(jp, cmd, FORK_FG) != 0) {
9038 exitstatus = waitforjob(jp);
9040 TRACE(("forked child exited with %d\n", exitstatus));
9045 listsetvar(varlist.list, VEXPORT|VSTACK);
9046 shellexec(argv, path, cmdentry.u.index);
9050 cmdenviron = varlist.list;
9052 struct strlist *list = cmdenviron;
9054 if (spclbltin > 0 || argc == 0) {
9056 if (cmd_is_exec && argc > 1)
9059 listsetvar(list, i);
9061 /* Tight loop with builtins only:
9062 * "while kill -0 $child; do true; done"
9063 * will never exit even if $child died, unless we do this
9064 * to reap the zombie and make kill detect that it's gone: */
9065 dowait(DOWAIT_NONBLOCK, NULL);
9067 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9069 int i = exception_type;
9074 exit_status = 128 + SIGINT;
9076 exit_status = 128 + pendingsig;
9077 exitstatus = exit_status;
9078 if (i == EXINT || spclbltin > 0) {
9080 longjmp(exception_handler->loc, 1);
9087 listsetvar(varlist.list, 0);
9088 /* See above for the rationale */
9089 dowait(DOWAIT_NONBLOCK, NULL);
9090 if (evalfun(cmdentry.u.func, argc, argv, flags))
9096 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9098 /* dsl: I think this is intended to be used to support
9099 * '_' in 'vi' command mode during line editing...
9100 * However I implemented that within libedit itself.
9102 setvar("_", lastarg, 0);
9104 popstackmark(&smark);
9108 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9110 char *volatile savecmdname;
9111 struct jmploc *volatile savehandler;
9112 struct jmploc jmploc;
9115 savecmdname = commandname;
9116 i = setjmp(jmploc.loc);
9119 savehandler = exception_handler;
9120 exception_handler = &jmploc;
9121 commandname = argv[0];
9123 optptr = NULL; /* initialize nextopt */
9124 exitstatus = (*cmd->builtin)(argc, argv);
9125 flush_stdout_stderr();
9127 exitstatus |= ferror(stdout);
9129 commandname = savecmdname;
9131 exception_handler = savehandler;
9137 goodname(const char *p)
9139 return !*endofname(p);
9144 * Search for a command. This is called before we fork so that the
9145 * location of the command will be available in the parent as well as
9146 * the child. The check for "goodname" is an overly conservative
9147 * check that the name will not be subject to expansion.
9150 prehash(union node *n)
9152 struct cmdentry entry;
9154 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9155 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9159 /* ============ Builtin commands
9161 * Builtin commands whose functions are closely tied to evaluation
9162 * are implemented here.
9166 * Handle break and continue commands. Break, continue, and return are
9167 * all handled by setting the evalskip flag. The evaluation routines
9168 * above all check this flag, and if it is set they start skipping
9169 * commands rather than executing them. The variable skipcount is
9170 * the number of loops to break/continue, or the number of function
9171 * levels to return. (The latter is always 1.) It should probably
9172 * be an error to break out of more loops than exist, but it isn't
9173 * in the standard shell so we don't make it one here.
9176 breakcmd(int argc UNUSED_PARAM, char **argv)
9178 int n = argv[1] ? number(argv[1]) : 1;
9181 ash_msg_and_raise_error(illnum, argv[1]);
9185 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9192 /* ============ input.c
9194 * This implements the input routines used by the parser.
9198 INPUT_PUSH_FILE = 1,
9199 INPUT_NOFILE_OK = 2,
9202 static smallint checkkwd;
9203 /* values of checkkwd variable */
9204 #define CHKALIAS 0x1
9209 * Push a string back onto the input at this current parsefile level.
9210 * We handle aliases this way.
9212 #if !ENABLE_ASH_ALIAS
9213 #define pushstring(s, ap) pushstring(s)
9216 pushstring(char *s, struct alias *ap)
9223 if (g_parsefile->strpush) {
9224 sp = ckzalloc(sizeof(*sp));
9225 sp->prev = g_parsefile->strpush;
9227 sp = &(g_parsefile->basestrpush);
9229 g_parsefile->strpush = sp;
9230 sp->prev_string = g_parsefile->next_to_pgetc;
9231 sp->prev_left_in_line = g_parsefile->left_in_line;
9232 #if ENABLE_ASH_ALIAS
9235 ap->flag |= ALIASINUSE;
9239 g_parsefile->next_to_pgetc = s;
9240 g_parsefile->left_in_line = len;
9247 struct strpush *sp = g_parsefile->strpush;
9250 #if ENABLE_ASH_ALIAS
9252 if (g_parsefile->next_to_pgetc[-1] == ' '
9253 || g_parsefile->next_to_pgetc[-1] == '\t'
9255 checkkwd |= CHKALIAS;
9257 if (sp->string != sp->ap->val) {
9260 sp->ap->flag &= ~ALIASINUSE;
9261 if (sp->ap->flag & ALIASDEAD) {
9262 unalias(sp->ap->name);
9266 g_parsefile->next_to_pgetc = sp->prev_string;
9267 g_parsefile->left_in_line = sp->prev_left_in_line;
9268 g_parsefile->strpush = sp->prev;
9269 if (sp != &(g_parsefile->basestrpush))
9274 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9275 //it peeks whether it is &>, and then pushes back both chars.
9276 //This function needs to save last *next_to_pgetc to buf[0]
9277 //to make two pungetc() reliable. Currently,
9278 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9283 char *buf = g_parsefile->buf;
9285 g_parsefile->next_to_pgetc = buf;
9286 #if ENABLE_FEATURE_EDITING
9288 if (!iflag || g_parsefile->fd != STDIN_FILENO)
9289 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9291 #if ENABLE_FEATURE_TAB_COMPLETION
9292 line_input_state->path_lookup = pathval();
9294 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9296 /* Ctrl+C pressed */
9305 if (nr < 0 && errno == 0) {
9306 /* Ctrl+D pressed */
9311 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9315 /* nonblock_safe_read() handles this problem */
9317 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9318 int flags = fcntl(0, F_GETFL);
9319 if (flags >= 0 && (flags & O_NONBLOCK)) {
9320 flags &= ~O_NONBLOCK;
9321 if (fcntl(0, F_SETFL, flags) >= 0) {
9322 out2str("sh: turning off NDELAY mode\n");
9333 * Refill the input buffer and return the next input character:
9335 * 1) If a string was pushed back on the input, pop it;
9336 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9337 * or we are reading from a string so we can't refill the buffer,
9339 * 3) If the is more stuff in this buffer, use it else call read to fill it.
9340 * 4) Process input up to the next newline, deleting nul characters.
9342 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9343 #define pgetc_debug(...) ((void)0)
9345 * NB: due to SIT(c) internals (syntax_index_table[] vector),
9346 * pgetc() and related functions must return chars SIGN-EXTENDED into ints,
9347 * not zero-extended. Seems fragile to me. Affects only !USE_SIT_FUNCTION case,
9348 * so we can fix it by ditching !USE_SIT_FUNCTION if Unicode requires that.
9356 while (g_parsefile->strpush) {
9357 #if ENABLE_ASH_ALIAS
9358 if (g_parsefile->left_in_line == -1
9359 && g_parsefile->strpush->ap
9360 && g_parsefile->next_to_pgetc[-1] != ' '
9361 && g_parsefile->next_to_pgetc[-1] != '\t'
9363 pgetc_debug("preadbuffer PEOA");
9368 /* try "pgetc" now: */
9369 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9370 g_parsefile->left_in_line,
9371 g_parsefile->next_to_pgetc,
9372 g_parsefile->next_to_pgetc);
9373 if (--g_parsefile->left_in_line >= 0)
9374 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9376 /* on both branches above g_parsefile->left_in_line < 0.
9377 * "pgetc" needs refilling.
9380 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9381 * pungetc() may increment it a few times.
9382 * Assuming it won't increment it to less than -90.
9384 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9385 pgetc_debug("preadbuffer PEOF1");
9386 /* even in failure keep left_in_line and next_to_pgetc
9387 * in lock step, for correct multi-layer pungetc.
9388 * left_in_line was decremented before preadbuffer(),
9389 * must inc next_to_pgetc: */
9390 g_parsefile->next_to_pgetc++;
9394 more = g_parsefile->left_in_buffer;
9396 flush_stdout_stderr();
9400 /* don't try reading again */
9401 g_parsefile->left_in_line = -99;
9402 pgetc_debug("preadbuffer PEOF2");
9403 g_parsefile->next_to_pgetc++;
9408 /* Find out where's the end of line.
9409 * Set g_parsefile->left_in_line
9410 * and g_parsefile->left_in_buffer acordingly.
9411 * NUL chars are deleted.
9413 q = g_parsefile->next_to_pgetc;
9421 memmove(q, q + 1, more);
9425 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9431 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9432 if (g_parsefile->left_in_line < 0)
9437 g_parsefile->left_in_buffer = more;
9442 out2str(g_parsefile->next_to_pgetc);
9446 pgetc_debug("preadbuffer at %d:%p'%s'",
9447 g_parsefile->left_in_line,
9448 g_parsefile->next_to_pgetc,
9449 g_parsefile->next_to_pgetc);
9450 return signed_char2int(*g_parsefile->next_to_pgetc++);
9453 #define pgetc_as_macro() \
9454 (--g_parsefile->left_in_line >= 0 \
9455 ? signed_char2int(*g_parsefile->next_to_pgetc++) \
9462 pgetc_debug("pgetc_fast at %d:%p'%s'",
9463 g_parsefile->left_in_line,
9464 g_parsefile->next_to_pgetc,
9465 g_parsefile->next_to_pgetc);
9466 return pgetc_as_macro();
9469 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9470 #define pgetc_fast() pgetc()
9472 #define pgetc_fast() pgetc_as_macro()
9476 * Same as pgetc(), but ignores PEOA.
9478 #if ENABLE_ASH_ALIAS
9484 pgetc_debug("pgetc_fast at %d:%p'%s'",
9485 g_parsefile->left_in_line,
9486 g_parsefile->next_to_pgetc,
9487 g_parsefile->next_to_pgetc);
9489 } while (c == PEOA);
9493 #define pgetc2() pgetc()
9497 * Read a line from the script.
9500 pfgets(char *line, int len)
9506 while (--nleft > 0) {
9522 * Undo the last call to pgetc. Only one character may be pushed back.
9523 * PEOF may be pushed back.
9528 g_parsefile->left_in_line++;
9529 g_parsefile->next_to_pgetc--;
9530 pgetc_debug("pushed back to %d:%p'%s'",
9531 g_parsefile->left_in_line,
9532 g_parsefile->next_to_pgetc,
9533 g_parsefile->next_to_pgetc);
9537 * To handle the "." command, a stack of input files is used. Pushfile
9538 * adds a new entry to the stack and popfile restores the previous level.
9543 struct parsefile *pf;
9545 pf = ckzalloc(sizeof(*pf));
9546 pf->prev = g_parsefile;
9548 /*pf->strpush = NULL; - ckzalloc did it */
9549 /*pf->basestrpush.prev = NULL;*/
9556 struct parsefile *pf = g_parsefile;
9564 g_parsefile = pf->prev;
9570 * Return to top level.
9575 while (g_parsefile != &basepf)
9580 * Close the file(s) that the shell is reading commands from. Called
9581 * after a fork is done.
9587 if (g_parsefile->fd > 0) {
9588 close(g_parsefile->fd);
9589 g_parsefile->fd = 0;
9594 * Like setinputfile, but takes an open file descriptor. Call this with
9598 setinputfd(int fd, int push)
9600 close_on_exec_on(fd);
9603 g_parsefile->buf = NULL;
9605 g_parsefile->fd = fd;
9606 if (g_parsefile->buf == NULL)
9607 g_parsefile->buf = ckmalloc(IBUFSIZ);
9608 g_parsefile->left_in_buffer = 0;
9609 g_parsefile->left_in_line = 0;
9610 g_parsefile->linno = 1;
9614 * Set the input to take input from a file. If push is set, push the
9615 * old input onto the stack first.
9618 setinputfile(const char *fname, int flags)
9624 fd = open(fname, O_RDONLY);
9626 if (flags & INPUT_NOFILE_OK)
9628 ash_msg_and_raise_error("can't open '%s'", fname);
9631 fd2 = copyfd(fd, 10);
9634 ash_msg_and_raise_error("out of file descriptors");
9637 setinputfd(fd, flags & INPUT_PUSH_FILE);
9644 * Like setinputfile, but takes input from a string.
9647 setinputstring(char *string)
9651 g_parsefile->next_to_pgetc = string;
9652 g_parsefile->left_in_line = strlen(string);
9653 g_parsefile->buf = NULL;
9654 g_parsefile->linno = 1;
9659 /* ============ mail.c
9661 * Routines to check for mail.
9666 #define MAXMBOXES 10
9668 /* times of mailboxes */
9669 static time_t mailtime[MAXMBOXES];
9670 /* Set if MAIL or MAILPATH is changed. */
9671 static smallint mail_var_path_changed;
9674 * Print appropriate message(s) if mail has arrived.
9675 * If mail_var_path_changed is set,
9676 * then the value of MAIL has mail_var_path_changed,
9677 * so we just update the values.
9686 struct stackmark smark;
9689 setstackmark(&smark);
9690 mpath = mpathset() ? mpathval() : mailval();
9691 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9692 p = padvance(&mpath, nullstr);
9697 for (q = p; *q; q++)
9703 q[-1] = '\0'; /* delete trailing '/' */
9704 if (stat(p, &statb) < 0) {
9708 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9711 pathopt ? pathopt : "you have mail"
9714 *mtp = statb.st_mtime;
9716 mail_var_path_changed = 0;
9717 popstackmark(&smark);
9721 changemail(const char *val UNUSED_PARAM)
9723 mail_var_path_changed = 1;
9726 #endif /* ASH_MAIL */
9729 /* ============ ??? */
9732 * Set the shell parameters.
9735 setparam(char **argv)
9741 for (nparam = 0; argv[nparam]; nparam++)
9743 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9745 *ap++ = ckstrdup(*argv++);
9748 freeparam(&shellparam);
9749 shellparam.malloced = 1;
9750 shellparam.nparam = nparam;
9751 shellparam.p = newparam;
9752 #if ENABLE_ASH_GETOPTS
9753 shellparam.optind = 1;
9754 shellparam.optoff = -1;
9759 * Process shell options. The global variable argptr contains a pointer
9760 * to the argument list; we advance it past the options.
9762 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9763 * For a non-interactive shell, an error condition encountered
9764 * by a special built-in ... shall cause the shell to write a diagnostic message
9765 * to standard error and exit as shown in the following table:
9766 * Error Special Built-In
9768 * Utility syntax error (option or operand error) Shall exit
9770 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9771 * we see that bash does not do that (set "finishes" with error code 1 instead,
9772 * and shell continues), and people rely on this behavior!
9774 * set -o barfoo 2>/dev/null
9777 * Oh well. Let's mimic that.
9780 plus_minus_o(char *name, int val)
9785 for (i = 0; i < NOPTS; i++) {
9786 if (strcmp(name, optnames(i)) == 0) {
9791 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9794 for (i = 0; i < NOPTS; i++) {
9796 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9798 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9804 setoption(int flag, int val)
9808 for (i = 0; i < NOPTS; i++) {
9809 if (optletters(i) == flag) {
9814 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9818 options(int cmdline)
9826 while ((p = *argptr) != NULL) {
9828 if (c != '-' && c != '+')
9831 val = 0; /* val = 0 if c == '+' */
9834 if (p[0] == '\0' || LONE_DASH(p)) {
9836 /* "-" means turn off -x and -v */
9839 /* "--" means reset params */
9840 else if (*argptr == NULL)
9843 break; /* "-" or "--" terminates options */
9846 /* first char was + or - */
9847 while ((c = *p++) != '\0') {
9848 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9849 if (c == 'c' && cmdline) {
9850 minusc = p; /* command is after shell args */
9851 } else if (c == 'o') {
9852 if (plus_minus_o(*argptr, val)) {
9853 /* it already printed err message */
9854 return 1; /* error */
9858 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9860 /* bash does not accept +-login, we also won't */
9861 } else if (cmdline && val && (c == '-')) { /* long options */
9862 if (strcmp(p, "login") == 0)
9874 * The shift builtin command.
9877 shiftcmd(int argc UNUSED_PARAM, char **argv)
9884 n = number(argv[1]);
9885 if (n > shellparam.nparam)
9886 n = 0; /* bash compat, was = shellparam.nparam; */
9888 shellparam.nparam -= n;
9889 for (ap1 = shellparam.p; --n >= 0; ap1++) {
9890 if (shellparam.malloced)
9894 while ((*ap2++ = *ap1++) != NULL)
9896 #if ENABLE_ASH_GETOPTS
9897 shellparam.optind = 1;
9898 shellparam.optoff = -1;
9905 * POSIX requires that 'set' (but not export or readonly) output the
9906 * variables in lexicographic order - by the locale's collating order (sigh).
9907 * Maybe we could keep them in an ordered balanced binary tree
9908 * instead of hashed lists.
9909 * For now just roll 'em through qsort for printing...
9912 showvars(const char *sep_prefix, int on, int off)
9917 ep = listvars(on, off, &epend);
9918 qsort(ep, epend - ep, sizeof(char *), vpcmp);
9920 sep = *sep_prefix ? " " : sep_prefix;
9922 for (; ep < epend; ep++) {
9926 p = strchrnul(*ep, '=');
9929 q = single_quote(++p);
9930 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
9936 * The set command builtin.
9939 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9944 return showvars(nullstr, 0, VUNSET);
9947 if (!options(0)) { /* if no parse error... */
9950 if (*argptr != NULL) {
9958 #if ENABLE_ASH_RANDOM_SUPPORT
9960 change_random(const char *value)
9962 /* Galois LFSR parameter */
9963 /* Taps at 32 31 29 1: */
9964 enum { MASK = 0x8000000b };
9965 /* Another example - taps at 32 31 30 10: */
9966 /* MASK = 0x00400007 */
9968 if (value == NULL) {
9969 /* "get", generate */
9972 /* LCG has period of 2^32 and alternating lowest bit */
9973 random_LCG = 1664525 * random_LCG + 1013904223;
9974 /* Galois LFSR has period of 2^32-1 = 3 * 5 * 17 * 257 * 65537 */
9975 t = (random_galois_LFSR << 1);
9976 if (random_galois_LFSR < 0) /* if we just shifted 1 out of msb... */
9978 random_galois_LFSR = t;
9979 /* Both are weak, combining them gives better randomness
9980 * and ~2^64 period. & 0x7fff is probably bash compat
9981 * for $RANDOM range. Combining with subtraction is
9982 * just for fun. + and ^ would work equally well. */
9983 t = (t - random_LCG) & 0x7fff;
9984 /* set without recursion */
9985 setvar(vrandom.text, utoa(t), VNOFUNC);
9986 vrandom.flags &= ~VNOFUNC;
9989 random_galois_LFSR = random_LCG = strtoul(value, (char **)NULL, 10);
9994 #if ENABLE_ASH_GETOPTS
9996 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10005 if (*param_optind < 1)
10007 optnext = optfirst + *param_optind - 1;
10009 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10012 p = optnext[-1] + *optoff;
10013 if (p == NULL || *p == '\0') {
10014 /* Current word is done, advance */
10016 if (p == NULL || *p != '-' || *++p == '\0') {
10023 if (LONE_DASH(p)) /* check for "--" */
10028 for (q = optstr; *q != c;) {
10030 if (optstr[0] == ':') {
10033 err |= setvarsafe("OPTARG", s, 0);
10035 fprintf(stderr, "Illegal option -%c\n", c);
10036 unsetvar("OPTARG");
10046 if (*p == '\0' && (p = *optnext) == NULL) {
10047 if (optstr[0] == ':') {
10050 err |= setvarsafe("OPTARG", s, 0);
10053 fprintf(stderr, "No arg for -%c option\n", c);
10054 unsetvar("OPTARG");
10062 err |= setvarsafe("OPTARG", p, 0);
10065 err |= setvarsafe("OPTARG", nullstr, 0);
10067 *optoff = p ? p - *(optnext - 1) : -1;
10068 *param_optind = optnext - optfirst + 1;
10069 fmtstr(s, sizeof(s), "%d", *param_optind);
10070 err |= setvarsafe("OPTIND", s, VNOFUNC);
10073 err |= setvarsafe(optvar, s, 0);
10077 flush_stdout_stderr();
10078 raise_exception(EXERROR);
10084 * The getopts builtin. Shellparam.optnext points to the next argument
10085 * to be processed. Shellparam.optptr points to the next character to
10086 * be processed in the current argument. If shellparam.optnext is NULL,
10087 * then it's the first time getopts has been called.
10090 getoptscmd(int argc, char **argv)
10095 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10097 optbase = shellparam.p;
10098 if (shellparam.optind > shellparam.nparam + 1) {
10099 shellparam.optind = 1;
10100 shellparam.optoff = -1;
10103 optbase = &argv[3];
10104 if (shellparam.optind > argc - 2) {
10105 shellparam.optind = 1;
10106 shellparam.optoff = -1;
10110 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10111 &shellparam.optoff);
10113 #endif /* ASH_GETOPTS */
10116 /* ============ Shell parser */
10119 struct heredoc *next; /* next here document in list */
10120 union node *here; /* redirection node */
10121 char *eofmark; /* string indicating end of input */
10122 smallint striptabs; /* if set, strip leading tabs */
10125 static smallint tokpushback; /* last token pushed back */
10126 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10127 static smallint quoteflag; /* set if (part of) last token was quoted */
10128 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10129 static struct heredoc *heredoclist; /* list of here documents to read */
10130 static char *wordtext; /* text of last word returned by readtoken */
10131 static struct nodelist *backquotelist;
10132 static union node *redirnode;
10133 static struct heredoc *heredoc;
10135 * NEOF is returned by parsecmd when it encounters an end of file. It
10136 * must be distinct from NULL, so we use the address of a variable that
10137 * happens to be handy.
10139 #define NEOF ((union node *)&tokpushback)
10141 static void raise_error_syntax(const char *) NORETURN;
10143 raise_error_syntax(const char *msg)
10145 ash_msg_and_raise_error("syntax error: %s", msg);
10150 * Called when an unexpected token is read during the parse. The argument
10151 * is the token that is expected, or -1 if more than one type of token can
10152 * occur at this point.
10154 static void raise_error_unexpected_syntax(int) NORETURN;
10156 raise_error_unexpected_syntax(int token)
10161 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
10163 sprintf(msg + l, " (expecting %s)", tokname(token));
10164 raise_error_syntax(msg);
10168 #define EOFMARKLEN 79
10170 /* parsing is heavily cross-recursive, need these forward decls */
10171 static union node *andor(void);
10172 static union node *pipeline(void);
10173 static union node *parse_command(void);
10174 static void parseheredoc(void);
10175 static char peektoken(void);
10176 static int readtoken(void);
10178 static union node *
10181 union node *n1, *n2, *n3;
10184 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10185 if (nlflag == 2 && peektoken())
10191 if (tok == TBACKGND) {
10192 if (n2->type == NPIPE) {
10193 n2->npipe.pipe_backgnd = 1;
10195 if (n2->type != NREDIR) {
10196 n3 = stzalloc(sizeof(struct nredir));
10198 /*n3->nredir.redirect = NULL; - stzalloc did it */
10201 n2->type = NBACKGND;
10207 n3 = stzalloc(sizeof(struct nbinary));
10209 n3->nbinary.ch1 = n1;
10210 n3->nbinary.ch2 = n2;
10226 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10234 pungetc(); /* push back EOF on input */
10238 raise_error_unexpected_syntax(-1);
10245 static union node *
10248 union node *n1, *n2, *n3;
10256 } else if (t == TOR) {
10262 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10264 n3 = stzalloc(sizeof(struct nbinary));
10266 n3->nbinary.ch1 = n1;
10267 n3->nbinary.ch2 = n2;
10272 static union node *
10275 union node *n1, *n2, *pipenode;
10276 struct nodelist *lp, *prev;
10280 TRACE(("pipeline: entered\n"));
10281 if (readtoken() == TNOT) {
10283 checkkwd = CHKKWD | CHKALIAS;
10286 n1 = parse_command();
10287 if (readtoken() == TPIPE) {
10288 pipenode = stzalloc(sizeof(struct npipe));
10289 pipenode->type = NPIPE;
10290 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10291 lp = stzalloc(sizeof(struct nodelist));
10292 pipenode->npipe.cmdlist = lp;
10296 lp = stzalloc(sizeof(struct nodelist));
10297 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10298 lp->n = parse_command();
10300 } while (readtoken() == TPIPE);
10306 n2 = stzalloc(sizeof(struct nnot));
10314 static union node *
10319 n = stzalloc(sizeof(struct narg));
10321 /*n->narg.next = NULL; - stzalloc did it */
10322 n->narg.text = wordtext;
10323 n->narg.backquote = backquotelist;
10328 fixredir(union node *n, const char *text, int err)
10332 TRACE(("Fix redir %s %d\n", text, err));
10334 n->ndup.vname = NULL;
10336 fd = bb_strtou(text, NULL, 10);
10337 if (!errno && fd >= 0)
10338 n->ndup.dupfd = fd;
10339 else if (LONE_DASH(text))
10340 n->ndup.dupfd = -1;
10343 raise_error_syntax("bad fd number");
10344 n->ndup.vname = makename();
10349 * Returns true if the text contains nothing to expand (no dollar signs
10353 noexpand(const char *text)
10359 while ((c = *p++) != '\0') {
10360 if (c == CTLQUOTEMARK)
10364 else if (SIT((signed char)c, BASESYNTAX) == CCTL)
10373 union node *n = redirnode;
10375 if (readtoken() != TWORD)
10376 raise_error_unexpected_syntax(-1);
10377 if (n->type == NHERE) {
10378 struct heredoc *here = heredoc;
10382 if (quoteflag == 0)
10384 TRACE(("Here document %d\n", n->type));
10385 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10386 raise_error_syntax("illegal eof marker for << redirection");
10387 rmescapes(wordtext);
10388 here->eofmark = wordtext;
10390 if (heredoclist == NULL)
10391 heredoclist = here;
10393 for (p = heredoclist; p->next; p = p->next)
10397 } else if (n->type == NTOFD || n->type == NFROMFD) {
10398 fixredir(n, wordtext, 0);
10400 n->nfile.fname = makename();
10404 static union node *
10407 union node *args, **app;
10408 union node *n = NULL;
10409 union node *vars, **vpp;
10410 union node **rpp, *redir;
10412 #if ENABLE_ASH_BASH_COMPAT
10413 smallint double_brackets_flag = 0;
10423 savecheckkwd = CHKALIAS;
10426 checkkwd = savecheckkwd;
10429 #if ENABLE_ASH_BASH_COMPAT
10430 case TAND: /* "&&" */
10431 case TOR: /* "||" */
10432 if (!double_brackets_flag) {
10436 wordtext = (char *) (t == TAND ? "-a" : "-o");
10439 n = stzalloc(sizeof(struct narg));
10441 /*n->narg.next = NULL; - stzalloc did it */
10442 n->narg.text = wordtext;
10443 #if ENABLE_ASH_BASH_COMPAT
10444 if (strcmp("[[", wordtext) == 0)
10445 double_brackets_flag = 1;
10446 else if (strcmp("]]", wordtext) == 0)
10447 double_brackets_flag = 0;
10449 n->narg.backquote = backquotelist;
10450 if (savecheckkwd && isassignment(wordtext)) {
10452 vpp = &n->narg.next;
10455 app = &n->narg.next;
10460 *rpp = n = redirnode;
10461 rpp = &n->nfile.next;
10462 parsefname(); /* read name of redirection file */
10465 if (args && app == &args->narg.next
10468 struct builtincmd *bcmd;
10471 /* We have a function */
10472 if (readtoken() != TRP)
10473 raise_error_unexpected_syntax(TRP);
10474 name = n->narg.text;
10475 if (!goodname(name)
10476 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10478 raise_error_syntax("bad function name");
10481 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10482 n->narg.next = parse_command();
10495 n = stzalloc(sizeof(struct ncmd));
10497 n->ncmd.args = args;
10498 n->ncmd.assign = vars;
10499 n->ncmd.redirect = redir;
10503 static union node *
10504 parse_command(void)
10506 union node *n1, *n2;
10507 union node *ap, **app;
10508 union node *cp, **cpp;
10509 union node *redir, **rpp;
10516 switch (readtoken()) {
10518 raise_error_unexpected_syntax(-1);
10521 n1 = stzalloc(sizeof(struct nif));
10523 n1->nif.test = list(0);
10524 if (readtoken() != TTHEN)
10525 raise_error_unexpected_syntax(TTHEN);
10526 n1->nif.ifpart = list(0);
10528 while (readtoken() == TELIF) {
10529 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10530 n2 = n2->nif.elsepart;
10532 n2->nif.test = list(0);
10533 if (readtoken() != TTHEN)
10534 raise_error_unexpected_syntax(TTHEN);
10535 n2->nif.ifpart = list(0);
10537 if (lasttoken == TELSE)
10538 n2->nif.elsepart = list(0);
10540 n2->nif.elsepart = NULL;
10548 n1 = stzalloc(sizeof(struct nbinary));
10549 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10550 n1->nbinary.ch1 = list(0);
10553 TRACE(("expecting DO got %s %s\n", tokname(got),
10554 got == TWORD ? wordtext : ""));
10555 raise_error_unexpected_syntax(TDO);
10557 n1->nbinary.ch2 = list(0);
10562 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10563 raise_error_syntax("bad for loop variable");
10564 n1 = stzalloc(sizeof(struct nfor));
10566 n1->nfor.var = wordtext;
10567 checkkwd = CHKKWD | CHKALIAS;
10568 if (readtoken() == TIN) {
10570 while (readtoken() == TWORD) {
10571 n2 = stzalloc(sizeof(struct narg));
10573 /*n2->narg.next = NULL; - stzalloc did it */
10574 n2->narg.text = wordtext;
10575 n2->narg.backquote = backquotelist;
10577 app = &n2->narg.next;
10580 n1->nfor.args = ap;
10581 if (lasttoken != TNL && lasttoken != TSEMI)
10582 raise_error_unexpected_syntax(-1);
10584 n2 = stzalloc(sizeof(struct narg));
10586 /*n2->narg.next = NULL; - stzalloc did it */
10587 n2->narg.text = (char *)dolatstr;
10588 /*n2->narg.backquote = NULL;*/
10589 n1->nfor.args = n2;
10591 * Newline or semicolon here is optional (but note
10592 * that the original Bourne shell only allowed NL).
10594 if (lasttoken != TNL && lasttoken != TSEMI)
10597 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10598 if (readtoken() != TDO)
10599 raise_error_unexpected_syntax(TDO);
10600 n1->nfor.body = list(0);
10604 n1 = stzalloc(sizeof(struct ncase));
10606 if (readtoken() != TWORD)
10607 raise_error_unexpected_syntax(TWORD);
10608 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10610 /*n2->narg.next = NULL; - stzalloc did it */
10611 n2->narg.text = wordtext;
10612 n2->narg.backquote = backquotelist;
10614 checkkwd = CHKKWD | CHKALIAS;
10615 } while (readtoken() == TNL);
10616 if (lasttoken != TIN)
10617 raise_error_unexpected_syntax(TIN);
10618 cpp = &n1->ncase.cases;
10620 checkkwd = CHKNL | CHKKWD;
10622 while (t != TESAC) {
10623 if (lasttoken == TLP)
10625 *cpp = cp = stzalloc(sizeof(struct nclist));
10627 app = &cp->nclist.pattern;
10629 *app = ap = stzalloc(sizeof(struct narg));
10631 /*ap->narg.next = NULL; - stzalloc did it */
10632 ap->narg.text = wordtext;
10633 ap->narg.backquote = backquotelist;
10634 if (readtoken() != TPIPE)
10636 app = &ap->narg.next;
10639 //ap->narg.next = NULL;
10640 if (lasttoken != TRP)
10641 raise_error_unexpected_syntax(TRP);
10642 cp->nclist.body = list(2);
10644 cpp = &cp->nclist.next;
10646 checkkwd = CHKNL | CHKKWD;
10650 raise_error_unexpected_syntax(TENDCASE);
10657 n1 = stzalloc(sizeof(struct nredir));
10658 n1->type = NSUBSHELL;
10659 n1->nredir.n = list(0);
10660 /*n1->nredir.redirect = NULL; - stzalloc did it */
10670 return simplecmd();
10673 if (readtoken() != t)
10674 raise_error_unexpected_syntax(t);
10677 /* Now check for redirection which may follow command */
10678 checkkwd = CHKKWD | CHKALIAS;
10680 while (readtoken() == TREDIR) {
10681 *rpp = n2 = redirnode;
10682 rpp = &n2->nfile.next;
10688 if (n1->type != NSUBSHELL) {
10689 n2 = stzalloc(sizeof(struct nredir));
10694 n1->nredir.redirect = redir;
10699 #if ENABLE_ASH_BASH_COMPAT
10700 static int decode_dollar_squote(void)
10702 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10708 p = strchr(C_escapes, c);
10713 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10717 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10719 } else if (c == 'x') { /* \xHH */
10723 } while (isxdigit(c) && --cnt);
10725 if (cnt == 3) { /* \x but next char is "bad" */
10729 } else { /* simple seq like \\ or \t */
10734 c = bb_process_escape_sequence((void*)&p);
10735 } else { /* unrecognized "\z": print both chars unless ' or " */
10736 if (c != '\'' && c != '"') {
10738 c |= 0x100; /* "please encode \, then me" */
10746 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10747 * is not NULL, read a here document. In the latter case, eofmark is the
10748 * word which marks the end of the document and striptabs is true if
10749 * leading tabs should be stripped from the document. The argument firstc
10750 * is the first character of the input token or document.
10752 * Because C does not have internal subroutines, I have simulated them
10753 * using goto's to implement the subroutine linkage. The following macros
10754 * will run code that appears at the end of readtoken1.
10756 #define CHECKEND() {goto checkend; checkend_return:;}
10757 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10758 #define PARSESUB() {goto parsesub; parsesub_return:;}
10759 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10760 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10761 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10763 readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
10765 /* NB: syntax parameter fits into smallint */
10769 char line[EOFMARKLEN + 1];
10770 struct nodelist *bqlist;
10774 smallint prevsyntax; /* syntax before arithmetic */
10775 #if ENABLE_ASH_EXPAND_PRMT
10776 smallint pssyntax; /* we are expanding a prompt string */
10778 int varnest; /* levels of variables expansion */
10779 int arinest; /* levels of arithmetic expansion */
10780 int parenlevel; /* levels of parens in arithmetic */
10781 int dqvarnest; /* levels of variables expansion within double quotes */
10783 USE_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10786 /* Avoid longjmp clobbering */
10792 (void) &parenlevel;
10795 (void) &prevsyntax;
10798 startlinno = g_parsefile->linno;
10803 #if ENABLE_ASH_EXPAND_PRMT
10804 pssyntax = (syntax == PSSYNTAX);
10808 dblquote = (syntax == DQSYNTAX);
10814 STARTSTACKSTR(out);
10816 /* For each line, until end of word */
10818 CHECKEND(); /* set c to PEOF if at end of here document */
10819 for (;;) { /* until end of line or end of word */
10820 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10821 switch (SIT(c, syntax)) {
10822 case CNL: /* '\n' */
10823 if (syntax == BASESYNTAX)
10824 goto endword; /* exit outer loop */
10826 g_parsefile->linno++;
10830 goto loop; /* continue outer loop */
10835 if (eofmark == NULL || dblquote)
10836 USTPUTC(CTLESC, out);
10837 #if ENABLE_ASH_BASH_COMPAT
10838 if (c == '\\' && bash_dollar_squote) {
10839 c = decode_dollar_squote();
10841 USTPUTC('\\', out);
10842 c = (unsigned char)c;
10848 case CBACK: /* backslash */
10851 USTPUTC(CTLESC, out);
10852 USTPUTC('\\', out);
10854 } else if (c == '\n') {
10858 #if ENABLE_ASH_EXPAND_PRMT
10859 if (c == '$' && pssyntax) {
10860 USTPUTC(CTLESC, out);
10861 USTPUTC('\\', out);
10864 if (dblquote && c != '\\'
10865 && c != '`' && c != '$'
10866 && (c != '"' || eofmark != NULL)
10868 USTPUTC(CTLESC, out);
10869 USTPUTC('\\', out);
10871 if (SIT(c, SQSYNTAX) == CCTL)
10872 USTPUTC(CTLESC, out);
10880 if (eofmark == NULL) {
10881 USTPUTC(CTLQUOTEMARK, out);
10889 USE_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
10890 if (eofmark != NULL && arinest == 0
10895 if (dqvarnest == 0) {
10896 syntax = BASESYNTAX;
10903 case CVAR: /* '$' */
10904 PARSESUB(); /* parse substitution */
10906 case CENDVAR: /* '}' */
10909 if (dqvarnest > 0) {
10912 USTPUTC(CTLENDVAR, out);
10917 #if ENABLE_SH_MATH_SUPPORT
10918 case CLP: /* '(' in arithmetic */
10922 case CRP: /* ')' in arithmetic */
10923 if (parenlevel > 0) {
10927 if (pgetc() == ')') {
10928 if (--arinest == 0) {
10929 USTPUTC(CTLENDARI, out);
10930 syntax = prevsyntax;
10931 dblquote = (syntax == DQSYNTAX);
10936 * unbalanced parens
10937 * (don't 2nd guess - no error)
10945 case CBQUOTE: /* '`' */
10949 goto endword; /* exit outer loop */
10953 if (varnest == 0) {
10954 #if ENABLE_ASH_BASH_COMPAT
10956 if (pgetc() == '>')
10957 c = 0x100 + '>'; /* flag &> */
10961 goto endword; /* exit outer loop */
10963 #if ENABLE_ASH_ALIAS
10973 #if ENABLE_SH_MATH_SUPPORT
10974 if (syntax == ARISYNTAX)
10975 raise_error_syntax("missing '))'");
10977 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
10978 raise_error_syntax("unterminated quoted string");
10979 if (varnest != 0) {
10980 startlinno = g_parsefile->linno;
10982 raise_error_syntax("missing '}'");
10984 USTPUTC('\0', out);
10985 len = out - (char *)stackblock();
10986 out = stackblock();
10987 if (eofmark == NULL) {
10988 if ((c == '>' || c == '<' USE_ASH_BASH_COMPAT( || c == 0x100 + '>'))
10991 if (isdigit_str9(out)) {
10992 PARSEREDIR(); /* passed as params: out, c */
10993 lasttoken = TREDIR;
10996 /* else: non-number X seen, interpret it
10997 * as "NNNX>file" = "NNNX >file" */
11001 quoteflag = quotef;
11002 backquotelist = bqlist;
11003 grabstackblock(len);
11007 /* end of readtoken routine */
11010 * Check to see whether we are at the end of the here document. When this
11011 * is called, c is set to the first character of the next input line. If
11012 * we are at the end of the here document, this routine sets the c to PEOF.
11016 #if ENABLE_ASH_ALIAS
11022 while (c == '\t') {
11026 if (c == *eofmark) {
11027 if (pfgets(line, sizeof(line)) != NULL) {
11031 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11033 if (*p == '\n' && *q == '\0') {
11035 g_parsefile->linno++;
11036 needprompt = doprompt;
11038 pushstring(line, NULL);
11043 goto checkend_return;
11047 * Parse a redirection operator. The variable "out" points to a string
11048 * specifying the fd to be redirected. The variable "c" contains the
11049 * first character of the redirection operator.
11052 /* out is already checked to be a valid number or "" */
11053 int fd = (*out == '\0' ? -1 : atoi(out));
11056 np = stzalloc(sizeof(struct nfile));
11061 np->type = NAPPEND;
11063 np->type = NCLOBBER;
11066 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11072 #if ENABLE_ASH_BASH_COMPAT
11073 else if (c == 0x100 + '>') { /* this flags &> redirection */
11075 pgetc(); /* this is '>', no need to check */
11079 else { /* c == '<' */
11080 /*np->nfile.fd = 0; - stzalloc did it */
11084 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11085 np = stzalloc(sizeof(struct nhere));
11086 /*np->nfile.fd = 0; - stzalloc did it */
11089 heredoc = stzalloc(sizeof(struct heredoc));
11090 heredoc->here = np;
11093 heredoc->striptabs = 1;
11095 /*heredoc->striptabs = 0; - stzalloc did it */
11101 np->type = NFROMFD;
11105 np->type = NFROMTO;
11117 goto parseredir_return;
11121 * Parse a substitution. At this point, we have read the dollar sign
11122 * and nothing else.
11125 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11126 * (assuming ascii char codes, as the original implementation did) */
11127 #define is_special(c) \
11128 (((unsigned)(c) - 33 < 32) \
11129 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11135 static const char types[] ALIGN1 = "}-+?=";
11138 if (c <= PEOA_OR_PEOF
11139 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11141 #if ENABLE_ASH_BASH_COMPAT
11143 bash_dollar_squote = 1;
11148 } else if (c == '(') { /* $(command) or $((arith)) */
11149 if (pgetc() == '(') {
11150 #if ENABLE_SH_MATH_SUPPORT
11153 raise_error_syntax("you disabled math support for $((arith)) syntax");
11160 USTPUTC(CTLVAR, out);
11161 typeloc = out - (char *)stackblock();
11162 USTPUTC(VSNORMAL, out);
11163 subtype = VSNORMAL;
11171 subtype = VSLENGTH;
11175 if (c > PEOA_OR_PEOF && is_name(c)) {
11179 } while (c > PEOA_OR_PEOF && is_in_name(c));
11180 } else if (isdigit(c)) {
11184 } while (isdigit(c));
11185 } else if (is_special(c)) {
11190 raise_error_syntax("bad substitution");
11195 if (subtype == 0) {
11199 #if ENABLE_ASH_BASH_COMPAT
11200 if (c == ':' || c == '$' || isdigit(c)) {
11202 subtype = VSSUBSTR;
11209 p = strchr(types, c);
11212 subtype = p - types + VSNORMAL;
11217 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11225 #if ENABLE_ASH_BASH_COMPAT
11227 subtype = VSREPLACE;
11230 subtype++; /* VSREPLACEALL */
11239 if (dblquote || arinest)
11241 *((char *)stackblock() + typeloc) = subtype | flags;
11242 if (subtype != VSNORMAL) {
11244 if (dblquote || arinest) {
11249 goto parsesub_return;
11253 * Called to parse command substitutions. Newstyle is set if the command
11254 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11255 * list of commands (passed by reference), and savelen is the number of
11256 * characters on the top of the stack which must be preserved.
11259 struct nodelist **nlpp;
11262 char *volatile str;
11263 struct jmploc jmploc;
11264 struct jmploc *volatile savehandler;
11266 smallint saveprompt = 0;
11269 (void) &saveprompt;
11271 savepbq = parsebackquote;
11272 if (setjmp(jmploc.loc)) {
11274 parsebackquote = 0;
11275 exception_handler = savehandler;
11276 longjmp(exception_handler->loc, 1);
11280 savelen = out - (char *)stackblock();
11282 str = ckmalloc(savelen);
11283 memcpy(str, stackblock(), savelen);
11285 savehandler = exception_handler;
11286 exception_handler = &jmploc;
11289 /* We must read until the closing backquote, giving special
11290 treatment to some slashes, and then push the string and
11291 reread it as input, interpreting it normally. */
11298 STARTSTACKSTR(pout);
11311 g_parsefile->linno++;
11315 * If eating a newline, avoid putting
11316 * the newline into the new character
11317 * stream (via the STPUTC after the
11322 if (pc != '\\' && pc != '`' && pc != '$'
11323 && (!dblquote || pc != '"'))
11324 STPUTC('\\', pout);
11325 if (pc > PEOA_OR_PEOF) {
11331 #if ENABLE_ASH_ALIAS
11334 startlinno = g_parsefile->linno;
11335 raise_error_syntax("EOF in backquote substitution");
11338 g_parsefile->linno++;
11339 needprompt = doprompt;
11348 STPUTC('\0', pout);
11349 psavelen = pout - (char *)stackblock();
11350 if (psavelen > 0) {
11351 pstr = grabstackstr(pout);
11352 setinputstring(pstr);
11357 nlpp = &(*nlpp)->next;
11358 *nlpp = stzalloc(sizeof(**nlpp));
11359 /* (*nlpp)->next = NULL; - stzalloc did it */
11360 parsebackquote = oldstyle;
11363 saveprompt = doprompt;
11370 doprompt = saveprompt;
11371 else if (readtoken() != TRP)
11372 raise_error_unexpected_syntax(TRP);
11377 * Start reading from old file again, ignoring any pushed back
11378 * tokens left from the backquote parsing
11383 while (stackblocksize() <= savelen)
11385 STARTSTACKSTR(out);
11387 memcpy(out, str, savelen);
11388 STADJUST(savelen, out);
11394 parsebackquote = savepbq;
11395 exception_handler = savehandler;
11396 if (arinest || dblquote)
11397 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11399 USTPUTC(CTLBACKQ, out);
11401 goto parsebackq_oldreturn;
11402 goto parsebackq_newreturn;
11405 #if ENABLE_SH_MATH_SUPPORT
11407 * Parse an arithmetic expansion (indicate start of one and set state)
11410 if (++arinest == 1) {
11411 prevsyntax = syntax;
11412 syntax = ARISYNTAX;
11413 USTPUTC(CTLARI, out);
11420 * we collapse embedded arithmetic expansion to
11421 * parenthesis, which should be equivalent
11425 goto parsearith_return;
11429 } /* end of readtoken */
11432 * Read the next input token.
11433 * If the token is a word, we set backquotelist to the list of cmds in
11434 * backquotes. We set quoteflag to true if any part of the word was
11436 * If the token is TREDIR, then we set redirnode to a structure containing
11438 * In all cases, the variable startlinno is set to the number of the line
11439 * on which the token starts.
11441 * [Change comment: here documents and internal procedures]
11442 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11443 * word parsing code into a separate routine. In this case, readtoken
11444 * doesn't need to have any internal procedures, but parseword does.
11445 * We could also make parseoperator in essence the main routine, and
11446 * have parseword (readtoken1?) handle both words and redirection.]
11448 #define NEW_xxreadtoken
11449 #ifdef NEW_xxreadtoken
11450 /* singles must be first! */
11451 static const char xxreadtoken_chars[7] ALIGN1 = {
11452 '\n', '(', ')', /* singles */
11453 '&', '|', ';', /* doubles */
11457 #define xxreadtoken_singles 3
11458 #define xxreadtoken_doubles 3
11460 static const char xxreadtoken_tokens[] ALIGN1 = {
11461 TNL, TLP, TRP, /* only single occurrence allowed */
11462 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11463 TEOF, /* corresponds to trailing nul */
11464 TAND, TOR, TENDCASE /* if double occurrence */
11479 startlinno = g_parsefile->linno;
11480 for (;;) { /* until token or start of word found */
11482 if (c == ' ' || c == '\t' USE_ASH_ALIAS( || c == PEOA))
11486 while ((c = pgetc()) != '\n' && c != PEOF)
11489 } else if (c == '\\') {
11490 if (pgetc() != '\n') {
11492 break; /* return readtoken1(...) */
11494 startlinno = ++g_parsefile->linno;
11500 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11503 g_parsefile->linno++;
11504 needprompt = doprompt;
11507 p = strchr(xxreadtoken_chars, c);
11509 break; /* return readtoken1(...) */
11511 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11513 if (cc == c) { /* double occurrence? */
11514 p += xxreadtoken_doubles + 1;
11517 #if ENABLE_ASH_BASH_COMPAT
11518 if (c == '&' && cc == '>') /* &> */
11519 break; /* return readtoken1(...) */
11524 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11529 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11531 #else /* old xxreadtoken */
11532 #define RETURN(token) return lasttoken = token
11545 startlinno = g_parsefile->linno;
11546 for (;;) { /* until token or start of word found */
11549 case ' ': case '\t':
11550 #if ENABLE_ASH_ALIAS
11555 while ((c = pgetc()) != '\n' && c != PEOF)
11560 if (pgetc() == '\n') {
11561 startlinno = ++g_parsefile->linno;
11569 g_parsefile->linno++;
11570 needprompt = doprompt;
11575 if (pgetc() == '&')
11580 if (pgetc() == '|')
11585 if (pgetc() == ';')
11598 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11601 #endif /* old xxreadtoken */
11608 smallint alreadyseen = tokpushback;
11611 #if ENABLE_ASH_ALIAS
11620 if (checkkwd & CHKNL) {
11627 if (t != TWORD || quoteflag) {
11632 * check for keywords
11634 if (checkkwd & CHKKWD) {
11635 const char *const *pp;
11637 pp = findkwd(wordtext);
11639 lasttoken = t = pp - tokname_array;
11640 TRACE(("keyword %s recognized\n", tokname(t)));
11645 if (checkkwd & CHKALIAS) {
11646 #if ENABLE_ASH_ALIAS
11648 ap = lookupalias(wordtext, 1);
11651 pushstring(ap->val, ap);
11661 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11663 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11675 return tokname_array[t][0];
11679 * Read and parse a command. Returns NEOF on end of file. (NULL is a
11680 * valid parse tree indicating a blank line.)
11682 static union node *
11683 parsecmd(int interact)
11688 doprompt = interact;
11690 setprompt(doprompt);
11702 * Input any here documents.
11707 struct heredoc *here;
11710 here = heredoclist;
11711 heredoclist = NULL;
11717 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11718 here->eofmark, here->striptabs);
11719 n = stzalloc(sizeof(struct narg));
11720 n->narg.type = NARG;
11721 /*n->narg.next = NULL; - stzalloc did it */
11722 n->narg.text = wordtext;
11723 n->narg.backquote = backquotelist;
11724 here->here->nhere.doc = n;
11731 * called by editline -- any expansions to the prompt should be added here.
11733 #if ENABLE_ASH_EXPAND_PRMT
11734 static const char *
11735 expandstr(const char *ps)
11739 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11740 * and token processing _can_ alter it (delete NULs etc). */
11741 setinputstring((char *)ps);
11742 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11745 n.narg.type = NARG;
11746 n.narg.next = NULL;
11747 n.narg.text = wordtext;
11748 n.narg.backquote = backquotelist;
11750 expandarg(&n, NULL, 0);
11751 return stackblock();
11756 * Execute a command or commands contained in a string.
11759 evalstring(char *s, int mask)
11762 struct stackmark smark;
11766 setstackmark(&smark);
11769 while ((n = parsecmd(0)) != NEOF) {
11771 popstackmark(&smark);
11784 * The eval command.
11787 evalcmd(int argc UNUSED_PARAM, char **argv)
11796 STARTSTACKSTR(concat);
11798 concat = stack_putstr(p, concat);
11802 STPUTC(' ', concat);
11804 STPUTC('\0', concat);
11805 p = grabstackstr(concat);
11807 evalstring(p, ~SKIPEVAL);
11814 * Read and execute commands. "Top" is nonzero for the top level command
11815 * loop; it turns on prompting if the shell is interactive.
11821 struct stackmark smark;
11825 TRACE(("cmdloop(%d) called\n", top));
11829 setstackmark(&smark);
11832 showjobs(stderr, SHOW_CHANGED);
11835 if (iflag && top) {
11837 #if ENABLE_ASH_MAIL
11841 n = parsecmd(inter);
11842 /* showtree(n); DEBUG */
11844 if (!top || numeof >= 50)
11846 if (!stoppedjobs()) {
11849 out2str("\nUse \"exit\" to leave shell.\n");
11852 } else if (nflag == 0) {
11853 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11858 popstackmark(&smark);
11863 return skip & SKIPEVAL;
11870 * Take commands from a file. To be compatible we should do a path
11871 * search for the file, which is necessary to find sub-commands.
11874 find_dot_file(char *name)
11877 const char *path = pathval();
11880 /* don't try this for absolute or relative paths */
11881 if (strchr(name, '/'))
11884 /* IIRC standards do not say whether . is to be searched.
11885 * And it is even smaller this way, making it unconditional for now:
11887 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11892 while ((fullname = padvance(&path, name)) != NULL) {
11894 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11896 * Don't bother freeing here, since it will
11897 * be freed by the caller.
11901 stunalloc(fullname);
11904 /* not found in the PATH */
11905 ash_msg_and_raise_error("%s: not found", name);
11910 dotcmd(int argc, char **argv)
11912 struct strlist *sp;
11913 volatile struct shparam saveparam;
11916 for (sp = cmdenviron; sp; sp = sp->next)
11917 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
11919 if (argv[1]) { /* That's what SVR2 does */
11920 char *fullname = find_dot_file(argv[1]);
11923 if (argc) { /* argc > 0, argv[0] != NULL */
11924 saveparam = shellparam;
11925 shellparam.malloced = 0;
11926 shellparam.nparam = argc;
11927 shellparam.p = argv;
11930 setinputfile(fullname, INPUT_PUSH_FILE);
11931 commandname = fullname;
11936 freeparam(&shellparam);
11937 shellparam = saveparam;
11939 status = exitstatus;
11945 exitcmd(int argc UNUSED_PARAM, char **argv)
11950 exitstatus = number(argv[1]);
11951 raise_exception(EXEXIT);
11956 * Read a file containing shell functions.
11959 readcmdfile(char *name)
11961 setinputfile(name, INPUT_PUSH_FILE);
11967 /* ============ find_command inplementation */
11970 * Resolve a command name. If you change this routine, you may have to
11971 * change the shellexec routine as well.
11974 find_command(char *name, struct cmdentry *entry, int act, const char *path)
11976 struct tblentry *cmdp;
11983 struct builtincmd *bcmd;
11985 /* If name contains a slash, don't use PATH or hash table */
11986 if (strchr(name, '/') != NULL) {
11987 entry->u.index = -1;
11988 if (act & DO_ABS) {
11989 while (stat(name, &statb) < 0) {
11991 if (errno == EINTR)
11994 entry->cmdtype = CMDUNKNOWN;
11998 entry->cmdtype = CMDNORMAL;
12002 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12004 updatetbl = (path == pathval());
12007 if (strstr(path, "%builtin") != NULL)
12008 act |= DO_ALTBLTIN;
12011 /* If name is in the table, check answer will be ok */
12012 cmdp = cmdlookup(name, 0);
12013 if (cmdp != NULL) {
12016 switch (cmdp->cmdtype) {
12034 } else if (cmdp->rehash == 0)
12035 /* if not invalidated by cd, we're done */
12039 /* If %builtin not in path, check for builtin next */
12040 bcmd = find_builtin(name);
12042 if (IS_BUILTIN_REGULAR(bcmd))
12043 goto builtin_success;
12044 if (act & DO_ALTPATH) {
12045 if (!(act & DO_ALTBLTIN))
12046 goto builtin_success;
12047 } else if (builtinloc <= 0) {
12048 goto builtin_success;
12052 #if ENABLE_FEATURE_SH_STANDALONE
12054 int applet_no = find_applet_by_name(name);
12055 if (applet_no >= 0) {
12056 entry->cmdtype = CMDNORMAL;
12057 entry->u.index = -2 - applet_no;
12063 /* We have to search path. */
12064 prev = -1; /* where to start */
12065 if (cmdp && cmdp->rehash) { /* doing a rehash */
12066 if (cmdp->cmdtype == CMDBUILTIN)
12069 prev = cmdp->param.index;
12075 while ((fullname = padvance(&path, name)) != NULL) {
12076 stunalloc(fullname);
12077 /* NB: code below will still use fullname
12078 * despite it being "unallocated" */
12081 if (prefix(pathopt, "builtin")) {
12083 goto builtin_success;
12086 if ((act & DO_NOFUNC)
12087 || !prefix(pathopt, "func")
12088 ) { /* ignore unimplemented options */
12092 /* if rehash, don't redo absolute path names */
12093 if (fullname[0] == '/' && idx <= prev) {
12096 TRACE(("searchexec \"%s\": no change\n", name));
12099 while (stat(fullname, &statb) < 0) {
12101 if (errno == EINTR)
12104 if (errno != ENOENT && errno != ENOTDIR)
12108 e = EACCES; /* if we fail, this will be the error */
12109 if (!S_ISREG(statb.st_mode))
12111 if (pathopt) { /* this is a %func directory */
12112 stalloc(strlen(fullname) + 1);
12113 /* NB: stalloc will return space pointed by fullname
12114 * (because we don't have any intervening allocations
12115 * between stunalloc above and this stalloc) */
12116 readcmdfile(fullname);
12117 cmdp = cmdlookup(name, 0);
12118 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12119 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12120 stunalloc(fullname);
12123 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12125 entry->cmdtype = CMDNORMAL;
12126 entry->u.index = idx;
12130 cmdp = cmdlookup(name, 1);
12131 cmdp->cmdtype = CMDNORMAL;
12132 cmdp->param.index = idx;
12137 /* We failed. If there was an entry for this command, delete it */
12138 if (cmdp && updatetbl)
12139 delete_cmd_entry();
12141 ash_msg("%s: %s", name, errmsg(e, "not found"));
12142 entry->cmdtype = CMDUNKNOWN;
12147 entry->cmdtype = CMDBUILTIN;
12148 entry->u.cmd = bcmd;
12152 cmdp = cmdlookup(name, 1);
12153 cmdp->cmdtype = CMDBUILTIN;
12154 cmdp->param.cmd = bcmd;
12158 entry->cmdtype = cmdp->cmdtype;
12159 entry->u = cmdp->param;
12163 /* ============ trap.c */
12166 * The trap builtin.
12169 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12178 for (signo = 0; signo < NSIG; signo++) {
12179 if (trap[signo] != NULL) {
12180 out1fmt("trap -- %s %s\n",
12181 single_quote(trap[signo]),
12182 get_signame(signo));
12191 signo = get_signum(*ap);
12193 ash_msg_and_raise_error("%s: bad trap", *ap);
12196 if (LONE_DASH(action))
12199 action = ckstrdup(action);
12202 trap[signo] = action;
12212 /* ============ Builtins */
12214 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12216 * Lists available builtins
12219 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12224 out1fmt("\nBuilt-in commands:\n-------------------\n");
12225 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12226 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12227 builtintab[i].name + 1);
12233 #if ENABLE_FEATURE_SH_STANDALONE
12235 const char *a = applet_names;
12237 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12242 a += strlen(a) + 1;
12247 return EXIT_SUCCESS;
12249 #endif /* FEATURE_SH_EXTRA_QUIET */
12252 * The export and readonly commands.
12255 exportcmd(int argc UNUSED_PARAM, char **argv)
12261 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12263 if (nextopt("p") != 'p') {
12268 p = strchr(name, '=');
12272 vp = *findvar(hashvar(name), name);
12278 setvar(name, p, flag);
12279 } while ((name = *++aptr) != NULL);
12283 showvars(argv[0], flag, 0);
12288 * Delete a function if it exists.
12291 unsetfunc(const char *name)
12293 struct tblentry *cmdp;
12295 cmdp = cmdlookup(name, 0);
12296 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12297 delete_cmd_entry();
12301 * The unset builtin command. We unset the function before we unset the
12302 * variable to allow a function to be unset when there is a readonly variable
12303 * with the same name.
12306 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12313 while ((i = nextopt("vf")) != '\0') {
12317 for (ap = argptr; *ap; ap++) {
12333 #include <sys/times.h>
12335 static const unsigned char timescmd_str[] ALIGN1 = {
12336 ' ', offsetof(struct tms, tms_utime),
12337 '\n', offsetof(struct tms, tms_stime),
12338 ' ', offsetof(struct tms, tms_cutime),
12339 '\n', offsetof(struct tms, tms_cstime),
12344 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12346 long clk_tck, s, t;
12347 const unsigned char *p;
12350 clk_tck = sysconf(_SC_CLK_TCK);
12355 t = *(clock_t *)(((char *) &buf) + p[1]);
12357 out1fmt("%ldm%ld.%.3lds%c",
12359 ((t - s * clk_tck) * 1000) / clk_tck,
12361 } while (*(p += 2));
12366 #if ENABLE_SH_MATH_SUPPORT
12368 dash_arith(const char *s)
12374 result = arith(s, &errcode, &math_hooks);
12377 ash_msg_and_raise_error("exponent less than 0");
12379 ash_msg_and_raise_error("divide by zero");
12381 ash_msg_and_raise_error("expression recursion loop detected");
12382 raise_error_syntax(s);
12390 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12391 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12393 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12396 letcmd(int argc UNUSED_PARAM, char **argv)
12402 ash_msg_and_raise_error("expression expected");
12404 i = dash_arith(*argv);
12409 #endif /* SH_MATH_SUPPORT */
12412 /* ============ miscbltin.c
12414 * Miscellaneous builtins.
12419 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
12420 typedef enum __rlimit_resource rlim_t;
12424 * The read builtin. Options:
12425 * -r Do not interpret '\' specially
12426 * -s Turn off echo (tty only)
12427 * -n NCHARS Read NCHARS max
12428 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12429 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12430 * -u FD Read from given FD instead of fd 0
12431 * This uses unbuffered input, which may be avoidable in some cases.
12432 * TODO: bash also has:
12433 * -a ARRAY Read into array[0],[1],etc
12434 * -d DELIM End on DELIM char, not newline
12435 * -e Use line editing (tty only)
12438 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12440 static const char *const arg_REPLY[] = { "REPLY", NULL };
12453 #if ENABLE_ASH_READ_NCHARS
12454 int nchars = 0; /* if != 0, -n is in effect */
12456 struct termios tty, old_tty;
12458 #if ENABLE_ASH_READ_TIMEOUT
12459 unsigned end_ms = 0;
12460 unsigned timeout = 0;
12465 while ((i = nextopt("p:u:r"
12466 USE_ASH_READ_TIMEOUT("t:")
12467 USE_ASH_READ_NCHARS("n:s")
12471 prompt = optionarg;
12473 #if ENABLE_ASH_READ_NCHARS
12475 nchars = bb_strtou(optionarg, NULL, 10);
12476 if (nchars < 0 || errno)
12477 ash_msg_and_raise_error("invalid count");
12478 /* nchars == 0: off (bash 3.2 does this too) */
12484 #if ENABLE_ASH_READ_TIMEOUT
12486 timeout = bb_strtou(optionarg, NULL, 10);
12487 if (errno || timeout > UINT_MAX / 2048)
12488 ash_msg_and_raise_error("invalid timeout");
12490 #if 0 /* even bash have no -t N.NNN support */
12491 ts.tv_sec = bb_strtou(optionarg, &p, 10);
12493 /* EINVAL means number is ok, but not terminated by NUL */
12494 if (*p == '.' && errno == EINVAL) {
12498 ts.tv_usec = bb_strtou(p, &p2, 10);
12500 ash_msg_and_raise_error("invalid timeout");
12502 /* normalize to usec */
12504 ash_msg_and_raise_error("invalid timeout");
12505 while (scale++ < 6)
12508 } else if (ts.tv_sec < 0 || errno) {
12509 ash_msg_and_raise_error("invalid timeout");
12511 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
12512 ash_msg_and_raise_error("invalid timeout");
12521 fd = bb_strtou(optionarg, NULL, 10);
12522 if (fd < 0 || errno)
12523 ash_msg_and_raise_error("invalid file descriptor");
12529 if (prompt && isatty(fd)) {
12534 ap = (char**)arg_REPLY;
12535 ifs = bltinlookup("IFS");
12538 #if ENABLE_ASH_READ_NCHARS
12539 tcgetattr(fd, &tty);
12541 if (nchars || silent) {
12543 tty.c_lflag &= ~ICANON;
12544 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
12547 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12549 /* if tcgetattr failed, tcsetattr will fail too.
12550 * Ignoring, it's harmless. */
12551 tcsetattr(fd, TCSANOW, &tty);
12558 #if ENABLE_ASH_READ_TIMEOUT
12559 if (timeout) /* NB: ensuring end_ms is nonzero */
12560 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12564 const char *is_ifs;
12566 #if ENABLE_ASH_READ_TIMEOUT
12568 struct pollfd pfd[1];
12570 pfd[0].events = POLLIN;
12571 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12572 if ((int)timeout <= 0 /* already late? */
12573 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12574 ) { /* timed out! */
12575 #if ENABLE_ASH_READ_NCHARS
12576 tcsetattr(fd, TCSANOW, &old_tty);
12582 if (nonblock_safe_read(fd, &c, 1) != 1) {
12594 if (!rflag && c == '\\') {
12600 /* $IFS splitting */
12601 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
12602 is_ifs = strchr(ifs, c);
12603 if (startword && is_ifs) {
12606 /* it is a non-space ifs char */
12608 if (startword == 1) /* first one? */
12609 continue; /* yes, it is not next word yet */
12612 if (ap[1] != NULL && is_ifs) {
12615 beg = stackblock();
12616 setvar(*ap, beg, 0);
12618 /* can we skip one non-space ifs char? (2: yes) */
12619 startword = isspace(c) ? 2 : 1;
12626 /* end of do {} while: */
12627 #if ENABLE_ASH_READ_NCHARS
12633 #if ENABLE_ASH_READ_NCHARS
12634 tcsetattr(fd, TCSANOW, &old_tty);
12638 /* Remove trailing space ifs chars */
12639 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
12641 setvar(*ap, stackblock(), 0);
12642 while (*++ap != NULL)
12643 setvar(*ap, nullstr, 0);
12648 umaskcmd(int argc UNUSED_PARAM, char **argv)
12650 static const char permuser[3] ALIGN1 = "ugo";
12651 static const char permmode[3] ALIGN1 = "rwx";
12652 static const short permmask[] ALIGN2 = {
12653 S_IRUSR, S_IWUSR, S_IXUSR,
12654 S_IRGRP, S_IWGRP, S_IXGRP,
12655 S_IROTH, S_IWOTH, S_IXOTH
12661 int symbolic_mode = 0;
12663 while (nextopt("S") != '\0') {
12674 if (symbolic_mode) {
12678 for (i = 0; i < 3; i++) {
12681 *p++ = permuser[i];
12683 for (j = 0; j < 3; j++) {
12684 if ((mask & permmask[3 * i + j]) == 0) {
12685 *p++ = permmode[j];
12693 out1fmt("%.4o\n", mask);
12696 if (isdigit((unsigned char) *ap)) {
12699 if (*ap >= '8' || *ap < '0')
12700 ash_msg_and_raise_error(illnum, argv[1]);
12701 mask = (mask << 3) + (*ap - '0');
12702 } while (*++ap != '\0');
12705 mask = ~mask & 0777;
12706 if (!bb_parse_mode(ap, &mask)) {
12707 ash_msg_and_raise_error("illegal mode: %s", ap);
12709 umask(~mask & 0777);
12718 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12719 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12720 * ash by J.T. Conklin.
12726 uint8_t cmd; /* RLIMIT_xxx fit into it */
12727 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
12731 static const struct limits limits_tbl[] = {
12733 { RLIMIT_CPU, 0, 't' },
12735 #ifdef RLIMIT_FSIZE
12736 { RLIMIT_FSIZE, 9, 'f' },
12739 { RLIMIT_DATA, 10, 'd' },
12741 #ifdef RLIMIT_STACK
12742 { RLIMIT_STACK, 10, 's' },
12745 { RLIMIT_CORE, 9, 'c' },
12748 { RLIMIT_RSS, 10, 'm' },
12750 #ifdef RLIMIT_MEMLOCK
12751 { RLIMIT_MEMLOCK, 10, 'l' },
12753 #ifdef RLIMIT_NPROC
12754 { RLIMIT_NPROC, 0, 'p' },
12756 #ifdef RLIMIT_NOFILE
12757 { RLIMIT_NOFILE, 0, 'n' },
12760 { RLIMIT_AS, 10, 'v' },
12762 #ifdef RLIMIT_LOCKS
12763 { RLIMIT_LOCKS, 0, 'w' },
12766 static const char limits_name[] =
12768 "time(seconds)" "\0"
12770 #ifdef RLIMIT_FSIZE
12771 "file(blocks)" "\0"
12776 #ifdef RLIMIT_STACK
12780 "coredump(blocks)" "\0"
12785 #ifdef RLIMIT_MEMLOCK
12786 "locked memory(kb)" "\0"
12788 #ifdef RLIMIT_NPROC
12791 #ifdef RLIMIT_NOFILE
12797 #ifdef RLIMIT_LOCKS
12802 enum limtype { SOFT = 0x1, HARD = 0x2 };
12805 printlim(enum limtype how, const struct rlimit *limit,
12806 const struct limits *l)
12810 val = limit->rlim_max;
12812 val = limit->rlim_cur;
12814 if (val == RLIM_INFINITY)
12815 out1fmt("unlimited\n");
12817 val >>= l->factor_shift;
12818 out1fmt("%lld\n", (long long) val);
12823 ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12827 enum limtype how = SOFT | HARD;
12828 const struct limits *l;
12831 struct rlimit limit;
12834 while ((optc = nextopt("HSa"
12838 #ifdef RLIMIT_FSIZE
12844 #ifdef RLIMIT_STACK
12853 #ifdef RLIMIT_MEMLOCK
12856 #ifdef RLIMIT_NPROC
12859 #ifdef RLIMIT_NOFILE
12865 #ifdef RLIMIT_LOCKS
12883 for (l = limits_tbl; l->option != what; l++)
12886 set = *argptr ? 1 : 0;
12890 if (all || argptr[1])
12891 ash_msg_and_raise_error("too many arguments");
12892 if (strncmp(p, "unlimited\n", 9) == 0)
12893 val = RLIM_INFINITY;
12897 while ((c = *p++) >= '0' && c <= '9') {
12898 val = (val * 10) + (long)(c - '0');
12899 // val is actually 'unsigned long int' and can't get < 0
12900 if (val < (rlim_t) 0)
12904 ash_msg_and_raise_error("bad number");
12905 val <<= l->factor_shift;
12909 const char *lname = limits_name;
12910 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
12911 getrlimit(l->cmd, &limit);
12912 out1fmt("%-20s ", lname);
12913 lname += strlen(lname) + 1;
12914 printlim(how, &limit, l);
12919 getrlimit(l->cmd, &limit);
12922 limit.rlim_max = val;
12924 limit.rlim_cur = val;
12925 if (setrlimit(l->cmd, &limit) < 0)
12926 ash_msg_and_raise_error("error setting limit (%m)");
12928 printlim(how, &limit, l);
12933 /* ============ main() and helpers */
12936 * Called to exit the shell.
12938 static void exitshell(void) NORETURN;
12946 status = exitstatus;
12947 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12948 if (setjmp(loc.loc)) {
12949 if (exception_type == EXEXIT)
12950 /* dash bug: it just does _exit(exitstatus) here
12951 * but we have to do setjobctl(0) first!
12952 * (bug is still not fixed in dash-0.5.3 - if you run dash
12953 * under Midnight Commander, on exit from dash MC is backgrounded) */
12954 status = exitstatus;
12957 exception_handler = &loc;
12963 flush_stdout_stderr();
12973 /* from input.c: */
12974 basepf.next_to_pgetc = basepf.buf = basebuf;
12977 signal(SIGCHLD, SIG_DFL);
12982 char ppid[sizeof(int)*3 + 1];
12984 struct stat st1, st2;
12987 for (envp = environ; envp && *envp; envp++) {
12988 if (strchr(*envp, '=')) {
12989 setvareq(*envp, VEXPORT|VTEXTFIXED);
12993 snprintf(ppid, sizeof(ppid), "%u", (unsigned) getppid());
12994 setvar("PPID", ppid, 0);
12996 p = lookupvar("PWD");
12998 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12999 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
13006 * Process the shell command line arguments.
13009 procargs(char **argv)
13012 const char *xminusc;
13017 /* if (xargv[0]) - mmm, this is always true! */
13019 for (i = 0; i < NOPTS; i++)
13023 /* it already printed err message */
13024 raise_exception(EXERROR);
13028 if (*xargv == NULL) {
13030 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13033 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13037 for (i = 0; i < NOPTS; i++)
13038 if (optlist[i] == 2)
13043 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13048 } else if (!sflag) {
13049 setinputfile(*xargv, 0);
13052 commandname = arg0;
13055 shellparam.p = xargv;
13056 #if ENABLE_ASH_GETOPTS
13057 shellparam.optind = 1;
13058 shellparam.optoff = -1;
13060 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13062 shellparam.nparam++;
13069 * Read /etc/profile or .profile.
13072 read_profile(const char *name)
13076 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13085 * This routine is called when an error or an interrupt occurs in an
13086 * interactive shell and control is returned to the main command loop.
13094 /* from input.c: */
13095 g_parsefile->left_in_buffer = 0;
13096 g_parsefile->left_in_line = 0; /* clear input buffer */
13098 /* from parser.c: */
13101 /* from redir.c: */
13102 clearredir(/*drop:*/ 0);
13106 static short profile_buf[16384];
13107 extern int etext();
13111 * Main routine. We initialize things, parse the arguments, execute
13112 * profiles if we're a login shell, and then call cmdloop to execute
13113 * commands. The setjmp call sets up the location to jump to when an
13114 * exception occurs. When an exception occurs the variable "state"
13115 * is used to figure out how far we had gotten.
13117 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13118 int ash_main(int argc UNUSED_PARAM, char **argv)
13120 const char *shinit;
13121 volatile smallint state;
13122 struct jmploc jmploc;
13123 struct stackmark smark;
13125 /* Initialize global data */
13129 #if ENABLE_ASH_ALIAS
13133 #if ENABLE_SH_MATH_SUPPORT
13134 math_hooks.lookupvar = lookupvar;
13135 math_hooks.setvar = setvar;
13136 math_hooks.endofname = endofname;
13140 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13143 #if ENABLE_FEATURE_EDITING
13144 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13147 if (setjmp(jmploc.loc)) {
13153 e = exception_type;
13157 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13160 outcslow('\n', stderr);
13162 popstackmark(&smark);
13163 FORCE_INT_ON; /* enable interrupts */
13172 exception_handler = &jmploc;
13175 TRACE(("Shell args: "));
13176 trace_puts_args(argv);
13178 rootpid = getpid();
13180 #if ENABLE_ASH_RANDOM_SUPPORT
13181 /* Can use monotonic_ns() for better randomness but for now it is
13182 * not used anywhere else in busybox... so avoid bloat */
13183 random_galois_LFSR = random_LCG = rootpid + monotonic_us();
13186 setstackmark(&smark);
13189 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13191 const char *hp = lookupvar("HISTFILE");
13194 hp = lookupvar("HOME");
13196 char *defhp = concat_path_file(hp, ".ash_history");
13197 setvar("HISTFILE", defhp, 0);
13203 if (/* argv[0] && */ argv[0][0] == '-')
13207 read_profile("/etc/profile");
13210 read_profile(".profile");
13216 getuid() == geteuid() && getgid() == getegid() &&
13220 shinit = lookupvar("ENV");
13221 if (shinit != NULL && *shinit != '\0') {
13222 read_profile(shinit);
13228 /* evalstring pushes parsefile stack.
13229 * Ensure we don't falsely claim that 0 (stdin)
13230 * is one of stacked source fds.
13231 * Testcase: ash -c 'exec 1>&0' must not complain. */
13233 g_parsefile->fd = -1;
13234 evalstring(minusc, 0);
13237 if (sflag || minusc == NULL) {
13238 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13240 const char *hp = lookupvar("HISTFILE");
13242 line_input_state->hist_file = hp;
13245 state4: /* XXX ??? - why isn't this before the "if" statement */
13253 extern void _mcleanup(void);
13263 * Copyright (c) 1989, 1991, 1993, 1994
13264 * The Regents of the University of California. All rights reserved.
13266 * This code is derived from software contributed to Berkeley by
13267 * Kenneth Almquist.
13269 * Redistribution and use in source and binary forms, with or without
13270 * modification, are permitted provided that the following conditions
13272 * 1. Redistributions of source code must retain the above copyright
13273 * notice, this list of conditions and the following disclaimer.
13274 * 2. Redistributions in binary form must reproduce the above copyright
13275 * notice, this list of conditions and the following disclaimer in the
13276 * documentation and/or other materials provided with the distribution.
13277 * 3. Neither the name of the University nor the names of its contributors
13278 * may be used to endorse or promote products derived from this software
13279 * without specific prior written permission.
13281 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13282 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13283 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13284 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13285 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13286 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13287 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13288 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13289 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13290 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF