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 static USE_ASH_OPTIMIZE_FOR_SIZE(inline) void
361 if (--suppressint == 0 && intpending) {
365 #define INT_ON int_on()
366 static USE_ASH_OPTIMIZE_FOR_SIZE(inline) void
374 #define FORCE_INT_ON force_int_on()
376 #define SAVE_INT(v) ((v) = suppressint)
378 #define RESTORE_INT(v) do { \
381 if (suppressint == 0 && intpending) \
386 /* ============ Stdout/stderr output */
389 outstr(const char *p, FILE *file)
397 flush_stdout_stderr(void)
414 outcslow(int c, FILE *dest)
422 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
424 out1fmt(const char *fmt, ...)
431 r = vprintf(fmt, ap);
437 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
439 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
446 ret = vsnprintf(outbuf, length, fmt, ap);
453 out1str(const char *p)
459 out2str(const char *p)
466 /* ============ Parser structures */
468 /* control characters in argument strings */
469 #define CTLESC '\201' /* escape next character */
470 #define CTLVAR '\202' /* variable defn */
471 #define CTLENDVAR '\203'
472 #define CTLBACKQ '\204'
473 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
474 /* CTLBACKQ | CTLQUOTE == '\205' */
475 #define CTLARI '\206' /* arithmetic expression */
476 #define CTLENDARI '\207'
477 #define CTLQUOTEMARK '\210'
479 /* variable substitution byte (follows CTLVAR) */
480 #define VSTYPE 0x0f /* type of variable substitution */
481 #define VSNUL 0x10 /* colon--treat the empty string as unset */
482 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
484 /* values of VSTYPE field */
485 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
486 #define VSMINUS 0x2 /* ${var-text} */
487 #define VSPLUS 0x3 /* ${var+text} */
488 #define VSQUESTION 0x4 /* ${var?message} */
489 #define VSASSIGN 0x5 /* ${var=text} */
490 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
491 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
492 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
493 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
494 #define VSLENGTH 0xa /* ${#var} */
495 #if ENABLE_ASH_BASH_COMPAT
496 #define VSSUBSTR 0xc /* ${var:position:length} */
497 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
498 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
501 static const char dolatstr[] ALIGN1 = {
502 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
522 #if ENABLE_ASH_BASH_COMPAT
539 smallint type; /* Nxxxx */
542 union node *redirect;
547 smallint pipe_backgnd;
548 struct nodelist *cmdlist;
554 union node *redirect;
567 union node *elsepart;
594 struct nodelist *backquote;
597 /* nfile and ndup layout must match!
598 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
599 * that it is actually NTO2 (>&file), and change its type.
616 char *_unused_expfname;
635 struct nredir nredir;
636 struct nbinary nbinary;
640 struct nclist nclist;
649 struct nodelist *next;
662 freefunc(struct funcnode *f)
664 if (f && --f->count < 0)
669 /* ============ Debugging output */
673 static FILE *tracefile;
676 trace_printf(const char *fmt, ...)
683 fprintf(tracefile, "%u ", (int) time(NULL));
685 fprintf(tracefile, "[%u] ", (int) getpid());
687 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pendingsig, intpending, suppressint);
689 vfprintf(tracefile, fmt, va);
694 trace_vprintf(const char *fmt, va_list va)
699 fprintf(tracefile, "%u ", (int) time(NULL));
701 fprintf(tracefile, "[%u] ", (int) getpid());
703 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pendingsig, intpending, suppressint);
704 vfprintf(tracefile, fmt, va);
708 trace_puts(const char *s)
716 trace_puts_quoted(char *s)
723 putc('"', tracefile);
724 for (p = s; *p; p++) {
726 case '\n': c = 'n'; goto backslash;
727 case '\t': c = 't'; goto backslash;
728 case '\r': c = 'r'; goto backslash;
729 case '"': c = '"'; goto backslash;
730 case '\\': c = '\\'; goto backslash;
731 case CTLESC: c = 'e'; goto backslash;
732 case CTLVAR: c = 'v'; goto backslash;
733 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
734 case CTLBACKQ: c = 'q'; goto backslash;
735 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
737 putc('\\', tracefile);
741 if (*p >= ' ' && *p <= '~')
744 putc('\\', tracefile);
745 putc(*p >> 6 & 03, tracefile);
746 putc(*p >> 3 & 07, tracefile);
747 putc(*p & 07, tracefile);
752 putc('"', tracefile);
756 trace_puts_args(char **ap)
763 trace_puts_quoted(*ap);
765 putc('\n', tracefile);
768 putc(' ', tracefile);
783 /* leave open because libedit might be using it */
786 strcpy(s, "./trace");
788 if (!freopen(s, "a", tracefile)) {
789 fprintf(stderr, "Can't re-open %s\n", s);
794 tracefile = fopen(s, "a");
795 if (tracefile == NULL) {
796 fprintf(stderr, "Can't open %s\n", s);
802 flags = fcntl(fileno(tracefile), F_GETFL);
804 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
806 setlinebuf(tracefile);
807 fputs("\nTracing started.\n", tracefile);
811 indent(int amount, char *pfx, FILE *fp)
815 for (i = 0; i < amount; i++) {
816 if (pfx && i == amount - 1)
822 /* little circular references here... */
823 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
826 sharg(union node *arg, FILE *fp)
829 struct nodelist *bqlist;
832 if (arg->type != NARG) {
833 out1fmt("<node type %d>\n", arg->type);
836 bqlist = arg->narg.backquote;
837 for (p = arg->narg.text; *p; p++) {
846 if (subtype == VSLENGTH)
855 switch (subtype & VSTYPE) {
888 out1fmt("<subtype %d>", subtype);
895 case CTLBACKQ|CTLQUOTE:
898 shtree(bqlist->n, -1, NULL, fp);
909 shcmd(union node *cmd, FILE *fp)
917 for (np = cmd->ncmd.args; np; np = np->narg.next) {
923 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
927 switch (np->nfile.type) {
928 case NTO: s = ">>"+1; dftfd = 1; break;
929 case NCLOBBER: s = ">|"; dftfd = 1; break;
930 case NAPPEND: s = ">>"; dftfd = 1; break;
931 #if ENABLE_ASH_BASH_COMPAT
934 case NTOFD: s = ">&"; dftfd = 1; break;
935 case NFROM: s = "<"; break;
936 case NFROMFD: s = "<&"; break;
937 case NFROMTO: s = "<>"; break;
938 default: s = "*error*"; break;
940 if (np->nfile.fd != dftfd)
941 fprintf(fp, "%d", np->nfile.fd);
943 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
944 fprintf(fp, "%d", np->ndup.dupfd);
946 sharg(np->nfile.fname, fp);
953 shtree(union node *n, int ind, char *pfx, FILE *fp)
961 indent(ind, pfx, fp);
972 shtree(n->nbinary.ch1, ind, NULL, fp);
975 shtree(n->nbinary.ch2, ind, NULL, fp);
983 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
988 if (n->npipe.pipe_backgnd)
994 fprintf(fp, "<node type %d>", n->type);
1002 showtree(union node *n)
1004 trace_puts("showtree called\n");
1005 shtree(n, 1, NULL, stdout);
1011 /* ============ Parser data */
1014 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1017 struct strlist *next;
1024 struct strpush *prev; /* preceding string on stack */
1026 int prev_left_in_line;
1027 #if ENABLE_ASH_ALIAS
1028 struct alias *ap; /* if push was associated with an alias */
1030 char *string; /* remember the string since it may change */
1034 struct parsefile *prev; /* preceding file on stack */
1035 int linno; /* current line */
1036 int fd; /* file descriptor (or -1 if string) */
1037 int left_in_line; /* number of chars left in this line */
1038 int left_in_buffer; /* number of chars left in this buffer past the line */
1039 char *next_to_pgetc; /* next char in buffer */
1040 char *buf; /* input buffer */
1041 struct strpush *strpush; /* for pushing strings at this level */
1042 struct strpush basestrpush; /* so pushing one is fast */
1045 static struct parsefile basepf; /* top level input file */
1046 static struct parsefile *g_parsefile = &basepf; /* current input file */
1047 static int startlinno; /* line # where last token started */
1048 static char *commandname; /* currently executing command */
1049 static struct strlist *cmdenviron; /* environment for builtin command */
1050 static uint8_t exitstatus; /* exit status of last command */
1053 /* ============ Message printing */
1056 ash_vmsg(const char *msg, va_list ap)
1058 fprintf(stderr, "%s: ", arg0);
1060 if (strcmp(arg0, commandname))
1061 fprintf(stderr, "%s: ", commandname);
1062 if (!iflag || g_parsefile->fd)
1063 fprintf(stderr, "line %d: ", startlinno);
1065 vfprintf(stderr, msg, ap);
1066 outcslow('\n', stderr);
1070 * Exverror is called to raise the error exception. If the second argument
1071 * is not NULL then error prints an error message using printf style
1072 * formatting. It then raises the error exception.
1074 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1076 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1080 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1082 TRACE(("\") pid=%d\n", getpid()));
1084 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1089 flush_stdout_stderr();
1090 raise_exception(cond);
1094 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1096 ash_msg_and_raise_error(const char *msg, ...)
1101 ash_vmsg_and_raise(EXERROR, msg, ap);
1106 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1108 ash_msg_and_raise(int cond, const char *msg, ...)
1113 ash_vmsg_and_raise(cond, msg, ap);
1119 * error/warning routines for external builtins
1122 ash_msg(const char *fmt, ...)
1132 * Return a string describing an error. The returned string may be a
1133 * pointer to a static buffer that will be overwritten on the next call.
1134 * Action describes the operation that got the error.
1137 errmsg(int e, const char *em)
1139 if (e == ENOENT || e == ENOTDIR) {
1146 /* ============ Memory allocation */
1149 * It appears that grabstackstr() will barf with such alignments
1150 * because stalloc() will return a string allocated in a new stackblock.
1152 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1154 /* Most machines require the value returned from malloc to be aligned
1155 * in some way. The following macro will get this right
1156 * on many machines. */
1157 SHELL_SIZE = sizeof(union {int i; char *cp; double d; }) - 1,
1158 /* Minimum size of a block */
1159 MINSIZE = SHELL_ALIGN(504),
1162 struct stack_block {
1163 struct stack_block *prev;
1164 char space[MINSIZE];
1168 struct stack_block *stackp;
1171 struct stackmark *marknext;
1175 struct globals_memstack {
1176 struct stack_block *g_stackp; // = &stackbase;
1177 struct stackmark *markp;
1178 char *g_stacknxt; // = stackbase.space;
1179 char *sstrend; // = stackbase.space + MINSIZE;
1180 size_t g_stacknleft; // = MINSIZE;
1181 int herefd; // = -1;
1182 struct stack_block stackbase;
1184 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1185 #define G_memstack (*ash_ptr_to_globals_memstack)
1186 #define g_stackp (G_memstack.g_stackp )
1187 #define markp (G_memstack.markp )
1188 #define g_stacknxt (G_memstack.g_stacknxt )
1189 #define sstrend (G_memstack.sstrend )
1190 #define g_stacknleft (G_memstack.g_stacknleft)
1191 #define herefd (G_memstack.herefd )
1192 #define stackbase (G_memstack.stackbase )
1193 #define INIT_G_memstack() do { \
1194 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1196 g_stackp = &stackbase; \
1197 g_stacknxt = stackbase.space; \
1198 g_stacknleft = MINSIZE; \
1199 sstrend = stackbase.space + MINSIZE; \
1203 #define stackblock() ((void *)g_stacknxt)
1204 #define stackblocksize() g_stacknleft
1208 ckrealloc(void * p, size_t nbytes)
1210 p = realloc(p, nbytes);
1212 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1217 ckmalloc(size_t nbytes)
1219 return ckrealloc(NULL, nbytes);
1223 ckzalloc(size_t nbytes)
1225 return memset(ckmalloc(nbytes), 0, nbytes);
1229 * Make a copy of a string in safe storage.
1232 ckstrdup(const char *s)
1234 char *p = strdup(s);
1236 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1241 * Parse trees for commands are allocated in lifo order, so we use a stack
1242 * to make this more efficient, and also to avoid all sorts of exception
1243 * handling code to handle interrupts in the middle of a parse.
1245 * The size 504 was chosen because the Ultrix malloc handles that size
1249 stalloc(size_t nbytes)
1254 aligned = SHELL_ALIGN(nbytes);
1255 if (aligned > g_stacknleft) {
1258 struct stack_block *sp;
1260 blocksize = aligned;
1261 if (blocksize < MINSIZE)
1262 blocksize = MINSIZE;
1263 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1264 if (len < blocksize)
1265 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1268 sp->prev = g_stackp;
1269 g_stacknxt = sp->space;
1270 g_stacknleft = blocksize;
1271 sstrend = g_stacknxt + blocksize;
1276 g_stacknxt += aligned;
1277 g_stacknleft -= aligned;
1282 stzalloc(size_t nbytes)
1284 return memset(stalloc(nbytes), 0, nbytes);
1291 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1292 write(STDERR_FILENO, "stunalloc\n", 10);
1296 g_stacknleft += g_stacknxt - (char *)p;
1301 * Like strdup but works with the ash stack.
1304 ststrdup(const char *p)
1306 size_t len = strlen(p) + 1;
1307 return memcpy(stalloc(len), p, len);
1311 setstackmark(struct stackmark *mark)
1313 mark->stackp = g_stackp;
1314 mark->stacknxt = g_stacknxt;
1315 mark->stacknleft = g_stacknleft;
1316 mark->marknext = markp;
1321 popstackmark(struct stackmark *mark)
1323 struct stack_block *sp;
1329 markp = mark->marknext;
1330 while (g_stackp != mark->stackp) {
1332 g_stackp = sp->prev;
1335 g_stacknxt = mark->stacknxt;
1336 g_stacknleft = mark->stacknleft;
1337 sstrend = mark->stacknxt + mark->stacknleft;
1342 * When the parser reads in a string, it wants to stick the string on the
1343 * stack and only adjust the stack pointer when it knows how big the
1344 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1345 * of space on top of the stack and stackblocklen returns the length of
1346 * this block. Growstackblock will grow this space by at least one byte,
1347 * possibly moving it (like realloc). Grabstackblock actually allocates the
1348 * part of the block that has been used.
1351 growstackblock(void)
1355 newlen = g_stacknleft * 2;
1356 if (newlen < g_stacknleft)
1357 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1361 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1362 struct stack_block *oldstackp;
1363 struct stackmark *xmark;
1364 struct stack_block *sp;
1365 struct stack_block *prevstackp;
1369 oldstackp = g_stackp;
1371 prevstackp = sp->prev;
1372 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1373 sp = ckrealloc(sp, grosslen);
1374 sp->prev = prevstackp;
1376 g_stacknxt = sp->space;
1377 g_stacknleft = newlen;
1378 sstrend = sp->space + newlen;
1381 * Stack marks pointing to the start of the old block
1382 * must be relocated to point to the new block
1385 while (xmark != NULL && xmark->stackp == oldstackp) {
1386 xmark->stackp = g_stackp;
1387 xmark->stacknxt = g_stacknxt;
1388 xmark->stacknleft = g_stacknleft;
1389 xmark = xmark->marknext;
1393 char *oldspace = g_stacknxt;
1394 size_t oldlen = g_stacknleft;
1395 char *p = stalloc(newlen);
1397 /* free the space we just allocated */
1398 g_stacknxt = memcpy(p, oldspace, oldlen);
1399 g_stacknleft += newlen;
1404 grabstackblock(size_t len)
1406 len = SHELL_ALIGN(len);
1408 g_stacknleft -= len;
1412 * The following routines are somewhat easier to use than the above.
1413 * The user declares a variable of type STACKSTR, which may be declared
1414 * to be a register. The macro STARTSTACKSTR initializes things. Then
1415 * the user uses the macro STPUTC to add characters to the string. In
1416 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1417 * grown as necessary. When the user is done, she can just leave the
1418 * string there and refer to it using stackblock(). Or she can allocate
1419 * the space for it using grabstackstr(). If it is necessary to allow
1420 * someone else to use the stack temporarily and then continue to grow
1421 * the string, the user should use grabstack to allocate the space, and
1422 * then call ungrabstr(p) to return to the previous mode of operation.
1424 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1425 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1426 * is space for at least one character.
1431 size_t len = stackblocksize();
1432 if (herefd >= 0 && len >= 1024) {
1433 full_write(herefd, stackblock(), len);
1434 return stackblock();
1437 return (char *)stackblock() + len;
1441 * Called from CHECKSTRSPACE.
1444 makestrspace(size_t newlen, char *p)
1446 size_t len = p - g_stacknxt;
1447 size_t size = stackblocksize();
1452 size = stackblocksize();
1454 if (nleft >= newlen)
1458 return (char *)stackblock() + len;
1462 stack_nputstr(const char *s, size_t n, char *p)
1464 p = makestrspace(n, p);
1465 p = (char *)memcpy(p, s, n) + n;
1470 stack_putstr(const char *s, char *p)
1472 return stack_nputstr(s, strlen(s), p);
1476 _STPUTC(int c, char *p)
1484 #define STARTSTACKSTR(p) ((p) = stackblock())
1485 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1486 #define CHECKSTRSPACE(n, p) do { \
1489 size_t m = sstrend - q; \
1491 (p) = makestrspace(l, q); \
1493 #define USTPUTC(c, p) (*(p)++ = (c))
1494 #define STACKSTRNUL(p) do { \
1495 if ((p) == sstrend) \
1496 (p) = growstackstr(); \
1499 #define STUNPUTC(p) (--(p))
1500 #define STTOPC(p) ((p)[-1])
1501 #define STADJUST(amount, p) ((p) += (amount))
1503 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1504 #define ungrabstackstr(s, p) stunalloc(s)
1505 #define stackstrend() ((void *)sstrend)
1508 /* ============ String helpers */
1511 * prefix -- see if pfx is a prefix of string.
1514 prefix(const char *string, const char *pfx)
1517 if (*pfx++ != *string++)
1520 return (char *) string;
1524 * Check for a valid number. This should be elsewhere.
1527 is_number(const char *p)
1532 } while (*++p != '\0');
1537 * Convert a string of digits to an integer, printing an error message on
1541 number(const char *s)
1544 ash_msg_and_raise_error(illnum, s);
1549 * Produce a possibly single quoted string suitable as input to the shell.
1550 * The return string is allocated on the stack.
1553 single_quote(const char *s)
1563 len = strchrnul(s, '\'') - s;
1565 q = p = makestrspace(len + 3, p);
1568 q = (char *)memcpy(q, s, len) + len;
1574 len = strspn(s, "'");
1578 q = p = makestrspace(len + 3, p);
1581 q = (char *)memcpy(q, s, len) + len;
1590 return stackblock();
1594 /* ============ nextopt */
1596 static char **argptr; /* argument list for builtin commands */
1597 static char *optionarg; /* set by nextopt (like getopt) */
1598 static char *optptr; /* used by nextopt */
1601 * XXX - should get rid of. Have all builtins use getopt(3).
1602 * The library getopt must have the BSD extension static variable
1603 * "optreset", otherwise it can't be used within the shell safely.
1605 * Standard option processing (a la getopt) for builtin routines.
1606 * The only argument that is passed to nextopt is the option string;
1607 * the other arguments are unnecessary. It returns the character,
1608 * or '\0' on end of input.
1611 nextopt(const char *optstring)
1618 if (p == NULL || *p == '\0') {
1619 /* We ate entire "-param", take next one */
1625 if (*++p == '\0') /* just "-" ? */
1628 if (LONE_DASH(p)) /* "--" ? */
1630 /* p => next "-param" */
1632 /* p => some option char in the middle of a "-param" */
1634 for (q = optstring; *q != c;) {
1636 ash_msg_and_raise_error("illegal option -%c", c);
1644 ash_msg_and_raise_error("no arg for -%c option", c);
1654 /* ============ Shell variables */
1657 * The parsefile structure pointed to by the global variable parsefile
1658 * contains information about the current file being read.
1661 int nparam; /* # of positional parameters (without $0) */
1662 #if ENABLE_ASH_GETOPTS
1663 int optind; /* next parameter to be processed by getopts */
1664 int optoff; /* used by getopts */
1666 unsigned char malloced; /* if parameter list dynamically allocated */
1667 char **p; /* parameter list */
1671 * Free the list of positional parameters.
1674 freeparam(volatile struct shparam *param)
1676 if (param->malloced) {
1678 ap = ap1 = param->p;
1685 #if ENABLE_ASH_GETOPTS
1686 static void getoptsreset(const char *value);
1690 struct var *next; /* next entry in hash list */
1691 int flags; /* flags are defined above */
1692 const char *text; /* name=value */
1693 void (*func)(const char *); /* function to be called when */
1694 /* the variable gets set/unset */
1698 struct localvar *next; /* next local variable in list */
1699 struct var *vp; /* the variable that was made local */
1700 int flags; /* saved flags */
1701 const char *text; /* saved text */
1705 #define VEXPORT 0x01 /* variable is exported */
1706 #define VREADONLY 0x02 /* variable cannot be modified */
1707 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1708 #define VTEXTFIXED 0x08 /* text is statically allocated */
1709 #define VSTACK 0x10 /* text is allocated on the stack */
1710 #define VUNSET 0x20 /* the variable is not set */
1711 #define VNOFUNC 0x40 /* don't call the callback function */
1712 #define VNOSET 0x80 /* do not set variable - just readonly test */
1713 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1714 #if ENABLE_ASH_RANDOM_SUPPORT
1715 # define VDYNAMIC 0x200 /* dynamic variable */
1721 static const char defifsvar[] ALIGN1 = "IFS= \t\n";
1722 #define defifs (defifsvar + 4)
1724 static const char defifs[] ALIGN1 = " \t\n";
1728 /* Need to be before varinit_data[] */
1729 #if ENABLE_LOCALE_SUPPORT
1731 change_lc_all(const char *value)
1733 if (value && *value != '\0')
1734 setlocale(LC_ALL, value);
1737 change_lc_ctype(const char *value)
1739 if (value && *value != '\0')
1740 setlocale(LC_CTYPE, value);
1744 static void chkmail(void);
1745 static void changemail(const char *);
1747 static void changepath(const char *);
1748 #if ENABLE_ASH_RANDOM_SUPPORT
1749 static void change_random(const char *);
1752 static const struct {
1755 void (*func)(const char *);
1756 } varinit_data[] = {
1758 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1760 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
1763 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1764 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1766 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1767 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1768 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1769 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1770 #if ENABLE_ASH_GETOPTS
1771 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1773 #if ENABLE_ASH_RANDOM_SUPPORT
1774 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
1776 #if ENABLE_LOCALE_SUPPORT
1777 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1778 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
1780 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1781 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
1787 struct globals_var {
1788 struct shparam shellparam; /* $@ current positional parameters */
1789 struct redirtab *redirlist;
1791 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1792 struct var *vartab[VTABSIZE];
1793 struct var varinit[ARRAY_SIZE(varinit_data)];
1795 extern struct globals_var *const ash_ptr_to_globals_var;
1796 #define G_var (*ash_ptr_to_globals_var)
1797 #define shellparam (G_var.shellparam )
1798 //#define redirlist (G_var.redirlist )
1799 #define g_nullredirs (G_var.g_nullredirs )
1800 #define preverrout_fd (G_var.preverrout_fd)
1801 #define vartab (G_var.vartab )
1802 #define varinit (G_var.varinit )
1803 #define INIT_G_var() do { \
1805 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1807 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1808 varinit[i].flags = varinit_data[i].flags; \
1809 varinit[i].text = varinit_data[i].text; \
1810 varinit[i].func = varinit_data[i].func; \
1814 #define vifs varinit[0]
1816 # define vmail (&vifs)[1]
1817 # define vmpath (&vmail)[1]
1818 # define vpath (&vmpath)[1]
1820 # define vpath (&vifs)[1]
1822 #define vps1 (&vpath)[1]
1823 #define vps2 (&vps1)[1]
1824 #define vps4 (&vps2)[1]
1825 #if ENABLE_ASH_GETOPTS
1826 # define voptind (&vps4)[1]
1827 # if ENABLE_ASH_RANDOM_SUPPORT
1828 # define vrandom (&voptind)[1]
1831 # if ENABLE_ASH_RANDOM_SUPPORT
1832 # define vrandom (&vps4)[1]
1837 * The following macros access the values of the above variables.
1838 * They have to skip over the name. They return the null string
1839 * for unset variables.
1841 #define ifsval() (vifs.text + 4)
1842 #define ifsset() ((vifs.flags & VUNSET) == 0)
1844 # define mailval() (vmail.text + 5)
1845 # define mpathval() (vmpath.text + 9)
1846 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1848 #define pathval() (vpath.text + 5)
1849 #define ps1val() (vps1.text + 4)
1850 #define ps2val() (vps2.text + 4)
1851 #define ps4val() (vps4.text + 4)
1852 #if ENABLE_ASH_GETOPTS
1853 # define optindval() (voptind.text + 7)
1857 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1858 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1860 #if ENABLE_ASH_GETOPTS
1862 getoptsreset(const char *value)
1864 shellparam.optind = number(value);
1865 shellparam.optoff = -1;
1870 * Return of a legal variable name (a letter or underscore followed by zero or
1871 * more letters, underscores, and digits).
1874 endofname(const char *name)
1882 if (!is_in_name(*p))
1889 * Compares two strings up to the first = or '\0'. The first
1890 * string must be terminated by '='; the second may be terminated by
1891 * either '=' or '\0'.
1894 varcmp(const char *p, const char *q)
1898 while ((c = *p) == (d = *q)) {
1913 varequal(const char *a, const char *b)
1915 return !varcmp(a, b);
1919 * Find the appropriate entry in the hash table from the name.
1921 static struct var **
1922 hashvar(const char *p)
1926 hashval = ((unsigned char) *p) << 4;
1927 while (*p && *p != '=')
1928 hashval += (unsigned char) *p++;
1929 return &vartab[hashval % VTABSIZE];
1933 vpcmp(const void *a, const void *b)
1935 return varcmp(*(const char **)a, *(const char **)b);
1939 * This routine initializes the builtin variables.
1949 * PS1 depends on uid
1951 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1952 vps1.text = "PS1=\\w \\$ ";
1955 vps1.text = "PS1=# ";
1958 end = vp + ARRAY_SIZE(varinit);
1960 vpp = hashvar(vp->text);
1963 } while (++vp < end);
1966 static struct var **
1967 findvar(struct var **vpp, const char *name)
1969 for (; *vpp; vpp = &(*vpp)->next) {
1970 if (varequal((*vpp)->text, name)) {
1978 * Find the value of a variable. Returns NULL if not set.
1981 lookupvar(const char *name)
1985 v = *findvar(hashvar(name), name);
1987 #if ENABLE_ASH_RANDOM_SUPPORT
1989 * Dynamic variables are implemented roughly the same way they are
1990 * in bash. Namely, they're "special" so long as they aren't unset.
1991 * As soon as they're unset, they're no longer dynamic, and dynamic
1992 * lookup will no longer happen at that point. -- PFM.
1994 if ((v->flags & VDYNAMIC))
1997 if (!(v->flags & VUNSET))
1998 return strchrnul(v->text, '=') + 1;
2004 * Search the environment of a builtin command.
2007 bltinlookup(const char *name)
2011 for (sp = cmdenviron; sp; sp = sp->next) {
2012 if (varequal(sp->text, name))
2013 return strchrnul(sp->text, '=') + 1;
2015 return lookupvar(name);
2019 * Same as setvar except that the variable and value are passed in
2020 * the first argument as name=value. Since the first argument will
2021 * be actually stored in the table, it should not be a string that
2023 * Called with interrupts off.
2026 setvareq(char *s, int flags)
2028 struct var *vp, **vpp;
2031 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2032 vp = *findvar(vpp, s);
2034 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2037 if (flags & VNOSAVE)
2040 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2046 if (vp->func && (flags & VNOFUNC) == 0)
2047 (*vp->func)(strchrnul(s, '=') + 1);
2049 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2050 free((char*)vp->text);
2052 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2057 vp = ckzalloc(sizeof(*vp));
2059 /*vp->func = NULL; - ckzalloc did it */
2062 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2069 * Set the value of a variable. The flags argument is ored with the
2070 * flags of the variable. If val is NULL, the variable is unset.
2073 setvar(const char *name, const char *val, int flags)
2080 q = endofname(name);
2081 p = strchrnul(q, '=');
2083 if (!namelen || p != q)
2084 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2089 vallen = strlen(val);
2092 nameeq = ckmalloc(namelen + vallen + 2);
2093 p = (char *)memcpy(nameeq, name, namelen) + namelen;
2096 p = (char *)memcpy(p, val, vallen) + vallen;
2099 setvareq(nameeq, flags | VNOSAVE);
2103 #if ENABLE_ASH_GETOPTS
2105 * Safe version of setvar, returns 1 on success 0 on failure.
2108 setvarsafe(const char *name, const char *val, int flags)
2111 volatile int saveint;
2112 struct jmploc *volatile savehandler = exception_handler;
2113 struct jmploc jmploc;
2116 if (setjmp(jmploc.loc))
2119 exception_handler = &jmploc;
2120 setvar(name, val, flags);
2123 exception_handler = savehandler;
2124 RESTORE_INT(saveint);
2130 * Unset the specified variable.
2133 unsetvar(const char *s)
2139 vpp = findvar(hashvar(s), s);
2143 int flags = vp->flags;
2146 if (flags & VREADONLY)
2148 #if ENABLE_ASH_RANDOM_SUPPORT
2149 vp->flags &= ~VDYNAMIC;
2153 if ((flags & VSTRFIXED) == 0) {
2155 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2156 free((char*)vp->text);
2162 vp->flags &= ~VEXPORT;
2172 * Process a linked list of variable assignments.
2175 listsetvar(struct strlist *list_set_var, int flags)
2177 struct strlist *lp = list_set_var;
2183 setvareq(lp->text, flags);
2190 * Generate a list of variables satisfying the given conditions.
2193 listvars(int on, int off, char ***end)
2204 for (vp = *vpp; vp; vp = vp->next) {
2205 if ((vp->flags & mask) == on) {
2206 if (ep == stackstrend())
2207 ep = growstackstr();
2208 *ep++ = (char *) vp->text;
2211 } while (++vpp < vartab + VTABSIZE);
2212 if (ep == stackstrend())
2213 ep = growstackstr();
2217 return grabstackstr(ep);
2221 /* ============ Path search helper
2223 * The variable path (passed by reference) should be set to the start
2224 * of the path before the first call; padvance will update
2225 * this value as it proceeds. Successive calls to padvance will return
2226 * the possible path expansions in sequence. If an option (indicated by
2227 * a percent sign) appears in the path entry then the global variable
2228 * pathopt will be set to point to it; otherwise pathopt will be set to
2231 static const char *pathopt; /* set by padvance */
2234 padvance(const char **path, const char *name)
2244 for (p = start; *p && *p != ':' && *p != '%'; p++)
2246 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2247 while (stackblocksize() < len)
2251 memcpy(q, start, p - start);
2259 while (*p && *p != ':')
2266 return stalloc(len);
2270 /* ============ Prompt */
2272 static smallint doprompt; /* if set, prompt the user */
2273 static smallint needprompt; /* true if interactive and at start of line */
2275 #if ENABLE_FEATURE_EDITING
2276 static line_input_t *line_input_state;
2277 static const char *cmdedit_prompt;
2279 putprompt(const char *s)
2281 if (ENABLE_ASH_EXPAND_PRMT) {
2282 free((char*)cmdedit_prompt);
2283 cmdedit_prompt = ckstrdup(s);
2290 putprompt(const char *s)
2296 #if ENABLE_ASH_EXPAND_PRMT
2297 /* expandstr() needs parsing machinery, so it is far away ahead... */
2298 static const char *expandstr(const char *ps);
2300 #define expandstr(s) s
2304 setprompt(int whichprompt)
2307 #if ENABLE_ASH_EXPAND_PRMT
2308 struct stackmark smark;
2313 switch (whichprompt) {
2323 #if ENABLE_ASH_EXPAND_PRMT
2324 setstackmark(&smark);
2325 stalloc(stackblocksize());
2327 putprompt(expandstr(prompt));
2328 #if ENABLE_ASH_EXPAND_PRMT
2329 popstackmark(&smark);
2334 /* ============ The cd and pwd commands */
2336 #define CD_PHYSICAL 1
2339 static int docd(const char *, int);
2348 while ((i = nextopt("LP"))) {
2350 flags ^= CD_PHYSICAL;
2359 * Update curdir (the name of the current directory) in response to a
2363 updatepwd(const char *dir)
2370 cdcomppath = ststrdup(dir);
2373 if (curdir == nullstr)
2375 new = stack_putstr(curdir, new);
2377 new = makestrspace(strlen(dir) + 2, new);
2378 lim = (char *)stackblock() + 1;
2382 if (new > lim && *lim == '/')
2387 if (dir[1] == '/' && dir[2] != '/') {
2393 p = strtok(cdcomppath, "/");
2397 if (p[1] == '.' && p[2] == '\0') {
2409 new = stack_putstr(p, new);
2417 return stackblock();
2421 * Find out what the current directory is. If we already know the current
2422 * directory, this routine returns immediately.
2427 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2428 return dir ? dir : nullstr;
2432 setpwd(const char *val, int setold)
2436 oldcur = dir = curdir;
2439 setvar("OLDPWD", oldcur, VEXPORT);
2442 if (physdir != nullstr) {
2443 if (physdir != oldcur)
2447 if (oldcur == val || !val) {
2453 dir = ckstrdup(val);
2454 if (oldcur != dir && oldcur != nullstr) {
2459 setvar("PWD", dir, VEXPORT);
2462 static void hashcd(void);
2465 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2466 * know that the current directory has changed.
2469 docd(const char *dest, int flags)
2471 const char *dir = 0;
2474 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2477 if (!(flags & CD_PHYSICAL)) {
2478 dir = updatepwd(dest);
2493 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2505 dest = bltinlookup(homestr);
2506 else if (LONE_DASH(dest)) {
2507 dest = bltinlookup("OLDPWD");
2529 path = bltinlookup("CDPATH");
2538 p = padvance(&path, dest);
2539 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2543 if (!docd(p, flags))
2548 ash_msg_and_raise_error("can't cd to %s", dest);
2551 if (flags & CD_PRINT)
2552 out1fmt(snlfmt, curdir);
2557 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2560 const char *dir = curdir;
2564 if (physdir == nullstr)
2568 out1fmt(snlfmt, dir);
2573 /* ============ ... */
2576 #define IBUFSIZ COMMON_BUFSIZE
2577 /* buffer for top level input file */
2578 #define basebuf bb_common_bufsiz1
2580 /* Syntax classes */
2581 #define CWORD 0 /* character is nothing special */
2582 #define CNL 1 /* newline character */
2583 #define CBACK 2 /* a backslash character */
2584 #define CSQUOTE 3 /* single quote */
2585 #define CDQUOTE 4 /* double quote */
2586 #define CENDQUOTE 5 /* a terminating quote */
2587 #define CBQUOTE 6 /* backwards single quote */
2588 #define CVAR 7 /* a dollar sign */
2589 #define CENDVAR 8 /* a '}' character */
2590 #define CLP 9 /* a left paren in arithmetic */
2591 #define CRP 10 /* a right paren in arithmetic */
2592 #define CENDFILE 11 /* end of file */
2593 #define CCTL 12 /* like CWORD, except it must be escaped */
2594 #define CSPCL 13 /* these terminate a word */
2595 #define CIGN 14 /* character should be ignored */
2597 #if ENABLE_ASH_ALIAS
2601 #define PEOA_OR_PEOF PEOA
2605 #define PEOA_OR_PEOF PEOF
2608 /* number syntax index */
2609 #define BASESYNTAX 0 /* not in quotes */
2610 #define DQSYNTAX 1 /* in double quotes */
2611 #define SQSYNTAX 2 /* in single quotes */
2612 #define ARISYNTAX 3 /* in arithmetic */
2613 #define PSSYNTAX 4 /* prompt */
2615 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
2616 #define USE_SIT_FUNCTION
2619 #if ENABLE_SH_MATH_SUPPORT
2620 static const char S_I_T[][4] = {
2621 #if ENABLE_ASH_ALIAS
2622 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
2624 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2625 { CNL, CNL, CNL, CNL }, /* 2, \n */
2626 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2627 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2628 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2629 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2630 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2631 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2632 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2633 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2634 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
2635 #ifndef USE_SIT_FUNCTION
2636 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2637 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2638 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2642 static const char S_I_T[][3] = {
2643 #if ENABLE_ASH_ALIAS
2644 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
2646 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2647 { CNL, CNL, CNL }, /* 2, \n */
2648 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2649 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2650 { CVAR, CVAR, CWORD }, /* 5, $ */
2651 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2652 { CSPCL, CWORD, CWORD }, /* 7, ( */
2653 { CSPCL, CWORD, CWORD }, /* 8, ) */
2654 { CBACK, CBACK, CCTL }, /* 9, \ */
2655 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2656 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
2657 #ifndef USE_SIT_FUNCTION
2658 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2659 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2660 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2663 #endif /* SH_MATH_SUPPORT */
2665 #ifdef USE_SIT_FUNCTION
2668 SIT(int c, int syntax)
2670 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2671 #if ENABLE_ASH_ALIAS
2672 static const char syntax_index_table[] ALIGN1 = {
2673 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2674 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2675 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2679 static const char syntax_index_table[] ALIGN1 = {
2680 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2681 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2682 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2689 if (c == PEOF) { /* 2^8+2 */
2692 #if ENABLE_ASH_ALIAS
2693 if (c == PEOA) { /* 2^8+1 */
2698 if ((unsigned char)c >= (unsigned char)(CTLESC)
2699 && (unsigned char)c <= (unsigned char)(CTLQUOTEMARK)
2703 s = strchrnul(spec_symbls, c);
2707 indx = syntax_index_table[s - spec_symbls];
2709 return S_I_T[indx][syntax];
2712 #else /* !USE_SIT_FUNCTION */
2714 #if ENABLE_ASH_ALIAS
2715 #define CSPCL_CIGN_CIGN_CIGN 0
2716 #define CSPCL_CWORD_CWORD_CWORD 1
2717 #define CNL_CNL_CNL_CNL 2
2718 #define CWORD_CCTL_CCTL_CWORD 3
2719 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2720 #define CVAR_CVAR_CWORD_CVAR 5
2721 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2722 #define CSPCL_CWORD_CWORD_CLP 7
2723 #define CSPCL_CWORD_CWORD_CRP 8
2724 #define CBACK_CBACK_CCTL_CBACK 9
2725 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2726 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2727 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2728 #define CWORD_CWORD_CWORD_CWORD 13
2729 #define CCTL_CCTL_CCTL_CCTL 14
2731 #define CSPCL_CWORD_CWORD_CWORD 0
2732 #define CNL_CNL_CNL_CNL 1
2733 #define CWORD_CCTL_CCTL_CWORD 2
2734 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2735 #define CVAR_CVAR_CWORD_CVAR 4
2736 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2737 #define CSPCL_CWORD_CWORD_CLP 6
2738 #define CSPCL_CWORD_CWORD_CRP 7
2739 #define CBACK_CBACK_CCTL_CBACK 8
2740 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2741 #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2742 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2743 #define CWORD_CWORD_CWORD_CWORD 12
2744 #define CCTL_CCTL_CCTL_CCTL 13
2747 static const char syntax_index_table[258] = {
2748 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2749 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2750 #if ENABLE_ASH_ALIAS
2751 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2753 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2755 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2756 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2757 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2758 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2759 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2760 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2761 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2762 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2763 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2764 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2765 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2766 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2767 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2768 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2769 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2770 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2771 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2772 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2773 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2774 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2775 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2776 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2777 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2778 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2779 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2780 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2781 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2782 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2793 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2794 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2795 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2796 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2797 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2798 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2799 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2800 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2801 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2802 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2803 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2804 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2805 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2806 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2807 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2808 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2809 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2810 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2811 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2812 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2813 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2814 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2815 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2816 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2817 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2818 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2819 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2820 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2821 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2822 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2823 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2824 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2825 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2826 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2827 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2828 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2829 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2830 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2831 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2832 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2833 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2834 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2835 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2836 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2837 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2838 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2839 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2840 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2841 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2842 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2891 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2892 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2914 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2915 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2916 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2918 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2920 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2921 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2922 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2923 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2924 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2926 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2927 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2928 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2929 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2940 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2941 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2942 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2943 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2944 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2945 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2973 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2974 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2975 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2978 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3006 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3007 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3008 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
3011 #define SIT(c, syntax) (S_I_T[(int)syntax_index_table[(int)(c) + SYNBASE]][syntax])
3013 #endif /* USE_SIT_FUNCTION */
3016 /* ============ Alias handling */
3018 #if ENABLE_ASH_ALIAS
3020 #define ALIASINUSE 1
3031 static struct alias **atab; // [ATABSIZE];
3032 #define INIT_G_alias() do { \
3033 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3037 static struct alias **
3038 __lookupalias(const char *name) {
3039 unsigned int hashval;
3046 ch = (unsigned char)*p;
3050 ch = (unsigned char)*++p;
3052 app = &atab[hashval % ATABSIZE];
3054 for (; *app; app = &(*app)->next) {
3055 if (strcmp(name, (*app)->name) == 0) {
3063 static struct alias *
3064 lookupalias(const char *name, int check)
3066 struct alias *ap = *__lookupalias(name);
3068 if (check && ap && (ap->flag & ALIASINUSE))
3073 static struct alias *
3074 freealias(struct alias *ap)
3078 if (ap->flag & ALIASINUSE) {
3079 ap->flag |= ALIASDEAD;
3091 setalias(const char *name, const char *val)
3093 struct alias *ap, **app;
3095 app = __lookupalias(name);
3099 if (!(ap->flag & ALIASINUSE)) {
3102 ap->val = ckstrdup(val);
3103 ap->flag &= ~ALIASDEAD;
3106 ap = ckzalloc(sizeof(struct alias));
3107 ap->name = ckstrdup(name);
3108 ap->val = ckstrdup(val);
3109 /*ap->flag = 0; - ckzalloc did it */
3110 /*ap->next = NULL;*/
3117 unalias(const char *name)
3121 app = __lookupalias(name);
3125 *app = freealias(*app);
3136 struct alias *ap, **app;
3140 for (i = 0; i < ATABSIZE; i++) {
3142 for (ap = *app; ap; ap = *app) {
3143 *app = freealias(*app);
3153 printalias(const struct alias *ap)
3155 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3159 * TODO - sort output
3162 aliascmd(int argc UNUSED_PARAM, char **argv)
3171 for (i = 0; i < ATABSIZE; i++) {
3172 for (ap = atab[i]; ap; ap = ap->next) {
3178 while ((n = *++argv) != NULL) {
3179 v = strchr(n+1, '=');
3180 if (v == NULL) { /* n+1: funny ksh stuff */
3181 ap = *__lookupalias(n);
3183 fprintf(stderr, "%s: %s not found\n", "alias", n);
3197 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3201 while ((i = nextopt("a")) != '\0') {
3207 for (i = 0; *argptr; argptr++) {
3208 if (unalias(*argptr)) {
3209 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3217 #endif /* ASH_ALIAS */
3220 /* ============ jobs.c */
3222 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3225 #define FORK_NOJOB 2
3227 /* mode flags for showjob(s) */
3228 #define SHOW_PGID 0x01 /* only show pgid - for jobs -p */
3229 #define SHOW_PID 0x04 /* include process pid */
3230 #define SHOW_CHANGED 0x08 /* only jobs whose state has changed */
3233 * A job structure contains information about a job. A job is either a
3234 * single process or a set of processes contained in a pipeline. In the
3235 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3240 pid_t pid; /* process id */
3241 int status; /* last process status from wait() */
3242 char *cmd; /* text of command being run */
3246 struct procstat ps0; /* status of process */
3247 struct procstat *ps; /* status or processes when more than one */
3249 int stopstatus; /* status of a stopped job */
3252 nprocs: 16, /* number of processes */
3254 #define JOBRUNNING 0 /* at least one proc running */
3255 #define JOBSTOPPED 1 /* all procs are stopped */
3256 #define JOBDONE 2 /* all procs are completed */
3258 sigint: 1, /* job was killed by SIGINT */
3259 jobctl: 1, /* job running under job control */
3261 waited: 1, /* true if this entry has been waited for */
3262 used: 1, /* true if this entry is in used */
3263 changed: 1; /* true if status has changed */
3264 struct job *prev_job; /* previous job */
3267 static struct job *makejob(/*union node *,*/ int);
3269 #define forkshell(job, node, mode) forkshell(job, mode)
3271 static int forkshell(struct job *, union node *, int);
3272 static int waitforjob(struct job *);
3275 enum { doing_jobctl = 0 };
3276 #define setjobctl(on) do {} while (0)
3278 static smallint doing_jobctl; //references:8
3279 static void setjobctl(int);
3286 ignoresig(int signo)
3288 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3289 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3290 /* No, need to do it */
3291 signal(signo, SIG_IGN);
3293 sigmode[signo - 1] = S_HARD_IGN;
3297 * Signal handler. Only one usage site - in setsignal()
3302 gotsig[signo - 1] = 1;
3304 if (/* exsig || */ (signo == SIGINT && !trap[SIGINT])) {
3307 raise_interrupt(); /* does not return */
3316 * Set the signal handler for the specified signal. The routine figures
3317 * out what it should be set to.
3320 setsignal(int signo)
3323 char cur_act, new_act;
3324 struct sigaction act;
3328 if (t != NULL) { /* trap for this sig is set */
3330 if (t[0] == '\0') /* trap is "": ignore this sig */
3334 if (rootshell && new_act == S_DFL) {
3337 if (iflag || minusc || sflag == 0)
3346 * "In all cases, bash ignores SIGQUIT. Non-builtin
3347 * commands run by bash have signal handlers
3348 * set to the values inherited by the shell
3349 * from its parent". */
3365 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3366 //whereas we have to restore it to what shell got on entry
3367 //from the parent. See comment above
3369 t = &sigmode[signo - 1];
3372 /* current setting is not yet known */
3373 if (sigaction(signo, NULL, &act)) {
3374 /* pretend it worked; maybe we should give a warning,
3375 * but other shells don't. We don't alter sigmode,
3376 * so we retry every time.
3377 * btw, in Linux it never fails. --vda */
3380 if (act.sa_handler == SIG_IGN) {
3381 cur_act = S_HARD_IGN;
3383 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3385 cur_act = S_IGN; /* don't hard ignore these */
3389 if (cur_act == S_HARD_IGN || cur_act == new_act)
3392 act.sa_handler = SIG_DFL;
3395 act.sa_handler = onsig;
3396 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3397 sigfillset(&act.sa_mask); /* ditto */
3400 act.sa_handler = SIG_IGN;
3403 sigaction_set(signo, &act);
3408 /* mode flags for set_curjob */
3409 #define CUR_DELETE 2
3410 #define CUR_RUNNING 1
3411 #define CUR_STOPPED 0
3413 /* mode flags for dowait */
3414 #define DOWAIT_NONBLOCK WNOHANG
3415 #define DOWAIT_BLOCK 0
3418 /* pgrp of shell on invocation */
3419 static int initialpgrp; //references:2
3420 static int ttyfd = -1; //5
3423 static struct job *jobtab; //5
3425 static unsigned njobs; //4
3427 static struct job *curjob; //lots
3428 /* number of presumed living untracked jobs */
3429 static int jobless; //4
3432 set_curjob(struct job *jp, unsigned mode)
3435 struct job **jpp, **curp;
3437 /* first remove from list */
3438 jpp = curp = &curjob;
3443 jpp = &jp1->prev_job;
3445 *jpp = jp1->prev_job;
3447 /* Then re-insert in correct position */
3455 /* job being deleted */
3458 /* newly created job or backgrounded job,
3459 put after all stopped jobs. */
3463 if (!jp1 || jp1->state != JOBSTOPPED)
3466 jpp = &jp1->prev_job;
3472 /* newly stopped job - becomes curjob */
3473 jp->prev_job = *jpp;
3481 jobno(const struct job *jp)
3483 return jp - jobtab + 1;
3488 * Convert a job name to a job structure.
3491 #define getjob(name, getctl) getjob(name)
3494 getjob(const char *name, int getctl)
3498 const char *err_msg = "No such job: %s";
3502 char *(*match)(const char *, const char *);
3517 if (c == '+' || c == '%') {
3519 err_msg = "No current job";
3525 err_msg = "No previous job";
3534 // TODO: number() instead? It does error checking...
3537 jp = jobtab + num - 1;
3554 if (match(jp->ps[0].cmd, p)) {
3558 err_msg = "%s: ambiguous";
3565 err_msg = "job %s not created under job control";
3566 if (getctl && jp->jobctl == 0)
3571 ash_msg_and_raise_error(err_msg, name);
3575 * Mark a job structure as unused.
3578 freejob(struct job *jp)
3580 struct procstat *ps;
3584 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3585 if (ps->cmd != nullstr)
3588 if (jp->ps != &jp->ps0)
3591 set_curjob(jp, CUR_DELETE);
3597 xtcsetpgrp(int fd, pid_t pgrp)
3599 if (tcsetpgrp(fd, pgrp))
3600 ash_msg_and_raise_error("can't set tty process group (%m)");
3604 * Turn job control on and off.
3606 * Note: This code assumes that the third arg to ioctl is a character
3607 * pointer, which is true on Berkeley systems but not System V. Since
3608 * System V doesn't have job control yet, this isn't a problem now.
3610 * Called with interrupts off.
3618 if (on == doing_jobctl || rootshell == 0)
3622 ofd = fd = open(_PATH_TTY, O_RDWR);
3624 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3625 * That sometimes helps to acquire controlling tty.
3626 * Obviously, a workaround for bugs when someone
3627 * failed to provide a controlling tty to bash! :) */
3633 fd = fcntl(fd, F_DUPFD, 10);
3638 /* fd is a tty at this point */
3639 close_on_exec_on(fd);
3640 do { /* while we are in the background */
3641 pgrp = tcgetpgrp(fd);
3644 ash_msg("can't access tty; job control turned off");
3648 if (pgrp == getpgrp())
3659 xtcsetpgrp(fd, pgrp);
3661 /* turning job control off */
3664 /* was xtcsetpgrp, but this can make exiting ash
3665 * loop forever if pty is already deleted */
3666 tcsetpgrp(fd, pgrp);
3681 killcmd(int argc, char **argv)
3684 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3686 if (argv[i][0] == '%') {
3687 struct job *jp = getjob(argv[i], 0);
3688 unsigned pid = jp->ps[0].pid;
3689 /* Enough space for ' -NNN<nul>' */
3690 argv[i] = alloca(sizeof(int)*3 + 3);
3691 /* kill_main has matching code to expect
3692 * leading space. Needed to not confuse
3693 * negative pids with "kill -SIGNAL_NO" syntax */
3694 sprintf(argv[i], " -%u", pid);
3696 } while (argv[++i]);
3698 return kill_main(argc, argv);
3702 showpipe(struct job *jp, FILE *out)
3704 struct procstat *sp;
3705 struct procstat *spend;
3707 spend = jp->ps + jp->nprocs;
3708 for (sp = jp->ps + 1; sp < spend; sp++)
3709 fprintf(out, " | %s", sp->cmd);
3710 outcslow('\n', out);
3711 flush_stdout_stderr();
3716 restartjob(struct job *jp, int mode)
3718 struct procstat *ps;
3724 if (jp->state == JOBDONE)
3726 jp->state = JOBRUNNING;
3728 if (mode == FORK_FG)
3729 xtcsetpgrp(ttyfd, pgid);
3730 killpg(pgid, SIGCONT);
3734 if (WIFSTOPPED(ps->status)) {
3740 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3746 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3753 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3758 jp = getjob(*argv, 1);
3759 if (mode == FORK_BG) {
3760 set_curjob(jp, CUR_RUNNING);
3761 fprintf(out, "[%d] ", jobno(jp));
3763 outstr(jp->ps->cmd, out);
3765 retval = restartjob(jp, mode);
3766 } while (*argv && *++argv);
3772 sprint_status(char *s, int status, int sigonly)
3778 if (!WIFEXITED(status)) {
3780 if (WIFSTOPPED(status))
3781 st = WSTOPSIG(status);
3784 st = WTERMSIG(status);
3786 if (st == SIGINT || st == SIGPIPE)
3789 if (WIFSTOPPED(status))
3794 col = fmtstr(s, 32, strsignal(st));
3795 if (WCOREDUMP(status)) {
3796 col += fmtstr(s + col, 16, " (core dumped)");
3798 } else if (!sigonly) {
3799 st = WEXITSTATUS(status);
3801 col = fmtstr(s, 16, "Done(%d)", st);
3803 col = fmtstr(s, 16, "Done");
3810 dowait(int wait_flags, struct job *job)
3815 struct job *thisjob;
3818 TRACE(("dowait(0x%x) called\n", wait_flags));
3820 /* Do a wait system call. If job control is compiled in, we accept
3821 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3822 * NB: _not_ safe_waitpid, we need to detect EINTR */
3823 pid = waitpid(-1, &status,
3824 (doing_jobctl ? (wait_flags | WUNTRACED) : wait_flags));
3825 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3826 pid, status, errno, strerror(errno)));
3832 for (jp = curjob; jp; jp = jp->prev_job) {
3833 struct procstat *sp;
3834 struct procstat *spend;
3835 if (jp->state == JOBDONE)
3838 spend = jp->ps + jp->nprocs;
3841 if (sp->pid == pid) {
3842 TRACE(("Job %d: changing status of proc %d "
3843 "from 0x%x to 0x%x\n",
3844 jobno(jp), pid, sp->status, status));
3845 sp->status = status;
3848 if (sp->status == -1)
3851 if (state == JOBRUNNING)
3853 if (WIFSTOPPED(sp->status)) {
3854 jp->stopstatus = sp->status;
3858 } while (++sp < spend);
3863 if (!WIFSTOPPED(status))
3869 if (state != JOBRUNNING) {
3870 thisjob->changed = 1;
3872 if (thisjob->state != state) {
3873 TRACE(("Job %d: changing state from %d to %d\n",
3874 jobno(thisjob), thisjob->state, state));
3875 thisjob->state = state;
3877 if (state == JOBSTOPPED) {
3878 set_curjob(thisjob, CUR_STOPPED);
3887 if (thisjob && thisjob == job) {
3891 len = sprint_status(s, status, 1);
3902 blocking_wait_with_raise_on_sig(struct job *job)
3904 pid_t pid = dowait(DOWAIT_BLOCK, job);
3905 if (pid <= 0 && pendingsig)
3906 raise_exception(EXSIG);
3912 showjob(FILE *out, struct job *jp, int mode)
3914 struct procstat *ps;
3915 struct procstat *psend;
3922 if (mode & SHOW_PGID) {
3923 /* just output process (group) id of pipeline */
3924 fprintf(out, "%d\n", ps->pid);
3928 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3933 else if (curjob && jp == curjob->prev_job)
3936 if (mode & SHOW_PID)
3937 col += fmtstr(s + col, 16, "%d ", ps->pid);
3939 psend = ps + jp->nprocs;
3941 if (jp->state == JOBRUNNING) {
3942 strcpy(s + col, "Running");
3943 col += sizeof("Running") - 1;
3945 int status = psend[-1].status;
3946 if (jp->state == JOBSTOPPED)
3947 status = jp->stopstatus;
3948 col += sprint_status(s + col, status, 0);
3954 /* for each process */
3955 col = fmtstr(s, 48, " |\n%*c%d ", indent_col, ' ', ps->pid) - 3;
3957 fprintf(out, "%s%*c%s",
3958 s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
3960 if (!(mode & SHOW_PID)) {
3964 if (++ps == psend) {
3965 outcslow('\n', out);
3972 if (jp->state == JOBDONE) {
3973 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3979 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3980 * statuses have changed since the last call to showjobs.
3983 showjobs(FILE *out, int mode)
3987 TRACE(("showjobs(%x) called\n", mode));
3989 /* Handle all finished jobs */
3990 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
3993 for (jp = curjob; jp; jp = jp->prev_job) {
3994 if (!(mode & SHOW_CHANGED) || jp->changed) {
3995 showjob(out, jp, mode);
4001 jobscmd(int argc UNUSED_PARAM, char **argv)
4006 while ((m = nextopt("lp"))) {
4016 showjob(stdout, getjob(*argv,0), mode);
4019 showjobs(stdout, mode);
4026 getstatus(struct job *job)
4031 status = job->ps[job->nprocs - 1].status;
4032 retval = WEXITSTATUS(status);
4033 if (!WIFEXITED(status)) {
4035 retval = WSTOPSIG(status);
4036 if (!WIFSTOPPED(status))
4039 /* XXX: limits number of signals */
4040 retval = WTERMSIG(status);
4042 if (retval == SIGINT)
4048 TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
4049 jobno(job), job->nprocs, status, retval));
4054 waitcmd(int argc UNUSED_PARAM, char **argv)
4063 raise_exception(EXSIG);
4070 /* wait for all jobs */
4074 if (!jp) /* no running procs */
4076 if (jp->state == JOBRUNNING)
4082 * "When bash is waiting for an asynchronous command via
4083 * the wait builtin, the reception of a signal for which a trap
4084 * has been set will cause the wait builtin to return immediately
4085 * with an exit status greater than 128, immediately after which
4086 * the trap is executed."
4087 * Do we do it that way? */
4088 blocking_wait_with_raise_on_sig(NULL);
4094 if (**argv != '%') {
4095 pid_t pid = number(*argv);
4100 if (job->ps[job->nprocs - 1].pid == pid)
4102 job = job->prev_job;
4105 job = getjob(*argv, 0);
4106 /* loop until process terminated or stopped */
4107 while (job->state == JOBRUNNING)
4108 blocking_wait_with_raise_on_sig(NULL);
4110 retval = getstatus(job);
4123 struct job *jp, *jq;
4125 len = njobs * sizeof(*jp);
4127 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4129 offset = (char *)jp - (char *)jq;
4131 /* Relocate pointers */
4134 jq = (struct job *)((char *)jq + l);
4138 #define joff(p) ((struct job *)((char *)(p) + l))
4139 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4140 if (joff(jp)->ps == &jq->ps0)
4141 jmove(joff(jp)->ps);
4142 if (joff(jp)->prev_job)
4143 jmove(joff(jp)->prev_job);
4153 jp = (struct job *)((char *)jp + len);
4157 } while (--jq >= jp);
4162 * Return a new job structure.
4163 * Called with interrupts off.
4166 makejob(/*union node *node,*/ int nprocs)
4171 for (i = njobs, jp = jobtab; ; jp++) {
4178 if (jp->state != JOBDONE || !jp->waited)
4187 memset(jp, 0, sizeof(*jp));
4189 /* jp->jobctl is a bitfield.
4190 * "jp->jobctl |= jobctl" likely to give awful code */
4194 jp->prev_job = curjob;
4199 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4201 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4208 * Return a string identifying a command (to be printed by the
4211 static char *cmdnextc;
4214 cmdputs(const char *s)
4216 static const char vstype[VSTYPE + 1][3] = {
4217 "", "}", "-", "+", "?", "=",
4218 "%", "%%", "#", "##"
4219 USE_ASH_BASH_COMPAT(, ":", "/", "//")
4222 const char *p, *str;
4223 char c, cc[2] = " ";
4228 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4230 while ((c = *p++) != 0) {
4238 if ((subtype & VSTYPE) == VSLENGTH)
4242 if (!(subtype & VSQUOTE) == !(quoted & 1))
4248 str = "\"}" + !(quoted & 1);
4255 case CTLBACKQ+CTLQUOTE:
4258 #if ENABLE_SH_MATH_SUPPORT
4273 if ((subtype & VSTYPE) != VSNORMAL)
4275 str = vstype[subtype & VSTYPE];
4276 if (subtype & VSNUL)
4285 /* These can only happen inside quotes */
4298 while ((c = *str++)) {
4303 USTPUTC('"', nextc);
4309 /* cmdtxt() and cmdlist() call each other */
4310 static void cmdtxt(union node *n);
4313 cmdlist(union node *np, int sep)
4315 for (; np; np = np->narg.next) {
4319 if (sep && np->narg.next)
4325 cmdtxt(union node *n)
4328 struct nodelist *lp;
4339 lp = n->npipe.cmdlist;
4357 cmdtxt(n->nbinary.ch1);
4373 cmdtxt(n->nif.test);
4376 if (n->nif.elsepart) {
4379 n = n->nif.elsepart;
4395 cmdtxt(n->nbinary.ch1);
4405 cmdputs(n->nfor.var);
4407 cmdlist(n->nfor.args, 1);
4412 cmdputs(n->narg.text);
4416 cmdlist(n->ncmd.args, 1);
4417 cmdlist(n->ncmd.redirect, 0);
4430 cmdputs(n->ncase.expr->narg.text);
4432 for (np = n->ncase.cases; np; np = np->nclist.next) {
4433 cmdtxt(np->nclist.pattern);
4435 cmdtxt(np->nclist.body);
4449 #if ENABLE_ASH_BASH_COMPAT
4464 cmdputs(utoa(n->nfile.fd));
4466 if (n->type == NTOFD || n->type == NFROMFD) {
4467 cmdputs(utoa(n->ndup.dupfd));
4476 commandtext(union node *n)
4480 STARTSTACKSTR(cmdnextc);
4482 name = stackblock();
4483 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4484 name, cmdnextc, cmdnextc));
4485 return ckstrdup(name);
4490 * Fork off a subshell. If we are doing job control, give the subshell its
4491 * own process group. Jp is a job structure that the job is to be added to.
4492 * N is the command that will be evaluated by the child. Both jp and n may
4493 * be NULL. The mode parameter can be one of the following:
4494 * FORK_FG - Fork off a foreground process.
4495 * FORK_BG - Fork off a background process.
4496 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4497 * process group even if job control is on.
4499 * When job control is turned off, background processes have their standard
4500 * input redirected to /dev/null (except for the second and later processes
4503 * Called with interrupts off.
4506 * Clear traps on a fork.
4513 for (tp = trap; tp < &trap[NSIG]; tp++) {
4514 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4519 setsignal(tp - trap);
4525 /* Lives far away from here, needed for forkchild */
4526 static void closescript(void);
4528 /* Called after fork(), in child */
4530 forkchild(struct job *jp, /*union node *n,*/ int mode)
4534 TRACE(("Child shell %d\n", getpid()));
4538 /* man bash: "Non-builtin commands run by bash have signal handlers
4539 * set to the values inherited by the shell from its parent".
4540 * Do we do it correctly? */
4545 /* do job control only in root shell */
4547 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4550 if (jp->nprocs == 0)
4553 pgrp = jp->ps[0].pid;
4554 /* this can fail because we are doing it in the parent also */
4556 if (mode == FORK_FG)
4557 xtcsetpgrp(ttyfd, pgrp);
4562 if (mode == FORK_BG) {
4563 /* man bash: "When job control is not in effect,
4564 * asynchronous commands ignore SIGINT and SIGQUIT" */
4567 if (jp->nprocs == 0) {
4569 if (open(bb_dev_null, O_RDONLY) != 0)
4570 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4574 if (iflag) { /* why if iflag only? */
4579 * "In all cases, bash ignores SIGQUIT. Non-builtin
4580 * commands run by bash have signal handlers
4581 * set to the values inherited by the shell
4583 * Take care of the second rule: */
4586 for (jp = curjob; jp; jp = jp->prev_job)
4591 /* Called after fork(), in parent */
4593 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4596 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4598 TRACE(("In parent shell: child = %d\n", pid));
4600 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4606 if (mode != FORK_NOJOB && jp->jobctl) {
4609 if (jp->nprocs == 0)
4612 pgrp = jp->ps[0].pid;
4613 /* This can fail because we are doing it in the child also */
4617 if (mode == FORK_BG) {
4618 backgndpid = pid; /* set $! */
4619 set_curjob(jp, CUR_RUNNING);
4622 struct procstat *ps = &jp->ps[jp->nprocs++];
4627 if (doing_jobctl && n)
4628 ps->cmd = commandtext(n);
4634 forkshell(struct job *jp, union node *n, int mode)
4638 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4641 TRACE(("Fork failed, errno=%d", errno));
4644 ash_msg_and_raise_error("can't fork");
4647 forkchild(jp, /*n,*/ mode);
4649 forkparent(jp, n, mode, pid);
4654 * Wait for job to finish.
4656 * Under job control we have the problem that while a child process
4657 * is running interrupts generated by the user are sent to the child
4658 * but not to the shell. This means that an infinite loop started by
4659 * an interactive user may be hard to kill. With job control turned off,
4660 * an interactive user may place an interactive program inside a loop.
4661 * If the interactive program catches interrupts, the user doesn't want
4662 * these interrupts to also abort the loop. The approach we take here
4663 * is to have the shell ignore interrupt signals while waiting for a
4664 * foreground process to terminate, and then send itself an interrupt
4665 * signal if the child process was terminated by an interrupt signal.
4666 * Unfortunately, some programs want to do a bit of cleanup and then
4667 * exit on interrupt; unless these processes terminate themselves by
4668 * sending a signal to themselves (instead of calling exit) they will
4669 * confuse this approach.
4671 * Called with interrupts off.
4674 waitforjob(struct job *jp)
4678 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4681 while (jp->state == JOBRUNNING) {
4682 /* In non-interactive shells, we _can_ get
4683 * a keyboard signal here and be EINTRed,
4684 * but we just loop back, waiting for command to complete.
4687 * "If bash is waiting for a command to complete and receives
4688 * a signal for which a trap has been set, the trap
4689 * will not be executed until the command completes."
4691 * Reality is that even if trap is not set, bash
4692 * will not act on the signal until command completes.
4693 * Try this. sleep5intoff.c:
4694 * #include <signal.h>
4695 * #include <unistd.h>
4698 * sigemptyset(&set);
4699 * sigaddset(&set, SIGINT);
4700 * sigaddset(&set, SIGQUIT);
4701 * sigprocmask(SIG_BLOCK, &set, NULL);
4705 * $ bash -c './sleep5intoff; echo hi'
4706 * ^C^C^C^C <--- pressing ^C once a second
4708 * $ bash -c './sleep5intoff; echo hi'
4709 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4712 dowait(DOWAIT_BLOCK, jp);
4719 xtcsetpgrp(ttyfd, rootpid);
4721 * This is truly gross.
4722 * If we're doing job control, then we did a TIOCSPGRP which
4723 * caused us (the shell) to no longer be in the controlling
4724 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4725 * intuit from the subprocess exit status whether a SIGINT
4726 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4728 if (jp->sigint) /* TODO: do the same with all signals */
4729 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4731 if (jp->state == JOBDONE)
4738 * return 1 if there are stopped jobs, otherwise 0
4750 if (jp && jp->state == JOBSTOPPED) {
4751 out2str("You have stopped jobs.\n");
4760 /* ============ redir.c
4762 * Code for dealing with input/output redirection.
4765 #define EMPTY -2 /* marks an unused slot in redirtab */
4766 #define CLOSED -3 /* marks a slot of previously-closed fd */
4769 * Open a file in noclobber mode.
4770 * The code was copied from bash.
4773 noclobberopen(const char *fname)
4776 struct stat finfo, finfo2;
4779 * If the file exists and is a regular file, return an error
4782 r = stat(fname, &finfo);
4783 if (r == 0 && S_ISREG(finfo.st_mode)) {
4789 * If the file was not present (r != 0), make sure we open it
4790 * exclusively so that if it is created before we open it, our open
4791 * will fail. Make sure that we do not truncate an existing file.
4792 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4793 * file was not a regular file, we leave O_EXCL off.
4796 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4797 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4799 /* If the open failed, return the file descriptor right away. */
4804 * OK, the open succeeded, but the file may have been changed from a
4805 * non-regular file to a regular file between the stat and the open.
4806 * We are assuming that the O_EXCL open handles the case where FILENAME
4807 * did not exist and is symlinked to an existing file between the stat
4812 * If we can open it and fstat the file descriptor, and neither check
4813 * revealed that it was a regular file, and the file has not been
4814 * replaced, return the file descriptor.
4816 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4817 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4820 /* The file has been replaced. badness. */
4827 * Handle here documents. Normally we fork off a process to write the
4828 * data to a pipe. If the document is short, we can stuff the data in
4829 * the pipe without forking.
4831 /* openhere needs this forward reference */
4832 static void expandhere(union node *arg, int fd);
4834 openhere(union node *redir)
4840 ash_msg_and_raise_error("pipe call failed");
4841 if (redir->type == NHERE) {
4842 len = strlen(redir->nhere.doc->narg.text);
4843 if (len <= PIPE_BUF) {
4844 full_write(pip[1], redir->nhere.doc->narg.text, len);
4848 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4851 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4852 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4853 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4854 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4855 signal(SIGPIPE, SIG_DFL);
4856 if (redir->type == NHERE)
4857 full_write(pip[1], redir->nhere.doc->narg.text, len);
4859 expandhere(redir->nhere.doc, pip[1]);
4860 _exit(EXIT_SUCCESS);
4868 openredirect(union node *redir)
4873 switch (redir->nfile.type) {
4875 fname = redir->nfile.expfname;
4876 f = open(fname, O_RDONLY);
4881 fname = redir->nfile.expfname;
4882 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4887 #if ENABLE_ASH_BASH_COMPAT
4890 /* Take care of noclobber mode. */
4892 fname = redir->nfile.expfname;
4893 f = noclobberopen(fname);
4900 fname = redir->nfile.expfname;
4901 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4906 fname = redir->nfile.expfname;
4907 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4915 /* Fall through to eliminate warning. */
4916 /* Our single caller does this itself */
4923 f = openhere(redir);
4929 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4931 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
4935 * Copy a file descriptor to be >= to. Returns -1
4936 * if the source file descriptor is closed, EMPTY if there are no unused
4937 * file descriptors left.
4939 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
4940 * old code was doing close(to) prior to copyfd() to achieve the same */
4942 COPYFD_EXACT = (int)~(INT_MAX),
4943 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
4946 copyfd(int from, int to)
4950 if (to & COPYFD_EXACT) {
4951 to &= ~COPYFD_EXACT;
4953 newfd = dup2(from, to);
4955 newfd = fcntl(from, F_DUPFD, to);
4958 if (errno == EMFILE)
4960 /* Happens when source fd is not open: try "echo >&99" */
4961 ash_msg_and_raise_error("%d: %m", from);
4966 /* Struct def and variable are moved down to the first usage site */
4971 struct redirtab *next;
4974 struct two_fd_t two_fd[0];
4976 #define redirlist (G_var.redirlist)
4978 static int need_to_remember(struct redirtab *rp, int fd)
4982 if (!rp) /* remembering was not requested */
4985 for (i = 0; i < rp->pair_count; i++) {
4986 if (rp->two_fd[i].orig == fd) {
4987 /* already remembered */
4994 /* "hidden" fd is a fd used to read scripts, or a copy of such */
4995 static int is_hidden_fd(struct redirtab *rp, int fd)
4998 struct parsefile *pf;
5011 fd |= COPYFD_RESTORE;
5012 for (i = 0; i < rp->pair_count; i++) {
5013 if (rp->two_fd[i].copy == fd) {
5021 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5022 * old file descriptors are stashed away so that the redirection can be
5023 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5024 * standard output, and the standard error if it becomes a duplicate of
5025 * stdout, is saved in memory.
5027 /* flags passed to redirect */
5028 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5029 #define REDIR_SAVEFD2 03 /* set preverrout */
5031 redirect(union node *redir, int flags)
5033 struct redirtab *sv;
5038 int copied_fd2 = -1;
5048 if (flags & REDIR_PUSH) {
5049 union node *tmp = redir;
5052 #if ENABLE_ASH_BASH_COMPAT
5053 if (redir->nfile.type == NTO2)
5056 tmp = tmp->nfile.next;
5058 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5059 sv->next = redirlist;
5060 sv->pair_count = sv_pos;
5062 sv->nullredirs = g_nullredirs - 1;
5064 while (sv_pos > 0) {
5066 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5071 fd = redir->nfile.fd;
5072 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5073 int right_fd = redir->ndup.dupfd;
5074 /* redirect from/to same file descriptor? */
5077 /* echo >&10 and 10 is a fd opened to the sh script? */
5078 if (is_hidden_fd(sv, right_fd)) {
5079 errno = EBADF; /* as if it is closed */
5080 ash_msg_and_raise_error("%d: %m", right_fd);
5084 newfd = openredirect(redir); /* always >= 0 */
5086 /* Descriptor wasn't open before redirect.
5087 * Mark it for close in the future */
5088 if (need_to_remember(sv, fd)) {
5089 goto remember_to_close;
5094 #if ENABLE_ASH_BASH_COMPAT
5097 if (need_to_remember(sv, fd)) {
5098 /* Copy old descriptor */
5099 i = fcntl(fd, F_DUPFD, 10);
5100 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5101 * are closed in popredir() in the child, preventing them from leaking
5102 * into child. (popredir() also cleans up the mess in case of failures)
5107 /* Strange error (e.g. "too many files" EMFILE?) */
5111 ash_msg_and_raise_error("%d: %m", fd);
5114 /* EBADF: it is not open - good, remember to close it */
5117 } else { /* fd is open, save its copy */
5118 /* "exec fd>&-" should not close fds
5119 * which point to script file(s).
5120 * Force them to be restored afterwards */
5121 if (is_hidden_fd(sv, fd))
5122 i |= COPYFD_RESTORE;
5126 sv->two_fd[sv_pos].orig = fd;
5127 sv->two_fd[sv_pos].copy = i;
5131 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5132 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5133 /* Don't want to trigger debugging */
5137 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5139 } else if (fd != newfd) { /* move newfd to fd */
5140 copyfd(newfd, fd | COPYFD_EXACT);
5141 #if ENABLE_ASH_BASH_COMPAT
5142 if (!(redir->nfile.type == NTO2 && fd == 2))
5146 #if ENABLE_ASH_BASH_COMPAT
5147 if (redir->nfile.type == NTO2 && fd == 1) {
5148 /* We already redirected it to fd 1, now copy it to 2 */
5154 } while ((redir = redir->nfile.next) != NULL);
5157 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5158 preverrout_fd = copied_fd2;
5162 * Undo the effects of the last redirection.
5165 popredir(int drop, int restore)
5167 struct redirtab *rp;
5170 if (--g_nullredirs >= 0)
5174 for (i = 0; i < rp->pair_count; i++) {
5175 int fd = rp->two_fd[i].orig;
5176 int copy = rp->two_fd[i].copy;
5177 if (copy == CLOSED) {
5182 if (copy != EMPTY) {
5183 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5184 copy &= ~COPYFD_RESTORE;
5186 copyfd(copy, fd | COPYFD_EXACT);
5188 close(copy & ~COPYFD_RESTORE);
5191 redirlist = rp->next;
5192 g_nullredirs = rp->nullredirs;
5198 * Undo all redirections. Called on error or interrupt.
5202 * Discard all saved file descriptors.
5205 clearredir(int drop)
5211 popredir(drop, /*restore:*/ 0);
5216 redirectsafe(union node *redir, int flags)
5219 volatile int saveint;
5220 struct jmploc *volatile savehandler = exception_handler;
5221 struct jmploc jmploc;
5224 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5225 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5227 exception_handler = &jmploc;
5228 redirect(redir, flags);
5230 exception_handler = savehandler;
5231 if (err && exception_type != EXERROR)
5232 longjmp(exception_handler->loc, 1);
5233 RESTORE_INT(saveint);
5238 /* ============ Routines to expand arguments to commands
5240 * We have to deal with backquotes, shell variables, and file metacharacters.
5243 #if ENABLE_SH_MATH_SUPPORT
5244 static arith_t dash_arith(const char *);
5250 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5251 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5252 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5253 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5254 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5255 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5256 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5257 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5258 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5262 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5263 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5264 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5265 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5266 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5269 * Structure specifying which parts of the string should be searched
5270 * for IFS characters.
5273 struct ifsregion *next; /* next region in list */
5274 int begoff; /* offset of start of region */
5275 int endoff; /* offset of end of region */
5276 int nulonly; /* search for nul bytes only */
5280 struct strlist *list;
5281 struct strlist **lastp;
5284 /* output of current string */
5285 static char *expdest;
5286 /* list of back quote expressions */
5287 static struct nodelist *argbackq;
5288 /* first struct in list of ifs regions */
5289 static struct ifsregion ifsfirst;
5290 /* last struct in list */
5291 static struct ifsregion *ifslastp;
5292 /* holds expanded arg list */
5293 static struct arglist exparg;
5303 expdest = makestrspace(32, expdest);
5304 len = fmtstr(expdest, 32, arith_t_fmt, num);
5305 STADJUST(len, expdest);
5310 esclen(const char *start, const char *p)
5314 while (p > start && *--p == CTLESC) {
5321 * Remove any CTLESC characters from a string.
5324 _rmescapes(char *str, int flag)
5326 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5333 p = strpbrk(str, qchars);
5339 if (flag & RMESCAPE_ALLOC) {
5340 size_t len = p - str;
5341 size_t fulllen = len + strlen(p) + 1;
5343 if (flag & RMESCAPE_GROW) {
5344 r = makestrspace(fulllen, expdest);
5345 } else if (flag & RMESCAPE_HEAP) {
5346 r = ckmalloc(fulllen);
5348 r = stalloc(fulllen);
5352 q = (char *)memcpy(q, str, len) + len;
5355 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5356 globbing = flag & RMESCAPE_GLOB;
5357 notescaped = globbing;
5359 if (*p == CTLQUOTEMARK) {
5360 inquotes = ~inquotes;
5362 notescaped = globbing;
5366 /* naked back slash */
5372 if (notescaped && inquotes && *p != '/') {
5376 notescaped = globbing;
5381 if (flag & RMESCAPE_GROW) {
5383 STADJUST(q - r + 1, expdest);
5387 #define rmescapes(p) _rmescapes((p), 0)
5389 #define pmatch(a, b) !fnmatch((a), (b), 0)
5392 * Prepare a pattern for a expmeta (internal glob(3)) call.
5394 * Returns an stalloced string.
5397 preglob(const char *pattern, int quoted, int flag)
5399 flag |= RMESCAPE_GLOB;
5401 flag |= RMESCAPE_QUOTED;
5403 return _rmescapes((char *)pattern, flag);
5407 * Put a string on the stack.
5410 memtodest(const char *p, size_t len, int syntax, int quotes)
5414 q = makestrspace(len * 2, q);
5417 int c = signed_char2int(*p++);
5420 if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
5429 strtodest(const char *p, int syntax, int quotes)
5431 memtodest(p, strlen(p), syntax, quotes);
5435 * Record the fact that we have to scan this region of the
5436 * string for IFS characters.
5439 recordregion(int start, int end, int nulonly)
5441 struct ifsregion *ifsp;
5443 if (ifslastp == NULL) {
5447 ifsp = ckzalloc(sizeof(*ifsp));
5448 /*ifsp->next = NULL; - ckzalloc did it */
5449 ifslastp->next = ifsp;
5453 ifslastp->begoff = start;
5454 ifslastp->endoff = end;
5455 ifslastp->nulonly = nulonly;
5459 removerecordregions(int endoff)
5461 if (ifslastp == NULL)
5464 if (ifsfirst.endoff > endoff) {
5465 while (ifsfirst.next != NULL) {
5466 struct ifsregion *ifsp;
5468 ifsp = ifsfirst.next->next;
5469 free(ifsfirst.next);
5470 ifsfirst.next = ifsp;
5473 if (ifsfirst.begoff > endoff)
5476 ifslastp = &ifsfirst;
5477 ifsfirst.endoff = endoff;
5482 ifslastp = &ifsfirst;
5483 while (ifslastp->next && ifslastp->next->begoff < endoff)
5484 ifslastp=ifslastp->next;
5485 while (ifslastp->next != NULL) {
5486 struct ifsregion *ifsp;
5488 ifsp = ifslastp->next->next;
5489 free(ifslastp->next);
5490 ifslastp->next = ifsp;
5493 if (ifslastp->endoff > endoff)
5494 ifslastp->endoff = endoff;
5498 exptilde(char *startp, char *p, int flag)
5504 int quotes = flag & (EXP_FULL | EXP_CASE);
5509 while ((c = *++p) != '\0') {
5516 if (flag & EXP_VARTILDE)
5526 if (*name == '\0') {
5527 home = lookupvar(homestr);
5529 pw = getpwnam(name);
5534 if (!home || !*home)
5537 startloc = expdest - (char *)stackblock();
5538 strtodest(home, SQSYNTAX, quotes);
5539 recordregion(startloc, expdest - (char *)stackblock(), 0);
5547 * Execute a command inside back quotes. If it's a builtin command, we
5548 * want to save its output in a block obtained from malloc. Otherwise
5549 * we fork off a subprocess and get the output of the command via a pipe.
5550 * Should be called with interrupts off.
5552 struct backcmd { /* result of evalbackcmd */
5553 int fd; /* file descriptor to read from */
5554 int nleft; /* number of chars in buffer */
5555 char *buf; /* buffer */
5556 struct job *jp; /* job structure for command */
5559 /* These forward decls are needed to use "eval" code for backticks handling: */
5560 static uint8_t back_exitstatus; /* exit status of backquoted command */
5561 #define EV_EXIT 01 /* exit after evaluating tree */
5562 static void evaltree(union node *, int);
5565 evalbackcmd(union node *n, struct backcmd *result)
5576 saveherefd = herefd;
5584 ash_msg_and_raise_error("pipe call failed");
5585 jp = makejob(/*n,*/ 1);
5586 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5591 copyfd(pip[1], 1 | COPYFD_EXACT);
5595 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5599 result->fd = pip[0];
5602 herefd = saveherefd;
5604 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5605 result->fd, result->buf, result->nleft, result->jp));
5609 * Expand stuff in backwards quotes.
5612 expbackq(union node *cmd, int quoted, int quotes)
5620 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5621 struct stackmark smark;
5624 setstackmark(&smark);
5626 startloc = dest - (char *)stackblock();
5628 evalbackcmd(cmd, &in);
5629 popstackmark(&smark);
5636 memtodest(p, i, syntax, quotes);
5640 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5641 TRACE(("expbackq: read returns %d\n", i));
5650 back_exitstatus = waitforjob(in.jp);
5654 /* Eat all trailing newlines */
5656 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5661 recordregion(startloc, dest - (char *)stackblock(), 0);
5662 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5663 (dest - (char *)stackblock()) - startloc,
5664 (dest - (char *)stackblock()) - startloc,
5665 stackblock() + startloc));
5668 #if ENABLE_SH_MATH_SUPPORT
5670 * Expand arithmetic expression. Backup to start of expression,
5671 * evaluate, place result in (backed up) result, adjust string position.
5684 * This routine is slightly over-complicated for
5685 * efficiency. Next we scan backwards looking for the
5686 * start of arithmetic.
5688 start = stackblock();
5695 while (*p != CTLARI) {
5699 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5704 esc = esclen(start, p);
5714 removerecordregions(begoff);
5723 len = cvtnum(dash_arith(p + 2));
5726 recordregion(begoff, begoff + len, 0);
5730 /* argstr needs it */
5731 static char *evalvar(char *p, int flag, struct strlist *var_str_list);
5734 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5735 * characters to allow for further processing. Otherwise treat
5736 * $@ like $* since no splitting will be performed.
5738 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5739 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5740 * for correct expansion of "B=$A" word.
5743 argstr(char *p, int flag, struct strlist *var_str_list)
5745 static const char spclchars[] ALIGN1 = {
5753 CTLBACKQ | CTLQUOTE,
5754 #if ENABLE_SH_MATH_SUPPORT
5759 const char *reject = spclchars;
5761 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
5762 int breakall = flag & EXP_WORD;
5767 if (!(flag & EXP_VARTILDE)) {
5769 } else if (flag & EXP_VARTILDE2) {
5774 if (flag & EXP_TILDE) {
5780 if (*q == CTLESC && (flag & EXP_QWORD))
5783 p = exptilde(p, q, flag);
5786 startloc = expdest - (char *)stackblock();
5788 length += strcspn(p + length, reject);
5790 if (c && (!(c & 0x80)
5791 #if ENABLE_SH_MATH_SUPPORT
5795 /* c == '=' || c == ':' || c == CTLENDARI */
5800 expdest = stack_nputstr(p, length, expdest);
5801 newloc = expdest - (char *)stackblock();
5802 if (breakall && !inquotes && newloc > startloc) {
5803 recordregion(startloc, newloc, 0);
5814 if (flag & EXP_VARTILDE2) {
5818 flag |= EXP_VARTILDE2;
5823 * sort of a hack - expand tildes in variable
5824 * assignments (after the first '=' and after ':'s).
5833 case CTLENDVAR: /* ??? */
5836 /* "$@" syntax adherence hack */
5839 !memcmp(p, dolatstr, 4) &&
5840 (p[4] == CTLQUOTEMARK || (
5841 p[4] == CTLENDVAR &&
5842 p[5] == CTLQUOTEMARK
5845 p = evalvar(p + 1, flag, /* var_str_list: */ NULL) + 1;
5848 inquotes = !inquotes;
5861 p = evalvar(p, flag, var_str_list);
5865 case CTLBACKQ|CTLQUOTE:
5866 expbackq(argbackq->n, c, quotes);
5867 argbackq = argbackq->next;
5869 #if ENABLE_SH_MATH_SUPPORT
5882 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
5885 // This commented out code was added by James Simmons <jsimmons@infradead.org>
5886 // as part of a larger change when he added support for ${var/a/b}.
5887 // However, it broke # and % operators:
5891 //echo ${var#ab} abcdcd abcdcd
5892 //echo ${var##ab} abcdcd abcdcd
5893 //echo ${var#a*b} abcdcd ababcdcd (!)
5894 //echo ${var##a*b} cdcd cdcd
5895 //echo ${var#?} babcdcd ababcdcd (!)
5896 //echo ${var##?} babcdcd babcdcd
5897 //echo ${var#*} ababcdcd babcdcd (!)
5899 //echo ${var%cd} ababcd ababcd
5900 //echo ${var%%cd} ababcd abab (!)
5901 //echo ${var%c*d} ababcd ababcd
5902 //echo ${var%%c*d} abab ababcdcd (!)
5903 //echo ${var%?} ababcdc ababcdc
5904 //echo ${var%%?} ababcdc ababcdcd (!)
5905 //echo ${var%*} ababcdcd ababcdcd
5908 // Commenting it back out helped. Remove it completely if it really
5911 char *loc, *loc2; //, *full;
5917 int match; // = strlen(str);
5918 const char *s = loc2;
5925 match = pmatch(str, s); // this line was deleted
5927 // // chop off end if its '*'
5928 // full = strrchr(str, '*');
5929 // if (full && full != str)
5932 // // If str starts with '*' replace with s.
5933 // if ((*str == '*') && strlen(s) >= match) {
5934 // full = xstrdup(s);
5935 // strncpy(full+strlen(s)-match+1, str+1, match-1);
5937 // full = xstrndup(str, match);
5938 // match = strncmp(s, full, strlen(full));
5942 if (match) // if (!match)
5944 if (quotes && *loc == CTLESC)
5953 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5960 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
5963 const char *s = loc2;
5968 match = pmatch(str, s);
5975 esc = esclen(startp, loc);
5986 static void varunset(const char *, const char *, const char *, int) NORETURN;
5988 varunset(const char *end, const char *var, const char *umsg, int varflags)
5994 msg = "parameter not set";
5996 if (*end == CTLENDVAR) {
5997 if (varflags & VSNUL)
6003 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6006 #if ENABLE_ASH_BASH_COMPAT
6008 parse_sub_pattern(char *arg, int inquotes)
6010 char *idx, *repl = NULL;
6019 /* Only the first '/' seen is our separator */
6026 if (!inquotes && c == '\\' && arg[1] == '\\')
6027 arg++; /* skip both \\, not just first one */
6034 #endif /* ENABLE_ASH_BASH_COMPAT */
6037 subevalvar(char *p, char *str, int strloc, int subtype,
6038 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6040 struct nodelist *saveargbackq = argbackq;
6043 char *rmesc, *rmescend;
6044 USE_ASH_BASH_COMPAT(char *repl = NULL;)
6045 USE_ASH_BASH_COMPAT(char null = '\0';)
6046 USE_ASH_BASH_COMPAT(int pos, len, orig_len;)
6047 int saveherefd = herefd;
6048 int amount, workloc, resetloc;
6050 char *(*scan)(char*, char*, char*, char*, int, int);
6053 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6055 STPUTC('\0', expdest);
6056 herefd = saveherefd;
6057 argbackq = saveargbackq;
6058 startp = (char *)stackblock() + startloc;
6062 setvar(str, startp, 0);
6063 amount = startp - expdest;
6064 STADJUST(amount, expdest);
6067 #if ENABLE_ASH_BASH_COMPAT
6069 loc = str = stackblock() + strloc;
6070 // TODO: number() instead? It does error checking...
6072 len = str - startp - 1;
6074 /* *loc != '\0', guaranteed by parser */
6078 /* We must adjust the length by the number of escapes we find. */
6079 for (ptr = startp; ptr < (str - 1); ptr++) {
6080 if (*ptr == CTLESC) {
6088 if (*loc++ == ':') {
6089 // TODO: number() instead? It does error checking...
6093 while (*loc && *loc != ':')
6096 // TODO: number() instead? It does error checking...
6099 if (pos >= orig_len) {
6103 if (len > (orig_len - pos))
6104 len = orig_len - pos;
6106 for (str = startp; pos; str++, pos--) {
6107 if (quotes && *str == CTLESC)
6110 for (loc = startp; len; len--) {
6111 if (quotes && *str == CTLESC)
6116 amount = loc - expdest;
6117 STADJUST(amount, expdest);
6122 varunset(p, str, startp, varflags);
6125 resetloc = expdest - (char *)stackblock();
6127 /* We'll comeback here if we grow the stack while handling
6128 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6129 * stack will need rebasing, and we'll need to remove our work
6132 USE_ASH_BASH_COMPAT(restart:)
6134 amount = expdest - ((char *)stackblock() + resetloc);
6135 STADJUST(-amount, expdest);
6136 startp = (char *)stackblock() + startloc;
6139 rmescend = (char *)stackblock() + strloc;
6141 rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6142 if (rmesc != startp) {
6144 startp = (char *)stackblock() + startloc;
6148 str = (char *)stackblock() + strloc;
6149 preglob(str, varflags & VSQUOTE, 0);
6150 workloc = expdest - (char *)stackblock();
6152 #if ENABLE_ASH_BASH_COMPAT
6153 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6154 char *idx, *end, *restart_detect;
6157 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6162 /* If there's no pattern to match, return the expansion unmolested */
6170 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6172 /* No match, advance */
6173 restart_detect = stackblock();
6174 STPUTC(*idx, expdest);
6175 if (quotes && *idx == CTLESC) {
6178 STPUTC(*idx, expdest);
6180 if (stackblock() != restart_detect)
6188 if (subtype == VSREPLACEALL) {
6190 if (quotes && *idx == CTLESC)
6199 for (loc = repl; *loc; loc++) {
6200 restart_detect = stackblock();
6201 STPUTC(*loc, expdest);
6202 if (stackblock() != restart_detect)
6207 if (subtype == VSREPLACE) {
6209 restart_detect = stackblock();
6210 STPUTC(*idx, expdest);
6211 if (stackblock() != restart_detect)
6220 /* We've put the replaced text into a buffer at workloc, now
6221 * move it to the right place and adjust the stack.
6223 startp = stackblock() + startloc;
6224 STPUTC('\0', expdest);
6225 memmove(startp, stackblock() + workloc, len);
6226 startp[len++] = '\0';
6227 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6228 STADJUST(-amount, expdest);
6231 #endif /* ENABLE_ASH_BASH_COMPAT */
6233 subtype -= VSTRIMRIGHT;
6235 if (subtype < 0 || subtype > 7)
6238 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6239 zero = subtype >> 1;
6240 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6241 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6243 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6246 memmove(startp, loc, str - loc);
6247 loc = startp + (str - loc) - 1;
6250 amount = loc - expdest;
6251 STADJUST(amount, expdest);
6257 * Add the value of a specialized variable to the stack string.
6260 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6270 int quoted = varflags & VSQUOTE;
6271 int subtype = varflags & VSTYPE;
6272 int quotes = flags & (EXP_FULL | EXP_CASE);
6274 if (quoted && (flags & EXP_FULL))
6275 sep = 1 << CHAR_BIT;
6277 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6286 num = shellparam.nparam;
6296 expdest = makestrspace(NOPTS, expdest);
6297 for (i = NOPTS - 1; i >= 0; i--) {
6299 USTPUTC(optletters(i), expdest);
6309 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
6310 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6316 while ((p = *ap++)) {
6319 partlen = strlen(p);
6322 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6323 memtodest(p, partlen, syntax, quotes);
6329 if (subtype == VSPLUS || subtype == VSLENGTH) {
6350 // TODO: number() instead? It does error checking...
6352 if (num < 0 || num > shellparam.nparam)
6354 p = num ? shellparam.p[num - 1] : arg0;
6357 /* NB: name has form "VAR=..." */
6359 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6360 * which should be considered before we check variables. */
6362 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6366 str = var_str_list->text;
6367 eq = strchr(str, '=');
6368 if (!eq) /* stop at first non-assignment */
6371 if (name_len == (unsigned)(eq - str)
6372 && strncmp(str, name, name_len) == 0) {
6374 /* goto value; - WRONG! */
6375 /* think "A=1 A=2 B=$A" */
6377 var_str_list = var_str_list->next;
6378 } while (var_str_list);
6382 p = lookupvar(name);
6388 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6389 memtodest(p, len, syntax, quotes);
6393 if (subtype == VSPLUS || subtype == VSLENGTH)
6394 STADJUST(-len, expdest);
6399 * Expand a variable, and return a pointer to the next character in the
6403 evalvar(char *p, int flag, struct strlist *var_str_list)
6415 subtype = varflags & VSTYPE;
6416 quoted = varflags & VSQUOTE;
6418 easy = (!quoted || (*var == '@' && shellparam.nparam));
6419 startloc = expdest - (char *)stackblock();
6420 p = strchr(p, '=') + 1;
6423 varlen = varvalue(var, varflags, flag, var_str_list);
6424 if (varflags & VSNUL)
6427 if (subtype == VSPLUS) {
6428 varlen = -1 - varlen;
6432 if (subtype == VSMINUS) {
6436 p, flag | EXP_TILDE |
6437 (quoted ? EXP_QWORD : EXP_WORD),
6447 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6449 if (subevalvar(p, var, /* strloc: */ 0,
6450 subtype, startloc, varflags,
6456 * Remove any recorded regions beyond
6459 removerecordregions(startloc);
6469 if (varlen < 0 && uflag)
6470 varunset(p, var, 0, 0);
6472 if (subtype == VSLENGTH) {
6473 cvtnum(varlen > 0 ? varlen : 0);
6477 if (subtype == VSNORMAL) {
6488 case VSTRIMRIGHTMAX:
6489 #if ENABLE_ASH_BASH_COMPAT
6502 * Terminate the string and start recording the pattern
6505 STPUTC('\0', expdest);
6506 patloc = expdest - (char *)stackblock();
6507 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6509 /* quotes: */ flag & (EXP_FULL | EXP_CASE),
6512 int amount = expdest - (
6513 (char *)stackblock() + patloc - 1
6515 STADJUST(-amount, expdest);
6517 /* Remove any recorded regions beyond start of variable */
6518 removerecordregions(startloc);
6520 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6524 if (subtype != VSNORMAL) { /* skip to end of alternative */
6530 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6532 argbackq = argbackq->next;
6533 } else if (c == CTLVAR) {
6534 if ((*p++ & VSTYPE) != VSNORMAL)
6536 } else if (c == CTLENDVAR) {
6546 * Break the argument string into pieces based upon IFS and add the
6547 * strings to the argument list. The regions of the string to be
6548 * searched for IFS characters have been stored by recordregion.
6551 ifsbreakup(char *string, struct arglist *arglist)
6553 struct ifsregion *ifsp;
6558 const char *ifs, *realifs;
6563 if (ifslastp != NULL) {
6566 realifs = ifsset() ? ifsval() : defifs;
6569 p = string + ifsp->begoff;
6570 nulonly = ifsp->nulonly;
6571 ifs = nulonly ? nullstr : realifs;
6573 while (p < string + ifsp->endoff) {
6577 if (!strchr(ifs, *p)) {
6582 ifsspc = (strchr(defifs, *p) != NULL);
6583 /* Ignore IFS whitespace at start */
6584 if (q == start && ifsspc) {
6590 sp = stzalloc(sizeof(*sp));
6592 *arglist->lastp = sp;
6593 arglist->lastp = &sp->next;
6597 if (p >= string + ifsp->endoff) {
6603 if (strchr(ifs, *p) == NULL) {
6607 if (strchr(defifs, *p) == NULL) {
6622 } while (ifsp != NULL);
6631 sp = stzalloc(sizeof(*sp));
6633 *arglist->lastp = sp;
6634 arglist->lastp = &sp->next;
6640 struct ifsregion *p;
6645 struct ifsregion *ifsp;
6651 ifsfirst.next = NULL;
6656 * Add a file name to the list.
6659 addfname(const char *name)
6663 sp = stzalloc(sizeof(*sp));
6664 sp->text = ststrdup(name);
6666 exparg.lastp = &sp->next;
6669 static char *expdir;
6672 * Do metacharacter (i.e. *, ?, [...]) expansion.
6675 expmeta(char *enddir, char *name)
6690 for (p = name; *p; p++) {
6691 if (*p == '*' || *p == '?')
6693 else if (*p == '[') {
6700 if (*q == '/' || *q == '\0')
6707 } else if (*p == '\\')
6709 else if (*p == '/') {
6716 if (metaflag == 0) { /* we've reached the end of the file name */
6717 if (enddir != expdir)
6725 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6736 } while (p < start);
6738 if (enddir == expdir) {
6740 } else if (enddir == expdir + 1 && *expdir == '/') {
6749 if (enddir != expdir)
6751 if (*endname == 0) {
6763 while (!intpending && (dp = readdir(dirp)) != NULL) {
6764 if (dp->d_name[0] == '.' && !matchdot)
6766 if (pmatch(start, dp->d_name)) {
6768 strcpy(enddir, dp->d_name);
6771 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6774 expmeta(p, endname);
6783 static struct strlist *
6784 msort(struct strlist *list, int len)
6786 struct strlist *p, *q = NULL;
6787 struct strlist **lpp;
6795 for (n = half; --n >= 0;) {
6799 q->next = NULL; /* terminate first half of list */
6800 q = msort(list, half); /* sort first half of list */
6801 p = msort(p, len - half); /* sort second half */
6804 #if ENABLE_LOCALE_SUPPORT
6805 if (strcoll(p->text, q->text) < 0)
6807 if (strcmp(p->text, q->text) < 0)
6831 * Sort the results of file name expansion. It calculates the number of
6832 * strings to sort and then calls msort (short for merge sort) to do the
6835 static struct strlist *
6836 expsort(struct strlist *str)
6842 for (sp = str; sp; sp = sp->next)
6844 return msort(str, len);
6848 expandmeta(struct strlist *str /*, int flag*/)
6850 static const char metachars[] ALIGN1 = {
6853 /* TODO - EXP_REDIR */
6856 struct strlist **savelastp;
6862 if (!strpbrk(str->text, metachars))
6864 savelastp = exparg.lastp;
6867 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6869 int i = strlen(str->text);
6870 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6878 if (exparg.lastp == savelastp) {
6883 *exparg.lastp = str;
6884 rmescapes(str->text);
6885 exparg.lastp = &str->next;
6887 *exparg.lastp = NULL;
6888 *savelastp = sp = expsort(*savelastp);
6889 while (sp->next != NULL)
6891 exparg.lastp = &sp->next;
6898 * Perform variable substitution and command substitution on an argument,
6899 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
6900 * perform splitting and file name expansion. When arglist is NULL, perform
6901 * here document expansion.
6904 expandarg(union node *arg, struct arglist *arglist, int flag)
6909 argbackq = arg->narg.backquote;
6910 STARTSTACKSTR(expdest);
6911 ifsfirst.next = NULL;
6913 argstr(arg->narg.text, flag,
6914 /* var_str_list: */ arglist ? arglist->list : NULL);
6915 p = _STPUTC('\0', expdest);
6917 if (arglist == NULL) {
6918 return; /* here document expanded */
6920 p = grabstackstr(p);
6921 exparg.lastp = &exparg.list;
6925 if (flag & EXP_FULL) {
6926 ifsbreakup(p, &exparg);
6927 *exparg.lastp = NULL;
6928 exparg.lastp = &exparg.list;
6929 expandmeta(exparg.list /*, flag*/);
6931 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
6933 sp = stzalloc(sizeof(*sp));
6936 exparg.lastp = &sp->next;
6940 *exparg.lastp = NULL;
6942 *arglist->lastp = exparg.list;
6943 arglist->lastp = exparg.lastp;
6948 * Expand shell variables and backquotes inside a here document.
6951 expandhere(union node *arg, int fd)
6954 expandarg(arg, (struct arglist *)NULL, 0);
6955 full_write(fd, stackblock(), expdest - (char *)stackblock());
6959 * Returns true if the pattern matches the string.
6962 patmatch(char *pattern, const char *string)
6964 return pmatch(preglob(pattern, 0, 0), string);
6968 * See if a pattern matches in a case statement.
6971 casematch(union node *pattern, char *val)
6973 struct stackmark smark;
6976 setstackmark(&smark);
6977 argbackq = pattern->narg.backquote;
6978 STARTSTACKSTR(expdest);
6980 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
6981 /* var_str_list: */ NULL);
6982 STACKSTRNUL(expdest);
6983 result = patmatch(stackblock(), val);
6984 popstackmark(&smark);
6989 /* ============ find_command */
6993 int (*builtin)(int, char **);
6994 /* unsigned flags; */
6996 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
6997 /* "regular" builtins always take precedence over commands,
6998 * regardless of PATH=....%builtin... position */
6999 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7000 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7003 smallint cmdtype; /* CMDxxx */
7006 /* index >= 0 for commands without path (slashes) */
7007 /* (TODO: what exactly does the value mean? PATH position?) */
7008 /* index == -1 for commands with slashes */
7009 /* index == (-2 - applet_no) for NOFORK applets */
7010 const struct builtincmd *cmd;
7011 struct funcnode *func;
7014 /* values of cmdtype */
7015 #define CMDUNKNOWN -1 /* no entry in table for command */
7016 #define CMDNORMAL 0 /* command is an executable program */
7017 #define CMDFUNCTION 1 /* command is a shell function */
7018 #define CMDBUILTIN 2 /* command is a shell builtin */
7020 /* action to find_command() */
7021 #define DO_ERR 0x01 /* prints errors */
7022 #define DO_ABS 0x02 /* checks absolute paths */
7023 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7024 #define DO_ALTPATH 0x08 /* using alternate path */
7025 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7027 static void find_command(char *, struct cmdentry *, int, const char *);
7030 /* ============ Hashing commands */
7033 * When commands are first encountered, they are entered in a hash table.
7034 * This ensures that a full path search will not have to be done for them
7035 * on each invocation.
7037 * We should investigate converting to a linear search, even though that
7038 * would make the command name "hash" a misnomer.
7042 struct tblentry *next; /* next entry in hash chain */
7043 union param param; /* definition of builtin function */
7044 smallint cmdtype; /* CMDxxx */
7045 char rehash; /* if set, cd done since entry created */
7046 char cmdname[1]; /* name of command */
7049 static struct tblentry **cmdtable;
7050 #define INIT_G_cmdtable() do { \
7051 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7054 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7058 tryexec(USE_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7062 #if ENABLE_FEATURE_SH_STANDALONE
7063 if (applet_no >= 0) {
7064 if (APPLET_IS_NOEXEC(applet_no)) {
7067 run_applet_no_and_exit(applet_no, argv);
7069 /* re-exec ourselves with the new arguments */
7070 execve(bb_busybox_exec_path, argv, envp);
7071 /* If they called chroot or otherwise made the binary no longer
7072 * executable, fall through */
7079 execve(cmd, argv, envp);
7080 } while (errno == EINTR);
7082 execve(cmd, argv, envp);
7088 if (errno == ENOEXEC) {
7092 for (ap = argv; *ap; ap++)
7094 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7096 ap[0] = cmd = (char *)DEFAULT_SHELL;
7099 while ((*ap++ = *argv++) != NULL)
7108 * Exec a program. Never returns. If you change this routine, you may
7109 * have to change the find_command routine as well.
7111 static void shellexec(char **, const char *, int) NORETURN;
7113 shellexec(char **argv, const char *path, int idx)
7119 #if ENABLE_FEATURE_SH_STANDALONE
7123 clearredir(/*drop:*/ 1);
7124 envp = listvars(VEXPORT, VUNSET, 0);
7125 if (strchr(argv[0], '/') != NULL
7126 #if ENABLE_FEATURE_SH_STANDALONE
7127 || (applet_no = find_applet_by_name(argv[0])) >= 0
7130 tryexec(USE_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7134 while ((cmdname = padvance(&path, argv[0])) != NULL) {
7135 if (--idx < 0 && pathopt == NULL) {
7136 tryexec(USE_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7137 if (errno != ENOENT && errno != ENOTDIR)
7144 /* Map to POSIX errors */
7156 exitstatus = exerrno;
7157 TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
7158 argv[0], e, suppressint));
7159 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7164 printentry(struct tblentry *cmdp)
7170 idx = cmdp->param.index;
7173 name = padvance(&path, cmdp->cmdname);
7175 } while (--idx >= 0);
7176 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7180 * Clear out command entries. The argument specifies the first entry in
7181 * PATH which has changed.
7184 clearcmdentry(int firstchange)
7186 struct tblentry **tblp;
7187 struct tblentry **pp;
7188 struct tblentry *cmdp;
7191 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7193 while ((cmdp = *pp) != NULL) {
7194 if ((cmdp->cmdtype == CMDNORMAL &&
7195 cmdp->param.index >= firstchange)
7196 || (cmdp->cmdtype == CMDBUILTIN &&
7197 builtinloc >= firstchange)
7210 * Locate a command in the command hash table. If "add" is nonzero,
7211 * add the command to the table if it is not already present. The
7212 * variable "lastcmdentry" is set to point to the address of the link
7213 * pointing to the entry, so that delete_cmd_entry can delete the
7216 * Interrupts must be off if called with add != 0.
7218 static struct tblentry **lastcmdentry;
7220 static struct tblentry *
7221 cmdlookup(const char *name, int add)
7223 unsigned int hashval;
7225 struct tblentry *cmdp;
7226 struct tblentry **pp;
7229 hashval = (unsigned char)*p << 4;
7231 hashval += (unsigned char)*p++;
7233 pp = &cmdtable[hashval % CMDTABLESIZE];
7234 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7235 if (strcmp(cmdp->cmdname, name) == 0)
7239 if (add && cmdp == NULL) {
7240 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7242 /* + 1 - already done because
7243 * tblentry::cmdname is char[1] */);
7244 /*cmdp->next = NULL; - ckzalloc did it */
7245 cmdp->cmdtype = CMDUNKNOWN;
7246 strcpy(cmdp->cmdname, name);
7253 * Delete the command entry returned on the last lookup.
7256 delete_cmd_entry(void)
7258 struct tblentry *cmdp;
7261 cmdp = *lastcmdentry;
7262 *lastcmdentry = cmdp->next;
7263 if (cmdp->cmdtype == CMDFUNCTION)
7264 freefunc(cmdp->param.func);
7270 * Add a new command entry, replacing any existing command entry for
7271 * the same name - except special builtins.
7274 addcmdentry(char *name, struct cmdentry *entry)
7276 struct tblentry *cmdp;
7278 cmdp = cmdlookup(name, 1);
7279 if (cmdp->cmdtype == CMDFUNCTION) {
7280 freefunc(cmdp->param.func);
7282 cmdp->cmdtype = entry->cmdtype;
7283 cmdp->param = entry->u;
7288 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7290 struct tblentry **pp;
7291 struct tblentry *cmdp;
7293 struct cmdentry entry;
7296 if (nextopt("r") != '\0') {
7301 if (*argptr == NULL) {
7302 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7303 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7304 if (cmdp->cmdtype == CMDNORMAL)
7312 while ((name = *argptr) != NULL) {
7313 cmdp = cmdlookup(name, 0);
7315 && (cmdp->cmdtype == CMDNORMAL
7316 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7320 find_command(name, &entry, DO_ERR, pathval());
7321 if (entry.cmdtype == CMDUNKNOWN)
7329 * Called when a cd is done. Marks all commands so the next time they
7330 * are executed they will be rehashed.
7335 struct tblentry **pp;
7336 struct tblentry *cmdp;
7338 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7339 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7340 if (cmdp->cmdtype == CMDNORMAL
7341 || (cmdp->cmdtype == CMDBUILTIN
7342 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7352 * Fix command hash table when PATH changed.
7353 * Called before PATH is changed. The argument is the new value of PATH;
7354 * pathval() still returns the old value at this point.
7355 * Called with interrupts off.
7358 changepath(const char *new)
7366 firstchange = 9999; /* assume no change */
7372 if ((*old == '\0' && *new == ':')
7373 || (*old == ':' && *new == '\0'))
7375 old = new; /* ignore subsequent differences */
7379 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7385 if (builtinloc < 0 && idx_bltin >= 0)
7386 builtinloc = idx_bltin; /* zap builtins */
7387 if (builtinloc >= 0 && idx_bltin < 0)
7389 clearcmdentry(firstchange);
7390 builtinloc = idx_bltin;
7405 #define TENDBQUOTE 12
7422 typedef smallint token_id_t;
7424 /* first char is indicating which tokens mark the end of a list */
7425 static const char *const tokname_array[] = {
7439 #define KWDOFFSET 13
7440 /* the following are keywords */
7462 static char buf[16];
7465 //if (tok < TSEMI) return tokname_array[tok] + 1;
7466 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7471 sprintf(buf + (tok >= TSEMI), "%s%c",
7472 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7476 /* Wrapper around strcmp for qsort/bsearch/... */
7478 pstrcmp(const void *a, const void *b)
7480 return strcmp((char*) a, (*(char**) b) + 1);
7483 static const char *const *
7484 findkwd(const char *s)
7486 return bsearch(s, tokname_array + KWDOFFSET,
7487 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7488 sizeof(tokname_array[0]), pstrcmp);
7492 * Locate and print what a word is...
7495 describe_command(char *command, int describe_command_verbose)
7497 struct cmdentry entry;
7498 struct tblentry *cmdp;
7499 #if ENABLE_ASH_ALIAS
7500 const struct alias *ap;
7502 const char *path = pathval();
7504 if (describe_command_verbose) {
7508 /* First look at the keywords */
7509 if (findkwd(command)) {
7510 out1str(describe_command_verbose ? " is a shell keyword" : command);
7514 #if ENABLE_ASH_ALIAS
7515 /* Then look at the aliases */
7516 ap = lookupalias(command, 0);
7518 if (!describe_command_verbose) {
7523 out1fmt(" is an alias for %s", ap->val);
7527 /* Then check if it is a tracked alias */
7528 cmdp = cmdlookup(command, 0);
7530 entry.cmdtype = cmdp->cmdtype;
7531 entry.u = cmdp->param;
7533 /* Finally use brute force */
7534 find_command(command, &entry, DO_ABS, path);
7537 switch (entry.cmdtype) {
7539 int j = entry.u.index;
7545 p = padvance(&path, command);
7549 if (describe_command_verbose) {
7551 (cmdp ? " a tracked alias for" : nullstr), p
7560 if (describe_command_verbose) {
7561 out1str(" is a shell function");
7568 if (describe_command_verbose) {
7569 out1fmt(" is a %sshell builtin",
7570 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7571 "special " : nullstr
7579 if (describe_command_verbose) {
7580 out1str(": not found\n");
7585 outstr("\n", stdout);
7590 typecmd(int argc UNUSED_PARAM, char **argv)
7596 /* type -p ... ? (we don't bother checking for 'p') */
7597 if (argv[1] && argv[1][0] == '-') {
7602 err |= describe_command(argv[i++], verbose);
7607 #if ENABLE_ASH_CMDCMD
7609 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7617 while ((c = nextopt("pvV")) != '\0')
7619 verify |= VERIFY_VERBOSE;
7621 verify |= VERIFY_BRIEF;
7626 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7627 if (verify && (*argptr != NULL)) {
7628 return describe_command(*argptr, verify - VERIFY_BRIEF);
7636 /* ============ eval.c */
7638 static int funcblocksize; /* size of structures in function */
7639 static int funcstringsize; /* size of strings in node */
7640 static void *funcblock; /* block to allocate function from */
7641 static char *funcstring; /* block to allocate strings from */
7643 /* flags in argument to evaltree */
7644 #define EV_EXIT 01 /* exit after evaluating tree */
7645 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7646 #define EV_BACKCMD 04 /* command executing within back quotes */
7648 static const short nodesize[N_NUMBER] = {
7649 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7650 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7651 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7652 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7653 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7654 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7655 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7656 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7657 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7658 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7659 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7660 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7661 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7662 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7663 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7664 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7665 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7666 #if ENABLE_ASH_BASH_COMPAT
7667 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7669 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7670 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7671 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7672 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7673 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7674 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7675 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7676 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7677 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7680 static void calcsize(union node *n);
7683 sizenodelist(struct nodelist *lp)
7686 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7693 calcsize(union node *n)
7697 funcblocksize += nodesize[n->type];
7700 calcsize(n->ncmd.redirect);
7701 calcsize(n->ncmd.args);
7702 calcsize(n->ncmd.assign);
7705 sizenodelist(n->npipe.cmdlist);
7710 calcsize(n->nredir.redirect);
7711 calcsize(n->nredir.n);
7718 calcsize(n->nbinary.ch2);
7719 calcsize(n->nbinary.ch1);
7722 calcsize(n->nif.elsepart);
7723 calcsize(n->nif.ifpart);
7724 calcsize(n->nif.test);
7727 funcstringsize += strlen(n->nfor.var) + 1;
7728 calcsize(n->nfor.body);
7729 calcsize(n->nfor.args);
7732 calcsize(n->ncase.cases);
7733 calcsize(n->ncase.expr);
7736 calcsize(n->nclist.body);
7737 calcsize(n->nclist.pattern);
7738 calcsize(n->nclist.next);
7742 sizenodelist(n->narg.backquote);
7743 funcstringsize += strlen(n->narg.text) + 1;
7744 calcsize(n->narg.next);
7747 #if ENABLE_ASH_BASH_COMPAT
7754 calcsize(n->nfile.fname);
7755 calcsize(n->nfile.next);
7759 calcsize(n->ndup.vname);
7760 calcsize(n->ndup.next);
7764 calcsize(n->nhere.doc);
7765 calcsize(n->nhere.next);
7768 calcsize(n->nnot.com);
7774 nodeckstrdup(char *s)
7776 char *rtn = funcstring;
7778 strcpy(funcstring, s);
7779 funcstring += strlen(s) + 1;
7783 static union node *copynode(union node *);
7785 static struct nodelist *
7786 copynodelist(struct nodelist *lp)
7788 struct nodelist *start;
7789 struct nodelist **lpp;
7794 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7795 (*lpp)->n = copynode(lp->n);
7797 lpp = &(*lpp)->next;
7804 copynode(union node *n)
7811 funcblock = (char *) funcblock + nodesize[n->type];
7815 new->ncmd.redirect = copynode(n->ncmd.redirect);
7816 new->ncmd.args = copynode(n->ncmd.args);
7817 new->ncmd.assign = copynode(n->ncmd.assign);
7820 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7821 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
7826 new->nredir.redirect = copynode(n->nredir.redirect);
7827 new->nredir.n = copynode(n->nredir.n);
7834 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7835 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7838 new->nif.elsepart = copynode(n->nif.elsepart);
7839 new->nif.ifpart = copynode(n->nif.ifpart);
7840 new->nif.test = copynode(n->nif.test);
7843 new->nfor.var = nodeckstrdup(n->nfor.var);
7844 new->nfor.body = copynode(n->nfor.body);
7845 new->nfor.args = copynode(n->nfor.args);
7848 new->ncase.cases = copynode(n->ncase.cases);
7849 new->ncase.expr = copynode(n->ncase.expr);
7852 new->nclist.body = copynode(n->nclist.body);
7853 new->nclist.pattern = copynode(n->nclist.pattern);
7854 new->nclist.next = copynode(n->nclist.next);
7858 new->narg.backquote = copynodelist(n->narg.backquote);
7859 new->narg.text = nodeckstrdup(n->narg.text);
7860 new->narg.next = copynode(n->narg.next);
7863 #if ENABLE_ASH_BASH_COMPAT
7870 new->nfile.fname = copynode(n->nfile.fname);
7871 new->nfile.fd = n->nfile.fd;
7872 new->nfile.next = copynode(n->nfile.next);
7876 new->ndup.vname = copynode(n->ndup.vname);
7877 new->ndup.dupfd = n->ndup.dupfd;
7878 new->ndup.fd = n->ndup.fd;
7879 new->ndup.next = copynode(n->ndup.next);
7883 new->nhere.doc = copynode(n->nhere.doc);
7884 new->nhere.fd = n->nhere.fd;
7885 new->nhere.next = copynode(n->nhere.next);
7888 new->nnot.com = copynode(n->nnot.com);
7891 new->type = n->type;
7896 * Make a copy of a parse tree.
7898 static struct funcnode *
7899 copyfunc(union node *n)
7904 funcblocksize = offsetof(struct funcnode, n);
7907 blocksize = funcblocksize;
7908 f = ckmalloc(blocksize + funcstringsize);
7909 funcblock = (char *) f + offsetof(struct funcnode, n);
7910 funcstring = (char *) f + blocksize;
7917 * Define a shell function.
7920 defun(char *name, union node *func)
7922 struct cmdentry entry;
7925 entry.cmdtype = CMDFUNCTION;
7926 entry.u.func = copyfunc(func);
7927 addcmdentry(name, &entry);
7931 /* Reasons for skipping commands (see comment on breakcmd routine) */
7932 #define SKIPBREAK (1 << 0)
7933 #define SKIPCONT (1 << 1)
7934 #define SKIPFUNC (1 << 2)
7935 #define SKIPFILE (1 << 3)
7936 #define SKIPEVAL (1 << 4)
7937 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
7938 static int skipcount; /* number of levels to skip */
7939 static int funcnest; /* depth of function calls */
7940 static int loopnest; /* current loop nesting level */
7942 /* Forward decl way out to parsing code - dotrap needs it */
7943 static int evalstring(char *s, int mask);
7945 /* Called to execute a trap.
7946 * Single callsite - at the end of evaltree().
7947 * If we return non-zero, exaltree raises EXEXIT exception.
7949 * Perhaps we should avoid entering new trap handlers
7950 * while we are executing a trap handler. [is it a TODO?]
7959 savestatus = exitstatus;
7963 TRACE(("dotrap entered\n"));
7964 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
7971 /* non-trapped SIGINT is handled separately by raise_interrupt,
7972 * don't upset it by resetting gotsig[SIGINT-1] */
7973 if (sig == SIGINT && !t)
7976 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
7980 want_exexit = evalstring(t, SKIPEVAL);
7981 exitstatus = savestatus;
7983 TRACE(("dotrap returns %d\n", want_exexit));
7988 TRACE(("dotrap returns 0\n"));
7992 /* forward declarations - evaluation is fairly recursive business... */
7993 static void evalloop(union node *, int);
7994 static void evalfor(union node *, int);
7995 static void evalcase(union node *, int);
7996 static void evalsubshell(union node *, int);
7997 static void expredir(union node *);
7998 static void evalpipe(union node *, int);
7999 static void evalcommand(union node *, int);
8000 static int evalbltin(const struct builtincmd *, int, char **);
8001 static void prehash(union node *);
8004 * Evaluate a parse tree. The value is left in the global variable
8008 evaltree(union node *n, int flags)
8010 struct jmploc *volatile savehandler = exception_handler;
8011 struct jmploc jmploc;
8013 void (*evalfn)(union node *, int);
8017 SAVE_INT(int_level);
8020 TRACE(("evaltree(NULL) called\n"));
8023 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8025 exception_handler = &jmploc;
8027 int err = setjmp(jmploc.loc);
8029 /* if it was a signal, check for trap handlers */
8030 if (exception_type == EXSIG) {
8031 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8032 exception_type, err));
8035 /* continue on the way out */
8036 TRACE(("exception %d in evaltree, propagating err=%d\n",
8037 exception_type, err));
8038 exception_handler = savehandler;
8039 longjmp(exception_handler->loc, err);
8046 out1fmt("Node type = %d\n", n->type);
8051 evaltree(n->nnot.com, EV_TESTED);
8052 status = !exitstatus;
8055 expredir(n->nredir.redirect);
8056 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8058 evaltree(n->nredir.n, flags & EV_TESTED);
8059 status = exitstatus;
8061 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8064 evalfn = evalcommand;
8066 if (eflag && !(flags & EV_TESTED))
8078 evalfn = evalsubshell;
8091 #error NAND + 1 != NOR
8093 #if NOR + 1 != NSEMI
8094 #error NOR + 1 != NSEMI
8096 unsigned is_or = n->type - NAND;
8099 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8101 if (!exitstatus == is_or)
8114 evaltree(n->nif.test, EV_TESTED);
8117 if (exitstatus == 0) {
8121 if (n->nif.elsepart) {
8122 n = n->nif.elsepart;
8127 defun(n->narg.text, n->narg.next);
8131 exitstatus = status;
8136 exception_handler = savehandler;
8138 if (checkexit & exitstatus)
8139 evalskip |= SKIPEVAL;
8140 else if (pendingsig && dotrap())
8143 if (flags & EV_EXIT) {
8145 raise_exception(EXEXIT);
8148 RESTORE_INT(int_level);
8149 TRACE(("leaving evaltree (no interrupts)\n"));
8152 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8155 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8158 evalloop(union node *n, int flags)
8168 evaltree(n->nbinary.ch1, EV_TESTED);
8171 if (evalskip == SKIPCONT && --skipcount <= 0) {
8175 if (evalskip == SKIPBREAK && --skipcount <= 0)
8180 if (n->type != NWHILE)
8184 evaltree(n->nbinary.ch2, flags);
8185 status = exitstatus;
8190 exitstatus = status;
8194 evalfor(union node *n, int flags)
8196 struct arglist arglist;
8199 struct stackmark smark;
8201 setstackmark(&smark);
8202 arglist.list = NULL;
8203 arglist.lastp = &arglist.list;
8204 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8205 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8210 *arglist.lastp = NULL;
8215 for (sp = arglist.list; sp; sp = sp->next) {
8216 setvar(n->nfor.var, sp->text, 0);
8217 evaltree(n->nfor.body, flags);
8219 if (evalskip == SKIPCONT && --skipcount <= 0) {
8223 if (evalskip == SKIPBREAK && --skipcount <= 0)
8230 popstackmark(&smark);
8234 evalcase(union node *n, int flags)
8238 struct arglist arglist;
8239 struct stackmark smark;
8241 setstackmark(&smark);
8242 arglist.list = NULL;
8243 arglist.lastp = &arglist.list;
8244 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8246 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8247 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8248 if (casematch(patp, arglist.list->text)) {
8249 if (evalskip == 0) {
8250 evaltree(cp->nclist.body, flags);
8257 popstackmark(&smark);
8261 * Kick off a subshell to evaluate a tree.
8264 evalsubshell(union node *n, int flags)
8267 int backgnd = (n->type == NBACKGND);
8270 expredir(n->nredir.redirect);
8271 if (!backgnd && flags & EV_EXIT && !trap[0])
8274 jp = makejob(/*n,*/ 1);
8275 if (forkshell(jp, n, backgnd) == 0) {
8279 flags &=~ EV_TESTED;
8281 redirect(n->nredir.redirect, 0);
8282 evaltreenr(n->nredir.n, flags);
8287 status = waitforjob(jp);
8288 exitstatus = status;
8293 * Compute the names of the files in a redirection list.
8295 static void fixredir(union node *, const char *, int);
8297 expredir(union node *n)
8301 for (redir = n; redir; redir = redir->nfile.next) {
8305 fn.lastp = &fn.list;
8306 switch (redir->type) {
8310 #if ENABLE_ASH_BASH_COMPAT
8315 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8316 #if ENABLE_ASH_BASH_COMPAT
8319 redir->nfile.expfname = fn.list->text;
8322 case NTOFD: /* >& */
8323 if (redir->ndup.vname) {
8324 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8325 if (fn.list == NULL)
8326 ash_msg_and_raise_error("redir error");
8327 #if ENABLE_ASH_BASH_COMPAT
8328 //FIXME: we used expandarg with different args!
8329 if (!isdigit_str9(fn.list->text)) {
8330 /* >&file, not >&fd */
8331 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8332 ash_msg_and_raise_error("redir error");
8334 goto store_expfname;
8337 fixredir(redir, fn.list->text, 1);
8345 * Evaluate a pipeline. All the processes in the pipeline are children
8346 * of the process creating the pipeline. (This differs from some versions
8347 * of the shell, which make the last process in a pipeline the parent
8351 evalpipe(union node *n, int flags)
8354 struct nodelist *lp;
8359 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8361 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8365 jp = makejob(/*n,*/ pipelen);
8367 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8371 if (pipe(pip) < 0) {
8373 ash_msg_and_raise_error("pipe call failed");
8376 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8389 evaltreenr(lp->n, flags);
8395 /* Don't want to trigger debugging */
8399 if (n->npipe.pipe_backgnd == 0) {
8400 exitstatus = waitforjob(jp);
8401 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8407 * Controls whether the shell is interactive or not.
8410 setinteractive(int on)
8412 static smallint is_interactive;
8414 if (++on == is_interactive)
8416 is_interactive = on;
8420 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8421 if (is_interactive > 1) {
8422 /* Looks like they want an interactive shell */
8423 static smallint did_banner;
8428 "%s built-in shell (ash)\n"
8429 "Enter 'help' for a list of built-in commands."
8444 setinteractive(iflag);
8446 #if ENABLE_FEATURE_EDITING_VI
8448 line_input_state->flags |= VI_MODE;
8450 line_input_state->flags &= ~VI_MODE;
8452 viflag = 0; /* forcibly keep the option off */
8456 static struct localvar *localvars;
8459 * Called after a function returns.
8460 * Interrupts must be off.
8465 struct localvar *lvp;
8468 while ((lvp = localvars) != NULL) {
8469 localvars = lvp->next;
8471 TRACE(("poplocalvar %s", vp ? vp->text : "-"));
8472 if (vp == NULL) { /* $- saved */
8473 memcpy(optlist, lvp->text, sizeof(optlist));
8474 free((char*)lvp->text);
8476 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8480 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8481 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8482 free((char*)vp->text);
8483 vp->flags = lvp->flags;
8484 vp->text = lvp->text;
8491 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8493 volatile struct shparam saveparam;
8494 struct localvar *volatile savelocalvars;
8495 struct jmploc *volatile savehandler;
8496 struct jmploc jmploc;
8499 saveparam = shellparam;
8500 savelocalvars = localvars;
8501 e = setjmp(jmploc.loc);
8506 savehandler = exception_handler;
8507 exception_handler = &jmploc;
8509 shellparam.malloced = 0;
8513 shellparam.nparam = argc - 1;
8514 shellparam.p = argv + 1;
8515 #if ENABLE_ASH_GETOPTS
8516 shellparam.optind = 1;
8517 shellparam.optoff = -1;
8519 evaltree(&func->n, flags & EV_TESTED);
8525 localvars = savelocalvars;
8526 freeparam(&shellparam);
8527 shellparam = saveparam;
8528 exception_handler = savehandler;
8530 evalskip &= ~SKIPFUNC;
8534 #if ENABLE_ASH_CMDCMD
8536 parse_command_args(char **argv, const char **path)
8549 if (c == '-' && !*cp) {
8556 *path = bb_default_path;
8559 /* run 'typecmd' for other options */
8570 * Make a variable a local variable. When a variable is made local, it's
8571 * value and flags are saved in a localvar structure. The saved values
8572 * will be restored when the shell function returns. We handle the name
8573 * "-" as a special case.
8578 struct localvar *lvp;
8583 lvp = ckzalloc(sizeof(struct localvar));
8584 if (LONE_DASH(name)) {
8586 p = ckmalloc(sizeof(optlist));
8587 lvp->text = memcpy(p, optlist, sizeof(optlist));
8592 vpp = hashvar(name);
8593 vp = *findvar(vpp, name);
8594 eq = strchr(name, '=');
8597 setvareq(name, VSTRFIXED);
8599 setvar(name, NULL, VSTRFIXED);
8600 vp = *vpp; /* the new variable */
8601 lvp->flags = VUNSET;
8603 lvp->text = vp->text;
8604 lvp->flags = vp->flags;
8605 vp->flags |= VSTRFIXED|VTEXTFIXED;
8611 lvp->next = localvars;
8617 * The "local" command.
8620 localcmd(int argc UNUSED_PARAM, char **argv)
8625 while ((name = *argv++) != NULL) {
8632 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8638 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8644 execcmd(int argc UNUSED_PARAM, char **argv)
8647 iflag = 0; /* exit on error */
8650 shellexec(argv + 1, pathval(), 0);
8656 * The return command.
8659 returncmd(int argc UNUSED_PARAM, char **argv)
8662 * If called outside a function, do what ksh does;
8663 * skip the rest of the file.
8665 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8666 return argv[1] ? number(argv[1]) : exitstatus;
8669 /* Forward declarations for builtintab[] */
8670 static int breakcmd(int, char **);
8671 static int dotcmd(int, char **);
8672 static int evalcmd(int, char **);
8673 static int exitcmd(int, char **);
8674 static int exportcmd(int, char **);
8675 #if ENABLE_ASH_GETOPTS
8676 static int getoptscmd(int, char **);
8678 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8679 static int helpcmd(int, char **);
8681 #if ENABLE_SH_MATH_SUPPORT
8682 static int letcmd(int, char **);
8684 static int readcmd(int, char **);
8685 static int setcmd(int, char **);
8686 static int shiftcmd(int, char **);
8687 static int timescmd(int, char **);
8688 static int trapcmd(int, char **);
8689 static int umaskcmd(int, char **);
8690 static int unsetcmd(int, char **);
8691 static int ulimitcmd(int, char **);
8693 #define BUILTIN_NOSPEC "0"
8694 #define BUILTIN_SPECIAL "1"
8695 #define BUILTIN_REGULAR "2"
8696 #define BUILTIN_SPEC_REG "3"
8697 #define BUILTIN_ASSIGN "4"
8698 #define BUILTIN_SPEC_ASSG "5"
8699 #define BUILTIN_REG_ASSG "6"
8700 #define BUILTIN_SPEC_REG_ASSG "7"
8702 /* We do not handle [[ expr ]] bashism bash-compatibly,
8703 * we make it a synonym of [ expr ].
8704 * Basically, word splitting and pathname expansion should NOT be performed
8706 * no word splitting: a="a b"; [[ $a = "a b" ]]; echo $? should print "0"
8707 * no pathname expansion: [[ /bin/m* = "/bin/m*" ]]; echo $? should print "0"
8708 * Additional operators:
8709 * || and && should work as -o and -a
8711 * Apart from the above, [[ expr ]] should work as [ expr ]
8714 #define echocmd echo_main
8715 #define printfcmd printf_main
8716 #define testcmd test_main
8718 /* Keep these in proper order since it is searched via bsearch() */
8719 static const struct builtincmd builtintab[] = {
8720 { BUILTIN_SPEC_REG ".", dotcmd },
8721 { BUILTIN_SPEC_REG ":", truecmd },
8722 #if ENABLE_ASH_BUILTIN_TEST
8723 { BUILTIN_REGULAR "[", testcmd },
8724 #if ENABLE_ASH_BASH_COMPAT
8725 { BUILTIN_REGULAR "[[", testcmd },
8728 #if ENABLE_ASH_ALIAS
8729 { BUILTIN_REG_ASSG "alias", aliascmd },
8732 { BUILTIN_REGULAR "bg", fg_bgcmd },
8734 { BUILTIN_SPEC_REG "break", breakcmd },
8735 { BUILTIN_REGULAR "cd", cdcmd },
8736 { BUILTIN_NOSPEC "chdir", cdcmd },
8737 #if ENABLE_ASH_CMDCMD
8738 { BUILTIN_REGULAR "command", commandcmd },
8740 { BUILTIN_SPEC_REG "continue", breakcmd },
8741 #if ENABLE_ASH_BUILTIN_ECHO
8742 { BUILTIN_REGULAR "echo", echocmd },
8744 { BUILTIN_SPEC_REG "eval", evalcmd },
8745 { BUILTIN_SPEC_REG "exec", execcmd },
8746 { BUILTIN_SPEC_REG "exit", exitcmd },
8747 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8748 { BUILTIN_REGULAR "false", falsecmd },
8750 { BUILTIN_REGULAR "fg", fg_bgcmd },
8752 #if ENABLE_ASH_GETOPTS
8753 { BUILTIN_REGULAR "getopts", getoptscmd },
8755 { BUILTIN_NOSPEC "hash", hashcmd },
8756 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8757 { BUILTIN_NOSPEC "help", helpcmd },
8760 { BUILTIN_REGULAR "jobs", jobscmd },
8761 { BUILTIN_REGULAR "kill", killcmd },
8763 #if ENABLE_SH_MATH_SUPPORT
8764 { BUILTIN_NOSPEC "let", letcmd },
8766 { BUILTIN_ASSIGN "local", localcmd },
8767 #if ENABLE_ASH_BUILTIN_PRINTF
8768 { BUILTIN_REGULAR "printf", printfcmd },
8770 { BUILTIN_NOSPEC "pwd", pwdcmd },
8771 { BUILTIN_REGULAR "read", readcmd },
8772 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8773 { BUILTIN_SPEC_REG "return", returncmd },
8774 { BUILTIN_SPEC_REG "set", setcmd },
8775 { BUILTIN_SPEC_REG "shift", shiftcmd },
8776 { BUILTIN_SPEC_REG "source", dotcmd },
8777 #if ENABLE_ASH_BUILTIN_TEST
8778 { BUILTIN_REGULAR "test", testcmd },
8780 { BUILTIN_SPEC_REG "times", timescmd },
8781 { BUILTIN_SPEC_REG "trap", trapcmd },
8782 { BUILTIN_REGULAR "true", truecmd },
8783 { BUILTIN_NOSPEC "type", typecmd },
8784 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8785 { BUILTIN_REGULAR "umask", umaskcmd },
8786 #if ENABLE_ASH_ALIAS
8787 { BUILTIN_REGULAR "unalias", unaliascmd },
8789 { BUILTIN_SPEC_REG "unset", unsetcmd },
8790 { BUILTIN_REGULAR "wait", waitcmd },
8793 /* Should match the above table! */
8794 #define COMMANDCMD (builtintab + \
8796 1 * ENABLE_ASH_BUILTIN_TEST + \
8797 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8798 1 * ENABLE_ASH_ALIAS + \
8799 1 * ENABLE_ASH_JOB_CONTROL + \
8801 #define EXECCMD (builtintab + \
8803 1 * ENABLE_ASH_BUILTIN_TEST + \
8804 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8805 1 * ENABLE_ASH_ALIAS + \
8806 1 * ENABLE_ASH_JOB_CONTROL + \
8808 1 * ENABLE_ASH_CMDCMD + \
8810 ENABLE_ASH_BUILTIN_ECHO + \
8814 * Search the table of builtin commands.
8816 static struct builtincmd *
8817 find_builtin(const char *name)
8819 struct builtincmd *bp;
8822 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8829 * Execute a simple command.
8832 isassignment(const char *p)
8834 const char *q = endofname(p);
8840 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8842 /* Preserve exitstatus of a previous possible redirection
8843 * as POSIX mandates */
8844 return back_exitstatus;
8847 evalcommand(union node *cmd, int flags)
8849 static const struct builtincmd null_bltin = {
8850 "\0\0", bltincmd /* why three NULs? */
8852 struct stackmark smark;
8854 struct arglist arglist;
8855 struct arglist varlist;
8858 const struct strlist *sp;
8859 struct cmdentry cmdentry;
8866 struct builtincmd *bcmd;
8867 smallint cmd_is_exec;
8868 smallint pseudovarflag = 0;
8870 /* First expand the arguments. */
8871 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8872 setstackmark(&smark);
8873 back_exitstatus = 0;
8875 cmdentry.cmdtype = CMDBUILTIN;
8876 cmdentry.u.cmd = &null_bltin;
8877 varlist.lastp = &varlist.list;
8878 *varlist.lastp = NULL;
8879 arglist.lastp = &arglist.list;
8880 *arglist.lastp = NULL;
8883 if (cmd->ncmd.args) {
8884 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8885 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8888 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8889 struct strlist **spp;
8891 spp = arglist.lastp;
8892 if (pseudovarflag && isassignment(argp->narg.text))
8893 expandarg(argp, &arglist, EXP_VARTILDE);
8895 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8897 for (sp = *spp; sp; sp = sp->next)
8901 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
8902 for (sp = arglist.list; sp; sp = sp->next) {
8903 TRACE(("evalcommand arg: %s\n", sp->text));
8904 *nargv++ = sp->text;
8909 if (iflag && funcnest == 0 && argc > 0)
8910 lastarg = nargv[-1];
8913 expredir(cmd->ncmd.redirect);
8914 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
8917 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
8918 struct strlist **spp;
8921 spp = varlist.lastp;
8922 expandarg(argp, &varlist, EXP_VARTILDE);
8925 * Modify the command lookup path, if a PATH= assignment
8929 if (varequal(p, path))
8933 /* Print the command if xflag is set. */
8936 const char *p = " %s";
8939 fdprintf(preverrout_fd, p, expandstr(ps4val()));
8942 for (n = 0; n < 2; n++) {
8944 fdprintf(preverrout_fd, p, sp->text);
8952 safe_write(preverrout_fd, "\n", 1);
8958 /* Now locate the command. */
8960 const char *oldpath;
8961 int cmd_flag = DO_ERR;
8966 find_command(argv[0], &cmdentry, cmd_flag, path);
8967 if (cmdentry.cmdtype == CMDUNKNOWN) {
8973 /* implement bltin and command here */
8974 if (cmdentry.cmdtype != CMDBUILTIN)
8977 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
8978 if (cmdentry.u.cmd == EXECCMD)
8980 #if ENABLE_ASH_CMDCMD
8981 if (cmdentry.u.cmd == COMMANDCMD) {
8983 nargv = parse_command_args(argv, &path);
8986 argc -= nargv - argv;
8988 cmd_flag |= DO_NOFUNC;
8996 /* We have a redirection error. */
8998 raise_exception(EXERROR);
9000 exitstatus = status;
9004 /* Execute the command. */
9005 switch (cmdentry.cmdtype) {
9008 #if ENABLE_FEATURE_SH_NOFORK
9009 /* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9010 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
9012 /* find_command() encodes applet_no as (-2 - applet_no) */
9013 int applet_no = (- cmdentry.u.index - 2);
9014 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9015 listsetvar(varlist.list, VEXPORT|VSTACK);
9016 /* run <applet>_main() */
9017 exitstatus = run_nofork_applet(applet_no, argv);
9022 /* Fork off a child process if necessary. */
9023 if (!(flags & EV_EXIT) || trap[0]) {
9025 jp = makejob(/*cmd,*/ 1);
9026 if (forkshell(jp, cmd, FORK_FG) != 0) {
9027 exitstatus = waitforjob(jp);
9029 TRACE(("forked child exited with %d\n", exitstatus));
9034 listsetvar(varlist.list, VEXPORT|VSTACK);
9035 shellexec(argv, path, cmdentry.u.index);
9039 cmdenviron = varlist.list;
9041 struct strlist *list = cmdenviron;
9043 if (spclbltin > 0 || argc == 0) {
9045 if (cmd_is_exec && argc > 1)
9048 listsetvar(list, i);
9050 /* Tight loop with builtins only:
9051 * "while kill -0 $child; do true; done"
9052 * will never exit even if $child died, unless we do this
9053 * to reap the zombie and make kill detect that it's gone: */
9054 dowait(DOWAIT_NONBLOCK, NULL);
9056 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9058 int i = exception_type;
9063 exit_status = 128 + SIGINT;
9065 exit_status = 128 + pendingsig;
9066 exitstatus = exit_status;
9067 if (i == EXINT || spclbltin > 0) {
9069 longjmp(exception_handler->loc, 1);
9076 listsetvar(varlist.list, 0);
9077 /* See above for the rationale */
9078 dowait(DOWAIT_NONBLOCK, NULL);
9079 if (evalfun(cmdentry.u.func, argc, argv, flags))
9085 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9087 /* dsl: I think this is intended to be used to support
9088 * '_' in 'vi' command mode during line editing...
9089 * However I implemented that within libedit itself.
9091 setvar("_", lastarg, 0);
9093 popstackmark(&smark);
9097 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9099 char *volatile savecmdname;
9100 struct jmploc *volatile savehandler;
9101 struct jmploc jmploc;
9104 savecmdname = commandname;
9105 i = setjmp(jmploc.loc);
9108 savehandler = exception_handler;
9109 exception_handler = &jmploc;
9110 commandname = argv[0];
9112 optptr = NULL; /* initialize nextopt */
9113 exitstatus = (*cmd->builtin)(argc, argv);
9114 flush_stdout_stderr();
9116 exitstatus |= ferror(stdout);
9118 commandname = savecmdname;
9120 exception_handler = savehandler;
9126 goodname(const char *p)
9128 return !*endofname(p);
9133 * Search for a command. This is called before we fork so that the
9134 * location of the command will be available in the parent as well as
9135 * the child. The check for "goodname" is an overly conservative
9136 * check that the name will not be subject to expansion.
9139 prehash(union node *n)
9141 struct cmdentry entry;
9143 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9144 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9148 /* ============ Builtin commands
9150 * Builtin commands whose functions are closely tied to evaluation
9151 * are implemented here.
9155 * Handle break and continue commands. Break, continue, and return are
9156 * all handled by setting the evalskip flag. The evaluation routines
9157 * above all check this flag, and if it is set they start skipping
9158 * commands rather than executing them. The variable skipcount is
9159 * the number of loops to break/continue, or the number of function
9160 * levels to return. (The latter is always 1.) It should probably
9161 * be an error to break out of more loops than exist, but it isn't
9162 * in the standard shell so we don't make it one here.
9165 breakcmd(int argc UNUSED_PARAM, char **argv)
9167 int n = argv[1] ? number(argv[1]) : 1;
9170 ash_msg_and_raise_error(illnum, argv[1]);
9174 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9181 /* ============ input.c
9183 * This implements the input routines used by the parser.
9187 INPUT_PUSH_FILE = 1,
9188 INPUT_NOFILE_OK = 2,
9191 static smallint checkkwd;
9192 /* values of checkkwd variable */
9193 #define CHKALIAS 0x1
9198 * Push a string back onto the input at this current parsefile level.
9199 * We handle aliases this way.
9201 #if !ENABLE_ASH_ALIAS
9202 #define pushstring(s, ap) pushstring(s)
9205 pushstring(char *s, struct alias *ap)
9212 if (g_parsefile->strpush) {
9213 sp = ckzalloc(sizeof(*sp));
9214 sp->prev = g_parsefile->strpush;
9216 sp = &(g_parsefile->basestrpush);
9218 g_parsefile->strpush = sp;
9219 sp->prev_string = g_parsefile->next_to_pgetc;
9220 sp->prev_left_in_line = g_parsefile->left_in_line;
9221 #if ENABLE_ASH_ALIAS
9224 ap->flag |= ALIASINUSE;
9228 g_parsefile->next_to_pgetc = s;
9229 g_parsefile->left_in_line = len;
9236 struct strpush *sp = g_parsefile->strpush;
9239 #if ENABLE_ASH_ALIAS
9241 if (g_parsefile->next_to_pgetc[-1] == ' '
9242 || g_parsefile->next_to_pgetc[-1] == '\t'
9244 checkkwd |= CHKALIAS;
9246 if (sp->string != sp->ap->val) {
9249 sp->ap->flag &= ~ALIASINUSE;
9250 if (sp->ap->flag & ALIASDEAD) {
9251 unalias(sp->ap->name);
9255 g_parsefile->next_to_pgetc = sp->prev_string;
9256 g_parsefile->left_in_line = sp->prev_left_in_line;
9257 g_parsefile->strpush = sp->prev;
9258 if (sp != &(g_parsefile->basestrpush))
9263 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9264 //it peeks whether it is &>, and then pushes back both chars.
9265 //This function needs to save last *next_to_pgetc to buf[0]
9266 //to make two pungetc() reliable. Currently,
9267 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9272 char *buf = g_parsefile->buf;
9274 g_parsefile->next_to_pgetc = buf;
9275 #if ENABLE_FEATURE_EDITING
9277 if (!iflag || g_parsefile->fd != STDIN_FILENO)
9278 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9280 #if ENABLE_FEATURE_TAB_COMPLETION
9281 line_input_state->path_lookup = pathval();
9283 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9285 /* Ctrl+C pressed */
9294 if (nr < 0 && errno == 0) {
9295 /* Ctrl+D pressed */
9300 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9304 /* nonblock_safe_read() handles this problem */
9306 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9307 int flags = fcntl(0, F_GETFL);
9308 if (flags >= 0 && (flags & O_NONBLOCK)) {
9309 flags &= ~O_NONBLOCK;
9310 if (fcntl(0, F_SETFL, flags) >= 0) {
9311 out2str("sh: turning off NDELAY mode\n");
9322 * Refill the input buffer and return the next input character:
9324 * 1) If a string was pushed back on the input, pop it;
9325 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9326 * or we are reading from a string so we can't refill the buffer,
9328 * 3) If the is more stuff in this buffer, use it else call read to fill it.
9329 * 4) Process input up to the next newline, deleting nul characters.
9331 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9332 #define pgetc_debug(...) ((void)0)
9334 * NB: due to SIT(c) internals (syntax_index_table[] vector),
9335 * pgetc() and related functions must return chars SIGN-EXTENDED into ints,
9336 * not zero-extended. Seems fragile to me. Affects only !USE_SIT_FUNCTION case,
9337 * so we can fix it by ditching !USE_SIT_FUNCTION if Unicode requires that.
9345 while (g_parsefile->strpush) {
9346 #if ENABLE_ASH_ALIAS
9347 if (g_parsefile->left_in_line == -1
9348 && g_parsefile->strpush->ap
9349 && g_parsefile->next_to_pgetc[-1] != ' '
9350 && g_parsefile->next_to_pgetc[-1] != '\t'
9352 pgetc_debug("preadbuffer PEOA");
9357 /* try "pgetc" now: */
9358 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9359 g_parsefile->left_in_line,
9360 g_parsefile->next_to_pgetc,
9361 g_parsefile->next_to_pgetc);
9362 if (--g_parsefile->left_in_line >= 0)
9363 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9365 /* on both branches above g_parsefile->left_in_line < 0.
9366 * "pgetc" needs refilling.
9369 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9370 * pungetc() may increment it a few times.
9371 * Assuming it won't increment it to less than -90.
9373 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9374 pgetc_debug("preadbuffer PEOF1");
9375 /* even in failure keep left_in_line and next_to_pgetc
9376 * in lock step, for correct multi-layer pungetc.
9377 * left_in_line was decremented before preadbuffer(),
9378 * must inc next_to_pgetc: */
9379 g_parsefile->next_to_pgetc++;
9383 more = g_parsefile->left_in_buffer;
9385 flush_stdout_stderr();
9389 /* don't try reading again */
9390 g_parsefile->left_in_line = -99;
9391 pgetc_debug("preadbuffer PEOF2");
9392 g_parsefile->next_to_pgetc++;
9397 /* Find out where's the end of line.
9398 * Set g_parsefile->left_in_line
9399 * and g_parsefile->left_in_buffer acordingly.
9400 * NUL chars are deleted.
9402 q = g_parsefile->next_to_pgetc;
9410 memmove(q, q + 1, more);
9414 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9420 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9421 if (g_parsefile->left_in_line < 0)
9426 g_parsefile->left_in_buffer = more;
9431 out2str(g_parsefile->next_to_pgetc);
9435 pgetc_debug("preadbuffer at %d:%p'%s'",
9436 g_parsefile->left_in_line,
9437 g_parsefile->next_to_pgetc,
9438 g_parsefile->next_to_pgetc);
9439 return signed_char2int(*g_parsefile->next_to_pgetc++);
9442 #define pgetc_as_macro() \
9443 (--g_parsefile->left_in_line >= 0 \
9444 ? signed_char2int(*g_parsefile->next_to_pgetc++) \
9451 pgetc_debug("pgetc_fast at %d:%p'%s'",
9452 g_parsefile->left_in_line,
9453 g_parsefile->next_to_pgetc,
9454 g_parsefile->next_to_pgetc);
9455 return pgetc_as_macro();
9458 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9459 #define pgetc_fast() pgetc()
9461 #define pgetc_fast() pgetc_as_macro()
9465 * Same as pgetc(), but ignores PEOA.
9467 #if ENABLE_ASH_ALIAS
9473 pgetc_debug("pgetc_fast at %d:%p'%s'",
9474 g_parsefile->left_in_line,
9475 g_parsefile->next_to_pgetc,
9476 g_parsefile->next_to_pgetc);
9478 } while (c == PEOA);
9482 #define pgetc2() pgetc()
9486 * Read a line from the script.
9489 pfgets(char *line, int len)
9495 while (--nleft > 0) {
9511 * Undo the last call to pgetc. Only one character may be pushed back.
9512 * PEOF may be pushed back.
9517 g_parsefile->left_in_line++;
9518 g_parsefile->next_to_pgetc--;
9519 pgetc_debug("pushed back to %d:%p'%s'",
9520 g_parsefile->left_in_line,
9521 g_parsefile->next_to_pgetc,
9522 g_parsefile->next_to_pgetc);
9526 * To handle the "." command, a stack of input files is used. Pushfile
9527 * adds a new entry to the stack and popfile restores the previous level.
9532 struct parsefile *pf;
9534 pf = ckzalloc(sizeof(*pf));
9535 pf->prev = g_parsefile;
9537 /*pf->strpush = NULL; - ckzalloc did it */
9538 /*pf->basestrpush.prev = NULL;*/
9545 struct parsefile *pf = g_parsefile;
9553 g_parsefile = pf->prev;
9559 * Return to top level.
9564 while (g_parsefile != &basepf)
9569 * Close the file(s) that the shell is reading commands from. Called
9570 * after a fork is done.
9576 if (g_parsefile->fd > 0) {
9577 close(g_parsefile->fd);
9578 g_parsefile->fd = 0;
9583 * Like setinputfile, but takes an open file descriptor. Call this with
9587 setinputfd(int fd, int push)
9589 close_on_exec_on(fd);
9592 g_parsefile->buf = NULL;
9594 g_parsefile->fd = fd;
9595 if (g_parsefile->buf == NULL)
9596 g_parsefile->buf = ckmalloc(IBUFSIZ);
9597 g_parsefile->left_in_buffer = 0;
9598 g_parsefile->left_in_line = 0;
9599 g_parsefile->linno = 1;
9603 * Set the input to take input from a file. If push is set, push the
9604 * old input onto the stack first.
9607 setinputfile(const char *fname, int flags)
9613 fd = open(fname, O_RDONLY);
9615 if (flags & INPUT_NOFILE_OK)
9617 ash_msg_and_raise_error("can't open '%s'", fname);
9620 fd2 = copyfd(fd, 10);
9623 ash_msg_and_raise_error("out of file descriptors");
9626 setinputfd(fd, flags & INPUT_PUSH_FILE);
9633 * Like setinputfile, but takes input from a string.
9636 setinputstring(char *string)
9640 g_parsefile->next_to_pgetc = string;
9641 g_parsefile->left_in_line = strlen(string);
9642 g_parsefile->buf = NULL;
9643 g_parsefile->linno = 1;
9648 /* ============ mail.c
9650 * Routines to check for mail.
9655 #define MAXMBOXES 10
9657 /* times of mailboxes */
9658 static time_t mailtime[MAXMBOXES];
9659 /* Set if MAIL or MAILPATH is changed. */
9660 static smallint mail_var_path_changed;
9663 * Print appropriate message(s) if mail has arrived.
9664 * If mail_var_path_changed is set,
9665 * then the value of MAIL has mail_var_path_changed,
9666 * so we just update the values.
9675 struct stackmark smark;
9678 setstackmark(&smark);
9679 mpath = mpathset() ? mpathval() : mailval();
9680 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9681 p = padvance(&mpath, nullstr);
9686 for (q = p; *q; q++)
9692 q[-1] = '\0'; /* delete trailing '/' */
9693 if (stat(p, &statb) < 0) {
9697 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9700 pathopt ? pathopt : "you have mail"
9703 *mtp = statb.st_mtime;
9705 mail_var_path_changed = 0;
9706 popstackmark(&smark);
9710 changemail(const char *val UNUSED_PARAM)
9712 mail_var_path_changed = 1;
9715 #endif /* ASH_MAIL */
9718 /* ============ ??? */
9721 * Set the shell parameters.
9724 setparam(char **argv)
9730 for (nparam = 0; argv[nparam]; nparam++)
9732 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9734 *ap++ = ckstrdup(*argv++);
9737 freeparam(&shellparam);
9738 shellparam.malloced = 1;
9739 shellparam.nparam = nparam;
9740 shellparam.p = newparam;
9741 #if ENABLE_ASH_GETOPTS
9742 shellparam.optind = 1;
9743 shellparam.optoff = -1;
9748 * Process shell options. The global variable argptr contains a pointer
9749 * to the argument list; we advance it past the options.
9751 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9752 * For a non-interactive shell, an error condition encountered
9753 * by a special built-in ... shall cause the shell to write a diagnostic message
9754 * to standard error and exit as shown in the following table:
9755 * Error Special Built-In
9757 * Utility syntax error (option or operand error) Shall exit
9759 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9760 * we see that bash does not do that (set "finishes" with error code 1 instead,
9761 * and shell continues), and people rely on this behavior!
9763 * set -o barfoo 2>/dev/null
9766 * Oh well. Let's mimic that.
9769 plus_minus_o(char *name, int val)
9774 for (i = 0; i < NOPTS; i++) {
9775 if (strcmp(name, optnames(i)) == 0) {
9780 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9783 for (i = 0; i < NOPTS; i++) {
9785 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9787 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9793 setoption(int flag, int val)
9797 for (i = 0; i < NOPTS; i++) {
9798 if (optletters(i) == flag) {
9803 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9807 options(int cmdline)
9815 while ((p = *argptr) != NULL) {
9817 if (c != '-' && c != '+')
9820 val = 0; /* val = 0 if c == '+' */
9823 if (p[0] == '\0' || LONE_DASH(p)) {
9825 /* "-" means turn off -x and -v */
9828 /* "--" means reset params */
9829 else if (*argptr == NULL)
9832 break; /* "-" or "--" terminates options */
9835 /* first char was + or - */
9836 while ((c = *p++) != '\0') {
9837 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9838 if (c == 'c' && cmdline) {
9839 minusc = p; /* command is after shell args */
9840 } else if (c == 'o') {
9841 if (plus_minus_o(*argptr, val)) {
9842 /* it already printed err message */
9843 return 1; /* error */
9847 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9849 /* bash does not accept +-login, we also won't */
9850 } else if (cmdline && val && (c == '-')) { /* long options */
9851 if (strcmp(p, "login") == 0)
9863 * The shift builtin command.
9866 shiftcmd(int argc UNUSED_PARAM, char **argv)
9873 n = number(argv[1]);
9874 if (n > shellparam.nparam)
9875 n = 0; /* bash compat, was = shellparam.nparam; */
9877 shellparam.nparam -= n;
9878 for (ap1 = shellparam.p; --n >= 0; ap1++) {
9879 if (shellparam.malloced)
9883 while ((*ap2++ = *ap1++) != NULL)
9885 #if ENABLE_ASH_GETOPTS
9886 shellparam.optind = 1;
9887 shellparam.optoff = -1;
9894 * POSIX requires that 'set' (but not export or readonly) output the
9895 * variables in lexicographic order - by the locale's collating order (sigh).
9896 * Maybe we could keep them in an ordered balanced binary tree
9897 * instead of hashed lists.
9898 * For now just roll 'em through qsort for printing...
9901 showvars(const char *sep_prefix, int on, int off)
9906 ep = listvars(on, off, &epend);
9907 qsort(ep, epend - ep, sizeof(char *), vpcmp);
9909 sep = *sep_prefix ? " " : sep_prefix;
9911 for (; ep < epend; ep++) {
9915 p = strchrnul(*ep, '=');
9918 q = single_quote(++p);
9919 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
9925 * The set command builtin.
9928 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9933 return showvars(nullstr, 0, VUNSET);
9936 if (!options(0)) { /* if no parse error... */
9939 if (*argptr != NULL) {
9947 #if ENABLE_ASH_RANDOM_SUPPORT
9949 change_random(const char *value)
9951 /* Galois LFSR parameter */
9952 /* Taps at 32 31 29 1: */
9953 enum { MASK = 0x8000000b };
9954 /* Another example - taps at 32 31 30 10: */
9955 /* MASK = 0x00400007 */
9957 if (value == NULL) {
9958 /* "get", generate */
9961 /* LCG has period of 2^32 and alternating lowest bit */
9962 random_LCG = 1664525 * random_LCG + 1013904223;
9963 /* Galois LFSR has period of 2^32-1 = 3 * 5 * 17 * 257 * 65537 */
9964 t = (random_galois_LFSR << 1);
9965 if (random_galois_LFSR < 0) /* if we just shifted 1 out of msb... */
9967 random_galois_LFSR = t;
9968 /* Both are weak, combining them gives better randomness
9969 * and ~2^64 period. & 0x7fff is probably bash compat
9970 * for $RANDOM range. Combining with subtraction is
9971 * just for fun. + and ^ would work equally well. */
9972 t = (t - random_LCG) & 0x7fff;
9973 /* set without recursion */
9974 setvar(vrandom.text, utoa(t), VNOFUNC);
9975 vrandom.flags &= ~VNOFUNC;
9978 random_galois_LFSR = random_LCG = strtoul(value, (char **)NULL, 10);
9983 #if ENABLE_ASH_GETOPTS
9985 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
9994 if (*param_optind < 1)
9996 optnext = optfirst + *param_optind - 1;
9998 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10001 p = optnext[-1] + *optoff;
10002 if (p == NULL || *p == '\0') {
10003 /* Current word is done, advance */
10005 if (p == NULL || *p != '-' || *++p == '\0') {
10012 if (LONE_DASH(p)) /* check for "--" */
10017 for (q = optstr; *q != c;) {
10019 if (optstr[0] == ':') {
10022 err |= setvarsafe("OPTARG", s, 0);
10024 fprintf(stderr, "Illegal option -%c\n", c);
10025 unsetvar("OPTARG");
10035 if (*p == '\0' && (p = *optnext) == NULL) {
10036 if (optstr[0] == ':') {
10039 err |= setvarsafe("OPTARG", s, 0);
10042 fprintf(stderr, "No arg for -%c option\n", c);
10043 unsetvar("OPTARG");
10051 err |= setvarsafe("OPTARG", p, 0);
10054 err |= setvarsafe("OPTARG", nullstr, 0);
10056 *optoff = p ? p - *(optnext - 1) : -1;
10057 *param_optind = optnext - optfirst + 1;
10058 fmtstr(s, sizeof(s), "%d", *param_optind);
10059 err |= setvarsafe("OPTIND", s, VNOFUNC);
10062 err |= setvarsafe(optvar, s, 0);
10066 flush_stdout_stderr();
10067 raise_exception(EXERROR);
10073 * The getopts builtin. Shellparam.optnext points to the next argument
10074 * to be processed. Shellparam.optptr points to the next character to
10075 * be processed in the current argument. If shellparam.optnext is NULL,
10076 * then it's the first time getopts has been called.
10079 getoptscmd(int argc, char **argv)
10084 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10086 optbase = shellparam.p;
10087 if (shellparam.optind > shellparam.nparam + 1) {
10088 shellparam.optind = 1;
10089 shellparam.optoff = -1;
10092 optbase = &argv[3];
10093 if (shellparam.optind > argc - 2) {
10094 shellparam.optind = 1;
10095 shellparam.optoff = -1;
10099 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10100 &shellparam.optoff);
10102 #endif /* ASH_GETOPTS */
10105 /* ============ Shell parser */
10108 struct heredoc *next; /* next here document in list */
10109 union node *here; /* redirection node */
10110 char *eofmark; /* string indicating end of input */
10111 smallint striptabs; /* if set, strip leading tabs */
10114 static smallint tokpushback; /* last token pushed back */
10115 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10116 static smallint quoteflag; /* set if (part of) last token was quoted */
10117 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10118 static struct heredoc *heredoclist; /* list of here documents to read */
10119 static char *wordtext; /* text of last word returned by readtoken */
10120 static struct nodelist *backquotelist;
10121 static union node *redirnode;
10122 static struct heredoc *heredoc;
10124 * NEOF is returned by parsecmd when it encounters an end of file. It
10125 * must be distinct from NULL, so we use the address of a variable that
10126 * happens to be handy.
10128 #define NEOF ((union node *)&tokpushback)
10130 static void raise_error_syntax(const char *) NORETURN;
10132 raise_error_syntax(const char *msg)
10134 ash_msg_and_raise_error("syntax error: %s", msg);
10139 * Called when an unexpected token is read during the parse. The argument
10140 * is the token that is expected, or -1 if more than one type of token can
10141 * occur at this point.
10143 static void raise_error_unexpected_syntax(int) NORETURN;
10145 raise_error_unexpected_syntax(int token)
10150 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
10152 sprintf(msg + l, " (expecting %s)", tokname(token));
10153 raise_error_syntax(msg);
10157 #define EOFMARKLEN 79
10159 /* parsing is heavily cross-recursive, need these forward decls */
10160 static union node *andor(void);
10161 static union node *pipeline(void);
10162 static union node *parse_command(void);
10163 static void parseheredoc(void);
10164 static char peektoken(void);
10165 static int readtoken(void);
10167 static union node *
10170 union node *n1, *n2, *n3;
10173 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10174 if (nlflag == 2 && peektoken())
10180 if (tok == TBACKGND) {
10181 if (n2->type == NPIPE) {
10182 n2->npipe.pipe_backgnd = 1;
10184 if (n2->type != NREDIR) {
10185 n3 = stzalloc(sizeof(struct nredir));
10187 /*n3->nredir.redirect = NULL; - stzalloc did it */
10190 n2->type = NBACKGND;
10196 n3 = stzalloc(sizeof(struct nbinary));
10198 n3->nbinary.ch1 = n1;
10199 n3->nbinary.ch2 = n2;
10215 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10223 pungetc(); /* push back EOF on input */
10227 raise_error_unexpected_syntax(-1);
10234 static union node *
10237 union node *n1, *n2, *n3;
10245 } else if (t == TOR) {
10251 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10253 n3 = stzalloc(sizeof(struct nbinary));
10255 n3->nbinary.ch1 = n1;
10256 n3->nbinary.ch2 = n2;
10261 static union node *
10264 union node *n1, *n2, *pipenode;
10265 struct nodelist *lp, *prev;
10269 TRACE(("pipeline: entered\n"));
10270 if (readtoken() == TNOT) {
10272 checkkwd = CHKKWD | CHKALIAS;
10275 n1 = parse_command();
10276 if (readtoken() == TPIPE) {
10277 pipenode = stzalloc(sizeof(struct npipe));
10278 pipenode->type = NPIPE;
10279 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10280 lp = stzalloc(sizeof(struct nodelist));
10281 pipenode->npipe.cmdlist = lp;
10285 lp = stzalloc(sizeof(struct nodelist));
10286 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10287 lp->n = parse_command();
10289 } while (readtoken() == TPIPE);
10295 n2 = stzalloc(sizeof(struct nnot));
10303 static union node *
10308 n = stzalloc(sizeof(struct narg));
10310 /*n->narg.next = NULL; - stzalloc did it */
10311 n->narg.text = wordtext;
10312 n->narg.backquote = backquotelist;
10317 fixredir(union node *n, const char *text, int err)
10321 TRACE(("Fix redir %s %d\n", text, err));
10323 n->ndup.vname = NULL;
10325 fd = bb_strtou(text, NULL, 10);
10326 if (!errno && fd >= 0)
10327 n->ndup.dupfd = fd;
10328 else if (LONE_DASH(text))
10329 n->ndup.dupfd = -1;
10332 raise_error_syntax("bad fd number");
10333 n->ndup.vname = makename();
10338 * Returns true if the text contains nothing to expand (no dollar signs
10342 noexpand(const char *text)
10348 while ((c = *p++) != '\0') {
10349 if (c == CTLQUOTEMARK)
10353 else if (SIT((signed char)c, BASESYNTAX) == CCTL)
10362 union node *n = redirnode;
10364 if (readtoken() != TWORD)
10365 raise_error_unexpected_syntax(-1);
10366 if (n->type == NHERE) {
10367 struct heredoc *here = heredoc;
10371 if (quoteflag == 0)
10373 TRACE(("Here document %d\n", n->type));
10374 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10375 raise_error_syntax("illegal eof marker for << redirection");
10376 rmescapes(wordtext);
10377 here->eofmark = wordtext;
10379 if (heredoclist == NULL)
10380 heredoclist = here;
10382 for (p = heredoclist; p->next; p = p->next)
10386 } else if (n->type == NTOFD || n->type == NFROMFD) {
10387 fixredir(n, wordtext, 0);
10389 n->nfile.fname = makename();
10393 static union node *
10396 union node *args, **app;
10397 union node *n = NULL;
10398 union node *vars, **vpp;
10399 union node **rpp, *redir;
10401 #if ENABLE_ASH_BASH_COMPAT
10402 smallint double_brackets_flag = 0;
10412 savecheckkwd = CHKALIAS;
10415 checkkwd = savecheckkwd;
10418 #if ENABLE_ASH_BASH_COMPAT
10419 case TAND: /* "&&" */
10420 case TOR: /* "||" */
10421 if (!double_brackets_flag) {
10425 wordtext = (char *) (t == TAND ? "-a" : "-o");
10428 n = stzalloc(sizeof(struct narg));
10430 /*n->narg.next = NULL; - stzalloc did it */
10431 n->narg.text = wordtext;
10432 #if ENABLE_ASH_BASH_COMPAT
10433 if (strcmp("[[", wordtext) == 0)
10434 double_brackets_flag = 1;
10435 else if (strcmp("]]", wordtext) == 0)
10436 double_brackets_flag = 0;
10438 n->narg.backquote = backquotelist;
10439 if (savecheckkwd && isassignment(wordtext)) {
10441 vpp = &n->narg.next;
10444 app = &n->narg.next;
10449 *rpp = n = redirnode;
10450 rpp = &n->nfile.next;
10451 parsefname(); /* read name of redirection file */
10454 if (args && app == &args->narg.next
10457 struct builtincmd *bcmd;
10460 /* We have a function */
10461 if (readtoken() != TRP)
10462 raise_error_unexpected_syntax(TRP);
10463 name = n->narg.text;
10464 if (!goodname(name)
10465 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10467 raise_error_syntax("bad function name");
10470 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10471 n->narg.next = parse_command();
10484 n = stzalloc(sizeof(struct ncmd));
10486 n->ncmd.args = args;
10487 n->ncmd.assign = vars;
10488 n->ncmd.redirect = redir;
10492 static union node *
10493 parse_command(void)
10495 union node *n1, *n2;
10496 union node *ap, **app;
10497 union node *cp, **cpp;
10498 union node *redir, **rpp;
10505 switch (readtoken()) {
10507 raise_error_unexpected_syntax(-1);
10510 n1 = stzalloc(sizeof(struct nif));
10512 n1->nif.test = list(0);
10513 if (readtoken() != TTHEN)
10514 raise_error_unexpected_syntax(TTHEN);
10515 n1->nif.ifpart = list(0);
10517 while (readtoken() == TELIF) {
10518 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10519 n2 = n2->nif.elsepart;
10521 n2->nif.test = list(0);
10522 if (readtoken() != TTHEN)
10523 raise_error_unexpected_syntax(TTHEN);
10524 n2->nif.ifpart = list(0);
10526 if (lasttoken == TELSE)
10527 n2->nif.elsepart = list(0);
10529 n2->nif.elsepart = NULL;
10537 n1 = stzalloc(sizeof(struct nbinary));
10538 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10539 n1->nbinary.ch1 = list(0);
10542 TRACE(("expecting DO got %s %s\n", tokname(got),
10543 got == TWORD ? wordtext : ""));
10544 raise_error_unexpected_syntax(TDO);
10546 n1->nbinary.ch2 = list(0);
10551 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10552 raise_error_syntax("bad for loop variable");
10553 n1 = stzalloc(sizeof(struct nfor));
10555 n1->nfor.var = wordtext;
10556 checkkwd = CHKKWD | CHKALIAS;
10557 if (readtoken() == TIN) {
10559 while (readtoken() == TWORD) {
10560 n2 = stzalloc(sizeof(struct narg));
10562 /*n2->narg.next = NULL; - stzalloc did it */
10563 n2->narg.text = wordtext;
10564 n2->narg.backquote = backquotelist;
10566 app = &n2->narg.next;
10569 n1->nfor.args = ap;
10570 if (lasttoken != TNL && lasttoken != TSEMI)
10571 raise_error_unexpected_syntax(-1);
10573 n2 = stzalloc(sizeof(struct narg));
10575 /*n2->narg.next = NULL; - stzalloc did it */
10576 n2->narg.text = (char *)dolatstr;
10577 /*n2->narg.backquote = NULL;*/
10578 n1->nfor.args = n2;
10580 * Newline or semicolon here is optional (but note
10581 * that the original Bourne shell only allowed NL).
10583 if (lasttoken != TNL && lasttoken != TSEMI)
10586 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10587 if (readtoken() != TDO)
10588 raise_error_unexpected_syntax(TDO);
10589 n1->nfor.body = list(0);
10593 n1 = stzalloc(sizeof(struct ncase));
10595 if (readtoken() != TWORD)
10596 raise_error_unexpected_syntax(TWORD);
10597 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10599 /*n2->narg.next = NULL; - stzalloc did it */
10600 n2->narg.text = wordtext;
10601 n2->narg.backquote = backquotelist;
10603 checkkwd = CHKKWD | CHKALIAS;
10604 } while (readtoken() == TNL);
10605 if (lasttoken != TIN)
10606 raise_error_unexpected_syntax(TIN);
10607 cpp = &n1->ncase.cases;
10609 checkkwd = CHKNL | CHKKWD;
10611 while (t != TESAC) {
10612 if (lasttoken == TLP)
10614 *cpp = cp = stzalloc(sizeof(struct nclist));
10616 app = &cp->nclist.pattern;
10618 *app = ap = stzalloc(sizeof(struct narg));
10620 /*ap->narg.next = NULL; - stzalloc did it */
10621 ap->narg.text = wordtext;
10622 ap->narg.backquote = backquotelist;
10623 if (readtoken() != TPIPE)
10625 app = &ap->narg.next;
10628 //ap->narg.next = NULL;
10629 if (lasttoken != TRP)
10630 raise_error_unexpected_syntax(TRP);
10631 cp->nclist.body = list(2);
10633 cpp = &cp->nclist.next;
10635 checkkwd = CHKNL | CHKKWD;
10639 raise_error_unexpected_syntax(TENDCASE);
10646 n1 = stzalloc(sizeof(struct nredir));
10647 n1->type = NSUBSHELL;
10648 n1->nredir.n = list(0);
10649 /*n1->nredir.redirect = NULL; - stzalloc did it */
10659 return simplecmd();
10662 if (readtoken() != t)
10663 raise_error_unexpected_syntax(t);
10666 /* Now check for redirection which may follow command */
10667 checkkwd = CHKKWD | CHKALIAS;
10669 while (readtoken() == TREDIR) {
10670 *rpp = n2 = redirnode;
10671 rpp = &n2->nfile.next;
10677 if (n1->type != NSUBSHELL) {
10678 n2 = stzalloc(sizeof(struct nredir));
10683 n1->nredir.redirect = redir;
10688 #if ENABLE_ASH_BASH_COMPAT
10689 static int decode_dollar_squote(void)
10691 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10697 p = strchr(C_escapes, c);
10702 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10706 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10708 } else if (c == 'x') { /* \xHH */
10712 } while (isxdigit(c) && --cnt);
10714 if (cnt == 3) { /* \x but next char is "bad" */
10718 } else { /* simple seq like \\ or \t */
10723 c = bb_process_escape_sequence((void*)&p);
10724 } else { /* unrecognized "\z": print both chars unless ' or " */
10725 if (c != '\'' && c != '"') {
10727 c |= 0x100; /* "please encode \, then me" */
10735 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10736 * is not NULL, read a here document. In the latter case, eofmark is the
10737 * word which marks the end of the document and striptabs is true if
10738 * leading tabs should be stripped from the document. The argument firstc
10739 * is the first character of the input token or document.
10741 * Because C does not have internal subroutines, I have simulated them
10742 * using goto's to implement the subroutine linkage. The following macros
10743 * will run code that appears at the end of readtoken1.
10745 #define CHECKEND() {goto checkend; checkend_return:;}
10746 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10747 #define PARSESUB() {goto parsesub; parsesub_return:;}
10748 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10749 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10750 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10752 readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
10754 /* NB: syntax parameter fits into smallint */
10758 char line[EOFMARKLEN + 1];
10759 struct nodelist *bqlist;
10763 smallint prevsyntax; /* syntax before arithmetic */
10764 #if ENABLE_ASH_EXPAND_PRMT
10765 smallint pssyntax; /* we are expanding a prompt string */
10767 int varnest; /* levels of variables expansion */
10768 int arinest; /* levels of arithmetic expansion */
10769 int parenlevel; /* levels of parens in arithmetic */
10770 int dqvarnest; /* levels of variables expansion within double quotes */
10772 USE_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10775 /* Avoid longjmp clobbering */
10781 (void) &parenlevel;
10784 (void) &prevsyntax;
10787 startlinno = g_parsefile->linno;
10792 #if ENABLE_ASH_EXPAND_PRMT
10793 pssyntax = (syntax == PSSYNTAX);
10797 dblquote = (syntax == DQSYNTAX);
10803 STARTSTACKSTR(out);
10805 /* For each line, until end of word */
10807 CHECKEND(); /* set c to PEOF if at end of here document */
10808 for (;;) { /* until end of line or end of word */
10809 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10810 switch (SIT(c, syntax)) {
10811 case CNL: /* '\n' */
10812 if (syntax == BASESYNTAX)
10813 goto endword; /* exit outer loop */
10815 g_parsefile->linno++;
10819 goto loop; /* continue outer loop */
10824 if (eofmark == NULL || dblquote)
10825 USTPUTC(CTLESC, out);
10826 #if ENABLE_ASH_BASH_COMPAT
10827 if (c == '\\' && bash_dollar_squote) {
10828 c = decode_dollar_squote();
10830 USTPUTC('\\', out);
10831 c = (unsigned char)c;
10837 case CBACK: /* backslash */
10840 USTPUTC(CTLESC, out);
10841 USTPUTC('\\', out);
10843 } else if (c == '\n') {
10847 #if ENABLE_ASH_EXPAND_PRMT
10848 if (c == '$' && pssyntax) {
10849 USTPUTC(CTLESC, out);
10850 USTPUTC('\\', out);
10853 if (dblquote && c != '\\'
10854 && c != '`' && c != '$'
10855 && (c != '"' || eofmark != NULL)
10857 USTPUTC(CTLESC, out);
10858 USTPUTC('\\', out);
10860 if (SIT(c, SQSYNTAX) == CCTL)
10861 USTPUTC(CTLESC, out);
10869 if (eofmark == NULL) {
10870 USTPUTC(CTLQUOTEMARK, out);
10878 USE_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
10879 if (eofmark != NULL && arinest == 0
10884 if (dqvarnest == 0) {
10885 syntax = BASESYNTAX;
10892 case CVAR: /* '$' */
10893 PARSESUB(); /* parse substitution */
10895 case CENDVAR: /* '}' */
10898 if (dqvarnest > 0) {
10901 USTPUTC(CTLENDVAR, out);
10906 #if ENABLE_SH_MATH_SUPPORT
10907 case CLP: /* '(' in arithmetic */
10911 case CRP: /* ')' in arithmetic */
10912 if (parenlevel > 0) {
10916 if (pgetc() == ')') {
10917 if (--arinest == 0) {
10918 USTPUTC(CTLENDARI, out);
10919 syntax = prevsyntax;
10920 dblquote = (syntax == DQSYNTAX);
10925 * unbalanced parens
10926 * (don't 2nd guess - no error)
10934 case CBQUOTE: /* '`' */
10938 goto endword; /* exit outer loop */
10942 if (varnest == 0) {
10943 #if ENABLE_ASH_BASH_COMPAT
10945 if (pgetc() == '>')
10946 c = 0x100 + '>'; /* flag &> */
10950 goto endword; /* exit outer loop */
10952 #if ENABLE_ASH_ALIAS
10962 #if ENABLE_SH_MATH_SUPPORT
10963 if (syntax == ARISYNTAX)
10964 raise_error_syntax("missing '))'");
10966 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
10967 raise_error_syntax("unterminated quoted string");
10968 if (varnest != 0) {
10969 startlinno = g_parsefile->linno;
10971 raise_error_syntax("missing '}'");
10973 USTPUTC('\0', out);
10974 len = out - (char *)stackblock();
10975 out = stackblock();
10976 if (eofmark == NULL) {
10977 if ((c == '>' || c == '<' USE_ASH_BASH_COMPAT( || c == 0x100 + '>'))
10980 if (isdigit_str9(out)) {
10981 PARSEREDIR(); /* passed as params: out, c */
10982 lasttoken = TREDIR;
10985 /* else: non-number X seen, interpret it
10986 * as "NNNX>file" = "NNNX >file" */
10990 quoteflag = quotef;
10991 backquotelist = bqlist;
10992 grabstackblock(len);
10996 /* end of readtoken routine */
10999 * Check to see whether we are at the end of the here document. When this
11000 * is called, c is set to the first character of the next input line. If
11001 * we are at the end of the here document, this routine sets the c to PEOF.
11005 #if ENABLE_ASH_ALIAS
11011 while (c == '\t') {
11015 if (c == *eofmark) {
11016 if (pfgets(line, sizeof(line)) != NULL) {
11020 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11022 if (*p == '\n' && *q == '\0') {
11024 g_parsefile->linno++;
11025 needprompt = doprompt;
11027 pushstring(line, NULL);
11032 goto checkend_return;
11036 * Parse a redirection operator. The variable "out" points to a string
11037 * specifying the fd to be redirected. The variable "c" contains the
11038 * first character of the redirection operator.
11041 /* out is already checked to be a valid number or "" */
11042 int fd = (*out == '\0' ? -1 : atoi(out));
11045 np = stzalloc(sizeof(struct nfile));
11050 np->type = NAPPEND;
11052 np->type = NCLOBBER;
11055 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11061 #if ENABLE_ASH_BASH_COMPAT
11062 else if (c == 0x100 + '>') { /* this flags &> redirection */
11064 pgetc(); /* this is '>', no need to check */
11068 else { /* c == '<' */
11069 /*np->nfile.fd = 0; - stzalloc did it */
11073 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11074 np = stzalloc(sizeof(struct nhere));
11075 /*np->nfile.fd = 0; - stzalloc did it */
11078 heredoc = stzalloc(sizeof(struct heredoc));
11079 heredoc->here = np;
11082 heredoc->striptabs = 1;
11084 /*heredoc->striptabs = 0; - stzalloc did it */
11090 np->type = NFROMFD;
11094 np->type = NFROMTO;
11106 goto parseredir_return;
11110 * Parse a substitution. At this point, we have read the dollar sign
11111 * and nothing else.
11114 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11115 * (assuming ascii char codes, as the original implementation did) */
11116 #define is_special(c) \
11117 (((unsigned)(c) - 33 < 32) \
11118 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11124 static const char types[] ALIGN1 = "}-+?=";
11127 if (c <= PEOA_OR_PEOF
11128 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11130 #if ENABLE_ASH_BASH_COMPAT
11132 bash_dollar_squote = 1;
11137 } else if (c == '(') { /* $(command) or $((arith)) */
11138 if (pgetc() == '(') {
11139 #if ENABLE_SH_MATH_SUPPORT
11142 raise_error_syntax("you disabled math support for $((arith)) syntax");
11149 USTPUTC(CTLVAR, out);
11150 typeloc = out - (char *)stackblock();
11151 USTPUTC(VSNORMAL, out);
11152 subtype = VSNORMAL;
11160 subtype = VSLENGTH;
11164 if (c > PEOA_OR_PEOF && is_name(c)) {
11168 } while (c > PEOA_OR_PEOF && is_in_name(c));
11169 } else if (isdigit(c)) {
11173 } while (isdigit(c));
11174 } else if (is_special(c)) {
11179 raise_error_syntax("bad substitution");
11184 if (subtype == 0) {
11188 #if ENABLE_ASH_BASH_COMPAT
11189 if (c == ':' || c == '$' || isdigit(c)) {
11191 subtype = VSSUBSTR;
11198 p = strchr(types, c);
11201 subtype = p - types + VSNORMAL;
11206 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11214 #if ENABLE_ASH_BASH_COMPAT
11216 subtype = VSREPLACE;
11219 subtype++; /* VSREPLACEALL */
11228 if (dblquote || arinest)
11230 *((char *)stackblock() + typeloc) = subtype | flags;
11231 if (subtype != VSNORMAL) {
11233 if (dblquote || arinest) {
11238 goto parsesub_return;
11242 * Called to parse command substitutions. Newstyle is set if the command
11243 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11244 * list of commands (passed by reference), and savelen is the number of
11245 * characters on the top of the stack which must be preserved.
11248 struct nodelist **nlpp;
11251 char *volatile str;
11252 struct jmploc jmploc;
11253 struct jmploc *volatile savehandler;
11255 smallint saveprompt = 0;
11258 (void) &saveprompt;
11260 savepbq = parsebackquote;
11261 if (setjmp(jmploc.loc)) {
11263 parsebackquote = 0;
11264 exception_handler = savehandler;
11265 longjmp(exception_handler->loc, 1);
11269 savelen = out - (char *)stackblock();
11271 str = ckmalloc(savelen);
11272 memcpy(str, stackblock(), savelen);
11274 savehandler = exception_handler;
11275 exception_handler = &jmploc;
11278 /* We must read until the closing backquote, giving special
11279 treatment to some slashes, and then push the string and
11280 reread it as input, interpreting it normally. */
11287 STARTSTACKSTR(pout);
11300 g_parsefile->linno++;
11304 * If eating a newline, avoid putting
11305 * the newline into the new character
11306 * stream (via the STPUTC after the
11311 if (pc != '\\' && pc != '`' && pc != '$'
11312 && (!dblquote || pc != '"'))
11313 STPUTC('\\', pout);
11314 if (pc > PEOA_OR_PEOF) {
11320 #if ENABLE_ASH_ALIAS
11323 startlinno = g_parsefile->linno;
11324 raise_error_syntax("EOF in backquote substitution");
11327 g_parsefile->linno++;
11328 needprompt = doprompt;
11337 STPUTC('\0', pout);
11338 psavelen = pout - (char *)stackblock();
11339 if (psavelen > 0) {
11340 pstr = grabstackstr(pout);
11341 setinputstring(pstr);
11346 nlpp = &(*nlpp)->next;
11347 *nlpp = stzalloc(sizeof(**nlpp));
11348 /* (*nlpp)->next = NULL; - stzalloc did it */
11349 parsebackquote = oldstyle;
11352 saveprompt = doprompt;
11359 doprompt = saveprompt;
11360 else if (readtoken() != TRP)
11361 raise_error_unexpected_syntax(TRP);
11366 * Start reading from old file again, ignoring any pushed back
11367 * tokens left from the backquote parsing
11372 while (stackblocksize() <= savelen)
11374 STARTSTACKSTR(out);
11376 memcpy(out, str, savelen);
11377 STADJUST(savelen, out);
11383 parsebackquote = savepbq;
11384 exception_handler = savehandler;
11385 if (arinest || dblquote)
11386 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11388 USTPUTC(CTLBACKQ, out);
11390 goto parsebackq_oldreturn;
11391 goto parsebackq_newreturn;
11394 #if ENABLE_SH_MATH_SUPPORT
11396 * Parse an arithmetic expansion (indicate start of one and set state)
11399 if (++arinest == 1) {
11400 prevsyntax = syntax;
11401 syntax = ARISYNTAX;
11402 USTPUTC(CTLARI, out);
11409 * we collapse embedded arithmetic expansion to
11410 * parenthesis, which should be equivalent
11414 goto parsearith_return;
11418 } /* end of readtoken */
11421 * Read the next input token.
11422 * If the token is a word, we set backquotelist to the list of cmds in
11423 * backquotes. We set quoteflag to true if any part of the word was
11425 * If the token is TREDIR, then we set redirnode to a structure containing
11427 * In all cases, the variable startlinno is set to the number of the line
11428 * on which the token starts.
11430 * [Change comment: here documents and internal procedures]
11431 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11432 * word parsing code into a separate routine. In this case, readtoken
11433 * doesn't need to have any internal procedures, but parseword does.
11434 * We could also make parseoperator in essence the main routine, and
11435 * have parseword (readtoken1?) handle both words and redirection.]
11437 #define NEW_xxreadtoken
11438 #ifdef NEW_xxreadtoken
11439 /* singles must be first! */
11440 static const char xxreadtoken_chars[7] ALIGN1 = {
11441 '\n', '(', ')', /* singles */
11442 '&', '|', ';', /* doubles */
11446 #define xxreadtoken_singles 3
11447 #define xxreadtoken_doubles 3
11449 static const char xxreadtoken_tokens[] ALIGN1 = {
11450 TNL, TLP, TRP, /* only single occurrence allowed */
11451 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11452 TEOF, /* corresponds to trailing nul */
11453 TAND, TOR, TENDCASE /* if double occurrence */
11468 startlinno = g_parsefile->linno;
11469 for (;;) { /* until token or start of word found */
11471 if (c == ' ' || c == '\t' USE_ASH_ALIAS( || c == PEOA))
11475 while ((c = pgetc()) != '\n' && c != PEOF)
11478 } else if (c == '\\') {
11479 if (pgetc() != '\n') {
11481 break; /* return readtoken1(...) */
11483 startlinno = ++g_parsefile->linno;
11489 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11492 g_parsefile->linno++;
11493 needprompt = doprompt;
11496 p = strchr(xxreadtoken_chars, c);
11498 break; /* return readtoken1(...) */
11500 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11502 if (cc == c) { /* double occurrence? */
11503 p += xxreadtoken_doubles + 1;
11506 #if ENABLE_ASH_BASH_COMPAT
11507 if (c == '&' && cc == '>') /* &> */
11508 break; /* return readtoken1(...) */
11513 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11518 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11520 #else /* old xxreadtoken */
11521 #define RETURN(token) return lasttoken = token
11534 startlinno = g_parsefile->linno;
11535 for (;;) { /* until token or start of word found */
11538 case ' ': case '\t':
11539 #if ENABLE_ASH_ALIAS
11544 while ((c = pgetc()) != '\n' && c != PEOF)
11549 if (pgetc() == '\n') {
11550 startlinno = ++g_parsefile->linno;
11558 g_parsefile->linno++;
11559 needprompt = doprompt;
11564 if (pgetc() == '&')
11569 if (pgetc() == '|')
11574 if (pgetc() == ';')
11587 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11590 #endif /* old xxreadtoken */
11597 smallint alreadyseen = tokpushback;
11600 #if ENABLE_ASH_ALIAS
11609 if (checkkwd & CHKNL) {
11616 if (t != TWORD || quoteflag) {
11621 * check for keywords
11623 if (checkkwd & CHKKWD) {
11624 const char *const *pp;
11626 pp = findkwd(wordtext);
11628 lasttoken = t = pp - tokname_array;
11629 TRACE(("keyword %s recognized\n", tokname(t)));
11634 if (checkkwd & CHKALIAS) {
11635 #if ENABLE_ASH_ALIAS
11637 ap = lookupalias(wordtext, 1);
11640 pushstring(ap->val, ap);
11650 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11652 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11664 return tokname_array[t][0];
11668 * Read and parse a command. Returns NEOF on end of file. (NULL is a
11669 * valid parse tree indicating a blank line.)
11671 static union node *
11672 parsecmd(int interact)
11677 doprompt = interact;
11679 setprompt(doprompt);
11691 * Input any here documents.
11696 struct heredoc *here;
11699 here = heredoclist;
11700 heredoclist = NULL;
11706 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11707 here->eofmark, here->striptabs);
11708 n = stzalloc(sizeof(struct narg));
11709 n->narg.type = NARG;
11710 /*n->narg.next = NULL; - stzalloc did it */
11711 n->narg.text = wordtext;
11712 n->narg.backquote = backquotelist;
11713 here->here->nhere.doc = n;
11720 * called by editline -- any expansions to the prompt should be added here.
11722 #if ENABLE_ASH_EXPAND_PRMT
11723 static const char *
11724 expandstr(const char *ps)
11728 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11729 * and token processing _can_ alter it (delete NULs etc). */
11730 setinputstring((char *)ps);
11731 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11734 n.narg.type = NARG;
11735 n.narg.next = NULL;
11736 n.narg.text = wordtext;
11737 n.narg.backquote = backquotelist;
11739 expandarg(&n, NULL, 0);
11740 return stackblock();
11745 * Execute a command or commands contained in a string.
11748 evalstring(char *s, int mask)
11751 struct stackmark smark;
11755 setstackmark(&smark);
11758 while ((n = parsecmd(0)) != NEOF) {
11760 popstackmark(&smark);
11773 * The eval command.
11776 evalcmd(int argc UNUSED_PARAM, char **argv)
11785 STARTSTACKSTR(concat);
11787 concat = stack_putstr(p, concat);
11791 STPUTC(' ', concat);
11793 STPUTC('\0', concat);
11794 p = grabstackstr(concat);
11796 evalstring(p, ~SKIPEVAL);
11803 * Read and execute commands. "Top" is nonzero for the top level command
11804 * loop; it turns on prompting if the shell is interactive.
11810 struct stackmark smark;
11814 TRACE(("cmdloop(%d) called\n", top));
11818 setstackmark(&smark);
11821 showjobs(stderr, SHOW_CHANGED);
11824 if (iflag && top) {
11826 #if ENABLE_ASH_MAIL
11830 n = parsecmd(inter);
11831 /* showtree(n); DEBUG */
11833 if (!top || numeof >= 50)
11835 if (!stoppedjobs()) {
11838 out2str("\nUse \"exit\" to leave shell.\n");
11841 } else if (nflag == 0) {
11842 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11847 popstackmark(&smark);
11852 return skip & SKIPEVAL;
11859 * Take commands from a file. To be compatible we should do a path
11860 * search for the file, which is necessary to find sub-commands.
11863 find_dot_file(char *name)
11866 const char *path = pathval();
11869 /* don't try this for absolute or relative paths */
11870 if (strchr(name, '/'))
11873 /* IIRC standards do not say whether . is to be searched.
11874 * And it is even smaller this way, making it unconditional for now:
11876 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11881 while ((fullname = padvance(&path, name)) != NULL) {
11883 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11885 * Don't bother freeing here, since it will
11886 * be freed by the caller.
11890 stunalloc(fullname);
11893 /* not found in the PATH */
11894 ash_msg_and_raise_error("%s: not found", name);
11899 dotcmd(int argc, char **argv)
11901 struct strlist *sp;
11902 volatile struct shparam saveparam;
11905 for (sp = cmdenviron; sp; sp = sp->next)
11906 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
11908 if (argv[1]) { /* That's what SVR2 does */
11909 char *fullname = find_dot_file(argv[1]);
11912 if (argc) { /* argc > 0, argv[0] != NULL */
11913 saveparam = shellparam;
11914 shellparam.malloced = 0;
11915 shellparam.nparam = argc;
11916 shellparam.p = argv;
11919 setinputfile(fullname, INPUT_PUSH_FILE);
11920 commandname = fullname;
11925 freeparam(&shellparam);
11926 shellparam = saveparam;
11928 status = exitstatus;
11934 exitcmd(int argc UNUSED_PARAM, char **argv)
11939 exitstatus = number(argv[1]);
11940 raise_exception(EXEXIT);
11945 * Read a file containing shell functions.
11948 readcmdfile(char *name)
11950 setinputfile(name, INPUT_PUSH_FILE);
11956 /* ============ find_command inplementation */
11959 * Resolve a command name. If you change this routine, you may have to
11960 * change the shellexec routine as well.
11963 find_command(char *name, struct cmdentry *entry, int act, const char *path)
11965 struct tblentry *cmdp;
11972 struct builtincmd *bcmd;
11974 /* If name contains a slash, don't use PATH or hash table */
11975 if (strchr(name, '/') != NULL) {
11976 entry->u.index = -1;
11977 if (act & DO_ABS) {
11978 while (stat(name, &statb) < 0) {
11980 if (errno == EINTR)
11983 entry->cmdtype = CMDUNKNOWN;
11987 entry->cmdtype = CMDNORMAL;
11991 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
11993 updatetbl = (path == pathval());
11996 if (strstr(path, "%builtin") != NULL)
11997 act |= DO_ALTBLTIN;
12000 /* If name is in the table, check answer will be ok */
12001 cmdp = cmdlookup(name, 0);
12002 if (cmdp != NULL) {
12005 switch (cmdp->cmdtype) {
12023 } else if (cmdp->rehash == 0)
12024 /* if not invalidated by cd, we're done */
12028 /* If %builtin not in path, check for builtin next */
12029 bcmd = find_builtin(name);
12031 if (IS_BUILTIN_REGULAR(bcmd))
12032 goto builtin_success;
12033 if (act & DO_ALTPATH) {
12034 if (!(act & DO_ALTBLTIN))
12035 goto builtin_success;
12036 } else if (builtinloc <= 0) {
12037 goto builtin_success;
12041 #if ENABLE_FEATURE_SH_STANDALONE
12043 int applet_no = find_applet_by_name(name);
12044 if (applet_no >= 0) {
12045 entry->cmdtype = CMDNORMAL;
12046 entry->u.index = -2 - applet_no;
12052 /* We have to search path. */
12053 prev = -1; /* where to start */
12054 if (cmdp && cmdp->rehash) { /* doing a rehash */
12055 if (cmdp->cmdtype == CMDBUILTIN)
12058 prev = cmdp->param.index;
12064 while ((fullname = padvance(&path, name)) != NULL) {
12065 stunalloc(fullname);
12066 /* NB: code below will still use fullname
12067 * despite it being "unallocated" */
12070 if (prefix(pathopt, "builtin")) {
12072 goto builtin_success;
12075 if ((act & DO_NOFUNC)
12076 || !prefix(pathopt, "func")
12077 ) { /* ignore unimplemented options */
12081 /* if rehash, don't redo absolute path names */
12082 if (fullname[0] == '/' && idx <= prev) {
12085 TRACE(("searchexec \"%s\": no change\n", name));
12088 while (stat(fullname, &statb) < 0) {
12090 if (errno == EINTR)
12093 if (errno != ENOENT && errno != ENOTDIR)
12097 e = EACCES; /* if we fail, this will be the error */
12098 if (!S_ISREG(statb.st_mode))
12100 if (pathopt) { /* this is a %func directory */
12101 stalloc(strlen(fullname) + 1);
12102 /* NB: stalloc will return space pointed by fullname
12103 * (because we don't have any intervening allocations
12104 * between stunalloc above and this stalloc) */
12105 readcmdfile(fullname);
12106 cmdp = cmdlookup(name, 0);
12107 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12108 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12109 stunalloc(fullname);
12112 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12114 entry->cmdtype = CMDNORMAL;
12115 entry->u.index = idx;
12119 cmdp = cmdlookup(name, 1);
12120 cmdp->cmdtype = CMDNORMAL;
12121 cmdp->param.index = idx;
12126 /* We failed. If there was an entry for this command, delete it */
12127 if (cmdp && updatetbl)
12128 delete_cmd_entry();
12130 ash_msg("%s: %s", name, errmsg(e, "not found"));
12131 entry->cmdtype = CMDUNKNOWN;
12136 entry->cmdtype = CMDBUILTIN;
12137 entry->u.cmd = bcmd;
12141 cmdp = cmdlookup(name, 1);
12142 cmdp->cmdtype = CMDBUILTIN;
12143 cmdp->param.cmd = bcmd;
12147 entry->cmdtype = cmdp->cmdtype;
12148 entry->u = cmdp->param;
12152 /* ============ trap.c */
12155 * The trap builtin.
12158 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12167 for (signo = 0; signo < NSIG; signo++) {
12168 if (trap[signo] != NULL) {
12169 out1fmt("trap -- %s %s\n",
12170 single_quote(trap[signo]),
12171 get_signame(signo));
12180 signo = get_signum(*ap);
12182 ash_msg_and_raise_error("%s: bad trap", *ap);
12185 if (LONE_DASH(action))
12188 action = ckstrdup(action);
12191 trap[signo] = action;
12201 /* ============ Builtins */
12203 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12205 * Lists available builtins
12208 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12213 out1fmt("\nBuilt-in commands:\n-------------------\n");
12214 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12215 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12216 builtintab[i].name + 1);
12222 #if ENABLE_FEATURE_SH_STANDALONE
12224 const char *a = applet_names;
12226 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12231 a += strlen(a) + 1;
12236 return EXIT_SUCCESS;
12238 #endif /* FEATURE_SH_EXTRA_QUIET */
12241 * The export and readonly commands.
12244 exportcmd(int argc UNUSED_PARAM, char **argv)
12250 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12252 if (nextopt("p") != 'p') {
12257 p = strchr(name, '=');
12261 vp = *findvar(hashvar(name), name);
12267 setvar(name, p, flag);
12268 } while ((name = *++aptr) != NULL);
12272 showvars(argv[0], flag, 0);
12277 * Delete a function if it exists.
12280 unsetfunc(const char *name)
12282 struct tblentry *cmdp;
12284 cmdp = cmdlookup(name, 0);
12285 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12286 delete_cmd_entry();
12290 * The unset builtin command. We unset the function before we unset the
12291 * variable to allow a function to be unset when there is a readonly variable
12292 * with the same name.
12295 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12302 while ((i = nextopt("vf")) != '\0') {
12306 for (ap = argptr; *ap; ap++) {
12322 #include <sys/times.h>
12324 static const unsigned char timescmd_str[] ALIGN1 = {
12325 ' ', offsetof(struct tms, tms_utime),
12326 '\n', offsetof(struct tms, tms_stime),
12327 ' ', offsetof(struct tms, tms_cutime),
12328 '\n', offsetof(struct tms, tms_cstime),
12333 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12335 long clk_tck, s, t;
12336 const unsigned char *p;
12339 clk_tck = sysconf(_SC_CLK_TCK);
12344 t = *(clock_t *)(((char *) &buf) + p[1]);
12346 out1fmt("%ldm%ld.%.3lds%c",
12348 ((t - s * clk_tck) * 1000) / clk_tck,
12350 } while (*(p += 2));
12355 #if ENABLE_SH_MATH_SUPPORT
12357 dash_arith(const char *s)
12363 result = arith(s, &errcode, &math_hooks);
12366 ash_msg_and_raise_error("exponent less than 0");
12368 ash_msg_and_raise_error("divide by zero");
12370 ash_msg_and_raise_error("expression recursion loop detected");
12371 raise_error_syntax(s);
12379 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12380 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12382 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12385 letcmd(int argc UNUSED_PARAM, char **argv)
12391 ash_msg_and_raise_error("expression expected");
12393 i = dash_arith(*argv);
12398 #endif /* SH_MATH_SUPPORT */
12401 /* ============ miscbltin.c
12403 * Miscellaneous builtins.
12408 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
12409 typedef enum __rlimit_resource rlim_t;
12413 * The read builtin. Options:
12414 * -r Do not interpret '\' specially
12415 * -s Turn off echo (tty only)
12416 * -n NCHARS Read NCHARS max
12417 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12418 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12419 * -u FD Read from given FD instead of fd 0
12420 * This uses unbuffered input, which may be avoidable in some cases.
12421 * TODO: bash also has:
12422 * -a ARRAY Read into array[0],[1],etc
12423 * -d DELIM End on DELIM char, not newline
12424 * -e Use line editing (tty only)
12427 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12429 static const char *const arg_REPLY[] = { "REPLY", NULL };
12442 #if ENABLE_ASH_READ_NCHARS
12443 int nchars = 0; /* if != 0, -n is in effect */
12445 struct termios tty, old_tty;
12447 #if ENABLE_ASH_READ_TIMEOUT
12448 unsigned end_ms = 0;
12449 unsigned timeout = 0;
12454 while ((i = nextopt("p:u:r"
12455 USE_ASH_READ_TIMEOUT("t:")
12456 USE_ASH_READ_NCHARS("n:s")
12460 prompt = optionarg;
12462 #if ENABLE_ASH_READ_NCHARS
12464 nchars = bb_strtou(optionarg, NULL, 10);
12465 if (nchars < 0 || errno)
12466 ash_msg_and_raise_error("invalid count");
12467 /* nchars == 0: off (bash 3.2 does this too) */
12473 #if ENABLE_ASH_READ_TIMEOUT
12475 timeout = bb_strtou(optionarg, NULL, 10);
12476 if (errno || timeout > UINT_MAX / 2048)
12477 ash_msg_and_raise_error("invalid timeout");
12479 #if 0 /* even bash have no -t N.NNN support */
12480 ts.tv_sec = bb_strtou(optionarg, &p, 10);
12482 /* EINVAL means number is ok, but not terminated by NUL */
12483 if (*p == '.' && errno == EINVAL) {
12487 ts.tv_usec = bb_strtou(p, &p2, 10);
12489 ash_msg_and_raise_error("invalid timeout");
12491 /* normalize to usec */
12493 ash_msg_and_raise_error("invalid timeout");
12494 while (scale++ < 6)
12497 } else if (ts.tv_sec < 0 || errno) {
12498 ash_msg_and_raise_error("invalid timeout");
12500 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
12501 ash_msg_and_raise_error("invalid timeout");
12510 fd = bb_strtou(optionarg, NULL, 10);
12511 if (fd < 0 || errno)
12512 ash_msg_and_raise_error("invalid file descriptor");
12518 if (prompt && isatty(fd)) {
12523 ap = (char**)arg_REPLY;
12524 ifs = bltinlookup("IFS");
12527 #if ENABLE_ASH_READ_NCHARS
12528 tcgetattr(fd, &tty);
12530 if (nchars || silent) {
12532 tty.c_lflag &= ~ICANON;
12533 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
12536 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12538 /* if tcgetattr failed, tcsetattr will fail too.
12539 * Ignoring, it's harmless. */
12540 tcsetattr(fd, TCSANOW, &tty);
12547 #if ENABLE_ASH_READ_TIMEOUT
12548 if (timeout) /* NB: ensuring end_ms is nonzero */
12549 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12553 const char *is_ifs;
12555 #if ENABLE_ASH_READ_TIMEOUT
12557 struct pollfd pfd[1];
12559 pfd[0].events = POLLIN;
12560 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12561 if ((int)timeout <= 0 /* already late? */
12562 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12563 ) { /* timed out! */
12564 #if ENABLE_ASH_READ_NCHARS
12565 tcsetattr(fd, TCSANOW, &old_tty);
12571 if (nonblock_safe_read(fd, &c, 1) != 1) {
12583 if (!rflag && c == '\\') {
12589 /* $IFS splitting */
12590 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
12591 is_ifs = strchr(ifs, c);
12592 if (startword && is_ifs) {
12595 /* it is a non-space ifs char */
12597 if (startword == 1) /* first one? */
12598 continue; /* yes, it is not next word yet */
12601 if (ap[1] != NULL && is_ifs) {
12604 beg = stackblock();
12605 setvar(*ap, beg, 0);
12607 /* can we skip one non-space ifs char? (2: yes) */
12608 startword = isspace(c) ? 2 : 1;
12615 /* end of do {} while: */
12616 #if ENABLE_ASH_READ_NCHARS
12622 #if ENABLE_ASH_READ_NCHARS
12623 tcsetattr(fd, TCSANOW, &old_tty);
12627 /* Remove trailing space ifs chars */
12628 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
12630 setvar(*ap, stackblock(), 0);
12631 while (*++ap != NULL)
12632 setvar(*ap, nullstr, 0);
12637 umaskcmd(int argc UNUSED_PARAM, char **argv)
12639 static const char permuser[3] ALIGN1 = "ugo";
12640 static const char permmode[3] ALIGN1 = "rwx";
12641 static const short permmask[] ALIGN2 = {
12642 S_IRUSR, S_IWUSR, S_IXUSR,
12643 S_IRGRP, S_IWGRP, S_IXGRP,
12644 S_IROTH, S_IWOTH, S_IXOTH
12650 int symbolic_mode = 0;
12652 while (nextopt("S") != '\0') {
12663 if (symbolic_mode) {
12667 for (i = 0; i < 3; i++) {
12670 *p++ = permuser[i];
12672 for (j = 0; j < 3; j++) {
12673 if ((mask & permmask[3 * i + j]) == 0) {
12674 *p++ = permmode[j];
12682 out1fmt("%.4o\n", mask);
12685 if (isdigit((unsigned char) *ap)) {
12688 if (*ap >= '8' || *ap < '0')
12689 ash_msg_and_raise_error(illnum, argv[1]);
12690 mask = (mask << 3) + (*ap - '0');
12691 } while (*++ap != '\0');
12694 mask = ~mask & 0777;
12695 if (!bb_parse_mode(ap, &mask)) {
12696 ash_msg_and_raise_error("illegal mode: %s", ap);
12698 umask(~mask & 0777);
12707 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12708 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12709 * ash by J.T. Conklin.
12715 uint8_t cmd; /* RLIMIT_xxx fit into it */
12716 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
12720 static const struct limits limits_tbl[] = {
12722 { RLIMIT_CPU, 0, 't' },
12724 #ifdef RLIMIT_FSIZE
12725 { RLIMIT_FSIZE, 9, 'f' },
12728 { RLIMIT_DATA, 10, 'd' },
12730 #ifdef RLIMIT_STACK
12731 { RLIMIT_STACK, 10, 's' },
12734 { RLIMIT_CORE, 9, 'c' },
12737 { RLIMIT_RSS, 10, 'm' },
12739 #ifdef RLIMIT_MEMLOCK
12740 { RLIMIT_MEMLOCK, 10, 'l' },
12742 #ifdef RLIMIT_NPROC
12743 { RLIMIT_NPROC, 0, 'p' },
12745 #ifdef RLIMIT_NOFILE
12746 { RLIMIT_NOFILE, 0, 'n' },
12749 { RLIMIT_AS, 10, 'v' },
12751 #ifdef RLIMIT_LOCKS
12752 { RLIMIT_LOCKS, 0, 'w' },
12755 static const char limits_name[] =
12757 "time(seconds)" "\0"
12759 #ifdef RLIMIT_FSIZE
12760 "file(blocks)" "\0"
12765 #ifdef RLIMIT_STACK
12769 "coredump(blocks)" "\0"
12774 #ifdef RLIMIT_MEMLOCK
12775 "locked memory(kb)" "\0"
12777 #ifdef RLIMIT_NPROC
12780 #ifdef RLIMIT_NOFILE
12786 #ifdef RLIMIT_LOCKS
12791 enum limtype { SOFT = 0x1, HARD = 0x2 };
12794 printlim(enum limtype how, const struct rlimit *limit,
12795 const struct limits *l)
12799 val = limit->rlim_max;
12801 val = limit->rlim_cur;
12803 if (val == RLIM_INFINITY)
12804 out1fmt("unlimited\n");
12806 val >>= l->factor_shift;
12807 out1fmt("%lld\n", (long long) val);
12812 ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12816 enum limtype how = SOFT | HARD;
12817 const struct limits *l;
12820 struct rlimit limit;
12823 while ((optc = nextopt("HSa"
12827 #ifdef RLIMIT_FSIZE
12833 #ifdef RLIMIT_STACK
12842 #ifdef RLIMIT_MEMLOCK
12845 #ifdef RLIMIT_NPROC
12848 #ifdef RLIMIT_NOFILE
12854 #ifdef RLIMIT_LOCKS
12872 for (l = limits_tbl; l->option != what; l++)
12875 set = *argptr ? 1 : 0;
12879 if (all || argptr[1])
12880 ash_msg_and_raise_error("too many arguments");
12881 if (strncmp(p, "unlimited\n", 9) == 0)
12882 val = RLIM_INFINITY;
12886 while ((c = *p++) >= '0' && c <= '9') {
12887 val = (val * 10) + (long)(c - '0');
12888 // val is actually 'unsigned long int' and can't get < 0
12889 if (val < (rlim_t) 0)
12893 ash_msg_and_raise_error("bad number");
12894 val <<= l->factor_shift;
12898 const char *lname = limits_name;
12899 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
12900 getrlimit(l->cmd, &limit);
12901 out1fmt("%-20s ", lname);
12902 lname += strlen(lname) + 1;
12903 printlim(how, &limit, l);
12908 getrlimit(l->cmd, &limit);
12911 limit.rlim_max = val;
12913 limit.rlim_cur = val;
12914 if (setrlimit(l->cmd, &limit) < 0)
12915 ash_msg_and_raise_error("error setting limit (%m)");
12917 printlim(how, &limit, l);
12922 /* ============ main() and helpers */
12925 * Called to exit the shell.
12927 static void exitshell(void) NORETURN;
12935 status = exitstatus;
12936 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12937 if (setjmp(loc.loc)) {
12938 if (exception_type == EXEXIT)
12939 /* dash bug: it just does _exit(exitstatus) here
12940 * but we have to do setjobctl(0) first!
12941 * (bug is still not fixed in dash-0.5.3 - if you run dash
12942 * under Midnight Commander, on exit from dash MC is backgrounded) */
12943 status = exitstatus;
12946 exception_handler = &loc;
12952 flush_stdout_stderr();
12962 /* from input.c: */
12963 basepf.next_to_pgetc = basepf.buf = basebuf;
12966 signal(SIGCHLD, SIG_DFL);
12971 char ppid[sizeof(int)*3 + 1];
12973 struct stat st1, st2;
12976 for (envp = environ; envp && *envp; envp++) {
12977 if (strchr(*envp, '=')) {
12978 setvareq(*envp, VEXPORT|VTEXTFIXED);
12982 snprintf(ppid, sizeof(ppid), "%u", (unsigned) getppid());
12983 setvar("PPID", ppid, 0);
12985 p = lookupvar("PWD");
12987 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12988 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12995 * Process the shell command line arguments.
12998 procargs(char **argv)
13001 const char *xminusc;
13006 /* if (xargv[0]) - mmm, this is always true! */
13008 for (i = 0; i < NOPTS; i++)
13012 /* it already printed err message */
13013 raise_exception(EXERROR);
13017 if (*xargv == NULL) {
13019 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13022 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13026 for (i = 0; i < NOPTS; i++)
13027 if (optlist[i] == 2)
13032 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13037 } else if (!sflag) {
13038 setinputfile(*xargv, 0);
13041 commandname = arg0;
13044 shellparam.p = xargv;
13045 #if ENABLE_ASH_GETOPTS
13046 shellparam.optind = 1;
13047 shellparam.optoff = -1;
13049 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13051 shellparam.nparam++;
13058 * Read /etc/profile or .profile.
13061 read_profile(const char *name)
13065 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13074 * This routine is called when an error or an interrupt occurs in an
13075 * interactive shell and control is returned to the main command loop.
13083 /* from input.c: */
13084 g_parsefile->left_in_buffer = 0;
13085 g_parsefile->left_in_line = 0; /* clear input buffer */
13087 /* from parser.c: */
13090 /* from redir.c: */
13091 clearredir(/*drop:*/ 0);
13095 static short profile_buf[16384];
13096 extern int etext();
13100 * Main routine. We initialize things, parse the arguments, execute
13101 * profiles if we're a login shell, and then call cmdloop to execute
13102 * commands. The setjmp call sets up the location to jump to when an
13103 * exception occurs. When an exception occurs the variable "state"
13104 * is used to figure out how far we had gotten.
13106 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13107 int ash_main(int argc UNUSED_PARAM, char **argv)
13109 const char *shinit;
13110 volatile smallint state;
13111 struct jmploc jmploc;
13112 struct stackmark smark;
13114 /* Initialize global data */
13118 #if ENABLE_ASH_ALIAS
13122 #if ENABLE_SH_MATH_SUPPORT
13123 math_hooks.lookupvar = lookupvar;
13124 math_hooks.setvar = setvar;
13125 math_hooks.endofname = endofname;
13129 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13132 #if ENABLE_FEATURE_EDITING
13133 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13136 if (setjmp(jmploc.loc)) {
13142 e = exception_type;
13146 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13149 outcslow('\n', stderr);
13151 popstackmark(&smark);
13152 FORCE_INT_ON; /* enable interrupts */
13161 exception_handler = &jmploc;
13164 TRACE(("Shell args: "));
13165 trace_puts_args(argv);
13167 rootpid = getpid();
13169 #if ENABLE_ASH_RANDOM_SUPPORT
13170 /* Can use monotonic_ns() for better randomness but for now it is
13171 * not used anywhere else in busybox... so avoid bloat */
13172 random_galois_LFSR = random_LCG = rootpid + monotonic_us();
13175 setstackmark(&smark);
13178 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13180 const char *hp = lookupvar("HISTFILE");
13183 hp = lookupvar("HOME");
13185 char *defhp = concat_path_file(hp, ".ash_history");
13186 setvar("HISTFILE", defhp, 0);
13192 if (/* argv[0] && */ argv[0][0] == '-')
13196 read_profile("/etc/profile");
13199 read_profile(".profile");
13205 getuid() == geteuid() && getgid() == getegid() &&
13209 shinit = lookupvar("ENV");
13210 if (shinit != NULL && *shinit != '\0') {
13211 read_profile(shinit);
13217 /* evalstring pushes parsefile stack.
13218 * Ensure we don't falsely claim that 0 (stdin)
13219 * is one of stacked source fds.
13220 * Testcase: ash -c 'exec 1>&0' must not complain. */
13222 g_parsefile->fd = -1;
13223 evalstring(minusc, 0);
13226 if (sflag || minusc == NULL) {
13227 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13229 const char *hp = lookupvar("HISTFILE");
13231 line_input_state->hist_file = hp;
13234 state4: /* XXX ??? - why isn't this before the "if" statement */
13242 extern void _mcleanup(void);
13252 * Copyright (c) 1989, 1991, 1993, 1994
13253 * The Regents of the University of California. All rights reserved.
13255 * This code is derived from software contributed to Berkeley by
13256 * Kenneth Almquist.
13258 * Redistribution and use in source and binary forms, with or without
13259 * modification, are permitted provided that the following conditions
13261 * 1. Redistributions of source code must retain the above copyright
13262 * notice, this list of conditions and the following disclaimer.
13263 * 2. Redistributions in binary form must reproduce the above copyright
13264 * notice, this list of conditions and the following disclaimer in the
13265 * documentation and/or other materials provided with the distribution.
13266 * 3. Neither the name of the University nor the names of its contributors
13267 * may be used to endorse or promote products derived from this software
13268 * without specific prior written permission.
13270 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13271 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13272 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13273 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13274 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13275 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13276 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13277 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13278 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13279 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF