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
54 #if ENABLE_ASH_RANDOM_SUPPORT
58 #if defined SINGLE_APPLET_MAIN
59 /* STANDALONE does not make sense, and won't compile */
60 # undef CONFIG_FEATURE_SH_STANDALONE
61 # undef ENABLE_FEATURE_SH_STANDALONE
62 # undef IF_FEATURE_SH_STANDALONE
63 # undef IF_NOT_FEATURE_SH_STANDALONE(...)
64 # define ENABLE_FEATURE_SH_STANDALONE 0
65 # define IF_FEATURE_SH_STANDALONE(...)
66 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
70 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
73 #if defined(__uClinux__)
74 # error "Do not even bother, ash will not run on NOMMU machine"
78 /* ============ Hash table sizes. Configurable. */
82 #define CMDTABLESIZE 31 /* should be prime */
85 /* ============ Shell options */
87 static const char *const optletters_optnames[] = {
108 #define optletters(n) optletters_optnames[(n)][0]
109 #define optnames(n) (&optletters_optnames[(n)][1])
111 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
114 /* ============ Misc data */
116 static const char homestr[] ALIGN1 = "HOME";
117 static const char snlfmt[] ALIGN1 = "%s\n";
118 static const char msg_illnum[] ALIGN1 = "Illegal number: %s";
121 * We enclose jmp_buf in a structure so that we can declare pointers to
122 * jump locations. The global variable handler contains the location to
123 * jump to when an exception occurs, and the global variable exception_type
124 * contains a code identifying the exception. To implement nested
125 * exception handlers, the user should save the value of handler on entry
126 * to an inner scope, set handler to point to a jmploc structure for the
127 * inner scope, and restore handler on exit from the scope.
133 struct globals_misc {
134 /* pid of main shell */
136 /* shell level: 0 for the main shell, 1 for its children, and so on */
138 #define rootshell (!shlvl)
139 char *minusc; /* argument to -c option */
141 char *curdir; // = nullstr; /* current working directory */
142 char *physdir; // = nullstr; /* physical working directory */
144 char *arg0; /* value of $0 */
146 struct jmploc *exception_handler;
148 volatile int suppress_int; /* counter */
149 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
150 /* last pending signal */
151 volatile /*sig_atomic_t*/ smallint pending_sig;
152 smallint exception_type; /* kind of exception (0..5) */
154 #define EXINT 0 /* SIGINT received */
155 #define EXERROR 1 /* a generic error */
156 #define EXSHELLPROC 2 /* execute a shell procedure */
157 #define EXEXEC 3 /* command execution failed */
158 #define EXEXIT 4 /* exit the shell */
159 #define EXSIG 5 /* trapped signal in wait(1) */
162 char nullstr[1]; /* zero length string */
165 #define eflag optlist[0]
166 #define fflag optlist[1]
167 #define Iflag optlist[2]
168 #define iflag optlist[3]
169 #define mflag optlist[4]
170 #define nflag optlist[5]
171 #define sflag optlist[6]
172 #define xflag optlist[7]
173 #define vflag optlist[8]
174 #define Cflag optlist[9]
175 #define aflag optlist[10]
176 #define bflag optlist[11]
177 #define uflag optlist[12]
178 #define viflag optlist[13]
180 #define nolog optlist[14]
181 #define debug optlist[15]
184 /* trap handler commands */
186 * Sigmode records the current value of the signal handlers for the various
187 * modes. A value of zero means that the current handler is not known.
188 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
190 char sigmode[NSIG - 1];
191 #define S_DFL 1 /* default signal handling (SIG_DFL) */
192 #define S_CATCH 2 /* signal is caught */
193 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
194 #define S_HARD_IGN 4 /* signal is ignored permenantly */
196 /* indicates specified signal received */
197 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
199 char **trap_ptr; /* used only by "trap hack" */
201 /* Rarely referenced stuff */
202 #if ENABLE_ASH_RANDOM_SUPPORT
205 pid_t backgndpid; /* pid of last background process */
206 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
208 extern struct globals_misc *const ash_ptr_to_globals_misc;
209 #define G_misc (*ash_ptr_to_globals_misc)
210 #define rootpid (G_misc.rootpid )
211 #define shlvl (G_misc.shlvl )
212 #define minusc (G_misc.minusc )
213 #define curdir (G_misc.curdir )
214 #define physdir (G_misc.physdir )
215 #define arg0 (G_misc.arg0 )
216 #define exception_handler (G_misc.exception_handler)
217 #define exception_type (G_misc.exception_type )
218 #define suppress_int (G_misc.suppress_int )
219 #define pending_int (G_misc.pending_int )
220 #define pending_sig (G_misc.pending_sig )
221 #define isloginsh (G_misc.isloginsh )
222 #define nullstr (G_misc.nullstr )
223 #define optlist (G_misc.optlist )
224 #define sigmode (G_misc.sigmode )
225 #define gotsig (G_misc.gotsig )
226 #define trap (G_misc.trap )
227 #define trap_ptr (G_misc.trap_ptr )
228 #define random_gen (G_misc.random_gen )
229 #define backgndpid (G_misc.backgndpid )
230 #define job_warning (G_misc.job_warning)
231 #define INIT_G_misc() do { \
232 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
240 /* ============ DEBUG */
242 static void trace_printf(const char *fmt, ...);
243 static void trace_vprintf(const char *fmt, va_list va);
244 # define TRACE(param) trace_printf param
245 # define TRACEV(param) trace_vprintf param
246 # define close(fd) do { \
248 if (close(dfd) < 0) \
249 bb_error_msg("bug on %d: closing %d(0x%x)", \
250 __LINE__, dfd, dfd); \
253 # define TRACE(param)
254 # define TRACEV(param)
258 /* ============ Utility functions */
259 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
261 /* C99 says: "char" declaration may be signed or unsigned by default */
262 #define signed_char2int(sc) ((int)(signed char)(sc))
264 static int isdigit_str9(const char *str)
266 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
267 while (--maxlen && isdigit(*str))
269 return (*str == '\0');
273 /* ============ Interrupts / exceptions */
275 * These macros allow the user to suspend the handling of interrupt signals
276 * over a period of time. This is similar to SIGHOLD or to sigblock, but
277 * much more efficient and portable. (But hacking the kernel is so much
278 * more fun than worrying about efficiency and portability. :-))
280 #define INT_OFF do { \
286 * Called to raise an exception. Since C doesn't include exceptions, we
287 * just do a longjmp to the exception handler. The type of exception is
288 * stored in the global variable "exception_type".
290 static void raise_exception(int) NORETURN;
292 raise_exception(int e)
295 if (exception_handler == NULL)
300 longjmp(exception_handler->loc, 1);
303 #define raise_exception(e) do { \
304 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
305 raise_exception(e); \
310 * Called from trap.c when a SIGINT is received. (If the user specifies
311 * that SIGINT is to be trapped or ignored using the trap builtin, then
312 * this routine is not called.) Suppressint is nonzero when interrupts
313 * are held using the INT_OFF macro. (The test for iflag is just
314 * defensive programming.)
316 static void raise_interrupt(void) NORETURN;
318 raise_interrupt(void)
323 /* Signal is not automatically unmasked after it is raised,
324 * do it ourself - unmask all signals */
325 sigprocmask_allsigs(SIG_UNBLOCK);
326 /* pending_sig = 0; - now done in onsig() */
329 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
330 if (!(rootshell && iflag)) {
331 /* Kill ourself with SIGINT */
332 signal(SIGINT, SIG_DFL);
337 raise_exception(ex_type);
341 #define raise_interrupt() do { \
342 TRACE(("raising interrupt on line %d\n", __LINE__)); \
347 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
351 if (--suppress_int == 0 && pending_int) {
355 #define INT_ON int_on()
356 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
364 #define FORCE_INT_ON force_int_on()
366 #define SAVE_INT(v) ((v) = suppress_int)
368 #define RESTORE_INT(v) do { \
370 suppress_int = (v); \
371 if (suppress_int == 0 && pending_int) \
376 /* ============ Stdout/stderr output */
379 outstr(const char *p, FILE *file)
387 flush_stdout_stderr(void)
404 outcslow(int c, FILE *dest)
412 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
414 out1fmt(const char *fmt, ...)
421 r = vprintf(fmt, ap);
427 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
429 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
436 ret = vsnprintf(outbuf, length, fmt, ap);
443 out1str(const char *p)
449 out2str(const char *p)
456 /* ============ Parser structures */
458 /* control characters in argument strings */
459 #define CTLESC ((unsigned char)'\201') /* escape next character */
460 #define CTLVAR ((unsigned char)'\202') /* variable defn */
461 #define CTLENDVAR ((unsigned char)'\203')
462 #define CTLBACKQ ((unsigned char)'\204')
463 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
464 /* CTLBACKQ | CTLQUOTE == '\205' */
465 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
466 #define CTLENDARI ((unsigned char)'\207')
467 #define CTLQUOTEMARK ((unsigned char)'\210')
469 /* variable substitution byte (follows CTLVAR) */
470 #define VSTYPE 0x0f /* type of variable substitution */
471 #define VSNUL 0x10 /* colon--treat the empty string as unset */
472 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
474 /* values of VSTYPE field */
475 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
476 #define VSMINUS 0x2 /* ${var-text} */
477 #define VSPLUS 0x3 /* ${var+text} */
478 #define VSQUESTION 0x4 /* ${var?message} */
479 #define VSASSIGN 0x5 /* ${var=text} */
480 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
481 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
482 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
483 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
484 #define VSLENGTH 0xa /* ${#var} */
485 #if ENABLE_ASH_BASH_COMPAT
486 #define VSSUBSTR 0xc /* ${var:position:length} */
487 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
488 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
491 static const char dolatstr[] ALIGN1 = {
492 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
512 #if ENABLE_ASH_BASH_COMPAT
529 smallint type; /* Nxxxx */
532 union node *redirect;
537 smallint pipe_backgnd;
538 struct nodelist *cmdlist;
544 union node *redirect;
557 union node *elsepart;
584 struct nodelist *backquote;
587 /* nfile and ndup layout must match!
588 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
589 * that it is actually NTO2 (>&file), and change its type.
606 char *_unused_expfname;
625 struct nredir nredir;
626 struct nbinary nbinary;
630 struct nclist nclist;
639 * NODE_EOF is returned by parsecmd when it encounters an end of file.
640 * It must be distinct from NULL.
642 #define NODE_EOF ((union node *) -1L)
645 struct nodelist *next;
658 freefunc(struct funcnode *f)
660 if (f && --f->count < 0)
665 /* ============ Debugging output */
669 static FILE *tracefile;
672 trace_printf(const char *fmt, ...)
679 fprintf(tracefile, "%u ", (int) time(NULL));
681 fprintf(tracefile, "[%u] ", (int) getpid());
683 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
685 vfprintf(tracefile, fmt, va);
690 trace_vprintf(const char *fmt, va_list va)
695 fprintf(tracefile, "%u ", (int) time(NULL));
697 fprintf(tracefile, "[%u] ", (int) getpid());
699 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
700 vfprintf(tracefile, fmt, va);
704 trace_puts(const char *s)
712 trace_puts_quoted(char *s)
719 putc('"', tracefile);
720 for (p = s; *p; p++) {
722 case '\n': c = 'n'; goto backslash;
723 case '\t': c = 't'; goto backslash;
724 case '\r': c = 'r'; goto backslash;
725 case '"': c = '"'; goto backslash;
726 case '\\': c = '\\'; goto backslash;
727 case CTLESC: c = 'e'; goto backslash;
728 case CTLVAR: c = 'v'; goto backslash;
729 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
730 case CTLBACKQ: c = 'q'; goto backslash;
731 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
733 putc('\\', tracefile);
737 if (*p >= ' ' && *p <= '~')
740 putc('\\', tracefile);
741 putc(*p >> 6 & 03, tracefile);
742 putc(*p >> 3 & 07, tracefile);
743 putc(*p & 07, tracefile);
748 putc('"', tracefile);
752 trace_puts_args(char **ap)
759 trace_puts_quoted(*ap);
761 putc('\n', tracefile);
764 putc(' ', tracefile);
779 /* leave open because libedit might be using it */
782 strcpy(s, "./trace");
784 if (!freopen(s, "a", tracefile)) {
785 fprintf(stderr, "Can't re-open %s\n", s);
790 tracefile = fopen(s, "a");
791 if (tracefile == NULL) {
792 fprintf(stderr, "Can't open %s\n", s);
798 flags = fcntl(fileno(tracefile), F_GETFL);
800 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
802 setlinebuf(tracefile);
803 fputs("\nTracing started.\n", tracefile);
807 indent(int amount, char *pfx, FILE *fp)
811 for (i = 0; i < amount; i++) {
812 if (pfx && i == amount - 1)
818 /* little circular references here... */
819 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
822 sharg(union node *arg, FILE *fp)
825 struct nodelist *bqlist;
828 if (arg->type != NARG) {
829 out1fmt("<node type %d>\n", arg->type);
832 bqlist = arg->narg.backquote;
833 for (p = arg->narg.text; *p; p++) {
842 if (subtype == VSLENGTH)
851 switch (subtype & VSTYPE) {
884 out1fmt("<subtype %d>", subtype);
891 case CTLBACKQ|CTLQUOTE:
894 shtree(bqlist->n, -1, NULL, fp);
905 shcmd(union node *cmd, FILE *fp)
913 for (np = cmd->ncmd.args; np; np = np->narg.next) {
919 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
923 switch (np->nfile.type) {
924 case NTO: s = ">>"+1; dftfd = 1; break;
925 case NCLOBBER: s = ">|"; dftfd = 1; break;
926 case NAPPEND: s = ">>"; dftfd = 1; break;
927 #if ENABLE_ASH_BASH_COMPAT
930 case NTOFD: s = ">&"; dftfd = 1; break;
931 case NFROM: s = "<"; break;
932 case NFROMFD: s = "<&"; break;
933 case NFROMTO: s = "<>"; break;
934 default: s = "*error*"; break;
936 if (np->nfile.fd != dftfd)
937 fprintf(fp, "%d", np->nfile.fd);
939 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
940 fprintf(fp, "%d", np->ndup.dupfd);
942 sharg(np->nfile.fname, fp);
949 shtree(union node *n, int ind, char *pfx, FILE *fp)
957 indent(ind, pfx, fp);
974 shtree(n->nbinary.ch1, ind, NULL, fp);
977 shtree(n->nbinary.ch2, ind, NULL, fp);
985 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
986 shtree(lp->n, 0, NULL, fp);
990 if (n->npipe.pipe_backgnd)
996 fprintf(fp, "<node type %d>", n->type);
1004 showtree(union node *n)
1006 trace_puts("showtree called\n");
1007 shtree(n, 1, NULL, stderr);
1013 /* ============ Parser data */
1016 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1019 struct strlist *next;
1026 struct strpush *prev; /* preceding string on stack */
1028 int prev_left_in_line;
1029 #if ENABLE_ASH_ALIAS
1030 struct alias *ap; /* if push was associated with an alias */
1032 char *string; /* remember the string since it may change */
1036 struct parsefile *prev; /* preceding file on stack */
1037 int linno; /* current line */
1038 int fd; /* file descriptor (or -1 if string) */
1039 int left_in_line; /* number of chars left in this line */
1040 int left_in_buffer; /* number of chars left in this buffer past the line */
1041 char *next_to_pgetc; /* next char in buffer */
1042 char *buf; /* input buffer */
1043 struct strpush *strpush; /* for pushing strings at this level */
1044 struct strpush basestrpush; /* so pushing one is fast */
1047 static struct parsefile basepf; /* top level input file */
1048 static struct parsefile *g_parsefile = &basepf; /* current input file */
1049 static int startlinno; /* line # where last token started */
1050 static char *commandname; /* currently executing command */
1051 static struct strlist *cmdenviron; /* environment for builtin command */
1052 static uint8_t exitstatus; /* exit status of last command */
1055 /* ============ Message printing */
1058 ash_vmsg(const char *msg, va_list ap)
1060 fprintf(stderr, "%s: ", arg0);
1062 if (strcmp(arg0, commandname))
1063 fprintf(stderr, "%s: ", commandname);
1064 if (!iflag || g_parsefile->fd)
1065 fprintf(stderr, "line %d: ", startlinno);
1067 vfprintf(stderr, msg, ap);
1068 outcslow('\n', stderr);
1072 * Exverror is called to raise the error exception. If the second argument
1073 * is not NULL then error prints an error message using printf style
1074 * formatting. It then raises the error exception.
1076 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1078 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1082 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1084 TRACE(("\") pid=%d\n", getpid()));
1086 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1091 flush_stdout_stderr();
1092 raise_exception(cond);
1096 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1098 ash_msg_and_raise_error(const char *msg, ...)
1103 ash_vmsg_and_raise(EXERROR, msg, ap);
1108 static void raise_error_syntax(const char *) NORETURN;
1110 raise_error_syntax(const char *msg)
1112 ash_msg_and_raise_error("syntax error: %s", msg);
1116 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1118 ash_msg_and_raise(int cond, const char *msg, ...)
1123 ash_vmsg_and_raise(cond, msg, ap);
1129 * error/warning routines for external builtins
1132 ash_msg(const char *fmt, ...)
1142 * Return a string describing an error. The returned string may be a
1143 * pointer to a static buffer that will be overwritten on the next call.
1144 * Action describes the operation that got the error.
1147 errmsg(int e, const char *em)
1149 if (e == ENOENT || e == ENOTDIR) {
1156 /* ============ Memory allocation */
1159 * It appears that grabstackstr() will barf with such alignments
1160 * because stalloc() will return a string allocated in a new stackblock.
1162 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1164 /* Most machines require the value returned from malloc to be aligned
1165 * in some way. The following macro will get this right
1166 * on many machines. */
1167 SHELL_SIZE = sizeof(union {int i; char *cp; double d; }) - 1,
1168 /* Minimum size of a block */
1169 MINSIZE = SHELL_ALIGN(504),
1172 struct stack_block {
1173 struct stack_block *prev;
1174 char space[MINSIZE];
1178 struct stack_block *stackp;
1181 struct stackmark *marknext;
1185 struct globals_memstack {
1186 struct stack_block *g_stackp; // = &stackbase;
1187 struct stackmark *markp;
1188 char *g_stacknxt; // = stackbase.space;
1189 char *sstrend; // = stackbase.space + MINSIZE;
1190 size_t g_stacknleft; // = MINSIZE;
1191 int herefd; // = -1;
1192 struct stack_block stackbase;
1194 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1195 #define G_memstack (*ash_ptr_to_globals_memstack)
1196 #define g_stackp (G_memstack.g_stackp )
1197 #define markp (G_memstack.markp )
1198 #define g_stacknxt (G_memstack.g_stacknxt )
1199 #define sstrend (G_memstack.sstrend )
1200 #define g_stacknleft (G_memstack.g_stacknleft)
1201 #define herefd (G_memstack.herefd )
1202 #define stackbase (G_memstack.stackbase )
1203 #define INIT_G_memstack() do { \
1204 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1206 g_stackp = &stackbase; \
1207 g_stacknxt = stackbase.space; \
1208 g_stacknleft = MINSIZE; \
1209 sstrend = stackbase.space + MINSIZE; \
1213 #define stackblock() ((void *)g_stacknxt)
1214 #define stackblocksize() g_stacknleft
1218 ckrealloc(void * p, size_t nbytes)
1220 p = realloc(p, nbytes);
1222 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1227 ckmalloc(size_t nbytes)
1229 return ckrealloc(NULL, nbytes);
1233 ckzalloc(size_t nbytes)
1235 return memset(ckmalloc(nbytes), 0, nbytes);
1239 * Make a copy of a string in safe storage.
1242 ckstrdup(const char *s)
1244 char *p = strdup(s);
1246 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1251 * Parse trees for commands are allocated in lifo order, so we use a stack
1252 * to make this more efficient, and also to avoid all sorts of exception
1253 * handling code to handle interrupts in the middle of a parse.
1255 * The size 504 was chosen because the Ultrix malloc handles that size
1259 stalloc(size_t nbytes)
1264 aligned = SHELL_ALIGN(nbytes);
1265 if (aligned > g_stacknleft) {
1268 struct stack_block *sp;
1270 blocksize = aligned;
1271 if (blocksize < MINSIZE)
1272 blocksize = MINSIZE;
1273 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1274 if (len < blocksize)
1275 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1278 sp->prev = g_stackp;
1279 g_stacknxt = sp->space;
1280 g_stacknleft = blocksize;
1281 sstrend = g_stacknxt + blocksize;
1286 g_stacknxt += aligned;
1287 g_stacknleft -= aligned;
1292 stzalloc(size_t nbytes)
1294 return memset(stalloc(nbytes), 0, nbytes);
1301 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1302 write(STDERR_FILENO, "stunalloc\n", 10);
1306 g_stacknleft += g_stacknxt - (char *)p;
1311 * Like strdup but works with the ash stack.
1314 ststrdup(const char *p)
1316 size_t len = strlen(p) + 1;
1317 return memcpy(stalloc(len), p, len);
1321 setstackmark(struct stackmark *mark)
1323 mark->stackp = g_stackp;
1324 mark->stacknxt = g_stacknxt;
1325 mark->stacknleft = g_stacknleft;
1326 mark->marknext = markp;
1331 popstackmark(struct stackmark *mark)
1333 struct stack_block *sp;
1339 markp = mark->marknext;
1340 while (g_stackp != mark->stackp) {
1342 g_stackp = sp->prev;
1345 g_stacknxt = mark->stacknxt;
1346 g_stacknleft = mark->stacknleft;
1347 sstrend = mark->stacknxt + mark->stacknleft;
1352 * When the parser reads in a string, it wants to stick the string on the
1353 * stack and only adjust the stack pointer when it knows how big the
1354 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1355 * of space on top of the stack and stackblocklen returns the length of
1356 * this block. Growstackblock will grow this space by at least one byte,
1357 * possibly moving it (like realloc). Grabstackblock actually allocates the
1358 * part of the block that has been used.
1361 growstackblock(void)
1365 newlen = g_stacknleft * 2;
1366 if (newlen < g_stacknleft)
1367 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1371 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1372 struct stack_block *oldstackp;
1373 struct stackmark *xmark;
1374 struct stack_block *sp;
1375 struct stack_block *prevstackp;
1379 oldstackp = g_stackp;
1381 prevstackp = sp->prev;
1382 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1383 sp = ckrealloc(sp, grosslen);
1384 sp->prev = prevstackp;
1386 g_stacknxt = sp->space;
1387 g_stacknleft = newlen;
1388 sstrend = sp->space + newlen;
1391 * Stack marks pointing to the start of the old block
1392 * must be relocated to point to the new block
1395 while (xmark != NULL && xmark->stackp == oldstackp) {
1396 xmark->stackp = g_stackp;
1397 xmark->stacknxt = g_stacknxt;
1398 xmark->stacknleft = g_stacknleft;
1399 xmark = xmark->marknext;
1403 char *oldspace = g_stacknxt;
1404 size_t oldlen = g_stacknleft;
1405 char *p = stalloc(newlen);
1407 /* free the space we just allocated */
1408 g_stacknxt = memcpy(p, oldspace, oldlen);
1409 g_stacknleft += newlen;
1414 grabstackblock(size_t len)
1416 len = SHELL_ALIGN(len);
1418 g_stacknleft -= len;
1422 * The following routines are somewhat easier to use than the above.
1423 * The user declares a variable of type STACKSTR, which may be declared
1424 * to be a register. The macro STARTSTACKSTR initializes things. Then
1425 * the user uses the macro STPUTC to add characters to the string. In
1426 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1427 * grown as necessary. When the user is done, she can just leave the
1428 * string there and refer to it using stackblock(). Or she can allocate
1429 * the space for it using grabstackstr(). If it is necessary to allow
1430 * someone else to use the stack temporarily and then continue to grow
1431 * the string, the user should use grabstack to allocate the space, and
1432 * then call ungrabstr(p) to return to the previous mode of operation.
1434 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1435 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1436 * is space for at least one character.
1441 size_t len = stackblocksize();
1442 if (herefd >= 0 && len >= 1024) {
1443 full_write(herefd, stackblock(), len);
1444 return stackblock();
1447 return (char *)stackblock() + len;
1451 * Called from CHECKSTRSPACE.
1454 makestrspace(size_t newlen, char *p)
1456 size_t len = p - g_stacknxt;
1457 size_t size = stackblocksize();
1462 size = stackblocksize();
1464 if (nleft >= newlen)
1468 return (char *)stackblock() + len;
1472 stack_nputstr(const char *s, size_t n, char *p)
1474 p = makestrspace(n, p);
1475 p = (char *)memcpy(p, s, n) + n;
1480 stack_putstr(const char *s, char *p)
1482 return stack_nputstr(s, strlen(s), p);
1486 _STPUTC(int c, char *p)
1494 #define STARTSTACKSTR(p) ((p) = stackblock())
1495 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1496 #define CHECKSTRSPACE(n, p) do { \
1499 size_t m = sstrend - q; \
1501 (p) = makestrspace(l, q); \
1503 #define USTPUTC(c, p) (*(p)++ = (c))
1504 #define STACKSTRNUL(p) do { \
1505 if ((p) == sstrend) \
1506 (p) = growstackstr(); \
1509 #define STUNPUTC(p) (--(p))
1510 #define STTOPC(p) ((p)[-1])
1511 #define STADJUST(amount, p) ((p) += (amount))
1513 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1514 #define ungrabstackstr(s, p) stunalloc(s)
1515 #define stackstrend() ((void *)sstrend)
1518 /* ============ String helpers */
1521 * prefix -- see if pfx is a prefix of string.
1524 prefix(const char *string, const char *pfx)
1527 if (*pfx++ != *string++)
1530 return (char *) string;
1534 * Check for a valid number. This should be elsewhere.
1537 is_number(const char *p)
1542 } while (*++p != '\0');
1547 * Convert a string of digits to an integer, printing an error message on
1551 number(const char *s)
1554 ash_msg_and_raise_error(msg_illnum, s);
1559 * Produce a possibly single quoted string suitable as input to the shell.
1560 * The return string is allocated on the stack.
1563 single_quote(const char *s)
1573 len = strchrnul(s, '\'') - s;
1575 q = p = makestrspace(len + 3, p);
1578 q = (char *)memcpy(q, s, len) + len;
1584 len = strspn(s, "'");
1588 q = p = makestrspace(len + 3, p);
1591 q = (char *)memcpy(q, s, len) + len;
1600 return stackblock();
1604 /* ============ nextopt */
1606 static char **argptr; /* argument list for builtin commands */
1607 static char *optionarg; /* set by nextopt (like getopt) */
1608 static char *optptr; /* used by nextopt */
1611 * XXX - should get rid of. Have all builtins use getopt(3).
1612 * The library getopt must have the BSD extension static variable
1613 * "optreset", otherwise it can't be used within the shell safely.
1615 * Standard option processing (a la getopt) for builtin routines.
1616 * The only argument that is passed to nextopt is the option string;
1617 * the other arguments are unnecessary. It returns the character,
1618 * or '\0' on end of input.
1621 nextopt(const char *optstring)
1628 if (p == NULL || *p == '\0') {
1629 /* We ate entire "-param", take next one */
1635 if (*++p == '\0') /* just "-" ? */
1638 if (LONE_DASH(p)) /* "--" ? */
1640 /* p => next "-param" */
1642 /* p => some option char in the middle of a "-param" */
1644 for (q = optstring; *q != c;) {
1646 ash_msg_and_raise_error("illegal option -%c", c);
1654 ash_msg_and_raise_error("no arg for -%c option", c);
1664 /* ============ Shell variables */
1667 * The parsefile structure pointed to by the global variable parsefile
1668 * contains information about the current file being read.
1671 int nparam; /* # of positional parameters (without $0) */
1672 #if ENABLE_ASH_GETOPTS
1673 int optind; /* next parameter to be processed by getopts */
1674 int optoff; /* used by getopts */
1676 unsigned char malloced; /* if parameter list dynamically allocated */
1677 char **p; /* parameter list */
1681 * Free the list of positional parameters.
1684 freeparam(volatile struct shparam *param)
1686 if (param->malloced) {
1688 ap = ap1 = param->p;
1695 #if ENABLE_ASH_GETOPTS
1696 static void FAST_FUNC getoptsreset(const char *value);
1700 struct var *next; /* next entry in hash list */
1701 int flags; /* flags are defined above */
1702 const char *text; /* name=value */
1703 void (*func)(const char *) FAST_FUNC; /* function to be called when */
1704 /* the variable gets set/unset */
1708 struct localvar *next; /* next local variable in list */
1709 struct var *vp; /* the variable that was made local */
1710 int flags; /* saved flags */
1711 const char *text; /* saved text */
1715 #define VEXPORT 0x01 /* variable is exported */
1716 #define VREADONLY 0x02 /* variable cannot be modified */
1717 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1718 #define VTEXTFIXED 0x08 /* text is statically allocated */
1719 #define VSTACK 0x10 /* text is allocated on the stack */
1720 #define VUNSET 0x20 /* the variable is not set */
1721 #define VNOFUNC 0x40 /* don't call the callback function */
1722 #define VNOSET 0x80 /* do not set variable - just readonly test */
1723 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1724 #if ENABLE_ASH_RANDOM_SUPPORT
1725 # define VDYNAMIC 0x200 /* dynamic variable */
1731 static const char defifsvar[] ALIGN1 = "IFS= \t\n";
1732 #define defifs (defifsvar + 4)
1734 static const char defifs[] ALIGN1 = " \t\n";
1738 /* Need to be before varinit_data[] */
1739 #if ENABLE_LOCALE_SUPPORT
1740 static void FAST_FUNC
1741 change_lc_all(const char *value)
1743 if (value && *value != '\0')
1744 setlocale(LC_ALL, value);
1746 static void FAST_FUNC
1747 change_lc_ctype(const char *value)
1749 if (value && *value != '\0')
1750 setlocale(LC_CTYPE, value);
1754 static void chkmail(void);
1755 static void changemail(const char *) FAST_FUNC;
1757 static void changepath(const char *) FAST_FUNC;
1758 #if ENABLE_ASH_RANDOM_SUPPORT
1759 static void change_random(const char *) FAST_FUNC;
1762 static const struct {
1765 void (*func)(const char *) FAST_FUNC;
1766 } varinit_data[] = {
1768 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1770 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
1773 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1774 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1776 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1777 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1778 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1779 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1780 #if ENABLE_ASH_GETOPTS
1781 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1783 #if ENABLE_ASH_RANDOM_SUPPORT
1784 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
1786 #if ENABLE_LOCALE_SUPPORT
1787 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1788 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
1790 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1791 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
1797 struct globals_var {
1798 struct shparam shellparam; /* $@ current positional parameters */
1799 struct redirtab *redirlist;
1801 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1802 struct var *vartab[VTABSIZE];
1803 struct var varinit[ARRAY_SIZE(varinit_data)];
1805 extern struct globals_var *const ash_ptr_to_globals_var;
1806 #define G_var (*ash_ptr_to_globals_var)
1807 #define shellparam (G_var.shellparam )
1808 //#define redirlist (G_var.redirlist )
1809 #define g_nullredirs (G_var.g_nullredirs )
1810 #define preverrout_fd (G_var.preverrout_fd)
1811 #define vartab (G_var.vartab )
1812 #define varinit (G_var.varinit )
1813 #define INIT_G_var() do { \
1815 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1817 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1818 varinit[i].flags = varinit_data[i].flags; \
1819 varinit[i].text = varinit_data[i].text; \
1820 varinit[i].func = varinit_data[i].func; \
1824 #define vifs varinit[0]
1826 # define vmail (&vifs)[1]
1827 # define vmpath (&vmail)[1]
1828 # define vpath (&vmpath)[1]
1830 # define vpath (&vifs)[1]
1832 #define vps1 (&vpath)[1]
1833 #define vps2 (&vps1)[1]
1834 #define vps4 (&vps2)[1]
1835 #if ENABLE_ASH_GETOPTS
1836 # define voptind (&vps4)[1]
1837 # if ENABLE_ASH_RANDOM_SUPPORT
1838 # define vrandom (&voptind)[1]
1841 # if ENABLE_ASH_RANDOM_SUPPORT
1842 # define vrandom (&vps4)[1]
1847 * The following macros access the values of the above variables.
1848 * They have to skip over the name. They return the null string
1849 * for unset variables.
1851 #define ifsval() (vifs.text + 4)
1852 #define ifsset() ((vifs.flags & VUNSET) == 0)
1854 # define mailval() (vmail.text + 5)
1855 # define mpathval() (vmpath.text + 9)
1856 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1858 #define pathval() (vpath.text + 5)
1859 #define ps1val() (vps1.text + 4)
1860 #define ps2val() (vps2.text + 4)
1861 #define ps4val() (vps4.text + 4)
1862 #if ENABLE_ASH_GETOPTS
1863 # define optindval() (voptind.text + 7)
1867 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1868 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1870 #if ENABLE_ASH_GETOPTS
1871 static void FAST_FUNC
1872 getoptsreset(const char *value)
1874 shellparam.optind = number(value);
1875 shellparam.optoff = -1;
1880 * Return of a legal variable name (a letter or underscore followed by zero or
1881 * more letters, underscores, and digits).
1884 endofname(const char *name)
1892 if (!is_in_name(*p))
1899 * Compares two strings up to the first = or '\0'. The first
1900 * string must be terminated by '='; the second may be terminated by
1901 * either '=' or '\0'.
1904 varcmp(const char *p, const char *q)
1908 while ((c = *p) == (d = *q)) {
1923 varequal(const char *a, const char *b)
1925 return !varcmp(a, b);
1929 * Find the appropriate entry in the hash table from the name.
1931 static struct var **
1932 hashvar(const char *p)
1936 hashval = ((unsigned char) *p) << 4;
1937 while (*p && *p != '=')
1938 hashval += (unsigned char) *p++;
1939 return &vartab[hashval % VTABSIZE];
1943 vpcmp(const void *a, const void *b)
1945 return varcmp(*(const char **)a, *(const char **)b);
1949 * This routine initializes the builtin variables.
1959 * PS1 depends on uid
1961 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1962 vps1.text = "PS1=\\w \\$ ";
1965 vps1.text = "PS1=# ";
1968 end = vp + ARRAY_SIZE(varinit);
1970 vpp = hashvar(vp->text);
1973 } while (++vp < end);
1976 static struct var **
1977 findvar(struct var **vpp, const char *name)
1979 for (; *vpp; vpp = &(*vpp)->next) {
1980 if (varequal((*vpp)->text, name)) {
1988 * Find the value of a variable. Returns NULL if not set.
1991 lookupvar(const char *name)
1995 v = *findvar(hashvar(name), name);
1997 #if ENABLE_ASH_RANDOM_SUPPORT
1999 * Dynamic variables are implemented roughly the same way they are
2000 * in bash. Namely, they're "special" so long as they aren't unset.
2001 * As soon as they're unset, they're no longer dynamic, and dynamic
2002 * lookup will no longer happen at that point. -- PFM.
2004 if ((v->flags & VDYNAMIC))
2007 if (!(v->flags & VUNSET))
2008 return strchrnul(v->text, '=') + 1;
2014 * Search the environment of a builtin command.
2017 bltinlookup(const char *name)
2021 for (sp = cmdenviron; sp; sp = sp->next) {
2022 if (varequal(sp->text, name))
2023 return strchrnul(sp->text, '=') + 1;
2025 return lookupvar(name);
2029 * Same as setvar except that the variable and value are passed in
2030 * the first argument as name=value. Since the first argument will
2031 * be actually stored in the table, it should not be a string that
2033 * Called with interrupts off.
2036 setvareq(char *s, int flags)
2038 struct var *vp, **vpp;
2041 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2042 vp = *findvar(vpp, s);
2044 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2047 if (flags & VNOSAVE)
2050 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2056 if (vp->func && (flags & VNOFUNC) == 0)
2057 (*vp->func)(strchrnul(s, '=') + 1);
2059 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2060 free((char*)vp->text);
2062 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2067 vp = ckzalloc(sizeof(*vp));
2069 /*vp->func = NULL; - ckzalloc did it */
2072 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2079 * Set the value of a variable. The flags argument is ored with the
2080 * flags of the variable. If val is NULL, the variable is unset.
2083 setvar(const char *name, const char *val, int flags)
2090 q = endofname(name);
2091 p = strchrnul(q, '=');
2093 if (!namelen || p != q)
2094 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2099 vallen = strlen(val);
2102 nameeq = ckmalloc(namelen + vallen + 2);
2103 p = (char *)memcpy(nameeq, name, namelen) + namelen;
2106 p = (char *)memcpy(p, val, vallen) + vallen;
2109 setvareq(nameeq, flags | VNOSAVE);
2113 #if ENABLE_ASH_GETOPTS
2115 * Safe version of setvar, returns 1 on success 0 on failure.
2118 setvarsafe(const char *name, const char *val, int flags)
2121 volatile int saveint;
2122 struct jmploc *volatile savehandler = exception_handler;
2123 struct jmploc jmploc;
2126 if (setjmp(jmploc.loc))
2129 exception_handler = &jmploc;
2130 setvar(name, val, flags);
2133 exception_handler = savehandler;
2134 RESTORE_INT(saveint);
2140 * Unset the specified variable.
2143 unsetvar(const char *s)
2149 vpp = findvar(hashvar(s), s);
2153 int flags = vp->flags;
2156 if (flags & VREADONLY)
2158 #if ENABLE_ASH_RANDOM_SUPPORT
2159 vp->flags &= ~VDYNAMIC;
2163 if ((flags & VSTRFIXED) == 0) {
2165 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2166 free((char*)vp->text);
2172 vp->flags &= ~VEXPORT;
2182 * Process a linked list of variable assignments.
2185 listsetvar(struct strlist *list_set_var, int flags)
2187 struct strlist *lp = list_set_var;
2193 setvareq(lp->text, flags);
2200 * Generate a list of variables satisfying the given conditions.
2203 listvars(int on, int off, char ***end)
2214 for (vp = *vpp; vp; vp = vp->next) {
2215 if ((vp->flags & mask) == on) {
2216 if (ep == stackstrend())
2217 ep = growstackstr();
2218 *ep++ = (char *) vp->text;
2221 } while (++vpp < vartab + VTABSIZE);
2222 if (ep == stackstrend())
2223 ep = growstackstr();
2227 return grabstackstr(ep);
2231 /* ============ Path search helper
2233 * The variable path (passed by reference) should be set to the start
2234 * of the path before the first call; path_advance will update
2235 * this value as it proceeds. Successive calls to path_advance will return
2236 * the possible path expansions in sequence. If an option (indicated by
2237 * a percent sign) appears in the path entry then the global variable
2238 * pathopt will be set to point to it; otherwise pathopt will be set to
2241 static const char *pathopt; /* set by path_advance */
2244 path_advance(const char **path, const char *name)
2254 for (p = start; *p && *p != ':' && *p != '%'; p++)
2256 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2257 while (stackblocksize() < len)
2261 memcpy(q, start, p - start);
2269 while (*p && *p != ':')
2276 return stalloc(len);
2280 /* ============ Prompt */
2282 static smallint doprompt; /* if set, prompt the user */
2283 static smallint needprompt; /* true if interactive and at start of line */
2285 #if ENABLE_FEATURE_EDITING
2286 static line_input_t *line_input_state;
2287 static const char *cmdedit_prompt;
2289 putprompt(const char *s)
2291 if (ENABLE_ASH_EXPAND_PRMT) {
2292 free((char*)cmdedit_prompt);
2293 cmdedit_prompt = ckstrdup(s);
2300 putprompt(const char *s)
2306 #if ENABLE_ASH_EXPAND_PRMT
2307 /* expandstr() needs parsing machinery, so it is far away ahead... */
2308 static const char *expandstr(const char *ps);
2310 #define expandstr(s) s
2314 setprompt(int whichprompt)
2317 #if ENABLE_ASH_EXPAND_PRMT
2318 struct stackmark smark;
2323 switch (whichprompt) {
2333 #if ENABLE_ASH_EXPAND_PRMT
2334 setstackmark(&smark);
2335 stalloc(stackblocksize());
2337 putprompt(expandstr(prompt));
2338 #if ENABLE_ASH_EXPAND_PRMT
2339 popstackmark(&smark);
2344 /* ============ The cd and pwd commands */
2346 #define CD_PHYSICAL 1
2356 while ((i = nextopt("LP")) != '\0') {
2358 flags ^= CD_PHYSICAL;
2367 * Update curdir (the name of the current directory) in response to a
2371 updatepwd(const char *dir)
2378 cdcomppath = ststrdup(dir);
2381 if (curdir == nullstr)
2383 new = stack_putstr(curdir, new);
2385 new = makestrspace(strlen(dir) + 2, new);
2386 lim = (char *)stackblock() + 1;
2390 if (new > lim && *lim == '/')
2395 if (dir[1] == '/' && dir[2] != '/') {
2401 p = strtok(cdcomppath, "/");
2405 if (p[1] == '.' && p[2] == '\0') {
2417 new = stack_putstr(p, new);
2425 return stackblock();
2429 * Find out what the current directory is. If we already know the current
2430 * directory, this routine returns immediately.
2435 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2436 return dir ? dir : nullstr;
2440 setpwd(const char *val, int setold)
2444 oldcur = dir = curdir;
2447 setvar("OLDPWD", oldcur, VEXPORT);
2450 if (physdir != nullstr) {
2451 if (physdir != oldcur)
2455 if (oldcur == val || !val) {
2461 dir = ckstrdup(val);
2462 if (oldcur != dir && oldcur != nullstr) {
2467 setvar("PWD", dir, VEXPORT);
2470 static void hashcd(void);
2473 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2474 * know that the current directory has changed.
2477 docd(const char *dest, int flags)
2479 const char *dir = 0;
2482 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2485 if (!(flags & CD_PHYSICAL)) {
2486 dir = updatepwd(dest);
2500 static int FAST_FUNC
2501 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2513 dest = bltinlookup(homestr);
2514 else if (LONE_DASH(dest)) {
2515 dest = bltinlookup("OLDPWD");
2537 path = bltinlookup("CDPATH");
2546 p = path_advance(&path, dest);
2547 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2551 if (!docd(p, flags))
2556 ash_msg_and_raise_error("can't cd to %s", dest);
2559 if (flags & CD_PRINT)
2560 out1fmt(snlfmt, curdir);
2564 static int FAST_FUNC
2565 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2568 const char *dir = curdir;
2572 if (physdir == nullstr)
2576 out1fmt(snlfmt, dir);
2581 /* ============ ... */
2584 #define IBUFSIZ COMMON_BUFSIZE
2585 /* buffer for top level input file */
2586 #define basebuf bb_common_bufsiz1
2588 /* Syntax classes */
2589 #define CWORD 0 /* character is nothing special */
2590 #define CNL 1 /* newline character */
2591 #define CBACK 2 /* a backslash character */
2592 #define CSQUOTE 3 /* single quote */
2593 #define CDQUOTE 4 /* double quote */
2594 #define CENDQUOTE 5 /* a terminating quote */
2595 #define CBQUOTE 6 /* backwards single quote */
2596 #define CVAR 7 /* a dollar sign */
2597 #define CENDVAR 8 /* a '}' character */
2598 #define CLP 9 /* a left paren in arithmetic */
2599 #define CRP 10 /* a right paren in arithmetic */
2600 #define CENDFILE 11 /* end of file */
2601 #define CCTL 12 /* like CWORD, except it must be escaped */
2602 #define CSPCL 13 /* these terminate a word */
2603 #define CIGN 14 /* character should be ignored */
2605 #if ENABLE_ASH_ALIAS
2609 #define PEOA_OR_PEOF PEOA
2613 #define PEOA_OR_PEOF PEOF
2616 /* number syntax index */
2617 #define BASESYNTAX 0 /* not in quotes */
2618 #define DQSYNTAX 1 /* in double quotes */
2619 #define SQSYNTAX 2 /* in single quotes */
2620 #define ARISYNTAX 3 /* in arithmetic */
2621 #define PSSYNTAX 4 /* prompt */
2623 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
2624 #define USE_SIT_FUNCTION
2627 #if ENABLE_SH_MATH_SUPPORT
2628 static const char S_I_T[][4] = {
2629 #if ENABLE_ASH_ALIAS
2630 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
2632 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2633 { CNL, CNL, CNL, CNL }, /* 2, \n */
2634 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2635 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2636 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2637 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2638 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2639 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2640 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2641 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2642 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
2643 #ifndef USE_SIT_FUNCTION
2644 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2645 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2646 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2650 static const char S_I_T[][3] = {
2651 #if ENABLE_ASH_ALIAS
2652 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
2654 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2655 { CNL, CNL, CNL }, /* 2, \n */
2656 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2657 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2658 { CVAR, CVAR, CWORD }, /* 5, $ */
2659 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2660 { CSPCL, CWORD, CWORD }, /* 7, ( */
2661 { CSPCL, CWORD, CWORD }, /* 8, ) */
2662 { CBACK, CBACK, CCTL }, /* 9, \ */
2663 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2664 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
2665 #ifndef USE_SIT_FUNCTION
2666 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2667 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2668 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2671 #endif /* SH_MATH_SUPPORT */
2673 #ifdef USE_SIT_FUNCTION
2676 SIT(int c, int syntax)
2678 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2679 #if ENABLE_ASH_ALIAS
2680 static const char syntax_index_table[] ALIGN1 = {
2681 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2682 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2683 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2687 static const char syntax_index_table[] ALIGN1 = {
2688 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2689 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2690 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2697 if (c == PEOF) { /* 2^8+2 */
2700 #if ENABLE_ASH_ALIAS
2701 if (c == PEOA) { /* 2^8+1 */
2706 if ((unsigned char)c >= CTLESC
2707 && (unsigned char)c <= CTLQUOTEMARK
2711 s = strchrnul(spec_symbls, c);
2715 indx = syntax_index_table[s - spec_symbls];
2717 return S_I_T[indx][syntax];
2720 #else /* !USE_SIT_FUNCTION */
2722 #if ENABLE_ASH_ALIAS
2723 #define CSPCL_CIGN_CIGN_CIGN 0
2724 #define CSPCL_CWORD_CWORD_CWORD 1
2725 #define CNL_CNL_CNL_CNL 2
2726 #define CWORD_CCTL_CCTL_CWORD 3
2727 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2728 #define CVAR_CVAR_CWORD_CVAR 5
2729 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2730 #define CSPCL_CWORD_CWORD_CLP 7
2731 #define CSPCL_CWORD_CWORD_CRP 8
2732 #define CBACK_CBACK_CCTL_CBACK 9
2733 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2734 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2735 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2736 #define CWORD_CWORD_CWORD_CWORD 13
2737 #define CCTL_CCTL_CCTL_CCTL 14
2739 #define CSPCL_CWORD_CWORD_CWORD 0
2740 #define CNL_CNL_CNL_CNL 1
2741 #define CWORD_CCTL_CCTL_CWORD 2
2742 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2743 #define CVAR_CVAR_CWORD_CVAR 4
2744 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2745 #define CSPCL_CWORD_CWORD_CLP 6
2746 #define CSPCL_CWORD_CWORD_CRP 7
2747 #define CBACK_CBACK_CCTL_CBACK 8
2748 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2749 #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2750 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2751 #define CWORD_CWORD_CWORD_CWORD 12
2752 #define CCTL_CCTL_CCTL_CCTL 13
2755 static const char syntax_index_table[258] = {
2756 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2757 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2758 #if ENABLE_ASH_ALIAS
2759 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2761 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2762 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2763 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2764 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2765 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2766 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2767 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2768 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2769 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2770 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2771 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2772 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2773 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2774 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2775 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2776 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2777 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2778 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2779 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2780 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2781 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2782 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2793 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2794 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2795 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2796 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2797 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2798 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2799 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2800 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2801 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2802 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2803 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2804 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2805 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2806 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2807 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2808 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2809 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2810 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2811 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2812 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2813 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2814 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2815 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2816 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2817 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2818 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2819 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2820 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2821 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2822 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2823 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2824 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2825 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2826 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2827 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2828 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2829 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2830 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2831 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2832 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2833 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2834 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2835 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2836 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2837 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2838 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2839 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2840 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2841 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2842 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2899 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2900 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2922 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2923 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2924 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2926 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2928 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2929 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2930 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2931 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2932 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2934 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2935 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2936 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2937 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2948 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2949 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2950 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2951 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2952 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2953 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2981 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2982 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2983 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2986 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3006 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3007 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3008 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3009 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3010 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3011 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3012 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3013 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3014 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3015 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3016 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
3019 #define SIT(c, syntax) (S_I_T[(int)syntax_index_table[(int)(c) + SYNBASE]][syntax])
3021 #endif /* USE_SIT_FUNCTION */
3024 /* ============ Alias handling */
3026 #if ENABLE_ASH_ALIAS
3028 #define ALIASINUSE 1
3039 static struct alias **atab; // [ATABSIZE];
3040 #define INIT_G_alias() do { \
3041 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3045 static struct alias **
3046 __lookupalias(const char *name) {
3047 unsigned int hashval;
3054 ch = (unsigned char)*p;
3058 ch = (unsigned char)*++p;
3060 app = &atab[hashval % ATABSIZE];
3062 for (; *app; app = &(*app)->next) {
3063 if (strcmp(name, (*app)->name) == 0) {
3071 static struct alias *
3072 lookupalias(const char *name, int check)
3074 struct alias *ap = *__lookupalias(name);
3076 if (check && ap && (ap->flag & ALIASINUSE))
3081 static struct alias *
3082 freealias(struct alias *ap)
3086 if (ap->flag & ALIASINUSE) {
3087 ap->flag |= ALIASDEAD;
3099 setalias(const char *name, const char *val)
3101 struct alias *ap, **app;
3103 app = __lookupalias(name);
3107 if (!(ap->flag & ALIASINUSE)) {
3110 ap->val = ckstrdup(val);
3111 ap->flag &= ~ALIASDEAD;
3114 ap = ckzalloc(sizeof(struct alias));
3115 ap->name = ckstrdup(name);
3116 ap->val = ckstrdup(val);
3117 /*ap->flag = 0; - ckzalloc did it */
3118 /*ap->next = NULL;*/
3125 unalias(const char *name)
3129 app = __lookupalias(name);
3133 *app = freealias(*app);
3144 struct alias *ap, **app;
3148 for (i = 0; i < ATABSIZE; i++) {
3150 for (ap = *app; ap; ap = *app) {
3151 *app = freealias(*app);
3161 printalias(const struct alias *ap)
3163 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3167 * TODO - sort output
3169 static int FAST_FUNC
3170 aliascmd(int argc UNUSED_PARAM, char **argv)
3179 for (i = 0; i < ATABSIZE; i++) {
3180 for (ap = atab[i]; ap; ap = ap->next) {
3186 while ((n = *++argv) != NULL) {
3187 v = strchr(n+1, '=');
3188 if (v == NULL) { /* n+1: funny ksh stuff */
3189 ap = *__lookupalias(n);
3191 fprintf(stderr, "%s: %s not found\n", "alias", n);
3204 static int FAST_FUNC
3205 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3209 while ((i = nextopt("a")) != '\0') {
3215 for (i = 0; *argptr; argptr++) {
3216 if (unalias(*argptr)) {
3217 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3225 #endif /* ASH_ALIAS */
3228 /* ============ jobs.c */
3230 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3233 #define FORK_NOJOB 2
3235 /* mode flags for showjob(s) */
3236 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3237 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3238 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3241 * A job structure contains information about a job. A job is either a
3242 * single process or a set of processes contained in a pipeline. In the
3243 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3247 pid_t pid; /* process id */
3248 int status; /* last process status from wait() */
3249 char *cmd; /* text of command being run */
3253 struct procstat ps0; /* status of process */
3254 struct procstat *ps; /* status or processes when more than one */
3256 int stopstatus; /* status of a stopped job */
3259 nprocs: 16, /* number of processes */
3261 #define JOBRUNNING 0 /* at least one proc running */
3262 #define JOBSTOPPED 1 /* all procs are stopped */
3263 #define JOBDONE 2 /* all procs are completed */
3265 sigint: 1, /* job was killed by SIGINT */
3266 jobctl: 1, /* job running under job control */
3268 waited: 1, /* true if this entry has been waited for */
3269 used: 1, /* true if this entry is in used */
3270 changed: 1; /* true if status has changed */
3271 struct job *prev_job; /* previous job */
3274 static struct job *makejob(/*union node *,*/ int);
3275 static int forkshell(struct job *, union node *, int);
3276 static int waitforjob(struct job *);
3279 enum { doing_jobctl = 0 };
3280 #define setjobctl(on) do {} while (0)
3282 static smallint doing_jobctl; //references:8
3283 static void setjobctl(int);
3290 ignoresig(int signo)
3292 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3293 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3294 /* No, need to do it */
3295 signal(signo, SIG_IGN);
3297 sigmode[signo - 1] = S_HARD_IGN;
3301 * Signal handler. Only one usage site - in setsignal()
3306 gotsig[signo - 1] = 1;
3308 if (signo == SIGINT && !trap[SIGINT]) {
3309 if (!suppress_int) {
3311 raise_interrupt(); /* does not return */
3315 pending_sig = signo;
3320 * Set the signal handler for the specified signal. The routine figures
3321 * out what it should be set to.
3324 setsignal(int signo)
3327 char cur_act, new_act;
3328 struct sigaction act;
3332 if (t != NULL) { /* trap for this sig is set */
3334 if (t[0] == '\0') /* trap is "": ignore this sig */
3338 if (rootshell && new_act == S_DFL) {
3341 if (iflag || minusc || sflag == 0)
3350 * "In all cases, bash ignores SIGQUIT. Non-builtin
3351 * commands run by bash have signal handlers
3352 * set to the values inherited by the shell
3353 * from its parent". */
3369 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3370 //whereas we have to restore it to what shell got on entry
3371 //from the parent. See comment above
3373 t = &sigmode[signo - 1];
3376 /* current setting is not yet known */
3377 if (sigaction(signo, NULL, &act)) {
3378 /* pretend it worked; maybe we should give a warning,
3379 * but other shells don't. We don't alter sigmode,
3380 * so we retry every time.
3381 * btw, in Linux it never fails. --vda */
3384 if (act.sa_handler == SIG_IGN) {
3385 cur_act = S_HARD_IGN;
3387 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3389 cur_act = S_IGN; /* don't hard ignore these */
3393 if (cur_act == S_HARD_IGN || cur_act == new_act)
3396 act.sa_handler = SIG_DFL;
3399 act.sa_handler = onsig;
3400 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3401 sigfillset(&act.sa_mask); /* ditto */
3404 act.sa_handler = SIG_IGN;
3407 sigaction_set(signo, &act);
3412 /* mode flags for set_curjob */
3413 #define CUR_DELETE 2
3414 #define CUR_RUNNING 1
3415 #define CUR_STOPPED 0
3417 /* mode flags for dowait */
3418 #define DOWAIT_NONBLOCK WNOHANG
3419 #define DOWAIT_BLOCK 0
3422 /* pgrp of shell on invocation */
3423 static int initialpgrp; //references:2
3424 static int ttyfd = -1; //5
3427 static struct job *jobtab; //5
3429 static unsigned njobs; //4
3431 static struct job *curjob; //lots
3432 /* number of presumed living untracked jobs */
3433 static int jobless; //4
3436 set_curjob(struct job *jp, unsigned mode)
3439 struct job **jpp, **curp;
3441 /* first remove from list */
3442 jpp = curp = &curjob;
3447 jpp = &jp1->prev_job;
3449 *jpp = jp1->prev_job;
3451 /* Then re-insert in correct position */
3459 /* job being deleted */
3462 /* newly created job or backgrounded job,
3463 put after all stopped jobs. */
3467 if (!jp1 || jp1->state != JOBSTOPPED)
3470 jpp = &jp1->prev_job;
3476 /* newly stopped job - becomes curjob */
3477 jp->prev_job = *jpp;
3485 jobno(const struct job *jp)
3487 return jp - jobtab + 1;
3492 * Convert a job name to a job structure.
3495 #define getjob(name, getctl) getjob(name)
3498 getjob(const char *name, int getctl)
3502 const char *err_msg = "%s: no such job";
3506 char *(*match)(const char *, const char *);
3521 if (c == '+' || c == '%') {
3523 err_msg = "No current job";
3529 err_msg = "No previous job";
3540 jp = jobtab + num - 1;
3555 if (match(jp->ps[0].cmd, p)) {
3559 err_msg = "%s: ambiguous";
3569 err_msg = "job %s not created under job control";
3570 if (getctl && jp->jobctl == 0)
3575 ash_msg_and_raise_error(err_msg, name);
3579 * Mark a job structure as unused.
3582 freejob(struct job *jp)
3584 struct procstat *ps;
3588 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3589 if (ps->cmd != nullstr)
3592 if (jp->ps != &jp->ps0)
3595 set_curjob(jp, CUR_DELETE);
3601 xtcsetpgrp(int fd, pid_t pgrp)
3603 if (tcsetpgrp(fd, pgrp))
3604 ash_msg_and_raise_error("can't set tty process group (%m)");
3608 * Turn job control on and off.
3610 * Note: This code assumes that the third arg to ioctl is a character
3611 * pointer, which is true on Berkeley systems but not System V. Since
3612 * System V doesn't have job control yet, this isn't a problem now.
3614 * Called with interrupts off.
3622 if (on == doing_jobctl || rootshell == 0)
3626 ofd = fd = open(_PATH_TTY, O_RDWR);
3628 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3629 * That sometimes helps to acquire controlling tty.
3630 * Obviously, a workaround for bugs when someone
3631 * failed to provide a controlling tty to bash! :) */
3637 fd = fcntl(fd, F_DUPFD, 10);
3642 /* fd is a tty at this point */
3643 close_on_exec_on(fd);
3644 do { /* while we are in the background */
3645 pgrp = tcgetpgrp(fd);
3648 ash_msg("can't access tty; job control turned off");
3652 if (pgrp == getpgrp())
3663 xtcsetpgrp(fd, pgrp);
3665 /* turning job control off */
3668 /* was xtcsetpgrp, but this can make exiting ash
3669 * loop forever if pty is already deleted */
3670 tcsetpgrp(fd, pgrp);
3684 static int FAST_FUNC
3685 killcmd(int argc, char **argv)
3688 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3690 if (argv[i][0] == '%') {
3691 struct job *jp = getjob(argv[i], 0);
3692 unsigned pid = jp->ps[0].pid;
3693 /* Enough space for ' -NNN<nul>' */
3694 argv[i] = alloca(sizeof(int)*3 + 3);
3695 /* kill_main has matching code to expect
3696 * leading space. Needed to not confuse
3697 * negative pids with "kill -SIGNAL_NO" syntax */
3698 sprintf(argv[i], " -%u", pid);
3700 } while (argv[++i]);
3702 return kill_main(argc, argv);
3706 showpipe(struct job *jp, FILE *out)
3708 struct procstat *sp;
3709 struct procstat *spend;
3711 spend = jp->ps + jp->nprocs;
3712 for (sp = jp->ps + 1; sp < spend; sp++)
3713 fprintf(out, " | %s", sp->cmd);
3714 outcslow('\n', out);
3715 flush_stdout_stderr();
3720 restartjob(struct job *jp, int mode)
3722 struct procstat *ps;
3728 if (jp->state == JOBDONE)
3730 jp->state = JOBRUNNING;
3732 if (mode == FORK_FG)
3733 xtcsetpgrp(ttyfd, pgid);
3734 killpg(pgid, SIGCONT);
3738 if (WIFSTOPPED(ps->status)) {
3744 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3749 static int FAST_FUNC
3750 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3757 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3762 jp = getjob(*argv, 1);
3763 if (mode == FORK_BG) {
3764 set_curjob(jp, CUR_RUNNING);
3765 fprintf(out, "[%d] ", jobno(jp));
3767 outstr(jp->ps->cmd, out);
3769 retval = restartjob(jp, mode);
3770 } while (*argv && *++argv);
3776 sprint_status(char *s, int status, int sigonly)
3782 if (!WIFEXITED(status)) {
3784 if (WIFSTOPPED(status))
3785 st = WSTOPSIG(status);
3788 st = WTERMSIG(status);
3790 if (st == SIGINT || st == SIGPIPE)
3793 if (WIFSTOPPED(status))
3798 col = fmtstr(s, 32, strsignal(st));
3799 if (WCOREDUMP(status)) {
3800 col += fmtstr(s + col, 16, " (core dumped)");
3802 } else if (!sigonly) {
3803 st = WEXITSTATUS(status);
3805 col = fmtstr(s, 16, "Done(%d)", st);
3807 col = fmtstr(s, 16, "Done");
3814 dowait(int wait_flags, struct job *job)
3819 struct job *thisjob;
3822 TRACE(("dowait(0x%x) called\n", wait_flags));
3824 /* Do a wait system call. If job control is compiled in, we accept
3825 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3826 * NB: _not_ safe_waitpid, we need to detect EINTR */
3827 pid = waitpid(-1, &status,
3828 (doing_jobctl ? (wait_flags | WUNTRACED) : wait_flags));
3829 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3830 pid, status, errno, strerror(errno)));
3836 for (jp = curjob; jp; jp = jp->prev_job) {
3837 struct procstat *sp;
3838 struct procstat *spend;
3839 if (jp->state == JOBDONE)
3842 spend = jp->ps + jp->nprocs;
3845 if (sp->pid == pid) {
3846 TRACE(("Job %d: changing status of proc %d "
3847 "from 0x%x to 0x%x\n",
3848 jobno(jp), pid, sp->status, status));
3849 sp->status = status;
3852 if (sp->status == -1)
3855 if (state == JOBRUNNING)
3857 if (WIFSTOPPED(sp->status)) {
3858 jp->stopstatus = sp->status;
3862 } while (++sp < spend);
3867 if (!WIFSTOPPED(status))
3873 if (state != JOBRUNNING) {
3874 thisjob->changed = 1;
3876 if (thisjob->state != state) {
3877 TRACE(("Job %d: changing state from %d to %d\n",
3878 jobno(thisjob), thisjob->state, state));
3879 thisjob->state = state;
3881 if (state == JOBSTOPPED) {
3882 set_curjob(thisjob, CUR_STOPPED);
3891 if (thisjob && thisjob == job) {
3895 len = sprint_status(s, status, 1);
3906 blocking_wait_with_raise_on_sig(struct job *job)
3908 pid_t pid = dowait(DOWAIT_BLOCK, job);
3909 if (pid <= 0 && pending_sig)
3910 raise_exception(EXSIG);
3916 showjob(FILE *out, struct job *jp, int mode)
3918 struct procstat *ps;
3919 struct procstat *psend;
3926 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
3927 /* just output process (group) id of pipeline */
3928 fprintf(out, "%d\n", ps->pid);
3932 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3937 else if (curjob && jp == curjob->prev_job)
3940 if (mode & SHOW_PIDS)
3941 col += fmtstr(s + col, 16, "%d ", ps->pid);
3943 psend = ps + jp->nprocs;
3945 if (jp->state == JOBRUNNING) {
3946 strcpy(s + col, "Running");
3947 col += sizeof("Running") - 1;
3949 int status = psend[-1].status;
3950 if (jp->state == JOBSTOPPED)
3951 status = jp->stopstatus;
3952 col += sprint_status(s + col, status, 0);
3954 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
3956 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3957 * or prints several "PID | <cmdN>" lines,
3958 * depending on SHOW_PIDS bit.
3959 * We do not print status of individual processes
3960 * between PID and <cmdN>. bash does it, but not very well:
3961 * first line shows overall job status, not process status,
3962 * making it impossible to know 1st process status.
3966 /* for each process */
3969 if (mode & SHOW_PIDS)
3970 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->pid) - 1;
3972 fprintf(out, "%s%*c", s, 33 - col >= 0 ? 33 - col : 0, ' ');
3975 fprintf(out, "%s", ps->cmd);
3979 outcslow('\n', out);
3983 if (jp->state == JOBDONE) {
3984 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3990 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3991 * statuses have changed since the last call to showjobs.
3994 showjobs(FILE *out, int mode)
3998 TRACE(("showjobs(0x%x) called\n", mode));
4000 /* Handle all finished jobs */
4001 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4004 for (jp = curjob; jp; jp = jp->prev_job) {
4005 if (!(mode & SHOW_CHANGED) || jp->changed) {
4006 showjob(out, jp, mode);
4011 static int FAST_FUNC
4012 jobscmd(int argc UNUSED_PARAM, char **argv)
4017 while ((m = nextopt("lp")) != '\0') {
4021 mode |= SHOW_ONLY_PGID;
4027 showjob(stdout, getjob(*argv, 0), mode);
4030 showjobs(stdout, mode);
4037 getstatus(struct job *job)
4042 status = job->ps[job->nprocs - 1].status;
4043 retval = WEXITSTATUS(status);
4044 if (!WIFEXITED(status)) {
4046 retval = WSTOPSIG(status);
4047 if (!WIFSTOPPED(status))
4050 /* XXX: limits number of signals */
4051 retval = WTERMSIG(status);
4053 if (retval == SIGINT)
4059 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4060 jobno(job), job->nprocs, status, retval));
4064 static int FAST_FUNC
4065 waitcmd(int argc UNUSED_PARAM, char **argv)
4072 raise_exception(EXSIG);
4079 /* wait for all jobs */
4083 if (!jp) /* no running procs */
4085 if (jp->state == JOBRUNNING)
4091 * "When bash is waiting for an asynchronous command via
4092 * the wait builtin, the reception of a signal for which a trap
4093 * has been set will cause the wait builtin to return immediately
4094 * with an exit status greater than 128, immediately after which
4095 * the trap is executed."
4096 * Do we do it that way? */
4097 blocking_wait_with_raise_on_sig(NULL);
4103 if (**argv != '%') {
4104 pid_t pid = number(*argv);
4109 if (job->ps[job->nprocs - 1].pid == pid)
4111 job = job->prev_job;
4114 job = getjob(*argv, 0);
4115 /* loop until process terminated or stopped */
4116 while (job->state == JOBRUNNING)
4117 blocking_wait_with_raise_on_sig(NULL);
4119 retval = getstatus(job);
4132 struct job *jp, *jq;
4134 len = njobs * sizeof(*jp);
4136 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4138 offset = (char *)jp - (char *)jq;
4140 /* Relocate pointers */
4143 jq = (struct job *)((char *)jq + l);
4147 #define joff(p) ((struct job *)((char *)(p) + l))
4148 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4149 if (joff(jp)->ps == &jq->ps0)
4150 jmove(joff(jp)->ps);
4151 if (joff(jp)->prev_job)
4152 jmove(joff(jp)->prev_job);
4162 jp = (struct job *)((char *)jp + len);
4166 } while (--jq >= jp);
4171 * Return a new job structure.
4172 * Called with interrupts off.
4175 makejob(/*union node *node,*/ int nprocs)
4180 for (i = njobs, jp = jobtab; ; jp++) {
4187 if (jp->state != JOBDONE || !jp->waited)
4196 memset(jp, 0, sizeof(*jp));
4198 /* jp->jobctl is a bitfield.
4199 * "jp->jobctl |= jobctl" likely to give awful code */
4203 jp->prev_job = curjob;
4208 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4210 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4217 * Return a string identifying a command (to be printed by the
4220 static char *cmdnextc;
4223 cmdputs(const char *s)
4225 static const char vstype[VSTYPE + 1][3] = {
4226 "", "}", "-", "+", "?", "=",
4227 "%", "%%", "#", "##"
4228 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4231 const char *p, *str;
4232 char c, cc[2] = " ";
4237 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4239 while ((c = *p++) != 0) {
4247 if ((subtype & VSTYPE) == VSLENGTH)
4251 if (!(subtype & VSQUOTE) == !(quoted & 1))
4257 str = "\"}" + !(quoted & 1);
4264 case CTLBACKQ+CTLQUOTE:
4267 #if ENABLE_SH_MATH_SUPPORT
4282 if ((subtype & VSTYPE) != VSNORMAL)
4284 str = vstype[subtype & VSTYPE];
4285 if (subtype & VSNUL)
4294 /* These can only happen inside quotes */
4307 while ((c = *str++) != '\0') {
4312 USTPUTC('"', nextc);
4318 /* cmdtxt() and cmdlist() call each other */
4319 static void cmdtxt(union node *n);
4322 cmdlist(union node *np, int sep)
4324 for (; np; np = np->narg.next) {
4328 if (sep && np->narg.next)
4334 cmdtxt(union node *n)
4337 struct nodelist *lp;
4348 lp = n->npipe.cmdlist;
4366 cmdtxt(n->nbinary.ch1);
4382 cmdtxt(n->nif.test);
4384 if (n->nif.elsepart) {
4385 cmdtxt(n->nif.ifpart);
4387 n = n->nif.elsepart;
4405 cmdtxt(n->nbinary.ch1);
4415 cmdputs(n->nfor.var);
4417 cmdlist(n->nfor.args, 1);
4422 cmdputs(n->narg.text);
4426 cmdlist(n->ncmd.args, 1);
4427 cmdlist(n->ncmd.redirect, 0);
4440 cmdputs(n->ncase.expr->narg.text);
4442 for (np = n->ncase.cases; np; np = np->nclist.next) {
4443 cmdtxt(np->nclist.pattern);
4445 cmdtxt(np->nclist.body);
4459 #if ENABLE_ASH_BASH_COMPAT
4474 cmdputs(utoa(n->nfile.fd));
4476 if (n->type == NTOFD || n->type == NFROMFD) {
4477 cmdputs(utoa(n->ndup.dupfd));
4486 commandtext(union node *n)
4490 STARTSTACKSTR(cmdnextc);
4492 name = stackblock();
4493 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4494 name, cmdnextc, cmdnextc));
4495 return ckstrdup(name);
4500 * Fork off a subshell. If we are doing job control, give the subshell its
4501 * own process group. Jp is a job structure that the job is to be added to.
4502 * N is the command that will be evaluated by the child. Both jp and n may
4503 * be NULL. The mode parameter can be one of the following:
4504 * FORK_FG - Fork off a foreground process.
4505 * FORK_BG - Fork off a background process.
4506 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4507 * process group even if job control is on.
4509 * When job control is turned off, background processes have their standard
4510 * input redirected to /dev/null (except for the second and later processes
4513 * Called with interrupts off.
4516 * Clear traps on a fork.
4523 for (tp = trap; tp < &trap[NSIG]; tp++) {
4524 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4526 if (trap_ptr == trap)
4528 /* else: it "belongs" to trap_ptr vector, don't free */
4530 if ((tp - trap) != 0)
4531 setsignal(tp - trap);
4537 /* Lives far away from here, needed for forkchild */
4538 static void closescript(void);
4540 /* Called after fork(), in child */
4541 static NOINLINE void
4542 forkchild(struct job *jp, union node *n, int mode)
4546 TRACE(("Child shell %d\n", getpid()));
4550 /* man bash: "Non-builtin commands run by bash have signal handlers
4551 * set to the values inherited by the shell from its parent".
4552 * Do we do it correctly? */
4556 if (mode == FORK_NOJOB /* is it `xxx` ? */
4557 && n && n->type == NCMD /* is it single cmd? */
4558 /* && n->ncmd.args->type == NARG - always true? */
4559 && strcmp(n->ncmd.args->narg.text, "trap") == 0
4560 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4561 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4563 TRACE(("Trap hack\n"));
4564 /* Awful hack for `trap` or $(trap).
4566 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4567 * contains an example where "trap" is executed in a subshell:
4569 * save_traps=$(trap)
4571 * eval "$save_traps"
4573 * Standard does not say that "trap" in subshell shall print
4574 * parent shell's traps. It only says that its output
4575 * must have suitable form, but then, in the above example
4576 * (which is not supposed to be normative), it implies that.
4578 * bash (and probably other shell) does implement it
4579 * (traps are reset to defaults, but "trap" still shows them),
4580 * but as a result, "trap" logic is hopelessly messed up:
4583 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4584 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4585 * # true | trap <--- trap is in subshell - no output (ditto)
4586 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4587 * trap -- 'echo Ho' SIGWINCH
4588 * # echo `(trap)` <--- in subshell in subshell - output
4589 * trap -- 'echo Ho' SIGWINCH
4590 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4591 * trap -- 'echo Ho' SIGWINCH
4593 * The rules when to forget and when to not forget traps
4594 * get really complex and nonsensical.
4596 * Our solution: ONLY bare $(trap) or `trap` is special.
4598 /* Save trap handler strings for trap builtin to print */
4599 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4600 /* Fall through into clearing traps */
4604 /* do job control only in root shell */
4606 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4609 if (jp->nprocs == 0)
4612 pgrp = jp->ps[0].pid;
4613 /* this can fail because we are doing it in the parent also */
4615 if (mode == FORK_FG)
4616 xtcsetpgrp(ttyfd, pgrp);
4621 if (mode == FORK_BG) {
4622 /* man bash: "When job control is not in effect,
4623 * asynchronous commands ignore SIGINT and SIGQUIT" */
4626 if (jp->nprocs == 0) {
4628 if (open(bb_dev_null, O_RDONLY) != 0)
4629 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4633 if (iflag) { /* why if iflag only? */
4638 * "In all cases, bash ignores SIGQUIT. Non-builtin
4639 * commands run by bash have signal handlers
4640 * set to the values inherited by the shell
4642 * Take care of the second rule: */
4646 if (n && n->type == NCMD
4647 && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4649 TRACE(("Job hack\n"));
4650 /* "jobs": we do not want to clear job list for it,
4651 * instead we remove only _its_ own_ job from job list.
4652 * This makes "jobs .... | cat" more useful.
4658 for (jp = curjob; jp; jp = jp->prev_job)
4663 /* Called after fork(), in parent */
4665 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4668 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4670 TRACE(("In parent shell: child = %d\n", pid));
4672 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4678 if (mode != FORK_NOJOB && jp->jobctl) {
4681 if (jp->nprocs == 0)
4684 pgrp = jp->ps[0].pid;
4685 /* This can fail because we are doing it in the child also */
4689 if (mode == FORK_BG) {
4690 backgndpid = pid; /* set $! */
4691 set_curjob(jp, CUR_RUNNING);
4694 struct procstat *ps = &jp->ps[jp->nprocs++];
4699 if (doing_jobctl && n)
4700 ps->cmd = commandtext(n);
4706 forkshell(struct job *jp, union node *n, int mode)
4710 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4713 TRACE(("Fork failed, errno=%d", errno));
4716 ash_msg_and_raise_error("can't fork");
4719 forkchild(jp, n, mode);
4721 forkparent(jp, n, mode, pid);
4726 * Wait for job to finish.
4728 * Under job control we have the problem that while a child process
4729 * is running interrupts generated by the user are sent to the child
4730 * but not to the shell. This means that an infinite loop started by
4731 * an interactive user may be hard to kill. With job control turned off,
4732 * an interactive user may place an interactive program inside a loop.
4733 * If the interactive program catches interrupts, the user doesn't want
4734 * these interrupts to also abort the loop. The approach we take here
4735 * is to have the shell ignore interrupt signals while waiting for a
4736 * foreground process to terminate, and then send itself an interrupt
4737 * signal if the child process was terminated by an interrupt signal.
4738 * Unfortunately, some programs want to do a bit of cleanup and then
4739 * exit on interrupt; unless these processes terminate themselves by
4740 * sending a signal to themselves (instead of calling exit) they will
4741 * confuse this approach.
4743 * Called with interrupts off.
4746 waitforjob(struct job *jp)
4750 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4753 while (jp->state == JOBRUNNING) {
4754 /* In non-interactive shells, we _can_ get
4755 * a keyboard signal here and be EINTRed,
4756 * but we just loop back, waiting for command to complete.
4759 * "If bash is waiting for a command to complete and receives
4760 * a signal for which a trap has been set, the trap
4761 * will not be executed until the command completes."
4763 * Reality is that even if trap is not set, bash
4764 * will not act on the signal until command completes.
4765 * Try this. sleep5intoff.c:
4766 * #include <signal.h>
4767 * #include <unistd.h>
4770 * sigemptyset(&set);
4771 * sigaddset(&set, SIGINT);
4772 * sigaddset(&set, SIGQUIT);
4773 * sigprocmask(SIG_BLOCK, &set, NULL);
4777 * $ bash -c './sleep5intoff; echo hi'
4778 * ^C^C^C^C <--- pressing ^C once a second
4780 * $ bash -c './sleep5intoff; echo hi'
4781 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4784 dowait(DOWAIT_BLOCK, jp);
4791 xtcsetpgrp(ttyfd, rootpid);
4793 * This is truly gross.
4794 * If we're doing job control, then we did a TIOCSPGRP which
4795 * caused us (the shell) to no longer be in the controlling
4796 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4797 * intuit from the subprocess exit status whether a SIGINT
4798 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4800 if (jp->sigint) /* TODO: do the same with all signals */
4801 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4803 if (jp->state == JOBDONE)
4810 * return 1 if there are stopped jobs, otherwise 0
4822 if (jp && jp->state == JOBSTOPPED) {
4823 out2str("You have stopped jobs.\n");
4832 /* ============ redir.c
4834 * Code for dealing with input/output redirection.
4837 #define EMPTY -2 /* marks an unused slot in redirtab */
4838 #define CLOSED -3 /* marks a slot of previously-closed fd */
4841 * Open a file in noclobber mode.
4842 * The code was copied from bash.
4845 noclobberopen(const char *fname)
4848 struct stat finfo, finfo2;
4851 * If the file exists and is a regular file, return an error
4854 r = stat(fname, &finfo);
4855 if (r == 0 && S_ISREG(finfo.st_mode)) {
4861 * If the file was not present (r != 0), make sure we open it
4862 * exclusively so that if it is created before we open it, our open
4863 * will fail. Make sure that we do not truncate an existing file.
4864 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4865 * file was not a regular file, we leave O_EXCL off.
4868 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4869 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4871 /* If the open failed, return the file descriptor right away. */
4876 * OK, the open succeeded, but the file may have been changed from a
4877 * non-regular file to a regular file between the stat and the open.
4878 * We are assuming that the O_EXCL open handles the case where FILENAME
4879 * did not exist and is symlinked to an existing file between the stat
4884 * If we can open it and fstat the file descriptor, and neither check
4885 * revealed that it was a regular file, and the file has not been
4886 * replaced, return the file descriptor.
4888 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4889 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4892 /* The file has been replaced. badness. */
4899 * Handle here documents. Normally we fork off a process to write the
4900 * data to a pipe. If the document is short, we can stuff the data in
4901 * the pipe without forking.
4903 /* openhere needs this forward reference */
4904 static void expandhere(union node *arg, int fd);
4906 openhere(union node *redir)
4912 ash_msg_and_raise_error("pipe call failed");
4913 if (redir->type == NHERE) {
4914 len = strlen(redir->nhere.doc->narg.text);
4915 if (len <= PIPE_BUF) {
4916 full_write(pip[1], redir->nhere.doc->narg.text, len);
4920 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4923 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4924 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4925 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4926 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4927 signal(SIGPIPE, SIG_DFL);
4928 if (redir->type == NHERE)
4929 full_write(pip[1], redir->nhere.doc->narg.text, len);
4931 expandhere(redir->nhere.doc, pip[1]);
4932 _exit(EXIT_SUCCESS);
4940 openredirect(union node *redir)
4945 switch (redir->nfile.type) {
4947 fname = redir->nfile.expfname;
4948 f = open(fname, O_RDONLY);
4953 fname = redir->nfile.expfname;
4954 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4959 #if ENABLE_ASH_BASH_COMPAT
4962 /* Take care of noclobber mode. */
4964 fname = redir->nfile.expfname;
4965 f = noclobberopen(fname);
4972 fname = redir->nfile.expfname;
4973 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4978 fname = redir->nfile.expfname;
4979 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4987 /* Fall through to eliminate warning. */
4988 /* Our single caller does this itself */
4995 f = openhere(redir);
5001 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5003 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5007 * Copy a file descriptor to be >= to. Returns -1
5008 * if the source file descriptor is closed, EMPTY if there are no unused
5009 * file descriptors left.
5011 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5012 * old code was doing close(to) prior to copyfd() to achieve the same */
5014 COPYFD_EXACT = (int)~(INT_MAX),
5015 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5018 copyfd(int from, int to)
5022 if (to & COPYFD_EXACT) {
5023 to &= ~COPYFD_EXACT;
5025 newfd = dup2(from, to);
5027 newfd = fcntl(from, F_DUPFD, to);
5030 if (errno == EMFILE)
5032 /* Happens when source fd is not open: try "echo >&99" */
5033 ash_msg_and_raise_error("%d: %m", from);
5038 /* Struct def and variable are moved down to the first usage site */
5043 struct redirtab *next;
5046 struct two_fd_t two_fd[];
5048 #define redirlist (G_var.redirlist)
5050 static int need_to_remember(struct redirtab *rp, int fd)
5054 if (!rp) /* remembering was not requested */
5057 for (i = 0; i < rp->pair_count; i++) {
5058 if (rp->two_fd[i].orig == fd) {
5059 /* already remembered */
5066 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5067 static int is_hidden_fd(struct redirtab *rp, int fd)
5070 struct parsefile *pf;
5083 fd |= COPYFD_RESTORE;
5084 for (i = 0; i < rp->pair_count; i++) {
5085 if (rp->two_fd[i].copy == fd) {
5093 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5094 * old file descriptors are stashed away so that the redirection can be
5095 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5096 * standard output, and the standard error if it becomes a duplicate of
5097 * stdout, is saved in memory.
5099 /* flags passed to redirect */
5100 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5101 #define REDIR_SAVEFD2 03 /* set preverrout */
5103 redirect(union node *redir, int flags)
5105 struct redirtab *sv;
5110 int copied_fd2 = -1;
5120 if (flags & REDIR_PUSH) {
5121 union node *tmp = redir;
5124 #if ENABLE_ASH_BASH_COMPAT
5125 if (redir->nfile.type == NTO2)
5128 tmp = tmp->nfile.next;
5130 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5131 sv->next = redirlist;
5132 sv->pair_count = sv_pos;
5134 sv->nullredirs = g_nullredirs - 1;
5136 while (sv_pos > 0) {
5138 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5143 fd = redir->nfile.fd;
5144 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5145 int right_fd = redir->ndup.dupfd;
5146 /* redirect from/to same file descriptor? */
5149 /* echo >&10 and 10 is a fd opened to the sh script? */
5150 if (is_hidden_fd(sv, right_fd)) {
5151 errno = EBADF; /* as if it is closed */
5152 ash_msg_and_raise_error("%d: %m", right_fd);
5156 newfd = openredirect(redir); /* always >= 0 */
5158 /* Descriptor wasn't open before redirect.
5159 * Mark it for close in the future */
5160 if (need_to_remember(sv, fd)) {
5161 goto remember_to_close;
5166 #if ENABLE_ASH_BASH_COMPAT
5169 if (need_to_remember(sv, fd)) {
5170 /* Copy old descriptor */
5171 i = fcntl(fd, F_DUPFD, 10);
5172 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5173 * are closed in popredir() in the child, preventing them from leaking
5174 * into child. (popredir() also cleans up the mess in case of failures)
5179 /* Strange error (e.g. "too many files" EMFILE?) */
5183 ash_msg_and_raise_error("%d: %m", fd);
5186 /* EBADF: it is not open - good, remember to close it */
5189 } else { /* fd is open, save its copy */
5190 /* "exec fd>&-" should not close fds
5191 * which point to script file(s).
5192 * Force them to be restored afterwards */
5193 if (is_hidden_fd(sv, fd))
5194 i |= COPYFD_RESTORE;
5198 sv->two_fd[sv_pos].orig = fd;
5199 sv->two_fd[sv_pos].copy = i;
5203 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5204 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5205 /* Don't want to trigger debugging */
5209 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5211 } else if (fd != newfd) { /* move newfd to fd */
5212 copyfd(newfd, fd | COPYFD_EXACT);
5213 #if ENABLE_ASH_BASH_COMPAT
5214 if (!(redir->nfile.type == NTO2 && fd == 2))
5218 #if ENABLE_ASH_BASH_COMPAT
5219 if (redir->nfile.type == NTO2 && fd == 1) {
5220 /* We already redirected it to fd 1, now copy it to 2 */
5226 } while ((redir = redir->nfile.next) != NULL);
5229 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5230 preverrout_fd = copied_fd2;
5234 * Undo the effects of the last redirection.
5237 popredir(int drop, int restore)
5239 struct redirtab *rp;
5242 if (--g_nullredirs >= 0)
5246 for (i = 0; i < rp->pair_count; i++) {
5247 int fd = rp->two_fd[i].orig;
5248 int copy = rp->two_fd[i].copy;
5249 if (copy == CLOSED) {
5254 if (copy != EMPTY) {
5255 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5256 copy &= ~COPYFD_RESTORE;
5258 copyfd(copy, fd | COPYFD_EXACT);
5260 close(copy & ~COPYFD_RESTORE);
5263 redirlist = rp->next;
5264 g_nullredirs = rp->nullredirs;
5270 * Undo all redirections. Called on error or interrupt.
5274 * Discard all saved file descriptors.
5277 clearredir(int drop)
5283 popredir(drop, /*restore:*/ 0);
5288 redirectsafe(union node *redir, int flags)
5291 volatile int saveint;
5292 struct jmploc *volatile savehandler = exception_handler;
5293 struct jmploc jmploc;
5296 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5297 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5299 exception_handler = &jmploc;
5300 redirect(redir, flags);
5302 exception_handler = savehandler;
5303 if (err && exception_type != EXERROR)
5304 longjmp(exception_handler->loc, 1);
5305 RESTORE_INT(saveint);
5310 /* ============ Routines to expand arguments to commands
5312 * We have to deal with backquotes, shell variables, and file metacharacters.
5315 #if ENABLE_SH_MATH_SUPPORT
5317 ash_arith(const char *s)
5319 arith_eval_hooks_t math_hooks;
5323 math_hooks.lookupvar = lookupvar;
5324 math_hooks.setvar = setvar;
5325 math_hooks.endofname = endofname;
5328 result = arith(s, &errcode, &math_hooks);
5331 ash_msg_and_raise_error("exponent less than 0");
5333 ash_msg_and_raise_error("divide by zero");
5335 ash_msg_and_raise_error("expression recursion loop detected");
5336 raise_error_syntax(s);
5347 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5348 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5349 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5350 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5351 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5352 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5353 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5354 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5355 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5359 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5360 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5361 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5362 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5363 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5366 * Structure specifying which parts of the string should be searched
5367 * for IFS characters.
5370 struct ifsregion *next; /* next region in list */
5371 int begoff; /* offset of start of region */
5372 int endoff; /* offset of end of region */
5373 int nulonly; /* search for nul bytes only */
5377 struct strlist *list;
5378 struct strlist **lastp;
5381 /* output of current string */
5382 static char *expdest;
5383 /* list of back quote expressions */
5384 static struct nodelist *argbackq;
5385 /* first struct in list of ifs regions */
5386 static struct ifsregion ifsfirst;
5387 /* last struct in list */
5388 static struct ifsregion *ifslastp;
5389 /* holds expanded arg list */
5390 static struct arglist exparg;
5400 expdest = makestrspace(32, expdest);
5401 len = fmtstr(expdest, 32, arith_t_fmt, num);
5402 STADJUST(len, expdest);
5407 esclen(const char *start, const char *p)
5411 while (p > start && (unsigned char)*--p == CTLESC) {
5418 * Remove any CTLESC characters from a string.
5421 rmescapes(char *str, int flag)
5423 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5427 unsigned protect_against_glob;
5430 p = strpbrk(str, qchars);
5436 if (flag & RMESCAPE_ALLOC) {
5437 size_t len = p - str;
5438 size_t fulllen = len + strlen(p) + 1;
5440 if (flag & RMESCAPE_GROW) {
5441 r = makestrspace(fulllen, expdest);
5442 } else if (flag & RMESCAPE_HEAP) {
5443 r = ckmalloc(fulllen);
5445 r = stalloc(fulllen);
5449 q = (char *)memcpy(q, str, len) + len;
5453 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5454 globbing = flag & RMESCAPE_GLOB;
5455 protect_against_glob = globbing;
5457 if (*p == CTLQUOTEMARK) {
5458 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5459 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5460 // Note: both inquotes and protect_against_glob only affect whether
5461 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5462 inquotes = ~inquotes;
5464 protect_against_glob = globbing;
5468 /* naked back slash */
5469 protect_against_glob = 0;
5474 if (protect_against_glob && inquotes && *p != '/') {
5478 protect_against_glob = globbing;
5483 if (flag & RMESCAPE_GROW) {
5485 STADJUST(q - r + 1, expdest);
5489 #define pmatch(a, b) !fnmatch((a), (b), 0)
5492 * Prepare a pattern for a expmeta (internal glob(3)) call.
5494 * Returns an stalloced string.
5497 preglob(const char *pattern, int quoted, int flag)
5499 flag |= RMESCAPE_GLOB;
5501 flag |= RMESCAPE_QUOTED;
5503 return rmescapes((char *)pattern, flag);
5507 * Put a string on the stack.
5510 memtodest(const char *p, size_t len, int syntax, int quotes)
5514 q = makestrspace(quotes ? len * 2 : len, q);
5517 int c = signed_char2int(*p++);
5521 int n = SIT(c, syntax);
5522 if (n == CCTL || n == CBACK)
5532 strtodest(const char *p, int syntax, int quotes)
5534 memtodest(p, strlen(p), syntax, quotes);
5538 * Record the fact that we have to scan this region of the
5539 * string for IFS characters.
5542 recordregion(int start, int end, int nulonly)
5544 struct ifsregion *ifsp;
5546 if (ifslastp == NULL) {
5550 ifsp = ckzalloc(sizeof(*ifsp));
5551 /*ifsp->next = NULL; - ckzalloc did it */
5552 ifslastp->next = ifsp;
5556 ifslastp->begoff = start;
5557 ifslastp->endoff = end;
5558 ifslastp->nulonly = nulonly;
5562 removerecordregions(int endoff)
5564 if (ifslastp == NULL)
5567 if (ifsfirst.endoff > endoff) {
5568 while (ifsfirst.next != NULL) {
5569 struct ifsregion *ifsp;
5571 ifsp = ifsfirst.next->next;
5572 free(ifsfirst.next);
5573 ifsfirst.next = ifsp;
5576 if (ifsfirst.begoff > endoff)
5579 ifslastp = &ifsfirst;
5580 ifsfirst.endoff = endoff;
5585 ifslastp = &ifsfirst;
5586 while (ifslastp->next && ifslastp->next->begoff < endoff)
5587 ifslastp=ifslastp->next;
5588 while (ifslastp->next != NULL) {
5589 struct ifsregion *ifsp;
5591 ifsp = ifslastp->next->next;
5592 free(ifslastp->next);
5593 ifslastp->next = ifsp;
5596 if (ifslastp->endoff > endoff)
5597 ifslastp->endoff = endoff;
5601 exptilde(char *startp, char *p, int flags)
5607 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5612 while ((c = *++p) != '\0') {
5619 if (flags & EXP_VARTILDE)
5629 if (*name == '\0') {
5630 home = lookupvar(homestr);
5632 pw = getpwnam(name);
5637 if (!home || !*home)
5640 startloc = expdest - (char *)stackblock();
5641 strtodest(home, SQSYNTAX, quotes);
5642 recordregion(startloc, expdest - (char *)stackblock(), 0);
5650 * Execute a command inside back quotes. If it's a builtin command, we
5651 * want to save its output in a block obtained from malloc. Otherwise
5652 * we fork off a subprocess and get the output of the command via a pipe.
5653 * Should be called with interrupts off.
5655 struct backcmd { /* result of evalbackcmd */
5656 int fd; /* file descriptor to read from */
5657 int nleft; /* number of chars in buffer */
5658 char *buf; /* buffer */
5659 struct job *jp; /* job structure for command */
5662 /* These forward decls are needed to use "eval" code for backticks handling: */
5663 static uint8_t back_exitstatus; /* exit status of backquoted command */
5664 #define EV_EXIT 01 /* exit after evaluating tree */
5665 static void evaltree(union node *, int);
5667 static void FAST_FUNC
5668 evalbackcmd(union node *n, struct backcmd *result)
5679 saveherefd = herefd;
5687 ash_msg_and_raise_error("pipe call failed");
5688 jp = makejob(/*n,*/ 1);
5689 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5694 copyfd(pip[1], 1 | COPYFD_EXACT);
5698 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5702 result->fd = pip[0];
5705 herefd = saveherefd;
5707 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5708 result->fd, result->buf, result->nleft, result->jp));
5712 * Expand stuff in backwards quotes.
5715 expbackq(union node *cmd, int quoted, int quotes)
5723 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5724 struct stackmark smark;
5727 setstackmark(&smark);
5729 startloc = dest - (char *)stackblock();
5731 evalbackcmd(cmd, &in);
5732 popstackmark(&smark);
5739 memtodest(p, i, syntax, quotes);
5743 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5744 TRACE(("expbackq: read returns %d\n", i));
5753 back_exitstatus = waitforjob(in.jp);
5757 /* Eat all trailing newlines */
5759 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5764 recordregion(startloc, dest - (char *)stackblock(), 0);
5765 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5766 (dest - (char *)stackblock()) - startloc,
5767 (dest - (char *)stackblock()) - startloc,
5768 stackblock() + startloc));
5771 #if ENABLE_SH_MATH_SUPPORT
5773 * Expand arithmetic expression. Backup to start of expression,
5774 * evaluate, place result in (backed up) result, adjust string position.
5787 * This routine is slightly over-complicated for
5788 * efficiency. Next we scan backwards looking for the
5789 * start of arithmetic.
5791 start = stackblock();
5798 while (*p != CTLARI) {
5802 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5807 esc = esclen(start, p);
5817 removerecordregions(begoff);
5824 rmescapes(p + 2, 0);
5826 len = cvtnum(ash_arith(p + 2));
5829 recordregion(begoff, begoff + len, 0);
5833 /* argstr needs it */
5834 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5837 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5838 * characters to allow for further processing. Otherwise treat
5839 * $@ like $* since no splitting will be performed.
5841 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5842 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5843 * for correct expansion of "B=$A" word.
5846 argstr(char *p, int flags, struct strlist *var_str_list)
5848 static const char spclchars[] ALIGN1 = {
5856 CTLBACKQ | CTLQUOTE,
5857 #if ENABLE_SH_MATH_SUPPORT
5862 const char *reject = spclchars;
5864 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5865 int breakall = flags & EXP_WORD;
5870 if (!(flags & EXP_VARTILDE)) {
5872 } else if (flags & EXP_VARTILDE2) {
5877 if (flags & EXP_TILDE) {
5880 flags &= ~EXP_TILDE;
5883 if (*q == CTLESC && (flags & EXP_QWORD))
5886 p = exptilde(p, q, flags);
5889 startloc = expdest - (char *)stackblock();
5891 length += strcspn(p + length, reject);
5892 c = (unsigned char) p[length];
5895 #if ENABLE_SH_MATH_SUPPORT
5899 /* c == '=' || c == ':' || c == CTLENDARI */
5905 expdest = stack_nputstr(p, length, expdest);
5906 newloc = expdest - (char *)stackblock();
5907 if (breakall && !inquotes && newloc > startloc) {
5908 recordregion(startloc, newloc, 0);
5919 if (flags & EXP_VARTILDE2) {
5923 flags |= EXP_VARTILDE2;
5928 * sort of a hack - expand tildes in variable
5929 * assignments (after the first '=' and after ':'s).
5938 case CTLENDVAR: /* ??? */
5941 /* "$@" syntax adherence hack */
5943 && memcmp(p, dolatstr, 4) == 0
5944 && ( p[4] == CTLQUOTEMARK
5945 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5948 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
5951 inquotes = !inquotes;
5964 p = evalvar(p, flags, var_str_list);
5968 case CTLBACKQ|CTLQUOTE:
5969 expbackq(argbackq->n, c, quotes);
5970 argbackq = argbackq->next;
5972 #if ENABLE_SH_MATH_SUPPORT
5985 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
5988 // This commented out code was added by James Simmons <jsimmons@infradead.org>
5989 // as part of a larger change when he added support for ${var/a/b}.
5990 // However, it broke # and % operators:
5994 //echo ${var#ab} abcdcd abcdcd
5995 //echo ${var##ab} abcdcd abcdcd
5996 //echo ${var#a*b} abcdcd ababcdcd (!)
5997 //echo ${var##a*b} cdcd cdcd
5998 //echo ${var#?} babcdcd ababcdcd (!)
5999 //echo ${var##?} babcdcd babcdcd
6000 //echo ${var#*} ababcdcd babcdcd (!)
6002 //echo ${var%cd} ababcd ababcd
6003 //echo ${var%%cd} ababcd abab (!)
6004 //echo ${var%c*d} ababcd ababcd
6005 //echo ${var%%c*d} abab ababcdcd (!)
6006 //echo ${var%?} ababcdc ababcdc
6007 //echo ${var%%?} ababcdc ababcdcd (!)
6008 //echo ${var%*} ababcdcd ababcdcd
6011 // Commenting it back out helped. Remove it completely if it really
6014 char *loc, *loc2; //, *full;
6020 int match; // = strlen(str);
6021 const char *s = loc2;
6028 match = pmatch(str, s); // this line was deleted
6030 // // chop off end if its '*'
6031 // full = strrchr(str, '*');
6032 // if (full && full != str)
6035 // // If str starts with '*' replace with s.
6036 // if ((*str == '*') && strlen(s) >= match) {
6037 // full = xstrdup(s);
6038 // strncpy(full+strlen(s)-match+1, str+1, match-1);
6040 // full = xstrndup(str, match);
6041 // match = strncmp(s, full, strlen(full));
6045 if (match) // if (!match)
6047 if (quotes && *loc == CTLESC)
6056 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6063 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6066 const char *s = loc2;
6071 match = pmatch(str, s);
6078 esc = esclen(startp, loc);
6089 static void varunset(const char *, const char *, const char *, int) NORETURN;
6091 varunset(const char *end, const char *var, const char *umsg, int varflags)
6097 msg = "parameter not set";
6099 if (*end == CTLENDVAR) {
6100 if (varflags & VSNUL)
6106 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6109 #if ENABLE_ASH_BASH_COMPAT
6111 parse_sub_pattern(char *arg, int inquotes)
6113 char *idx, *repl = NULL;
6122 /* Only the first '/' seen is our separator */
6129 if (!inquotes && c == '\\' && arg[1] == '\\')
6130 arg++; /* skip both \\, not just first one */
6137 #endif /* ENABLE_ASH_BASH_COMPAT */
6140 subevalvar(char *p, char *str, int strloc, int subtype,
6141 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6143 struct nodelist *saveargbackq = argbackq;
6146 char *rmesc, *rmescend;
6147 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6148 IF_ASH_BASH_COMPAT(char null = '\0';)
6149 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6150 int saveherefd = herefd;
6151 int amount, workloc, resetloc;
6153 char *(*scan)(char*, char*, char*, char*, int, int);
6156 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6158 STPUTC('\0', expdest);
6159 herefd = saveherefd;
6160 argbackq = saveargbackq;
6161 startp = (char *)stackblock() + startloc;
6165 setvar(str, startp, 0);
6166 amount = startp - expdest;
6167 STADJUST(amount, expdest);
6170 #if ENABLE_ASH_BASH_COMPAT
6172 loc = str = stackblock() + strloc;
6173 /* Read POS in ${var:POS:LEN} */
6174 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6175 len = str - startp - 1;
6177 /* *loc != '\0', guaranteed by parser */
6181 /* Adjust the length by the number of escapes */
6182 for (ptr = startp; ptr < (str - 1); ptr++) {
6183 if (*ptr == CTLESC) {
6191 if (*loc++ == ':') {
6195 /* Skip POS in ${var:POS:LEN} */
6197 while (*loc && *loc != ':') {
6199 * bash complains on: var=qwe; echo ${var:1a:123}
6201 ash_msg_and_raise_error(msg_illnum, str);
6205 if (*loc++ == ':') {
6209 if (pos >= orig_len) {
6213 if (len > (orig_len - pos))
6214 len = orig_len - pos;
6216 for (str = startp; pos; str++, pos--) {
6217 if (quotes && *str == CTLESC)
6220 for (loc = startp; len; len--) {
6221 if (quotes && *str == CTLESC)
6226 amount = loc - expdest;
6227 STADJUST(amount, expdest);
6232 varunset(p, str, startp, varflags);
6235 resetloc = expdest - (char *)stackblock();
6237 /* We'll comeback here if we grow the stack while handling
6238 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6239 * stack will need rebasing, and we'll need to remove our work
6242 IF_ASH_BASH_COMPAT(restart:)
6244 amount = expdest - ((char *)stackblock() + resetloc);
6245 STADJUST(-amount, expdest);
6246 startp = (char *)stackblock() + startloc;
6249 rmescend = (char *)stackblock() + strloc;
6251 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6252 if (rmesc != startp) {
6254 startp = (char *)stackblock() + startloc;
6258 str = (char *)stackblock() + strloc;
6259 preglob(str, varflags & VSQUOTE, 0);
6260 workloc = expdest - (char *)stackblock();
6262 #if ENABLE_ASH_BASH_COMPAT
6263 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6264 char *idx, *end, *restart_detect;
6267 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6272 /* If there's no pattern to match, return the expansion unmolested */
6280 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6282 /* No match, advance */
6283 restart_detect = stackblock();
6284 STPUTC(*idx, expdest);
6285 if (quotes && *idx == CTLESC) {
6288 STPUTC(*idx, expdest);
6290 if (stackblock() != restart_detect)
6298 if (subtype == VSREPLACEALL) {
6300 if (quotes && *idx == CTLESC)
6309 for (loc = repl; *loc; loc++) {
6310 restart_detect = stackblock();
6311 STPUTC(*loc, expdest);
6312 if (stackblock() != restart_detect)
6317 if (subtype == VSREPLACE) {
6319 restart_detect = stackblock();
6320 STPUTC(*idx, expdest);
6321 if (stackblock() != restart_detect)
6330 /* We've put the replaced text into a buffer at workloc, now
6331 * move it to the right place and adjust the stack.
6333 startp = stackblock() + startloc;
6334 STPUTC('\0', expdest);
6335 memmove(startp, stackblock() + workloc, len);
6336 startp[len++] = '\0';
6337 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6338 STADJUST(-amount, expdest);
6341 #endif /* ENABLE_ASH_BASH_COMPAT */
6343 subtype -= VSTRIMRIGHT;
6345 if (subtype < 0 || subtype > 7)
6348 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6349 zero = subtype >> 1;
6350 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6351 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6353 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6356 memmove(startp, loc, str - loc);
6357 loc = startp + (str - loc) - 1;
6360 amount = loc - expdest;
6361 STADJUST(amount, expdest);
6367 * Add the value of a specialized variable to the stack string.
6368 * name parameter (examples):
6369 * ash -c 'echo $1' name:'1='
6370 * ash -c 'echo $qwe' name:'qwe='
6371 * ash -c 'echo $$' name:'$='
6372 * ash -c 'echo ${$}' name:'$='
6373 * ash -c 'echo ${$##q}' name:'$=q'
6374 * ash -c 'echo ${#$}' name:'$='
6375 * note: examples with bad shell syntax:
6376 * ash -c 'echo ${#$1}' name:'$=1'
6377 * ash -c 'echo ${#1#}' name:'1=#'
6379 static NOINLINE ssize_t
6380 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6390 int quoted = varflags & VSQUOTE;
6391 int subtype = varflags & VSTYPE;
6392 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6394 if (quoted && (flags & EXP_FULL))
6395 sep = 1 << CHAR_BIT;
6397 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6406 num = shellparam.nparam;
6414 goto check_1char_name;
6416 expdest = makestrspace(NOPTS, expdest);
6417 for (i = NOPTS - 1; i >= 0; i--) {
6419 USTPUTC(optletters(i), expdest);
6425 /* handles cases similar to ${#$1} */
6426 if (name[2] != '\0')
6427 raise_error_syntax("bad substitution");
6435 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
6436 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6442 while ((p = *ap++) != NULL) {
6445 partlen = strlen(p);
6448 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6449 memtodest(p, partlen, syntax, quotes);
6455 if (subtype == VSPLUS || subtype == VSLENGTH) {
6476 num = atoi(name); /* number(name) fails on ${N#str} etc */
6477 if (num < 0 || num > shellparam.nparam)
6479 p = num ? shellparam.p[num - 1] : arg0;
6482 /* NB: name has form "VAR=..." */
6484 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6485 * which should be considered before we check variables. */
6487 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6491 str = var_str_list->text;
6492 eq = strchr(str, '=');
6493 if (!eq) /* stop at first non-assignment */
6496 if (name_len == (unsigned)(eq - str)
6497 && strncmp(str, name, name_len) == 0) {
6499 /* goto value; - WRONG! */
6500 /* think "A=1 A=2 B=$A" */
6502 var_str_list = var_str_list->next;
6503 } while (var_str_list);
6507 p = lookupvar(name);
6513 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6514 memtodest(p, len, syntax, quotes);
6518 if (subtype == VSPLUS || subtype == VSLENGTH)
6519 STADJUST(-len, expdest);
6524 * Expand a variable, and return a pointer to the next character in the
6528 evalvar(char *p, int flags, struct strlist *var_str_list)
6539 varflags = (unsigned char) *p++;
6540 subtype = varflags & VSTYPE;
6541 quoted = varflags & VSQUOTE;
6543 easy = (!quoted || (*var == '@' && shellparam.nparam));
6544 startloc = expdest - (char *)stackblock();
6545 p = strchr(p, '=') + 1;
6548 varlen = varvalue(var, varflags, flags, var_str_list);
6549 if (varflags & VSNUL)
6552 if (subtype == VSPLUS) {
6553 varlen = -1 - varlen;
6557 if (subtype == VSMINUS) {
6561 p, flags | EXP_TILDE |
6562 (quoted ? EXP_QWORD : EXP_WORD),
6572 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6574 if (subevalvar(p, var, /* strloc: */ 0,
6575 subtype, startloc, varflags,
6581 * Remove any recorded regions beyond
6584 removerecordregions(startloc);
6594 if (varlen < 0 && uflag)
6595 varunset(p, var, 0, 0);
6597 if (subtype == VSLENGTH) {
6598 cvtnum(varlen > 0 ? varlen : 0);
6602 if (subtype == VSNORMAL) {
6613 case VSTRIMRIGHTMAX:
6614 #if ENABLE_ASH_BASH_COMPAT
6627 * Terminate the string and start recording the pattern
6630 STPUTC('\0', expdest);
6631 patloc = expdest - (char *)stackblock();
6632 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6634 //TODO: | EXP_REDIR too? All other such places do it too
6635 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6638 int amount = expdest - (
6639 (char *)stackblock() + patloc - 1
6641 STADJUST(-amount, expdest);
6643 /* Remove any recorded regions beyond start of variable */
6644 removerecordregions(startloc);
6646 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6650 if (subtype != VSNORMAL) { /* skip to end of alternative */
6656 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6658 argbackq = argbackq->next;
6659 } else if (c == CTLVAR) {
6660 if ((*p++ & VSTYPE) != VSNORMAL)
6662 } else if (c == CTLENDVAR) {
6672 * Break the argument string into pieces based upon IFS and add the
6673 * strings to the argument list. The regions of the string to be
6674 * searched for IFS characters have been stored by recordregion.
6677 ifsbreakup(char *string, struct arglist *arglist)
6679 struct ifsregion *ifsp;
6684 const char *ifs, *realifs;
6689 if (ifslastp != NULL) {
6692 realifs = ifsset() ? ifsval() : defifs;
6695 p = string + ifsp->begoff;
6696 nulonly = ifsp->nulonly;
6697 ifs = nulonly ? nullstr : realifs;
6699 while (p < string + ifsp->endoff) {
6703 if (!strchr(ifs, *p)) {
6708 ifsspc = (strchr(defifs, *p) != NULL);
6709 /* Ignore IFS whitespace at start */
6710 if (q == start && ifsspc) {
6716 sp = stzalloc(sizeof(*sp));
6718 *arglist->lastp = sp;
6719 arglist->lastp = &sp->next;
6723 if (p >= string + ifsp->endoff) {
6729 if (strchr(ifs, *p) == NULL) {
6733 if (strchr(defifs, *p) == NULL) {
6748 } while (ifsp != NULL);
6757 sp = stzalloc(sizeof(*sp));
6759 *arglist->lastp = sp;
6760 arglist->lastp = &sp->next;
6766 struct ifsregion *p;
6771 struct ifsregion *ifsp;
6777 ifsfirst.next = NULL;
6782 * Add a file name to the list.
6785 addfname(const char *name)
6789 sp = stzalloc(sizeof(*sp));
6790 sp->text = ststrdup(name);
6792 exparg.lastp = &sp->next;
6795 static char *expdir;
6798 * Do metacharacter (i.e. *, ?, [...]) expansion.
6801 expmeta(char *enddir, char *name)
6816 for (p = name; *p; p++) {
6817 if (*p == '*' || *p == '?')
6819 else if (*p == '[') {
6826 if (*q == '/' || *q == '\0')
6833 } else if (*p == '\\')
6835 else if (*p == '/') {
6842 if (metaflag == 0) { /* we've reached the end of the file name */
6843 if (enddir != expdir)
6851 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6862 } while (p < start);
6864 if (enddir == expdir) {
6866 } else if (enddir == expdir + 1 && *expdir == '/') {
6875 if (enddir != expdir)
6877 if (*endname == 0) {
6889 while (!pending_int && (dp = readdir(dirp)) != NULL) {
6890 if (dp->d_name[0] == '.' && !matchdot)
6892 if (pmatch(start, dp->d_name)) {
6894 strcpy(enddir, dp->d_name);
6897 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6900 expmeta(p, endname);
6909 static struct strlist *
6910 msort(struct strlist *list, int len)
6912 struct strlist *p, *q = NULL;
6913 struct strlist **lpp;
6921 for (n = half; --n >= 0;) {
6925 q->next = NULL; /* terminate first half of list */
6926 q = msort(list, half); /* sort first half of list */
6927 p = msort(p, len - half); /* sort second half */
6930 #if ENABLE_LOCALE_SUPPORT
6931 if (strcoll(p->text, q->text) < 0)
6933 if (strcmp(p->text, q->text) < 0)
6957 * Sort the results of file name expansion. It calculates the number of
6958 * strings to sort and then calls msort (short for merge sort) to do the
6961 static struct strlist *
6962 expsort(struct strlist *str)
6968 for (sp = str; sp; sp = sp->next)
6970 return msort(str, len);
6974 expandmeta(struct strlist *str /*, int flag*/)
6976 static const char metachars[] ALIGN1 = {
6979 /* TODO - EXP_REDIR */
6982 struct strlist **savelastp;
6988 if (!strpbrk(str->text, metachars))
6990 savelastp = exparg.lastp;
6993 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6995 int i = strlen(str->text);
6996 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7004 if (exparg.lastp == savelastp) {
7009 *exparg.lastp = str;
7010 rmescapes(str->text, 0);
7011 exparg.lastp = &str->next;
7013 *exparg.lastp = NULL;
7014 *savelastp = sp = expsort(*savelastp);
7015 while (sp->next != NULL)
7017 exparg.lastp = &sp->next;
7024 * Perform variable substitution and command substitution on an argument,
7025 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7026 * perform splitting and file name expansion. When arglist is NULL, perform
7027 * here document expansion.
7030 expandarg(union node *arg, struct arglist *arglist, int flag)
7035 argbackq = arg->narg.backquote;
7036 STARTSTACKSTR(expdest);
7037 ifsfirst.next = NULL;
7039 argstr(arg->narg.text, flag,
7040 /* var_str_list: */ arglist ? arglist->list : NULL);
7041 p = _STPUTC('\0', expdest);
7043 if (arglist == NULL) {
7044 return; /* here document expanded */
7046 p = grabstackstr(p);
7047 exparg.lastp = &exparg.list;
7051 if (flag & EXP_FULL) {
7052 ifsbreakup(p, &exparg);
7053 *exparg.lastp = NULL;
7054 exparg.lastp = &exparg.list;
7055 expandmeta(exparg.list /*, flag*/);
7057 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7059 sp = stzalloc(sizeof(*sp));
7062 exparg.lastp = &sp->next;
7066 *exparg.lastp = NULL;
7068 *arglist->lastp = exparg.list;
7069 arglist->lastp = exparg.lastp;
7074 * Expand shell variables and backquotes inside a here document.
7077 expandhere(union node *arg, int fd)
7080 expandarg(arg, (struct arglist *)NULL, 0);
7081 full_write(fd, stackblock(), expdest - (char *)stackblock());
7085 * Returns true if the pattern matches the string.
7088 patmatch(char *pattern, const char *string)
7090 return pmatch(preglob(pattern, 0, 0), string);
7094 * See if a pattern matches in a case statement.
7097 casematch(union node *pattern, char *val)
7099 struct stackmark smark;
7102 setstackmark(&smark);
7103 argbackq = pattern->narg.backquote;
7104 STARTSTACKSTR(expdest);
7106 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7107 /* var_str_list: */ NULL);
7108 STACKSTRNUL(expdest);
7109 result = patmatch(stackblock(), val);
7110 popstackmark(&smark);
7115 /* ============ find_command */
7119 int (*builtin)(int, char **) FAST_FUNC;
7120 /* unsigned flags; */
7122 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7123 /* "regular" builtins always take precedence over commands,
7124 * regardless of PATH=....%builtin... position */
7125 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7126 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7129 smallint cmdtype; /* CMDxxx */
7132 /* index >= 0 for commands without path (slashes) */
7133 /* (TODO: what exactly does the value mean? PATH position?) */
7134 /* index == -1 for commands with slashes */
7135 /* index == (-2 - applet_no) for NOFORK applets */
7136 const struct builtincmd *cmd;
7137 struct funcnode *func;
7140 /* values of cmdtype */
7141 #define CMDUNKNOWN -1 /* no entry in table for command */
7142 #define CMDNORMAL 0 /* command is an executable program */
7143 #define CMDFUNCTION 1 /* command is a shell function */
7144 #define CMDBUILTIN 2 /* command is a shell builtin */
7146 /* action to find_command() */
7147 #define DO_ERR 0x01 /* prints errors */
7148 #define DO_ABS 0x02 /* checks absolute paths */
7149 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7150 #define DO_ALTPATH 0x08 /* using alternate path */
7151 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7153 static void find_command(char *, struct cmdentry *, int, const char *);
7156 /* ============ Hashing commands */
7159 * When commands are first encountered, they are entered in a hash table.
7160 * This ensures that a full path search will not have to be done for them
7161 * on each invocation.
7163 * We should investigate converting to a linear search, even though that
7164 * would make the command name "hash" a misnomer.
7168 struct tblentry *next; /* next entry in hash chain */
7169 union param param; /* definition of builtin function */
7170 smallint cmdtype; /* CMDxxx */
7171 char rehash; /* if set, cd done since entry created */
7172 char cmdname[1]; /* name of command */
7175 static struct tblentry **cmdtable;
7176 #define INIT_G_cmdtable() do { \
7177 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7180 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7184 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7188 #if ENABLE_FEATURE_SH_STANDALONE
7189 if (applet_no >= 0) {
7190 if (APPLET_IS_NOEXEC(applet_no)) {
7193 run_applet_no_and_exit(applet_no, argv);
7195 /* re-exec ourselves with the new arguments */
7196 execve(bb_busybox_exec_path, argv, envp);
7197 /* If they called chroot or otherwise made the binary no longer
7198 * executable, fall through */
7205 execve(cmd, argv, envp);
7206 } while (errno == EINTR);
7208 execve(cmd, argv, envp);
7214 if (errno == ENOEXEC) {
7218 for (ap = argv; *ap; ap++)
7220 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7222 ap[0] = cmd = (char *)DEFAULT_SHELL;
7225 while ((*ap++ = *argv++) != NULL)
7234 * Exec a program. Never returns. If you change this routine, you may
7235 * have to change the find_command routine as well.
7237 static void shellexec(char **, const char *, int) NORETURN;
7239 shellexec(char **argv, const char *path, int idx)
7245 #if ENABLE_FEATURE_SH_STANDALONE
7249 clearredir(/*drop:*/ 1);
7250 envp = listvars(VEXPORT, VUNSET, 0);
7251 if (strchr(argv[0], '/') != NULL
7252 #if ENABLE_FEATURE_SH_STANDALONE
7253 || (applet_no = find_applet_by_name(argv[0])) >= 0
7256 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7260 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7261 if (--idx < 0 && pathopt == NULL) {
7262 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7263 if (errno != ENOENT && errno != ENOTDIR)
7270 /* Map to POSIX errors */
7282 exitstatus = exerrno;
7283 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7284 argv[0], e, suppress_int));
7285 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7290 printentry(struct tblentry *cmdp)
7296 idx = cmdp->param.index;
7299 name = path_advance(&path, cmdp->cmdname);
7301 } while (--idx >= 0);
7302 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7306 * Clear out command entries. The argument specifies the first entry in
7307 * PATH which has changed.
7310 clearcmdentry(int firstchange)
7312 struct tblentry **tblp;
7313 struct tblentry **pp;
7314 struct tblentry *cmdp;
7317 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7319 while ((cmdp = *pp) != NULL) {
7320 if ((cmdp->cmdtype == CMDNORMAL &&
7321 cmdp->param.index >= firstchange)
7322 || (cmdp->cmdtype == CMDBUILTIN &&
7323 builtinloc >= firstchange)
7336 * Locate a command in the command hash table. If "add" is nonzero,
7337 * add the command to the table if it is not already present. The
7338 * variable "lastcmdentry" is set to point to the address of the link
7339 * pointing to the entry, so that delete_cmd_entry can delete the
7342 * Interrupts must be off if called with add != 0.
7344 static struct tblentry **lastcmdentry;
7346 static struct tblentry *
7347 cmdlookup(const char *name, int add)
7349 unsigned int hashval;
7351 struct tblentry *cmdp;
7352 struct tblentry **pp;
7355 hashval = (unsigned char)*p << 4;
7357 hashval += (unsigned char)*p++;
7359 pp = &cmdtable[hashval % CMDTABLESIZE];
7360 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7361 if (strcmp(cmdp->cmdname, name) == 0)
7365 if (add && cmdp == NULL) {
7366 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7368 /* + 1 - already done because
7369 * tblentry::cmdname is char[1] */);
7370 /*cmdp->next = NULL; - ckzalloc did it */
7371 cmdp->cmdtype = CMDUNKNOWN;
7372 strcpy(cmdp->cmdname, name);
7379 * Delete the command entry returned on the last lookup.
7382 delete_cmd_entry(void)
7384 struct tblentry *cmdp;
7387 cmdp = *lastcmdentry;
7388 *lastcmdentry = cmdp->next;
7389 if (cmdp->cmdtype == CMDFUNCTION)
7390 freefunc(cmdp->param.func);
7396 * Add a new command entry, replacing any existing command entry for
7397 * the same name - except special builtins.
7400 addcmdentry(char *name, struct cmdentry *entry)
7402 struct tblentry *cmdp;
7404 cmdp = cmdlookup(name, 1);
7405 if (cmdp->cmdtype == CMDFUNCTION) {
7406 freefunc(cmdp->param.func);
7408 cmdp->cmdtype = entry->cmdtype;
7409 cmdp->param = entry->u;
7413 static int FAST_FUNC
7414 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7416 struct tblentry **pp;
7417 struct tblentry *cmdp;
7419 struct cmdentry entry;
7422 if (nextopt("r") != '\0') {
7427 if (*argptr == NULL) {
7428 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7429 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7430 if (cmdp->cmdtype == CMDNORMAL)
7438 while ((name = *argptr) != NULL) {
7439 cmdp = cmdlookup(name, 0);
7441 && (cmdp->cmdtype == CMDNORMAL
7442 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7446 find_command(name, &entry, DO_ERR, pathval());
7447 if (entry.cmdtype == CMDUNKNOWN)
7455 * Called when a cd is done. Marks all commands so the next time they
7456 * are executed they will be rehashed.
7461 struct tblentry **pp;
7462 struct tblentry *cmdp;
7464 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7465 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7466 if (cmdp->cmdtype == CMDNORMAL
7467 || (cmdp->cmdtype == CMDBUILTIN
7468 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7478 * Fix command hash table when PATH changed.
7479 * Called before PATH is changed. The argument is the new value of PATH;
7480 * pathval() still returns the old value at this point.
7481 * Called with interrupts off.
7483 static void FAST_FUNC
7484 changepath(const char *new)
7492 firstchange = 9999; /* assume no change */
7498 if ((*old == '\0' && *new == ':')
7499 || (*old == ':' && *new == '\0'))
7501 old = new; /* ignore subsequent differences */
7505 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7511 if (builtinloc < 0 && idx_bltin >= 0)
7512 builtinloc = idx_bltin; /* zap builtins */
7513 if (builtinloc >= 0 && idx_bltin < 0)
7515 clearcmdentry(firstchange);
7516 builtinloc = idx_bltin;
7531 #define TENDBQUOTE 12
7548 typedef smallint token_id_t;
7550 /* first char is indicating which tokens mark the end of a list */
7551 static const char *const tokname_array[] = {
7565 #define KWDOFFSET 13
7566 /* the following are keywords */
7588 static char buf[16];
7591 //if (tok < TSEMI) return tokname_array[tok] + 1;
7592 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7597 sprintf(buf + (tok >= TSEMI), "%s%c",
7598 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7602 /* Wrapper around strcmp for qsort/bsearch/... */
7604 pstrcmp(const void *a, const void *b)
7606 return strcmp((char*) a, (*(char**) b) + 1);
7609 static const char *const *
7610 findkwd(const char *s)
7612 return bsearch(s, tokname_array + KWDOFFSET,
7613 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7614 sizeof(tokname_array[0]), pstrcmp);
7618 * Locate and print what a word is...
7621 describe_command(char *command, int describe_command_verbose)
7623 struct cmdentry entry;
7624 struct tblentry *cmdp;
7625 #if ENABLE_ASH_ALIAS
7626 const struct alias *ap;
7628 const char *path = pathval();
7630 if (describe_command_verbose) {
7634 /* First look at the keywords */
7635 if (findkwd(command)) {
7636 out1str(describe_command_verbose ? " is a shell keyword" : command);
7640 #if ENABLE_ASH_ALIAS
7641 /* Then look at the aliases */
7642 ap = lookupalias(command, 0);
7644 if (!describe_command_verbose) {
7649 out1fmt(" is an alias for %s", ap->val);
7653 /* Then check if it is a tracked alias */
7654 cmdp = cmdlookup(command, 0);
7656 entry.cmdtype = cmdp->cmdtype;
7657 entry.u = cmdp->param;
7659 /* Finally use brute force */
7660 find_command(command, &entry, DO_ABS, path);
7663 switch (entry.cmdtype) {
7665 int j = entry.u.index;
7671 p = path_advance(&path, command);
7675 if (describe_command_verbose) {
7677 (cmdp ? " a tracked alias for" : nullstr), p
7686 if (describe_command_verbose) {
7687 out1str(" is a shell function");
7694 if (describe_command_verbose) {
7695 out1fmt(" is a %sshell builtin",
7696 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7697 "special " : nullstr
7705 if (describe_command_verbose) {
7706 out1str(": not found\n");
7711 outstr("\n", stdout);
7715 static int FAST_FUNC
7716 typecmd(int argc UNUSED_PARAM, char **argv)
7722 /* type -p ... ? (we don't bother checking for 'p') */
7723 if (argv[1] && argv[1][0] == '-') {
7728 err |= describe_command(argv[i++], verbose);
7733 #if ENABLE_ASH_CMDCMD
7734 static int FAST_FUNC
7735 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7743 while ((c = nextopt("pvV")) != '\0')
7745 verify |= VERIFY_VERBOSE;
7747 verify |= VERIFY_BRIEF;
7752 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7753 if (verify && (*argptr != NULL)) {
7754 return describe_command(*argptr, verify - VERIFY_BRIEF);
7762 /* ============ eval.c */
7764 static int funcblocksize; /* size of structures in function */
7765 static int funcstringsize; /* size of strings in node */
7766 static void *funcblock; /* block to allocate function from */
7767 static char *funcstring; /* block to allocate strings from */
7769 /* flags in argument to evaltree */
7770 #define EV_EXIT 01 /* exit after evaluating tree */
7771 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7772 #define EV_BACKCMD 04 /* command executing within back quotes */
7774 static const short nodesize[N_NUMBER] = {
7775 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7776 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7777 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7778 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7779 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7780 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7781 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7782 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7783 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7784 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7785 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7786 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7787 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7788 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7789 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7790 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7791 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7792 #if ENABLE_ASH_BASH_COMPAT
7793 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7795 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7796 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7797 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7798 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7799 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7800 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7801 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7802 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7803 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7806 static void calcsize(union node *n);
7809 sizenodelist(struct nodelist *lp)
7812 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7819 calcsize(union node *n)
7823 funcblocksize += nodesize[n->type];
7826 calcsize(n->ncmd.redirect);
7827 calcsize(n->ncmd.args);
7828 calcsize(n->ncmd.assign);
7831 sizenodelist(n->npipe.cmdlist);
7836 calcsize(n->nredir.redirect);
7837 calcsize(n->nredir.n);
7844 calcsize(n->nbinary.ch2);
7845 calcsize(n->nbinary.ch1);
7848 calcsize(n->nif.elsepart);
7849 calcsize(n->nif.ifpart);
7850 calcsize(n->nif.test);
7853 funcstringsize += strlen(n->nfor.var) + 1;
7854 calcsize(n->nfor.body);
7855 calcsize(n->nfor.args);
7858 calcsize(n->ncase.cases);
7859 calcsize(n->ncase.expr);
7862 calcsize(n->nclist.body);
7863 calcsize(n->nclist.pattern);
7864 calcsize(n->nclist.next);
7868 sizenodelist(n->narg.backquote);
7869 funcstringsize += strlen(n->narg.text) + 1;
7870 calcsize(n->narg.next);
7873 #if ENABLE_ASH_BASH_COMPAT
7880 calcsize(n->nfile.fname);
7881 calcsize(n->nfile.next);
7885 calcsize(n->ndup.vname);
7886 calcsize(n->ndup.next);
7890 calcsize(n->nhere.doc);
7891 calcsize(n->nhere.next);
7894 calcsize(n->nnot.com);
7900 nodeckstrdup(char *s)
7902 char *rtn = funcstring;
7904 strcpy(funcstring, s);
7905 funcstring += strlen(s) + 1;
7909 static union node *copynode(union node *);
7911 static struct nodelist *
7912 copynodelist(struct nodelist *lp)
7914 struct nodelist *start;
7915 struct nodelist **lpp;
7920 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7921 (*lpp)->n = copynode(lp->n);
7923 lpp = &(*lpp)->next;
7930 copynode(union node *n)
7937 funcblock = (char *) funcblock + nodesize[n->type];
7941 new->ncmd.redirect = copynode(n->ncmd.redirect);
7942 new->ncmd.args = copynode(n->ncmd.args);
7943 new->ncmd.assign = copynode(n->ncmd.assign);
7946 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7947 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
7952 new->nredir.redirect = copynode(n->nredir.redirect);
7953 new->nredir.n = copynode(n->nredir.n);
7960 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7961 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7964 new->nif.elsepart = copynode(n->nif.elsepart);
7965 new->nif.ifpart = copynode(n->nif.ifpart);
7966 new->nif.test = copynode(n->nif.test);
7969 new->nfor.var = nodeckstrdup(n->nfor.var);
7970 new->nfor.body = copynode(n->nfor.body);
7971 new->nfor.args = copynode(n->nfor.args);
7974 new->ncase.cases = copynode(n->ncase.cases);
7975 new->ncase.expr = copynode(n->ncase.expr);
7978 new->nclist.body = copynode(n->nclist.body);
7979 new->nclist.pattern = copynode(n->nclist.pattern);
7980 new->nclist.next = copynode(n->nclist.next);
7984 new->narg.backquote = copynodelist(n->narg.backquote);
7985 new->narg.text = nodeckstrdup(n->narg.text);
7986 new->narg.next = copynode(n->narg.next);
7989 #if ENABLE_ASH_BASH_COMPAT
7996 new->nfile.fname = copynode(n->nfile.fname);
7997 new->nfile.fd = n->nfile.fd;
7998 new->nfile.next = copynode(n->nfile.next);
8002 new->ndup.vname = copynode(n->ndup.vname);
8003 new->ndup.dupfd = n->ndup.dupfd;
8004 new->ndup.fd = n->ndup.fd;
8005 new->ndup.next = copynode(n->ndup.next);
8009 new->nhere.doc = copynode(n->nhere.doc);
8010 new->nhere.fd = n->nhere.fd;
8011 new->nhere.next = copynode(n->nhere.next);
8014 new->nnot.com = copynode(n->nnot.com);
8017 new->type = n->type;
8022 * Make a copy of a parse tree.
8024 static struct funcnode *
8025 copyfunc(union node *n)
8030 funcblocksize = offsetof(struct funcnode, n);
8033 blocksize = funcblocksize;
8034 f = ckmalloc(blocksize + funcstringsize);
8035 funcblock = (char *) f + offsetof(struct funcnode, n);
8036 funcstring = (char *) f + blocksize;
8043 * Define a shell function.
8046 defun(char *name, union node *func)
8048 struct cmdentry entry;
8051 entry.cmdtype = CMDFUNCTION;
8052 entry.u.func = copyfunc(func);
8053 addcmdentry(name, &entry);
8057 /* Reasons for skipping commands (see comment on breakcmd routine) */
8058 #define SKIPBREAK (1 << 0)
8059 #define SKIPCONT (1 << 1)
8060 #define SKIPFUNC (1 << 2)
8061 #define SKIPFILE (1 << 3)
8062 #define SKIPEVAL (1 << 4)
8063 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8064 static int skipcount; /* number of levels to skip */
8065 static int funcnest; /* depth of function calls */
8066 static int loopnest; /* current loop nesting level */
8068 /* Forward decl way out to parsing code - dotrap needs it */
8069 static int evalstring(char *s, int mask);
8071 /* Called to execute a trap.
8072 * Single callsite - at the end of evaltree().
8073 * If we return non-zero, exaltree raises EXEXIT exception.
8075 * Perhaps we should avoid entering new trap handlers
8076 * while we are executing a trap handler. [is it a TODO?]
8085 savestatus = exitstatus;
8089 TRACE(("dotrap entered\n"));
8090 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8097 /* non-trapped SIGINT is handled separately by raise_interrupt,
8098 * don't upset it by resetting gotsig[SIGINT-1] */
8099 if (sig == SIGINT && !t)
8102 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8106 want_exexit = evalstring(t, SKIPEVAL);
8107 exitstatus = savestatus;
8109 TRACE(("dotrap returns %d\n", want_exexit));
8114 TRACE(("dotrap returns 0\n"));
8118 /* forward declarations - evaluation is fairly recursive business... */
8119 static void evalloop(union node *, int);
8120 static void evalfor(union node *, int);
8121 static void evalcase(union node *, int);
8122 static void evalsubshell(union node *, int);
8123 static void expredir(union node *);
8124 static void evalpipe(union node *, int);
8125 static void evalcommand(union node *, int);
8126 static int evalbltin(const struct builtincmd *, int, char **);
8127 static void prehash(union node *);
8130 * Evaluate a parse tree. The value is left in the global variable
8134 evaltree(union node *n, int flags)
8136 struct jmploc *volatile savehandler = exception_handler;
8137 struct jmploc jmploc;
8139 void (*evalfn)(union node *, int);
8143 SAVE_INT(int_level);
8146 TRACE(("evaltree(NULL) called\n"));
8149 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8151 exception_handler = &jmploc;
8153 int err = setjmp(jmploc.loc);
8155 /* if it was a signal, check for trap handlers */
8156 if (exception_type == EXSIG) {
8157 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8158 exception_type, err));
8161 /* continue on the way out */
8162 TRACE(("exception %d in evaltree, propagating err=%d\n",
8163 exception_type, err));
8164 exception_handler = savehandler;
8165 longjmp(exception_handler->loc, err);
8172 out1fmt("Node type = %d\n", n->type);
8177 evaltree(n->nnot.com, EV_TESTED);
8178 status = !exitstatus;
8181 expredir(n->nredir.redirect);
8182 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8184 evaltree(n->nredir.n, flags & EV_TESTED);
8185 status = exitstatus;
8187 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8190 evalfn = evalcommand;
8192 if (eflag && !(flags & EV_TESTED))
8204 evalfn = evalsubshell;
8217 #error NAND + 1 != NOR
8219 #if NOR + 1 != NSEMI
8220 #error NOR + 1 != NSEMI
8222 unsigned is_or = n->type - NAND;
8225 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8227 if (!exitstatus == is_or)
8240 evaltree(n->nif.test, EV_TESTED);
8243 if (exitstatus == 0) {
8247 if (n->nif.elsepart) {
8248 n = n->nif.elsepart;
8253 defun(n->narg.text, n->narg.next);
8257 exitstatus = status;
8262 exception_handler = savehandler;
8264 if (checkexit & exitstatus)
8265 evalskip |= SKIPEVAL;
8266 else if (pending_sig && dotrap())
8269 if (flags & EV_EXIT) {
8271 raise_exception(EXEXIT);
8274 RESTORE_INT(int_level);
8275 TRACE(("leaving evaltree (no interrupts)\n"));
8278 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8281 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8284 evalloop(union node *n, int flags)
8294 evaltree(n->nbinary.ch1, EV_TESTED);
8297 if (evalskip == SKIPCONT && --skipcount <= 0) {
8301 if (evalskip == SKIPBREAK && --skipcount <= 0)
8306 if (n->type != NWHILE)
8310 evaltree(n->nbinary.ch2, flags);
8311 status = exitstatus;
8316 exitstatus = status;
8320 evalfor(union node *n, int flags)
8322 struct arglist arglist;
8325 struct stackmark smark;
8327 setstackmark(&smark);
8328 arglist.list = NULL;
8329 arglist.lastp = &arglist.list;
8330 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8331 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8336 *arglist.lastp = NULL;
8341 for (sp = arglist.list; sp; sp = sp->next) {
8342 setvar(n->nfor.var, sp->text, 0);
8343 evaltree(n->nfor.body, flags);
8345 if (evalskip == SKIPCONT && --skipcount <= 0) {
8349 if (evalskip == SKIPBREAK && --skipcount <= 0)
8356 popstackmark(&smark);
8360 evalcase(union node *n, int flags)
8364 struct arglist arglist;
8365 struct stackmark smark;
8367 setstackmark(&smark);
8368 arglist.list = NULL;
8369 arglist.lastp = &arglist.list;
8370 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8372 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8373 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8374 if (casematch(patp, arglist.list->text)) {
8375 if (evalskip == 0) {
8376 evaltree(cp->nclist.body, flags);
8383 popstackmark(&smark);
8387 * Kick off a subshell to evaluate a tree.
8390 evalsubshell(union node *n, int flags)
8393 int backgnd = (n->type == NBACKGND);
8396 expredir(n->nredir.redirect);
8397 if (!backgnd && flags & EV_EXIT && !trap[0])
8400 jp = makejob(/*n,*/ 1);
8401 if (forkshell(jp, n, backgnd) == 0) {
8405 flags &=~ EV_TESTED;
8407 redirect(n->nredir.redirect, 0);
8408 evaltreenr(n->nredir.n, flags);
8413 status = waitforjob(jp);
8414 exitstatus = status;
8419 * Compute the names of the files in a redirection list.
8421 static void fixredir(union node *, const char *, int);
8423 expredir(union node *n)
8427 for (redir = n; redir; redir = redir->nfile.next) {
8431 fn.lastp = &fn.list;
8432 switch (redir->type) {
8436 #if ENABLE_ASH_BASH_COMPAT
8441 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8442 #if ENABLE_ASH_BASH_COMPAT
8445 redir->nfile.expfname = fn.list->text;
8448 case NTOFD: /* >& */
8449 if (redir->ndup.vname) {
8450 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8451 if (fn.list == NULL)
8452 ash_msg_and_raise_error("redir error");
8453 #if ENABLE_ASH_BASH_COMPAT
8454 //FIXME: we used expandarg with different args!
8455 if (!isdigit_str9(fn.list->text)) {
8456 /* >&file, not >&fd */
8457 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8458 ash_msg_and_raise_error("redir error");
8460 goto store_expfname;
8463 fixredir(redir, fn.list->text, 1);
8471 * Evaluate a pipeline. All the processes in the pipeline are children
8472 * of the process creating the pipeline. (This differs from some versions
8473 * of the shell, which make the last process in a pipeline the parent
8477 evalpipe(union node *n, int flags)
8480 struct nodelist *lp;
8485 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8487 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8491 jp = makejob(/*n,*/ pipelen);
8493 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8497 if (pipe(pip) < 0) {
8499 ash_msg_and_raise_error("pipe call failed");
8502 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8515 evaltreenr(lp->n, flags);
8521 /* Don't want to trigger debugging */
8525 if (n->npipe.pipe_backgnd == 0) {
8526 exitstatus = waitforjob(jp);
8527 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8533 * Controls whether the shell is interactive or not.
8536 setinteractive(int on)
8538 static smallint is_interactive;
8540 if (++on == is_interactive)
8542 is_interactive = on;
8546 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8547 if (is_interactive > 1) {
8548 /* Looks like they want an interactive shell */
8549 static smallint did_banner;
8552 /* note: ash and hush share this string */
8553 out1fmt("\n\n%s %s\n"
8554 "Enter 'help' for a list of built-in commands."
8557 "built-in shell (ash)"
8571 setinteractive(iflag);
8573 #if ENABLE_FEATURE_EDITING_VI
8575 line_input_state->flags |= VI_MODE;
8577 line_input_state->flags &= ~VI_MODE;
8579 viflag = 0; /* forcibly keep the option off */
8583 static struct localvar *localvars;
8586 * Called after a function returns.
8587 * Interrupts must be off.
8592 struct localvar *lvp;
8595 while ((lvp = localvars) != NULL) {
8596 localvars = lvp->next;
8598 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8599 if (vp == NULL) { /* $- saved */
8600 memcpy(optlist, lvp->text, sizeof(optlist));
8601 free((char*)lvp->text);
8603 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8607 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8608 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8609 free((char*)vp->text);
8610 vp->flags = lvp->flags;
8611 vp->text = lvp->text;
8618 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8620 volatile struct shparam saveparam;
8621 struct localvar *volatile savelocalvars;
8622 struct jmploc *volatile savehandler;
8623 struct jmploc jmploc;
8626 saveparam = shellparam;
8627 savelocalvars = localvars;
8628 e = setjmp(jmploc.loc);
8633 savehandler = exception_handler;
8634 exception_handler = &jmploc;
8636 shellparam.malloced = 0;
8640 shellparam.nparam = argc - 1;
8641 shellparam.p = argv + 1;
8642 #if ENABLE_ASH_GETOPTS
8643 shellparam.optind = 1;
8644 shellparam.optoff = -1;
8646 evaltree(&func->n, flags & EV_TESTED);
8652 localvars = savelocalvars;
8653 freeparam(&shellparam);
8654 shellparam = saveparam;
8655 exception_handler = savehandler;
8657 evalskip &= ~SKIPFUNC;
8661 #if ENABLE_ASH_CMDCMD
8663 parse_command_args(char **argv, const char **path)
8676 if (c == '-' && !*cp) {
8683 *path = bb_default_path;
8686 /* run 'typecmd' for other options */
8697 * Make a variable a local variable. When a variable is made local, it's
8698 * value and flags are saved in a localvar structure. The saved values
8699 * will be restored when the shell function returns. We handle the name
8700 * "-" as a special case.
8705 struct localvar *lvp;
8710 lvp = ckzalloc(sizeof(struct localvar));
8711 if (LONE_DASH(name)) {
8713 p = ckmalloc(sizeof(optlist));
8714 lvp->text = memcpy(p, optlist, sizeof(optlist));
8719 vpp = hashvar(name);
8720 vp = *findvar(vpp, name);
8721 eq = strchr(name, '=');
8724 setvareq(name, VSTRFIXED);
8726 setvar(name, NULL, VSTRFIXED);
8727 vp = *vpp; /* the new variable */
8728 lvp->flags = VUNSET;
8730 lvp->text = vp->text;
8731 lvp->flags = vp->flags;
8732 vp->flags |= VSTRFIXED|VTEXTFIXED;
8738 lvp->next = localvars;
8744 * The "local" command.
8746 static int FAST_FUNC
8747 localcmd(int argc UNUSED_PARAM, char **argv)
8752 while ((name = *argv++) != NULL) {
8758 static int FAST_FUNC
8759 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8764 static int FAST_FUNC
8765 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8770 static int FAST_FUNC
8771 execcmd(int argc UNUSED_PARAM, char **argv)
8774 iflag = 0; /* exit on error */
8777 shellexec(argv + 1, pathval(), 0);
8783 * The return command.
8785 static int FAST_FUNC
8786 returncmd(int argc UNUSED_PARAM, char **argv)
8789 * If called outside a function, do what ksh does;
8790 * skip the rest of the file.
8792 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8793 return argv[1] ? number(argv[1]) : exitstatus;
8796 /* Forward declarations for builtintab[] */
8797 static int breakcmd(int, char **) FAST_FUNC;
8798 static int dotcmd(int, char **) FAST_FUNC;
8799 static int evalcmd(int, char **) FAST_FUNC;
8800 static int exitcmd(int, char **) FAST_FUNC;
8801 static int exportcmd(int, char **) FAST_FUNC;
8802 #if ENABLE_ASH_GETOPTS
8803 static int getoptscmd(int, char **) FAST_FUNC;
8805 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8806 static int helpcmd(int, char **) FAST_FUNC;
8808 #if ENABLE_SH_MATH_SUPPORT
8809 static int letcmd(int, char **) FAST_FUNC;
8811 static int readcmd(int, char **) FAST_FUNC;
8812 static int setcmd(int, char **) FAST_FUNC;
8813 static int shiftcmd(int, char **) FAST_FUNC;
8814 static int timescmd(int, char **) FAST_FUNC;
8815 static int trapcmd(int, char **) FAST_FUNC;
8816 static int umaskcmd(int, char **) FAST_FUNC;
8817 static int unsetcmd(int, char **) FAST_FUNC;
8818 static int ulimitcmd(int, char **) FAST_FUNC;
8820 #define BUILTIN_NOSPEC "0"
8821 #define BUILTIN_SPECIAL "1"
8822 #define BUILTIN_REGULAR "2"
8823 #define BUILTIN_SPEC_REG "3"
8824 #define BUILTIN_ASSIGN "4"
8825 #define BUILTIN_SPEC_ASSG "5"
8826 #define BUILTIN_REG_ASSG "6"
8827 #define BUILTIN_SPEC_REG_ASSG "7"
8829 /* Stubs for calling non-FAST_FUNC's */
8830 #if ENABLE_ASH_BUILTIN_ECHO
8831 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8833 #if ENABLE_ASH_BUILTIN_PRINTF
8834 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8836 #if ENABLE_ASH_BUILTIN_TEST
8837 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8840 /* Keep these in proper order since it is searched via bsearch() */
8841 static const struct builtincmd builtintab[] = {
8842 { BUILTIN_SPEC_REG ".", dotcmd },
8843 { BUILTIN_SPEC_REG ":", truecmd },
8844 #if ENABLE_ASH_BUILTIN_TEST
8845 { BUILTIN_REGULAR "[", testcmd },
8846 #if ENABLE_ASH_BASH_COMPAT
8847 { BUILTIN_REGULAR "[[", testcmd },
8850 #if ENABLE_ASH_ALIAS
8851 { BUILTIN_REG_ASSG "alias", aliascmd },
8854 { BUILTIN_REGULAR "bg", fg_bgcmd },
8856 { BUILTIN_SPEC_REG "break", breakcmd },
8857 { BUILTIN_REGULAR "cd", cdcmd },
8858 { BUILTIN_NOSPEC "chdir", cdcmd },
8859 #if ENABLE_ASH_CMDCMD
8860 { BUILTIN_REGULAR "command", commandcmd },
8862 { BUILTIN_SPEC_REG "continue", breakcmd },
8863 #if ENABLE_ASH_BUILTIN_ECHO
8864 { BUILTIN_REGULAR "echo", echocmd },
8866 { BUILTIN_SPEC_REG "eval", evalcmd },
8867 { BUILTIN_SPEC_REG "exec", execcmd },
8868 { BUILTIN_SPEC_REG "exit", exitcmd },
8869 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8870 { BUILTIN_REGULAR "false", falsecmd },
8872 { BUILTIN_REGULAR "fg", fg_bgcmd },
8874 #if ENABLE_ASH_GETOPTS
8875 { BUILTIN_REGULAR "getopts", getoptscmd },
8877 { BUILTIN_NOSPEC "hash", hashcmd },
8878 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8879 { BUILTIN_NOSPEC "help", helpcmd },
8882 { BUILTIN_REGULAR "jobs", jobscmd },
8883 { BUILTIN_REGULAR "kill", killcmd },
8885 #if ENABLE_SH_MATH_SUPPORT
8886 { BUILTIN_NOSPEC "let", letcmd },
8888 { BUILTIN_ASSIGN "local", localcmd },
8889 #if ENABLE_ASH_BUILTIN_PRINTF
8890 { BUILTIN_REGULAR "printf", printfcmd },
8892 { BUILTIN_NOSPEC "pwd", pwdcmd },
8893 { BUILTIN_REGULAR "read", readcmd },
8894 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8895 { BUILTIN_SPEC_REG "return", returncmd },
8896 { BUILTIN_SPEC_REG "set", setcmd },
8897 { BUILTIN_SPEC_REG "shift", shiftcmd },
8898 { BUILTIN_SPEC_REG "source", dotcmd },
8899 #if ENABLE_ASH_BUILTIN_TEST
8900 { BUILTIN_REGULAR "test", testcmd },
8902 { BUILTIN_SPEC_REG "times", timescmd },
8903 { BUILTIN_SPEC_REG "trap", trapcmd },
8904 { BUILTIN_REGULAR "true", truecmd },
8905 { BUILTIN_NOSPEC "type", typecmd },
8906 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8907 { BUILTIN_REGULAR "umask", umaskcmd },
8908 #if ENABLE_ASH_ALIAS
8909 { BUILTIN_REGULAR "unalias", unaliascmd },
8911 { BUILTIN_SPEC_REG "unset", unsetcmd },
8912 { BUILTIN_REGULAR "wait", waitcmd },
8915 /* Should match the above table! */
8916 #define COMMANDCMD (builtintab + \
8918 1 * ENABLE_ASH_BUILTIN_TEST + \
8919 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8920 1 * ENABLE_ASH_ALIAS + \
8921 1 * ENABLE_ASH_JOB_CONTROL + \
8923 #define EXECCMD (builtintab + \
8925 1 * ENABLE_ASH_BUILTIN_TEST + \
8926 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8927 1 * ENABLE_ASH_ALIAS + \
8928 1 * ENABLE_ASH_JOB_CONTROL + \
8930 1 * ENABLE_ASH_CMDCMD + \
8932 ENABLE_ASH_BUILTIN_ECHO + \
8936 * Search the table of builtin commands.
8938 static struct builtincmd *
8939 find_builtin(const char *name)
8941 struct builtincmd *bp;
8944 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8951 * Execute a simple command.
8954 isassignment(const char *p)
8956 const char *q = endofname(p);
8961 static int FAST_FUNC
8962 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8964 /* Preserve exitstatus of a previous possible redirection
8965 * as POSIX mandates */
8966 return back_exitstatus;
8969 evalcommand(union node *cmd, int flags)
8971 static const struct builtincmd null_bltin = {
8972 "\0\0", bltincmd /* why three NULs? */
8974 struct stackmark smark;
8976 struct arglist arglist;
8977 struct arglist varlist;
8980 const struct strlist *sp;
8981 struct cmdentry cmdentry;
8988 struct builtincmd *bcmd;
8989 smallint cmd_is_exec;
8990 smallint pseudovarflag = 0;
8992 /* First expand the arguments. */
8993 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8994 setstackmark(&smark);
8995 back_exitstatus = 0;
8997 cmdentry.cmdtype = CMDBUILTIN;
8998 cmdentry.u.cmd = &null_bltin;
8999 varlist.lastp = &varlist.list;
9000 *varlist.lastp = NULL;
9001 arglist.lastp = &arglist.list;
9002 *arglist.lastp = NULL;
9005 if (cmd->ncmd.args) {
9006 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9007 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9010 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9011 struct strlist **spp;
9013 spp = arglist.lastp;
9014 if (pseudovarflag && isassignment(argp->narg.text))
9015 expandarg(argp, &arglist, EXP_VARTILDE);
9017 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9019 for (sp = *spp; sp; sp = sp->next)
9023 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9024 for (sp = arglist.list; sp; sp = sp->next) {
9025 TRACE(("evalcommand arg: %s\n", sp->text));
9026 *nargv++ = sp->text;
9031 if (iflag && funcnest == 0 && argc > 0)
9032 lastarg = nargv[-1];
9035 expredir(cmd->ncmd.redirect);
9036 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9039 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9040 struct strlist **spp;
9043 spp = varlist.lastp;
9044 expandarg(argp, &varlist, EXP_VARTILDE);
9047 * Modify the command lookup path, if a PATH= assignment
9051 if (varequal(p, path))
9055 /* Print the command if xflag is set. */
9058 const char *p = " %s";
9061 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9064 for (n = 0; n < 2; n++) {
9066 fdprintf(preverrout_fd, p, sp->text);
9074 safe_write(preverrout_fd, "\n", 1);
9080 /* Now locate the command. */
9082 const char *oldpath;
9083 int cmd_flag = DO_ERR;
9088 find_command(argv[0], &cmdentry, cmd_flag, path);
9089 if (cmdentry.cmdtype == CMDUNKNOWN) {
9095 /* implement bltin and command here */
9096 if (cmdentry.cmdtype != CMDBUILTIN)
9099 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9100 if (cmdentry.u.cmd == EXECCMD)
9102 #if ENABLE_ASH_CMDCMD
9103 if (cmdentry.u.cmd == COMMANDCMD) {
9105 nargv = parse_command_args(argv, &path);
9108 argc -= nargv - argv;
9110 cmd_flag |= DO_NOFUNC;
9118 /* We have a redirection error. */
9120 raise_exception(EXERROR);
9122 exitstatus = status;
9126 /* Execute the command. */
9127 switch (cmdentry.cmdtype) {
9130 #if ENABLE_FEATURE_SH_NOFORK
9131 /* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9132 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
9134 /* find_command() encodes applet_no as (-2 - applet_no) */
9135 int applet_no = (- cmdentry.u.index - 2);
9136 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9137 listsetvar(varlist.list, VEXPORT|VSTACK);
9138 /* run <applet>_main() */
9139 exitstatus = run_nofork_applet(applet_no, argv);
9144 /* Fork off a child process if necessary. */
9145 if (!(flags & EV_EXIT) || trap[0]) {
9147 jp = makejob(/*cmd,*/ 1);
9148 if (forkshell(jp, cmd, FORK_FG) != 0) {
9149 exitstatus = waitforjob(jp);
9151 TRACE(("forked child exited with %d\n", exitstatus));
9156 listsetvar(varlist.list, VEXPORT|VSTACK);
9157 shellexec(argv, path, cmdentry.u.index);
9161 cmdenviron = varlist.list;
9163 struct strlist *list = cmdenviron;
9165 if (spclbltin > 0 || argc == 0) {
9167 if (cmd_is_exec && argc > 1)
9170 listsetvar(list, i);
9172 /* Tight loop with builtins only:
9173 * "while kill -0 $child; do true; done"
9174 * will never exit even if $child died, unless we do this
9175 * to reap the zombie and make kill detect that it's gone: */
9176 dowait(DOWAIT_NONBLOCK, NULL);
9178 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9180 int i = exception_type;
9185 exit_status = 128 + SIGINT;
9187 exit_status = 128 + pending_sig;
9188 exitstatus = exit_status;
9189 if (i == EXINT || spclbltin > 0) {
9191 longjmp(exception_handler->loc, 1);
9198 listsetvar(varlist.list, 0);
9199 /* See above for the rationale */
9200 dowait(DOWAIT_NONBLOCK, NULL);
9201 if (evalfun(cmdentry.u.func, argc, argv, flags))
9207 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9209 /* dsl: I think this is intended to be used to support
9210 * '_' in 'vi' command mode during line editing...
9211 * However I implemented that within libedit itself.
9213 setvar("_", lastarg, 0);
9215 popstackmark(&smark);
9219 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9221 char *volatile savecmdname;
9222 struct jmploc *volatile savehandler;
9223 struct jmploc jmploc;
9226 savecmdname = commandname;
9227 i = setjmp(jmploc.loc);
9230 savehandler = exception_handler;
9231 exception_handler = &jmploc;
9232 commandname = argv[0];
9234 optptr = NULL; /* initialize nextopt */
9235 exitstatus = (*cmd->builtin)(argc, argv);
9236 flush_stdout_stderr();
9238 exitstatus |= ferror(stdout);
9240 commandname = savecmdname;
9241 exception_handler = savehandler;
9247 goodname(const char *p)
9249 return !*endofname(p);
9254 * Search for a command. This is called before we fork so that the
9255 * location of the command will be available in the parent as well as
9256 * the child. The check for "goodname" is an overly conservative
9257 * check that the name will not be subject to expansion.
9260 prehash(union node *n)
9262 struct cmdentry entry;
9264 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9265 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9269 /* ============ Builtin commands
9271 * Builtin commands whose functions are closely tied to evaluation
9272 * are implemented here.
9276 * Handle break and continue commands. Break, continue, and return are
9277 * all handled by setting the evalskip flag. The evaluation routines
9278 * above all check this flag, and if it is set they start skipping
9279 * commands rather than executing them. The variable skipcount is
9280 * the number of loops to break/continue, or the number of function
9281 * levels to return. (The latter is always 1.) It should probably
9282 * be an error to break out of more loops than exist, but it isn't
9283 * in the standard shell so we don't make it one here.
9285 static int FAST_FUNC
9286 breakcmd(int argc UNUSED_PARAM, char **argv)
9288 int n = argv[1] ? number(argv[1]) : 1;
9291 ash_msg_and_raise_error(msg_illnum, argv[1]);
9295 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9302 /* ============ input.c
9304 * This implements the input routines used by the parser.
9308 INPUT_PUSH_FILE = 1,
9309 INPUT_NOFILE_OK = 2,
9312 static smallint checkkwd;
9313 /* values of checkkwd variable */
9314 #define CHKALIAS 0x1
9319 * Push a string back onto the input at this current parsefile level.
9320 * We handle aliases this way.
9322 #if !ENABLE_ASH_ALIAS
9323 #define pushstring(s, ap) pushstring(s)
9326 pushstring(char *s, struct alias *ap)
9333 if (g_parsefile->strpush) {
9334 sp = ckzalloc(sizeof(*sp));
9335 sp->prev = g_parsefile->strpush;
9337 sp = &(g_parsefile->basestrpush);
9339 g_parsefile->strpush = sp;
9340 sp->prev_string = g_parsefile->next_to_pgetc;
9341 sp->prev_left_in_line = g_parsefile->left_in_line;
9342 #if ENABLE_ASH_ALIAS
9345 ap->flag |= ALIASINUSE;
9349 g_parsefile->next_to_pgetc = s;
9350 g_parsefile->left_in_line = len;
9357 struct strpush *sp = g_parsefile->strpush;
9360 #if ENABLE_ASH_ALIAS
9362 if (g_parsefile->next_to_pgetc[-1] == ' '
9363 || g_parsefile->next_to_pgetc[-1] == '\t'
9365 checkkwd |= CHKALIAS;
9367 if (sp->string != sp->ap->val) {
9370 sp->ap->flag &= ~ALIASINUSE;
9371 if (sp->ap->flag & ALIASDEAD) {
9372 unalias(sp->ap->name);
9376 g_parsefile->next_to_pgetc = sp->prev_string;
9377 g_parsefile->left_in_line = sp->prev_left_in_line;
9378 g_parsefile->strpush = sp->prev;
9379 if (sp != &(g_parsefile->basestrpush))
9384 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9385 //it peeks whether it is &>, and then pushes back both chars.
9386 //This function needs to save last *next_to_pgetc to buf[0]
9387 //to make two pungetc() reliable. Currently,
9388 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9393 char *buf = g_parsefile->buf;
9395 g_parsefile->next_to_pgetc = buf;
9396 #if ENABLE_FEATURE_EDITING
9398 if (!iflag || g_parsefile->fd != STDIN_FILENO)
9399 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9401 #if ENABLE_FEATURE_TAB_COMPLETION
9402 line_input_state->path_lookup = pathval();
9404 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9406 /* Ctrl+C pressed */
9415 if (nr < 0 && errno == 0) {
9416 /* Ctrl+D pressed */
9421 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9425 /* nonblock_safe_read() handles this problem */
9427 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9428 int flags = fcntl(0, F_GETFL);
9429 if (flags >= 0 && (flags & O_NONBLOCK)) {
9430 flags &= ~O_NONBLOCK;
9431 if (fcntl(0, F_SETFL, flags) >= 0) {
9432 out2str("sh: turning off NDELAY mode\n");
9443 * Refill the input buffer and return the next input character:
9445 * 1) If a string was pushed back on the input, pop it;
9446 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9447 * or we are reading from a string so we can't refill the buffer,
9449 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9450 * 4) Process input up to the next newline, deleting nul characters.
9452 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9453 #define pgetc_debug(...) ((void)0)
9455 * NB: due to SIT(c) internals (syntax_index_table[] vector),
9456 * pgetc() and related functions must return chars SIGN-EXTENDED into ints,
9457 * not zero-extended. Seems fragile to me. Affects only !USE_SIT_FUNCTION case,
9458 * so we can fix it by ditching !USE_SIT_FUNCTION if Unicode requires that.
9466 while (g_parsefile->strpush) {
9467 #if ENABLE_ASH_ALIAS
9468 if (g_parsefile->left_in_line == -1
9469 && g_parsefile->strpush->ap
9470 && g_parsefile->next_to_pgetc[-1] != ' '
9471 && g_parsefile->next_to_pgetc[-1] != '\t'
9473 pgetc_debug("preadbuffer PEOA");
9478 /* try "pgetc" now: */
9479 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9480 g_parsefile->left_in_line,
9481 g_parsefile->next_to_pgetc,
9482 g_parsefile->next_to_pgetc);
9483 if (--g_parsefile->left_in_line >= 0)
9484 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9486 /* on both branches above g_parsefile->left_in_line < 0.
9487 * "pgetc" needs refilling.
9490 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9491 * pungetc() may increment it a few times.
9492 * Assuming it won't increment it to less than -90.
9494 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9495 pgetc_debug("preadbuffer PEOF1");
9496 /* even in failure keep left_in_line and next_to_pgetc
9497 * in lock step, for correct multi-layer pungetc.
9498 * left_in_line was decremented before preadbuffer(),
9499 * must inc next_to_pgetc: */
9500 g_parsefile->next_to_pgetc++;
9504 more = g_parsefile->left_in_buffer;
9506 flush_stdout_stderr();
9510 /* don't try reading again */
9511 g_parsefile->left_in_line = -99;
9512 pgetc_debug("preadbuffer PEOF2");
9513 g_parsefile->next_to_pgetc++;
9518 /* Find out where's the end of line.
9519 * Set g_parsefile->left_in_line
9520 * and g_parsefile->left_in_buffer acordingly.
9521 * NUL chars are deleted.
9523 q = g_parsefile->next_to_pgetc;
9531 memmove(q, q + 1, more);
9535 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9541 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9542 if (g_parsefile->left_in_line < 0)
9547 g_parsefile->left_in_buffer = more;
9552 out2str(g_parsefile->next_to_pgetc);
9556 pgetc_debug("preadbuffer at %d:%p'%s'",
9557 g_parsefile->left_in_line,
9558 g_parsefile->next_to_pgetc,
9559 g_parsefile->next_to_pgetc);
9560 return signed_char2int(*g_parsefile->next_to_pgetc++);
9563 #define pgetc_as_macro() \
9564 (--g_parsefile->left_in_line >= 0 \
9565 ? signed_char2int(*g_parsefile->next_to_pgetc++) \
9572 pgetc_debug("pgetc_fast at %d:%p'%s'",
9573 g_parsefile->left_in_line,
9574 g_parsefile->next_to_pgetc,
9575 g_parsefile->next_to_pgetc);
9576 return pgetc_as_macro();
9579 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9580 #define pgetc_fast() pgetc()
9582 #define pgetc_fast() pgetc_as_macro()
9586 * Same as pgetc(), but ignores PEOA.
9588 #if ENABLE_ASH_ALIAS
9594 pgetc_debug("pgetc_fast at %d:%p'%s'",
9595 g_parsefile->left_in_line,
9596 g_parsefile->next_to_pgetc,
9597 g_parsefile->next_to_pgetc);
9599 } while (c == PEOA);
9603 #define pgetc2() pgetc()
9607 * Read a line from the script.
9610 pfgets(char *line, int len)
9616 while (--nleft > 0) {
9632 * Undo the last call to pgetc. Only one character may be pushed back.
9633 * PEOF may be pushed back.
9638 g_parsefile->left_in_line++;
9639 g_parsefile->next_to_pgetc--;
9640 pgetc_debug("pushed back to %d:%p'%s'",
9641 g_parsefile->left_in_line,
9642 g_parsefile->next_to_pgetc,
9643 g_parsefile->next_to_pgetc);
9647 * To handle the "." command, a stack of input files is used. Pushfile
9648 * adds a new entry to the stack and popfile restores the previous level.
9653 struct parsefile *pf;
9655 pf = ckzalloc(sizeof(*pf));
9656 pf->prev = g_parsefile;
9658 /*pf->strpush = NULL; - ckzalloc did it */
9659 /*pf->basestrpush.prev = NULL;*/
9666 struct parsefile *pf = g_parsefile;
9674 g_parsefile = pf->prev;
9680 * Return to top level.
9685 while (g_parsefile != &basepf)
9690 * Close the file(s) that the shell is reading commands from. Called
9691 * after a fork is done.
9697 if (g_parsefile->fd > 0) {
9698 close(g_parsefile->fd);
9699 g_parsefile->fd = 0;
9704 * Like setinputfile, but takes an open file descriptor. Call this with
9708 setinputfd(int fd, int push)
9710 close_on_exec_on(fd);
9713 g_parsefile->buf = NULL;
9715 g_parsefile->fd = fd;
9716 if (g_parsefile->buf == NULL)
9717 g_parsefile->buf = ckmalloc(IBUFSIZ);
9718 g_parsefile->left_in_buffer = 0;
9719 g_parsefile->left_in_line = 0;
9720 g_parsefile->linno = 1;
9724 * Set the input to take input from a file. If push is set, push the
9725 * old input onto the stack first.
9728 setinputfile(const char *fname, int flags)
9734 fd = open(fname, O_RDONLY);
9736 if (flags & INPUT_NOFILE_OK)
9738 ash_msg_and_raise_error("can't open '%s'", fname);
9741 fd2 = copyfd(fd, 10);
9744 ash_msg_and_raise_error("out of file descriptors");
9747 setinputfd(fd, flags & INPUT_PUSH_FILE);
9754 * Like setinputfile, but takes input from a string.
9757 setinputstring(char *string)
9761 g_parsefile->next_to_pgetc = string;
9762 g_parsefile->left_in_line = strlen(string);
9763 g_parsefile->buf = NULL;
9764 g_parsefile->linno = 1;
9769 /* ============ mail.c
9771 * Routines to check for mail.
9776 #define MAXMBOXES 10
9778 /* times of mailboxes */
9779 static time_t mailtime[MAXMBOXES];
9780 /* Set if MAIL or MAILPATH is changed. */
9781 static smallint mail_var_path_changed;
9784 * Print appropriate message(s) if mail has arrived.
9785 * If mail_var_path_changed is set,
9786 * then the value of MAIL has mail_var_path_changed,
9787 * so we just update the values.
9796 struct stackmark smark;
9799 setstackmark(&smark);
9800 mpath = mpathset() ? mpathval() : mailval();
9801 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9802 p = path_advance(&mpath, nullstr);
9807 for (q = p; *q; q++)
9813 q[-1] = '\0'; /* delete trailing '/' */
9814 if (stat(p, &statb) < 0) {
9818 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9821 pathopt ? pathopt : "you have mail"
9824 *mtp = statb.st_mtime;
9826 mail_var_path_changed = 0;
9827 popstackmark(&smark);
9830 static void FAST_FUNC
9831 changemail(const char *val UNUSED_PARAM)
9833 mail_var_path_changed = 1;
9836 #endif /* ASH_MAIL */
9839 /* ============ ??? */
9842 * Set the shell parameters.
9845 setparam(char **argv)
9851 for (nparam = 0; argv[nparam]; nparam++)
9853 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9855 *ap++ = ckstrdup(*argv++);
9858 freeparam(&shellparam);
9859 shellparam.malloced = 1;
9860 shellparam.nparam = nparam;
9861 shellparam.p = newparam;
9862 #if ENABLE_ASH_GETOPTS
9863 shellparam.optind = 1;
9864 shellparam.optoff = -1;
9869 * Process shell options. The global variable argptr contains a pointer
9870 * to the argument list; we advance it past the options.
9872 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9873 * For a non-interactive shell, an error condition encountered
9874 * by a special built-in ... shall cause the shell to write a diagnostic message
9875 * to standard error and exit as shown in the following table:
9876 * Error Special Built-In
9878 * Utility syntax error (option or operand error) Shall exit
9880 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9881 * we see that bash does not do that (set "finishes" with error code 1 instead,
9882 * and shell continues), and people rely on this behavior!
9884 * set -o barfoo 2>/dev/null
9887 * Oh well. Let's mimic that.
9890 plus_minus_o(char *name, int val)
9895 for (i = 0; i < NOPTS; i++) {
9896 if (strcmp(name, optnames(i)) == 0) {
9901 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9904 for (i = 0; i < NOPTS; i++) {
9906 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9908 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9914 setoption(int flag, int val)
9918 for (i = 0; i < NOPTS; i++) {
9919 if (optletters(i) == flag) {
9924 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9928 options(int cmdline)
9936 while ((p = *argptr) != NULL) {
9938 if (c != '-' && c != '+')
9941 val = 0; /* val = 0 if c == '+' */
9944 if (p[0] == '\0' || LONE_DASH(p)) {
9946 /* "-" means turn off -x and -v */
9949 /* "--" means reset params */
9950 else if (*argptr == NULL)
9953 break; /* "-" or "--" terminates options */
9956 /* first char was + or - */
9957 while ((c = *p++) != '\0') {
9958 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9959 if (c == 'c' && cmdline) {
9960 minusc = p; /* command is after shell args */
9961 } else if (c == 'o') {
9962 if (plus_minus_o(*argptr, val)) {
9963 /* it already printed err message */
9964 return 1; /* error */
9968 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9970 /* bash does not accept +-login, we also won't */
9971 } else if (cmdline && val && (c == '-')) { /* long options */
9972 if (strcmp(p, "login") == 0)
9984 * The shift builtin command.
9986 static int FAST_FUNC
9987 shiftcmd(int argc UNUSED_PARAM, char **argv)
9994 n = number(argv[1]);
9995 if (n > shellparam.nparam)
9996 n = 0; /* bash compat, was = shellparam.nparam; */
9998 shellparam.nparam -= n;
9999 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10000 if (shellparam.malloced)
10003 ap2 = shellparam.p;
10004 while ((*ap2++ = *ap1++) != NULL)
10006 #if ENABLE_ASH_GETOPTS
10007 shellparam.optind = 1;
10008 shellparam.optoff = -1;
10015 * POSIX requires that 'set' (but not export or readonly) output the
10016 * variables in lexicographic order - by the locale's collating order (sigh).
10017 * Maybe we could keep them in an ordered balanced binary tree
10018 * instead of hashed lists.
10019 * For now just roll 'em through qsort for printing...
10022 showvars(const char *sep_prefix, int on, int off)
10025 char **ep, **epend;
10027 ep = listvars(on, off, &epend);
10028 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10030 sep = *sep_prefix ? " " : sep_prefix;
10032 for (; ep < epend; ep++) {
10036 p = strchrnul(*ep, '=');
10039 q = single_quote(++p);
10040 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10046 * The set command builtin.
10048 static int FAST_FUNC
10049 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10054 return showvars(nullstr, 0, VUNSET);
10057 if (!options(0)) { /* if no parse error... */
10060 if (*argptr != NULL) {
10068 #if ENABLE_ASH_RANDOM_SUPPORT
10069 static void FAST_FUNC
10070 change_random(const char *value)
10072 /* Galois LFSR parameter */
10073 /* Taps at 32 31 29 1: */
10074 enum { MASK = 0x8000000b };
10075 /* Another example - taps at 32 31 30 10: */
10076 /* MASK = 0x00400007 */
10080 if (value == NULL) {
10081 /* "get", generate */
10082 t = next_random(&random_gen);
10083 /* set without recursion */
10084 setvar(vrandom.text, utoa(t), VNOFUNC);
10085 vrandom.flags &= ~VNOFUNC;
10088 t = strtoul(value, NULL, 10);
10089 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10094 #if ENABLE_ASH_GETOPTS
10096 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10105 if (*param_optind < 1)
10107 optnext = optfirst + *param_optind - 1;
10109 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10112 p = optnext[-1] + *optoff;
10113 if (p == NULL || *p == '\0') {
10114 /* Current word is done, advance */
10116 if (p == NULL || *p != '-' || *++p == '\0') {
10123 if (LONE_DASH(p)) /* check for "--" */
10128 for (q = optstr; *q != c;) {
10130 if (optstr[0] == ':') {
10133 err |= setvarsafe("OPTARG", s, 0);
10135 fprintf(stderr, "Illegal option -%c\n", c);
10136 unsetvar("OPTARG");
10146 if (*p == '\0' && (p = *optnext) == NULL) {
10147 if (optstr[0] == ':') {
10150 err |= setvarsafe("OPTARG", s, 0);
10153 fprintf(stderr, "No arg for -%c option\n", c);
10154 unsetvar("OPTARG");
10162 err |= setvarsafe("OPTARG", p, 0);
10165 err |= setvarsafe("OPTARG", nullstr, 0);
10167 *optoff = p ? p - *(optnext - 1) : -1;
10168 *param_optind = optnext - optfirst + 1;
10169 fmtstr(s, sizeof(s), "%d", *param_optind);
10170 err |= setvarsafe("OPTIND", s, VNOFUNC);
10173 err |= setvarsafe(optvar, s, 0);
10177 flush_stdout_stderr();
10178 raise_exception(EXERROR);
10184 * The getopts builtin. Shellparam.optnext points to the next argument
10185 * to be processed. Shellparam.optptr points to the next character to
10186 * be processed in the current argument. If shellparam.optnext is NULL,
10187 * then it's the first time getopts has been called.
10189 static int FAST_FUNC
10190 getoptscmd(int argc, char **argv)
10195 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10197 optbase = shellparam.p;
10198 if (shellparam.optind > shellparam.nparam + 1) {
10199 shellparam.optind = 1;
10200 shellparam.optoff = -1;
10203 optbase = &argv[3];
10204 if (shellparam.optind > argc - 2) {
10205 shellparam.optind = 1;
10206 shellparam.optoff = -1;
10210 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10211 &shellparam.optoff);
10213 #endif /* ASH_GETOPTS */
10216 /* ============ Shell parser */
10219 struct heredoc *next; /* next here document in list */
10220 union node *here; /* redirection node */
10221 char *eofmark; /* string indicating end of input */
10222 smallint striptabs; /* if set, strip leading tabs */
10225 static smallint tokpushback; /* last token pushed back */
10226 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10227 static smallint quoteflag; /* set if (part of) last token was quoted */
10228 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10229 static struct heredoc *heredoclist; /* list of here documents to read */
10230 static char *wordtext; /* text of last word returned by readtoken */
10231 static struct nodelist *backquotelist;
10232 static union node *redirnode;
10233 static struct heredoc *heredoc;
10236 * Called when an unexpected token is read during the parse. The argument
10237 * is the token that is expected, or -1 if more than one type of token can
10238 * occur at this point.
10240 static void raise_error_unexpected_syntax(int) NORETURN;
10242 raise_error_unexpected_syntax(int token)
10247 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
10249 sprintf(msg + l, " (expecting %s)", tokname(token));
10250 raise_error_syntax(msg);
10254 #define EOFMARKLEN 79
10256 /* parsing is heavily cross-recursive, need these forward decls */
10257 static union node *andor(void);
10258 static union node *pipeline(void);
10259 static union node *parse_command(void);
10260 static void parseheredoc(void);
10261 static char peektoken(void);
10262 static int readtoken(void);
10264 static union node *
10267 union node *n1, *n2, *n3;
10270 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10271 if (nlflag == 2 && peektoken())
10277 if (tok == TBACKGND) {
10278 if (n2->type == NPIPE) {
10279 n2->npipe.pipe_backgnd = 1;
10281 if (n2->type != NREDIR) {
10282 n3 = stzalloc(sizeof(struct nredir));
10284 /*n3->nredir.redirect = NULL; - stzalloc did it */
10287 n2->type = NBACKGND;
10293 n3 = stzalloc(sizeof(struct nbinary));
10295 n3->nbinary.ch1 = n1;
10296 n3->nbinary.ch2 = n2;
10312 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10320 pungetc(); /* push back EOF on input */
10324 raise_error_unexpected_syntax(-1);
10331 static union node *
10334 union node *n1, *n2, *n3;
10342 } else if (t == TOR) {
10348 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10350 n3 = stzalloc(sizeof(struct nbinary));
10352 n3->nbinary.ch1 = n1;
10353 n3->nbinary.ch2 = n2;
10358 static union node *
10361 union node *n1, *n2, *pipenode;
10362 struct nodelist *lp, *prev;
10366 TRACE(("pipeline: entered\n"));
10367 if (readtoken() == TNOT) {
10369 checkkwd = CHKKWD | CHKALIAS;
10372 n1 = parse_command();
10373 if (readtoken() == TPIPE) {
10374 pipenode = stzalloc(sizeof(struct npipe));
10375 pipenode->type = NPIPE;
10376 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10377 lp = stzalloc(sizeof(struct nodelist));
10378 pipenode->npipe.cmdlist = lp;
10382 lp = stzalloc(sizeof(struct nodelist));
10383 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10384 lp->n = parse_command();
10386 } while (readtoken() == TPIPE);
10392 n2 = stzalloc(sizeof(struct nnot));
10400 static union node *
10405 n = stzalloc(sizeof(struct narg));
10407 /*n->narg.next = NULL; - stzalloc did it */
10408 n->narg.text = wordtext;
10409 n->narg.backquote = backquotelist;
10414 fixredir(union node *n, const char *text, int err)
10418 TRACE(("Fix redir %s %d\n", text, err));
10420 n->ndup.vname = NULL;
10422 fd = bb_strtou(text, NULL, 10);
10423 if (!errno && fd >= 0)
10424 n->ndup.dupfd = fd;
10425 else if (LONE_DASH(text))
10426 n->ndup.dupfd = -1;
10429 raise_error_syntax("bad fd number");
10430 n->ndup.vname = makename();
10435 * Returns true if the text contains nothing to expand (no dollar signs
10439 noexpand(const char *text)
10445 while ((c = *p++) != '\0') {
10446 if (c == CTLQUOTEMARK)
10450 else if (SIT((signed char)c, BASESYNTAX) == CCTL)
10459 union node *n = redirnode;
10461 if (readtoken() != TWORD)
10462 raise_error_unexpected_syntax(-1);
10463 if (n->type == NHERE) {
10464 struct heredoc *here = heredoc;
10468 if (quoteflag == 0)
10470 TRACE(("Here document %d\n", n->type));
10471 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10472 raise_error_syntax("illegal eof marker for << redirection");
10473 rmescapes(wordtext, 0);
10474 here->eofmark = wordtext;
10476 if (heredoclist == NULL)
10477 heredoclist = here;
10479 for (p = heredoclist; p->next; p = p->next)
10483 } else if (n->type == NTOFD || n->type == NFROMFD) {
10484 fixredir(n, wordtext, 0);
10486 n->nfile.fname = makename();
10490 static union node *
10493 union node *args, **app;
10494 union node *n = NULL;
10495 union node *vars, **vpp;
10496 union node **rpp, *redir;
10498 #if ENABLE_ASH_BASH_COMPAT
10499 smallint double_brackets_flag = 0;
10509 savecheckkwd = CHKALIAS;
10512 checkkwd = savecheckkwd;
10515 #if ENABLE_ASH_BASH_COMPAT
10516 case TAND: /* "&&" */
10517 case TOR: /* "||" */
10518 if (!double_brackets_flag) {
10522 wordtext = (char *) (t == TAND ? "-a" : "-o");
10525 n = stzalloc(sizeof(struct narg));
10527 /*n->narg.next = NULL; - stzalloc did it */
10528 n->narg.text = wordtext;
10529 #if ENABLE_ASH_BASH_COMPAT
10530 if (strcmp("[[", wordtext) == 0)
10531 double_brackets_flag = 1;
10532 else if (strcmp("]]", wordtext) == 0)
10533 double_brackets_flag = 0;
10535 n->narg.backquote = backquotelist;
10536 if (savecheckkwd && isassignment(wordtext)) {
10538 vpp = &n->narg.next;
10541 app = &n->narg.next;
10546 *rpp = n = redirnode;
10547 rpp = &n->nfile.next;
10548 parsefname(); /* read name of redirection file */
10551 if (args && app == &args->narg.next
10554 struct builtincmd *bcmd;
10557 /* We have a function */
10558 if (readtoken() != TRP)
10559 raise_error_unexpected_syntax(TRP);
10560 name = n->narg.text;
10561 if (!goodname(name)
10562 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10564 raise_error_syntax("bad function name");
10567 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10568 n->narg.next = parse_command();
10581 n = stzalloc(sizeof(struct ncmd));
10583 n->ncmd.args = args;
10584 n->ncmd.assign = vars;
10585 n->ncmd.redirect = redir;
10589 static union node *
10590 parse_command(void)
10592 union node *n1, *n2;
10593 union node *ap, **app;
10594 union node *cp, **cpp;
10595 union node *redir, **rpp;
10602 switch (readtoken()) {
10604 raise_error_unexpected_syntax(-1);
10607 n1 = stzalloc(sizeof(struct nif));
10609 n1->nif.test = list(0);
10610 if (readtoken() != TTHEN)
10611 raise_error_unexpected_syntax(TTHEN);
10612 n1->nif.ifpart = list(0);
10614 while (readtoken() == TELIF) {
10615 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10616 n2 = n2->nif.elsepart;
10618 n2->nif.test = list(0);
10619 if (readtoken() != TTHEN)
10620 raise_error_unexpected_syntax(TTHEN);
10621 n2->nif.ifpart = list(0);
10623 if (lasttoken == TELSE)
10624 n2->nif.elsepart = list(0);
10626 n2->nif.elsepart = NULL;
10634 n1 = stzalloc(sizeof(struct nbinary));
10635 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10636 n1->nbinary.ch1 = list(0);
10639 TRACE(("expecting DO got %s %s\n", tokname(got),
10640 got == TWORD ? wordtext : ""));
10641 raise_error_unexpected_syntax(TDO);
10643 n1->nbinary.ch2 = list(0);
10648 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10649 raise_error_syntax("bad for loop variable");
10650 n1 = stzalloc(sizeof(struct nfor));
10652 n1->nfor.var = wordtext;
10653 checkkwd = CHKKWD | CHKALIAS;
10654 if (readtoken() == TIN) {
10656 while (readtoken() == TWORD) {
10657 n2 = stzalloc(sizeof(struct narg));
10659 /*n2->narg.next = NULL; - stzalloc did it */
10660 n2->narg.text = wordtext;
10661 n2->narg.backquote = backquotelist;
10663 app = &n2->narg.next;
10666 n1->nfor.args = ap;
10667 if (lasttoken != TNL && lasttoken != TSEMI)
10668 raise_error_unexpected_syntax(-1);
10670 n2 = stzalloc(sizeof(struct narg));
10672 /*n2->narg.next = NULL; - stzalloc did it */
10673 n2->narg.text = (char *)dolatstr;
10674 /*n2->narg.backquote = NULL;*/
10675 n1->nfor.args = n2;
10677 * Newline or semicolon here is optional (but note
10678 * that the original Bourne shell only allowed NL).
10680 if (lasttoken != TNL && lasttoken != TSEMI)
10683 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10684 if (readtoken() != TDO)
10685 raise_error_unexpected_syntax(TDO);
10686 n1->nfor.body = list(0);
10690 n1 = stzalloc(sizeof(struct ncase));
10692 if (readtoken() != TWORD)
10693 raise_error_unexpected_syntax(TWORD);
10694 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10696 /*n2->narg.next = NULL; - stzalloc did it */
10697 n2->narg.text = wordtext;
10698 n2->narg.backquote = backquotelist;
10700 checkkwd = CHKKWD | CHKALIAS;
10701 } while (readtoken() == TNL);
10702 if (lasttoken != TIN)
10703 raise_error_unexpected_syntax(TIN);
10704 cpp = &n1->ncase.cases;
10706 checkkwd = CHKNL | CHKKWD;
10708 while (t != TESAC) {
10709 if (lasttoken == TLP)
10711 *cpp = cp = stzalloc(sizeof(struct nclist));
10713 app = &cp->nclist.pattern;
10715 *app = ap = stzalloc(sizeof(struct narg));
10717 /*ap->narg.next = NULL; - stzalloc did it */
10718 ap->narg.text = wordtext;
10719 ap->narg.backquote = backquotelist;
10720 if (readtoken() != TPIPE)
10722 app = &ap->narg.next;
10725 //ap->narg.next = NULL;
10726 if (lasttoken != TRP)
10727 raise_error_unexpected_syntax(TRP);
10728 cp->nclist.body = list(2);
10730 cpp = &cp->nclist.next;
10732 checkkwd = CHKNL | CHKKWD;
10736 raise_error_unexpected_syntax(TENDCASE);
10743 n1 = stzalloc(sizeof(struct nredir));
10744 n1->type = NSUBSHELL;
10745 n1->nredir.n = list(0);
10746 /*n1->nredir.redirect = NULL; - stzalloc did it */
10756 return simplecmd();
10759 if (readtoken() != t)
10760 raise_error_unexpected_syntax(t);
10763 /* Now check for redirection which may follow command */
10764 checkkwd = CHKKWD | CHKALIAS;
10766 while (readtoken() == TREDIR) {
10767 *rpp = n2 = redirnode;
10768 rpp = &n2->nfile.next;
10774 if (n1->type != NSUBSHELL) {
10775 n2 = stzalloc(sizeof(struct nredir));
10780 n1->nredir.redirect = redir;
10785 #if ENABLE_ASH_BASH_COMPAT
10786 static int decode_dollar_squote(void)
10788 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10794 p = strchr(C_escapes, c);
10799 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10803 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10805 } else if (c == 'x') { /* \xHH */
10809 } while (isxdigit(c) && --cnt);
10811 if (cnt == 3) { /* \x but next char is "bad" */
10815 } else { /* simple seq like \\ or \t */
10820 c = bb_process_escape_sequence((void*)&p);
10821 } else { /* unrecognized "\z": print both chars unless ' or " */
10822 if (c != '\'' && c != '"') {
10824 c |= 0x100; /* "please encode \, then me" */
10832 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10833 * is not NULL, read a here document. In the latter case, eofmark is the
10834 * word which marks the end of the document and striptabs is true if
10835 * leading tabs should be stripped from the document. The argument firstc
10836 * is the first character of the input token or document.
10838 * Because C does not have internal subroutines, I have simulated them
10839 * using goto's to implement the subroutine linkage. The following macros
10840 * will run code that appears at the end of readtoken1.
10842 #define CHECKEND() {goto checkend; checkend_return:;}
10843 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10844 #define PARSESUB() {goto parsesub; parsesub_return:;}
10845 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10846 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10847 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10849 readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
10851 /* NB: syntax parameter fits into smallint */
10855 char line[EOFMARKLEN + 1];
10856 struct nodelist *bqlist;
10860 smallint prevsyntax; /* syntax before arithmetic */
10861 #if ENABLE_ASH_EXPAND_PRMT
10862 smallint pssyntax; /* we are expanding a prompt string */
10864 int varnest; /* levels of variables expansion */
10865 int arinest; /* levels of arithmetic expansion */
10866 int parenlevel; /* levels of parens in arithmetic */
10867 int dqvarnest; /* levels of variables expansion within double quotes */
10869 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10872 /* Avoid longjmp clobbering */
10878 (void) &parenlevel;
10881 (void) &prevsyntax;
10884 startlinno = g_parsefile->linno;
10889 #if ENABLE_ASH_EXPAND_PRMT
10890 pssyntax = (syntax == PSSYNTAX);
10894 dblquote = (syntax == DQSYNTAX);
10900 STARTSTACKSTR(out);
10902 /* For each line, until end of word */
10904 CHECKEND(); /* set c to PEOF if at end of here document */
10905 for (;;) { /* until end of line or end of word */
10906 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10907 switch (SIT(c, syntax)) {
10908 case CNL: /* '\n' */
10909 if (syntax == BASESYNTAX)
10910 goto endword; /* exit outer loop */
10912 g_parsefile->linno++;
10916 goto loop; /* continue outer loop */
10921 if (eofmark == NULL || dblquote)
10922 USTPUTC(CTLESC, out);
10923 #if ENABLE_ASH_BASH_COMPAT
10924 if (c == '\\' && bash_dollar_squote) {
10925 c = decode_dollar_squote();
10927 USTPUTC('\\', out);
10928 c = (unsigned char)c;
10934 case CBACK: /* backslash */
10937 USTPUTC(CTLESC, out);
10938 USTPUTC('\\', out);
10940 } else if (c == '\n') {
10944 #if ENABLE_ASH_EXPAND_PRMT
10945 if (c == '$' && pssyntax) {
10946 USTPUTC(CTLESC, out);
10947 USTPUTC('\\', out);
10950 if (dblquote && c != '\\'
10951 && c != '`' && c != '$'
10952 && (c != '"' || eofmark != NULL)
10954 USTPUTC(CTLESC, out);
10955 USTPUTC('\\', out);
10957 if (SIT(c, SQSYNTAX) == CCTL)
10958 USTPUTC(CTLESC, out);
10966 if (eofmark == NULL) {
10967 USTPUTC(CTLQUOTEMARK, out);
10975 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
10976 if (eofmark != NULL && arinest == 0
10981 if (dqvarnest == 0) {
10982 syntax = BASESYNTAX;
10989 case CVAR: /* '$' */
10990 PARSESUB(); /* parse substitution */
10992 case CENDVAR: /* '}' */
10995 if (dqvarnest > 0) {
10998 USTPUTC(CTLENDVAR, out);
11003 #if ENABLE_SH_MATH_SUPPORT
11004 case CLP: /* '(' in arithmetic */
11008 case CRP: /* ')' in arithmetic */
11009 if (parenlevel > 0) {
11013 if (pgetc() == ')') {
11014 if (--arinest == 0) {
11015 USTPUTC(CTLENDARI, out);
11016 syntax = prevsyntax;
11017 dblquote = (syntax == DQSYNTAX);
11022 * unbalanced parens
11023 * (don't 2nd guess - no error)
11031 case CBQUOTE: /* '`' */
11035 goto endword; /* exit outer loop */
11039 if (varnest == 0) {
11040 #if ENABLE_ASH_BASH_COMPAT
11042 if (pgetc() == '>')
11043 c = 0x100 + '>'; /* flag &> */
11047 goto endword; /* exit outer loop */
11049 #if ENABLE_ASH_ALIAS
11059 #if ENABLE_SH_MATH_SUPPORT
11060 if (syntax == ARISYNTAX)
11061 raise_error_syntax("missing '))'");
11063 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11064 raise_error_syntax("unterminated quoted string");
11065 if (varnest != 0) {
11066 startlinno = g_parsefile->linno;
11068 raise_error_syntax("missing '}'");
11070 USTPUTC('\0', out);
11071 len = out - (char *)stackblock();
11072 out = stackblock();
11073 if (eofmark == NULL) {
11074 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11077 if (isdigit_str9(out)) {
11078 PARSEREDIR(); /* passed as params: out, c */
11079 lasttoken = TREDIR;
11082 /* else: non-number X seen, interpret it
11083 * as "NNNX>file" = "NNNX >file" */
11087 quoteflag = quotef;
11088 backquotelist = bqlist;
11089 grabstackblock(len);
11093 /* end of readtoken routine */
11096 * Check to see whether we are at the end of the here document. When this
11097 * is called, c is set to the first character of the next input line. If
11098 * we are at the end of the here document, this routine sets the c to PEOF.
11102 #if ENABLE_ASH_ALIAS
11108 while (c == '\t') {
11112 if (c == *eofmark) {
11113 if (pfgets(line, sizeof(line)) != NULL) {
11117 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11119 if (*p == '\n' && *q == '\0') {
11121 g_parsefile->linno++;
11122 needprompt = doprompt;
11124 pushstring(line, NULL);
11129 goto checkend_return;
11133 * Parse a redirection operator. The variable "out" points to a string
11134 * specifying the fd to be redirected. The variable "c" contains the
11135 * first character of the redirection operator.
11138 /* out is already checked to be a valid number or "" */
11139 int fd = (*out == '\0' ? -1 : atoi(out));
11142 np = stzalloc(sizeof(struct nfile));
11147 np->type = NAPPEND;
11149 np->type = NCLOBBER;
11152 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11158 #if ENABLE_ASH_BASH_COMPAT
11159 else if (c == 0x100 + '>') { /* this flags &> redirection */
11161 pgetc(); /* this is '>', no need to check */
11165 else { /* c == '<' */
11166 /*np->nfile.fd = 0; - stzalloc did it */
11170 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11171 np = stzalloc(sizeof(struct nhere));
11172 /*np->nfile.fd = 0; - stzalloc did it */
11175 heredoc = stzalloc(sizeof(struct heredoc));
11176 heredoc->here = np;
11179 heredoc->striptabs = 1;
11181 /*heredoc->striptabs = 0; - stzalloc did it */
11187 np->type = NFROMFD;
11191 np->type = NFROMTO;
11203 goto parseredir_return;
11207 * Parse a substitution. At this point, we have read the dollar sign
11208 * and nothing else.
11211 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11212 * (assuming ascii char codes, as the original implementation did) */
11213 #define is_special(c) \
11214 (((unsigned)(c) - 33 < 32) \
11215 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11221 static const char types[] ALIGN1 = "}-+?=";
11224 if (c <= PEOA_OR_PEOF
11225 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11227 #if ENABLE_ASH_BASH_COMPAT
11229 bash_dollar_squote = 1;
11234 } else if (c == '(') { /* $(command) or $((arith)) */
11235 if (pgetc() == '(') {
11236 #if ENABLE_SH_MATH_SUPPORT
11239 raise_error_syntax("you disabled math support for $((arith)) syntax");
11246 USTPUTC(CTLVAR, out);
11247 typeloc = out - (char *)stackblock();
11248 USTPUTC(VSNORMAL, out);
11249 subtype = VSNORMAL;
11257 subtype = VSLENGTH;
11261 if (c > PEOA_OR_PEOF && is_name(c)) {
11265 } while (c > PEOA_OR_PEOF && is_in_name(c));
11266 } else if (isdigit(c)) {
11270 } while (isdigit(c));
11271 } else if (is_special(c)) {
11276 raise_error_syntax("bad substitution");
11278 if (c != '}' && subtype == VSLENGTH)
11283 if (subtype == 0) {
11287 #if ENABLE_ASH_BASH_COMPAT
11288 if (c == ':' || c == '$' || isdigit(c)) {
11290 subtype = VSSUBSTR;
11297 p = strchr(types, c);
11300 subtype = p - types + VSNORMAL;
11305 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11313 #if ENABLE_ASH_BASH_COMPAT
11315 subtype = VSREPLACE;
11318 subtype++; /* VSREPLACEALL */
11327 if (dblquote || arinest)
11329 *((char *)stackblock() + typeloc) = subtype | flags;
11330 if (subtype != VSNORMAL) {
11332 if (dblquote || arinest) {
11337 goto parsesub_return;
11341 * Called to parse command substitutions. Newstyle is set if the command
11342 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11343 * list of commands (passed by reference), and savelen is the number of
11344 * characters on the top of the stack which must be preserved.
11347 struct nodelist **nlpp;
11350 char *volatile str;
11351 struct jmploc jmploc;
11352 struct jmploc *volatile savehandler;
11354 smallint saveprompt = 0;
11357 (void) &saveprompt;
11359 savepbq = parsebackquote;
11360 if (setjmp(jmploc.loc)) {
11362 parsebackquote = 0;
11363 exception_handler = savehandler;
11364 longjmp(exception_handler->loc, 1);
11368 savelen = out - (char *)stackblock();
11370 str = ckmalloc(savelen);
11371 memcpy(str, stackblock(), savelen);
11373 savehandler = exception_handler;
11374 exception_handler = &jmploc;
11377 /* We must read until the closing backquote, giving special
11378 treatment to some slashes, and then push the string and
11379 reread it as input, interpreting it normally. */
11386 STARTSTACKSTR(pout);
11399 g_parsefile->linno++;
11403 * If eating a newline, avoid putting
11404 * the newline into the new character
11405 * stream (via the STPUTC after the
11410 if (pc != '\\' && pc != '`' && pc != '$'
11411 && (!dblquote || pc != '"'))
11412 STPUTC('\\', pout);
11413 if (pc > PEOA_OR_PEOF) {
11419 #if ENABLE_ASH_ALIAS
11422 startlinno = g_parsefile->linno;
11423 raise_error_syntax("EOF in backquote substitution");
11426 g_parsefile->linno++;
11427 needprompt = doprompt;
11436 STPUTC('\0', pout);
11437 psavelen = pout - (char *)stackblock();
11438 if (psavelen > 0) {
11439 pstr = grabstackstr(pout);
11440 setinputstring(pstr);
11445 nlpp = &(*nlpp)->next;
11446 *nlpp = stzalloc(sizeof(**nlpp));
11447 /* (*nlpp)->next = NULL; - stzalloc did it */
11448 parsebackquote = oldstyle;
11451 saveprompt = doprompt;
11458 doprompt = saveprompt;
11459 else if (readtoken() != TRP)
11460 raise_error_unexpected_syntax(TRP);
11465 * Start reading from old file again, ignoring any pushed back
11466 * tokens left from the backquote parsing
11471 while (stackblocksize() <= savelen)
11473 STARTSTACKSTR(out);
11475 memcpy(out, str, savelen);
11476 STADJUST(savelen, out);
11482 parsebackquote = savepbq;
11483 exception_handler = savehandler;
11484 if (arinest || dblquote)
11485 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11487 USTPUTC(CTLBACKQ, out);
11489 goto parsebackq_oldreturn;
11490 goto parsebackq_newreturn;
11493 #if ENABLE_SH_MATH_SUPPORT
11495 * Parse an arithmetic expansion (indicate start of one and set state)
11498 if (++arinest == 1) {
11499 prevsyntax = syntax;
11500 syntax = ARISYNTAX;
11501 USTPUTC(CTLARI, out);
11508 * we collapse embedded arithmetic expansion to
11509 * parenthesis, which should be equivalent
11513 goto parsearith_return;
11517 } /* end of readtoken */
11520 * Read the next input token.
11521 * If the token is a word, we set backquotelist to the list of cmds in
11522 * backquotes. We set quoteflag to true if any part of the word was
11524 * If the token is TREDIR, then we set redirnode to a structure containing
11526 * In all cases, the variable startlinno is set to the number of the line
11527 * on which the token starts.
11529 * [Change comment: here documents and internal procedures]
11530 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11531 * word parsing code into a separate routine. In this case, readtoken
11532 * doesn't need to have any internal procedures, but parseword does.
11533 * We could also make parseoperator in essence the main routine, and
11534 * have parseword (readtoken1?) handle both words and redirection.]
11536 #define NEW_xxreadtoken
11537 #ifdef NEW_xxreadtoken
11538 /* singles must be first! */
11539 static const char xxreadtoken_chars[7] ALIGN1 = {
11540 '\n', '(', ')', /* singles */
11541 '&', '|', ';', /* doubles */
11545 #define xxreadtoken_singles 3
11546 #define xxreadtoken_doubles 3
11548 static const char xxreadtoken_tokens[] ALIGN1 = {
11549 TNL, TLP, TRP, /* only single occurrence allowed */
11550 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11551 TEOF, /* corresponds to trailing nul */
11552 TAND, TOR, TENDCASE /* if double occurrence */
11567 startlinno = g_parsefile->linno;
11568 for (;;) { /* until token or start of word found */
11570 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11574 while ((c = pgetc()) != '\n' && c != PEOF)
11577 } else if (c == '\\') {
11578 if (pgetc() != '\n') {
11580 break; /* return readtoken1(...) */
11582 startlinno = ++g_parsefile->linno;
11588 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11591 g_parsefile->linno++;
11592 needprompt = doprompt;
11595 p = strchr(xxreadtoken_chars, c);
11597 break; /* return readtoken1(...) */
11599 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11601 if (cc == c) { /* double occurrence? */
11602 p += xxreadtoken_doubles + 1;
11605 #if ENABLE_ASH_BASH_COMPAT
11606 if (c == '&' && cc == '>') /* &> */
11607 break; /* return readtoken1(...) */
11612 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11617 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11619 #else /* old xxreadtoken */
11620 #define RETURN(token) return lasttoken = token
11633 startlinno = g_parsefile->linno;
11634 for (;;) { /* until token or start of word found */
11637 case ' ': case '\t':
11638 #if ENABLE_ASH_ALIAS
11643 while ((c = pgetc()) != '\n' && c != PEOF)
11648 if (pgetc() == '\n') {
11649 startlinno = ++g_parsefile->linno;
11657 g_parsefile->linno++;
11658 needprompt = doprompt;
11663 if (pgetc() == '&')
11668 if (pgetc() == '|')
11673 if (pgetc() == ';')
11686 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11689 #endif /* old xxreadtoken */
11696 smallint alreadyseen = tokpushback;
11699 #if ENABLE_ASH_ALIAS
11708 if (checkkwd & CHKNL) {
11715 if (t != TWORD || quoteflag) {
11720 * check for keywords
11722 if (checkkwd & CHKKWD) {
11723 const char *const *pp;
11725 pp = findkwd(wordtext);
11727 lasttoken = t = pp - tokname_array;
11728 TRACE(("keyword %s recognized\n", tokname(t)));
11733 if (checkkwd & CHKALIAS) {
11734 #if ENABLE_ASH_ALIAS
11736 ap = lookupalias(wordtext, 1);
11739 pushstring(ap->val, ap);
11749 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11751 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11763 return tokname_array[t][0];
11767 * Read and parse a command. Returns NODE_EOF on end of file.
11768 * (NULL is a valid parse tree indicating a blank line.)
11770 static union node *
11771 parsecmd(int interact)
11776 doprompt = interact;
11778 setprompt(doprompt);
11790 * Input any here documents.
11795 struct heredoc *here;
11798 here = heredoclist;
11799 heredoclist = NULL;
11805 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11806 here->eofmark, here->striptabs);
11807 n = stzalloc(sizeof(struct narg));
11808 n->narg.type = NARG;
11809 /*n->narg.next = NULL; - stzalloc did it */
11810 n->narg.text = wordtext;
11811 n->narg.backquote = backquotelist;
11812 here->here->nhere.doc = n;
11819 * called by editline -- any expansions to the prompt should be added here.
11821 #if ENABLE_ASH_EXPAND_PRMT
11822 static const char *
11823 expandstr(const char *ps)
11827 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11828 * and token processing _can_ alter it (delete NULs etc). */
11829 setinputstring((char *)ps);
11830 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11833 n.narg.type = NARG;
11834 n.narg.next = NULL;
11835 n.narg.text = wordtext;
11836 n.narg.backquote = backquotelist;
11838 expandarg(&n, NULL, 0);
11839 return stackblock();
11844 * Execute a command or commands contained in a string.
11847 evalstring(char *s, int mask)
11850 struct stackmark smark;
11854 setstackmark(&smark);
11857 while ((n = parsecmd(0)) != NODE_EOF) {
11859 popstackmark(&smark);
11872 * The eval command.
11874 static int FAST_FUNC
11875 evalcmd(int argc UNUSED_PARAM, char **argv)
11884 STARTSTACKSTR(concat);
11886 concat = stack_putstr(p, concat);
11890 STPUTC(' ', concat);
11892 STPUTC('\0', concat);
11893 p = grabstackstr(concat);
11895 evalstring(p, ~SKIPEVAL);
11902 * Read and execute commands. "Top" is nonzero for the top level command
11903 * loop; it turns on prompting if the shell is interactive.
11909 struct stackmark smark;
11913 TRACE(("cmdloop(%d) called\n", top));
11917 setstackmark(&smark);
11920 showjobs(stderr, SHOW_CHANGED);
11923 if (iflag && top) {
11925 #if ENABLE_ASH_MAIL
11929 n = parsecmd(inter);
11931 if (DEBUG > 2 && debug && (n != NODE_EOF))
11934 if (n == NODE_EOF) {
11935 if (!top || numeof >= 50)
11937 if (!stoppedjobs()) {
11940 out2str("\nUse \"exit\" to leave shell.\n");
11943 } else if (nflag == 0) {
11944 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11949 popstackmark(&smark);
11954 return skip & SKIPEVAL;
11961 * Take commands from a file. To be compatible we should do a path
11962 * search for the file, which is necessary to find sub-commands.
11965 find_dot_file(char *name)
11968 const char *path = pathval();
11971 /* don't try this for absolute or relative paths */
11972 if (strchr(name, '/'))
11975 /* IIRC standards do not say whether . is to be searched.
11976 * And it is even smaller this way, making it unconditional for now:
11978 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11983 while ((fullname = path_advance(&path, name)) != NULL) {
11985 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11987 * Don't bother freeing here, since it will
11988 * be freed by the caller.
11992 if (fullname != name)
11993 stunalloc(fullname);
11996 /* not found in the PATH */
11997 ash_msg_and_raise_error("%s: not found", name);
12001 static int FAST_FUNC
12002 dotcmd(int argc, char **argv)
12004 struct strlist *sp;
12005 volatile struct shparam saveparam;
12008 for (sp = cmdenviron; sp; sp = sp->next)
12009 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12011 if (argv[1]) { /* That's what SVR2 does */
12012 char *fullname = find_dot_file(argv[1]);
12015 if (argc) { /* argc > 0, argv[0] != NULL */
12016 saveparam = shellparam;
12017 shellparam.malloced = 0;
12018 shellparam.nparam = argc;
12019 shellparam.p = argv;
12022 setinputfile(fullname, INPUT_PUSH_FILE);
12023 commandname = fullname;
12028 freeparam(&shellparam);
12029 shellparam = saveparam;
12031 status = exitstatus;
12036 static int FAST_FUNC
12037 exitcmd(int argc UNUSED_PARAM, char **argv)
12042 exitstatus = number(argv[1]);
12043 raise_exception(EXEXIT);
12048 * Read a file containing shell functions.
12051 readcmdfile(char *name)
12053 setinputfile(name, INPUT_PUSH_FILE);
12059 /* ============ find_command inplementation */
12062 * Resolve a command name. If you change this routine, you may have to
12063 * change the shellexec routine as well.
12066 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12068 struct tblentry *cmdp;
12075 struct builtincmd *bcmd;
12077 /* If name contains a slash, don't use PATH or hash table */
12078 if (strchr(name, '/') != NULL) {
12079 entry->u.index = -1;
12080 if (act & DO_ABS) {
12081 while (stat(name, &statb) < 0) {
12083 if (errno == EINTR)
12086 entry->cmdtype = CMDUNKNOWN;
12090 entry->cmdtype = CMDNORMAL;
12094 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12096 updatetbl = (path == pathval());
12099 if (strstr(path, "%builtin") != NULL)
12100 act |= DO_ALTBLTIN;
12103 /* If name is in the table, check answer will be ok */
12104 cmdp = cmdlookup(name, 0);
12105 if (cmdp != NULL) {
12108 switch (cmdp->cmdtype) {
12126 } else if (cmdp->rehash == 0)
12127 /* if not invalidated by cd, we're done */
12131 /* If %builtin not in path, check for builtin next */
12132 bcmd = find_builtin(name);
12134 if (IS_BUILTIN_REGULAR(bcmd))
12135 goto builtin_success;
12136 if (act & DO_ALTPATH) {
12137 if (!(act & DO_ALTBLTIN))
12138 goto builtin_success;
12139 } else if (builtinloc <= 0) {
12140 goto builtin_success;
12144 #if ENABLE_FEATURE_SH_STANDALONE
12146 int applet_no = find_applet_by_name(name);
12147 if (applet_no >= 0) {
12148 entry->cmdtype = CMDNORMAL;
12149 entry->u.index = -2 - applet_no;
12155 /* We have to search path. */
12156 prev = -1; /* where to start */
12157 if (cmdp && cmdp->rehash) { /* doing a rehash */
12158 if (cmdp->cmdtype == CMDBUILTIN)
12161 prev = cmdp->param.index;
12167 while ((fullname = path_advance(&path, name)) != NULL) {
12168 stunalloc(fullname);
12169 /* NB: code below will still use fullname
12170 * despite it being "unallocated" */
12173 if (prefix(pathopt, "builtin")) {
12175 goto builtin_success;
12178 if ((act & DO_NOFUNC)
12179 || !prefix(pathopt, "func")
12180 ) { /* ignore unimplemented options */
12184 /* if rehash, don't redo absolute path names */
12185 if (fullname[0] == '/' && idx <= prev) {
12188 TRACE(("searchexec \"%s\": no change\n", name));
12191 while (stat(fullname, &statb) < 0) {
12193 if (errno == EINTR)
12196 if (errno != ENOENT && errno != ENOTDIR)
12200 e = EACCES; /* if we fail, this will be the error */
12201 if (!S_ISREG(statb.st_mode))
12203 if (pathopt) { /* this is a %func directory */
12204 stalloc(strlen(fullname) + 1);
12205 /* NB: stalloc will return space pointed by fullname
12206 * (because we don't have any intervening allocations
12207 * between stunalloc above and this stalloc) */
12208 readcmdfile(fullname);
12209 cmdp = cmdlookup(name, 0);
12210 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12211 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12212 stunalloc(fullname);
12215 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12217 entry->cmdtype = CMDNORMAL;
12218 entry->u.index = idx;
12222 cmdp = cmdlookup(name, 1);
12223 cmdp->cmdtype = CMDNORMAL;
12224 cmdp->param.index = idx;
12229 /* We failed. If there was an entry for this command, delete it */
12230 if (cmdp && updatetbl)
12231 delete_cmd_entry();
12233 ash_msg("%s: %s", name, errmsg(e, "not found"));
12234 entry->cmdtype = CMDUNKNOWN;
12239 entry->cmdtype = CMDBUILTIN;
12240 entry->u.cmd = bcmd;
12244 cmdp = cmdlookup(name, 1);
12245 cmdp->cmdtype = CMDBUILTIN;
12246 cmdp->param.cmd = bcmd;
12250 entry->cmdtype = cmdp->cmdtype;
12251 entry->u = cmdp->param;
12255 /* ============ trap.c */
12258 * The trap builtin.
12260 static int FAST_FUNC
12261 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12270 for (signo = 0; signo < NSIG; signo++) {
12271 char *tr = trap_ptr[signo];
12273 /* note: bash adds "SIG", but only if invoked
12274 * as "bash". If called as "sh", or if set -o posix,
12275 * then it prints short signal names.
12276 * We are printing short names: */
12277 out1fmt("trap -- %s %s\n",
12279 get_signame(signo));
12280 /* trap_ptr != trap only if we are in special-cased `trap` code.
12281 * In this case, we will exit very soon, no need to free(). */
12282 /* if (trap_ptr != trap && tp[0]) */
12287 if (trap_ptr != trap) {
12299 signo = get_signum(*ap);
12301 ash_msg_and_raise_error("%s: bad trap", *ap);
12304 if (LONE_DASH(action))
12307 action = ckstrdup(action);
12310 trap[signo] = action;
12320 /* ============ Builtins */
12322 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12324 * Lists available builtins
12326 static int FAST_FUNC
12327 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12333 "Built-in commands:\n"
12334 "------------------\n");
12335 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12336 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12337 builtintab[i].name + 1);
12343 #if ENABLE_FEATURE_SH_STANDALONE
12345 const char *a = applet_names;
12347 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12352 a += strlen(a) + 1;
12357 return EXIT_SUCCESS;
12359 #endif /* FEATURE_SH_EXTRA_QUIET */
12362 * The export and readonly commands.
12364 static int FAST_FUNC
12365 exportcmd(int argc UNUSED_PARAM, char **argv)
12371 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12373 if (nextopt("p") != 'p') {
12378 p = strchr(name, '=');
12382 vp = *findvar(hashvar(name), name);
12388 setvar(name, p, flag);
12389 } while ((name = *++aptr) != NULL);
12393 showvars(argv[0], flag, 0);
12398 * Delete a function if it exists.
12401 unsetfunc(const char *name)
12403 struct tblentry *cmdp;
12405 cmdp = cmdlookup(name, 0);
12406 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12407 delete_cmd_entry();
12411 * The unset builtin command. We unset the function before we unset the
12412 * variable to allow a function to be unset when there is a readonly variable
12413 * with the same name.
12415 static int FAST_FUNC
12416 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12423 while ((i = nextopt("vf")) != '\0') {
12427 for (ap = argptr; *ap; ap++) {
12443 #include <sys/times.h>
12445 static const unsigned char timescmd_str[] ALIGN1 = {
12446 ' ', offsetof(struct tms, tms_utime),
12447 '\n', offsetof(struct tms, tms_stime),
12448 ' ', offsetof(struct tms, tms_cutime),
12449 '\n', offsetof(struct tms, tms_cstime),
12453 static int FAST_FUNC
12454 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12456 long clk_tck, s, t;
12457 const unsigned char *p;
12460 clk_tck = sysconf(_SC_CLK_TCK);
12465 t = *(clock_t *)(((char *) &buf) + p[1]);
12467 out1fmt("%ldm%ld.%.3lds%c",
12469 ((t - s * clk_tck) * 1000) / clk_tck,
12471 } while (*(p += 2));
12476 #if ENABLE_SH_MATH_SUPPORT
12478 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12479 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12481 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12483 static int FAST_FUNC
12484 letcmd(int argc UNUSED_PARAM, char **argv)
12490 ash_msg_and_raise_error("expression expected");
12492 i = ash_arith(*argv);
12497 #endif /* SH_MATH_SUPPORT */
12500 /* ============ miscbltin.c
12502 * Miscellaneous builtins.
12507 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
12508 typedef enum __rlimit_resource rlim_t;
12512 * The read builtin. Options:
12513 * -r Do not interpret '\' specially
12514 * -s Turn off echo (tty only)
12515 * -n NCHARS Read NCHARS max
12516 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12517 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12518 * -u FD Read from given FD instead of fd 0
12519 * This uses unbuffered input, which may be avoidable in some cases.
12520 * TODO: bash also has:
12521 * -a ARRAY Read into array[0],[1],etc
12522 * -d DELIM End on DELIM char, not newline
12523 * -e Use line editing (tty only)
12525 static int FAST_FUNC
12526 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12528 static const char *const arg_REPLY[] = { "REPLY", NULL };
12541 #if ENABLE_ASH_READ_NCHARS
12542 int nchars = 0; /* if != 0, -n is in effect */
12544 struct termios tty, old_tty;
12546 #if ENABLE_ASH_READ_TIMEOUT
12547 unsigned end_ms = 0;
12548 unsigned timeout = 0;
12553 while ((i = nextopt("p:u:r"
12554 IF_ASH_READ_TIMEOUT("t:")
12555 IF_ASH_READ_NCHARS("n:s")
12559 prompt = optionarg;
12561 #if ENABLE_ASH_READ_NCHARS
12563 nchars = bb_strtou(optionarg, NULL, 10);
12564 if (nchars < 0 || errno)
12565 ash_msg_and_raise_error("invalid count");
12566 /* nchars == 0: off (bash 3.2 does this too) */
12572 #if ENABLE_ASH_READ_TIMEOUT
12574 timeout = bb_strtou(optionarg, NULL, 10);
12575 if (errno || timeout > UINT_MAX / 2048)
12576 ash_msg_and_raise_error("invalid timeout");
12578 #if 0 /* even bash have no -t N.NNN support */
12579 ts.tv_sec = bb_strtou(optionarg, &p, 10);
12581 /* EINVAL means number is ok, but not terminated by NUL */
12582 if (*p == '.' && errno == EINVAL) {
12586 ts.tv_usec = bb_strtou(p, &p2, 10);
12588 ash_msg_and_raise_error("invalid timeout");
12590 /* normalize to usec */
12592 ash_msg_and_raise_error("invalid timeout");
12593 while (scale++ < 6)
12596 } else if (ts.tv_sec < 0 || errno) {
12597 ash_msg_and_raise_error("invalid timeout");
12599 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
12600 ash_msg_and_raise_error("invalid timeout");
12609 fd = bb_strtou(optionarg, NULL, 10);
12610 if (fd < 0 || errno)
12611 ash_msg_and_raise_error("invalid file descriptor");
12617 if (prompt && isatty(fd)) {
12622 ap = (char**)arg_REPLY;
12623 ifs = bltinlookup("IFS");
12626 #if ENABLE_ASH_READ_NCHARS
12627 tcgetattr(fd, &tty);
12629 if (nchars || silent) {
12631 tty.c_lflag &= ~ICANON;
12632 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
12635 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12637 /* if tcgetattr failed, tcsetattr will fail too.
12638 * Ignoring, it's harmless. */
12639 tcsetattr(fd, TCSANOW, &tty);
12646 #if ENABLE_ASH_READ_TIMEOUT
12647 if (timeout) /* NB: ensuring end_ms is nonzero */
12648 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12652 const char *is_ifs;
12654 #if ENABLE_ASH_READ_TIMEOUT
12656 struct pollfd pfd[1];
12658 pfd[0].events = POLLIN;
12659 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12660 if ((int)timeout <= 0 /* already late? */
12661 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12662 ) { /* timed out! */
12663 #if ENABLE_ASH_READ_NCHARS
12664 tcsetattr(fd, TCSANOW, &old_tty);
12670 if (nonblock_safe_read(fd, &c, 1) != 1) {
12682 if (!rflag && c == '\\') {
12688 /* $IFS splitting */
12689 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
12690 is_ifs = strchr(ifs, c);
12691 if (startword && is_ifs) {
12694 /* it is a non-space ifs char */
12696 if (startword == 1) /* first one? */
12697 continue; /* yes, it is not next word yet */
12700 if (ap[1] != NULL && is_ifs) {
12703 beg = stackblock();
12704 setvar(*ap, beg, 0);
12706 /* can we skip one non-space ifs char? (2: yes) */
12707 startword = isspace(c) ? 2 : 1;
12714 /* end of do {} while: */
12715 #if ENABLE_ASH_READ_NCHARS
12721 #if ENABLE_ASH_READ_NCHARS
12722 tcsetattr(fd, TCSANOW, &old_tty);
12726 /* Remove trailing space ifs chars */
12727 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
12729 setvar(*ap, stackblock(), 0);
12730 while (*++ap != NULL)
12731 setvar(*ap, nullstr, 0);
12735 static int FAST_FUNC
12736 umaskcmd(int argc UNUSED_PARAM, char **argv)
12738 static const char permuser[3] ALIGN1 = "ugo";
12739 static const char permmode[3] ALIGN1 = "rwx";
12740 static const short permmask[] ALIGN2 = {
12741 S_IRUSR, S_IWUSR, S_IXUSR,
12742 S_IRGRP, S_IWGRP, S_IXGRP,
12743 S_IROTH, S_IWOTH, S_IXOTH
12746 /* TODO: use bb_parse_mode() instead */
12751 int symbolic_mode = 0;
12753 while (nextopt("S") != '\0') {
12764 if (symbolic_mode) {
12768 for (i = 0; i < 3; i++) {
12771 *p++ = permuser[i];
12773 for (j = 0; j < 3; j++) {
12774 if ((mask & permmask[3 * i + j]) == 0) {
12775 *p++ = permmode[j];
12783 out1fmt("%.4o\n", mask);
12786 if (isdigit((unsigned char) *ap)) {
12789 if (*ap >= '8' || *ap < '0')
12790 ash_msg_and_raise_error(msg_illnum, argv[1]);
12791 mask = (mask << 3) + (*ap - '0');
12792 } while (*++ap != '\0');
12795 mask = ~mask & 0777;
12796 if (!bb_parse_mode(ap, &mask)) {
12797 ash_msg_and_raise_error("illegal mode: %s", ap);
12799 umask(~mask & 0777);
12808 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12809 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12810 * ash by J.T. Conklin.
12815 uint8_t cmd; /* RLIMIT_xxx fit into it */
12816 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
12820 static const struct limits limits_tbl[] = {
12822 { RLIMIT_CPU, 0, 't' },
12824 #ifdef RLIMIT_FSIZE
12825 { RLIMIT_FSIZE, 9, 'f' },
12828 { RLIMIT_DATA, 10, 'd' },
12830 #ifdef RLIMIT_STACK
12831 { RLIMIT_STACK, 10, 's' },
12834 { RLIMIT_CORE, 9, 'c' },
12837 { RLIMIT_RSS, 10, 'm' },
12839 #ifdef RLIMIT_MEMLOCK
12840 { RLIMIT_MEMLOCK, 10, 'l' },
12842 #ifdef RLIMIT_NPROC
12843 { RLIMIT_NPROC, 0, 'p' },
12845 #ifdef RLIMIT_NOFILE
12846 { RLIMIT_NOFILE, 0, 'n' },
12849 { RLIMIT_AS, 10, 'v' },
12851 #ifdef RLIMIT_LOCKS
12852 { RLIMIT_LOCKS, 0, 'w' },
12855 static const char limits_name[] =
12857 "time(seconds)" "\0"
12859 #ifdef RLIMIT_FSIZE
12860 "file(blocks)" "\0"
12865 #ifdef RLIMIT_STACK
12869 "coredump(blocks)" "\0"
12874 #ifdef RLIMIT_MEMLOCK
12875 "locked memory(kb)" "\0"
12877 #ifdef RLIMIT_NPROC
12880 #ifdef RLIMIT_NOFILE
12886 #ifdef RLIMIT_LOCKS
12891 enum limtype { SOFT = 0x1, HARD = 0x2 };
12894 printlim(enum limtype how, const struct rlimit *limit,
12895 const struct limits *l)
12899 val = limit->rlim_max;
12901 val = limit->rlim_cur;
12903 if (val == RLIM_INFINITY)
12904 out1fmt("unlimited\n");
12906 val >>= l->factor_shift;
12907 out1fmt("%lld\n", (long long) val);
12911 static int FAST_FUNC
12912 ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12915 enum limtype how = SOFT | HARD;
12916 const struct limits *l;
12919 struct rlimit limit;
12922 while ((optc = nextopt("HSa"
12926 #ifdef RLIMIT_FSIZE
12932 #ifdef RLIMIT_STACK
12941 #ifdef RLIMIT_MEMLOCK
12944 #ifdef RLIMIT_NPROC
12947 #ifdef RLIMIT_NOFILE
12953 #ifdef RLIMIT_LOCKS
12971 for (l = limits_tbl; l->option != what; l++)
12974 set = *argptr ? 1 : 0;
12979 if (all || argptr[1])
12980 ash_msg_and_raise_error("too many arguments");
12981 if (strncmp(p, "unlimited\n", 9) == 0)
12982 val = RLIM_INFINITY;
12984 if (sizeof(val) == sizeof(int))
12985 val = bb_strtou(p, NULL, 10);
12986 else if (sizeof(val) == sizeof(long))
12987 val = bb_strtoul(p, NULL, 10);
12989 val = bb_strtoull(p, NULL, 10);
12991 ash_msg_and_raise_error("bad number");
12992 val <<= l->factor_shift;
12996 const char *lname = limits_name;
12997 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
12998 getrlimit(l->cmd, &limit);
12999 out1fmt("%-20s ", lname);
13000 lname += strlen(lname) + 1;
13001 printlim(how, &limit, l);
13006 getrlimit(l->cmd, &limit);
13009 limit.rlim_max = val;
13011 limit.rlim_cur = val;
13012 if (setrlimit(l->cmd, &limit) < 0)
13013 ash_msg_and_raise_error("error setting limit (%m)");
13015 printlim(how, &limit, l);
13020 /* ============ main() and helpers */
13023 * Called to exit the shell.
13025 static void exitshell(void) NORETURN;
13033 status = exitstatus;
13034 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13035 if (setjmp(loc.loc)) {
13036 if (exception_type == EXEXIT)
13037 /* dash bug: it just does _exit(exitstatus) here
13038 * but we have to do setjobctl(0) first!
13039 * (bug is still not fixed in dash-0.5.3 - if you run dash
13040 * under Midnight Commander, on exit from dash MC is backgrounded) */
13041 status = exitstatus;
13044 exception_handler = &loc;
13051 flush_stdout_stderr();
13061 /* from input.c: */
13062 basepf.next_to_pgetc = basepf.buf = basebuf;
13065 signal(SIGCHLD, SIG_DFL);
13071 struct stat st1, st2;
13074 for (envp = environ; envp && *envp; envp++) {
13075 if (strchr(*envp, '=')) {
13076 setvareq(*envp, VEXPORT|VTEXTFIXED);
13080 setvar("PPID", utoa(getppid()), 0);
13082 p = lookupvar("PWD");
13084 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13085 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
13092 * Process the shell command line arguments.
13095 procargs(char **argv)
13098 const char *xminusc;
13103 /* if (xargv[0]) - mmm, this is always true! */
13105 for (i = 0; i < NOPTS; i++)
13109 /* it already printed err message */
13110 raise_exception(EXERROR);
13114 if (*xargv == NULL) {
13116 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13119 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13123 for (i = 0; i < NOPTS; i++)
13124 if (optlist[i] == 2)
13129 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13134 } else if (!sflag) {
13135 setinputfile(*xargv, 0);
13138 commandname = arg0;
13141 shellparam.p = xargv;
13142 #if ENABLE_ASH_GETOPTS
13143 shellparam.optind = 1;
13144 shellparam.optoff = -1;
13146 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13148 shellparam.nparam++;
13155 * Read /etc/profile or .profile.
13158 read_profile(const char *name)
13162 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13171 * This routine is called when an error or an interrupt occurs in an
13172 * interactive shell and control is returned to the main command loop.
13180 /* from input.c: */
13181 g_parsefile->left_in_buffer = 0;
13182 g_parsefile->left_in_line = 0; /* clear input buffer */
13184 /* from parser.c: */
13187 /* from redir.c: */
13188 clearredir(/*drop:*/ 0);
13192 static short profile_buf[16384];
13193 extern int etext();
13197 * Main routine. We initialize things, parse the arguments, execute
13198 * profiles if we're a login shell, and then call cmdloop to execute
13199 * commands. The setjmp call sets up the location to jump to when an
13200 * exception occurs. When an exception occurs the variable "state"
13201 * is used to figure out how far we had gotten.
13203 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13204 int ash_main(int argc UNUSED_PARAM, char **argv)
13206 const char *shinit;
13207 volatile smallint state;
13208 struct jmploc jmploc;
13209 struct stackmark smark;
13211 /* Initialize global data */
13215 #if ENABLE_ASH_ALIAS
13221 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13224 #if ENABLE_FEATURE_EDITING
13225 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13228 if (setjmp(jmploc.loc)) {
13234 e = exception_type;
13238 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13241 outcslow('\n', stderr);
13243 popstackmark(&smark);
13244 FORCE_INT_ON; /* enable interrupts */
13253 exception_handler = &jmploc;
13256 TRACE(("Shell args: "));
13257 trace_puts_args(argv);
13259 rootpid = getpid();
13261 #if ENABLE_ASH_RANDOM_SUPPORT
13262 /* Can use monotonic_ns() for better randomness but for now it is
13263 * not used anywhere else in busybox... so avoid bloat */
13264 INIT_RANDOM_T(&random_gen, rootpid, monotonic_us());
13267 setstackmark(&smark);
13270 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13272 const char *hp = lookupvar("HISTFILE");
13275 hp = lookupvar("HOME");
13277 char *defhp = concat_path_file(hp, ".ash_history");
13278 setvar("HISTFILE", defhp, 0);
13284 if (/* argv[0] && */ argv[0][0] == '-')
13288 read_profile("/etc/profile");
13291 read_profile(".profile");
13297 getuid() == geteuid() && getgid() == getegid() &&
13301 shinit = lookupvar("ENV");
13302 if (shinit != NULL && *shinit != '\0') {
13303 read_profile(shinit);
13309 /* evalstring pushes parsefile stack.
13310 * Ensure we don't falsely claim that 0 (stdin)
13311 * is one of stacked source fds.
13312 * Testcase: ash -c 'exec 1>&0' must not complain. */
13314 g_parsefile->fd = -1;
13315 evalstring(minusc, 0);
13318 if (sflag || minusc == NULL) {
13319 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13321 const char *hp = lookupvar("HISTFILE");
13323 line_input_state->hist_file = hp;
13326 state4: /* XXX ??? - why isn't this before the "if" statement */
13334 extern void _mcleanup(void);
13344 * Copyright (c) 1989, 1991, 1993, 1994
13345 * The Regents of the University of California. All rights reserved.
13347 * This code is derived from software contributed to Berkeley by
13348 * Kenneth Almquist.
13350 * Redistribution and use in source and binary forms, with or without
13351 * modification, are permitted provided that the following conditions
13353 * 1. Redistributions of source code must retain the above copyright
13354 * notice, this list of conditions and the following disclaimer.
13355 * 2. Redistributions in binary form must reproduce the above copyright
13356 * notice, this list of conditions and the following disclaimer in the
13357 * documentation and/or other materials provided with the distribution.
13358 * 3. Neither the name of the University nor the names of its contributors
13359 * may be used to endorse or promote products derived from this software
13360 * without specific prior written permission.
13362 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13363 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13364 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13365 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13366 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13367 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13368 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13369 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13370 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13371 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF